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): 补齐 OAuth 与设备码授权流程 (#526)

Chris Zhang0921d45aa2a6
diff --git a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt
index b3e745a10a..dea87128fd 100644
--- a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt
+++ b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt
@@ -3111,7 +3111,7 @@ necessary. Here is a sample; alter the names:
That's all there is to it!
------------------------------------------------------------------------------
-Code Island NotchPanelShape & mascot parameters (adapted) adapted
+Code Island NotchPanelShape & mascot parameters (adapted)
License: MIT
Source: https://github.com/wxtsky/CodeIsland
------------------------------------------------------------------------------
@@ -3377,6 +3377,33 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Electron 自身捆绑了 Chromium、Node.js、V8 等组件,其完整许可证集合
(LICENSES.chromium.html)由 Electron 打包流程自动包含在应用安装目录中。
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
------------------------------------------------------------------------------
Lobe Icons SVG paths (vendored) 5.14.0
License: MIT
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index 1196d86575..37b95eb6cd 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -451,6 +451,100 @@ describe('被控端控制链路生命周期', () => {
expect(getActiveControllers()).toHaveLength(0);
});
+ it('link-open capability controls whether provider projection includes new logo kinds', async () => {
+ const { client, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ registry.register('maker:provider:list', () => ({
+ providers: [{
+ id: 'renamed-vercel',
+ name: 'Team gateway',
+ routing: { codex: { upstream: 'https://ai-gateway.vercel.sh/v1' } },
+ }],
+ }));
+
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'r-cap',
+ src: 'ctrl-cap',
+ payload: {
+ controllerName: 'Current mobile',
+ protocolVersion: 1,
+ appVersion: '2.0.0',
+ capabilities: ['provider-logo-kinds-v2'],
+ },
+ });
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'r-legacy',
+ src: 'ctrl-legacy',
+ payload: {
+ controllerName: 'Legacy mobile',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ },
+ });
+
+ const current = await runInvoke('ctrl-cap', { channel: 'maker:provider:list', args: [] });
+ const legacy = await runInvoke('ctrl-legacy', { channel: 'maker:provider:list', args: [] });
+ expect(current).toMatchObject({
+ ok: true,
+ result: { providers: [{ logoKind: 'vercel', routing: { codex: {} } }] },
+ });
+ expect(legacy).toMatchObject({
+ ok: true,
+ result: { providers: [{ routing: { codex: {} } }] },
+ });
+ expect((legacy as { result: { providers: Record<string, unknown>[] } }).result.providers[0])
+ .not.toHaveProperty('logoKind');
+ });
+
+ it('listing-only invoke can negotiate new logo kinds without link-open', async () => {
+ registry.register('maker:provider:list', () => ({
+ providers: [{
+ id: 'renamed-vercel',
+ name: 'Team gateway',
+ routing: { codex: { upstream: 'https://ai-gateway.vercel.sh/v1' } },
+ }],
+ }));
+
+ const current = await runInvoke('ctrl-list-only', {
+ channel: 'maker:provider:list',
+ args: [{ capabilities: ['provider-logo-kinds-v2'] }],
+ });
+ expect(current).toMatchObject({
+ ok: true,
+ result: { providers: [{ logoKind: 'vercel', routing: { codex: {} } }] },
+ });
+ });
+
+ it('malformed link-open capabilities fail closed without blocking link acceptance', async () => {
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'r-malformed-cap',
+ src: 'ctrl-malformed-cap',
+ payload: {
+ controllerName: 'Mixed client',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ capabilities: { invalid: true } as never,
+ },
+ });
+
+ expect(calls.linkAccept).toContainEqual({
+ dst: 'ctrl-malformed-cap',
+ requestId: 'r-malformed-cap',
+ });
+ expect(dispatchTesting.controllerSupports(
+ 'ctrl-malformed-cap',
+ 'provider-logo-kinds-v2',
+ )).toBe(false);
+ });
+
it('link-close → 移除控制端,最后一个关闭后停 broadcast-tap', () => {
remoteControlEnabled = true;
const { client, feed } = makeFakeClient();
@@ -469,17 +563,53 @@ const SUB = 'device-link:subscribe';
const UNSUB = 'device-link:unsubscribe';
/** feed 一个 subscribe/unsubscribe 控制帧(走 invoke 帧承载)。 */
-function subFrame(src: string, channel: string, topics: string[], controllerName?: string): Envelope {
+function subFrame(
+ src: string,
+ channel: string,
+ topics: string[],
+ controllerName?: string,
+ capabilities?: unknown,
+): Envelope {
return {
v: 1,
kind: 'invoke',
id: `q-${src}-${topics.join(',')}`,
src,
- payload: { channel, args: [{ topics, ...(controllerName ? { controllerName } : {}) }] },
+ payload: {
+ channel,
+ args: [{
+ topics,
+ ...(controllerName ? { controllerName } : {}),
+ ...(capabilities !== undefined ? { capabilities } : {}),
+ }],
+ },
};
}
describe('被控端订阅 registry + topic 转发', () => {
+ it('subscribe frame negotiates bounded capabilities and rejects malformed shapes', () => {
+ const { client, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed(subFrame(
+ 'ctrl-current',
+ SUB,
+ ['sessions'],
+ 'Current',
+ ['provider-logo-kinds-v2'],
+ ));
+ expect(dispatchTesting.controllerSupports(
+ 'ctrl-current',
+ 'provider-logo-kinds-v2',
+ )).toBe(true);
+
+ feed(subFrame('ctrl-malformed', SUB, ['sessions'], 'Malformed', { invalid: true }));
+ expect(dispatchTesting.controllerSupports(
+ 'ctrl-malformed',
+ 'provider-logo-kinds-v2',
+ )).toBe(false);
+ });
+
it('subscribe 帧 → 回 invoke-result;sessions topic 只发列表订阅者,不发未订阅的 heavy 事件', () => {
remoteControlEnabled = true;
const { client, calls, feed } = makeFakeClient();
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/manifest.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/manifest.test.ts
new file mode 100644
index 0000000000..e93d07d9ad
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/__tests__/manifest.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Manifest } from '../../manifestService.js';
+import { getVendorAsset } from '../manifest.js';
+
+function manifestWithVersion(version: string): Manifest {
+ return {
+ app: { version: 'test' },
+ codex: {
+ version,
+ file: 'codex/darwin-arm64/codex.gz',
+ sha256: 'a'.repeat(64),
+ size: 1,
+ },
+ };
+}
+
+describe('getVendorAsset version path boundary', () => {
+ it.each(['0.145.0', '2.1.219-beta.1', 'release_2026-07-27'])(
+ 'accepts a safe version segment: %s',
+ (version) => {
+ expect(getVendorAsset(manifestWithVersion(version), 'codex')?.version).toBe(version);
+ },
+ );
+
+ it.each([
+ '',
+ '.',
+ '..',
+ '../outside',
+ 'nested/version',
+ 'nested\\version',
+ '/absolute',
+ `v${'1'.repeat(128)}`,
+ ])('rejects a version that can escape or abuse the install directory: %s', (version) => {
+ expect(getVendorAsset(manifestWithVersion(version), 'codex')).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/agent-binaries/manifest.ts b/apps/desktop/src/main/agent-binaries/manifest.ts
index ef886625dc..0f501249bc 100644
--- a/apps/desktop/src/main/agent-binaries/manifest.ts
+++ b/apps/desktop/src/main/agent-binaries/manifest.ts
@@ -21,6 +21,21 @@ export interface VendorAsset {
size: number;
}
+/**
+ * version 会成为 userData 下的一层目录名,必须是单个、有限长度的安全 path segment。
+ * 这既阻断 manifest 通过 `../` / 分隔符逃逸安装根,也让后续 spawn 的命令路径只可能
+ * 指向受管目录(CodeQL js/command-line-injection)。
+ */
+function isSafeVersionDirectoryName(value: string): boolean {
+ return (
+ value.length > 0
+ && value.length <= 128
+ && value !== '.'
+ && value !== '..'
+ && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)
+ );
+}
+
/**
* 按 manifestField 字符串索引 manifest 顶层,提取 vendor binary 资产。
*
@@ -35,6 +50,7 @@ export function getVendorAsset(manifest: Manifest, manifestField: string): Vendo
if (!raw || typeof raw !== 'object') return undefined;
const obj = raw as Record<string, unknown>;
if (typeof obj.version !== 'string') return undefined;
+ if (!isSafeVersionDirectoryName(obj.version)) return undefined;
if (typeof obj.file !== 'string') return undefined;
if (typeof obj.sha256 !== 'string') return undefined;
if (typeof obj.size !== 'number') return undefined;
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index 686a26d1e3..dd130b4e45 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -4,15 +4,18 @@
* 背景:控制端远程会话曾靠 `provider.routing[agent].supportsFastMode` 决定显隐 Fast 开关,
* 故投影需保留该字段。**现 Fast 能力已收归 per-(provider, agent) 的 `models[agent].supportsFastMode`
* (唯一真相)**,控制端从隧道带来的 `models` 现查、不再读 routing,于是投影把 routing 的
- * 全部字段整条剥掉(只留 agent 键 + 空对象以维持形状)。本测试锁住三件事:
+ * 执行字段整条剥掉,只保留跨端可用性需要的 `disabled:true` 与可选 wireProtocol。
+ * 本测试锁住五件事:
* 1. 执行细节字段(upstream / authStrategy / headerDelete / headerOverride / modelIdRewrite /
* adapter) → 投影后全部消失(安全边界 D3)。
* 2. 即便输入里残留 supportsFastMode → 也一并剥掉(routing 不再承载任何 Fast 信息)。
* 3. models[agent](含 supportsFastMode 显示门控)原样透传 —— Fast 显隐数据源在这里。
- * 4. 品牌只以非敏感 logoKind 透传;重命名 preset 仍可识别,upstream 绝不泄漏。
+ * 4. disabled runtime 在控制端仍保持禁用,不会被共享 registry 重新列为可选。
+ * 5. 品牌只以非敏感 logoKind 透传;重命名 preset 仍可识别,upstream 绝不泄漏。
* 只 mock electron(app)+ logger,与同目录 dispatchSendSafety.test 同范式。
*/
import { describe, it, expect, vi } from 'vitest';
+import { connectedProvidersForAgent, type ProviderView } from '@cindy/model-providers';
import { TEST_XD_GATEWAY_BASE_URL as XD_GATEWAY_BASE_URL } from '../../../test/vitest/clientEndpointsFixture';
vi.mock('electron', () => ({
@@ -35,7 +38,23 @@ import { __testing } from '../dispatch';
const project = (result: unknown) =>
__testing.projectInvokeResultForTunnel('maker:provider:list', result) as {
providers: Record<string, unknown>[];
+ modelVisibilityOverrides?: Record<string, boolean>;
};
+const projectForCurrentController = (result: unknown) =>
+ __testing.projectInvokeResultForTunnel('maker:provider:list', result, true) as {
+ providers: Record<string, unknown>[];
+ modelVisibilityOverrides?: Record<string, boolean>;
+ };
+
+describe('controller capability metadata', () => {
+ it('distinguishes an absent subscribe field from an explicit empty capability set', () => {
+ expect(__testing.optionalControllerCapabilities({})).toBeUndefined();
+ expect(__testing.optionalControllerCapabilities({ capabilities: [] })).toEqual([]);
+ expect(__testing.optionalControllerCapabilities({
+ capabilities: ['provider-logo-kinds-v2', 42, 'provider-logo-kinds-v2'],
+ })).toEqual(['provider-logo-kinds-v2']);
+ });
+});
/** 一个带完整 routing(含执行机密 + 残留 supportsFastMode)+ per-provider models 的被控端 provider。仿 XD 网关。 */
function xdProviderWithFullRouting() {
@@ -104,12 +123,44 @@ describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {
expect(routing.codex).not.toHaveProperty('authStrategy');
});
+ it('保留 disabled:true 可用性门控,避免禁用 runtime 在控制端重新变成可选', () => {
+ const provider = xdProviderWithFullRouting() as ReturnType<typeof xdProviderWithFullRouting> & {
+ routing: { codex: Record<string, unknown>; 'claude-code': Record<string, unknown> };
+ };
+ provider.routing.codex.disabled = true;
+ const { providers } = project({ providers: [provider] });
+ const routing = providers[0].routing as Record<string, Record<string, unknown>>;
+
+ expect(routing.codex).toEqual({ disabled: true });
+ expect(routing['claude-code']).toEqual({});
+ expect(connectedProvidersForAgent(providers as unknown as ProviderView[], 'codex')).toEqual([]);
+ expect(connectedProvidersForAgent(providers as unknown as ProviderView[], 'claude-code'))
+ .toHaveLength(1);
+ expect(JSON.stringify(routing)).not.toContain(XD_GATEWAY_BASE_URL);
+ });
+
it('models[agent] 原样透传(Fast 显隐数据源:per-provider supportsFastMode)', () => {
const { providers } = project({ providers: [xdProviderWithFullRouting()] });
const models = providers[0].models as Record<string, { id: string; supportsFastMode?: boolean }[]>;
expect(models['claude-code'][0]).toMatchObject({ id: 'claude-opus-4-8', supportsFastMode: true });
});
+ it('保留模型显示 override 快照并过滤非布尔值', () => {
+ const projected = project({
+ providers: [xdProviderWithFullRouting()],
+ modelVisibilityOverrides: {
+ 'claude-code:xd:claude-opus-4-8': false,
+ 'codex:xd:gpt-5.4': true,
+ malformed: 'hidden',
+ },
+ });
+
+ expect(projected.modelVisibilityOverrides).toEqual({
+ 'claude-code:xd:claude-opus-4-8': false,
+ 'codex:xd:gpt-5.4': true,
+ });
+ });
+
it('provider 无 routing → 投影为 undefined(不报错)', () => {
const { providers } = project({
providers: [{ id: 'bare', name: 'Bare', connected: true, agents: ['claude-code'] }],
@@ -148,6 +199,36 @@ describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {
expect(JSON.stringify(providers[0])).not.toContain('secret');
});
+ it('新 logo kind 不发给独立更新的旧版 mobile,避免旧路径表索引 undefined', () => {
+ const { providers } = project({
+ providers: [{
+ ...xdProviderWithFullRouting(),
+ id: 'my-renamed-vercel-provider',
+ routing: {
+ codex: { upstream: 'https://ai-gateway.vercel.sh/v1' },
+ },
+ }],
+ });
+
+ expect(providers[0]).not.toHaveProperty('logoKind');
+ expect(providers[0].routing).toEqual({ codex: {} });
+ });
+
+ it('声明完整 logo 能力的当前控制端收到新 logo kind', () => {
+ const { providers } = projectForCurrentController({
+ providers: [{
+ ...xdProviderWithFullRouting(),
+ id: 'my-renamed-vercel-provider',
+ routing: {
+ codex: { upstream: 'https://ai-gateway.vercel.sh/v1' },
+ },
+ }],
+ });
+
+ expect(providers[0].logoKind).toBe('vercel');
+ expect(providers[0].routing).toEqual({ codex: {} });
+ });
+
it('混合品牌 routing 不产生 logoKind,也不透传伪造值', () => {
const { providers } = project({
providers: [{
diff --git a/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts b/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts
index 1c78af95eb..a4df7d61d4 100644
--- a/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts
@@ -34,6 +34,15 @@ describe('subscriptions topic lifecycle listeners', () => {
expect(subscribed).toHaveBeenCalledTimes(2);
});
+ it('keeps negotiated controller capabilities until the controller is cleared', () => {
+ subscriptions.subscribe('c1', ['sessions'], 'Phone', ['provider-logo-kinds-v2']);
+ expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(true);
+ subscriptions.subscribe('c1', ['session:s1'], 'Phone');
+ expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(true);
+ subscriptions.clearController('c1');
+ expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(false);
+ });
+
it('unsubscribe releases only when no controller still holds the topic', () => {
subscriptions.subscribe('c1', ['fs-watch:/w1']);
subscriptions.subscribe('c2', ['fs-watch:/w1']);
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 9ffeb6dd43..3a0291dc38 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -31,6 +31,7 @@ import {
DL_VOICE_TRANSCRIBE_CHANNEL,
DL_VOICE_CREDENTIAL_SYNC_CHANNEL,
DL_VOICE_DICTIONARY_LEARNING_CHANNEL,
+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
DL_VOICE_DICTIONARY_GET_CHANNEL,
DeviceLinkError,
parseFsWatchTopic,
@@ -43,6 +44,7 @@ import {
import type { MobileVoiceDictionaryLearningRequest } from '@cindy/maker-shared/device-link-contract';
import {
resolveProviderLogoKind,
+ type ProviderLogoKind,
type ProviderLogoRouting,
} from '@cindy/model-providers/branding';
import { app } from 'electron';
@@ -68,8 +70,28 @@ import {
const log = createLogger('device-link-dispatch');
+/**
+ * 老版本 mobile 只认识 #527 之前已发布的 logo kind。新 mark 可由同版本客户端按
+ * provider id 自行解析,但不能作为新 wire enum 发给独立更新的旧控制端。
+ */
+const LEGACY_DEVICE_LINK_LOGO_KINDS: ReadonlySet<ProviderLogoKind> = new Set([
+ 'anthropic',
+ 'openai',
+ 'xd',
+ 'xai',
+ 'openrouter',
+ 'deepseek',
+ 'zhipu',
+ 'zai',
+ 'moonshot',
+ 'minimax',
+ 'alibaba',
+]);
+
/** 控制端名展示上限,挡掉远端塞超长字符串撑爆被控端状态条 */
const MAX_CONTROLLER_NAME_LEN = 64;
+const MAX_CONTROLLER_CAPABILITIES = 32;
+const MAX_CONTROLLER_CAPABILITY_LEN = 80;
const REMOTE_MESSAGE_CHANNELS: ReadonlySet<string> = new Set([
'local-db:messages:list',
'local-db:messages:around',
@@ -85,6 +107,41 @@ const REMOTE_INVOKE_TRUNCATED_CONTENT = '[remote content truncated: payload too
const REMOTE_INVOKE_FRAME_SAFETY_BYTES = 1024;
const textEncoder = new TextEncoder();
+/** wire 输入 fail-closed:未知形状视为空能力集,并限制数量/长度避免撑大常驻 registry。 */
+function sanitizeControllerCapabilities(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const item of value) {
+ if (
+ typeof item !== 'string'
+ || item.length === 0
+ || item.length > MAX_CONTROLLER_CAPABILITY_LEN
+ || seen.has(item)
+ ) continue;
+ seen.add(item);
+ out.push(item);
+ if (out.length >= MAX_CONTROLLER_CAPABILITIES) break;
+ }
+ return out;
+}
+
+function invokeControllerCapabilities(payload: InvokePayload): string[] {
+ const metadata = payload.args?.[0];
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return [];
+ return sanitizeControllerCapabilities(
+ (metadata as { capabilities?: unknown }).capabilities,
+ );
+}
+
+function optionalControllerCapabilities(
+ value: { capabilities?: unknown },
+): string[] | undefined {
+ return Object.prototype.hasOwnProperty.call(value, 'capabilities')
+ ? sanitizeControllerCapabilities(value.capabilities)
+ : undefined;
+}
+
/** 远控 push 的紧凑重试预算:只在首发超 2MB 后使用,避免大 tool 输出反复打爆 relay 帧。 */
const REMOTE_PUSH_TEXT_BUDGET_CHARS = 160_000;
const REMOTE_PUSH_MAX_DEPTH = 8;
@@ -193,25 +250,29 @@ async function persistRemoteSetting(channel: string, args: unknown[], result: un
/**
* routing 投影:剥掉每个 agent 路由的执行细节(upstream / authStrategy / headerDelete /
- * headerOverride / modelIdRewrite / adapter,含自定义供应商 endpoint),只保留可选
- * `wireProtocol:'openai-chat'` 展示标记,让手机区分 Cindy 桥接来源。
+ * headerOverride / modelIdRewrite / adapter,含自定义供应商 endpoint),只保留非敏感的
+ * `wireProtocol:'openai-chat'` 展示标记与 `disabled:true` 可用性门控。后者必须跨端保留,
+ * 否则控制端用共享 registry 重算来源时会把被控端禁用的 runtime 重新当成可选。
*
* 历史上这里曾保留 `routing.supportsFastMode` 给控制端做 Fast 显隐;现 Fast 能力已收归
* per-(provider, agent) 的 `models[agent].supportsFastMode`(唯一真相),控制端直接从隧道带来的
- * `models` 现查(见 ModelSelector),不再读 routing,故 routing 不需保留任何字段。
+ * `models` 现查(见 ModelSelector),不再读 routing;routing 只承载上述两项跨端展示/可用性字段。
*/
function projectRoutingForDisplay(
routing: unknown,
-): Record<string, { wireProtocol?: 'openai-chat' }> | undefined {
+): Record<string, { wireProtocol?: 'openai-chat'; disabled?: true }> | undefined {
if (!routing || typeof routing !== 'object' || Array.isArray(routing)) return undefined;
- const out: Record<string, { wireProtocol?: 'openai-chat' }> = {};
+ const out: Record<string, { wireProtocol?: 'openai-chat'; disabled?: true }> = {};
for (const [agent, value] of Object.entries(routing as Record<string, unknown>)) {
const route = value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null;
- // 只暴露控制端需要展示的「Cindy 桥接」标记。原生协议缺省不回传;endpoint、鉴权、
- // headers、adapter 等执行字段仍全部留在被控端。
- out[agent] = route?.wireProtocol === 'openai-chat' ? { wireProtocol: 'openai-chat' } : {};
+ // 只暴露控制端需要的「Cindy 桥接」标记与禁用门控。原生协议/启用态缺省不回传;
+ // endpoint、鉴权、headers、adapter 等执行字段仍全部留在被控端。
+ out[agent] = {
+ ...(route?.wireProtocol === 'openai-chat' ? { wireProtocol: 'openai-chat' as const } : {}),
+ ...(route?.disabled === true ? { disabled: true as const } : {}),
+ };
}
return out;
}
@@ -221,12 +282,17 @@ function projectRoutingForDisplay(
* 解析非敏感 `logoKind`,再剥掉每个 provider 的 `routing` 执行字段(upstream /
* authStrategy / 密钥策略 / 自定义供应商 endpoint 等)。执行细节(路由 / 密钥)不出被控端
* (控制端只渲染、不执行,见设计文档 D3),但用户重命名 preset 后手机仍能按 logoKind 展示
- * 正确品牌。Fast 显隐由控制端从隧道带来的 `models[agent].supportsFastMode` 现查。
+ * 正确品牌。Fast 显隐由控制端从隧道带来的 `models[agent].supportsFastMode` 现查;
+ * 模型显示 override 快照同样属于非敏感展示状态,需随目录投影给控制端。
* 其它通道原样返回。
*/
-function projectInvokeResultForTunnel(channel: string, result: unknown): unknown {
+function projectInvokeResultForTunnel(
+ channel: string,
+ result: unknown,
+ supportsFullLogoKinds = false,
+): unknown {
if (channel !== 'maker:provider:list') return result;
- const r = result as { providers?: unknown };
+ const r = result as { providers?: unknown; modelVisibilityOverrides?: unknown };
if (!Array.isArray(r.providers)) return result;
const providers = (r.providers as Record<string, unknown>[]).map((p) => {
const rest = { ...p };
@@ -235,11 +301,27 @@ function projectInvokeResultForTunnel(channel: string, result: unknown): unknown
: null;
// Never trust/pass through an arbitrary pre-existing value: only shared resolver output crosses.
delete rest.logoKind;
- if (logoKind) rest.logoKind = logoKind;
+ if (
+ logoKind
+ && (supportsFullLogoKinds || LEGACY_DEVICE_LINK_LOGO_KINDS.has(logoKind))
+ ) {
+ rest.logoKind = logoKind;
+ }
rest.routing = projectRoutingForDisplay(p.routing);
return rest;
});
- return { providers };
+ const modelVisibilityOverrides = r.modelVisibilityOverrides
+ && typeof r.modelVisibilityOverrides === 'object'
+ && !Array.isArray(r.modelVisibilityOverrides)
+ ? Object.fromEntries(
+ Object.entries(r.modelVisibilityOverrides)
+ .filter((entry): entry is [string, boolean] => typeof entry[1] === 'boolean'),
+ )
+ : undefined;
+ return {
+ providers,
+ ...(modelVisibilityOverrides !== undefined ? { modelVisibilityOverrides } : {}),
+ };
}
/** 持有 client 的引用(转发 push 用);wireInboundDispatch 接入时设置。 */
@@ -527,7 +609,12 @@ function handleLinkOpen(
? payload.controllerName.trim().slice(0, MAX_CONTROLLER_NAME_LEN)
: src.slice(0, 8);
// 老控制端无 subscribe 能力:link-open 视作订阅 legacy '*'(全量转发 + 横幅),向后兼容。
- subscriptions.subscribe(src, [LEGACY_TOPIC], name);
+ subscriptions.subscribe(
+ src,
+ [LEGACY_TOPIC],
+ name,
+ sanitizeControllerCapabilities(payload?.capabilities),
+ );
syncForwarding();
client.sendLinkAccept(src, requestId, {
appVersion: app.getVersion(),
@@ -851,7 +938,7 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
const arg = (payload.args ?? [])[0];
const o =
arg && typeof arg === 'object'
- ? (arg as { topics?: unknown; controllerName?: unknown })
+ ? (arg as { topics?: unknown; controllerName?: unknown; capabilities?: unknown })
: {};
const topics = Array.isArray(o.topics)
? o.topics.filter(isRemoteSubscriptionTopic)
@@ -864,7 +951,7 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
: undefined;
const isSub = payload.channel === DL_SUBSCRIBE_CHANNEL;
if (isSub) {
- subscriptions.subscribe(src, topics, name);
+ subscriptions.subscribe(src, topics, name, optionalControllerCapabilities(o));
} else {
subscriptions.unsubscribe(src, topics);
}
@@ -999,14 +1086,33 @@ export async function runInvoke(
}
try {
+ const args = payload.args ?? [];
+ const listingCapabilities = payload.channel === 'maker:provider:list'
+ ? invokeControllerCapabilities(payload)
+ : [];
const result = await runDeviceLinkInvokeContext(
{ controllerDeviceId: src, channel: payload.channel },
- () => dispatchLocalInvoke(payload.channel, payload.args ?? []),
+ // provider:list 的首参只承载隧道能力协商,不进入本机 IPC handler。
+ () => dispatchLocalInvoke(
+ payload.channel,
+ payload.channel === 'maker:provider:list' ? [] : args,
+ ),
);
// 远程 set-* 回流:被控端 set-* runtime-only,补一次 DB 持久化 + 广播 patched,让控制端
// 镜像收敛到被控端真相(取代控制端乐观覆盖)。本机会话不走这条(走 renderer update)。
await persistRemoteSetting(payload.channel, payload.args ?? [], result);
- return { ok: true, result: projectInvokeResultForTunnel(payload.channel, result) };
+ return {
+ ok: true,
+ result: projectInvokeResultForTunnel(
+ payload.channel,
+ result,
+ subscriptions.controllerSupports(
+ src,
+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
+ )
+ || listingCapabilities.includes(CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2),
+ ),
+ };
} catch (err) {
// 被控端 handler 的 throwIpcError `[CODE] message` 原样透传,
// 控制端 renderer 继续用 extractIpcError 解码
@@ -1088,6 +1194,8 @@ export const __testing = {
},
getActiveControllers,
getSubscribedControllers,
+ controllerSupports: subscriptions.controllerSupports,
+ optionalControllerCapabilities,
sendInvokeResultSafe,
projectInvokeResultForTunnel,
forwardPush,
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 90afa0cd17..c74e2ef902 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -15,6 +15,7 @@ import { app, BrowserWindow } from 'electron';
import WebSocket from 'ws';
import {
DeviceLinkClient,
+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
DL_SUBSCRIBE_CHANNEL,
DL_UNSUBSCRIBE_CHANNEL,
type DeviceLinkConnectionIssue,
@@ -737,6 +738,7 @@ export async function openRemoteLink(deviceId: string): Promise<LinkAcceptPayloa
controllerName: deviceName(),
protocolVersion: 1,
appVersion: app.getVersion(),
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
});
openLinkInFlight.set(deviceId, request);
const cleanup = (): void => {
@@ -786,7 +788,11 @@ export async function remoteSubscribe(
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
return client.invoke(deviceId, {
channel: DL_SUBSCRIBE_CHANNEL,
- args: [{ topics, controllerName: deviceName() }],
+ args: [{
+ topics,
+ controllerName: deviceName(),
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ }],
});
}
diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.ts
index d945b317db..55bb8a31c7 100644
--- a/apps/desktop/src/main/device-link/subscriptions.ts
+++ b/apps/desktop/src/main/device-link/subscriptions.ts
@@ -24,6 +24,8 @@ interface ControllerEntry {
/** 友好名(横幅展示用),来自 link-open / subscribe 的 controllerName。 */
name: string;
topics: Set<StoredTopic>;
+ /** link-open 声明的 append-only 控制端能力;旧控制端缺省为空集。 */
+ capabilities: Set<string>;
}
/** 控制本机的控制端信息(被控端可见性状态条用)。 */
@@ -82,7 +84,11 @@ function topicStillHeld(topic: StoredTopic): boolean {
function getOrCreate(deviceId: string, name?: string): ControllerEntry {
let e = registry.get(deviceId);
if (!e) {
- e = { name: name ?? deviceId.slice(0, 8), topics: new Set() };
+ e = {
+ name: name ?? deviceId.slice(0, 8),
+ topics: new Set(),
+ capabilities: new Set(),
+ };
registry.set(deviceId, e);
} else if (name) {
e.name = name;
@@ -91,11 +97,19 @@ function getOrCreate(deviceId: string, name?: string): ControllerEntry {
}
/** 订阅:把 topics 并入该控制端(name 可选,subscribe/link-open 携带时更新)。 */
-export function subscribe(deviceId: string, topics: readonly string[], name?: string): void {
+export function subscribe(
+ deviceId: string,
+ topics: readonly string[],
+ name?: string,
+ capabilities?: readonly string[],
+): void {
// Empty/fully-filtered subscribe frames must not create a registry entry:
// getSubscribedControllers() treats every entry as update-relaunch busy.
if (topics.length === 0) return;
const e = getOrCreate(deviceId, name);
+ if (capabilities) {
+ e.capabilities = new Set(capabilities.filter((value) => typeof value === 'string'));
+ }
for (const t of topics) e.topics.add(t as StoredTopic);
// 幂等重放也通知(控制端断链重连后 replay subscribe → 消费方按幂等语义恢复 watch)。
notifySubscribed(topics);
@@ -155,6 +169,11 @@ export function getControllersForTopic(topic: Topic): string[] {
return out;
}
+/** 查询 link-open 协商出的控制端能力;未知/已断链控制端一律 false。 */
+export function controllerSupports(deviceId: string, capability: string): boolean {
+ return registry.get(deviceId)?.capabilities.has(capability) === true;
+}
+
function isControlTopic(t: StoredTopic): boolean {
return t === LEGACY_TOPIC || t.startsWith('session:');
}
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index 687751f7cb..95f81bac41 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -234,7 +234,9 @@ function connectedProvider(
source: 'builtin',
agents: [agentKind],
auth: { method: 'managed' },
- routing: {},
+ routing: {
+ [agentKind]: { upstream: 'https://example.test', authStrategy: 'gateway-key' },
+ },
models: { [agentKind]: models },
connected: true,
};
diff --git a/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts b/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts
index 2012715fcf..cb532dc975 100644
--- a/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts
+++ b/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts
@@ -81,7 +81,10 @@ const providers = [
'claude-code': claudeModels,
codex: codexModels,
},
- routing: {},
+ routing: {
+ 'claude-code': { upstream: 'https://xd.example', authStrategy: 'gateway-key' },
+ codex: { upstream: 'https://xd.example', authStrategy: 'gateway-key' },
+ },
},
{
id: 'openai',
@@ -93,7 +96,9 @@ const providers = [
'claude-code': [],
codex: openAiCodexModels,
},
- routing: {},
+ routing: {
+ codex: { upstream: 'https://api.openai.com', authStrategy: 'oauth-passthrough' },
+ },
},
];
diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
index 845b407d90..e2bc2b8fad 100644
--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
@@ -102,6 +102,32 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {
expect(deriveAvailableModels(cat, 'codex').find((m) => m.id === 'gpt-5.5')?.contextWindow).toBe(272_000);
});
+ it('跳过 routing.disabled runtime,且不占用同模型的 first-wins', () => {
+ const cat = injectedCatalog();
+ const openai = cat.providers.find((provider) => provider.id === 'openai')!;
+ const xd = cat.providers.find((provider) => provider.id === 'xd')!;
+ const openaiCodexRoute = openai.routing.codex;
+ if (!openaiCodexRoute) throw new Error('OpenAI Codex route fixture missing');
+ openai.routing.codex = {
+ ...openaiCodexRoute,
+ disabled: true,
+ };
+ openai.models.codex = [
+ model('disabled-only', { name: 'Disabled only' }),
+ model('gpt-5.5', { name: 'Disabled first', contextWindow: 111 }),
+ ];
+ xd.models.codex = [
+ model('gpt-5.5', { name: 'Enabled later', contextWindow: 222 }),
+ ];
+
+ const derived = deriveAvailableModels(cat, 'codex');
+ expect(derived.some((candidate) => candidate.id === 'disabled-only')).toBe(false);
+ expect(derived.find((candidate) => candidate.id === 'gpt-5.5')).toMatchObject({
+ displayName: 'Enabled later',
+ contextWindow: 222,
+ });
+ });
+
it('runtime refresh replaces both agent model lists in place so existing sessions keep the live reference', () => {
const claudeModels: ModelDescriptor[] = [{ id: 'stale-claude', displayName: 'Stale', contextWindow: 1, efforts: [], defaultEffort: null }];
const codexModels: ModelDescriptor[] = [{ id: 'stale-codex', displayName: 'Stale', contextWindow: 1, efforts: [], defaultEffort: null }];
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
new file mode 100644
index 0000000000..8b34d9e1a3
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
@@ -0,0 +1,298 @@
+import type { AgentLoginMode, AuthLoginOptions, AuthState } from '@cindy/maker-core';
+import { describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({ userDataDir: '/tmp/cindy-codex-login-concurrency' }));
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: () => h.userDataDir,
+ getAppPath: () => h.userDataDir,
+ isPackaged: false,
+ },
+ safeStorage: { isEncryptionAvailable: () => false },
+}));
+
+vi.mock('@cindy/maker-core', () => ({}));
+
+describe('DesktopCodexAuthAdapter login single-flight', () => {
+ it('rolls back credentials when Cancel arrives during successful-login finalization', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+ let finishLocalRead!: (state: AuthState) => void;
+ const readLocalCodexAuthState = vi.fn(() => new Promise<AuthState>((resolve) => {
+ finishLocalRead = resolve;
+ }));
+ const disconnectCodexOAuth = vi.fn().mockResolvedValue(undefined);
+ const pending = {
+ mode: 'browser' as const,
+ promise: Promise.resolve({ authenticated: false }),
+ progressListeners: new Set(),
+ progressHistory: [],
+ progressHistoryChars: 0,
+ cancelled: false,
+ };
+ Object.defineProperties(adapter, {
+ codexHome: { configurable: true, value: h.userDataDir },
+ readLocalCodexAuthState: { configurable: true, value: readLocalCodexAuthState },
+ disconnectCodexOAuth: { configurable: true, value: disconnectCodexOAuth },
+ pendingLogin: { configurable: true, writable: true, value: pending },
+ loginCancellationOpen: { configurable: true, writable: true, value: true },
+ loginAborted: { configurable: true, writable: true, value: false },
+ currentLoginProc: { configurable: true, writable: true, value: null },
+ });
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(
+ fallback: AuthState | undefined,
+ isCancelled: () => boolean,
+ ): Promise<AuthState>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+
+ const result = finishSuccessfulCodexLogin(undefined, () => pending.cancelled);
+ await vi.waitFor(() => expect(readLocalCodexAuthState).toHaveBeenCalledOnce());
+ adapter.cancelLogin();
+ finishLocalRead({ authenticated: true, authSource: 'oauth' });
+
+ await expect(result).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ expect(disconnectCodexOAuth).toHaveBeenCalledOnce();
+ });
+
+ it('coalesces the same mode but cancels and serializes a different mode', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+
+ let finishBrowser!: (state: AuthState) => void;
+ const browserRun = new Promise<AuthState>((resolve) => {
+ finishBrowser = resolve;
+ });
+ let browserOptions: AuthLoginOptions | undefined;
+ const runTriggerLogin = vi.fn((opts?: AuthLoginOptions): Promise<AuthState> => {
+ const mode: AgentLoginMode = opts?.mode ?? 'browser';
+ if (mode === 'browser') browserOptions = opts;
+ return mode === 'browser'
+ ? browserRun
+ : Promise.resolve({ authenticated: true, authSource: 'oauth' });
+ });
+ Object.defineProperty(adapter, 'runTriggerLogin', {
+ configurable: true,
+ value: runTriggerLogin,
+ });
+ const cancelLogin = vi.spyOn(adapter, 'cancelLogin').mockImplementation(() => {});
+
+ const firstProgress = vi.fn();
+ const duplicateProgress = vi.fn();
+ const firstBrowser = adapter.triggerLogin({ mode: 'browser', onProgress: firstProgress });
+ const duplicateBrowser = adapter.triggerLogin({ mode: 'browser', onProgress: duplicateProgress });
+ browserOptions?.onProgress?.('stdout:Authorize at https://example.com/device');
+ const deviceCode = adapter.triggerLogin({ mode: 'device-code' });
+
+ expect(duplicateBrowser).toBe(firstBrowser);
+ expect(firstProgress).toHaveBeenCalledOnce();
+ expect(duplicateProgress).toHaveBeenCalledOnce();
+ expect(runTriggerLogin).toHaveBeenCalledTimes(1);
+ expect(cancelLogin).toHaveBeenCalledOnce();
+ expect(
+ (adapter as unknown as { pendingLogin: { mode: AgentLoginMode; promise: Promise<AuthState> } })
+ .pendingLogin,
+ ).toMatchObject({ mode: 'device-code', promise: deviceCode });
+
+ finishBrowser({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(firstBrowser).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ await expect(deviceCode).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ expect(runTriggerLogin).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ mode: 'device-code',
+ onProgress: expect.any(Function),
+ }),
+ expect.any(Function),
+ );
+ });
+
+ it('lets a later logout-style cancellation cancel a queued mode switch before it starts', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+ let finishBrowser!: (state: AuthState) => void;
+ const browserRun = new Promise<AuthState>((resolve) => {
+ finishBrowser = resolve;
+ });
+ const runTriggerLogin = vi.fn((opts?: AuthLoginOptions): Promise<AuthState> =>
+ (opts?.mode ?? 'browser') === 'browser'
+ ? browserRun
+ : Promise.resolve({ authenticated: true, authSource: 'oauth' }),
+ );
+ Object.defineProperty(adapter, 'runTriggerLogin', {
+ configurable: true,
+ value: runTriggerLogin,
+ });
+ Object.defineProperty(adapter, 'loginCancellationOpen', {
+ configurable: true,
+ writable: true,
+ value: true,
+ });
+
+ const browser = adapter.triggerLogin({ mode: 'browser' });
+ const deviceCode = adapter.triggerLogin({ mode: 'device-code' });
+ adapter.cancelLogin();
+ finishBrowser({ authenticated: false, errorReason: 'login_cancelled' });
+
+ await expect(browser).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ await expect(deviceCode).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ expect(runTriggerLogin).toHaveBeenCalledTimes(1);
+ });
+
+ it('restarts a cancelled same-mode login after the cancelled operation settles', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+ let finishFirst!: (state: AuthState) => void;
+ const firstRun = new Promise<AuthState>((resolve) => {
+ finishFirst = resolve;
+ });
+ const runTriggerLogin = vi.fn()
+ .mockReturnValueOnce(firstRun)
+ .mockResolvedValueOnce({ authenticated: true, authSource: 'oauth' });
+ Object.defineProperty(adapter, 'runTriggerLogin', {
+ configurable: true,
+ value: runTriggerLogin,
+ });
+
+ const first = adapter.triggerLogin({ mode: 'browser' });
+ adapter.cancelLogin();
+ const retry = adapter.triggerLogin({ mode: 'browser' });
+
+ expect(retry).not.toBe(first);
+ expect(runTriggerLogin).toHaveBeenCalledTimes(1);
+ finishFirst({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(first).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ await expect(retry).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ expect(runTriggerLogin).toHaveBeenCalledTimes(2);
+ });
+
+ it('queues a mode switch behind both the cancelled login and an active logout', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+ let finishBrowser!: (state: AuthState) => void;
+ const browserRun = new Promise<AuthState>((resolve) => {
+ finishBrowser = resolve;
+ });
+ let finishLogout!: () => void;
+ const logoutOperation = new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ });
+ const runTriggerLogin = vi.fn((opts?: AuthLoginOptions): Promise<AuthState> =>
+ (opts?.mode ?? 'browser') === 'browser'
+ ? browserRun
+ : Promise.resolve({ authenticated: true, authSource: 'oauth' }),
+ );
+ Object.defineProperty(adapter, 'runTriggerLogin', {
+ configurable: true,
+ value: runTriggerLogin,
+ });
+
+ const browser = adapter.triggerLogin({ mode: 'browser' });
+ Object.defineProperty(adapter, 'logoutOperation', {
+ configurable: true,
+ writable: true,
+ value: logoutOperation,
+ });
+ const deviceCode = adapter.triggerLogin({ mode: 'device-code' });
+ finishBrowser({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(browser).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ await Promise.resolve();
+ expect(runTriggerLogin).toHaveBeenCalledTimes(1);
+
+ finishLogout();
+ await expect(deviceCode).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ expect(runTriggerLogin).toHaveBeenCalledTimes(2);
+ });
+
+ it('queues a new login until an in-flight logout fully settles', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+ let finishLogout!: () => void;
+ const logoutOperation = new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ });
+ Object.defineProperty(adapter, 'logoutOperation', {
+ configurable: true,
+ writable: true,
+ value: logoutOperation,
+ });
+ const runTriggerLogin = vi.fn(async (): Promise<AuthState> => ({
+ authenticated: true,
+ authSource: 'oauth',
+ }));
+ Object.defineProperty(adapter, 'runTriggerLogin', {
+ configurable: true,
+ value: runTriggerLogin,
+ });
+
+ const login = adapter.triggerLogin({ mode: 'device-code' });
+ await Promise.resolve();
+ expect(runTriggerLogin).not.toHaveBeenCalled();
+
+ finishLogout();
+ await expect(login).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ expect(runTriggerLogin).toHaveBeenCalledOnce();
+ });
+
+ it('lets a repeated logout cancel a login queued behind the active logout', async () => {
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
+ typeof DesktopCodexAuthAdapter
+ >;
+ let finishLogout!: () => void;
+ const logoutOperation = new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ });
+ Object.defineProperty(adapter, 'logoutOperation', {
+ configurable: true,
+ writable: true,
+ value: logoutOperation,
+ });
+ const runTriggerLogin = vi.fn(async (): Promise<AuthState> => ({
+ authenticated: true,
+ authSource: 'oauth',
+ }));
+ Object.defineProperty(adapter, 'runTriggerLogin', {
+ configurable: true,
+ value: runTriggerLogin,
+ });
+
+ const queuedLogin = adapter.triggerLogin({ mode: 'device-code' });
+ const repeatedLogout = adapter.logout();
+ expect(repeatedLogout).toBe(logoutOperation);
+
+ finishLogout();
+ await expect(queuedLogin).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ expect(runTriggerLogin).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthState.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthState.test.ts
index 6cb364e662..dcd28f7b74 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthState.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthState.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
buildCodexLoginTerminationPlan,
+ codexLoginArgs,
requireCodexOAuthLoginState,
resolveCodexLoginCleanupPreflight,
resolveCodexLoginExitState,
@@ -13,6 +14,17 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe('codexLoginArgs', () => {
+ it('uses the official browser flow by default', () => {
+ expect(codexLoginArgs()).toEqual(['login']);
+ expect(codexLoginArgs('browser')).toEqual(['login']);
+ });
+
+ it('uses the official device authorization flow when requested', () => {
+ expect(codexLoginArgs('device-code')).toEqual(['login', '--device-auth']);
+ });
+});
+
describe('requireCodexOAuthLoginState', () => {
it('accepts an authenticated OAuth state unchanged', () => {
const state = {
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 350a5d0305..15e0a7b2b4 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
@@ -15,6 +15,7 @@ import {
getCustomProvider,
listCustomProviders,
updateCustomProvider,
+ updateCustomProviderIfUnchanged,
validateCustomProviderConfig,
} from '../custom-provider-store.js';
import type { CustomProviderConfig } from '@cindy/model-providers';
@@ -182,6 +183,43 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect(await getCustomProvider('openrouter')).toBeNull();
});
+ it('applies discovered models only while the saved provider still matches its snapshot', async () => {
+ mountDb();
+ await createCustomProvider(valid, 1_000);
+ const snapshot = await getCustomProvider('openrouter');
+ expect(snapshot).not.toBeNull();
+ const discovered = {
+ ...snapshot!,
+ runtimes: {
+ ...snapshot!.runtimes,
+ codex: {
+ ...snapshot!.runtimes.codex!,
+ models: [
+ ...snapshot!.runtimes.codex!.models,
+ { id: 'new-model', name: 'New model' },
+ ],
+ },
+ },
+ };
+
+ expect(
+ await updateCustomProviderIfUnchanged('openrouter', snapshot!, discovered, 1_000),
+ ).toBe(true);
+ expect((await getCustomProvider('openrouter'))?.runtimes.codex?.models).toHaveLength(2);
+
+ await updateCustomProvider('openrouter', {
+ ...valid,
+ name: 'Edited in another window',
+ }, 1_000);
+ expect(
+ await updateCustomProviderIfUnchanged('openrouter', discovered, {
+ ...discovered,
+ name: 'Stale discovery write',
+ }, 1_000),
+ ).toBe(false);
+ expect((await getCustomProvider('openrouter'))?.name).toBe('Edited in another window');
+ });
+
it('round-trips headers + dedupes models on normalize', async () => {
mountDb();
await createCustomProvider({
@@ -220,6 +258,53 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe('openai-chat');
});
+ it('preserves legacy remote auth:none records for repair without deleting them', async () => {
+ mountDb();
+ raw!.prepare(
+ `INSERT INTO custom_providers
+ (id, name, runtimes, auth, sort_order, created_at, updated_at)
+ VALUES (?, ?, ?, ?, 0, 1, 1)`,
+ ).run(
+ 'legacy-no-auth',
+ 'Legacy no auth',
+ JSON.stringify({
+ codex: {
+ baseUrl: 'https://remote.example/v1',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ }),
+ JSON.stringify({ method: 'none' }),
+ );
+
+ const [loaded] = await listCustomProviders();
+ expect(loaded.id).toBe('legacy-no-auth');
+ expect(loaded.auth).toEqual({ method: 'none' });
+ expect(loaded.runtimes.codex?.baseUrl).toBe('https://remote.example/v1');
+ expect(raw!.prepare('SELECT auth FROM custom_providers WHERE id = ?').get('legacy-no-auth'))
+ .toEqual({ auth: JSON.stringify({ method: 'none' }) });
+ });
+
+ it('keeps legacy loopback auth:none records enabled when loading', async () => {
+ mountDb();
+ raw!.prepare(
+ `INSERT INTO custom_providers
+ (id, name, runtimes, auth, sort_order, created_at, updated_at)
+ VALUES (?, ?, ?, ?, 0, 1, 1)`,
+ ).run(
+ 'legacy-loopback',
+ 'Legacy loopback',
+ JSON.stringify({
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ }),
+ JSON.stringify({ method: 'none' }),
+ );
+
+ expect((await getCustomProvider('legacy-loopback'))?.auth).toEqual({ method: 'none' });
+ });
+
it('round-trips a validated exact inference request path', async () => {
mountDb();
await createCustomProvider({
diff --git a/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts
index 44bdcb9684..761d858ed9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts
@@ -72,8 +72,34 @@ describe('validateCustomProviderConfig auth 段', () => {
expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'apiKey' } }).ok).toBe(true);
});
- it('none method 明确允许无密钥代理,但不允许夹带 OAuth 描述符', () => {
- expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'none' } }).ok).toBe(true);
+ it('none method 只允许无密钥回环代理,且不允许夹带 OAuth 描述符', () => {
+ expect(
+ validateCustomProviderConfig({
+ ...BASE,
+ auth: { method: 'none' },
+ runtimes: {
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ modelsUrl: 'http://localhost:4000/v1/models',
+ models: [],
+ },
+ },
+ }).ok,
+ ).toBe(true);
+ expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'none' } }).ok).toBe(false);
+ expect(
+ validateCustomProviderConfig({
+ ...BASE,
+ auth: { method: 'none' },
+ runtimes: {
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ modelsUrl: 'https://models.example/v1/models',
+ models: [],
+ },
+ },
+ }).ok,
+ ).toBe(false);
expect(
validateCustomProviderConfig({
...BASE,
diff --git a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
index 248d55694b..cd29d41855 100644
--- a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
@@ -22,6 +22,7 @@ import {
deriveModelsDiscoveryUrl,
hasGenericOAuthLogin,
logoutGenericOAuth,
+ removeGenericOAuthCredentialsReversibly,
readCachedGenericOAuthAccessToken,
refreshGenericOAuthIfNeeded,
discoverGenericOAuthModels,
@@ -64,12 +65,14 @@ function memStorage(): GenericOAuthStorage & { map: Map<string, string> } {
return {
map,
read: (id) => map.get(id) ?? null,
+ readStrict: (id) => map.get(id) ?? null,
write: (id, v) => {
map.set(id, v);
return true;
},
remove: (id) => {
map.delete(id);
+ return true;
},
};
}
@@ -132,6 +135,55 @@ describe('blob 读写 / has / logout', () => {
resetGenericOAuthMemoryCache();
expect(hasGenericOAuthLogin('acme')).toBe(false);
});
+
+ it('可回滚删除会在配置写失败后恢复原 OAuth blob', () => {
+ seedBlob('acme', { access_token: 'at-1', refresh_token: 'rt-1' });
+
+ const restore = removeGenericOAuthCredentialsReversibly('acme');
+ expect(restore).not.toBeNull();
+ expect(storage.map.has('acme')).toBe(false);
+ expect(restore?.()).toBe(true);
+
+ resetGenericOAuthMemoryCache();
+ expect(readCachedGenericOAuthAccessToken('acme', OAUTH)).toBe('at-1');
+ });
+
+ it('冷缓存严格快照不可读时在删除前中止,不把现有凭证误判成缺失', () => {
+ storage.map.set('acme', JSON.stringify({ access_token: 'at-1' }));
+ const remove = storage.remove;
+ storage.remove = () => {
+ throw new Error('must not remove');
+ };
+ storage.readStrict = () => {
+ throw new Error('safeStorage unavailable');
+ };
+ resetGenericOAuthMemoryCache();
+
+ expect(removeGenericOAuthCredentialsReversibly('acme')).toBeNull();
+ expect(storage.map.get('acme')).toContain('at-1');
+
+ storage.remove = remove;
+ });
+
+ it('回滚按原始字符串恢复持久 blob,同时恢复删除前的热缓存', () => {
+ const raw = '{ "access_token": "durable", "refresh_token": "rt" }';
+ storage.map.set('acme', raw);
+ resetGenericOAuthMemoryCache();
+ expect(readCachedGenericOAuthAccessToken('acme', OAUTH)).toBe('durable');
+
+ const restore = removeGenericOAuthCredentialsReversibly('acme');
+ expect(restore?.()).toBe(true);
+ expect(storage.map.get('acme')).toBe(raw);
+ expect(readCachedGenericOAuthAccessToken('acme', OAUTH)).toBe('durable');
+ });
+
+ it('凭证删除失败时保留当前登录态并返回失败', () => {
+ seedBlob('acme', { access_token: 'at-1' });
+ storage.remove = () => false;
+
+ expect(logoutGenericOAuth('acme')).toBe(false);
+ expect(hasGenericOAuthLogin('acme')).toBe(true);
+ });
});
describe('临期刷新(单飞)', () => {
@@ -197,6 +249,61 @@ describe('登录流与凭证落盘失败', () => {
expect(JSON.parse(storage.map.get('acme')!).access_token).toBe('at-new');
});
+ it('迟到取消只回滚本次登录写入的凭证,不误删更新的 blob', async () => {
+ autoAuthorize();
+ fetchResponder = () =>
+ new Response(JSON.stringify({ access_token: 'at-new', expires_in: 3600 }), { status: 200 });
+ let rollback: (() => boolean) | undefined;
+
+ const res = await runGenericOAuthLogin(
+ { id: 'acme', name: 'Acme' },
+ OAUTH,
+ { onCredentialPersisted: (fn) => { rollback = fn; } },
+ );
+ expect(res.ok).toBe(true);
+ expect(rollback).toBeTypeOf('function');
+
+ storage.map.set('acme', JSON.stringify({ access_token: 'newer-login' }));
+ expect(rollback?.()).toBe(true);
+ expect(JSON.parse(storage.map.get('acme')!).access_token).toBe('newer-login');
+ });
+
+ it('取消回滚用严格持久读取核对本次 token,不受热路径 fail-soft 读取影响', async () => {
+ autoAuthorize();
+ fetchResponder = () =>
+ new Response(JSON.stringify({ access_token: 'at-new', expires_in: 3600 }), { status: 200 });
+ let rollback: (() => boolean) | undefined;
+
+ await runGenericOAuthLogin(
+ { id: 'acme', name: 'Acme' },
+ OAUTH,
+ { onCredentialPersisted: (fn) => { rollback = fn; } },
+ );
+ storage.read = () => null;
+
+ expect(rollback?.()).toBe(true);
+ expect(storage.map.has('acme')).toBe(false);
+ });
+
+ it('取消回滚无法严格核对持久 token 时报告失败并保留凭证', async () => {
+ autoAuthorize();
+ fetchResponder = () =>
+ new Response(JSON.stringify({ access_token: 'at-new', expires_in: 3600 }), { status: 200 });
+ let rollback: (() => boolean) | undefined;
+
+ await runGenericOAuthLogin(
+ { id: 'acme', name: 'Acme' },
+ OAUTH,
+ { onCredentialPersisted: (fn) => { rollback = fn; } },
+ );
+ storage.readStrict = () => {
+ throw new Error('safeStorage unavailable');
+ };
+
+ expect(rollback?.()).toBe(false);
+ expect(JSON.parse(storage.map.get('acme')!).access_token).toBe('at-new');
+ });
+
it('登录时 storage.write 失败 → 硬失败且不留「已连接」内存态(回归:防重启后授权静默丢失)', async () => {
autoAuthorize();
storage.write = () => false;
@@ -464,6 +571,15 @@ describe('deriveModelsDiscoveryUrl', () => {
);
expect(deriveModelsDiscoveryUrl('https://api.acme.example/')).toBe('https://api.acme.example/v1/models');
});
+
+ it('基于 pathname 追加模型端点,保留 query 并丢弃 fragment', () => {
+ expect(deriveModelsDiscoveryUrl('https://api.acme.example/v1?tenant=a#ignored')).toBe(
+ 'https://api.acme.example/v1/models?tenant=a',
+ );
+ expect(deriveModelsDiscoveryUrl('https://api.acme.example/root/?tenant=a')).toBe(
+ 'https://api.acme.example/root/v1/models?tenant=a',
+ );
+ });
});
describe('oauth-token 路由分支', () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts
index 86548bdc70..daa3c45095 100644
--- a/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts
@@ -3,12 +3,13 @@
* 覆盖:整表替换、脏数据过滤、key 维度命中、未设 ⇒ undefined(回落目录默认)、重置。
*/
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
__resetModelVisibilityMirrorForTest,
getModelVisibilityOverride,
setModelVisibilityMirror,
+ syncModelVisibilityMirror,
} from '../model-visibility-mirror.js';
afterEach(() => {
@@ -39,6 +40,35 @@ describe('model-visibility-mirror', () => {
expect(getModelVisibilityOverride('claude-code', 'xd', 'b')).toBe(true);
});
+ it('仅在净化后的整表实际变化时返回 true,供调用方广播目录失效事件', () => {
+ expect(setModelVisibilityMirror({
+ 'claude-code:xd:a': false,
+ dirty: 'ignored',
+ })).toBe(true);
+ expect(setModelVisibilityMirror({
+ dirty: 1,
+ 'claude-code:xd:a': false,
+ })).toBe(false);
+ expect(setModelVisibilityMirror({
+ 'claude-code:xd:a': true,
+ })).toBe(true);
+ expect(setModelVisibilityMirror(null)).toBe(true);
+ expect(setModelVisibilityMirror([])).toBe(false);
+ });
+
+ it('只在镜像实变时调用目录失效回调', () => {
+ const invalidate = vi.fn();
+
+ expect(syncModelVisibilityMirror({ 'codex:openai:gpt-5': false }, invalidate)).toBe(true);
+ expect(syncModelVisibilityMirror(
+ { dirty: 'ignored', 'codex:openai:gpt-5': false },
+ invalidate,
+ )).toBe(false);
+ expect(syncModelVisibilityMirror({ 'codex:openai:gpt-5': true }, invalidate)).toBe(true);
+
+ expect(invalidate).toHaveBeenCalledTimes(2);
+ });
+
it('过滤非 boolean 脏值;非对象入参清空镜像', () => {
setModelVisibilityMirror({ 'claude-code:xd:a': false, 'claude-code:xd:bad': 'nope' as unknown as boolean });
expect(getModelVisibilityOverride('claude-code', 'xd', 'a')).toBe(false);
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts
index 690f94b1ae..4ffa07d5ee 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts
@@ -203,6 +203,24 @@ describe('buildProbeRequest', () => {
expect(headers['x-api-key']).toBeUndefined();
expect(headers['authorization']).toBeUndefined();
});
+
+ it('no-auth 探测剥掉表单残留的大小写混合凭证头', () => {
+ const { init } = buildProbeRequest({
+ agent: 'codex',
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ modelId: 'local-model',
+ authMethod: 'none',
+ headers: {
+ Authorization: 'Bearer must-not-leak',
+ 'X-API-Key': 'must-not-leak',
+ 'X-Tenant': 'local',
+ },
+ });
+ expect(init.headers).toEqual({
+ 'content-type': 'application/json',
+ 'X-Tenant': 'local',
+ });
+ });
});
function fakeResponse(status: number, body = ''): Response {
@@ -437,6 +455,7 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {
runtimes: {
'claude-code': {
...config.runtimes['claude-code'],
+ baseUrl: 'http://127.0.0.1:4100',
headers: {
...config.runtimes['claude-code'].headers,
Authorization: 'Bearer must-not-leak',
@@ -452,4 +471,32 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {
expect(spec.apiKey).toBeNull();
expect(spec.headers).toEqual({ 'x-tenant': 't1' });
});
+
+ it('拒绝探测已禁用的 saved runtime,绝不进入网络请求', async () => {
+ setCustomProviders([
+ buildUserProvider({
+ id: 'legacy-remote-no-auth',
+ name: 'Legacy remote no-auth',
+ auth: { method: 'none' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://remote.example/v1',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ },
+ }),
+ ]);
+ let fetchCalled = false;
+
+ await expect(
+ testProviderConnection(
+ { kind: 'saved', providerId: 'legacy-remote-no-auth', agent: 'codex' },
+ async () => {
+ fetchCalled = true;
+ return fakeResponse(200, '{}');
+ },
+ ),
+ ).rejects.toThrow(/disabled/);
+ expect(fetchCalled).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
index aa58513f7e..ee4088c561 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
@@ -4,7 +4,7 @@
* (模式同 providerDiagnostics.test.ts)。
*/
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import {
buildModelsFetchRequest,
@@ -28,6 +28,14 @@ describe('buildModelsFetchRequest', () => {
).toBe('https://openrouter.ai/api/v1/models');
});
+ it('preserves base URL query parameters while appending the discovery pathname', () => {
+ expect(
+ buildModelsFetchRequest(
+ spec({ agent: 'codex', baseUrl: 'https://openrouter.ai/api/v1?tenant=a#ignored' }),
+ ).url,
+ ).toBe('https://openrouter.ai/api/v1/models?tenant=a');
+ });
+
it('explicit modelsUrl wins over derivation only when same-host as baseUrl', () => {
// 同主机(Moonshot 形态:baseUrl …/anthropic,列模型在同 host 的 /v1/models)→ 采用。
expect(
@@ -69,9 +77,58 @@ describe('buildModelsFetchRequest', () => {
expect(h['authorization']).toBeUndefined();
expect(h['x-extra']).toBe('1');
});
+
+ it.each(['none', 'oauth'] as const)(
+ 'strips legacy credential headers for %s auth even without an apiKey',
+ (authMethod) => {
+ const h = buildModelsFetchRequest(spec({
+ authMethod,
+ apiKey: null,
+ headers: {
+ Authorization: 'Bearer legacy',
+ 'X-API-Key': 'legacy',
+ 'x-extra': '1',
+ },
+ })).init.headers as Record<string, string>;
+
+ expect(h.Authorization).toBeUndefined();
+ expect(h['X-API-Key']).toBeUndefined();
+ expect(h.authorization).toBeUndefined();
+ expect(h['x-api-key']).toBeUndefined();
+ expect(h['x-extra']).toBe('1');
+ },
+ );
});
describe('fetchProviderModels', () => {
+ it.each([
+ {
+ baseUrl: 'https://remote.example/v1',
+ modelsUrl: null,
+ },
+ {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ modelsUrl: 'https://remote.example/v1/models',
+ },
+ ])('returns a structured failure for non-loopback no-auth discovery: %j', async (urls) => {
+ const fetchImpl = vi.fn<typeof fetch>();
+ const result = await fetchProviderModels(
+ spec({
+ ...urls,
+ authMethod: 'none',
+ apiKey: null,
+ }),
+ fetchImpl,
+ );
+
+ expect(result).toEqual({
+ ok: false,
+ code: 'UNKNOWN',
+ detail: 'no-auth provider model discovery requires loopback URLs',
+ });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
it('parses OpenAI {data:[{id}]} shape, preferring display_name/name for labels', async () => {
const r = await fetchProviderModels(spec(), async () =>
fakeResponse(
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts
index 6aa9b5b674..c75bd96a7f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts
@@ -11,6 +11,7 @@ vi.mock('../../appCapabilities.js', () => ({
import { BUNDLED_CATALOG, buildUserProvider, type AgentKind, type RoutingDescriptor } from '@cindy/model-providers';
import {
+ beginProviderRouteMutation,
buildLocalHandlerHeaders,
buildRouteDecision,
resolveSessionRouteDecision,
@@ -473,6 +474,38 @@ describe('none (无鉴权自定义代理 buildRouteDecision)', () => {
});
});
+ it('disabled 的历史远程无鉴权路由直接 fail closed', async () => {
+ const decision = buildRouteDecision(
+ {
+ upstream: 'https://remote.example/v1',
+ authStrategy: 'none',
+ disabled: true,
+ },
+ KEY,
+ 'codex',
+ null,
+ );
+ expect(decision).toEqual({ localHandler: expect.any(Function) });
+
+ const end = vi.fn();
+ await decision!.localHandler!({
+ rawBody: Buffer.from('{}'),
+ parsedBody: { model: 'legacy-model' },
+ ctx: {
+ reqId: 1,
+ method: 'POST',
+ url: '/responses',
+ headers: {},
+ },
+ res: { writeHead: vi.fn(), end } as never,
+ });
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: {
+ message: 'The selected provider is disabled; update its endpoint or authentication settings before retrying.',
+ },
+ });
+ });
+
it('本地 Chat 桥也剥掉复制配置里残留的鉴权与账号头', () => {
expect(
buildLocalHandlerHeaders({
@@ -528,6 +561,75 @@ describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 k
});
});
+ it('blocks new routes while endpoint and key switch as one logical mutation', async () => {
+ setCustomProviders([
+ buildUserProvider({
+ id: 'openrouter',
+ name: 'OpenRouter',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://old.example/v1',
+ models: [{ id: 'custom-model', name: 'Custom Model' }],
+ },
+ },
+ }),
+ ]);
+ setCustomProviderKeyReader(() => 'old-key');
+ setSessionProvider('s-user', 'openrouter');
+ expect(resolveSessionRouteDecision('s-user', 'codex', KEY)).toMatchObject({
+ upstreamOverride: 'https://old.example/v1',
+ headerOverride: { authorization: 'Bearer old-key' },
+ });
+
+ const finishMutation = beginProviderRouteMutation('openrouter');
+ try {
+ // Secret writes are synchronous and may become visible before the catalog refresh awaits.
+ setCustomProviderKeyReader(() => 'new-key');
+ const decision = await Promise.resolve(
+ resolveSessionRouteDecision('s-user', 'codex', KEY),
+ );
+ expect(decision).toEqual({ localHandler: expect.any(Function) });
+ const writeHead = vi.fn();
+ const end = vi.fn();
+ await decision!.localHandler!({
+ rawBody: Buffer.from('{}'),
+ parsedBody: { model: 'custom-model' },
+ ctx: { reqId: 1, method: 'POST', url: '/responses', headers: {} },
+ res: { writeHead, end } as never,
+ });
+ expect(writeHead).toHaveBeenCalledWith(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: {
+ type: 'provider_route_updating',
+ code: 'provider_route_updating',
+ },
+ });
+ } finally {
+ finishMutation();
+ }
+
+ setCustomProviders([
+ buildUserProvider({
+ id: 'openrouter',
+ name: 'OpenRouter',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://new.example/v1',
+ models: [{ id: 'custom-model', name: 'Custom Model' }],
+ },
+ },
+ }),
+ ]);
+ expect(resolveSessionRouteDecision('s-user', 'codex', KEY)).toMatchObject({
+ upstreamOverride: 'https://new.example/v1',
+ headerOverride: { authorization: 'Bearer new-key' },
+ });
+ });
+
it('精确请求路径只覆盖带 model 的推理请求,不改写无 body 的控制面请求', () => {
setCustomProviders([
buildUserProvider({
@@ -558,6 +660,52 @@ describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 k
});
});
+ it('disabled runtime 返回本地错误,不允许 proxy 回落到默认供应商', async () => {
+ const disabled = buildUserProvider({
+ id: 'legacy-remote',
+ name: 'Legacy Remote',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://remote.example/v1',
+ models: [{ id: 'legacy-model', name: 'Legacy Model' }],
+ },
+ },
+ auth: { method: 'none' },
+ });
+ expect(disabled.routing.codex?.disabled).toBe(true);
+ setCustomProviders([disabled]);
+ setSessionProvider('s-user', 'legacy-remote');
+
+ const decision = await Promise.resolve(
+ resolveSessionRouteDecision('s-user', 'codex', KEY, 'legacy-model'),
+ );
+ expect(decision).toEqual({ localHandler: expect.any(Function) });
+
+ const writeHead = vi.fn();
+ const end = vi.fn();
+ await decision!.localHandler!({
+ rawBody: Buffer.from('{}'),
+ parsedBody: { model: 'legacy-model' },
+ ctx: {
+ reqId: 1,
+ method: 'POST',
+ url: '/responses',
+ headers: {},
+ },
+ res: { writeHead, end } as never,
+ });
+ expect(writeHead).toHaveBeenCalledWith(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: {
+ type: 'provider_route_disabled',
+ code: 'provider_route_disabled',
+ },
+ });
+ });
+
it('内置供应商 isUserProviderSession=false', () => {
setSessionProvider('s-user', 'xd');
expect(isUserProviderSession('s-user')).toBe(false);
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts
index b018171558..66f3075c95 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
-import { BUNDLED_CATALOG } from '@cindy/model-providers';
+import { BUNDLED_CATALOG, connectedProvidersForAgent } from '@cindy/model-providers';
import { createProviderService } from '../provider-service.js';
@@ -71,4 +71,86 @@ describe('createProviderService', () => {
(await svc.listProviders()).find((provider) => provider.id === noAuthProvider.id)?.connected,
).toBe(true);
});
+
+ it('keeps a disabled legacy no-auth provider disconnected', async () => {
+ const base = BUNDLED_CATALOG.providers[0];
+ const disabledProvider = {
+ ...base,
+ id: 'legacy-remote-no-auth',
+ name: 'Legacy remote no-auth',
+ auth: { method: 'none' as const },
+ routing: Object.fromEntries(
+ Object.entries(base.routing).map(([agent, routing]) => [
+ agent,
+ routing ? { ...routing, disabled: true } : routing,
+ ]),
+ ),
+ };
+ const svc = createProviderService({
+ getCatalog: () => ({
+ version: 'disabled-no-auth-test',
+ providers: [disabledProvider],
+ }),
+ connection: {
+ xd: () => false,
+ anthropic: () => false,
+ openai: () => false,
+ xai: () => false,
+ },
+ });
+
+ expect((await svc.listProviders())[0]?.connected).toBe(false);
+ });
+
+ it('keeps a no-auth provider disconnected when its declared runtime has no routing descriptor', async () => {
+ const base = BUNDLED_CATALOG.providers[0];
+ const missingRouteProvider = {
+ ...base,
+ id: 'missing-route-no-auth',
+ name: 'Missing route no-auth',
+ auth: { method: 'none' as const },
+ routing: {},
+ };
+ const svc = createProviderService({
+ getCatalog: () => ({ version: 'missing-route-no-auth-test', providers: [missingRouteProvider] }),
+ connection: {
+ xd: () => false,
+ anthropic: () => false,
+ openai: () => false,
+ xai: () => false,
+ },
+ });
+
+ const providers = await svc.listProviders();
+ expect(providers[0]?.connected).toBe(false);
+ expect(connectedProvidersForAgent(providers, base.agents[0]!)).toHaveLength(0);
+ });
+
+ it('does not promote a disabled runtime when another runtime keeps a no-auth provider connected', async () => {
+ const base = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd')!;
+ const mixedProvider = {
+ ...base,
+ id: 'mixed-local-no-auth',
+ name: 'Mixed local no-auth',
+ auth: { method: 'none' as const },
+ routing: {
+ ...base.routing,
+ codex: { ...base.routing.codex!, disabled: true },
+ },
+ };
+ const svc = createProviderService({
+ getCatalog: () => ({ version: 'mixed-runtime-test', providers: [mixedProvider] }),
+ connection: {
+ xd: () => false,
+ anthropic: () => false,
+ openai: () => false,
+ xai: () => false,
+ },
+ });
+
+ const providers = await svc.listProviders();
+ expect(providers[0]?.connected).toBe(true);
+ expect(connectedProvidersForAgent(providers, 'claude-code')).toHaveLength(1);
+ expect(connectedProvidersForAgent(providers, 'codex')).toHaveLength(0);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 5ff8954bb8..923191cfd6 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -21,7 +21,13 @@ import { promises as fsp, existsSync } from 'node:fs';
import { spawn, execFile, type ChildProcess } from 'node:child_process';
import { promisify } from 'node:util';
-import type { AuthAdapter, AuthAdapterOptions, AuthState } from '@cindy/maker-core';
+import type {
+ AgentLoginMode,
+ AuthAdapter,
+ AuthAdapterOptions,
+ AuthLoginOptions,
+ AuthState,
+} from '@cindy/maker-core';
import { getCachedBinaryStatus, isVettedAgentBinaryPath } from '../agent-binaries/index.js';
import { createLogger } from '../logger.js';
import { prepareCodexGlobalSkillsLinks } from './codex-global-skills.js';
@@ -40,6 +46,7 @@ import {
writeInvalidatedSystemCodexAuthMarker,
} from './codex-auth-invalidation.js';
import {
+ codexLoginArgs,
requireCodexOAuthLoginState,
resolveCodexLoginCleanupPreflight,
resolveCodexLoginExitState,
@@ -531,12 +538,25 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
// ═════════════════════════════════════════════════════════════════════════════
/** Codex AuthAdapter —— OAuth 子进程登录 + auth.json 读状态; getAuthEnv 仅注入 CODEX_HOME。 */
+type PendingCodexLogin = {
+ mode: AgentLoginMode;
+ promise: Promise<AuthState>;
+ progressListeners: Set<NonNullable<AuthLoginOptions['onProgress']>>;
+ progressHistory: string[];
+ progressHistoryChars: number;
+ cancelled: boolean;
+};
+
+const MAX_COALESCED_LOGIN_PROGRESS_CHARS = 64 * 1024;
+
export class DesktopCodexAuthAdapter implements AuthAdapter {
private currentLoginProc: ChildProcess | null = null;
- /** 多窗口 / 重复点击共用同一条登录流程,避免两个 codex login 同时写 auth.json。 */
- private pendingLogin: Promise<AuthState> | null = null;
+ /** 同模式重复点击共用流程;切换登录模式时先取消旧流程再串行启动新流程。 */
+ private pendingLogin: PendingCodexLogin | null = null;
+ /** logout 全流程的线性化点;其间新登录排队到凭证清理和解绑全部完成之后。 */
+ private logoutOperation: Promise<void> | null = null;
private loginAborted = false;
- /** 只在 CLI 尚未成功退出时接受取消;进入凭证 finalize 后成功线性化,迟到取消不再翻转结果。 */
+ /** CLI 和凭证 finalize 都未收口时接受取消;成功结果返回后才关闭窗口。 */
private loginCancellationOpen = false;
/**
* logout() 成功后回调 —— 由 maker-host 注入本地 Codex host 收割。
@@ -982,19 +1002,87 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
}
- triggerLogin(opts?: { onProgress?: (msg: string) => void }): Promise<AuthState> {
- if (this.pendingLogin) return this.pendingLogin;
- const run = this.runTriggerLogin(opts).finally(() => {
- if (this.pendingLogin === run) {
- this.pendingLogin = null;
- this.loginCancellationOpen = false;
+ triggerLogin(opts?: AuthLoginOptions): Promise<AuthState> {
+ const mode = opts?.mode ?? 'browser';
+ if (this.pendingLogin) {
+ if (this.pendingLogin.mode === mode && !this.pendingLogin.cancelled) {
+ if (opts?.onProgress && !this.pendingLogin.progressListeners.has(opts.onProgress)) {
+ this.pendingLogin.progressListeners.add(opts.onProgress);
+ for (const message of this.pendingLogin.progressHistory) {
+ try {
+ opts.onProgress(message);
+ } catch {
+ /* 一个 IPC listener 失败不能阻断其它窗口或登录流程。 */
+ }
+ }
+ }
+ return this.pendingLogin.promise;
+ }
+ const previous = this.pendingLogin.promise;
+ if (!this.pendingLogin.cancelled) this.cancelLogin();
+ const waits = [previous, ...(this.logoutOperation ? [this.logoutOperation] : [])];
+ const barrier = Promise.all(waits.map((operation) => operation.catch(() => undefined)));
+ return this.startTrackedLogin(opts, barrier);
+ }
+ return this.startTrackedLogin(opts, this.logoutOperation ?? undefined);
+ }
+
+ private startTrackedLogin(
+ opts?: AuthLoginOptions,
+ waitFor?: Promise<unknown>,
+ ): Promise<AuthState> {
+ const mode = opts?.mode ?? 'browser';
+ const operation: PendingCodexLogin = {
+ mode,
+ promise: null as unknown as Promise<AuthState>,
+ progressListeners: new Set(opts?.onProgress ? [opts.onProgress] : []),
+ progressHistory: [],
+ progressHistoryChars: 0,
+ cancelled: false,
+ };
+ const emitProgress = (message: string): void => {
+ operation.progressHistory.push(message);
+ operation.progressHistoryChars += message.length;
+ while (
+ operation.progressHistoryChars > MAX_COALESCED_LOGIN_PROGRESS_CHARS
+ && operation.progressHistory.length > 1
+ ) {
+ operation.progressHistoryChars -= operation.progressHistory.shift()?.length ?? 0;
+ }
+ for (const listener of operation.progressListeners) {
+ try {
+ listener(message);
+ } catch {
+ /* 一个 IPC listener 失败不能阻断其它窗口或登录流程。 */
+ }
}
+ };
+ const start = (): Promise<AuthState> => {
+ if (operation.cancelled) {
+ return Promise.resolve({ authenticated: false, errorReason: 'login_cancelled' });
+ }
+ return this.runTriggerLogin(
+ { ...opts, mode, onProgress: emitProgress },
+ () => operation.cancelled,
+ );
+ };
+ const execution = waitFor
+ ? waitFor.catch(() => undefined).then(start)
+ : start();
+ const run = execution.finally(() => {
+ if (this.pendingLogin?.promise !== run) return;
+ this.pendingLogin = null;
+ this.loginCancellationOpen = false;
});
- this.pendingLogin = run;
+ operation.promise = run;
+ this.pendingLogin = operation;
return run;
}
- private async runTriggerLogin(opts?: { onProgress?: (msg: string) => void }): Promise<AuthState> {
+ private async runTriggerLogin(
+ opts?: AuthLoginOptions,
+ isCancelled: () => boolean = () => false,
+ ): Promise<AuthState> {
this.ensureInvalidationMarkerLoaded();
this.loginAborted = false;
this.loginCancellationOpen = true;
@@ -1026,7 +1114,9 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// spawn codex login。POSIX 建独立进程组,取消/超时时连同回调 server 一起收割。
return new Promise<AuthState>((resolve) => {
- const proc = spawn(binaryPath, ['login'], {
+ const mode: AgentLoginMode = opts?.mode ?? 'browser';
+ const proc = spawn(binaryPath, codexLoginArgs(mode), {
+ shell: false,
env: { ...process.env, CODEX_HOME: this.codexHome },
stdio: ['ignore', 'pipe', 'pipe'],
detached: process.platform !== 'win32',
@@ -1039,13 +1129,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
const stderrTail: string[] = [];
proc.stdout?.on('data', (chunk: Buffer) => {
- opts?.onProgress?.(`stdout:${String(chunk).trim()}`);
+ // data chunk 边界不等于文本边界;保留原始空白,IPC 层会分流累积后解析。
+ opts?.onProgress?.(`stdout:${String(chunk)}`);
});
proc.stderr?.on('data', (chunk: Buffer) => {
- const s = String(chunk).trim();
- stderrTail.push(s);
+ const raw = String(chunk);
+ stderrTail.push(raw.trim());
if (stderrTail.length > 5) stderrTail.shift();
- opts?.onProgress?.(`stderr:${s}`);
+ opts?.onProgress?.(`stderr:${raw}`);
});
const complete = (state: AuthState): void => {
@@ -1068,8 +1159,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// cancel 可能重复终止已退出进程,或把成功结果错误翻成 cancelled。
if (timeout) clearTimeout(timeout);
if (this.currentLoginProc === proc) this.currentLoginProc = null;
- const cancelled = this.loginAborted;
- this.loginCancellationOpen = false;
+ const cancelled = this.loginAborted || isCancelled();
const exitState = resolveCodexLoginExitState({
cancelled,
timedOut,
@@ -1085,7 +1175,10 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
: timedOut
? { authenticated: false, errorReason: 'login_timeout' }
: undefined;
- void this.finishSuccessfulCodexLogin(noOAuthFallback).then(complete, (err: unknown) => {
+ void this.finishSuccessfulCodexLogin(
+ noOAuthFallback,
+ () => this.loginAborted || isCancelled(),
+ ).then(complete, (err: unknown) => {
complete({
authenticated: false,
errorReason: `login_finalize_error:${err instanceof Error ? err.message : String(err)}`,
@@ -1100,7 +1193,22 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
});
}
- private async finishSuccessfulCodexLogin(noOAuthFallback?: AuthState): Promise<AuthState> {
+ private async finishSuccessfulCodexLogin(
+ noOAuthFallback?: AuthState,
+ isCancelled: () => boolean = () => false,
+ ): Promise<AuthState> {
+ const cancelFinalization = (): Promise<AuthState> | null => {
+ if (!isCancelled()) return null;
+ // The CLI may already have written a valid token. A late Cancel must establish the same
+ // durable disconnected boundary as logout, otherwise the next state read can resurrect it.
+ return this.disconnectCodexOAuth().then(() => ({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ }));
+ };
+ const cancelledBeforeFinalize = cancelFinalization();
+ if (cancelledBeforeFinalize) return cancelledBeforeFinalize;
+
// 收紧 auth.json 权限 (fail-soft: 失败只打日志, 不阻塞登录成功)。
// Win 上 chmod 0o600 在 NTFS 是 no-op,走 icacls;POSIX 用标准 0o600。
const authPath = path.join(this.codexHome, 'auth.json');
@@ -1118,6 +1226,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// 先直接校验刚由 CLI 写入的本地文件,再改变 invalidation / reconcile 状态。否则 CLI
// 即使 exit 0 但没产出 access_token,也会把原来的 token_invalidated 内存态提前清掉。
const localOAuthState = requireCodexOAuthLoginState(await this.readLocalCodexAuthState());
+ const cancelledAfterLocalRead = cancelFinalization();
+ if (cancelledAfterLocalRead) return cancelledAfterLocalRead;
if (!localOAuthState.authenticated) return noOAuthFallback ?? localOAuthState;
// 系统文件仍是被判坏 / 被用户主动断开的原凭证时继续 suppress,避免覆盖新登录。
@@ -1132,11 +1242,15 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
} else {
await this.reconcileWithSystemCodexAfterLogin();
}
+ const cancelledAfterReconcile = cancelFinalization();
+ if (cancelledAfterReconcile) return cancelledAfterReconcile;
// `codex login` 的成功必须由真实 access_token 证明;绝不能被 XD Gateway fallback 冒充。
bindNativeProviderAuth('openai');
const state = requireCodexOAuthLoginState(
await this.readState({ skipReconcile: true, credentialMode: 'oauth-bearer' }),
);
+ const cancelledAfterStateRead = cancelFinalization();
+ if (cancelledAfterStateRead) return cancelledAfterStateRead;
if (!state.authenticated) return state;
// 真正拿到 OAuth 后才重启本地 codex host;失败只记日志,不翻转登录结果。
@@ -1147,25 +1261,53 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
log.warn('onLoginSuccess threw', { error: (e as Error).message });
}
}
+ const cancelledAfterHostRestart = cancelFinalization();
+ if (cancelledAfterHostRestart) return cancelledAfterHostRestart;
return state;
}
/** Codex OAuth 子进程 abort —— 用户在浏览器授权流半路反悔时调。 */
cancelLogin(): void {
- // 设置 abort 标志覆盖 assets prepare 阶段;CLI 成功 exit 后取消窗口已关闭。
- if (!this.pendingLogin || !this.loginCancellationOpen) return;
+ // 设置 abort 标志覆盖 assets prepare、CLI 和凭证 finalize 阶段。
+ if (!this.pendingLogin) return;
+ this.pendingLogin.cancelled = true;
+ if (!this.loginCancellationOpen) return;
this.loginAborted = true;
if (this.currentLoginProc) terminateCodexLoginProcess(this.currentLoginProc);
}
- async logout(opts?: { preserveInvalidatedReason?: boolean }): Promise<void> {
+ logout(opts?: { preserveInvalidatedReason?: boolean }): Promise<void> {
+ if (this.logoutOperation) {
+ // 登录可能在第一次 logout 之后排队、等待同一个 barrier。后来的 logout 仍代表更新的
+ // 用户意图,必须把这份 queued login 标成 cancelled,不能只复用旧 Promise 后让它启动。
+ this.cancelLogin();
+ return this.logoutOperation;
+ }
+ const run = this.runLogout(opts).finally(() => {
+ if (this.logoutOperation === run) this.logoutOperation = null;
+ });
+ this.logoutOperation = run;
+ return run;
+ }
+
+ private async runLogout(opts?: { preserveInvalidatedReason?: boolean }): Promise<void> {
this.ensureInvalidationMarkerLoaded();
// 登出与在途登录串行:先取消并等它完全收口,防迟到的 auth.json 在登出后复活账号。
- const pendingLogin = this.pendingLogin;
+ const pendingLogin = this.pendingLogin?.promise;
if (pendingLogin) {
this.cancelLogin();
await pendingLogin.catch(() => undefined);
}
+ await this.disconnectCodexOAuth(opts);
+ }
+
+ /**
+ * 建立 durable Codex 断开边界并清理 host/cache。
+ * 调用方负责先处理 pendingLogin;登录 finalize 自身取消时不能等待自己的 Promise。
+ */
+ private async disconnectCodexOAuth(
+ opts?: { preserveInvalidatedReason?: boolean },
+ ): Promise<void> {
let durableDisconnectCommitted = false;
if (!opts?.preserveInvalidatedReason) {
const systemAuthPath = getSystemCodexAuthPath();
diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
index c847cb0542..d5fd6e2f37 100644
--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
@@ -6,10 +6,9 @@
* CODEX_MODELS(其 capabilities.availableModels 起始为空),host 在 bootstrap 时从**同步的**
* BUNDLED_CATALOG 派生每个 agent 的模型列表,经 capabilityAdditions 注入。
*
- * union 规则:按 `catalog.providers` 数组序 flatMap 各 provider 的 `models[agent]`,按 id
- * **首见胜出**去重(provider 序即 anthropic → openai → xd)。同一 agent 内同 id 跨 provider
- * 的元数据一致性由 @cindy/model-providers 的 parseCatalog → validateModelConsistency 保证,
- * 因此去重取首个即可,不会丢信息。
+ * union 规则:跳过 `routing[agent].disabled` 的 runtime,再按 `catalog.providers` 数组序
+ * flatMap 各 provider 的 `models[agent]`,按 id **首见胜出**去重(provider 序即
+ * anthropic → openai → xd)。禁用来源不占 seen,同 id 仍可由后续可用来源补上。
*
* 顺序契约(no-break):派生结果必须逐字逐序复现迁移前的有效列表
* (cc = 旧 CLAUDE_MODELS 序 then XD 追加序;codex = 旧 CODEX_MODELS 序 then 折扣追加序)。
@@ -46,6 +45,7 @@ export function deriveAvailableModels(catalog: Catalog, agent: AgentKind): Model
const seen = new Set<string>();
const out: ModelDescriptor[] = [];
for (const provider of catalog.providers) {
+ if (provider.routing[agent]?.disabled === true) continue;
for (const m of provider.models[agent] ?? []) {
if (seen.has(m.id)) continue;
seen.add(m.id);
diff --git a/apps/desktop/src/main/maker-host/codex-auth-state.ts b/apps/desktop/src/main/maker-host/codex-auth-state.ts
index 8d9822fa72..b891025d4b 100644
--- a/apps/desktop/src/main/maker-host/codex-auth-state.ts
+++ b/apps/desktop/src/main/maker-host/codex-auth-state.ts
@@ -2,6 +2,13 @@ import type { ChildProcess } from 'node:child_process';
import type { AuthState } from '@cindy/maker-core';
+export type CodexLoginMode = 'browser' | 'device-code';
+
+/** 官方 Codex CLI 的两种交互登录入口。 */
+export function codexLoginArgs(mode: CodexLoginMode = 'browser'): string[] {
+ return mode === 'device-code' ? ['login', '--device-auth'] : ['login'];
+}
+
/** 平台化的 Codex 登录子进程终止方案。 */
export type CodexLoginTerminationPlan =
| { kind: 'windows-handle'; signal: 'SIGKILL' }
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 04060f7562..751c026212 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -12,7 +12,7 @@
* (测试用 `setCurrentDbClient` 注入内存 db,见 __tests__)。
*/
-import { asc, eq } from 'drizzle-orm';
+import { and, asc, eq } from 'drizzle-orm';
import type {
AgentKind,
@@ -22,6 +22,7 @@ import type {
} from '@cindy/model-providers';
import {
findReservedOAuthExtraParam,
+ isLoopbackProviderUrl,
isProviderRequestPath,
} from '@cindy/model-providers';
@@ -45,6 +46,23 @@ function invalid(message: string): ValidationResult {
return { ok: false, code: 'INVALID_PARAMS', message };
}
+function validateNoAuthLoopbackBoundary(
+ auth: CustomProviderConfig['auth'],
+ runtimes: Partial<Record<AgentKind, CustomProviderRuntimeConfig>>,
+): ValidationResult {
+ if (auth?.method !== 'none') return { ok: true };
+ for (const [agent, runtime] of Object.entries(runtimes)) {
+ if (!runtime) continue;
+ if (!isLoopbackProviderUrl(runtime.baseUrl)) {
+ return invalid(`runtime '${agent}' baseUrl must be loopback when auth method is none`);
+ }
+ if (runtime.modelsUrl !== undefined && !isLoopbackProviderUrl(runtime.modelsUrl)) {
+ return invalid(`runtime '${agent}' modelsUrl must be loopback when auth method is none`);
+ }
+ }
+ return { ok: true };
+}
+
function validateRuntime(agent: string, rt: unknown): ValidationResult {
if (!rt || typeof rt !== 'object') return invalid(`runtime '${agent}' must be an object`);
const r = rt as Record<string, unknown>;
@@ -144,6 +162,30 @@ function validateAuthSection(auth: unknown): ValidationResult {
if (flow !== 'authorization-code' && flow !== 'device-code') {
return invalid("auth.oauth.flow must be 'authorization-code' | 'device-code'");
}
+ const allowedFields = new Set(
+ flow === 'device-code'
+ ? [
+ 'flow',
+ 'tokenUrl',
+ 'clientId',
+ 'scopes',
+ 'modelsDiscoveryUrl',
+ 'deviceAuthorizationUrl',
+ 'extraDeviceParams',
+ ]
+ : [
+ 'flow',
+ 'tokenUrl',
+ 'clientId',
+ 'scopes',
+ 'modelsDiscoveryUrl',
+ 'authorizeUrl',
+ 'redirectPort',
+ 'extraAuthParams',
+ ],
+ );
+ const unknownField = Object.keys(o).find((field) => !allowedFields.has(field));
+ if (unknownField) return invalid(`auth.oauth.${unknownField} is not allowed`);
if (
flow === 'authorization-code'
&& (o.deviceAuthorizationUrl !== undefined || o.extraDeviceParams !== undefined)
@@ -262,7 +304,10 @@ export function validateCustomProviderConfig(config: unknown): ValidationResult
const r = validateRuntime(k, rts[k]);
if (!r.ok) return r;
}
- return { ok: true };
+ return validateNoAuthLoopbackBoundary(
+ c.auth as CustomProviderConfig['auth'],
+ rts as Partial<Record<AgentKind, CustomProviderRuntimeConfig>>,
+ );
}
/** 规整单个 runtime(trim baseUrl、去重 models、裁 headers)。 */
@@ -429,7 +474,16 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRun
function rowToConfig(row: typeof customProviders.$inferSelect): CustomProviderConfig {
const auth = parseAuth(row.auth);
- return { id: row.id, name: row.name, ...(auth ? { auth } : {}), runtimes: parseRuntimes(row.runtimes) };
+ const runtimes = parseRuntimes(row.runtimes);
+ // #527 之前保存的远程 auth:none 记录保留原始表单数据,供设置页展示和修复。
+ // buildUserProvider 会把不满足当前 loopback 边界的 runtime 标成 disabled;路由解析
+ // 一律拒绝 disabled 描述符,因此不会把历史远程 endpoint 重新解释成 API-key 路由。
+ return {
+ id: row.id,
+ name: row.name,
+ ...(auth ? { auth } : {}),
+ runtimes,
+ };
}
/** 列出当前账号的全部自定义供应商(按 sortOrder 升序,再按 createdAt)。 */
@@ -497,12 +551,49 @@ export async function updateCustomProvider(
name: c.name,
runtimes: JSON.stringify(c.runtimes),
auth: c.auth ? JSON.stringify(c.auth) : null,
- updatedAt: now,
+ updatedAt: Math.max(now, existing.updatedAt + 1),
})
.where(eq(customProviders.id, id));
return c;
}
+/**
+ * 仅当配置仍与调用方读取的快照一致时更新。供 OAuth 登录后的异步模型发现使用:
+ * 用户若在网络请求期间编辑了供应商,旧结果不能覆盖新配置。
+ */
+export async function updateCustomProviderIfUnchanged(
+ id: string,
+ expected: CustomProviderConfig,
+ config: CustomProviderConfig,
+ now: number = Date.now(),
+): Promise<boolean> {
+ const expectedConfig = normalizeConfig({ ...expected, id });
+ const nextConfig = normalizeConfig({ ...config, id });
+ const db = getDbClient().drizzle;
+ const existing = await db.select().from(customProviders).where(eq(customProviders.id, id)).get();
+ if (!existing) return false;
+ const expectedRuntimes = JSON.stringify(expectedConfig.runtimes);
+ const expectedAuth = expectedConfig.auth ? JSON.stringify(expectedConfig.auth) : null;
+ if (
+ existing.name !== expectedConfig.name
+ || existing.runtimes !== expectedRuntimes
+ || existing.auth !== expectedAuth
+ ) return false;
+ const result = await db
+ .update(customProviders)
+ .set({
+ name: nextConfig.name,
+ runtimes: JSON.stringify(nextConfig.runtimes),
+ auth: nextConfig.auth ? JSON.stringify(nextConfig.auth) : null,
+ updatedAt: Math.max(now, existing.updatedAt + 1),
+ })
+ .where(and(
+ eq(customProviders.id, id),
+ eq(customProviders.updatedAt, existing.updatedAt),
+ ));
+ return result.changes === 1;
+}
+
/** 删除(幂等:不存在也不报错)。 */
export async function deleteCustomProvider(id: string): Promise<void> {
const db = getDbClient().drizzle;
diff --git a/apps/desktop/src/main/maker-host/generic-oauth.ts b/apps/desktop/src/main/maker-host/generic-oauth.ts
index 32267b54e2..a53141ee48 100644
--- a/apps/desktop/src/main/maker-host/generic-oauth.ts
+++ b/apps/desktop/src/main/maker-host/generic-oauth.ts
@@ -48,8 +48,13 @@ const DEFAULT_TOKEN_TTL_MS = 60 * 60 * 1000;
// ── 注入点(默认 no-op,host 启动期接线;测试注入内存实现)──────────────────────
export interface GenericOAuthStorage {
read(providerId: string): string | null;
+ /**
+ * 配置 mutation 前的严格快照读取:不存在返回 null;读取/解密失败必须抛错,
+ * 不能像热路径 read 一样折叠成“无凭证”。
+ */
+ readStrict(providerId: string): string | null;
write(providerId: string, value: string): boolean;
- remove(providerId: string): void;
+ remove(providerId: string): boolean;
}
interface GenericOAuthIo {
@@ -77,7 +82,12 @@ function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {
}
let io: GenericOAuthIo = {
- storage: { read: () => null, write: () => false, remove: () => {} },
+ storage: {
+ read: () => null,
+ readStrict: () => null,
+ write: () => false,
+ remove: () => true,
+ },
// 第三方 provider 的 token / device / refresh 端点多在境外,默认走吃系统代理的通道。
fetchImpl: outboundFetch,
openExternal: async () => {
@@ -133,19 +143,21 @@ function blobFromTokenResponse(t: TokenResponse, prev?: OAuthTokenBlob | null):
// undefined = 尚未从磁盘读过;null = 确认无凭证。凭证只经本模块读写,失效点精确。
const blobCache = new Map<string, OAuthTokenBlob | null>();
+function parseBlob(raw: string | null): OAuthTokenBlob | null {
+ if (!raw) return null;
+ try {
+ const blob = JSON.parse(raw) as OAuthTokenBlob;
+ return typeof blob.access_token === 'string' && blob.access_token.length > 0 ? blob : null;
+ } catch {
+ return null;
+ }
+}
+
function readBlob(providerId: string): OAuthTokenBlob | null {
const cached = blobCache.get(providerId);
if (cached !== undefined) return cached;
const raw = io.storage.read(providerId);
- let blob: OAuthTokenBlob | null = null;
- if (raw) {
- try {
- const b = JSON.parse(raw) as OAuthTokenBlob;
- blob = typeof b.access_token === 'string' && b.access_token.length > 0 ? b : null;
- } catch {
- blob = null;
- }
- }
+ const blob = parseBlob(raw);
blobCache.set(providerId, blob);
return blob;
}
@@ -167,12 +179,45 @@ export function hasGenericOAuthLogin(providerId: string): boolean {
return readBlob(providerId) !== null;
}
-/** 登出:清凭证 + 缓存(含 per-provider 刷新链条目,防长期运行下 Map 积累)。 */
-export function logoutGenericOAuth(providerId: string): void {
- io.storage.remove(providerId);
+/** 登出:持久凭证删除成功后才清缓存,失败时保持登录态并通知调用方。 */
+export function logoutGenericOAuth(providerId: string): boolean {
+ if (!io.storage.remove(providerId)) return false;
blobCache.set(providerId, null);
// 链上若有 in-flight 刷新也安全:doRefresh 落盘前会复核 blob 已清则不回写。
refreshChains.delete(providerId);
+ return true;
+}
+
+/**
+ * 可回滚地删除凭证。配置写入与 safeStorage 无法组成同一个数据库事务,因此调用方在
+ * 配置提交失败时必须用返回的闭包恢复旧 blob;成功提交后直接丢弃闭包即可。
+ */
+export function removeGenericOAuthCredentialsReversibly(
+ providerId: string,
+): (() => boolean) | null {
+ let previousRaw: string | null;
+ try {
+ previousRaw = io.storage.readStrict(providerId);
+ } catch (err) {
+ log.warn('generic oauth 凭证严格快照失败,拒绝删除', {
+ providerId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+ const durableBlob = parseBlob(previousRaw);
+ // 已有文件却无法解析也不是“无凭证”。保留原始文件并中止 mutation,避免配置失败回滚时
+ // 把坏/新版 blob 静默删掉;未来格式迁移仍有恢复机会。
+ if (previousRaw !== null && !durableBlob) return null;
+ const cachedBeforeDelete = blobCache.get(providerId);
+ const cacheToRestore = cachedBeforeDelete ?? durableBlob;
+ if (!logoutGenericOAuth(providerId)) return null;
+ return () => {
+ if (previousRaw !== null && !io.storage.write(providerId, previousRaw)) return false;
+ if (cacheToRestore !== undefined) blobCache.set(providerId, cacheToRestore);
+ else blobCache.delete(providerId);
+ return true;
+ };
}
/**
@@ -456,6 +501,11 @@ export interface GenericOAuthDeviceCodeProgress {
export interface GenericOAuthLoginOptions {
onProgress?: (progress: GenericOAuthDeviceCodeProgress) => void;
+ /**
+ * 凭证成功落盘后交出一次竞态安全的回滚闭包。只有当前凭证仍是本次登录写入的 blob
+ * 时才删除;若后续登录/刷新已换新则 no-op,避免迟到取消误删新凭证。
+ */
+ onCredentialPersisted?: (rollback: () => boolean) => void;
}
// 同一时刻每个 provider 只允许一个登录流。
@@ -686,12 +736,28 @@ export async function runGenericOAuthLogin(
// 落盘前最后检查:已取消的登录绝不写凭证(同 grok)。
if (abort.signal.aborted) throw new Error('login_cancelled');
- if (!writeBlob(provider.id, blobFromTokenResponse(tok))) {
+ const persistedBlob = blobFromTokenResponse(tok);
+ if (!writeBlob(provider.id, persistedBlob)) {
// 落盘失败必须硬失败并回滚内存态:否则 UI 显示已连接、路由能用,重启/刷新后
// 授权静默消失(safeStorage 不可用或 .enc 写不进磁盘的机器上尤其致命)。
blobCache.set(provider.id, null);
throw new Error('凭证写入本机安全存储失败,请检查系统钥匙串/加密服务后重试');
}
+ const persistedRaw = JSON.stringify(persistedBlob);
+ options?.onCredentialPersisted?.(() => {
+ let currentRaw: string | null;
+ try {
+ currentRaw = io.storage.readStrict(provider.id);
+ } catch (err) {
+ log.warn('generic oauth 取消回滚无法严格核对持久凭证', {
+ providerId: provider.id,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ return false;
+ }
+ if (currentRaw !== persistedRaw) return true;
+ return logoutGenericOAuth(provider.id);
+ });
listener?.succeed(provider.name);
log.info('generic oauth login success', { providerId: provider.id, scope: tok.scope });
return { ok: true };
@@ -714,8 +780,14 @@ export async function runGenericOAuthLogin(
* 此时只追加 `/models`。自定义 OAuth 供应商靠这条推导免去用户手填发现端点。
*/
export function deriveModelsDiscoveryUrl(baseUrl: string): string {
- const u = baseUrl.replace(/\/+$/, '');
- return /\/v\d+$/i.test(u) ? `${u}/models` : `${u}/v1/models`;
+ const url = new URL(baseUrl);
+ url.hash = '';
+ let pathname = url.pathname;
+ while (pathname.length > 1 && pathname.endsWith('/')) pathname = pathname.slice(0, -1);
+ url.pathname = /\/v\d+$/i.test(pathname)
+ ? `${pathname}/models`
+ : `${pathname === '/' ? '' : pathname}/v1/models`;
+ return url.toString();
}
/**
diff --git a/apps/desktop/src/main/maker-host/model-visibility-mirror.ts b/apps/desktop/src/main/maker-host/model-visibility-mirror.ts
index 356ee0c00e..df41d7b81c 100644
--- a/apps/desktop/src/main/maker-host/model-visibility-mirror.ts
+++ b/apps/desktop/src/main/maker-host/model-visibility-mirror.ts
@@ -31,17 +31,40 @@ function keyOf(agent: AgentKind, providerId: string, modelId: string): string {
/**
* 接收 renderer 推来的整张 override map(MODEL_VISIBILITY_SYNC handler 调用)。
* 整表替换语义(renderer 每次推完整快照),只保留 value 为 boolean 的条目(防脏数据)。
+ * 返回净化后的镜像是否实际变化,调用方据此避免重复广播目录失效事件。
*/
-export function setModelVisibilityMirror(raw: unknown): void {
- if (!raw || typeof raw !== 'object') {
- mirror = {};
- return;
- }
+export function setModelVisibilityMirror(raw: unknown): boolean {
const next: VisibilityMap = {};
- for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
- if (k && typeof v === 'boolean') next[k] = v;
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
+ if (k && typeof v === 'boolean') next[k] = v;
+ }
+ }
+
+ const currentKeys = Object.keys(mirror);
+ const nextKeys = Object.keys(next);
+ if (
+ currentKeys.length === nextKeys.length
+ && currentKeys.every((key) => mirror[key] === next[key])
+ ) {
+ return false;
}
+
mirror = next;
+ return true;
+}
+
+/**
+ * 应用 renderer 的整表快照,并只在规范化值实变时通知目录消费者失效。
+ * 抽成可直接行为测试的边界,避免 IPC 接线只能靠源码字符串断言。
+ */
+export function syncModelVisibilityMirror(
+ raw: unknown,
+ onChanged: () => void,
+): boolean {
+ if (!setModelVisibilityMirror(raw)) return false;
+ onChanged();
+ return true;
}
/**
diff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
index f155ff9e8e..da157593d5 100644
--- a/apps/desktop/src/main/maker-host/provider-diagnostics.ts
+++ b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
@@ -16,6 +16,7 @@
import {
appendProviderRequestPath,
+ isLoopbackProviderUrl,
type AgentKind,
type ProviderWireProtocol,
} from '@cindy/model-providers';
@@ -38,6 +39,8 @@ export interface ProviderProbeSpec {
agent: AgentKind;
baseUrl: string;
modelId: string;
+ /** 表单态鉴权方式;main IPC 用它强制 none 只访问 loopback。 */
+ authMethod?: 'apiKey' | 'oauth' | 'none';
/** 缺省按 agent 保持历史行为。 */
wireProtocol?: ProviderWireProtocol;
/** 非标准推理端点的精确相对路径。 */
@@ -87,9 +90,13 @@ function withoutCredentialHeaders(
/** 构造探测请求(纯函数,单测直断言)。header 组合与 provider-route 的 api-key-header 分支对齐。 */
export function buildProbeRequest(spec: ProviderProbeSpec): { url: string; init: RequestInit } {
+ const mustStripCredentialHeaders =
+ !!spec.apiKey || spec.authMethod === 'none' || spec.authMethod === 'oauth';
const headers: Record<string, string> = {
'content-type': 'application/json',
- ...(spec.apiKey ? withoutCredentialHeaders(spec.headers) : (spec.headers ?? {})),
+ ...(mustStripCredentialHeaders
+ ? withoutCredentialHeaders(spec.headers)
+ : (spec.headers ?? {})),
};
if (spec.agent === 'claude-code') {
// Anthropic Messages wire。anthropic-version 为兼容端点普遍要求的必带头。
@@ -218,6 +225,9 @@ export async function runProviderProbe(
// 默认吃系统代理:探测必须与真实会话同口径,否则代理用户会被误判成「连不通」。
fetchImpl: typeof fetch = outboundFetch,
): Promise<ProviderTestResult> {
+ if (spec.authMethod === 'none' && !isLoopbackProviderUrl(spec.baseUrl)) {
+ throw new TypeError('no-auth provider probes require a loopback URL');
+ }
const { url, init } = buildProbeRequest(spec);
const start = Date.now();
let res: Response;
@@ -305,6 +315,7 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Pro
if (provider.source !== 'user') throw new Error(`provider '${providerId}' is not a custom provider`);
const routing = provider.routing[agent];
if (!routing) throw new Error(`provider '${providerId}' has no runtime for '${agent}'`);
+ if (routing.disabled) throw new Error(`provider '${providerId}' runtime '${agent}' is disabled`);
const model = (provider.models[agent] ?? [])[0];
if (!model) throw new Error(`provider '${providerId}' has no models for '${agent}'`);
// OAuth 形态:探测凭证用 Runner 持有的 access_token(与 oauth-token 路由同源),未登录时
diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
index 22673b0554..60e401781d 100644
--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
@@ -11,7 +11,7 @@
* - fetch 可注入(单测不联网)。
*/
-import type { AgentKind } from '@cindy/model-providers';
+import { isLoopbackProviderUrl, type AgentKind } from '@cindy/model-providers';
import {
classifyProviderError,
@@ -29,6 +29,8 @@ const MAX_ERROR_BODY_BYTES = 16 * 1024;
export interface ProviderModelsFetchSpec {
agent: AgentKind;
baseUrl: string;
+ /** 表单态鉴权方式;main IPC 用它强制 none 只访问 loopback。 */
+ authMethod?: 'apiKey' | 'oauth' | 'none';
/** 显式列模型端点(预设 / 配置的 modelsUrl);缺省由 baseUrl 推导 `…/v1/models`。 */
modelsUrl?: string | null;
/** 用户 API key;缺省 = 不注入鉴权头(端点可能靠自定义 headers 鉴权)。 */
@@ -72,7 +74,9 @@ function withoutCredentialHeaders(
/** 构造列模型请求(纯函数,单测直断言)。鉴权头组合与 buildProbeRequest 同口径。 */
export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: string; init: RequestInit } {
- const headers: Record<string, string> = spec.apiKey
+ const mustStripCredentialHeaders =
+ !!spec.apiKey || spec.authMethod === 'none' || spec.authMethod === 'oauth';
+ const headers: Record<string, string> = mustStripCredentialHeaders
? withoutCredentialHeaders(spec.headers)
: { ...(spec.headers ?? {}) };
if (spec.agent === 'claude-code') {
@@ -110,6 +114,19 @@ export async function fetchProviderModels(
spec: ProviderModelsFetchSpec,
fetchImpl: typeof fetch = outboundFetch,
): Promise<ProviderModelsFetchResult> {
+ if (
+ spec.authMethod === 'none'
+ && (
+ !isLoopbackProviderUrl(spec.baseUrl)
+ || (!!spec.modelsUrl?.trim() && !isLoopbackProviderUrl(spec.modelsUrl.trim()))
+ )
+ ) {
+ return {
+ ok: false,
+ code: 'UNKNOWN',
+ detail: 'no-auth provider model discovery requires loopback URLs',
+ };
+ }
const { url, init } = buildModelsFetchRequest(spec);
let res: Response;
try {
diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.ts
index 837d1ead34..940976c1e7 100644
--- a/apps/desktop/src/main/maker-host/provider-route.ts
+++ b/apps/desktop/src/main/maker-host/provider-route.ts
@@ -38,12 +38,39 @@ import { getSessionProvider } from './session-provider-store.js';
*/
type CustomProviderKeyReader = (providerId: string, agent: AgentKind) => string | null;
let customProviderKeyReader: CustomProviderKeyReader = () => null;
+const providerRouteMutationCounts = new Map<string, number>();
/** host 启动期接通真实 safeStorage 读取(按 `provider_key_<id>_<agent>`,per-runtime 独立密钥)。 */
export function setCustomProviderKeyReader(reader: CustomProviderKeyReader): void {
customProviderKeyReader = reader;
}
+/**
+ * 暂停某个 provider 的新路由解析,直到配置、secret 与 active catalog 一起切换完成。
+ *
+ * 配置和 safeStorage 无法组成同一个物理事务;mutation 期间直接拒绝新请求,避免把旧
+ * endpoint 与新 key(或新 endpoint 与旧 key)拼成一次上游请求。计数使排队的多窗口
+ * mutation 之间不会短暂恢复路由。
+ */
+export function beginProviderRouteMutation(providerId: string): () => void {
+ providerRouteMutationCounts.set(
+ providerId,
+ (providerRouteMutationCounts.get(providerId) ?? 0) + 1,
+ );
+ let finished = false;
+ return () => {
+ if (finished) return;
+ finished = true;
+ const remaining = (providerRouteMutationCounts.get(providerId) ?? 1) - 1;
+ if (remaining <= 0) providerRouteMutationCounts.delete(providerId);
+ else providerRouteMutationCounts.set(providerId, remaining);
+ };
+}
+
+export function isProviderRouteMutationInProgress(providerId: string): boolean {
+ return providerRouteMutationCounts.has(providerId);
+}
+
/**
* 通用 OAuth 供应商的 access_token 读取器(注入,同 key reader 模式)。
*
@@ -61,6 +88,7 @@ export function setOAuthTokenReader(reader: OAuthTokenReader): void {
/** 查询自定义供应商该 runtime 是否已有可注入的 API key(不暴露明文)。 */
export function hasCustomProviderKey(providerId: string, agent: AgentKind): boolean {
+ if (isProviderRouteMutationInProgress(providerId)) return false;
return Boolean(customProviderKeyReader(providerId, agent));
}
@@ -86,6 +114,54 @@ const CODEX_ACCOUNT_HEADERS = ['chatgpt-account-id', 'openai-beta', 'originator'
const CLIENT_AUTH_HEADERS = ['authorization', 'x-api-key'];
/** 缺少自定义供应商 key 时覆盖 CLI 凭证的哑值:目标上游应 401,但绝不收到订阅 token。 */
const MISSING_CUSTOM_PROVIDER_API_KEY = 'cindy-missing-custom-provider-api-key';
+const DISABLED_PROVIDER_ROUTE_ERROR = 'provider_route_disabled';
+const UPDATING_PROVIDER_ROUTE_ERROR = 'provider_route_updating';
+
+/**
+ * 已迁移但无法安全执行的历史路由必须由 proxy 原地拒绝,不能返回 null:
+ * null 在两个 proxy host 里表示“未命中”,会继续走默认网关/订阅上游。
+ */
+function disabledProviderRouteDecision(providerId?: string): RoutingDecision {
+ return {
+ localHandler: async ({ res }) => {
+ const providerLabel = providerId ? `Provider '${providerId}'` : 'The selected provider';
+ const payload = JSON.stringify({
+ type: 'error',
+ error: {
+ type: DISABLED_PROVIDER_ROUTE_ERROR,
+ code: DISABLED_PROVIDER_ROUTE_ERROR,
+ message: `${providerLabel} is disabled; update its endpoint or authentication settings before retrying.`,
+ },
+ });
+ res.writeHead(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ res.end(payload);
+ },
+ };
+}
+
+function updatingProviderRouteDecision(providerId: string): RoutingDecision {
+ return {
+ localHandler: async ({ res }) => {
+ const payload = JSON.stringify({
+ type: 'error',
+ error: {
+ type: UPDATING_PROVIDER_ROUTE_ERROR,
+ code: UPDATING_PROVIDER_ROUTE_ERROR,
+ message: `Provider '${providerId}' is updating; retry after the configuration change completes.`,
+ },
+ });
+ res.writeHead(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ res.end(payload);
+ },
+ };
+}
function withoutClientAuthHeaders(
headers: Record<string, string> | undefined,
@@ -130,6 +206,7 @@ export function buildRouteDecision(
// routing 只会命中其一,共用一个参数无歧义。
oauthToken?: string | null,
): RoutingDecision | null {
+ if (routing.disabled) return disabledProviderRouteDecision();
switch (routing.authStrategy) {
case 'none': {
// 本机 / 自托管无鉴权代理:仍固定路由到所选 upstream,但显式剥掉子进程自带的
@@ -280,6 +357,7 @@ export function gatewayDefaultRouteDecision(
* wireModel 为空 = 控制面请求(如 codex `GET /models`,无 body.model),不受范围限制。
*/
function routingServesWireModel(routing: RoutingDescriptor, wireModel: string | undefined): boolean {
+ if (routing.disabled) return false;
if (!routing.modelPrefixes?.length) return true;
if (!wireModel) return true;
return routing.modelPrefixes.some((prefix) => wireModel.startsWith(prefix));
@@ -327,6 +405,7 @@ export function getSessionRoutingDescriptor(
): RoutingDescriptor | null {
const providerId = getSessionProvider(sessionId);
if (!providerId) return null;
+ if (isProviderRouteMutationInProgress(providerId)) return null;
const routing = getActiveCatalog().providers.find((provider) => provider.id === providerId)?.routing[agent];
if (!routing || !routingServesWireModel(routing, wireModel)) return null;
return routing;
@@ -351,6 +430,7 @@ export async function resolveSessionRoute(
): Promise<ResolvedSessionRoute | null> {
const providerId = getSessionProvider(sessionId);
if (!providerId) return null;
+ if (isProviderRouteMutationInProgress(providerId)) return null;
const provider = getActiveCatalog().providers.find((candidate) => candidate.id === providerId);
const routing = provider?.routing[agent];
if (!provider || !routing || !routingServesWireModel(routing, wireModel)) return null;
@@ -426,10 +506,14 @@ export function resolveSessionRouteDecision(
): RoutingDecision | null | Promise<RoutingDecision | null> {
const providerId = getSessionProvider(sessionId);
if (!providerId) return null;
+ if (isProviderRouteMutationInProgress(providerId)) {
+ return updatingProviderRouteDecision(providerId);
+ }
if (providerId === 'xd' && !getAppCapabilities().canUseCindyGateway) return null;
const provider = getActiveCatalog().providers.find((p) => p.id === providerId);
const routing = provider?.routing[agent];
if (!routing) return null;
+ if (routing.disabled) return disabledProviderRouteDecision(providerId);
if (!routingServesWireModel(routing, wireModel)) return null;
// 自定义供应商:resolve 时按 provider_key_<id>_<agent> 读出该 runtime 的 API key 注入鉴权头(不在 catalog)。
const apiKey = provider?.source === 'user' ? customProviderKeyReader(providerId, agent) : null;
@@ -454,9 +538,10 @@ export function resolveSessionRouteDecision(
function providersForModel(modelId: string, agent: AgentKind) {
return getActiveCatalog().providers.filter((provider) =>
+ !isProviderRouteMutationInProgress(provider.id) &&
(provider.id !== 'xd' || getAppCapabilities().canUseCindyGateway) &&
provider.agents.includes(agent) &&
- Boolean(provider.routing[agent]) &&
+ Boolean(provider.routing[agent] && !provider.routing[agent]?.disabled) &&
(provider.models[agent] ?? []).some((model) => model.id === modelId),
);
}
@@ -509,7 +594,11 @@ export function resolveProviderOAuthControlRouteDecision(
): RoutingDecision | null | Promise<RoutingDecision | null> {
const providers = getActiveCatalog().providers.filter((provider) => {
const routing = provider.routing[agent];
- return provider.agents.includes(agent) && routing?.authStrategy === 'provider-oauth-header';
+ return (
+ !isProviderRouteMutationInProgress(provider.id)
+ && provider.agents.includes(agent)
+ && routing?.authStrategy === 'provider-oauth-header'
+ );
});
if (providers.length !== 1) return null;
const provider = providers[0];
diff --git a/apps/desktop/src/main/maker-host/provider-service.ts b/apps/desktop/src/main/maker-host/provider-service.ts
index 01a2352b0c..f20214ec45 100644
--- a/apps/desktop/src/main/maker-host/provider-service.ts
+++ b/apps/desktop/src/main/maker-host/provider-service.ts
@@ -105,7 +105,10 @@ export function createProviderService(deps: ProviderServiceDeps): ProviderServic
// 无鉴权供应商无需任何登录或密钥:只要目录声明有效,就可立即参与模型选择。
// 该规则与 source 无关,覆盖远端目录下发的 built-in/self-hosted 条目。
if (p.auth.method === 'none') {
- connected[p.id] = true;
+ connected[p.id] = p.agents.some((agent) => {
+ const routing = p.routing[agent];
+ return routing !== undefined && routing.disabled !== true;
+ });
}
// 通用 OAuth 供应商(带 auth.oauth 描述符,内置目录下发或用户自建皆同):
// 连接态 = 本机是否有凭证 blob(登录过才算连接)。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
index 9b8066ef26..c93b3e5d73 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
@@ -1,6 +1,6 @@
-import type { Maker } from '@cindy/maker-core';
+import type { AuthState, Maker } from '@cindy/maker-core';
import { describe, expect, it, vi } from 'vitest';
-import { registerMakerAuthHandlers } from '../authHandlers';
+import { parseCodexDeviceCodeProgress, registerMakerAuthHandlers } from '../authHandlers';
import { MAKER_INVOKE, MAKER_PUSH } from '../channels';
import { registerMakerStatusHandlers } from '../statusHandlers';
import { registerMakerUsageHandlers } from '../usageHandlers';
@@ -17,12 +17,7 @@ describe('maker auth IPC handlers', () => {
const harness = new IpcHarness();
const getAgentAuthState = vi.fn().mockResolvedValue({ authenticated: true });
- registerMakerAuthHandlers(
- harness,
- createMakerStub({ getAgentAuthState }),
- vi.fn(),
- () => null,
- );
+ registerMakerAuthHandlers(harness, createMakerStub({ getAgentAuthState }), vi.fn(), () => null);
await expect(harness.invoke(MAKER_INVOKE.AUTH_GET_STATE, 'codex')).resolves.toEqual({
authenticated: true,
@@ -37,16 +32,18 @@ describe('maker auth IPC handlers', () => {
const refreshAgentLocalModels = vi.fn().mockResolvedValue(true);
const triggerAgentLogin = vi
.fn()
- .mockImplementation(async (_agentKind, options: { onProgress: (msg: string) => void }) => {
- options.onProgress('stdout:https://example.test/oauth');
- options.onProgress('stderr:waiting');
- options.onProgress('done');
- return {
- authenticated: true,
- authSource: 'oauth',
- identity: { email: '[email protected]' },
- };
- });
+ .mockImplementation(
+ async (_agentKind, options: { mode?: string; onProgress: (msg: string) => void }) => {
+ options.onProgress('stdout:https://example.test/oauth');
+ options.onProgress('stderr:waiting');
+ options.onProgress('done');
+ return {
+ authenticated: true,
+ authSource: 'oauth',
+ identity: { email: '[email protected]' },
+ };
+ },
+ );
registerMakerAuthHandlers(
harness,
@@ -67,16 +64,19 @@ describe('maker auth IPC handlers', () => {
expect(broadcast).toHaveBeenNthCalledWith(1, MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
agentKind: 'codex',
phase: 'login-pending',
+ mode: 'browser',
detail: 'https://example.test/oauth',
});
expect(broadcast).toHaveBeenNthCalledWith(2, MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
agentKind: 'codex',
phase: 'login-pending',
+ mode: 'browser',
detail: 'waiting',
});
expect(broadcast).toHaveBeenNthCalledWith(3, MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
agentKind: 'codex',
phase: 'done',
+ mode: 'browser',
});
expect(broadcast).toHaveBeenNthCalledWith(4, MAKER_PUSH.AUTH_STATE_CHANGED, {
agentKind: 'codex',
@@ -84,12 +84,173 @@ describe('maker auth IPC handlers', () => {
authSource: 'oauth',
identity: { email: '[email protected]' },
});
+ expect(triggerAgentLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ mode: 'browser' }),
+ );
+ });
+
+ it('extracts a split ANSI-colored Codex device code and emits a structured progress event', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const triggerAgentLogin = vi
+ .fn()
+ .mockImplementation(
+ async (_agentKind, options: { mode?: string; onProgress: (msg: string) => void }) => {
+ options.onProgress('stdout:\u001b[1mhttps://auth.openai.com/codex/device\u001b[0m');
+ options.onProgress('stderr:Enter code \u001b[32mRUH2-7E2VH\u001b[0m');
+ return { authenticated: false, errorReason: 'login_cancelled' };
+ },
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin }),
+ broadcast,
+ () => null,
+ );
+
+ await harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ mode: 'device-code',
+ });
+
+ expect(triggerAgentLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ mode: 'device-code' }),
+ );
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
+ agentKind: 'codex',
+ phase: 'device-code',
+ mode: 'device-code',
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'RUH2-7E2VH',
+ });
+ });
+
+ it('replays the retained device code when another BrowserWindow joins the login', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ let emitProgress!: (msg: string) => void;
+ let finishLogin!: (state: AuthState) => void;
+ const triggerAgentLogin = vi.fn(
+ (_agentKind, options: { onProgress: (msg: string) => void }) =>
+ new Promise<AuthState>((resolve) => {
+ emitProgress = options.onProgress;
+ finishLogin = resolve;
+ }),
+ );
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin }),
+ broadcast,
+ () => null,
+ );
+
+ const first = harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ mode: 'device-code',
+ ownerId: 'window-101-device-code',
+ });
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ emitProgress('stdout:https://auth.openai.com/codex/device');
+ emitProgress('stderr:Enter code ABCD-EFGH');
+ await vi.waitFor(() =>
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
+ agentKind: 'codex',
+ phase: 'device-code',
+ mode: 'device-code',
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'ABCD-EFGH',
+ }),
+ );
+
+ broadcast.mockClear();
+ const second = harness.invokeFrom(202, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ mode: 'device-code',
+ ownerId: 'window-202-device-code',
+ });
+ await vi.waitFor(() =>
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
+ agentKind: 'codex',
+ phase: 'device-code',
+ mode: 'device-code',
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'ABCD-EFGH',
+ }),
+ );
+ expect(triggerAgentLogin).toHaveBeenCalledOnce();
+
+ finishLogin({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(first).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ await expect(second).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ });
+
+ it('reassembles URL and code tokens split across arbitrary stdout chunks', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const triggerAgentLogin = vi
+ .fn()
+ .mockImplementation(
+ async (_agentKind, options: { mode?: string; onProgress: (msg: string) => void }) => {
+ options.onProgress('stdout:Open https://auth.openai.com/cod');
+ options.onProgress('stdout:ex/device\nEnter code AB');
+ options.onProgress('stdout:CD-EF');
+ options.onProgress('stdout:GH\n');
+ return { authenticated: false, errorReason: 'login_cancelled' };
+ },
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin }),
+ broadcast,
+ () => null,
+ );
+
+ await harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ mode: 'device-code',
+ });
+
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
+ agentKind: 'codex',
+ phase: 'device-code',
+ mode: 'device-code',
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'ABCD-EFGH',
+ });
+ });
+
+ it('rejects unsupported login modes and malformed owner options before invoking Maker', async () => {
+ const harness = new IpcHarness();
+ const triggerAgentLogin = vi.fn();
+ registerMakerAuthHandlers(harness, createMakerStub({ triggerAgentLogin }), vi.fn(), () => null);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', { mode: 'password' }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'claude-code', {
+ mode: 'device-code',
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'contains whitespace',
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ harness.invokeFrom(101, MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex', {
+ releaseOwner: true,
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(triggerAgentLogin).not.toHaveBeenCalled();
});
it('keeps login successful and requests disk fallback when live model refresh fails', async () => {
const harness = new IpcHarness();
const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
- const triggerAgentLogin = vi.fn().mockResolvedValue({ authenticated: true, authSource: 'oauth' });
+ const triggerAgentLogin = vi
+ .fn()
+ .mockResolvedValue({ authenticated: true, authSource: 'oauth' });
const refreshAgentLocalModels = vi.fn().mockRejectedValue(new Error('model/list unavailable'));
registerMakerAuthHandlers(
@@ -110,11 +271,16 @@ describe('maker auth IPC handlers', () => {
const harness = new IpcHarness();
const broadcast = vi.fn();
let resolveRefresh!: (value: boolean) => void;
- const refreshAgentLocalModels = vi.fn(() => new Promise<boolean>((resolve) => {
- resolveRefresh = resolve;
- }));
+ const refreshAgentLocalModels = vi.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ );
const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
- const triggerAgentLogin = vi.fn().mockResolvedValue({ authenticated: true, authSource: 'oauth' });
+ const triggerAgentLogin = vi
+ .fn()
+ .mockResolvedValue({ authenticated: true, authSource: 'oauth' });
const logoutAgent = vi.fn().mockResolvedValue(undefined);
registerMakerAuthHandlers(
@@ -143,6 +309,440 @@ describe('maker auth IPC handlers', () => {
});
});
+ it('preserves cancellation while invalidating post-login refresh work', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const logoutAgent = vi.fn().mockResolvedValue(undefined);
+ let finishRefresh!: (value: boolean) => void;
+ const refreshAgentLocalModels = vi.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ finishRefresh = resolve;
+ }),
+ );
+ const triggerAgentLogin = vi.fn().mockResolvedValue({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({
+ triggerAgentLogin,
+ refreshAgentLocalModels,
+ cancelAgentLogin,
+ logoutAgent,
+ }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const login = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ await vi.waitFor(() => expect(refreshAgentLocalModels).toHaveBeenCalledOnce());
+ const cancel = harness.invoke(MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex');
+ finishRefresh(true);
+
+ await expect(login).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(cancel).resolves.toBeUndefined();
+ expect(cancelAgentLogin).toHaveBeenCalledWith('codex');
+ expect(logoutAgent).toHaveBeenCalledWith('codex');
+ expect(onCodexAuthChange).toHaveBeenCalledOnce();
+ expect(onCodexAuthChange).toHaveBeenCalledWith(false, false, expect.any(Function));
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+
+ it('re-broadcasts authoritative auth and rejects cancel when durable cleanup fails', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const logoutAgent = vi.fn().mockRejectedValue(new Error('disconnect marker write failed'));
+ const getAgentAuthState = vi.fn().mockResolvedValue({
+ authenticated: true,
+ authSource: 'oauth',
+ identity: '[email protected]',
+ });
+ let finishRefresh!: (value: boolean) => void;
+ const refreshAgentLocalModels = vi.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ finishRefresh = resolve;
+ }),
+ );
+ const triggerAgentLogin = vi.fn().mockResolvedValue({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({
+ triggerAgentLogin,
+ refreshAgentLocalModels,
+ cancelAgentLogin,
+ logoutAgent,
+ getAgentAuthState,
+ }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const login = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ await vi.waitFor(() => expect(refreshAgentLocalModels).toHaveBeenCalledOnce());
+ const cancel = harness.invoke(MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex');
+ finishRefresh(true);
+
+ await expect(login).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(cancel).rejects.toMatchObject({ code: 'INTERNAL' });
+ expect(getAgentAuthState).toHaveBeenCalledWith('codex');
+ expect(onCodexAuthChange).not.toHaveBeenCalled();
+ expect(broadcast).toHaveBeenCalledTimes(1);
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: true,
+ authSource: 'oauth',
+ identity: '[email protected]',
+ });
+ });
+
+ it('reuses adapter-stage durable cancellation, then performs cache cleanup and one push', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const logoutAgent = vi.fn().mockResolvedValue(undefined);
+ const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
+ let finishLogin!: (state: { authenticated: false; errorReason: string }) => void;
+ const triggerAgentLogin = vi.fn(
+ () =>
+ new Promise<{ authenticated: false; errorReason: string }>((resolve) => {
+ finishLogin = resolve;
+ }),
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin, cancelAgentLogin, logoutAgent }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const login = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ const cancel = harness.invoke(MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex');
+ finishLogin({ authenticated: false, errorReason: 'login_cancelled' });
+
+ await expect(login).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(cancel).resolves.toBeUndefined();
+ expect(logoutAgent).not.toHaveBeenCalled();
+ expect(onCodexAuthChange).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledTimes(1);
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+
+ it('treats Cancel with no in-flight login as a state-preserving no-op', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const logoutAgent = vi.fn();
+ const onCodexAuthChange = vi.fn();
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ cancelAgentLogin, logoutAgent }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ await expect(harness.invoke(MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex')).resolves.toBeUndefined();
+ expect(cancelAgentLogin).not.toHaveBeenCalled();
+ expect(logoutAgent).not.toHaveBeenCalled();
+ expect(onCodexAuthChange).not.toHaveBeenCalled();
+ expect(broadcast).not.toHaveBeenCalled();
+ });
+
+ it('keeps a shared login alive until the last BrowserWindow owner releases it', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
+ let finishLogin!: (state: AuthState) => void;
+ const sharedLogin = new Promise<AuthState>((resolve) => {
+ finishLogin = resolve;
+ });
+ const triggerAgentLogin = vi.fn(() => sharedLogin);
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin, cancelAgentLogin }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const first = harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-101-operation-1',
+ });
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ const second = harness.invokeFrom(202, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-202-operation-1',
+ });
+ await Promise.resolve();
+ expect(triggerAgentLogin).toHaveBeenCalledOnce();
+
+ await expect(
+ harness.invokeFrom(101, MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex', {
+ releaseOwner: true,
+ ownerId: 'window-101-operation-1',
+ }),
+ ).resolves.toBeUndefined();
+ expect(cancelAgentLogin).not.toHaveBeenCalled();
+ await expect(
+ harness.invokeFrom(101, MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex', {
+ releaseOwner: true,
+ ownerId: 'window-101-operation-1',
+ }),
+ ).resolves.toBeUndefined();
+ expect(cancelAgentLogin).not.toHaveBeenCalled();
+
+ const lastRelease = harness.invokeFrom(202, MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex', {
+ releaseOwner: true,
+ ownerId: 'window-202-operation-1',
+ });
+ await vi.waitFor(() => expect(cancelAgentLogin).toHaveBeenCalledOnce());
+ expect(cancelAgentLogin).toHaveBeenCalledWith('codex');
+
+ finishLogin({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(first).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(second).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(lastRelease).resolves.toBeUndefined();
+ expect(onCodexAuthChange).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+
+ it('coalesces same-mode BrowserWindow callers through one successful main finalization', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ let finishLogin!: (state: AuthState) => void;
+ const triggerAgentLogin = vi.fn(
+ () =>
+ new Promise<AuthState>((resolve) => {
+ finishLogin = resolve;
+ }),
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin }),
+ broadcast,
+ () => null,
+ );
+
+ const first = harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-101-success',
+ });
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ const second = harness.invokeFrom(202, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-202-success',
+ });
+ finishLogin({ authenticated: true, authSource: 'api-key' });
+
+ await expect(first).resolves.toEqual({ authenticated: true, authSource: 'api-key' });
+ await expect(second).resolves.toEqual({ authenticated: true, authSource: 'api-key' });
+ expect(triggerAgentLogin).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: true,
+ authSource: 'api-key',
+ });
+ });
+
+ it('releases login ownership when BrowserWindows are destroyed', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
+ let finishLogin!: (state: AuthState) => void;
+ const triggerAgentLogin = vi.fn(
+ () =>
+ new Promise<AuthState>((resolve) => {
+ finishLogin = resolve;
+ }),
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin, cancelAgentLogin }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const first = harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-101-destroyed',
+ });
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ const second = harness.invokeFrom(202, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-202-destroyed',
+ });
+
+ harness.destroySender(101);
+ expect(cancelAgentLogin).not.toHaveBeenCalled();
+ harness.destroySender(202);
+ expect(cancelAgentLogin).toHaveBeenCalledOnce();
+
+ finishLogin({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(first).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(second).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await vi.waitFor(() => expect(onCodexAuthChange).toHaveBeenCalledOnce());
+ expect(broadcast).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+
+ it('ignores a stale owner release from the same BrowserWindow', async () => {
+ const harness = new IpcHarness();
+ const cancelAgentLogin = vi.fn();
+ let finishLogin!: (state: AuthState) => void;
+ const triggerAgentLogin = vi.fn(
+ () =>
+ new Promise<AuthState>((resolve) => {
+ finishLogin = resolve;
+ }),
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin, cancelAgentLogin }),
+ vi.fn(),
+ () => null,
+ vi.fn().mockResolvedValue(undefined),
+ );
+
+ const login = harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-101-new-operation',
+ });
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ await expect(
+ harness.invokeFrom(101, MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex', {
+ releaseOwner: true,
+ ownerId: 'window-101-old-operation',
+ }),
+ ).resolves.toBeUndefined();
+ expect(cancelAgentLogin).not.toHaveBeenCalled();
+
+ const release = harness.invokeFrom(101, MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex', {
+ releaseOwner: true,
+ ownerId: 'window-101-new-operation',
+ });
+ expect(cancelAgentLogin).toHaveBeenCalledOnce();
+ finishLogin({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(login).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ await expect(release).resolves.toBeUndefined();
+ });
+
+ it('does not let an older Cancel cleanup disconnect a newer login', async () => {
+ const harness = new IpcHarness();
+ const broadcast = vi.fn();
+ const cancelAgentLogin = vi.fn();
+ const logoutAgent = vi.fn().mockResolvedValue(undefined);
+ const onCodexAuthChange = vi.fn().mockResolvedValue(undefined);
+ let finishFirst!: (state: AuthState) => void;
+ let finishSecond!: (state: AuthState) => void;
+ const triggerAgentLogin = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<AuthState>((resolve) => {
+ finishFirst = resolve;
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise<AuthState>((resolve) => {
+ finishSecond = resolve;
+ }),
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin, cancelAgentLogin, logoutAgent }),
+ broadcast,
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const first = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledTimes(1));
+ const cancel = harness.invoke(MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex');
+ const second = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledTimes(2));
+
+ finishFirst({ authenticated: false, errorReason: 'login_cancelled' });
+ finishSecond({ authenticated: true, authSource: 'api-key' });
+
+ await expect(first).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(cancel).resolves.toBeUndefined();
+ await expect(second).resolves.toEqual({
+ authenticated: true,
+ authSource: 'api-key',
+ });
+ expect(logoutAgent).not.toHaveBeenCalled();
+ expect(onCodexAuthChange).not.toHaveBeenCalled();
+ expect(broadcast).toHaveBeenCalledTimes(1);
+ expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: 'codex',
+ authenticated: true,
+ authSource: 'api-key',
+ });
+ });
+
it('does not refresh Codex models when login fails', async () => {
const harness = new IpcHarness();
const broadcast = vi.fn();
@@ -238,6 +838,187 @@ describe('maker auth IPC handlers', () => {
});
});
+ it('finishes Codex logout cleanup before starting a login queued during logout', async () => {
+ const harness = new IpcHarness();
+ let finishLogout!: () => void;
+ let finishFinalization!: () => void;
+ const logoutAgent = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ }),
+ );
+ const onCodexAuthChange = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishFinalization = resolve;
+ }),
+ );
+ const triggerAgentLogin = vi.fn().mockResolvedValue({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ logoutAgent, triggerAgentLogin }),
+ vi.fn(),
+ () => null,
+ onCodexAuthChange,
+ );
+
+ const logout = harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex');
+ await vi.waitFor(() => expect(logoutAgent).toHaveBeenCalledOnce());
+ const login = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ expect(triggerAgentLogin).not.toHaveBeenCalled();
+
+ finishLogout();
+ await vi.waitFor(() => expect(onCodexAuthChange).toHaveBeenCalledOnce());
+ expect(triggerAgentLogin).not.toHaveBeenCalled();
+
+ finishFinalization();
+ await expect(logout).resolves.toBeUndefined();
+ await expect(login).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ expect(triggerAgentLogin).toHaveBeenCalledOnce();
+ });
+
+ it('does not coalesce a new login into the operation being logged out', async () => {
+ const harness = new IpcHarness();
+ let finishFirstLogin!: (state: AuthState) => void;
+ let finishLogout!: () => void;
+ const triggerAgentLogin = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<AuthState>((resolve) => {
+ finishFirstLogin = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({ authenticated: true, authSource: 'api-key' });
+ const logoutAgent = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ }),
+ );
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ triggerAgentLogin, logoutAgent }),
+ vi.fn(),
+ () => null,
+ vi.fn().mockResolvedValue(undefined),
+ );
+
+ const first = harness.invokeFrom(101, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-101-before-logout',
+ });
+ await vi.waitFor(() => expect(triggerAgentLogin).toHaveBeenCalledOnce());
+ const logout = harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex');
+ await vi.waitFor(() => expect(logoutAgent).toHaveBeenCalledOnce());
+ const second = harness.invokeFrom(202, MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex', {
+ ownerId: 'window-202-after-logout',
+ });
+ expect(triggerAgentLogin).toHaveBeenCalledOnce();
+
+ finishFirstLogin({ authenticated: false, errorReason: 'login_cancelled' });
+ finishLogout();
+
+ await expect(first).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'auth_mutation_superseded',
+ });
+ await expect(logout).resolves.toBeUndefined();
+ await expect(second).resolves.toEqual({ authenticated: true, authSource: 'api-key' });
+ expect(triggerAgentLogin).toHaveBeenCalledTimes(2);
+ });
+
+ it('cancels a login request while it is queued behind logout finalization', async () => {
+ const harness = new IpcHarness();
+ let finishLogout!: () => void;
+ const logoutAgent = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ }),
+ )
+ .mockResolvedValue(undefined);
+ const triggerAgentLogin = vi.fn().mockResolvedValue({
+ authenticated: true,
+ authSource: 'oauth',
+ });
+ const cancelAgentLogin = vi.fn();
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ logoutAgent, triggerAgentLogin, cancelAgentLogin }),
+ vi.fn(),
+ () => null,
+ vi.fn().mockResolvedValue(undefined),
+ );
+
+ const logout = harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex');
+ await vi.waitFor(() => expect(logoutAgent).toHaveBeenCalledOnce());
+ const login = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ expect(triggerAgentLogin).not.toHaveBeenCalled();
+
+ const cancel = harness.invoke(MAKER_INVOKE.AUTH_CANCEL_LOGIN, 'codex');
+ finishLogout();
+
+ await expect(logout).resolves.toBeUndefined();
+ await expect(login).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await expect(cancel).resolves.toBeUndefined();
+ expect(cancelAgentLogin).toHaveBeenCalledWith('codex');
+ expect(logoutAgent).toHaveBeenCalledOnce();
+ expect(triggerAgentLogin).not.toHaveBeenCalled();
+ });
+
+ it('waits for a later logout that supersedes the finalization already being awaited', async () => {
+ const harness = new IpcHarness();
+ const logoutResolvers: Array<() => void> = [];
+ const logoutAgent = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ logoutResolvers.push(resolve);
+ }),
+ );
+ const triggerAgentLogin = vi.fn().mockResolvedValue({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+
+ registerMakerAuthHandlers(
+ harness,
+ createMakerStub({ logoutAgent, triggerAgentLogin }),
+ vi.fn(),
+ () => null,
+ vi.fn().mockResolvedValue(undefined),
+ );
+
+ const firstLogout = harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex');
+ await vi.waitFor(() => expect(logoutAgent).toHaveBeenCalledTimes(1));
+ const login = harness.invoke(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, 'codex');
+ const secondLogout = harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex');
+ await vi.waitFor(() => expect(logoutAgent).toHaveBeenCalledTimes(2));
+
+ logoutResolvers[0]();
+ await Promise.resolve();
+ expect(triggerAgentLogin).not.toHaveBeenCalled();
+
+ logoutResolvers[1]();
+ await expect(Promise.all([firstLogout, secondLogout])).resolves.toEqual([undefined, undefined]);
+ await expect(login).resolves.toMatchObject({ errorReason: 'login_cancelled' });
+ expect(triggerAgentLogin).toHaveBeenCalledOnce();
+ });
+
it('encodes logout persistence failures as an IPC INTERNAL error without broadcasting success', async () => {
const harness = new IpcHarness();
const broadcast = vi.fn();
@@ -303,6 +1084,60 @@ describe('maker auth IPC handlers', () => {
});
});
+describe('parseCodexDeviceCodeProgress', () => {
+ it('returns null until both the official verification URL and code are present', () => {
+ expect(parseCodexDeviceCodeProgress('https://auth.openai.com/codex/device')).toBeNull();
+ expect(
+ parseCodexDeviceCodeProgress(
+ '\u001b[1mhttps://auth.openai.com/codex/device\u001b[0m\ncode: RUH2-7E2VH',
+ ),
+ ).toEqual({
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'RUH2-7E2VH',
+ });
+ });
+
+ it('does not expose a verification URL from an untrusted host', () => {
+ expect(
+ parseCodexDeviceCodeProgress('https://auth.openai.com.evil.test/device\nRUH2-7E2VH'),
+ ).toBeNull();
+ });
+
+ it('finds the official device page after unrelated URLs in cumulative CLI output', () => {
+ expect(
+ parseCodexDeviceCodeProgress(
+ 'Learn more at https://developers.openai.com/codex/auth\n' +
+ 'Open https://auth.openai.com/codex/device and enter ABCD-EFGH',
+ ),
+ ).toEqual({
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'ABCD-EFGH',
+ });
+ });
+
+ it.each([
+ ['period', 'Open https://auth.openai.com/codex/device. Code ABCD-EFGH'],
+ ['comma', 'Open https://auth.openai.com/codex/device, then enter ABCD-EFGH'],
+ ['closing parenthesis', '(https://auth.openai.com/codex/device) Code ABCD-EFGH'],
+ ])('strips trailing prose punctuation from the verification URL (%s)', (_label, text) => {
+ expect(parseCodexDeviceCodeProgress(text)).toEqual({
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'ABCD-EFGH',
+ });
+ });
+
+ it('keeps balanced parentheses that are part of the verification URL', () => {
+ expect(
+ parseCodexDeviceCodeProgress(
+ 'Open https://auth.openai.com/codex/device(test) and enter ABCD-EFGH',
+ ),
+ ).toEqual({
+ verificationUrl: 'https://auth.openai.com/codex/device(test)',
+ userCode: 'ABCD-EFGH',
+ });
+ });
+});
+
describe('maker status IPC handlers', () => {
it('delegates agent status lookup to Maker', async () => {
const harness = new IpcHarness();
@@ -442,19 +1277,22 @@ describe('maker usage IPC handlers', () => {
rateLimits: snapshot,
});
- registerMakerUsageHandlers(harness, makeUsageDeps({
- readCodexRateLimits,
- consumeCodexRateLimitReset,
- }));
+ registerMakerUsageHandlers(
+ harness,
+ makeUsageDeps({
+ readCodexRateLimits,
+ consumeCodexRateLimitReset,
+ }),
+ );
await expect(harness.invoke(MAKER_INVOKE.USAGE_CODEX_RATE_LIMITS)).resolves.toEqual(snapshot);
- await expect(harness.invoke(
- MAKER_INVOKE.USAGE_CODEX_RATE_LIMIT_RESET,
- '018f4ec7-c6d8-7f10-8d43-9f8791d33000',
- )).resolves.toEqual({ outcome: 'reset', rateLimits: snapshot });
- expect(consumeCodexRateLimitReset).toHaveBeenCalledWith(
- '018f4ec7-c6d8-7f10-8d43-9f8791d33000',
- );
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.USAGE_CODEX_RATE_LIMIT_RESET,
+ '018f4ec7-c6d8-7f10-8d43-9f8791d33000',
+ ),
+ ).resolves.toEqual({ outcome: 'reset', rateLimits: snapshot });
+ expect(consumeCodexRateLimitReset).toHaveBeenCalledWith('018f4ec7-c6d8-7f10-8d43-9f8791d33000');
});
it('rejects arbitrary reset input before it reaches the mutation dependency', async () => {
@@ -462,24 +1300,25 @@ describe('maker usage IPC handlers', () => {
const consumeCodexRateLimitReset = vi.fn();
registerMakerUsageHandlers(harness, makeUsageDeps({ consumeCodexRateLimitReset }));
- await expect(harness.invoke(
- MAKER_INVOKE.USAGE_CODEX_RATE_LIMIT_RESET,
- 'credit-id-from-client',
- )).rejects.toThrow(/idempotencyKey must be a UUID/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.USAGE_CODEX_RATE_LIMIT_RESET, 'credit-id-from-client'),
+ ).rejects.toThrow(/idempotencyKey must be a UUID/);
expect(consumeCodexRateLimitReset).not.toHaveBeenCalled();
});
it('encodes stale reset offers as a stable IPC precondition error', async () => {
const harness = new IpcHarness();
- const consumeCodexRateLimitReset = vi.fn().mockRejectedValue(
- new CodexRateLimitResetRejectedError('OFFER_EXPIRED', 'refresh usage'),
- );
+ const consumeCodexRateLimitReset = vi
+ .fn()
+ .mockRejectedValue(new CodexRateLimitResetRejectedError('OFFER_EXPIRED', 'refresh usage'));
registerMakerUsageHandlers(harness, makeUsageDeps({ consumeCodexRateLimitReset }));
- await expect(harness.invoke(
- MAKER_INVOKE.USAGE_CODEX_RATE_LIMIT_RESET,
- '018f4ec7-c6d8-7f10-8d43-9f8791d33000',
- )).rejects.toMatchObject({
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.USAGE_CODEX_RATE_LIMIT_RESET,
+ '018f4ec7-c6d8-7f10-8d43-9f8791d33000',
+ ),
+ ).rejects.toMatchObject({
code: 'PRECONDITION_FAILED',
message: expect.stringContaining('OFFER_EXPIRED'),
});
@@ -487,9 +1326,11 @@ describe('maker usage IPC handlers', () => {
it('encodes account changes during rate-limit reads as a stable IPC precondition error', async () => {
const harness = new IpcHarness();
- const readCodexRateLimits = vi.fn().mockRejectedValue(
- new CodexRateLimitResetRejectedError('ACCOUNT_CHANGED', 'retry after account settles'),
- );
+ const readCodexRateLimits = vi
+ .fn()
+ .mockRejectedValue(
+ new CodexRateLimitResetRejectedError('ACCOUNT_CHANGED', 'retry after account settles'),
+ );
registerMakerUsageHandlers(harness, makeUsageDeps({ readCodexRateLimits }));
await expect(harness.invoke(MAKER_INVOKE.USAGE_CODEX_RATE_LIMITS)).rejects.toMatchObject({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/helpers/ipcHarness.ts b/apps/desktop/src/main/maker-ipc/__tests__/helpers/ipcHarness.ts
index 01a86c46bd..45745df4c6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/helpers/ipcHarness.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/helpers/ipcHarness.ts
@@ -1,8 +1,17 @@
+import { EventEmitter } from 'node:events';
+
import type { IpcHandler, IpcHandlerRegistry } from '../../ipcHandlerRegistry';
+class IpcHarnessSender extends EventEmitter {
+ constructor(readonly id: number) {
+ super();
+ }
+}
+
/** 内存版 IPC registry,用于直接 invoke handler body。 */
export class IpcHarness implements IpcHandlerRegistry {
private readonly handlers = new Map<string, IpcHandler>();
+ private readonly senders = new Map<number, IpcHarnessSender>();
handle(channel: string, handler: IpcHandler): void {
if (this.handlers.has(channel)) {
@@ -16,4 +25,23 @@ export class IpcHarness implements IpcHandlerRegistry {
if (!handler) throw new Error(`missing IPC handler: ${channel}`);
return await handler({}, ...args);
}
+
+ async invokeFrom(senderId: number, channel: string, ...args: unknown[]): Promise<unknown> {
+ const handler = this.handlers.get(channel);
+ if (!handler) throw new Error(`missing IPC handler: ${channel}`);
+ return await handler({ sender: this.sender(senderId) }, ...args);
+ }
+
+ destroySender(senderId: number): void {
+ this.sender(senderId).emit('destroyed');
+ }
+
+ private sender(senderId: number): IpcHarnessSender {
+ let sender = this.senders.get(senderId);
+ if (!sender) {
+ sender = new IpcHarnessSender(senderId);
+ this.senders.set(senderId, sender);
+ }
+ return sender;
+ }
}
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 25293d2465..903c92ae59 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -2,7 +2,7 @@ import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterEach, describe, it, expect, vi } from 'vitest';
-import type { CustomProviderConfig, ProviderView } from '@cindy/model-providers';
+import type { AgentKind, CustomProviderConfig, ProviderView } from '@cindy/model-providers';
import type { DbClient } from '../../localDb/client/DbClient.js';
import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current.js';
@@ -61,6 +61,7 @@ function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps
listProviders: async () => [],
getModelVisibilityOverrides: () => ({}),
refreshCatalog: vi.fn(async () => {}),
+ beginRouteMutation: vi.fn(() => () => {}),
broadcastChanged: vi.fn(() => {}),
listPresets: () => [],
testConnection: vi.fn(async () => ({ ok: true, latencyMs: 1 })),
@@ -72,7 +73,10 @@ function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps
oauthLogin: vi.fn(async () => ({ ok: true })),
oauthLogout: vi.fn(async () => {}),
oauthCancel: vi.fn(() => {}),
- clearOAuthCredentials: vi.fn(() => {}),
+ removeOAuthCredentials: vi.fn(() => () => true),
+ readCustomProviderKeyForMutation: vi.fn(() => null),
+ storeCustomProviderKey: vi.fn(() => true),
+ removeCustomProviderKey: vi.fn(() => ({ success: true })),
scanLocalCli: vi.fn(async () => []),
...over,
};
@@ -118,7 +122,7 @@ describe('provider:list IPC handler', () => {
describe('provider:models-rediscover handler', () => {
it('校验 sender 后才发起重新发现;不可信 sender 直接拒绝', async () => {
const harness = new IpcHarness();
- const assertTrustedSender = vi.fn((_event: unknown) => {
+ const assertTrustedSender = vi.fn(() => {
throwIpcError('PERMISSION_DENIED', '此操作只能从 Cindy 主页面发起');
});
const deps = makeDeps({ assertTrustedSender });
@@ -193,6 +197,50 @@ describe('provider:models-rediscover handler', () => {
});
describe('provider:custom:* CRUD handlers', () => {
+ it('rejects credential-mutating CRUD before parsing or touching secrets for an untrusted sender', async () => {
+ const harness = new IpcHarness();
+ const assertTrustedSender = vi.fn(() => {
+ throwIpcError('PERMISSION_DENIED', 'untrusted provider mutation sender');
+ });
+ const deps = makeDeps({ assertTrustedSender });
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ validConfig,
+ { codex: 'must-not-stage' },
+ ),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,
+ validConfig,
+ { codex: 'must-not-stage' },
+ ),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, validConfig.id),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+
+ expect(assertTrustedSender).toHaveBeenCalledTimes(3);
+ expect(deps.readCustomProviderKeyForMutation).not.toHaveBeenCalled();
+ expect(deps.storeCustomProviderKey).not.toHaveBeenCalled();
+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();
+ expect(deps.removeOAuthCredentials).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when the provider mutation sender guard is not wired', async () => {
+ const harness = new IpcHarness();
+ const deps = makeDeps({ assertTrustedSender: undefined });
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig),
+ ).rejects.toThrow(/PERMISSION_DENIED.*guard unavailable/);
+ expect(deps.storeCustomProviderKey).not.toHaveBeenCalled();
+ });
+
it('creates a valid provider, persists it, refreshes + broadcasts', async () => {
mountDb();
const harness = new IpcHarness();
@@ -206,6 +254,90 @@ describe('provider:custom:* CRUD handlers', () => {
expect(deps.broadcastChanged).toHaveBeenCalledOnce();
});
+ it('rolls back partial create keys before any provider config is committed', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>();
+ const storeCalls: string[] = [];
+ const removeCalls: AgentKind[] = [];
+ registerProviderHandlers(harness, makeDeps({
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent, value) => {
+ storeCalls.push(`${agent}:${value}`);
+ if (agent === 'codex') return false;
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey: vi.fn((_providerId, agent) => {
+ removeCalls.push(agent);
+ keys.delete(agent);
+ return { success: true };
+ }),
+ }));
+ const config: CustomProviderConfig = {
+ ...validConfig,
+ id: 'partial-create',
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'claude-model', name: 'Claude model' }],
+ },
+ codex: {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'codex-model', name: 'Codex model' }],
+ },
+ },
+ };
+
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ config,
+ { 'claude-code': 'first-key', codex: 'second-key' },
+ ),
+ ).rejects.toThrow(/failed to update codex provider credential/);
+
+ expect(await listCustomProviders()).toEqual([]);
+ expect(keys.size).toBe(0);
+ expect(storeCalls).toEqual([
+ 'claude-code:first-key',
+ 'codex:second-key',
+ ]);
+ expect(removeCalls).toEqual(['codex', 'claude-code']);
+ });
+
+ it('does not stage supplied API keys when creating a no-auth provider', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+ const config: CustomProviderConfig = {
+ ...validConfig,
+ id: 'local-no-auth',
+ auth: { method: 'none' },
+ runtimes: {
+ codex: {
+ ...validConfig.runtimes.codex!,
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ },
+ },
+ };
+
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ config,
+ { codex: 'must-not-be-stored' },
+ ),
+ ).resolves.toEqual({ ok: true });
+
+ expect(deps.readCustomProviderKeyForMutation).not.toHaveBeenCalled();
+ expect(deps.storeCustomProviderKey).not.toHaveBeenCalled();
+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();
+ });
+
it('rejects invalid config (bad id) with INVALID_PARAMS and does not write', async () => {
mountDb();
const harness = new IpcHarness();
@@ -248,21 +380,508 @@ describe('provider:custom:* CRUD handlers', () => {
).rejects.toThrow(/NOT_FOUND/);
});
- it('deletes (idempotent) + broadcasts; bad providerId → INVALID_PARAMS', async () => {
+ it('clears an OAuth token when its descriptor changes but preserves it for model-only edits', async () => {
mountDb();
const harness = new IpcHarness();
- const deps = makeDeps();
+ const calls: string[] = [];
+ const oauthCancel = vi.fn(() => calls.push('cancel'));
+ const removeOAuthCredentials = vi.fn(() => {
+ calls.push('clear');
+ return () => true;
+ });
+ const deps = makeDeps({ oauthCancel, removeOAuthCredentials });
+ registerProviderHandlers(harness, deps);
+ const oauth = {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid models.read',
+ };
+ const oauthConfig: CustomProviderConfig = {
+ ...validConfig,
+ auth: {
+ method: 'oauth',
+ oauth,
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, oauthConfig);
+
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ name: 'OpenRouter renamed',
+ });
+ expect(removeOAuthCredentials).not.toHaveBeenCalled();
+ expect(oauthCancel).not.toHaveBeenCalled();
+
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ ...oauth,
+ tokenUrl: 'https://auth.example/token-v2',
+ },
+ },
+ });
+ expect(calls).toEqual(['cancel', 'clear']);
+ expect(oauthCancel).toHaveBeenCalledWith('openrouter');
+ expect(removeOAuthCredentials).toHaveBeenCalledWith('openrouter');
+ });
+
+ it('rejects unknown recursive OAuth fields at the IPC validation boundary', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ registerProviderHandlers(harness, makeDeps());
+ const oauth = {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid',
+ } as Record<string, unknown>;
+ oauth.unknown = oauth;
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, {
+ ...validConfig,
+ auth: { method: 'oauth', oauth },
+ }),
+ ).rejects.toThrow(/INVALID_PARAMS.*unknown is not allowed/);
+ expect(await listCustomProviders()).toEqual([]);
+ });
+
+ it('keeps the existing config when OAuth credential removal fails', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const oauthConfig: CustomProviderConfig = {
+ ...validConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid',
+ },
+ },
+ };
+ const deps = makeDeps({ removeOAuthCredentials: vi.fn(() => null) });
+ registerProviderHandlers(harness, deps);
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, oauthConfig);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ ...oauthConfig.auth!.oauth,
+ clientId: 'replacement-client',
+ },
+ },
+ }),
+ ).rejects.toThrow(/INTERNAL.*failed to remove existing OAuth credentials/);
+ expect((await listCustomProviders())[0]?.auth).toEqual(oauthConfig.auth);
+ expect(deps.refreshCatalog).toHaveBeenCalledTimes(1);
+ });
+
+ it('restores OAuth credentials when the config write fails after removal', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const restore = vi.fn(() => true);
+ const removeOAuthCredentials = vi.fn(() => restore);
+ registerProviderHandlers(harness, makeDeps({ removeOAuthCredentials }));
+ const oauthConfig: CustomProviderConfig = {
+ ...validConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid',
+ },
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, oauthConfig);
+ raw!.exec(`
+ CREATE TRIGGER fail_custom_provider_update
+ BEFORE UPDATE ON custom_providers
+ BEGIN
+ SELECT RAISE(ABORT, 'simulated write failure');
+ END
+ `);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ ...oauthConfig.auth!.oauth,
+ clientId: 'replacement-client',
+ },
+ },
+ }),
+ ).rejects.toThrow(/simulated write failure/);
+
+ expect(removeOAuthCredentials).toHaveBeenCalledWith(oauthConfig.id);
+ expect(restore).toHaveBeenCalledOnce();
+ expect((await listCustomProviders())[0]?.auth).toEqual(oauthConfig.auth);
+ });
+
+ it('serializes provider updates so a failed write restores credentials before the next edit', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const calls: string[] = [];
+ let removalCount = 0;
+ const removeOAuthCredentials = vi.fn(() => {
+ removalCount += 1;
+ calls.push(`remove-${removalCount}`);
+ return () => {
+ calls.push(`restore-${removalCount}`);
+ if (removalCount === 1) raw!.exec('DROP TRIGGER fail_first_custom_provider_update');
+ return true;
+ };
+ });
+ registerProviderHandlers(harness, makeDeps({ removeOAuthCredentials }));
+ const oauthConfig: CustomProviderConfig = {
+ ...validConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid',
+ },
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, oauthConfig);
+ raw!.exec(`
+ CREATE TRIGGER fail_first_custom_provider_update
+ BEFORE UPDATE ON custom_providers
+ BEGIN
+ SELECT RAISE(ABORT, 'simulated first write failure');
+ END
+ `);
+
+ const first = harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ auth: {
+ method: 'oauth',
+ oauth: { ...oauthConfig.auth!.oauth, clientId: 'failed-client' },
+ },
+ });
+ const second = harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ auth: {
+ method: 'oauth',
+ oauth: { ...oauthConfig.auth!.oauth, clientId: 'winning-client' },
+ },
+ });
+
+ await expect(first).rejects.toThrow(/simulated first write failure/);
+ await expect(second).resolves.toEqual({ ok: true });
+ expect(calls).toEqual(['remove-1', 'restore-1', 'remove-2']);
+ const savedAuth = (await listCustomProviders())[0]?.auth;
+ expect(savedAuth?.method === 'oauth' ? savedAuth.oauth.clientId : undefined).toBe(
+ 'winning-client',
+ );
+ });
+
+ it('restores a staged API key when the provider config write fails', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>([['codex', 'old-key']]);
+ const storeCalls: string[] = [];
+ registerProviderHandlers(harness, makeDeps({
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent, value) => {
+ storeCalls.push(`${agent}:${value}`);
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey: vi.fn((_providerId, agent) => {
+ keys.delete(agent);
+ return { success: true };
+ }),
+ }));
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig);
+ raw!.exec(`
+ CREATE TRIGGER fail_custom_provider_update
+ BEFORE UPDATE ON custom_providers
+ BEGIN
+ SELECT RAISE(ABORT, 'simulated write failure');
+ END
+ `);
+
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,
+ { ...validConfig, name: 'Must not persist' },
+ { codex: 'replacement-key' },
+ ),
+ ).rejects.toThrow(/simulated write failure/);
+
+ expect(storeCalls).toEqual(['codex:replacement-key', 'codex:old-key']);
+ expect(keys.get('codex')).toBe('old-key');
+ expect((await listCustomProviders())[0]?.name).toBe(validConfig.name);
+ });
+
+ it('aborts before overwriting an existing key that cannot be read for rollback', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>();
+ let unreadable = false;
+ const readCustomProviderKeyForMutation = vi.fn((_providerId, agent: AgentKind) => {
+ if (unreadable && agent === 'claude-code') {
+ throw new Error('encryption temporarily unavailable');
+ }
+ return keys.get(agent) ?? null;
+ });
+ const storeCustomProviderKey = vi.fn((_providerId, agent: AgentKind, value: string) => {
+ keys.set(agent, value);
+ return true;
+ });
+ const removeCustomProviderKey = vi.fn((_providerId, agent: AgentKind) => {
+ keys.delete(agent);
+ return { success: true };
+ });
+ registerProviderHandlers(harness, makeDeps({
+ readCustomProviderKeyForMutation,
+ storeCustomProviderKey,
+ removeCustomProviderKey,
+ }));
+ const config: CustomProviderConfig = {
+ ...validConfig,
+ id: 'strict-snapshot',
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'claude-model', name: 'Claude model' }],
+ },
+ },
+ };
+ await harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ config,
+ { 'claude-code': 'old-key' },
+ );
+ unreadable = true;
+ storeCustomProviderKey.mockClear();
+ removeCustomProviderKey.mockClear();
+
+ await expect(
+ harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,
+ { ...config, name: 'Must not persist' },
+ { 'claude-code': 'replacement-key' },
+ ),
+ ).rejects.toThrow(/failed to read existing claude-code provider credential/);
+
+ expect(keys.get('claude-code')).toBe('old-key');
+ expect(storeCustomProviderKey).not.toHaveBeenCalled();
+ expect(removeCustomProviderKey).not.toHaveBeenCalled();
+ expect((await listCustomProviders())[0]?.name).toBe(config.name);
+ });
+
+ it('serializes create key staging with a later cross-window update', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>();
+ const storeCalls: string[] = [];
+ let releaseRefresh!: () => void;
+ let reachedRefresh!: () => void;
+ const refreshGate = new Promise<void>((resolve) => {
+ releaseRefresh = resolve;
+ });
+ const firstReachedRefresh = new Promise<void>((resolve) => {
+ reachedRefresh = resolve;
+ });
+ let refreshCount = 0;
+ const refreshCatalog = vi.fn(async () => {
+ refreshCount += 1;
+ if (refreshCount === 1) {
+ reachedRefresh();
+ await refreshGate;
+ }
+ });
+ registerProviderHandlers(harness, makeDeps({
+ refreshCatalog,
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent, value) => {
+ storeCalls.push(`${agent}:${value}`);
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey: vi.fn((_providerId, agent) => {
+ keys.delete(agent);
+ return { success: true };
+ }),
+ }));
+
+ const create = harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ validConfig,
+ { codex: 'created-key' },
+ );
+ await firstReachedRefresh;
+ const update = harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,
+ { ...validConfig, name: 'Later edit' },
+ { codex: 'updated-key' },
+ );
+ await Promise.resolve();
+
+ expect(storeCalls).toEqual(['codex:created-key']);
+ expect((await listCustomProviders())[0]?.name).toBe(validConfig.name);
+
+ releaseRefresh();
+ await expect(create).resolves.toEqual({ ok: true });
+ await expect(update).resolves.toEqual({ ok: true });
+ expect(storeCalls).toEqual(['codex:created-key', 'codex:updated-key']);
+ expect(keys.get('codex')).toBe('updated-key');
+ expect((await listCustomProviders())[0]?.name).toBe('Later edit');
+ });
+
+ it('serializes API key staging with config updates across concurrent renderer edits', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>([['codex', 'old-key']]);
+ const storeCalls: string[] = [];
+ let holdRefresh = false;
+ let releaseRefresh!: () => void;
+ let reachedRefresh!: () => void;
+ const refreshGate = new Promise<void>((resolve) => {
+ releaseRefresh = resolve;
+ });
+ const firstReachedRefresh = new Promise<void>((resolve) => {
+ reachedRefresh = resolve;
+ });
+ const refreshCatalog = vi.fn(async () => {
+ if (!holdRefresh) return;
+ reachedRefresh();
+ await refreshGate;
+ });
+ const deps = makeDeps({
+ refreshCatalog,
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent, value) => {
+ storeCalls.push(`${agent}:${value}`);
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey: vi.fn((_providerId, agent) => {
+ keys.delete(agent);
+ return { success: true };
+ }),
+ });
registerProviderHandlers(harness, deps);
await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig);
+ holdRefresh = true;
+
+ const first = harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,
+ { ...validConfig, name: 'First edit' },
+ { codex: 'first-key' },
+ );
+ await firstReachedRefresh;
+ const second = harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,
+ { ...validConfig, name: 'Second edit' },
+ { codex: 'second-key' },
+ );
+ await Promise.resolve();
+
+ expect(storeCalls).toEqual(['codex:first-key']);
+ expect(keys.get('codex')).toBe('first-key');
+
+ releaseRefresh();
+ await expect(first).resolves.toEqual({ ok: true });
+ await expect(second).resolves.toEqual({ ok: true });
+ expect(storeCalls).toEqual(['codex:first-key', 'codex:second-key']);
+ expect(keys.get('codex')).toBe('second-key');
+ expect((await listCustomProviders())[0]?.name).toBe('Second edit');
+ });
+
+ it('deletes (idempotent) + broadcasts; bad providerId → INVALID_PARAMS', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const calls: string[] = [];
+ const keys = new Map<AgentKind, string>();
+ const deps = makeDeps({
+ oauthCancel: vi.fn(() => calls.push('cancel')),
+ removeOAuthCredentials: vi.fn(() => {
+ calls.push('clear');
+ return () => true;
+ }),
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent, value) => {
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey: vi.fn((_providerId, agent) => {
+ keys.delete(agent);
+ return { success: true };
+ }),
+ });
+ registerProviderHandlers(harness, deps);
+ await harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ validConfig,
+ { codex: 'delete-me' },
+ );
const del = await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, 'openrouter');
expect(del).toEqual({ ok: true });
expect(await listCustomProviders()).toEqual([]);
+ expect(keys.size).toBe(0);
+ expect(calls).toEqual(['cancel', 'clear']);
await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, '')).rejects.toThrow(
/INVALID_PARAMS/,
);
});
+
+ it('does not delete a provider when OAuth credential removal fails', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>();
+ const deps = makeDeps({
+ removeOAuthCredentials: vi.fn(() => null),
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent, value) => {
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey: vi.fn((_providerId, agent) => {
+ keys.delete(agent);
+ return { success: true };
+ }),
+ });
+ registerProviderHandlers(harness, deps);
+ await harness.invoke(
+ MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,
+ validConfig,
+ { codex: 'must-survive' },
+ );
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, 'openrouter'),
+ ).rejects.toThrow(/INTERNAL.*failed to remove existing OAuth credentials/);
+ expect(await listCustomProviders()).toHaveLength(1);
+ expect(keys.get('codex')).toBe('must-survive');
+ });
});
describe('provider:presets handler', () => {
@@ -297,6 +916,7 @@ describe('provider:test-connection handler', () => {
agent: 'claude-code',
baseUrl: 'https://x.example',
modelId: 'm',
+ authMethod: 'apiKey',
requestPath: '/tenant/acme/infer?stream=1',
apiKey: 'k',
},
@@ -308,6 +928,7 @@ describe('provider:test-connection handler', () => {
agent: 'claude-code',
baseUrl: 'https://x.example',
modelId: 'm',
+ authMethod: 'apiKey',
wireProtocol: undefined,
requestPath: '/tenant/acme/infer?stream=1',
apiKey: 'k',
@@ -316,6 +937,25 @@ describe('provider:test-connection handler', () => {
});
});
+ it('rejects remote no-auth adhoc probes before invoking the network dependency', async () => {
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_TEST_CONNECTION, {
+ kind: 'adhoc',
+ spec: {
+ agent: 'codex',
+ baseUrl: 'https://remote.example/v1',
+ modelId: 'm',
+ authMethod: 'none',
+ },
+ }),
+ ).rejects.toThrow(/INVALID_PARAMS/);
+ expect(deps.testConnection).not.toHaveBeenCalled();
+ });
+
it('rejects malformed input with INVALID_PARAMS (bad agent / bad url / missing model)', async () => {
const harness = new IpcHarness();
const deps = makeDeps();
@@ -325,6 +965,8 @@ describe('provider:test-connection handler', () => {
{ kind: 'adhoc', spec: { agent: 'gemini', baseUrl: 'https://x.example', modelId: 'm' } },
{ kind: 'adhoc', spec: { agent: 'codex', baseUrl: 'ftp://x', modelId: 'm' } },
{ kind: 'adhoc', spec: { agent: 'codex', baseUrl: 'https://x.example', modelId: '' } },
+ { kind: 'adhoc', spec: { agent: 'codex', baseUrl: 'https://x.example', modelId: 'm', requestPath: '//evil.example' } },
+ { kind: 'adhoc', spec: { agent: 'codex', baseUrl: 'https://x.example', modelId: 'm', requestPath: '/infer#fragment' } },
{
kind: 'adhoc',
spec: {
@@ -370,6 +1012,7 @@ describe('provider:models-fetch handler', () => {
const result = await harness.invoke(MAKER_INVOKE.PROVIDER_MODELS_FETCH, {
agent: 'claude-code',
baseUrl: 'https://x.example/anthropic',
+ authMethod: 'apiKey',
modelsUrl: 'https://x.example/v1/models',
apiKey: 'k',
});
@@ -377,12 +1020,29 @@ describe('provider:models-fetch handler', () => {
expect(fetchModels).toHaveBeenCalledWith({
agent: 'claude-code',
baseUrl: 'https://x.example/anthropic',
+ authMethod: 'apiKey',
modelsUrl: 'https://x.example/v1/models',
apiKey: 'k',
headers: undefined,
});
});
+ it('rejects remote no-auth model discovery URLs before invoking fetch', async () => {
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_MODELS_FETCH, {
+ agent: 'codex',
+ authMethod: 'none',
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ modelsUrl: 'https://remote.example/v1/models',
+ }),
+ ).rejects.toThrow(/INVALID_PARAMS/);
+ expect(deps.fetchModels).not.toHaveBeenCalled();
+ });
+
it('rejects malformed input with INVALID_PARAMS (bad agent / bad url / bad modelsUrl / bad headers)', async () => {
const harness = new IpcHarness();
const deps = makeDeps();
@@ -401,3 +1061,322 @@ describe('provider:models-fetch handler', () => {
expect(deps.fetchModels).not.toHaveBeenCalled();
});
});
+
+describe('provider:oauth mutation ordering', () => {
+ it('cancels an active login before removing OAuth credentials', async () => {
+ const harness = new IpcHarness();
+ const calls: string[] = [];
+ const deps = makeDeps({
+ oauthCancel: vi.fn(() => calls.push('cancel')),
+ oauthLogout: vi.fn(async () => {
+ calls.push('logout');
+ }),
+ });
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, 'openrouter'),
+ ).resolves.toEqual({ ok: true });
+ expect(calls).toEqual(['cancel', 'logout']);
+ });
+
+ it('encodes credential deletion failures as an IPC INTERNAL error', async () => {
+ const harness = new IpcHarness();
+ registerProviderHandlers(
+ harness,
+ makeDeps({
+ oauthLogout: vi.fn().mockRejectedValue(new Error('safe storage deletion failed')),
+ }),
+ );
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, 'openrouter'),
+ ).rejects.toMatchObject({ code: 'INTERNAL' });
+ });
+
+ it('does not let a stale window release cancel a newer generic OAuth operation', async () => {
+ const harness = new IpcHarness();
+ const pending: Array<{
+ isCurrent: () => boolean;
+ finish: (result: { ok: boolean }) => void;
+ }> = [];
+ const oauthLogin = vi.fn(
+ async (
+ _providerId: string,
+ isCurrent: () => boolean,
+ ): Promise<{ ok: boolean }> =>
+ new Promise((resolve) => {
+ pending.push({ isCurrent, finish: resolve });
+ }),
+ );
+ const oauthCancel = vi.fn();
+ registerProviderHandlers(harness, makeDeps({ oauthLogin, oauthCancel }));
+
+ const first = harness.invokeFrom(
+ 101,
+ MAKER_INVOKE.PROVIDER_OAUTH_LOGIN,
+ 'openrouter',
+ { ownerId: 'window-101-provider-login' },
+ );
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ const second = harness.invokeFrom(
+ 202,
+ MAKER_INVOKE.PROVIDER_OAUTH_LOGIN,
+ 'openrouter',
+ { ownerId: 'window-202-provider-login' },
+ );
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ expect(pending[0].isCurrent()).toBe(false);
+ expect(pending[1].isCurrent()).toBe(true);
+
+ await expect(
+ harness.invokeFrom(
+ 101,
+ MAKER_INVOKE.PROVIDER_OAUTH_CANCEL,
+ 'openrouter',
+ { releaseOwner: true, ownerId: 'window-101-provider-login' },
+ ),
+ ).resolves.toEqual({ ok: true });
+ expect(oauthCancel).not.toHaveBeenCalled();
+ expect(pending[1].isCurrent()).toBe(true);
+
+ await expect(
+ harness.invokeFrom(
+ 202,
+ MAKER_INVOKE.PROVIDER_OAUTH_CANCEL,
+ 'openrouter',
+ { releaseOwner: true, ownerId: 'window-202-provider-login' },
+ ),
+ ).resolves.toEqual({ ok: true });
+ expect(oauthCancel).toHaveBeenCalledOnce();
+ expect(oauthCancel).toHaveBeenCalledWith('openrouter');
+ expect(pending[1].isCurrent()).toBe(false);
+
+ pending[0].finish({ ok: false });
+ pending[1].finish({ ok: false });
+ await expect(first).resolves.toEqual({ ok: false, reason: 'login_cancelled' });
+ await expect(second).resolves.toEqual({ ok: false, reason: 'login_cancelled' });
+ });
+
+ it('cancels the current owned generic OAuth operation when its window is destroyed', async () => {
+ const harness = new IpcHarness();
+ let isCurrent!: () => boolean;
+ let finishLogin!: (result: { ok: boolean }) => void;
+ const oauthLogin = vi.fn(
+ async (
+ _providerId: string,
+ checkCurrent: () => boolean,
+ ): Promise<{ ok: boolean }> =>
+ new Promise((resolve) => {
+ isCurrent = checkCurrent;
+ finishLogin = resolve;
+ }),
+ );
+ const oauthCancel = vi.fn();
+ registerProviderHandlers(harness, makeDeps({ oauthLogin, oauthCancel }));
+
+ const login = harness.invokeFrom(
+ 101,
+ MAKER_INVOKE.PROVIDER_OAUTH_LOGIN,
+ 'openrouter',
+ { ownerId: 'window-101-destroyed' },
+ );
+ await vi.waitFor(() => expect(oauthLogin).toHaveBeenCalledOnce());
+ expect(isCurrent()).toBe(true);
+
+ harness.destroySender(101);
+ expect(oauthCancel).toHaveBeenCalledWith('openrouter');
+ expect(isCurrent()).toBe(false);
+
+ finishLogin({ ok: false });
+ await expect(login).resolves.toEqual({ ok: false, reason: 'login_cancelled' });
+ });
+
+ it('invalidates post-login work when the provider is edited before discovery finishes', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ let finishLogin!: (result: {
+ ok: boolean;
+ rollbackCredentials?: () => boolean;
+ }) => void;
+ let loginIsCurrent!: () => boolean;
+ const oauthLogin = vi.fn(
+ async (
+ _providerId: string,
+ isCurrent: () => boolean,
+ ): Promise<{ ok: boolean; rollbackCredentials?: () => boolean }> => {
+ loginIsCurrent = isCurrent;
+ return new Promise((resolve) => {
+ finishLogin = resolve;
+ });
+ },
+ );
+ registerProviderHandlers(harness, makeDeps({ oauthLogin }));
+ const oauthConfig: CustomProviderConfig = {
+ ...validConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid models.read',
+ },
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, oauthConfig);
+
+ const login = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, oauthConfig.id);
+ await vi.waitFor(() => expect(oauthLogin).toHaveBeenCalledOnce());
+ expect(loginIsCurrent()).toBe(true);
+
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ runtimes: {
+ codex: {
+ ...oauthConfig.runtimes.codex,
+ baseUrl: 'https://new-endpoint.example/v1',
+ },
+ },
+ });
+ expect(loginIsCurrent()).toBe(false);
+
+ const rollbackCredentials = vi.fn(() => true);
+ finishLogin({ ok: true, rollbackCredentials });
+ await expect(login).resolves.toEqual({ ok: false, reason: 'login_cancelled' });
+ expect(rollbackCredentials).toHaveBeenCalledOnce();
+ });
+
+ it('encodes failed stale-login credential rollback as an IPC INTERNAL error', async () => {
+ const harness = new IpcHarness();
+ let finishLogin!: (result: { ok: boolean; rollbackCredentials?: () => boolean }) => void;
+ const oauthLogin = vi.fn(
+ async (): Promise<{ ok: boolean; rollbackCredentials?: () => boolean }> =>
+ new Promise((resolve) => {
+ finishLogin = resolve;
+ }),
+ );
+ registerProviderHandlers(harness, makeDeps({ oauthLogin }));
+
+ const login = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, 'openrouter');
+ await vi.waitFor(() => expect(oauthLogin).toHaveBeenCalledOnce());
+ await harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_CANCEL, 'openrouter');
+ finishLogin({ ok: true, rollbackCredentials: () => false });
+
+ await expect(login).rejects.toMatchObject({ code: 'INTERNAL' });
+ });
+
+ it('rejects a new login until provider update and catalog refresh fully settle', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ let finishRefresh!: () => void;
+ const blockedRefresh = new Promise<void>((resolve) => {
+ finishRefresh = resolve;
+ });
+ const refreshCatalog = vi.fn()
+ .mockResolvedValueOnce(undefined)
+ .mockReturnValueOnce(blockedRefresh);
+ const oauthLogin = vi.fn(async () => ({ ok: true }));
+ registerProviderHandlers(harness, makeDeps({ refreshCatalog, oauthLogin }));
+ const oauthConfig: CustomProviderConfig = {
+ ...validConfig,
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example/authorize',
+ tokenUrl: 'https://auth.example/token',
+ clientId: 'desktop',
+ scopes: 'openid',
+ },
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, oauthConfig);
+
+ const update = harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...oauthConfig,
+ name: 'Updated while refresh is blocked',
+ });
+ await vi.waitFor(() => expect(refreshCatalog).toHaveBeenCalledTimes(2));
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, oauthConfig.id),
+ ).resolves.toEqual({ ok: false, reason: 'provider_update_in_progress' });
+ expect(oauthLogin).not.toHaveBeenCalled();
+
+ finishRefresh();
+ await expect(update).resolves.toEqual({ ok: true });
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, oauthConfig.id),
+ ).resolves.toEqual({ ok: true });
+ expect(oauthLogin).toHaveBeenCalledOnce();
+ });
+
+ it('serializes explicit logout behind an in-flight provider update', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ let finishRefresh!: () => void;
+ const blockedRefresh = new Promise<void>((resolve) => {
+ finishRefresh = resolve;
+ });
+ const refreshCatalog = vi.fn()
+ .mockResolvedValueOnce(undefined)
+ .mockReturnValueOnce(blockedRefresh)
+ .mockResolvedValueOnce(undefined);
+ const oauthLogout = vi.fn().mockResolvedValue(undefined);
+ registerProviderHandlers(harness, makeDeps({ refreshCatalog, oauthLogout }));
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig);
+
+ const update = harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...validConfig,
+ name: 'Update before logout',
+ });
+ await vi.waitFor(() => expect(refreshCatalog).toHaveBeenCalledTimes(2));
+
+ const logout = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, validConfig.id);
+ await Promise.resolve();
+ expect(oauthLogout).not.toHaveBeenCalled();
+
+ finishRefresh();
+ await expect(update).resolves.toEqual({ ok: true });
+ await expect(logout).resolves.toEqual({ ok: true });
+ expect(oauthLogout).toHaveBeenCalledOnce();
+ });
+
+ it('cleans mutation entries without reviving an older login generation', async () => {
+ const harness = new IpcHarness();
+ const pending: Array<{
+ isCurrent: () => boolean;
+ finish: (result: {
+ ok: boolean;
+ rollbackCredentials?: () => boolean;
+ }) => void;
+ }> = [];
+ const oauthLogin = vi.fn(
+ async (
+ _providerId: string,
+ isCurrent: () => boolean,
+ ): Promise<{ ok: boolean; rollbackCredentials?: () => boolean }> =>
+ new Promise((resolve) => {
+ pending.push({ isCurrent, finish: resolve });
+ }),
+ );
+ registerProviderHandlers(harness, makeDeps({ oauthLogin }));
+
+ const first = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, 'openrouter');
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ await harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_CANCEL, 'openrouter');
+ expect(pending[0].isCurrent()).toBe(false);
+
+ const second = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, 'openrouter');
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ expect(pending[0].isCurrent()).toBe(false);
+ expect(pending[1].isCurrent()).toBe(true);
+
+ const rollbackCredentials = vi.fn(() => true);
+ pending[0].finish({ ok: true, rollbackCredentials });
+ pending[1].finish({ ok: true });
+ await expect(first).resolves.toEqual({ ok: false, reason: 'login_cancelled' });
+ await expect(second).resolves.toEqual({ ok: true });
+ expect(rollbackCredentials).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/authHandlers.ts b/apps/desktop/src/main/maker-ipc/authHandlers.ts
index 9cc0291e58..89f894e746 100644
--- a/apps/desktop/src/main/maker-ipc/authHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/authHandlers.ts
@@ -5,9 +5,9 @@
* push payload 归一化。
*/
-import type { AgentKind, AuthState, Maker } from '@cindy/maker-core';
+import type { AgentKind, AgentLoginMode, AuthState, Maker } from '@cindy/maker-core';
-import { requireEnum, throwIpcError } from '../utils/ipcValidate.js';
+import { optionalEnum, requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';
import { createLogger } from '../logger.js';
import { MAKER_INVOKE, MAKER_PUSH } from './channels.js';
import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
@@ -19,6 +19,100 @@ export type MakerIpcBroadcast = (channel: string, payload: unknown) => void;
/** IPC 允许的 agent 种类;运行时枚举校验不能靠 TypeScript 强转替代。 */
const AGENT_KINDS = ['claude-code', 'codex'] as const satisfies readonly AgentKind[];
+const AGENT_LOGIN_MODES = ['browser', 'device-code'] as const satisfies readonly AgentLoginMode[];
+const MAX_LOGIN_PROGRESS_CHARS = 16_384;
+const LOGIN_OWNER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
+const ANSI_SEQUENCE = new RegExp(
+ `${String.fromCodePoint(27)}\\[[0-?]*[ -/]*[@-~]`,
+ 'g',
+);
+
+export interface CodexDeviceCodeProgress {
+ verificationUrl: string;
+ userCode: string;
+}
+
+type CodexDeviceCodeProgressPayload = CodexDeviceCodeProgress & {
+ agentKind: 'codex';
+ phase: 'device-code';
+ mode: 'device-code';
+};
+
+type RendererSender = {
+ readonly id: number;
+ once?: (event: 'destroyed', listener: () => void) => unknown;
+ removeListener?: (event: 'destroyed', listener: () => void) => unknown;
+};
+
+type ActiveLoginOperation = {
+ mode: AgentLoginMode;
+ promise: Promise<AuthState>;
+ settled: Promise<void>;
+ requiresDurableDisconnect: boolean;
+ acceptingOwners: boolean;
+ settledFlag: boolean;
+ ownerIds: Set<string>;
+ hasUnmanagedOwner: boolean;
+ latestDeviceCodeProgress?: CodexDeviceCodeProgressPayload;
+ cancellation?: Promise<void>;
+};
+
+type LoginOwner = {
+ kind: AgentKind;
+ sender: RendererSender;
+ operation: ActiveLoginOperation;
+};
+
+/** Codex CLI 输出带 ANSI 色码;Renderer 只应收到可展示的纯文本。 */
+function stripAnsi(value: string): string {
+ return value.replace(ANSI_SEQUENCE, '');
+}
+
+/**
+ * CLI 会把 URL 嵌在自然语言里,句末标点不属于验证地址。成对括号仍可能是 URL
+ * 路径的一部分,只移除没有对应左括号的尾部闭合符。
+ */
+function trimTrailingUrlPunctuation(value: string): string {
+ let candidate = value.replace(/[.,;:!?]+$/g, '');
+ const pairs = [
+ ['(', ')'],
+ ['[', ']'],
+ ['{', '}'],
+ ] as const;
+
+ while (candidate.length > 0) {
+ const pair = pairs.find(([, close]) => candidate.endsWith(close));
+ if (!pair) break;
+ const [open, close] = pair;
+ const openCount = candidate.split(open).length - 1;
+ const closeCount = candidate.split(close).length - 1;
+ if (closeCount <= openCount) break;
+ candidate = candidate.slice(0, -1).replace(/[.,;:!?]+$/g, '');
+ }
+
+ return candidate;
+}
+
+/**
+ * 从 `codex login --device-auth` 的渐进输出提取验证页与一次性代码。
+ * 输入可以是不完整的多 chunk 累积文本;两项没齐时返回 null。
+ */
+export function parseCodexDeviceCodeProgress(text: string): CodexDeviceCodeProgress | null {
+ const clean = stripAnsi(text);
+ const codeMatch = clean.match(/\b[A-Z0-9]{4,8}(?:-[A-Z0-9]{4,8})+\b/);
+ if (!codeMatch) return null;
+ for (const match of clean.matchAll(/https:\/\/[^\s<>"']+/gi)) {
+ try {
+ const url = new URL(trimTrailingUrlPunctuation(match[0]));
+ if (url.protocol === 'https:' && url.hostname === 'auth.openai.com') {
+ return { verificationUrl: url.toString(), userCode: codeMatch[0] };
+ }
+ } catch {
+ // CLI prose may trail punctuation after a URL; keep scanning later candidates.
+ }
+ }
+ return null;
+}
export function registerMakerAuthHandlers(
registry: IpcHandlerRegistry,
@@ -39,6 +133,18 @@ export function registerMakerAuthHandlers(
) => void | Promise<void>,
): void {
const mutationGeneration = new Map<AgentKind, number>();
+ const loginRequestGeneration = new Map<AgentKind, number>();
+ const loginCancellationGeneration = new Map<AgentKind, number>();
+ const logoutFinalizations = new Map<AgentKind, Promise<void>>();
+ const activeLoginOperations = new Map<AgentKind, ActiveLoginOperation>();
+ // 一个 Maker/adapter 服务所有 BrowserWindow。owner token 同时绑定 operation 与
+ // webContents:旧组件的迟到 cleanup 不能误删同窗口的新登录,窗口被直接销毁时 main
+ // 也能回收它名下所有 token。
+ const loginOwners = new Map<string, LoginOwner>();
+ const senderOwners = new Map<
+ RendererSender,
+ { ownerIds: Set<string>; onDestroyed: () => void }
+ >();
const beginMutation = (kind: AgentKind): number => {
const generation = (mutationGeneration.get(kind) ?? 0) + 1;
mutationGeneration.set(kind, generation);
@@ -46,29 +152,157 @@ export function registerMakerAuthHandlers(
};
const isMutationCurrent = (kind: AgentKind, generation: number): boolean =>
(mutationGeneration.get(kind) ?? 0) === generation;
+ const beginLoginRequest = (kind: AgentKind): number => {
+ const generation = (loginRequestGeneration.get(kind) ?? 0) + 1;
+ loginRequestGeneration.set(kind, generation);
+ return generation;
+ };
+ const isLoginRequestCurrent = (kind: AgentKind, generation: number): boolean =>
+ (loginRequestGeneration.get(kind) ?? 0) === generation;
+ const beginLoginCancellation = (kind: AgentKind): number => {
+ const generation = (loginCancellationGeneration.get(kind) ?? 0) + 1;
+ loginCancellationGeneration.set(kind, generation);
+ return generation;
+ };
+ const currentLoginCancellation = (kind: AgentKind): number =>
+ loginCancellationGeneration.get(kind) ?? 0;
+ const waitForLatestLogoutFinalization = async (kind: AgentKind): Promise<void> => {
+ while (true) {
+ const observed = logoutFinalizations.get(kind);
+ if (!observed) return;
+ await observed.catch(() => undefined);
+ // A later logout may replace the entry while this login is waiting. Only proceed
+ // after the most recently observed finalization has itself settled.
+ if (logoutFinalizations.get(kind) === observed) return;
+ }
+ };
- registry.handle(MAKER_INVOKE.AUTH_GET_STATE, async (_e, agentKind: unknown): Promise<AuthState> => {
- return maker.getAgentAuthState(requireAgentKind(agentKind));
- });
+ const removeLoginOwner = (
+ ownerId: string,
+ expectedSender?: RendererSender,
+ ): LoginOwner | null => {
+ const owner = loginOwners.get(ownerId);
+ if (!owner || (expectedSender && owner.sender !== expectedSender)) return null;
+ loginOwners.delete(ownerId);
+ owner.operation.ownerIds.delete(ownerId);
- // presence-only:只回「有没有配 key」,绝不回密钥本体。device-link 控制端(手机 / 远程桌面)
- // 用它决定折扣版(codex/)行是否置灰 —— key 与请求都在被控端,这里才是判定真相。
- registry.handle(MAKER_INVOKE.API_KEY_PRESENT, async (): Promise<{ present: boolean }> => {
- return { present: !!readApiKey() };
- });
+ const subscription = senderOwners.get(owner.sender);
+ subscription?.ownerIds.delete(ownerId);
+ if (subscription && subscription.ownerIds.size === 0) {
+ owner.sender.removeListener?.('destroyed', subscription.onDestroyed);
+ senderOwners.delete(owner.sender);
+ }
+ return owner;
+ };
- registry.handle(MAKER_INVOKE.AUTH_TRIGGER_LOGIN, async (_e, agentKind: unknown): Promise<AuthState> => {
- const kind = requireAgentKind(agentKind);
+ const clearOperationOwners = (operation: ActiveLoginOperation): void => {
+ for (const ownerId of [...operation.ownerIds]) removeLoginOwner(ownerId);
+ };
+
+ const clearOwnersForKind = (kind: AgentKind): void => {
+ for (const [ownerId, owner] of [...loginOwners]) {
+ if (owner.kind === kind) removeLoginOwner(ownerId);
+ }
+ };
+
+ const registerLoginOwner = (
+ kind: AgentKind,
+ operation: ActiveLoginOperation,
+ sender: RendererSender | null,
+ ownerId: string | undefined,
+ ): void => {
+ // 老版本 renderer / tunnel 不会提供 owner token;它们仍可登录,但不能被某个新版
+ // renderer 的组件 cleanup 当作“无人持有”而取消。
+ if (!ownerId) {
+ operation.hasUnmanagedOwner = true;
+ return;
+ }
+ if (!sender) {
+ throwIpcError('INVALID_PARAMS', 'ownerId requires an Electron sender');
+ }
+
+ const existing = loginOwners.get(ownerId);
+ if (existing) {
+ if (
+ existing.kind === kind &&
+ existing.sender === sender &&
+ existing.operation === operation
+ ) {
+ return;
+ }
+ throwIpcError('INVALID_PARAMS', 'ownerId is already bound to another login operation');
+ }
+
+ let subscription = senderOwners.get(sender);
+ if (!subscription) {
+ const onDestroyed = (): void => handleRendererDestroyed(sender);
+ subscription = { ownerIds: new Set(), onDestroyed };
+ senderOwners.set(sender, subscription);
+ sender.once?.('destroyed', onDestroyed);
+ }
+ subscription.ownerIds.add(ownerId);
+ operation.ownerIds.add(ownerId);
+ loginOwners.set(ownerId, { kind, sender, operation });
+ };
+
+ const runLoginOperation = async (
+ kind: AgentKind,
+ mode: AgentLoginMode,
+ operation: ActiveLoginOperation,
+ ): Promise<AuthState> => {
+ // 先登记请求再等待注销收尾,使等待期间到达的 Cancel 也能作废这次登录。
+ // 此 generation 与 auth mutation 分离,避免排队登录反过来提前作废正在收尾的 logout。
+ const loginGeneration = beginLoginRequest(kind);
+ const cancellationGeneration = currentLoginCancellation(kind);
+ const invalidatedState = (): AuthState =>
+ currentLoginCancellation(kind) !== cancellationGeneration
+ ? cancelledAuthState()
+ : supersededAuthState();
+ // Adapter 会把注销期间到达的登录排在 CLI logout 后面;这里还必须等主进程完成
+ // credential bridge / model snapshot 的注销收尾,再建立新的 mutation generation。
+ // 否则新登录会提前作废旧 generation,导致注销回调被跳过。
+ await waitForLatestLogoutFinalization(kind);
+ if (!isLoginRequestCurrent(kind, loginGeneration)) return invalidatedState();
const generation = beginMutation(kind);
- const isCurrent = (): boolean => isMutationCurrent(kind, generation);
+ const isCurrent = (): boolean =>
+ isLoginRequestCurrent(kind, loginGeneration) && isMutationCurrent(kind, generation);
+ const progressText = { stdout: '', stderr: '', other: '' };
+ let emittedDeviceCode = '';
const result = await maker.triggerAgentLogin(kind, {
+ mode,
onProgress: (msg) => {
- if (isCurrent()) {
- broadcast(MAKER_PUSH.AUTH_LOGIN_PROGRESS, toLoginProgressPayload(kind, msg));
- }
+ if (!isCurrent()) return;
+ broadcast(MAKER_PUSH.AUTH_LOGIN_PROGRESS, toLoginProgressPayload(kind, msg, mode));
+ if (kind !== 'codex' || mode !== 'device-code') return;
+
+ const stream = progressStream(msg);
+ progressText[stream] = (progressText[stream] + progressDetail(msg)).slice(
+ -MAX_LOGIN_PROGRESS_CHARS,
+ );
+ // stdout / stderr 是互相独立的字节流,只在两条流之间加分隔;同一流的
+ // data chunk 必须原样拼接,chunk 边界可能恰好落在 URL 或设备码中间。
+ const deviceCode = parseCodexDeviceCodeProgress(
+ [progressText.stdout, progressText.stderr, progressText.other].join('\n'),
+ );
+ if (!deviceCode) return;
+ const signature = `${deviceCode.verificationUrl}\n${deviceCode.userCode}`;
+ if (signature === emittedDeviceCode) return;
+ emittedDeviceCode = signature;
+ const payload: CodexDeviceCodeProgressPayload = {
+ agentKind: kind,
+ phase: 'device-code',
+ mode,
+ ...deviceCode,
+ };
+ operation.latestDeviceCodeProgress = payload;
+ broadcast(MAKER_PUSH.AUTH_LOGIN_PROGRESS, payload);
},
});
- if (!isCurrent()) return supersededAuthState();
+ // Adapter 已返回 OAuth 成功后,pending login 会被清掉;若 Cancel 落在后续模型刷新/
+ // bridge 收口阶段,只有 handler 能再建立 durable disconnect。Adapter 自己返回
+ // login_cancelled 的路径已在 finalize 内完成必要清理,不能重复 logout。
+ operation.requiresDurableDisconnect = result.authenticated && result.authSource === 'oauth';
+ if (!isCurrent()) return invalidatedState();
if (kind === 'codex' && result.authenticated && result.authSource === 'oauth') {
let liveModelsApplied = false;
try {
@@ -81,31 +315,227 @@ export function registerMakerAuthHandlers(
`codex live model refresh threw during login: ${e instanceof Error ? e.message : String(e)}`,
);
}
- if (!isCurrent()) return supersededAuthState();
+ if (!isCurrent()) return invalidatedState();
await onCodexAuthChange?.(true, liveModelsApplied, isCurrent);
- if (!isCurrent()) return supersededAuthState();
+ if (!isCurrent()) return invalidatedState();
}
broadcast(MAKER_PUSH.AUTH_STATE_CHANGED, { agentKind: kind, ...result });
return result;
+ };
+
+ const cancelLoginOperation = (
+ kind: AgentKind,
+ operation: ActiveLoginOperation,
+ ): Promise<void> => {
+ if (operation.cancellation) return operation.cancellation;
+ if (operation.settledFlag || activeLoginOperations.get(kind) !== operation) {
+ return Promise.resolve();
+ }
+
+ operation.acceptingOwners = false;
+ const cancellation = (async (): Promise<void> => {
+ // Cancel is an auth mutation too: invalidate handler-level refresh/finalization work even
+ // when the CLI process has already exited and the adapter is reconciling credentials. The
+ // separate login request generation also covers a request still queued behind logout.
+ beginLoginCancellation(kind);
+ const loginGeneration = beginLoginRequest(kind);
+ const generation = beginMutation(kind);
+ const isCurrent = (): boolean =>
+ isLoginRequestCurrent(kind, loginGeneration) && isMutationCurrent(kind, generation);
+ maker.cancelAgentLogin(kind);
+
+ // 等被取消 handler 完全退出(含 adapter finalize / model refresh checkpoint),再建立
+ // 唯一的取消收口边界。否则旧 handler 可能在这次清理之后迟到写回缓存或成功广播。
+ await operation.settled;
+ if (!isCurrent()) return;
+ if (kind === 'codex') {
+ if (operation.requiresDurableDisconnect) {
+ try {
+ // Cancel 可能落在 adapter 已返回成功、handler 正刷新模型的窗口;此时 adapter 的
+ // cancelLogin 已无 pending process,必须显式走 durable logout 才不会留下新 token。
+ await maker.logoutAgent(kind);
+ } catch (err) {
+ // 登录调用已经因 generation 作废并向其调用方返回 cancelled;durable logout
+ // 若失败,不能让其它观察窗口继续相信“已断开”。重读 Maker 权威状态并广播,
+ // renderer 的显式 cancel 路径也会重读一次,以覆盖广播丢失/订阅尚未就绪。
+ try {
+ const authoritative = await maker.getAgentAuthState(kind);
+ if (isCurrent()) {
+ broadcast(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: kind,
+ ...authoritative,
+ });
+ }
+ } catch (stateErr) {
+ log.warn(
+ `failed to reconcile auth after cancellation cleanup error: ${
+ stateErr instanceof Error ? stateErr.message : String(stateErr)
+ }`,
+ );
+ }
+ throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ }
+ }
+ if (!isCurrent()) return;
+ await onCodexAuthChange?.(false, false, isCurrent);
+ }
+ if (!isCurrent()) return;
+ broadcast(MAKER_PUSH.AUTH_STATE_CHANGED, {
+ agentKind: kind,
+ ...cancelledAuthState(),
+ });
+ })();
+ operation.cancellation = cancellation;
+ return cancellation;
+ };
+
+ function handleRendererDestroyed(sender: RendererSender): void {
+ const subscription = senderOwners.get(sender);
+ if (!subscription) return;
+ const affected = new Map<ActiveLoginOperation, AgentKind>();
+ for (const ownerId of [...subscription.ownerIds]) {
+ const owner = removeLoginOwner(ownerId, sender);
+ if (owner) affected.set(owner.operation, owner.kind);
+ }
+ for (const [operation, kind] of affected) {
+ if (
+ !operation.settledFlag &&
+ !operation.hasUnmanagedOwner &&
+ operation.ownerIds.size === 0 &&
+ activeLoginOperations.get(kind) === operation
+ ) {
+ void cancelLoginOperation(kind, operation).catch((err) => {
+ log.warn('failed to cancel login after renderer destruction', {
+ agentKind: kind,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
+ }
+ }
+ }
+
+ registry.handle(MAKER_INVOKE.AUTH_GET_STATE, async (_e, agentKind: unknown): Promise<AuthState> => {
+ return maker.getAgentAuthState(requireAgentKind(agentKind));
});
- registry.handle(MAKER_INVOKE.AUTH_CANCEL_LOGIN, async (_e, agentKind: unknown): Promise<void> => {
- maker.cancelAgentLogin(requireAgentKind(agentKind));
+ // presence-only:只回「有没有配 key」,绝不回密钥本体。device-link 控制端(手机 / 远程桌面)
+ // 用它决定折扣版(codex/)行是否置灰 —— key 与请求都在被控端,这里才是判定真相。
+ registry.handle(MAKER_INVOKE.API_KEY_PRESENT, async (): Promise<{ present: boolean }> => {
+ return { present: !!readApiKey() };
+ });
+
+ registry.handle(
+ MAKER_INVOKE.AUTH_TRIGGER_LOGIN,
+ async (event, agentKind: unknown, rawOptions?: unknown): Promise<AuthState> => {
+ const kind = requireAgentKind(agentKind);
+ const { mode, ownerId } = requireLoginOptions(kind, rawOptions);
+ const sender = rendererSender(event);
+ const current = activeLoginOperations.get(kind);
+ if (current?.acceptingOwners && !current.settledFlag && current.mode === mode) {
+ registerLoginOwner(kind, current, sender, ownerId);
+ // Device URL/code may have been emitted before this BrowserWindow joined the shared
+ // operation. Re-broadcast the retained payload so the late caller can render and finish it.
+ if (current.latestDeviceCodeProgress) {
+ broadcast(MAKER_PUSH.AUTH_LOGIN_PROGRESS, current.latestDeviceCodeProgress);
+ }
+ return current.promise;
+ }
+
+ // 不同模式交给 adapter 串行切换,但 main 层必须建立新的 operation 边界;旧调用方
+ // 会按 generation 得到 superseded/cancelled,新调用方不会复用旧模式结果。
+ let settleOperation!: () => void;
+ const activeOperation: ActiveLoginOperation = {
+ mode,
+ promise: null as unknown as Promise<AuthState>,
+ settled: new Promise<void>((resolve) => {
+ settleOperation = resolve;
+ }),
+ requiresDurableDisconnect: false,
+ acceptingOwners: true,
+ settledFlag: false,
+ ownerIds: new Set(),
+ hasUnmanagedOwner: false,
+ };
+ registerLoginOwner(kind, activeOperation, sender, ownerId);
+ if (current) current.acceptingOwners = false;
+ activeLoginOperations.set(kind, activeOperation);
+ const run = runLoginOperation(kind, mode, activeOperation).finally(() => {
+ activeOperation.acceptingOwners = false;
+ activeOperation.settledFlag = true;
+ clearOperationOwners(activeOperation);
+ if (activeLoginOperations.get(kind) === activeOperation) {
+ activeLoginOperations.delete(kind);
+ }
+ settleOperation();
+ });
+ activeOperation.promise = run;
+ return run;
+ },
+ );
+
+ registry.handle(MAKER_INVOKE.AUTH_CANCEL_LOGIN, async (
+ event,
+ agentKind: unknown,
+ rawOptions?: unknown,
+ ): Promise<void> => {
+ const kind = requireAgentKind(agentKind);
+ const { releaseOwner, ownerId } = requireCancelOptions(rawOptions);
+ if (releaseOwner) {
+ if (kind !== 'codex') {
+ throwIpcError('INVALID_PARAMS', 'owner release is only supported by codex');
+ }
+ const sender = rendererSender(event);
+ if (!sender) throwIpcError('INVALID_PARAMS', 'owner release requires an Electron sender');
+ const owner = removeLoginOwner(ownerId!, sender);
+ if (!owner) return;
+ const operation = owner.operation;
+ if (
+ operation.hasUnmanagedOwner ||
+ operation.ownerIds.size > 0 ||
+ operation.settledFlag ||
+ activeLoginOperations.get(kind) !== operation
+ ) {
+ return;
+ }
+ await cancelLoginOperation(kind, operation);
+ return;
+ }
+
+ // 显式“取消”保持既有语义:用户要求终止当前全局 CLI 登录。
+ clearOwnersForKind(kind);
+ const activeOperation = activeLoginOperations.get(kind);
+ // 无在途登录的迟到 Cancel 是彻底的 no-op:既不能翻转已认证状态,也不能推进
+ // generation 后误作废正在收尾的 logout。
+ if (!activeOperation) return;
+ await cancelLoginOperation(kind, activeOperation);
});
registry.handle(MAKER_INVOKE.AUTH_LOGOUT, async (_e, agentKind: unknown): Promise<void> => {
const kind = requireAgentKind(agentKind);
+ const activeOperation = activeLoginOperations.get(kind);
+ if (activeOperation) activeOperation.acceptingOwners = false;
+ clearOwnersForKind(kind);
const generation = beginMutation(kind);
const isCurrent = (): boolean => isMutationCurrent(kind, generation);
+ const finalization = (async (): Promise<void> => {
+ try {
+ await maker.logoutAgent(kind);
+ } catch (err) {
+ throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ }
+ if (!isCurrent()) return;
+ if (kind === 'codex') await onCodexAuthChange?.(false, false, isCurrent);
+ if (!isCurrent()) return;
+ broadcast(MAKER_PUSH.AUTH_STATE_CHANGED, { agentKind: kind, authenticated: false });
+ })();
+ logoutFinalizations.set(kind, finalization);
try {
- await maker.logoutAgent(kind);
- } catch (err) {
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ await finalization;
+ } finally {
+ if (logoutFinalizations.get(kind) === finalization) {
+ logoutFinalizations.delete(kind);
+ }
}
- if (!isCurrent()) return;
- if (kind === 'codex') await onCodexAuthChange?.(false, false, isCurrent);
- if (!isCurrent()) return;
- broadcast(MAKER_PUSH.AUTH_STATE_CHANGED, { agentKind: kind, authenticated: false });
});
}
@@ -114,17 +544,93 @@ function supersededAuthState(): AuthState {
return { authenticated: false, errorReason: 'auth_mutation_superseded' };
}
+function cancelledAuthState(): AuthState {
+ return { authenticated: false, errorReason: 'login_cancelled' };
+}
+
function requireAgentKind(value: unknown): AgentKind {
return requireEnum(value, AGENT_KINDS, 'agentKind');
}
-function toLoginProgressPayload(agentKind: AgentKind, msg: string): Record<string, unknown> {
+function requireLoginOptions(
+ agentKind: AgentKind,
+ value: unknown,
+): { mode: AgentLoginMode; ownerId?: string } {
+ const options = value === undefined ? {} : requireObject(value, 'options');
+ const mode = optionalEnum(options.mode, AGENT_LOGIN_MODES, 'login mode') ?? 'browser';
+ if (agentKind !== 'codex' && mode === 'device-code') {
+ throwIpcError('INVALID_PARAMS', 'device-code login is only supported by codex');
+ }
+ const ownerId = requireLoginOwnerId(options.ownerId);
+ if (agentKind !== 'codex' && ownerId) {
+ throwIpcError('INVALID_PARAMS', 'ownerId is only supported by codex');
+ }
+ return { mode, ownerId };
+}
+
+function requireCancelOptions(
+ value: unknown,
+): { releaseOwner: boolean; ownerId?: string } {
+ if (value === undefined) return { releaseOwner: false };
+ const options = requireObject(value, 'options');
+ if (options.releaseOwner !== undefined && typeof options.releaseOwner !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'releaseOwner must be a boolean');
+ }
+ const releaseOwner = options.releaseOwner === true;
+ const ownerId = requireLoginOwnerId(options.ownerId, releaseOwner);
+ if (!releaseOwner && ownerId) {
+ throwIpcError('INVALID_PARAMS', 'ownerId requires releaseOwner');
+ }
+ return { releaseOwner, ownerId };
+}
+
+function requireLoginOwnerId(value: unknown, required = false): string | undefined {
+ if (value === undefined) {
+ if (required) throwIpcError('INVALID_PARAMS', 'ownerId is required');
+ return undefined;
+ }
+ if (typeof value !== 'string' || !LOGIN_OWNER_ID_PATTERN.test(value)) {
+ throwIpcError('INVALID_PARAMS', 'ownerId must be a valid opaque login owner token');
+ }
+ return value;
+}
+
+function rendererSender(event: unknown): RendererSender | null {
+ if (!event || typeof event !== 'object') return null;
+ const sender = (event as { sender?: unknown }).sender;
+ if (!sender || typeof sender !== 'object') return null;
+ const id = (sender as { id?: unknown }).id;
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0) return null;
+ const once = (sender as { once?: unknown }).once;
+ const removeListener = (sender as { removeListener?: unknown }).removeListener;
+ if (once !== undefined && typeof once !== 'function') return null;
+ if (removeListener !== undefined && typeof removeListener !== 'function') return null;
+ return sender as RendererSender;
+}
+
+function progressDetail(msg: string): string {
+ if (msg.startsWith('stdout:')) return stripAnsi(msg.slice('stdout:'.length));
+ if (msg.startsWith('stderr:')) return stripAnsi(msg.slice('stderr:'.length));
+ return stripAnsi(msg);
+}
+
+function progressStream(msg: string): 'stdout' | 'stderr' | 'other' {
+ if (msg.startsWith('stdout:')) return 'stdout';
+ if (msg.startsWith('stderr:')) return 'stderr';
+ return 'other';
+}
+
+function toLoginProgressPayload(
+ agentKind: AgentKind,
+ msg: string,
+ mode: AgentLoginMode,
+): Record<string, unknown> {
// Codex CLI 会把 OAuth URL 打到 stdout/stderr,两路都归一成 login-pending。
if (msg.startsWith('stdout:')) {
- return { agentKind, phase: 'login-pending', detail: msg.slice('stdout:'.length) };
+ return { agentKind, phase: 'login-pending', mode, detail: progressDetail(msg).trim() };
}
if (msg.startsWith('stderr:')) {
- return { agentKind, phase: 'login-pending', detail: msg.slice('stderr:'.length) };
+ return { agentKind, phase: 'login-pending', mode, detail: progressDetail(msg).trim() };
}
- return { agentKind, phase: msg };
+ return { agentKind, phase: stripAnsi(msg), mode };
}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index a737854b35..d0b26f2ecc 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -380,8 +380,8 @@ export const MAKER_INVOKE = {
*/
PROVIDER_LIST: 'maker:provider:list',
/**
- * 自定义模型供应商 CRUD(配置入 localDb,密钥另走通用 safe-storage IPC)。
- * create/update 入参 = CustomProviderConfig;delete 入参 = providerId。
+ * 自定义模型供应商 CRUD(配置入 localDb;update 的 runtime 密钥与配置原子排队)。
+ * create/update 入参 = config + runtimeKeys;delete 入参 = providerId。
* 成功后 main 重算 active-catalog 并广播 PROVIDER_CHANGED(见 MAKER_PUSH)。
*/
PROVIDER_CUSTOM_CREATE: 'maker:provider:custom:create',
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index a1f5b75921..7fd694cbab 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -2,19 +2,20 @@
* provider:* IPC handlers。
*
* - PROVIDER_LIST(只读:目录元数据 + 各供应商实时连接状态)。
- * - PROVIDER_CUSTOM_CREATE / UPDATE / DELETE(自定义供应商**配置** CRUD,配置入 localDb)。
+ * - PROVIDER_CUSTOM_CREATE / UPDATE / DELETE(自定义供应商配置 + API key CRUD)。
*
* 内置三家(Anthropic / OpenAI / XD)的「连接 / 断开」**复用各 agent 已有的鉴权通道**,不另立通道。
* 自定义供应商用 CRUD 替代连接/断开。
*
- * 密钥**不经这些 handler**:renderer 用通用 safe-storage IPC 写 `provider_key_<id>`(与
- * XdGatewayKeyDialog 同源),delete 时同样由 renderer 经通用 safe-storage-remove 清密钥。
+ * create / update / delete 的密钥与配置在同一 provider mutation queue 内暂存 / 回滚,
+ * 避免多个窗口并发编辑时出现“配置 A + 密钥 B”或旧回滚覆盖新写入。
*
* 副作用(CRUD 成功后刷新 active-catalog + 广播 PROVIDER_CHANGED)经 deps 注入,
* handler body 可脱 Electron 用 IpcHarness + 内存 db 直接 invoke 单测(规则 14)。
*/
import {
+ isLoopbackProviderUrl,
isProviderRequestPath,
type AgentKind,
type CustomProviderConfig,
@@ -24,6 +25,7 @@ import {
} from '@cindy/model-providers';
import type { LocalCliDetection } from '../../shared/localCliDetect.js';
+import { isIpcError } from '../../shared/ipc-errors.js';
import { createLogger } from '../logger.js';
import { throwIpcError } from '../utils/ipcValidate.js';
@@ -31,6 +33,7 @@ import {
createCustomProvider,
customProviderExists,
deleteCustomProvider,
+ getCustomProvider,
updateCustomProvider,
validateCustomProviderConfig,
} from '../maker-host/custom-provider-store.js';
@@ -45,6 +48,110 @@ import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
const log = createLogger('maker-ipc:provider');
const VALID_AGENTS: readonly string[] = ['claude-code', 'codex'];
+const VALID_ADHOC_AUTH_METHODS: readonly string[] = ['apiKey', 'oauth', 'none'];
+const PROVIDER_OAUTH_OWNER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
+type RuntimeKeys = Partial<Record<AgentKind, string>>;
+
+type ProviderOAuthRendererSender = {
+ readonly id: number;
+ once?: (event: 'destroyed', listener: () => void) => unknown;
+ removeListener?: (event: 'destroyed', listener: () => void) => unknown;
+};
+
+function providerOAuthOptions(value: unknown): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throwIpcError('INVALID_PARAMS', 'provider OAuth options must be an object');
+ }
+ return value as Record<string, unknown>;
+}
+
+function requireProviderOAuthOwnerId(value: unknown, required = false): string | undefined {
+ if (value === undefined) {
+ if (required) throwIpcError('INVALID_PARAMS', 'ownerId is required');
+ return undefined;
+ }
+ if (typeof value !== 'string' || !PROVIDER_OAUTH_OWNER_ID_PATTERN.test(value)) {
+ throwIpcError('INVALID_PARAMS', 'ownerId must be a valid opaque OAuth owner token');
+ }
+ return value;
+}
+
+function requireProviderOAuthLoginOptions(value: unknown): { ownerId?: string } {
+ if (value === undefined) return {};
+ const options = providerOAuthOptions(value);
+ return { ownerId: requireProviderOAuthOwnerId(options.ownerId) };
+}
+
+function requireProviderOAuthCancelOptions(
+ value: unknown,
+): { releaseOwner: boolean; ownerId?: string } {
+ if (value === undefined) return { releaseOwner: false };
+ const options = providerOAuthOptions(value);
+ if (options.releaseOwner !== undefined && typeof options.releaseOwner !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'releaseOwner must be a boolean');
+ }
+ const releaseOwner = options.releaseOwner === true;
+ const ownerId = requireProviderOAuthOwnerId(options.ownerId, releaseOwner);
+ if (!releaseOwner && ownerId) {
+ throwIpcError('INVALID_PARAMS', 'ownerId requires releaseOwner');
+ }
+ return { releaseOwner, ownerId };
+}
+
+function providerOAuthRendererSender(event: unknown): ProviderOAuthRendererSender | null {
+ if (!event || typeof event !== 'object') return null;
+ const sender = (event as { sender?: unknown }).sender;
+ if (!sender || typeof sender !== 'object') return null;
+ const id = (sender as { id?: unknown }).id;
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0) return null;
+ const once = (sender as { once?: unknown }).once;
+ const removeListener = (sender as { removeListener?: unknown }).removeListener;
+ if (once !== undefined && typeof once !== 'function') return null;
+ if (removeListener !== undefined && typeof removeListener !== 'function') return null;
+ return sender as ProviderOAuthRendererSender;
+}
+
+function parseRuntimeKeys(input: unknown): RuntimeKeys | null {
+ if (input === undefined) return {};
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
+ const entries = Object.entries(input as Record<string, unknown>);
+ if (
+ entries.some(([agent, value]) => !VALID_AGENTS.includes(agent) || typeof value !== 'string')
+ ) return null;
+ return Object.fromEntries(entries) as RuntimeKeys;
+}
+
+function sortedStringRecord(value: Record<string, string> | undefined): Record<string, string> | undefined {
+ if (!value) return undefined;
+ return Object.fromEntries(
+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b)),
+ );
+}
+
+function oauthDescriptorSignature(config: CustomProviderConfig | null): string | null {
+ if (config?.auth?.method !== 'oauth') return null;
+ const oauth = config.auth.oauth;
+ const common = {
+ tokenUrl: oauth.tokenUrl,
+ clientId: oauth.clientId,
+ scopes: oauth.scopes,
+ modelsDiscoveryUrl: oauth.modelsDiscoveryUrl,
+ };
+ return oauth.flow === 'device-code'
+ ? JSON.stringify({
+ ...common,
+ flow: 'device-code',
+ deviceAuthorizationUrl: oauth.deviceAuthorizationUrl,
+ extraDeviceParams: sortedStringRecord(oauth.extraDeviceParams),
+ })
+ : JSON.stringify({
+ ...common,
+ flow: 'authorization-code',
+ authorizeUrl: oauth.authorizeUrl,
+ redirectPort: oauth.redirectPort,
+ extraAuthParams: sortedStringRecord(oauth.extraAuthParams),
+ });
+}
export interface ProviderHandlerDeps {
/**
@@ -63,6 +170,11 @@ export interface ProviderHandlerDeps {
getModelVisibilityOverrides(): Record<string, boolean>;
/** CRUD 成功后重算 active-catalog(生产 = refreshCustomProvidersIntoCatalog)。 */
refreshCatalog(): Promise<void>;
+ /**
+ * 配置、secret 与 active catalog 切换期间暂停该 provider 的新请求;返回幂等 release。
+ * 生产 = beginProviderRouteMutation。
+ */
+ beginRouteMutation(providerId: string): () => void;
/** CRUD 成功后广播变更(生产 = 向所有窗口 send PROVIDER_CHANGED)。 */
broadcastChanged(): void;
/** 目录 presets 段(生产 = () => getActiveCatalog().presets ?? [])。 */
@@ -95,11 +207,30 @@ export interface ProviderHandlerDeps {
* 通用 OAuth 登录 / 登出 / 取消(生产接 generic-oauth Runner + 目录描述符解析;
* login 成功后由生产 deps 负责模型发现与 PROVIDER_CHANGED 广播)。
*/
- oauthLogin(providerId: string): Promise<{ ok: boolean; reason?: string }>;
+ oauthLogin(
+ providerId: string,
+ isCurrent: () => boolean,
+ ): Promise<{
+ ok: boolean;
+ reason?: string;
+ rollbackCredentials?: () => boolean;
+ }>;
oauthLogout(providerId: string): Promise<void>;
oauthCancel(providerId: string): void;
- /** 删除自定义供应商时清理其 OAuth 凭证 blob(生产 = logoutGenericOAuth;幂等)。 */
- clearOAuthCredentials(providerId: string): void;
+ /**
+ * 可回滚地移除 OAuth 凭证。null 表示持久删除失败;返回闭包供配置写失败时恢复旧 blob。
+ */
+ removeOAuthCredentials(providerId: string): (() => boolean) | null;
+ /**
+ * 自定义 provider API key 的严格快照读取:不存在返回 null,不可解密 / 不可读时抛错。
+ * 与配置 CRUD 共用 per-provider mutation queue。
+ */
+ readCustomProviderKeyForMutation(providerId: string, agent: AgentKind): string | null;
+ storeCustomProviderKey(providerId: string, agent: AgentKind, value: string): boolean;
+ removeCustomProviderKey(
+ providerId: string,
+ agent: AgentKind,
+ ): { success: boolean; error?: string };
/**
* 本机 agent CLI 安装 / 登录态扫描(生产 = scanLocalCliAuth(createLocalCliScanDeps());
* 单测注入 stub 不碰真实 home)。只 stat 不读内容(规则 23)。
@@ -121,6 +252,10 @@ function parseTestInput(input: unknown): ProviderTestInput | null {
if (!s || typeof s !== 'object') return null;
const spec = s as Record<string, unknown>;
if (typeof spec.agent !== 'string' || !VALID_AGENTS.includes(spec.agent)) return null;
+ if (
+ typeof spec.authMethod !== 'string'
+ || !VALID_ADHOC_AUTH_METHODS.includes(spec.authMethod)
+ ) return null;
if (typeof spec.baseUrl !== 'string' || spec.baseUrl.length === 0) return null;
try {
const u = new URL(spec.baseUrl);
@@ -128,6 +263,7 @@ function parseTestInput(input: unknown): ProviderTestInput | null {
} catch {
return null;
}
+ if (spec.authMethod === 'none' && !isLoopbackProviderUrl(spec.baseUrl)) return null;
if (typeof spec.modelId !== 'string' || spec.modelId.length === 0) return null;
if (spec.apiKey !== undefined && spec.apiKey !== null && typeof spec.apiKey !== 'string') return null;
if (spec.headers !== undefined) {
@@ -147,6 +283,7 @@ function parseTestInput(input: unknown): ProviderTestInput | null {
agent: spec.agent as AgentKind,
baseUrl: spec.baseUrl,
modelId: spec.modelId,
+ authMethod: spec.authMethod as ProviderProbeSpec['authMethod'],
wireProtocol: spec.wireProtocol as ProviderProbeSpec['wireProtocol'],
requestPath: spec.requestPath as string | undefined,
apiKey: (spec.apiKey as string | null | undefined) ?? null,
@@ -162,6 +299,10 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {
if (!input || typeof input !== 'object') return null;
const spec = input as Record<string, unknown>;
if (typeof spec.agent !== 'string' || !VALID_AGENTS.includes(spec.agent)) return null;
+ if (
+ typeof spec.authMethod !== 'string'
+ || !VALID_ADHOC_AUTH_METHODS.includes(spec.authMethod)
+ ) return null;
if (typeof spec.baseUrl !== 'string' || spec.baseUrl.length === 0) return null;
const httpUrlOk = (v: string): boolean => {
try {
@@ -175,6 +316,17 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {
if (spec.modelsUrl !== undefined && spec.modelsUrl !== null) {
if (typeof spec.modelsUrl !== 'string' || !httpUrlOk(spec.modelsUrl)) return null;
}
+ if (
+ spec.authMethod === 'none'
+ && (
+ !isLoopbackProviderUrl(spec.baseUrl)
+ || (
+ typeof spec.modelsUrl === 'string'
+ && spec.modelsUrl.trim().length > 0
+ && !isLoopbackProviderUrl(spec.modelsUrl)
+ )
+ )
+ ) return null;
if (spec.apiKey !== undefined && spec.apiKey !== null && typeof spec.apiKey !== 'string') return null;
if (spec.headers !== undefined) {
if (!spec.headers || typeof spec.headers !== 'object' || Array.isArray(spec.headers)) return null;
@@ -183,6 +335,7 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {
return {
agent: spec.agent as AgentKind,
baseUrl: spec.baseUrl,
+ authMethod: spec.authMethod as ProviderModelsFetchSpec['authMethod'],
modelsUrl: (spec.modelsUrl as string | null | undefined) ?? null,
apiKey: (spec.apiKey as string | null | undefined) ?? null,
headers: spec.headers as Record<string, string> | undefined,
@@ -193,6 +346,208 @@ export function registerProviderHandlers(
registry: IpcHandlerRegistry,
deps: ProviderHandlerDeps,
): void {
+ const oauthMutationGeneration = new Map<string, symbol>();
+ const beginOAuthMutation = (providerId: string): symbol => {
+ // Unique token avoids ABA when a completed entry is deleted and the same provider starts again.
+ const generation = Symbol(providerId);
+ oauthMutationGeneration.set(providerId, generation);
+ return generation;
+ };
+ const isOAuthMutationCurrent = (providerId: string, generation: symbol): boolean =>
+ oauthMutationGeneration.get(providerId) === generation;
+ const finishOAuthMutation = (providerId: string, generation: symbol): void => {
+ if (isOAuthMutationCurrent(providerId, generation)) {
+ oauthMutationGeneration.delete(providerId);
+ }
+ };
+ type ProviderOAuthOwner = {
+ providerId: string;
+ generation: symbol;
+ sender: ProviderOAuthRendererSender;
+ };
+ const providerOAuthOwners = new Map<string, ProviderOAuthOwner>();
+ const providerOAuthSenderOwners = new Map<
+ ProviderOAuthRendererSender,
+ { ownerIds: Set<string>; onDestroyed: () => void }
+ >();
+ const removeProviderOAuthOwner = (
+ ownerId: string,
+ expectedSender?: ProviderOAuthRendererSender,
+ expectedOwner?: ProviderOAuthOwner,
+ ): ProviderOAuthOwner | null => {
+ const owner = providerOAuthOwners.get(ownerId);
+ if (
+ !owner
+ || (expectedSender && owner.sender !== expectedSender)
+ || (expectedOwner && owner !== expectedOwner)
+ ) {
+ return null;
+ }
+ providerOAuthOwners.delete(ownerId);
+ const subscription = providerOAuthSenderOwners.get(owner.sender);
+ subscription?.ownerIds.delete(ownerId);
+ if (subscription && subscription.ownerIds.size === 0) {
+ owner.sender.removeListener?.('destroyed', subscription.onDestroyed);
+ providerOAuthSenderOwners.delete(owner.sender);
+ }
+ return owner;
+ };
+ const cancelOwnedProviderOAuth = (owner: ProviderOAuthOwner): void => {
+ if (!isOAuthMutationCurrent(owner.providerId, owner.generation)) return;
+ const cancellationGeneration = beginOAuthMutation(owner.providerId);
+ try {
+ deps.oauthCancel(owner.providerId);
+ } catch (err) {
+ log.warn('failed to cancel owned provider OAuth login during teardown', {
+ providerId: owner.providerId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ finishOAuthMutation(owner.providerId, cancellationGeneration);
+ }
+ };
+ const handleProviderOAuthRendererDestroyed = (
+ sender: ProviderOAuthRendererSender,
+ ): void => {
+ const subscription = providerOAuthSenderOwners.get(sender);
+ if (!subscription) return;
+ for (const ownerId of [...subscription.ownerIds]) {
+ const owner = removeProviderOAuthOwner(ownerId, sender);
+ if (owner) cancelOwnedProviderOAuth(owner);
+ }
+ };
+ const registerProviderOAuthOwner = (
+ providerId: string,
+ generation: symbol,
+ sender: ProviderOAuthRendererSender,
+ ownerId: string,
+ ): ProviderOAuthOwner => {
+ if (providerOAuthOwners.has(ownerId)) {
+ throwIpcError('INVALID_PARAMS', 'ownerId is already bound to another OAuth operation');
+ }
+ let subscription = providerOAuthSenderOwners.get(sender);
+ if (!subscription) {
+ const onDestroyed = (): void => handleProviderOAuthRendererDestroyed(sender);
+ subscription = { ownerIds: new Set(), onDestroyed };
+ providerOAuthSenderOwners.set(sender, subscription);
+ sender.once?.('destroyed', onDestroyed);
+ }
+ const owner = { providerId, generation, sender };
+ subscription.ownerIds.add(ownerId);
+ providerOAuthOwners.set(ownerId, owner);
+ return owner;
+ };
+ const clearProviderOAuthOwners = (providerId: string): void => {
+ for (const [ownerId, owner] of [...providerOAuthOwners]) {
+ if (owner.providerId === providerId) removeProviderOAuthOwner(ownerId);
+ }
+ };
+ const providerConfigMutationCounts = new Map<string, number>();
+ const providerConfigMutationTails = new Map<string, Promise<void>>();
+ const beginProviderConfigMutation = (providerId: string): void => {
+ providerConfigMutationCounts.set(
+ providerId,
+ (providerConfigMutationCounts.get(providerId) ?? 0) + 1,
+ );
+ };
+ const finishProviderConfigMutation = (providerId: string): void => {
+ const remaining = (providerConfigMutationCounts.get(providerId) ?? 1) - 1;
+ if (remaining <= 0) providerConfigMutationCounts.delete(providerId);
+ else providerConfigMutationCounts.set(providerId, remaining);
+ };
+ const withProviderConfigMutation = async <T>(
+ providerId: string,
+ operation: () => Promise<T>,
+ ): Promise<T> => {
+ const finishRouteMutation = deps.beginRouteMutation(providerId);
+ const previous = providerConfigMutationTails.get(providerId) ?? Promise.resolve();
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const tail = previous.catch(() => undefined).then(() => gate);
+ providerConfigMutationTails.set(providerId, tail);
+ // 排队时即计入 mutation,避免等待前序写入期间启动新的 OAuth flow。
+ beginProviderConfigMutation(providerId);
+ try {
+ await previous.catch(() => undefined);
+ return await operation();
+ } finally {
+ release();
+ if (providerConfigMutationTails.get(providerId) === tail) {
+ providerConfigMutationTails.delete(providerId);
+ }
+ finishProviderConfigMutation(providerId);
+ finishRouteMutation();
+ }
+ };
+ type KeySnapshot = { agent: AgentKind; previous: string | null };
+ type KeyMutation = { agent: AgentKind; replacement: string | null };
+ const restoreProviderKeys = (
+ providerId: string,
+ snapshots: readonly KeySnapshot[],
+ ): boolean => {
+ let restored = true;
+ for (const { agent, previous } of [...snapshots].reverse()) {
+ if (previous !== null) {
+ if (!deps.storeCustomProviderKey(providerId, agent, previous)) restored = false;
+ } else if (!deps.removeCustomProviderKey(providerId, agent).success) {
+ restored = false;
+ }
+ }
+ return restored;
+ };
+ const planProviderKeyMutations = (
+ config: CustomProviderConfig,
+ keys: RuntimeKeys,
+ mode: 'create' | 'update',
+ ): KeyMutation[] => {
+ const mutations: KeyMutation[] = [];
+ const usesApiKey = !config.auth || config.auth.method === 'apiKey';
+ for (const agent of VALID_AGENTS as readonly AgentKind[]) {
+ const replacement = keys[agent]?.trim();
+ if (mode === 'create') {
+ if (usesApiKey && config.runtimes[agent] && replacement) {
+ mutations.push({ agent, replacement });
+ }
+ continue;
+ }
+ const shouldRemove = !usesApiKey || !config.runtimes[agent];
+ if (shouldRemove) mutations.push({ agent, replacement: null });
+ else if (replacement) mutations.push({ agent, replacement });
+ }
+ return mutations;
+ };
+ const stageProviderKeys = (
+ providerId: string,
+ mutations: readonly KeyMutation[],
+ ): KeySnapshot[] => {
+ const snapshots: KeySnapshot[] = [];
+ try {
+ for (const { agent, replacement } of mutations) {
+ let previous: string | null;
+ try {
+ previous = deps.readCustomProviderKeyForMutation(providerId, agent);
+ } catch {
+ throwIpcError('INTERNAL', `failed to read existing ${agent} provider credential`);
+ }
+ snapshots.push({ agent, previous });
+ const succeeded = replacement === null
+ ? deps.removeCustomProviderKey(providerId, agent).success
+ : deps.storeCustomProviderKey(providerId, agent, replacement);
+ if (!succeeded) {
+ throwIpcError('INTERNAL', `failed to update ${agent} provider credential`);
+ }
+ }
+ return snapshots;
+ } catch (error) {
+ if (!restoreProviderKeys(providerId, snapshots)) {
+ throwIpcError('INTERNAL', 'provider credential update failed and could not be rolled back');
+ }
+ throw error;
+ }
+ };
+
// 只读聚合:loadCatalog 永不抛(最差回退内置目录),故无需 throwIpcError 包裹。
registry.handle(
MAKER_INVOKE.PROVIDER_LIST,
@@ -216,37 +571,154 @@ export function registerProviderHandlers(
deps.broadcastChanged();
}
- registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, async (_event, input: unknown) => {
+ function assertTrustedProviderMutationSender(event: unknown): void {
+ if (!deps.assertTrustedSender) {
+ throwIpcError('PERMISSION_DENIED', 'sender trust guard unavailable');
+ }
+ deps.assertTrustedSender(event);
+ }
+
+ registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, async (event, input: unknown, keyInput?: unknown) => {
+ assertTrustedProviderMutationSender(event);
const v = validateCustomProviderConfig(input);
if (!v.ok) throwIpcError(v.code, v.message);
+ const keys = parseRuntimeKeys(keyInput);
+ if (!keys) throwIpcError('INVALID_PARAMS', 'invalid provider runtime keys');
const config = input as CustomProviderConfig;
- if (await customProviderExists(config.id)) {
- throwIpcError('ALREADY_EXISTS', `custom provider '${config.id}' already exists`);
- }
- await createCustomProvider(config);
- await afterChange();
- return { ok: true };
+ return withProviderConfigMutation(config.id, async () => {
+ if (await customProviderExists(config.id)) {
+ throwIpcError('ALREADY_EXISTS', `custom provider '${config.id}' already exists`);
+ }
+ const keySnapshots = stageProviderKeys(
+ config.id,
+ planProviderKeyMutations(config, keys, 'create'),
+ );
+ try {
+ await createCustomProvider(config);
+ } catch (error) {
+ if (!restoreProviderKeys(config.id, keySnapshots)) {
+ throwIpcError(
+ 'INTERNAL',
+ 'provider creation failed and credentials could not be rolled back',
+ );
+ }
+ throw error;
+ }
+ await afterChange();
+ return { ok: true };
+ });
});
- registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, async (_event, input: unknown) => {
+ registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, async (event, input: unknown, keyInput?: unknown) => {
+ assertTrustedProviderMutationSender(event);
const v = validateCustomProviderConfig(input);
if (!v.ok) throwIpcError(v.code, v.message);
+ const keys = parseRuntimeKeys(keyInput);
+ if (!keys) throwIpcError('INVALID_PARAMS', 'invalid provider runtime keys');
const config = input as CustomProviderConfig;
- const updated = await updateCustomProvider(config.id, config);
- if (!updated) throwIpcError('NOT_FOUND', `custom provider '${config.id}' not found`);
- await afterChange();
- return { ok: true };
+ return withProviderConfigMutation(config.id, async () => {
+ let generation: symbol | null = null;
+ try {
+ const previous = await getCustomProvider(config.id);
+ if (!previous) throwIpcError('NOT_FOUND', `custom provider '${config.id}' not found`);
+ // 即便 OAuth 描述符没变,runtime / model 编辑也必须让旧登录尾部的自动发现失效,
+ // 否则旧 endpoint 的迟到结果可能合并进刚保存的新配置。
+ generation = beginOAuthMutation(config.id);
+ const shouldResetOAuth =
+ config.auth?.method !== 'oauth'
+ || oauthDescriptorSignature(previous) !== oauthDescriptorSignature(config);
+ // API key 的写 / 删与配置更新处于同一 main 队列;若后续 OAuth 清理或 DB 写失败,
+ // 用原值回滚,确保并发窗口不能把另一份配置和密钥拼在一起。
+ const keySnapshots = stageProviderKeys(
+ config.id,
+ planProviderKeyMutations(config, keys, 'update'),
+ );
+ // 先阻止在途 flow 写回,再改描述符;否则旧 flow 可能在 clear 后迟到落一枚旧 token。
+ if (shouldResetOAuth) deps.oauthCancel(config.id);
+ // 旧 client / endpoint 下签发的 token 不能沿用到新 OAuth 描述符;切到 API key /
+ // 无鉴权时也清掉不再可达的 blob。删除失败时必须在配置变更前中止,避免重启后
+ // 旧 token 被新 client / endpoint 重新激活。
+ let restoreOAuthCredentials: (() => boolean) | null = null;
+ let updated: CustomProviderConfig | null;
+ try {
+ if (shouldResetOAuth) {
+ restoreOAuthCredentials = deps.removeOAuthCredentials(config.id);
+ if (!restoreOAuthCredentials) {
+ throwIpcError('INTERNAL', 'failed to remove existing OAuth credentials');
+ }
+ }
+ updated = await updateCustomProvider(config.id, config);
+ } catch (err) {
+ const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
+ const keysRestored = restoreProviderKeys(config.id, keySnapshots);
+ if (!oauthRestored || !keysRestored) {
+ throwIpcError(
+ 'INTERNAL',
+ 'provider update failed and existing credentials could not be restored',
+ );
+ }
+ throw err;
+ }
+ if (!updated) {
+ const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
+ const keysRestored = restoreProviderKeys(config.id, keySnapshots);
+ if (!oauthRestored || !keysRestored) {
+ throwIpcError(
+ 'INTERNAL',
+ 'provider disappeared during update and existing credentials could not be restored',
+ );
+ }
+ throwIpcError('NOT_FOUND', `custom provider '${config.id}' not found`);
+ }
+ await afterChange();
+ return { ok: true };
+ } finally {
+ if (generation !== null) finishOAuthMutation(config.id, generation);
+ }
+ });
});
- registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, async (_event, providerId: unknown) => {
+ registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, async (event, providerId: unknown) => {
+ assertTrustedProviderMutationSender(event);
if (typeof providerId !== 'string' || providerId.length === 0) {
throwIpcError('INVALID_PARAMS', 'providerId required');
}
- await deleteCustomProvider(providerId);
- // OAuth 形态自定义供应商的凭证 blob 一并清掉(apiKey 形态无 blob,幂等无害)。
- deps.clearOAuthCredentials(providerId);
- await afterChange();
- return { ok: true };
+ return withProviderConfigMutation(providerId, async () => {
+ const generation = beginOAuthMutation(providerId);
+ try {
+ deps.oauthCancel(providerId);
+ const keySnapshots = stageProviderKeys(
+ providerId,
+ (VALID_AGENTS as readonly AgentKind[]).map((agent) => ({
+ agent,
+ replacement: null,
+ })),
+ );
+ // OAuth 形态自定义供应商的凭证 blob 一并清掉(apiKey 形态无 blob,幂等无害)。
+ let restoreOAuthCredentials: (() => boolean) | null = null;
+ try {
+ restoreOAuthCredentials = deps.removeOAuthCredentials(providerId);
+ if (!restoreOAuthCredentials) {
+ throwIpcError('INTERNAL', 'failed to remove existing OAuth credentials');
+ }
+ await deleteCustomProvider(providerId);
+ } catch (err) {
+ const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
+ const keysRestored = restoreProviderKeys(providerId, keySnapshots);
+ if (!oauthRestored || !keysRestored) {
+ throwIpcError(
+ 'INTERNAL',
+ 'provider deletion failed and existing credentials could not be restored',
+ );
+ }
+ throw err;
+ }
+ await afterChange();
+ return { ok: true };
+ } finally {
+ finishOAuthMutation(providerId, generation);
+ }
+ });
});
// 只读:目录 presets 段(创建对话框「从模板创建」消费)。
@@ -303,10 +775,7 @@ export function registerProviderHandlers(
// 守卫缺席按拒绝处理:可选依赖用 `?.()` 调用时,漏接线会静默退化成「无守卫」,而这种
// 退化没有任何编译期或运行期信号。宁可在接线回归时把功能打死,也不要让它悄悄敞开
// (PR #548 review)。
- if (!deps.assertTrustedSender) {
- throwIpcError('PERMISSION_DENIED', 'sender trust guard unavailable');
- }
- deps.assertTrustedSender(event);
+ assertTrustedProviderMutationSender(event);
const providerId = requireProviderId(input);
let failure: ProviderModelDiscoveryFailure | null;
try {
@@ -324,7 +793,8 @@ export function registerProviderHandlers(
// 与 buildRegistry 的投影同口径:detail 可能是上游原始响应体,不能过 IPC 边界。
// 这是独立于 provider 列表的第二条返回路径,必须各自剥离(PR #548 review)。
if (!failure) return { ok: true };
- const { detail: _detail, ...failureView } = failure;
+ const failureView = { ...failure };
+ delete failureView.detail;
return { ok: false, failure: failureView };
});
@@ -336,21 +806,99 @@ export function registerProviderHandlers(
}
return input;
}
- registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, async (_event, providerId: unknown) => {
+ registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, async (
+ event,
+ providerId: unknown,
+ rawOptions?: unknown,
+ ) => {
const id = requireProviderId(providerId);
+ const { ownerId } = requireProviderOAuthLoginOptions(rawOptions);
+ const sender = providerOAuthRendererSender(event);
+ if (ownerId && !sender) {
+ throwIpcError('INVALID_PARAMS', 'ownerId requires an Electron sender');
+ }
+ if (ownerId && providerOAuthOwners.has(ownerId)) {
+ throwIpcError('INVALID_PARAMS', 'ownerId is already bound to another OAuth operation');
+ }
+ // 更新事务从旧配置读取、写库到 refresh 完成前是一个整体。期间拒绝新登录,避免 runner
+ // 读取旧描述符后在新配置生效时写回旧 client / endpoint 签发的 token。
+ if (providerConfigMutationCounts.has(id)) {
+ return { ok: false, reason: 'provider_update_in_progress' };
+ }
+ const generation = beginOAuthMutation(id);
+ let owner: ProviderOAuthOwner | null = null;
try {
- return await deps.oauthLogin(id);
+ if (ownerId && sender) {
+ owner = registerProviderOAuthOwner(id, generation, sender, ownerId);
+ }
+ const result = await deps.oauthLogin(id, () => isOAuthMutationCurrent(id, generation));
+ if (isOAuthMutationCurrent(id, generation)) {
+ return { ok: result.ok, ...(result.reason ? { reason: result.reason } : {}) };
+ }
+ if (result.ok && result.rollbackCredentials && !result.rollbackCredentials()) {
+ throwIpcError('INTERNAL', 'failed to remove credentials from cancelled OAuth login');
+ }
+ return { ok: false, reason: 'login_cancelled' };
} catch (err) {
+ if (isIpcError(err)) throw err;
throwIpcError('INVALID_PARAMS', err instanceof Error ? err.message : String(err));
+ } finally {
+ if (ownerId && owner) removeProviderOAuthOwner(ownerId, sender ?? undefined, owner);
+ finishOAuthMutation(id, generation);
}
});
registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, async (_event, providerId: unknown) => {
- await deps.oauthLogout(requireProviderId(providerId));
- await afterChange();
- return { ok: true };
+ const id = requireProviderId(providerId);
+ const generation = beginOAuthMutation(id);
+ // Invalidate and stop an active flow immediately, then serialize credential deletion with
+ // config CRUD so a failed earlier update cannot restore a token after this explicit logout.
+ deps.oauthCancel(id);
+ try {
+ return await withProviderConfigMutation(id, async () => {
+ try {
+ await deps.oauthLogout(id);
+ await afterChange();
+ return { ok: true };
+ } catch (err) {
+ throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ }
+ });
+ } finally {
+ finishOAuthMutation(id, generation);
+ }
});
- registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_CANCEL, async (_event, providerId: unknown) => {
- deps.oauthCancel(requireProviderId(providerId));
- return { ok: true };
+ registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_CANCEL, async (
+ event,
+ providerId: unknown,
+ rawOptions?: unknown,
+ ) => {
+ const id = requireProviderId(providerId);
+ const { releaseOwner, ownerId } = requireProviderOAuthCancelOptions(rawOptions);
+ if (releaseOwner) {
+ const sender = providerOAuthRendererSender(event);
+ if (!sender) {
+ throwIpcError('INVALID_PARAMS', 'owner release requires an Electron sender');
+ }
+ const expectedOwner = providerOAuthOwners.get(ownerId!);
+ if (
+ !expectedOwner
+ || expectedOwner.sender !== sender
+ || expectedOwner.providerId !== id
+ ) {
+ return { ok: true };
+ }
+ const owner = removeProviderOAuthOwner(ownerId!, sender, expectedOwner);
+ if (owner) cancelOwnedProviderOAuth(owner);
+ return { ok: true };
+ }
+ clearProviderOAuthOwners(id);
+ const generation = beginOAuthMutation(id);
+ try {
+ deps.oauthCancel(id);
+ return { ok: true };
+ } finally {
+ // Cancel is synchronous; retaining arbitrary renderer-supplied ids here would grow the map forever.
+ finishOAuthMutation(id, generation);
+ }
});
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bdee939b78..ebbe7cb392 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -398,6 +398,7 @@ import {
import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';
import { testProviderConnection } from '../maker-host/provider-diagnostics.js';
import { fetchProviderModels } from '../maker-host/provider-model-fetch.js';
+import { beginProviderRouteMutation } from '../maker-host/provider-route.js';
import {
getAnthropicModelDiscoveryFailure,
refreshAnthropicModelsFromHttp,
@@ -412,15 +413,24 @@ import {
deriveModelsDiscoveryUrl,
discoverGenericOAuthModels,
logoutGenericOAuth,
+ removeGenericOAuthCredentialsReversibly,
runGenericOAuthLogin,
} from '../maker-host/generic-oauth.js';
import {
getCustomProvider,
mergeDiscoveredModelsIntoConfig,
- updateCustomProvider,
+ updateCustomProviderIfUnchanged,
} from '../maker-host/custom-provider-store.js';
+import {
+ readCustomProviderKeyForMutation,
+ removeCustomProviderKey,
+ storeCustomProviderKey,
+} from '../secrets/providerSecretStore.js';
import { setSessionEffort, setSessionFastMode } from '../maker-host/session-effort-store.js';
-import { getModelVisibilityMirrorSnapshot, setModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';
+import {
+ getModelVisibilityMirrorSnapshot,
+ syncModelVisibilityMirror,
+} from '../maker-host/model-visibility-mirror.js';
import { setClaudeProxySessionIdResolver } from '../maker-host/anthropic-compat-proxy-host.js';
import {
clearClaudeSessionBackgroundActivity,
@@ -3466,6 +3476,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
listProviders: (opts) => getDesktopProviderService().listProviders(opts),
getModelVisibilityOverrides: () => getModelVisibilityMirrorSnapshot(),
refreshCatalog: () => refreshCustomProvidersIntoCatalog(),
+ beginRouteMutation: (providerId) => beginProviderRouteMutation(providerId),
broadcastChanged: () => broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {}),
listPresets: () => getActiveCatalog().presets ?? [],
testConnection: (input) => testProviderConnection(input),
@@ -3487,10 +3498,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
scanLocalCli: () => scanLocalCliAuth(createLocalCliScanDeps()),
// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现
// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。
- oauthLogin: async (providerId) => {
+ oauthLogin: async (providerId, isCurrent) => {
const provider = getActiveCatalog().providers.find((p) => p.id === providerId);
const oauth = provider?.auth.oauth;
if (!provider || !oauth) throw new Error(`provider '${providerId}' has no oauth descriptor`);
+ let rollbackCredentials: (() => boolean) | undefined;
const result = await runGenericOAuthLogin(
{ id: provider.id, name: provider.name },
oauth,
@@ -3500,9 +3512,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
providerId,
...progress,
}),
+ onCredentialPersisted: (rollback) => {
+ rollbackCredentials = rollback;
+ },
},
);
- if (result.ok) {
+ if (result.ok && isCurrent()) {
// 授权成功后按 agent 自动发现模型(与内置订阅体验统一,用户不必手填模型):
// 发现端点 = 描述符显式声明 ?? 由该 runtime 的 baseUrl 推导(…/v1/models)。
// 自定义供应商的发现结果 additions-only 持久化进配置(重启后仍在);内置供应商走
@@ -3511,22 +3526,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
const fetched = new Map<string, { id: string; name: string }[] | null>();
let customChanged = false;
for (const agent of provider.agents) {
+ if (!isCurrent()) break;
const upstream = provider.routing[agent]?.upstream;
const url = oauth.modelsDiscoveryUrl ?? (upstream ? deriveModelsDiscoveryUrl(upstream) : null);
if (!url) continue;
// 去重键含 agent:发现请求头按 wire 分派(cc 带 anthropic-version),同 URL 不同 wire 不能共用响应。
const key = `${agent}\n${url}`;
if (!fetched.has(key)) fetched.set(key, await discoverGenericOAuthModels(providerId, oauth, url, agent));
+ if (!isCurrent()) break;
const models = fetched.get(key);
if (!models || models.length === 0) continue;
if (provider.source === 'user') {
const cfg = await getCustomProvider(providerId);
- const nextCfg = cfg ? mergeDiscoveredModelsIntoConfig(cfg, agent, models) : null;
- if (nextCfg) {
- await updateCustomProvider(providerId, nextCfg);
- customChanged = true;
+ if (!isCurrent()) break;
+ if (cfg) {
+ const nextCfg = mergeDiscoveredModelsIntoConfig(cfg, agent, models);
+ if (nextCfg) {
+ const applied = await updateCustomProviderIfUnchanged(providerId, cfg, nextCfg);
+ if (!isCurrent()) break;
+ if (applied) customChanged = true;
+ }
}
} else {
+ if (!isCurrent()) break;
setDiscoveredProviderModels(
providerId,
agent,
@@ -3542,19 +3564,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
);
}
}
- if (customChanged) await refreshCustomProvidersIntoCatalog();
+ if (customChanged && isCurrent()) await refreshCustomProvidersIntoCatalog();
} catch {
/* 发现失败保持纯静态目录,不影响登录结果 */
}
- broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
+ if (isCurrent()) broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
}
- return result;
+ return {
+ ...result,
+ ...(rollbackCredentials ? { rollbackCredentials } : {}),
+ };
},
+ readCustomProviderKeyForMutation,
+ storeCustomProviderKey,
+ removeCustomProviderKey,
oauthLogout: async (providerId) => {
- logoutGenericOAuth(providerId);
+ if (!logoutGenericOAuth(providerId)) {
+ throw new Error('failed to remove generic OAuth credentials');
+ }
},
oauthCancel: (providerId) => cancelGenericOAuthLogin(providerId),
- clearOAuthCredentials: (providerId) => logoutGenericOAuth(providerId),
+ removeOAuthCredentials: (providerId) =>
+ removeGenericOAuthCredentialsReversibly(providerId),
});
// 自定义 MCP 服务器 CRUD —— CRUD 成功后刷新两个 agent 的 mcpProviders 数组
@@ -7217,10 +7248,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
});
// renderer → main 单向镜像「模型显示/隐藏」override(整张快照,fire-and-forget,不落盘)。
- // main 缓存供 IM /model 派生模型列表时复用同一套可见性过滤,与应用内列表逐模型一致。
+ // main 缓存供 IM /model 与 device-link provider:list 复用同一套可见性过滤。值实变时
+ // 复用 PROVIDER_CHANGED 目录失效事件,让已连接控制端驱逐缓存并重拉 override 快照。
// 容错存储(非对象 ⇒ 清空),无错误路径,故不需要 throwIpcError。
ipcMain.handle(MAKER_INVOKE.MODEL_VISIBILITY_SYNC, async (_e, map: unknown) => {
- setModelVisibilityMirror(map);
+ syncModelVisibilityMirror(map, () => {
+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
+ });
});
// 附加只读引用目录的运行时 closure 推送。DB 持久化由 renderer 同步调
diff --git a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
index 63e086267e..eb878c77c1 100644
--- a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
+++ b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
@@ -34,6 +34,7 @@ vi.mock('../../appSessionState', () => ({
import {
createProviderSecretStore,
+ readCustomProviderKeyForMutation,
readGhostSecretTailFromIo,
setProviderSecretsClearedListener,
type SecretStorageIo,
@@ -141,6 +142,21 @@ describe('providerSecrets registry', () => {
expect(providerSecretStorageKey(id)).toMatch(valid);
}
});
+
+ it('strict custom-provider snapshot treats a missing file as absent when encryption is unavailable', () => {
+ const previousMode = sessionState.mode;
+ const previousOwnerId = sessionState.dataOwnerId;
+ sessionState.mode = 'cloud';
+ sessionState.dataOwnerId = `missing-key-owner-${process.pid}`;
+ try {
+ expect(
+ readCustomProviderKeyForMutation(`missing-key-provider-${process.pid}`, 'codex'),
+ ).toBeNull();
+ } finally {
+ sessionState.mode = previousMode;
+ sessionState.dataOwnerId = previousOwnerId;
+ }
+ });
});
describe('providerSecretStore', () => {
diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.ts
index 5f8c8fbc6c..7f2ae531a9 100644
--- a/apps/desktop/src/main/secrets/providerSecretStore.ts
+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts
@@ -51,8 +51,8 @@ const OWNER_STORAGE_KEY = 'provider_secret_owner';
*
* 注意:本 store 的 set / remove **不触发** 任何副作用(例如 api_key 变更后重建
* Codex —— 那是 safe-storage IPC 层 onApiKeyChangedMaybeRestartCodex 的职责)。
- * 当前没有"main 端写供应商 key"的路径(写入都走 renderer → IPC),set / remove
- * 仅为 API 对称而提供;未来若有 main 端写 api_key 的需求,需自行补副作用。
+ * main 端写路径仅限自定义供应商 CRUD 的 per-provider mutation queue;若扩展到
+ * 需要重建运行时的内置 provider key,必须同步补对应副作用。
*/
/** 低层加密 KV(按 safeStorage 存储键名读写),抽出以便注入测试。 */
@@ -377,6 +377,78 @@ export function readCustomProviderKey(providerId: string, agent: string): string
}
}
+/**
+ * 配置 CRUD 回滚前的严格 API key 快照读取。
+ * 仅 ENOENT 表示“没有旧 key”;owner / 加密不可用、文件读取或解密失败都必须抛错,
+ * 防止调用方把暂时不可读的现有凭证误判为空并永久删除。
+ */
+export function readCustomProviderKeyForMutation(
+ providerId: string,
+ agent: string,
+): string | null {
+ const logicalKey = customProviderSecretStorageKey(providerId, agent);
+ const scopedKey = resolveOwnerScopedSecretStorageKey(logicalKey);
+ if (!scopedKey) throw new Error('provider secret owner is unavailable');
+ let encoded: string;
+ try {
+ encoded = fs.readFileSync(path.join(secretDir(), `${scopedKey}.enc`), 'utf-8');
+ } catch (err) {
+ if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') {
+ return null;
+ }
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'read custom provider key snapshot failed',
+ );
+ throw new Error('existing provider credential is unreadable');
+ }
+ if (!safeStorage.isEncryptionAvailable()) {
+ throw new Error('provider credential encryption is unavailable');
+ }
+ try {
+ return safeStorage.decryptString(Buffer.from(encoded, 'base64'));
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'decrypt custom provider key snapshot failed',
+ );
+ throw new Error('existing provider credential is unreadable');
+ }
+}
+
+/** 写入某自定义供应商 runtime 的 API key;供 main 侧原子配置更新使用。 */
+export function storeCustomProviderKey(
+ providerId: string,
+ agent: string,
+ value: string,
+): boolean {
+ try {
+ return electronSecretIo.write(customProviderSecretStorageKey(providerId, agent), value);
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'write custom provider key failed',
+ );
+ return false;
+ }
+}
+
+/** 删除某自定义供应商 runtime 的 API key;不存在视为成功。 */
+export function removeCustomProviderKey(
+ providerId: string,
+ agent: string,
+): { success: boolean; error?: string } {
+ try {
+ return electronSecretIo.remove(customProviderSecretStorageKey(providerId, agent));
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'remove custom provider key failed',
+ );
+ return { success: false, error: 'remove_failed' };
+ }
+}
+
/**
* 读取某自定义 MCP 服务器的 bearer token(**main 侧 CustomMcpProvider resolve 专用**)。
* 不存在 / safeStorage 不可用 / 读失败均返回 null。与 renderer 经通用 safe-storage IPC
@@ -552,6 +624,36 @@ export const genericOAuthSecretIo = {
return null;
}
},
+ readStrict(providerId: string): string | null {
+ const logicalKey = providerOAuthStorageKey(providerId);
+ const scopedKey = resolveOwnerScopedSecretStorageKey(logicalKey);
+ if (!scopedKey) throw new Error('provider secret owner is unavailable');
+ let encoded: string;
+ try {
+ encoded = fs.readFileSync(path.join(secretDir(), `${scopedKey}.enc`), 'utf-8');
+ } catch (err) {
+ if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') {
+ return null;
+ }
+ log.warn(
+ { providerId, err: err instanceof Error ? err.message : String(err) },
+ 'read generic oauth blob snapshot failed',
+ );
+ throw new Error('existing OAuth credential is unreadable');
+ }
+ if (!safeStorage.isEncryptionAvailable()) {
+ throw new Error('provider credential encryption is unavailable');
+ }
+ try {
+ return safeStorage.decryptString(Buffer.from(encoded, 'base64'));
+ } catch (err) {
+ log.warn(
+ { providerId, err: err instanceof Error ? err.message : String(err) },
+ 'decrypt generic oauth blob snapshot failed',
+ );
+ throw new Error('existing OAuth credential is unreadable');
+ }
+ },
write(providerId: string, value: string): boolean {
try {
return electronSecretIo.write(providerOAuthStorageKey(providerId), value);
@@ -563,15 +665,23 @@ export const genericOAuthSecretIo = {
return false;
}
},
- remove(providerId: string): void {
+ remove(providerId: string): boolean {
try {
- electronSecretIo.remove(providerOAuthStorageKey(providerId));
+ const result = electronSecretIo.remove(providerOAuthStorageKey(providerId));
+ if (!result.success) {
+ log.warn(
+ { providerId, error: result.error ?? 'remove_failed' },
+ 'remove generic oauth blob failed',
+ );
+ }
+ return result.success;
} catch (err) {
- // 键名校验抛错(非法 id)或底层删除异常:降级记日志,与 read/write 的容错口径一致。
+ // 键名校验抛错(非法 id)或底层删除异常:保留现有登录态并把失败交给调用方。
log.warn(
{ providerId, err: err instanceof Error ? err.message : String(err) },
'remove generic oauth blob failed',
);
+ return false;
}
},
};
diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
index 67d211fa7f..7db6dd2907 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -39,6 +39,10 @@ vi.mock('../../maker-host/active-catalog.js', () => ({
getActiveCatalog: vi.fn(() => ({ providers: [] })),
}));
+vi.mock('../../maker-host/provider-route.js', () => ({
+ isProviderRouteMutationInProgress: vi.fn(() => false),
+}));
+
vi.mock('../../secrets/providerSecretStore.js', () => ({
readCustomProviderKey: vi.fn(),
}));
@@ -63,6 +67,7 @@ import { getValidClaudeAiOAuth } from '../../maker-host/claude-oauth-refresh.js'
import { getGrokAccessToken } from '../../maker-host/grok-oauth-login.js';
import { readCachedGenericOAuthAccessToken } from '../../maker-host/generic-oauth.js';
import { getActiveCatalog } from '../../maker-host/active-catalog.js';
+import { isProviderRouteMutationInProgress } from '../../maker-host/provider-route.js';
import { readCustomProviderKey } from '../../secrets/providerSecretStore.js';
import { getUtilityModelChainProfiles } from '../UtilityModelSelection.js';
import { getUtilityTextCandidates, requestUtilityText } from '../oneShotCandidates.js';
@@ -75,6 +80,7 @@ const readGrokToken = vi.mocked(getGrokAccessToken);
const readGenericOAuthToken = vi.mocked(readCachedGenericOAuthAccessToken);
const fetchMock = vi.mocked(undiciFetch);
const activeCatalog = vi.mocked(getActiveCatalog);
+const providerRouteMutationInProgress = vi.mocked(isProviderRouteMutationInProgress);
const readCustomKey = vi.mocked(readCustomProviderKey);
function makerMock(authenticated: boolean): Maker {
@@ -93,6 +99,7 @@ describe('utility one-shot candidates', () => {
readClaudeOAuth.mockResolvedValue(null);
readGrokToken.mockRejectedValue(new Error('not authenticated'));
readGenericOAuthToken.mockReturnValue(null);
+ providerRouteMutationInProgress.mockReturnValue(false);
readCustomKey.mockReturnValue(null);
activeCatalog.mockReturnValue({ providers: [] } as never);
getProfiles.mockReturnValue([
@@ -270,6 +277,47 @@ describe('utility one-shot candidates', () => {
});
});
+ it('does not read or send a custom-provider key while its route is mutating', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'tapsvc',
+ name: 'Tap Service',
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'apiKey' },
+ routing: {
+ codex: {
+ upstream: 'https://old.example/v1',
+ authStrategy: 'api-key-header',
+ },
+ },
+ models: {
+ codex: [{ id: 'custom-mini', name: 'Custom Mini', contextWindow: 100_000 }],
+ },
+ }],
+ } as never);
+ providerRouteMutationInProgress.mockReturnValue(true);
+ readCustomKey.mockReturnValue('replacement-secret');
+
+ const result = await requestUtilityText(makerMock(false), 'generate', {
+ providerId: 'tapsvc',
+ agentKind: 'codex',
+ model: 'custom-mini',
+ });
+
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: [expect.objectContaining({
+ providerId: 'tapsvc',
+ status: 'failed',
+ reason: 'request_failed',
+ })],
+ });
+ expect(readCustomKey).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('uses Chat Completions for an explicitly selected openai-chat provider', async () => {
activeCatalog.mockReturnValue({
providers: [{
@@ -361,6 +409,46 @@ describe('utility one-shot candidates', () => {
);
});
+ it('fails closed when an explicitly selected no-auth runtime is disabled', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'legacy-remote',
+ name: 'Legacy Remote',
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'none' },
+ routing: {
+ codex: {
+ upstream: 'https://remote.example/v1',
+ authStrategy: 'none',
+ disabled: true,
+ },
+ },
+ models: {
+ codex: [{ id: 'legacy-model', name: 'Legacy Model', contextWindow: 100_000 }],
+ },
+ }],
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'generate', {
+ providerId: 'legacy-remote',
+ agentKind: 'codex',
+ model: 'legacy-model',
+ });
+
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'no_candidate',
+ attempts: [{
+ providerId: 'legacy-remote',
+ model: 'legacy-model',
+ status: 'skipped',
+ reason: 'endpoint_missing',
+ }],
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('rejects base URL userinfo when applying an exact provider request path', async () => {
activeCatalog.mockReturnValue({
providers: [{
@@ -622,6 +710,51 @@ describe('utility one-shot candidates', () => {
expect(init.headers['anthropic-version']).toBeUndefined();
});
+ it('routes a descriptor-backed no-auth builtin through the generic utility transport', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'catalog-local',
+ name: 'Catalog Local',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: { method: 'none' },
+ routing: {
+ codex: {
+ upstream: 'http://127.0.0.1:4000/v1',
+ wireProtocol: 'openai-chat',
+ authStrategy: 'none',
+ },
+ },
+ models: {
+ codex: [{ id: 'catalog-model', name: 'Catalog Model', contextWindow: 100_000 }],
+ },
+ }],
+ } as never);
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => JSON.stringify({
+ choices: [{ message: { content: 'catalog result' } }],
+ }),
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'generate', {
+ providerId: 'catalog-local',
+ agentKind: 'codex',
+ model: 'catalog-model',
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ text: 'catalog result',
+ providerId: 'catalog-local',
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'http://127.0.0.1:4000/v1/chat/completions',
+ expect.anything(),
+ );
+ expect(readCustomKey).not.toHaveBeenCalled();
+ });
+
it('can infer a unique custom provider when an older caller omits providerId', async () => {
activeCatalog.mockReturnValue({
providers: [{
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 77cbc08129..ce5be01d13 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -13,6 +13,7 @@ import { readCachedGenericOAuthAccessToken } from '../maker-host/generic-oauth.j
import { outboundUndiciFetch as undiciFetch } from '../maker-host/outbound-fetch.js';
import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
+import { isProviderRouteMutationInProgress } from '../maker-host/provider-route.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
import { readCustomProviderKey } from '../secrets/providerSecretStore.js';
import { getUtilityModelChainProfiles } from './UtilityModelSelection.js';
@@ -235,6 +236,19 @@ async function requestExplicitProviderText(
}],
};
}
+ if (isProviderRouteMutationInProgress(provider.id)) {
+ return {
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: [{
+ providerId: provider.id,
+ model,
+ transport,
+ status: 'failed',
+ reason: 'request_failed',
+ }],
+ };
+ }
if (!model) {
return {
ok: false,
@@ -262,7 +276,7 @@ async function requestExplicitProviderText(
};
}
- if (provider.source !== 'user') {
+ if (provider.id === 'xd' || provider.id === 'anthropic' || provider.id === 'openai' || provider.id === 'xai') {
return requestBuiltinProviderText(prompt, {
provider,
agentKind,
@@ -274,6 +288,19 @@ async function requestExplicitProviderText(
}
const routing = provider.routing[agentKind];
+ if (routing?.disabled) {
+ return {
+ ok: false,
+ reason: 'no_candidate',
+ attempts: [{
+ providerId: provider.id,
+ model,
+ transport,
+ status: 'skipped',
+ reason: 'endpoint_missing',
+ }],
+ };
+ }
if (
routing?.authStrategy !== 'api-key-header'
&& routing?.authStrategy !== 'oauth-token'
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index a8e42d8d72..9697f1b14f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3616,13 +3616,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
listProviders: (): Promise<{ providers: import('@cindy/model-providers').ProviderView[] }> =>
ipcRenderer.invoke('maker:provider:list'),
- // 自定义供应商配置 CRUD(密钥另走通用 safeStorage IPC,不经这里)。
+ // 自定义供应商配置 CRUD(配置与 runtime 密钥均由 main 原子排队)。
createCustomProvider: (
config: import('@cindy/model-providers').CustomProviderConfig,
- ): Promise<{ ok: true }> => ipcRenderer.invoke('maker:provider:custom:create', config),
+ keys: Partial<Record<'claude-code' | 'codex', string>>,
+ ): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('maker:provider:custom:create', config, keys),
updateCustomProvider: (
config: import('@cindy/model-providers').CustomProviderConfig,
- ): Promise<{ ok: true }> => ipcRenderer.invoke('maker:provider:custom:update', config),
+ keys: Partial<Record<'claude-code' | 'codex', string>>,
+ ): Promise<{ ok: true }> => ipcRenderer.invoke('maker:provider:custom:update', config, keys),
deleteCustomProvider: (providerId: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('maker:provider:custom:delete', providerId),
/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */
@@ -3641,6 +3644,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
agent: 'claude-code' | 'codex';
baseUrl: string;
modelId: string;
+ authMethod: 'apiKey' | 'oauth' | 'none';
wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;
requestPath?: string;
apiKey?: string | null;
@@ -3661,6 +3665,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
fetchProviderModels: (input: {
agent: 'claude-code' | 'codex';
baseUrl: string;
+ authMethod: 'apiKey' | 'oauth' | 'none';
modelsUrl?: string | null;
apiKey?: string | null;
headers?: Record<string, string>;
@@ -3733,12 +3738,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
): Promise<{ tasks: Array<{ taskId: string; taskType?: string; toolUseId?: string; title?: string }> }> =>
ipcRenderer.invoke('maker:session-background-tasks:list', sessionId),
/** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动)登录 / 登出 / 取消。 */
- providerOAuthLogin: (providerId: string): Promise<{ ok: boolean; reason?: string }> =>
- ipcRenderer.invoke('maker:provider:oauth:login', providerId),
+ providerOAuthLogin: (
+ providerId: string,
+ options?: { ownerId?: string },
+ ): Promise<{ ok: boolean; reason?: string }> =>
+ ipcRenderer.invoke('maker:provider:oauth:login', providerId, options),
providerOAuthLogout: (providerId: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('maker:provider:oauth:logout', providerId),
- providerOAuthCancel: (providerId: string): Promise<{ ok: true }> =>
- ipcRenderer.invoke('maker:provider:oauth:cancel', providerId),
+ providerOAuthCancel: (
+ providerId: string,
+ options?: { releaseOwner?: boolean; ownerId?: string },
+ ): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('maker:provider:oauth:cancel', providerId, options),
onProviderOAuthProgress: fanOutMakerProviderOAuthProgress,
/**
* renderer → main 单向镜像「模型显示/隐藏」override 整张快照(modelVisibilityPrefs)。
@@ -4503,10 +4514,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
auth: {
getState: (agentKind: 'claude-code' | 'codex'): Promise<unknown> =>
ipcRenderer.invoke('maker:auth:get-state', agentKind),
- triggerLogin: (agentKind: 'claude-code' | 'codex'): Promise<unknown> =>
- ipcRenderer.invoke('maker:auth:trigger-login', agentKind),
- cancelLogin: (agentKind: 'claude-code' | 'codex'): Promise<void> =>
- ipcRenderer.invoke('maker:auth:cancel-login', agentKind),
+ triggerLogin: (
+ agentKind: 'claude-code' | 'codex',
+ options?: { mode?: 'browser' | 'device-code'; ownerId?: string },
+ ): Promise<unknown> =>
+ ipcRenderer.invoke('maker:auth:trigger-login', agentKind, options),
+ cancelLogin: (
+ agentKind: 'claude-code' | 'codex',
+ options?: { releaseOwner?: boolean; ownerId?: string },
+ ): Promise<void> =>
+ ipcRenderer.invoke('maker:auth:cancel-login', agentKind, options),
logout: (agentKind: 'claude-code' | 'codex'): Promise<void> =>
ipcRenderer.invoke('maker:auth:logout', agentKind),
onStateChanged: fanOutMakerAuthStateChanged,
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx
index 8558b3980f..446038e5a2 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx
@@ -8,7 +8,7 @@
* OpenAI 会出现弹窗一闪即逝,且 provider 仍保持未连接。
*/
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -23,6 +23,8 @@ const { triggerLogin, cancelLogin, codexAuthMock } = vi.hoisted(() => ({
state: { kind: 'authenticated', authSource: 'oauth' } as {
kind: string;
authSource?: string;
+ mode?: 'browser' | 'device-code';
+ deviceCode?: { verificationUrl: string; userCode: string };
},
},
}));
@@ -75,10 +77,71 @@ const OPENAI_PROVIDER = {
models: { codex: [] },
connected: false,
} satisfies ProviderView;
+const DEVICE_PROVIDER = {
+ id: 'device-provider',
+ name: 'Device Provider',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: {
+ method: 'oauth',
+ oauth: {
+ flow: 'device-code',
+ deviceAuthorizationUrl: 'https://auth.example.test/device',
+ tokenUrl: 'https://auth.example.test/token',
+ clientId: 'device-client',
+ scopes: 'openid',
+ },
+ },
+ routing: {
+ codex: {
+ upstream: 'https://api.example.test/v1',
+ authStrategy: 'oauth-token',
+ },
+ },
+ models: { codex: [] },
+ connected: false,
+} satisfies ProviderView;
+const AUTH_CODE_PROVIDER = {
+ id: 'auth-code-provider',
+ name: 'Authorization Code Provider',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example.test/authorize',
+ tokenUrl: 'https://auth.example.test/token',
+ clientId: 'auth-code-client',
+ scopes: 'openid',
+ },
+ },
+ routing: {
+ codex: {
+ upstream: 'https://api.example.test/v1',
+ authStrategy: 'oauth-token',
+ },
+ },
+ models: { codex: [] },
+ connected: false,
+} satisfies ProviderView;
+
+const providerOAuthLogin = vi.fn();
+const providerOAuthCancel = vi.fn();
+type ProviderOAuthProgress = {
+ providerId: string;
+ phase: 'device-code';
+ verificationUrl: string;
+ userCode: string;
+ expiresAt: number;
+};
+let providerOAuthProgressListener: ((progress: ProviderOAuthProgress) => void) | null = null;
beforeEach(() => {
triggerLogin.mockReset();
cancelLogin.mockReset();
+ providerOAuthLogin.mockReset();
+ providerOAuthCancel.mockReset();
+ providerOAuthProgressListener = null;
codexAuthMock.state = { kind: 'authenticated', authSource: 'oauth' };
// 登录成功 = 快照翻转到 authenticated;完成边界必须由这次翻转驱动。
triggerLogin.mockImplementation(async () => {
@@ -88,6 +151,14 @@ beforeEach(() => {
(window as unknown as { electronAPI: unknown }).electronAPI = {
maker: {
listProviderPresets: vi.fn(async () => ({ presets: [] })),
+ providerOAuthLogin,
+ providerOAuthCancel,
+ onProviderOAuthProgress: vi.fn((listener: (progress: ProviderOAuthProgress) => void) => {
+ providerOAuthProgressListener = listener;
+ return () => {
+ if (providerOAuthProgressListener === listener) providerOAuthProgressListener = null;
+ };
+ }),
},
};
});
@@ -110,7 +181,7 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {
/>,
);
- expect(screen.getByText('settings.providers.button.authorize')).not.toBeNull();
+ expect(screen.getByText('settings.providers.wizard.authorizeInBrowser')).not.toBeNull();
await waitFor(() => expect(onDone).not.toHaveBeenCalled());
});
@@ -129,9 +200,10 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {
/>,
);
- fireEvent.click(screen.getByText('settings.providers.button.authorize'));
+ fireEvent.click(screen.getByText('settings.providers.wizard.authorizeInBrowser'));
await waitFor(() => expect(triggerLogin).toHaveBeenCalledTimes(1));
+ expect(triggerLogin).toHaveBeenCalledWith('browser');
await waitFor(() => expect(onDone).toHaveBeenCalledWith('openai'));
});
@@ -150,14 +222,133 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {
/>,
);
- fireEvent.click(screen.getByText('settings.providers.button.authorize'));
+ fireEvent.click(screen.getByText('settings.providers.wizard.authorizeInBrowser'));
await waitFor(() => expect(triggerLogin).toHaveBeenCalledTimes(1));
// 先等授权流程 settle(按钮从「取消」回到「授权」= loggingIn 已复位),
// 再做负向断言——避免「负向 waitFor」首查即过、断言早于异步流程收尾。
await waitFor(() =>
- expect(screen.getByText('settings.providers.button.authorize')).not.toBeNull(),
+ expect(screen.getByText('settings.providers.wizard.authorizeInBrowser')).not.toBeNull(),
);
expect(onDone).not.toHaveBeenCalled();
});
+
+ it('设备码路径展示代码,并支持复制和打开官方验证页', async () => {
+ codexAuthMock.state = { kind: 'unauthenticated' };
+ triggerLogin.mockImplementation(() => {
+ codexAuthMock.state = {
+ kind: 'login-pending',
+ mode: 'device-code',
+ deviceCode: {
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'RUH2-7E2VH',
+ },
+ };
+ return new Promise<string>(() => undefined);
+ });
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText },
+ });
+ const openExternal = vi.fn().mockResolvedValue({ success: true });
+ (
+ window.electronAPI as unknown as {
+ openExternal: typeof openExternal;
+ }
+ ).openExternal = openExternal;
+
+ render(
+ <AddProviderWizard
+ providers={[OPENAI_PROVIDER]}
+ entry={{ kind: 'builtin', providerId: 'openai' }}
+ onOpenCustomForm={vi.fn()}
+ onClose={vi.fn()}
+ onDone={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('settings.providers.wizard.authorizeWithDeviceCode'));
+ await waitFor(() => expect(screen.getByText('RUH2-7E2VH')).not.toBeNull());
+ expect(triggerLogin).toHaveBeenCalledWith('device-code');
+
+ fireEvent.click(screen.getByText('settings.providers.wizard.copyDeviceCode'));
+ fireEvent.click(screen.getByText('settings.providers.wizard.openVerificationPage'));
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith('RUH2-7E2VH'));
+ await waitFor(() =>
+ expect(openExternal).toHaveBeenCalledWith('https://auth.openai.com/codex/device'),
+ );
+ });
+
+ it('目录声明 Device Grant 时,添加流程直接展示供应商设备码', async () => {
+ providerOAuthLogin.mockImplementation(() => new Promise(() => undefined));
+ const { unmount } = render(
+ <AddProviderWizard
+ providers={[DEVICE_PROVIDER]}
+ entry={{ kind: 'builtin', providerId: DEVICE_PROVIDER.id }}
+ onOpenCustomForm={vi.fn()}
+ onClose={vi.fn()}
+ onDone={vi.fn()}
+ />,
+ );
+ await waitFor(() => expect(providerOAuthProgressListener).not.toBeNull());
+
+ fireEvent.click(screen.getByText('settings.providers.wizard.authorizeWithDeviceCode'));
+ await waitFor(() =>
+ expect(providerOAuthLogin).toHaveBeenCalledWith(
+ DEVICE_PROVIDER.id,
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
+ const ownerId = providerOAuthLogin.mock.calls[0]?.[1]?.ownerId;
+ act(() => {
+ providerOAuthProgressListener?.({
+ providerId: DEVICE_PROVIDER.id,
+ phase: 'device-code',
+ verificationUrl: 'https://auth.example.test/device',
+ userCode: 'TEST-CODE',
+ expiresAt: Date.now() + 300_000,
+ });
+ });
+
+ expect(await screen.findByText('TEST-CODE')).not.toBeNull();
+ expect(screen.getByText(/auth\.example\.test/)).not.toBeNull();
+
+ unmount();
+ expect(providerOAuthCancel).toHaveBeenCalledOnce();
+ expect(providerOAuthCancel).toHaveBeenCalledWith(DEVICE_PROVIDER.id, {
+ releaseOwner: true,
+ ownerId,
+ });
+ });
+
+ it('authorization-code 登录期间被父级卸载时取消仍在等待的回环授权', async () => {
+ providerOAuthLogin.mockImplementation(() => new Promise(() => undefined));
+ const { unmount } = render(
+ <AddProviderWizard
+ providers={[AUTH_CODE_PROVIDER]}
+ entry={{ kind: 'builtin', providerId: AUTH_CODE_PROVIDER.id }}
+ onOpenCustomForm={vi.fn()}
+ onClose={vi.fn()}
+ onDone={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('settings.providers.button.authorize'));
+ await waitFor(() =>
+ expect(providerOAuthLogin).toHaveBeenCalledWith(
+ AUTH_CODE_PROVIDER.id,
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
+ const ownerId = providerOAuthLogin.mock.calls[0]?.[1]?.ownerId;
+ expect(providerOAuthProgressListener).toBeNull();
+
+ unmount();
+ expect(providerOAuthCancel).toHaveBeenCalledOnce();
+ expect(providerOAuthCancel).toHaveBeenCalledWith(AUTH_CODE_PROVIDER.id, {
+ releaseOwner: true,
+ ownerId,
+ });
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx
index 334c27c2c7..1439f13ac5 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx
@@ -113,7 +113,7 @@ describe('AddProviderWizard — OpenAI 检测建议直达', () => {
renderWizard('openai', onDone);
// 授权步可见、可交互;onDone 不得被立即触发。
- expect(screen.getByText('settings.providers.button.authorize')).not.toBeNull();
+ expect(screen.getByText('settings.providers.wizard.authorizeInBrowser')).not.toBeNull();
expect(onDone).not.toHaveBeenCalled();
});
@@ -122,9 +122,10 @@ describe('AddProviderWizard — OpenAI 检测建议直达', () => {
const onDone = vi.fn();
renderWizard('openai', onDone);
- fireEvent.click(screen.getByText('settings.providers.button.authorize'));
+ fireEvent.click(screen.getByText('settings.providers.wizard.authorizeInBrowser'));
await waitFor(() => expect(onDone).toHaveBeenCalledWith('openai'));
expect(triggerLoginMock).toHaveBeenCalledTimes(1);
+ expect(triggerLoginMock).toHaveBeenCalledWith('browser');
});
it('anthropic entry 直达 → 授权步正常渲染(对照组)', () => {
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
index fc0737eb10..6426f16c0c 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
@@ -67,6 +67,48 @@ const deepseekPreset = {
name: 'DeepSeek',
runtimes: { 'claude-code': { baseUrl: 'https://api.deepseek.com/anthropic', models: [] } },
};
+const liteLlmPreset = {
+ id: 'litellm',
+ name: 'LiteLLM Proxy',
+ authMethod: 'none' as const,
+ runtimes: {
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ baseUrlEditable: true,
+ requestPath: '/tenant/acme/infer',
+ models: [],
+ },
+ },
+};
+const unsafeNoAuthDiscoveryPreset = {
+ id: 'unsafe-no-auth-discovery',
+ name: 'Unsafe no-auth discovery',
+ authMethod: 'none' as const,
+ runtimes: {
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ modelsUrl: 'https://remote.example/v1/models',
+ models: [],
+ },
+ },
+};
+const openCodePreset = {
+ id: 'opencode-go',
+ name: 'OpenCode Go',
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://opencode.ai/zen/go',
+ modelsUrl: 'https://opencode.ai/zen/go/v1/models',
+ models: [{ id: 'minimax-m3', name: 'MiniMax M3' }],
+ },
+ codex: {
+ baseUrl: 'https://opencode.ai/zen/go/v1',
+ wireProtocol: 'openai-chat' as const,
+ modelsUrl: 'https://opencode.ai/zen/go/v1/models',
+ models: [{ id: 'glm-5.2', name: 'GLM-5.2' }],
+ },
+ },
+};
function renderWizard(presetId: string) {
return render(
@@ -83,7 +125,14 @@ function renderWizard(presetId: string) {
beforeEach(() => {
(window as unknown as { electronAPI: unknown }).electronAPI = {
maker: {
- listProviderPresets: vi.fn(async () => ({ presets: [deepseekPreset] })),
+ listProviderPresets: vi.fn(async () => ({
+ presets: [
+ deepseekPreset,
+ liteLlmPreset,
+ unsafeNoAuthDiscoveryPreset,
+ openCodePreset,
+ ],
+ })),
// 列模型失败场景兜底(Greptile P1 回归):官方 API 预设必须靠推荐模型仍可完成。
fetchProviderModels: vi.fn(async () => ({ ok: false, code: 'NETWORK' })),
},
@@ -232,6 +281,100 @@ describe('AddProviderWizard — preset 直达', () => {
});
});
+ it('LiteLLM:模型发现失败时可手填模型 ID,并以 none 鉴权保存', async () => {
+ renderWizard('litellm');
+
+ await waitFor(() => expect(screen.getByDisplayValue('LiteLLM Proxy')).not.toBeNull());
+ expect(screen.queryByPlaceholderText('sk-…')).toBeNull();
+ expect(screen.getByText('settings.providers.wizard.noAuthNote')).not.toBeNull();
+
+ const endpoint = screen.getByDisplayValue('http://127.0.0.1:4000/v1');
+ fireEvent.change(endpoint, { target: { value: 'http://localhost:4100/v1' } });
+ const next = screen
+ .getByText('settings.providers.wizard.next')
+ .closest('button') as HTMLButtonElement;
+ expect(next.disabled).toBe(false);
+ fireEvent.click(next);
+
+ const manualModel = await screen.findByPlaceholderText(
+ 'settings.providers.wizard.manualModelPlaceholder',
+ );
+ expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agent: 'codex',
+ baseUrl: 'http://localhost:4100/v1',
+ authMethod: 'none',
+ apiKey: null,
+ }),
+ );
+ fireEvent.change(manualModel, { target: { value: 'local-model' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.addManualModel'));
+ expect(screen.getByText('local-model')).not.toBeNull();
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
+ expect(vi.mocked(createCustomProvider).mock.calls[0][0]).toEqual(
+ expect.objectContaining({
+ auth: { method: 'none' },
+ runtimes: {
+ codex: expect.objectContaining({
+ baseUrl: 'http://localhost:4100/v1',
+ requestPath: '/tenant/acme/infer',
+ models: [{ id: 'local-model', name: 'local-model' }],
+ }),
+ },
+ }),
+ );
+ expect(vi.mocked(createCustomProvider).mock.calls[0][1]).toEqual({});
+ });
+
+ it('none 预设的远端 modelsUrl 会在第二步阻止继续', async () => {
+ renderWizard('unsafe-no-auth-discovery');
+
+ await waitFor(() =>
+ expect(screen.getByDisplayValue('Unsafe no-auth discovery')).not.toBeNull(),
+ );
+ const next = screen.getByText('settings.providers.wizard.next')
+ .closest('button') as HTMLButtonElement;
+ expect(next.disabled).toBe(true);
+ expect(window.electronAPI.maker.fetchProviderModels).not.toHaveBeenCalled();
+ });
+
+ it('共享模型目录不会扩大 OpenCode 的逐协议模型归属', async () => {
+ vi.mocked(window.electronAPI.maker.fetchProviderModels).mockResolvedValue({
+ ok: true,
+ models: [
+ { id: 'minimax-m3', name: 'MiniMax M3' },
+ { id: 'glm-5.2', name: 'GLM-5.2' },
+ ],
+ });
+ renderWizard('opencode-go');
+
+ await waitFor(() => expect(screen.getByDisplayValue('OpenCode Go')).not.toBeNull());
+ fireEvent.change(screen.getByPlaceholderText('sk-…'), { target: { value: 'sk-test' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));
+ await waitFor(() => expect(screen.getByText('MiniMax M3')).not.toBeNull());
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
+ const config = vi.mocked(createCustomProvider).mock.calls[0][0];
+ expect(config.runtimes['claude-code']?.models.map((model) => model.id)).toEqual(['minimax-m3']);
+ expect(config.runtimes.codex?.models.map((model) => model.id)).toEqual(['glm-5.2']);
+ });
+
+ it('LiteLLM:清空可编辑端点后不回退预设地址,也不能继续', async () => {
+ renderWizard('litellm');
+
+ const endpoint = await screen.findByDisplayValue('http://127.0.0.1:4000/v1');
+ fireEvent.change(endpoint, { target: { value: ' ' } });
+
+ const next = screen.getByText('settings.providers.wizard.next')
+ .closest('button') as HTMLButtonElement;
+ expect(next.disabled).toBe(true);
+ expect(window.electronAPI.maker.fetchProviderModels).not.toHaveBeenCalled();
+ expect(createCustomProvider).not.toHaveBeenCalled();
+ });
+
it('presetId 不存在 → 回落目录第一步', async () => {
renderWizard('nonexistent');
diff --git a/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts b/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts
index 16d4fa20ff..5560196f21 100644
--- a/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts
@@ -10,7 +10,10 @@ beforeEach(() => {
vi.resetModules();
});
-type Providers = { providers: Array<{ id: string }> };
+type Providers = {
+ providers: Array<{ id: string }>;
+ modelVisibilityOverrides?: Record<string, boolean>;
+};
const result = (deviceId: string): Providers => ({ providers: [{ id: `${deviceId}-xd` }] });
/** stub window.electronAPI.deviceLink.invoke,返回 spy。 */
@@ -25,7 +28,9 @@ describe('useDeviceProviders deviceId-aware cache', () => {
const invoke = stubDeviceLink();
const mod = await import('@/hooks/useDeviceProviders');
await mod.prefetchDeviceProviders('dev-1');
- expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', []);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', [{
+ capabilities: ['provider-logo-kinds-v2'],
+ }]);
});
it('缓存命中:同设备二次 prefetch 不再发请求', async () => {
@@ -36,6 +41,30 @@ describe('useDeviceProviders deviceId-aware cache', () => {
expect(invoke).toHaveBeenCalledTimes(1);
});
+ it('缓存并通知被控端的模型可见性 override 快照', async () => {
+ const overrides = { 'codex:openai:hidden-model': false };
+ const invoke = vi.fn(async () => ({
+ ...result('dev-1'),
+ modelVisibilityOverrides: overrides,
+ }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const listener = vi.fn();
+ mod.subscribeDeviceProviders('dev-1', listener);
+
+ await mod.prefetchDeviceProviders('dev-1');
+
+ expect(mod.getCachedDeviceProviders('dev-1')).toEqual({
+ providers: [{ id: 'dev-1-xd' }],
+ modelVisibilityOverrides: overrides,
+ });
+ expect(listener).toHaveBeenCalledWith({
+ status: 'ready',
+ providers: [{ id: 'dev-1-xd' }],
+ modelVisibilityOverrides: overrides,
+ });
+ });
+
it('inflight 去重:同设备并发只发一次', async () => {
const invoke = stubDeviceLink();
const mod = await import('@/hooks/useDeviceProviders');
@@ -48,8 +77,12 @@ describe('useDeviceProviders deviceId-aware cache', () => {
const mod = await import('@/hooks/useDeviceProviders');
await mod.prefetchDeviceProviders('dev-1');
await mod.prefetchDeviceProviders('dev-2');
- expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', []);
- expect(invoke).toHaveBeenCalledWith('dev-2', 'maker:provider:list', []);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', [{
+ capabilities: ['provider-logo-kinds-v2'],
+ }]);
+ expect(invoke).toHaveBeenCalledWith('dev-2', 'maker:provider:list', [{
+ capabilities: ['provider-logo-kinds-v2'],
+ }]);
expect(invoke).toHaveBeenCalledTimes(2);
// dev-2 已缓存:再 prefetch 不重拉(隔离 + 命中)。
await mod.prefetchDeviceProviders('dev-2');
diff --git a/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts b/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts
index 3cb76720a3..78dd45183c 100644
--- a/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts
@@ -33,13 +33,20 @@ function provider(
connected: boolean,
models: Record<string, CatalogModel[]>,
): ProviderView {
+ const agents = Object.keys(models);
return {
id,
name: id,
source: 'builtin',
- agents: Object.keys(models),
+ agents,
models,
- routing: {},
+ // Provider availability now requires an enabled runtime, not only an entry in `agents`.
+ routing: Object.fromEntries(
+ agents.map((agent) => [
+ agent,
+ { upstream: 'https://provider.test', authStrategy: 'none' },
+ ]),
+ ),
auth: { method: 'oauth' },
connected,
} as unknown as ProviderView;
diff --git a/apps/desktop/src/renderer/__tests__/modelMarkSemantics.test.tsx b/apps/desktop/src/renderer/__tests__/modelMarkSemantics.test.tsx
index 841f10f571..d3e2bfc7a8 100644
--- a/apps/desktop/src/renderer/__tests__/modelMarkSemantics.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelMarkSemantics.test.tsx
@@ -37,6 +37,18 @@ describe('model mark semantics', () => {
expect(firstPath(<ProviderMark providerId="xai" />)).toBe(
firstPath(<ProviderLogoMark providerId="xai" />),
);
+ expect(
+ firstPath(<ProviderMark providerId="renamed-kimi" name="My Kimi" logoKind="moonshot" />),
+ ).toBe(firstPath(<ProviderLogoMark providerId="renamed-kimi" logoKind="moonshot" />));
+ const unknownLogo = render(
+ <ProviderMark
+ providerId="future-provider"
+ name="My Provider"
+ logoKind={'future-brand' as never}
+ />,
+ );
+ expect(unknownLogo.container.querySelector('svg')).toBeNull();
+ expect(unknownLogo.container.textContent).toBe('M');
expect(firstPath(<ModelIconMark icon="claude" providerId="xd" />)).toBe(anthropicPath);
expect(firstPath(<ModelIconMark icon="openai" providerId="xd" />)).toBe(openaiPath);
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
index 7a2b1b792a..7ae6b84187 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
@@ -218,7 +218,7 @@ const providersRef = vi.hoisted(() => {
source: 'builtin',
agents: ['claude-code'],
auth: { method: 'oauth' },
- routing: {},
+ routing: { 'claude-code': {} },
connected: true,
models: {
'claude-code': [
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index f0fbed5fe9..a99fecaa2b 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -8,7 +8,7 @@
* 4. wizard=1 → 向导目录第一步(entry undefined)。
*/
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -219,4 +219,55 @@ describe('ProvidersSection — 深链定位', () => {
expect(wizardSpy).toHaveBeenCalledWith(undefined);
await waitFor(() => expect(screen.getByTestId('search').textContent).toBe('?tab=providers'));
});
+
+ it('authorization-code 自定义供应商登录期间卸载时取消本视图拥有的授权', async () => {
+ const providerOAuthLogin = vi.fn<
+ (providerId: string, options?: { ownerId?: string }) => Promise<{ ok: boolean }>
+ >(() => new Promise(() => undefined));
+ const providerOAuthCancel = vi.fn(async () => ({ ok: true }));
+ const onProviderOAuthProgress = vi.fn(() => () => undefined);
+ providersState.providers = [
+ makeProvider('custom-oauth', {
+ name: 'Custom OAuth',
+ source: 'user',
+ auth: {
+ method: 'oauth',
+ oauth: {
+ authorizeUrl: 'https://auth.example.test/authorize',
+ tokenUrl: 'https://auth.example.test/token',
+ clientId: 'custom-client',
+ scopes: 'openid',
+ },
+ },
+ }),
+ ];
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: {
+ scanLocalCli: vi.fn(async () => ({ detections: [] })),
+ providerOAuthLogin,
+ providerOAuthCancel,
+ onProviderOAuthProgress,
+ },
+ };
+
+ const view = renderAt('?tab=providers');
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'settings.providers.button.authorize' }),
+ );
+ await waitFor(() =>
+ expect(providerOAuthLogin).toHaveBeenCalledWith(
+ 'custom-oauth',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
+ const ownerId = providerOAuthLogin.mock.calls[0]?.[1]?.ownerId;
+ expect(onProviderOAuthProgress).not.toHaveBeenCalled();
+
+ view.unmount();
+ expect(providerOAuthCancel).toHaveBeenCalledOnce();
+ expect(providerOAuthCancel).toHaveBeenCalledWith('custom-oauth', {
+ releaseOwner: true,
+ ownerId,
+ });
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts b/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts
index b779c995ba..98358e3aeb 100644
--- a/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts
+++ b/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts
@@ -13,7 +13,11 @@
import { describe, expect, it } from 'vitest';
import type { ModelDescriptor } from '@/hooks/useAgentCapabilities';
-import { filterChatBridgedCodexProviders, selectVisibleModels } from '@/lib/providerModels';
+import {
+ filterChatBridgedCodexProviders,
+ isDeviceModelVisible,
+ selectVisibleModels,
+} from '@/lib/providerModels';
import type { AgentKind, ProviderView } from '@cindy/model-providers';
/** 被控端 capabilities.availableModels 形态(renderer ModelDescriptor)。 */
@@ -27,6 +31,7 @@ function provider(id: string, agent: AgentKind, modelIds: string[]): ProviderVie
id,
name: id,
agents: [agent],
+ routing: { [agent]: {} },
models: {
[agent]: modelIds.map((mid) => ({
id: mid,
@@ -122,6 +127,27 @@ describe('selectVisibleModels — device-link「以被控端为准」', () => {
});
});
+describe('isDeviceModelVisible — 使用被控端可见性快照', () => {
+ const model = { id: 'gpt-5.5', defaultEnabled: true };
+
+ it('显式 override 优先于目录默认值', () => {
+ expect(
+ isDeviceModelVisible(
+ { 'codex:openai:gpt-5.5': false },
+ 'codex',
+ 'openai',
+ model,
+ ),
+ ).toBe(false);
+ });
+
+ it('现代被控端无 override 时跟随目录默认值,旧被控端缺快照时 fail-open', () => {
+ const defaultHidden = { id: 'preview-model', defaultEnabled: false };
+ expect(isDeviceModelVisible({}, 'codex', 'openai', defaultHidden)).toBe(false);
+ expect(isDeviceModelVisible(undefined, 'codex', 'openai', defaultHidden)).toBe(true);
+ });
+});
+
describe('selectVisibleModels — excludeSubscriptionDirect(SSH 远程隐藏订阅直连模型)', () => {
it('true:过滤 chatgpt/ 与 xai/ 前缀模型,其余保留(本机 providers 派生路径)', () => {
const out = selectVisibleModels({
diff --git a/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts b/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts
index 151cee2376..e3689ca30d 100644
--- a/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts
@@ -475,6 +475,7 @@ describe('isSelectedSourceDisconnected — 会话显式来源断连判定', () =
name: id,
connected,
agents,
+ routing: Object.fromEntries(agents.map((agent) => [agent, {}])),
models: { [AGENT]: [{ id: MODEL_ID }] },
}) as unknown as ProviderView;
diff --git a/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts b/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts
index 4d495584f8..309fdcd132 100644
--- a/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts
+++ b/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts
@@ -79,7 +79,14 @@ describe('deriveRemoteReadiness(被控端就绪推导)', () => {
describe('sourceReadyFromProviderList(隧道 provider:list 响应解析)', () => {
// 与被控端 dispatch 剥离执行字段后的回显结构一致,判定只消费 connected + agents。
const provider = (over: Partial<ProviderView>): ProviderView =>
- ({ id: 'p', name: 'P', agents: ['codex'], connected: true, ...over }) as ProviderView;
+ ({
+ id: 'p',
+ name: 'P',
+ agents: ['codex'],
+ routing: { codex: {} },
+ connected: true,
+ ...over,
+ }) as ProviderView;
it('该 agent 有已连接来源 → true;来源都未连接 / 不支持该 agent → false', () => {
expect(sourceReadyFromProviderList({ providers: [provider({})] }, 'codex')).toBe(true);
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index fbec62c711..45c0bbb1b5 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ErrorBanner } from '../ErrorBanner';
import { useCodexAuth } from '@/hooks/useCodexAuth';
+import { useCodexSessionExpiredPrompt } from '@/hooks/useCodexSessionExpiredPrompt';
type AuthStateChangedPayload = {
agentKind: 'claude-code' | 'codex';
@@ -137,7 +138,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
);
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledWith('codex'));
+ await waitFor(() =>
+ expect(mocks.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
expect(mocks.confirm).not.toHaveBeenCalled();
expect(mocks.toastSuccess).toHaveBeenCalledWith('logic.toasts.codexConnected');
expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
@@ -180,7 +186,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
);
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledWith('codex'));
+ await waitFor(() =>
+ expect(mocks.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
expect(mocks.toastError).not.toHaveBeenCalled();
expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
expect(
@@ -235,7 +246,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
);
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledWith('codex'));
+ await waitFor(() =>
+ expect(mocks.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
});
@@ -458,6 +474,63 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
- expect(mocks.triggerLogin).toHaveBeenCalledWith('codex');
+ expect(mocks.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ );
+ });
+
+ it('cancels an owned reconnect when its prompt owner unmounts', async () => {
+ const login = deferred<AuthStateChangedPayload>();
+ mocks.triggerLogin.mockImplementation(() => login.promise);
+ const prompt = renderHook(() =>
+ useCodexSessionExpiredPrompt({ confirmBeforeLogin: false }),
+ );
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
+ });
+ await waitFor(() =>
+ expect(mocks.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ ),
+ );
+
+ prompt.unmount();
+ expect(mocks.cancelLogin).toHaveBeenCalledOnce();
+ expect(mocks.cancelLogin).toHaveBeenCalledWith('codex', {
+ releaseOwner: true,
+ ownerId: expect.any(String),
+ });
+
+ await act(async () => {
+ login.resolve({
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await login.promise;
+ });
+ });
+
+ it('does not start reconnect after unmount while confirmation is pending', async () => {
+ const confirmation = deferred<boolean>();
+ mocks.confirm.mockImplementationOnce(() => confirmation.promise);
+ const prompt = renderHook(() => useCodexSessionExpiredPrompt());
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
+ });
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());
+
+ prompt.unmount();
+ await act(async () => {
+ confirmation.resolve(true);
+ await confirmation.promise;
+ });
+
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(mocks.cancelLogin).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/renderer/components/icons/ProviderLogoMark.tsx b/apps/desktop/src/renderer/components/icons/ProviderLogoMark.tsx
index f82c77b8fb..27b4c236f3 100644
--- a/apps/desktop/src/renderer/components/icons/ProviderLogoMark.tsx
+++ b/apps/desktop/src/renderer/components/icons/ProviderLogoMark.tsx
@@ -7,8 +7,10 @@
import {
hasProviderLogo,
+ isProviderLogoKind,
PROVIDER_LOGO_PATHS,
resolveProviderLogoKind,
+ type ProviderLogoKind,
type ProviderLogoRouting,
} from '@cindy/model-providers/branding';
@@ -22,6 +24,8 @@ export type { ProviderLogoRouting };
interface ProviderLogoMarkProps {
providerId: string;
routing?: ProviderLogoRouting;
+ /** Device-link projection resolved this before stripping private routing details. */
+ logoKind?: ProviderLogoKind;
size?: number;
className?: string;
}
@@ -30,10 +34,13 @@ interface ProviderLogoMarkProps {
export function ProviderLogoMark({
providerId,
routing,
+ logoKind,
size = 14,
className,
}: ProviderLogoMarkProps) {
- const kind = resolveProviderLogoKind(providerId, routing);
+ const kind = isProviderLogoKind(logoKind)
+ ? logoKind
+ : resolveProviderLogoKind(providerId, routing);
if (!kind) return null;
if (kind === 'anthropic') return <AnthropicMark size={size} className={className} />;
if (kind === 'openai') return <OpenAIMark size={size} className={className} />;
diff --git a/apps/desktop/src/renderer/components/icons/__tests__/ProviderLogoMark.test.tsx b/apps/desktop/src/renderer/components/icons/__tests__/ProviderLogoMark.test.tsx
index c367d3f61f..938a1984a6 100644
--- a/apps/desktop/src/renderer/components/icons/__tests__/ProviderLogoMark.test.tsx
+++ b/apps/desktop/src/renderer/components/icons/__tests__/ProviderLogoMark.test.tsx
@@ -33,6 +33,8 @@ describe('ProviderLogoMark', () => {
it('keeps preset-backed provider logos after the user-facing id changes', () => {
for (const preset of BUNDLED_CATALOG.presets ?? []) {
+ // Editable self-hosted endpoints have no stable vendor hostname after a rename.
+ if (Object.values(preset.runtimes).some((runtime) => runtime?.baseUrlEditable)) continue;
const routing: Record<string, { upstream: string }> = {};
for (const [agent, runtime] of Object.entries(preset.runtimes)) {
if (runtime) routing[agent] = { upstream: runtime.baseUrl };
@@ -71,4 +73,12 @@ describe('ProviderLogoMark', () => {
render(<ProviderLogoMark providerId="future-provider" />).container.firstChild,
).toBeNull();
});
+
+ it('ignores an unknown projected logo kind and falls back to provider identity', () => {
+ const mark = render(
+ <ProviderLogoMark providerId="xai" logoKind={'future-brand' as never} />,
+ );
+ expect(mark.container.querySelector('svg')).not.toBeNull();
+ expect(mark.container.querySelector('path')).not.toBeNull();
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index 8b2acadb75..3606c825f2 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -34,6 +34,7 @@ import {
} from '@/lib/modelPriceFormat';
import {
filterChatBridgedCodexProviders,
+ isDeviceModelVisible,
providerMonogram,
resolveVisibleModelAgentKind,
selectVisibleModels,
@@ -53,6 +54,7 @@ import {
visibleModelUnion,
type ProviderView,
} from '@cindy/model-providers';
+import { isProviderLogoKind } from '@cindy/model-providers/branding';
import { getModelPriceQuote } from '../../../shared/modelPriceQuote';
import type { ModelPricingCatalog } from '../../../shared/regionalMoney';
import { buildProviderSections } from './sourceSwitch';
@@ -114,6 +116,7 @@ export function ProviderMark({
providerId,
name,
routing,
+ logoKind,
colorClass = 'text-[var(--model-trigger-text)]',
withMargin = true,
dense = false,
@@ -121,6 +124,7 @@ export function ProviderMark({
providerId: string;
name?: string;
routing?: ProviderView['routing'];
+ logoKind?: ProviderView['logoKind'];
colorClass?: string;
withMargin?: boolean;
/** 列表行前缀用 dense:比 trigger 小一档(约 -10%)。两套静态尺寸,JIT 友好。 */
@@ -128,11 +132,12 @@ export function ProviderMark({
}) {
const common = cn(withMargin && 'mr-1.5', 'shrink-0', colorClass);
const markSize = dense ? 12.3 : 13;
- if (hasProviderLogo(providerId, routing)) {
+ if (isProviderLogoKind(logoKind) || hasProviderLogo(providerId, routing)) {
return (
<ProviderLogoMark
providerId={providerId}
routing={routing}
+ logoKind={logoKind}
size={markSize}
className={
providerId === 'xd'
@@ -169,6 +174,7 @@ export function ModelIconMark({
providerId,
name,
routing,
+ logoKind,
colorClass = 'text-[var(--model-trigger-text)]',
withMargin = true,
dense = false,
@@ -179,6 +185,7 @@ export function ModelIconMark({
providerId: string;
name?: string;
routing?: ProviderView['routing'];
+ logoKind?: ProviderView['logoKind'];
colorClass?: string;
withMargin?: boolean;
dense?: boolean;
@@ -201,6 +208,7 @@ export function ModelIconMark({
providerId={providerId}
name={name}
routing={routing}
+ logoKind={logoKind}
colorClass={colorClass}
withMargin={withMargin}
dense={dense}
@@ -755,12 +763,19 @@ function ModelSelectorContentView({
agent: currentAgentKind,
selectedModelId: modelId,
selectedProviderId: activeSourceId,
- // device-link 远程会话:被控端目录「是啥就是啥」,绝不套控制端本机的可见性 override
- // —— modelVisibilityPrefs 是控制端本机 UI 偏好(设置→供应商的隐藏开关),与被控端无关,
- // 套上去会让远程列表变成「被控端目录 ∩ 控制端隐藏开关」,跟被控端实际清单对不上。
- // 本机会话仍按用户本机开关过滤(行为不变)。
+ // device-link 远程会话使用被控端随 provider:list 返回的 override 快照,绝不套
+ // 控制端本机 modelVisibilityPrefs。旧被控端不回传快照时 fail-open,保持兼容。
isVisible: deviceId
- ? () => true
+ ? (pid, mid) => {
+ const p = connected.find((x) => x.id === pid);
+ const cat = p ? getModel(p, mid, currentAgentKind) : undefined;
+ return isDeviceModelVisible(
+ remoteProviders.modelVisibilityOverrides,
+ currentAgentKind,
+ pid,
+ { id: mid, defaultEnabled: cat?.defaultEnabled },
+ );
+ }
: (pid, mid) => {
const p = connected.find((x) => x.id === pid);
const cat = p ? getModel(p, mid, currentAgentKind) : undefined;
@@ -781,6 +796,7 @@ function ModelSelectorContentView({
query,
visibilityVersion,
deviceId,
+ remoteProviders.modelVisibilityOverrides,
]);
const flatModels = useMemo(() => {
@@ -796,9 +812,22 @@ function ModelSelectorContentView({
// 本地 flat 入口(子代理模型、Worker 等)没有 provider sections 帮忙过滤,必须显式复用
// 会话选择器 / IM `/model` 的同一套「已连接来源 × 用户可见模型」规则。否则设置页里
// 已忽略或仅由断开来源提供的目录项仍会被列出来,选中后没有可用路由。
- // device-link 的目录来自被控端,不能叠加控制端本机的可见性偏好,保持原样。
+ // device-link 使用被控端 override;旧被控端没有快照时保持历史 fail-open。
const selectableIds = deviceId
- ? null
+ ? remoteProviders.modelVisibilityOverrides === undefined
+ ? null
+ : new Set(
+ (agentKind ? [agentKind] : (['claude-code', 'codex'] as const)).flatMap((agent) =>
+ visibleModelUnion(providers, agent, (providerId, model) =>
+ isDeviceModelVisible(
+ remoteProviders.modelVisibilityOverrides,
+ agent,
+ providerId,
+ model,
+ ),
+ ).map((model) => model.id),
+ ),
+ )
: new Set(
(agentKind ? [agentKind] : (['claude-code', 'codex'] as const)).flatMap((agent) =>
visibleModelUnion(providers, agent, (providerId, model) =>
@@ -811,7 +840,17 @@ function ModelSelectorContentView({
return selectable.filter(
(m) => m.displayName.toLowerCase().includes(q) || m.id.toLowerCase().includes(q),
);
- }, [sections, visibleModels, query, browsing, agentKind, providers, deviceId, visibilityVersion]);
+ }, [
+ sections,
+ visibleModels,
+ query,
+ browsing,
+ agentKind,
+ providers,
+ deviceId,
+ visibilityVersion,
+ remoteProviders.modelVisibilityOverrides,
+ ]);
// 选中判定:flat 模式只比模型 id;分段模式还要比供应商(同模型多供应商下只高亮当前来源那行)。
// 浏览目标引擎态恒 false:当前会话模型属于旧引擎,目标列表里同 id 行(如 gpt-5.5
@@ -1092,9 +1131,7 @@ function ModelSelectorContentView({
{t(`newChat.modelSelector.pricing.${row.kind}`)}
</span>
<span className="flex items-center justify-end gap-1.5 tabular-nums">
- <span className="text-[var(--model-item-text)]">
- {row.value}
- </span>
+ <span className="text-[var(--model-item-text)]">{row.value}</span>
{row.originalValue && (
<span className="text-[var(--text-tertiary)] line-through">
{row.originalValue}
@@ -1250,6 +1287,7 @@ function ModelSelectorContentView({
providerId={provider.id}
name={provider.name}
routing={provider.routing}
+ logoKind={provider.logoKind}
colorClass="text-[var(--text-secondary)]"
withMargin={false}
dense
@@ -1614,8 +1652,7 @@ export function ModelSelector({
// 用户既看不到自己存的是什么,也看不到实际会跑什么。unknownModelLabel 让这类调用方
// 给出诊断性文案(通常是裸 id),行为与本组件接管前一致。
// unknown label 空串/全空白按缺省处理(否则 ?? 不回落,trigger 渲染成空白)。
- const unknownLabel =
- modelId && unknownModelLabel ? unknownModelLabel(modelId).trim() : '';
+ const unknownLabel = modelId && unknownModelLabel ? unknownModelLabel(modelId).trim() : '';
const displayLabel = fallbackOption?.active
? fallbackOption.label
: (currentModel?.displayName ??
@@ -1823,6 +1860,7 @@ export function ModelSelector({
providerId={currentProviderId}
name={disconnectedProvider?.name}
routing={disconnectedProvider?.routing}
+ logoKind={disconnectedProvider?.logoKind}
colorClass="text-[var(--error-fg)]"
/>
<span
@@ -1868,6 +1906,7 @@ export function ModelSelector({
providerId={activeSourceId}
name={triggerActiveProvider?.name}
routing={triggerActiveProvider?.routing}
+ logoKind={triggerActiveProvider?.logoKind}
colorClass={
isCreateAgentVariant ? 'text-[var(--create-agent-control-icon)]' : undefined
}
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index 013d242ebe..23918d2fc7 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -26,9 +26,15 @@ import { createCustomProvider, type RuntimeKeys } from '@/lib/customProviders';
import { uniqueCustomProviderId } from '@/lib/customProviderId';
import { providerMonogram } from '@/lib/providerModels';
import { isChatGptConnectionConnected, useCodexAuth } from '@/hooks/useCodexAuth';
+import { useProviderOAuthDeviceCode } from '@/hooks/useProviderOAuthDeviceCode';
import { hasProviderLogo, ProviderLogoMark } from '@/components/icons/ProviderLogoMark';
+import { OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';
-import { presetDisplayName, sortPresetsForLocale } from '@cindy/model-providers';
+import {
+ isLoopbackProviderUrl,
+ presetDisplayName,
+ sortPresetsForLocale,
+} from '@cindy/model-providers';
import type {
AgentKind,
CustomProviderConfig,
@@ -283,11 +289,26 @@ export function AddProviderWizard({
const [presetBaseUrls, setPresetBaseUrls] = useState<PresetBaseUrls>({});
const [saving, setSaving] = useState(false);
const [loggingIn, setLoggingIn] = useState(false);
+ const genericOAuthProviderId =
+ sel?.kind === 'oauth' && sel.provider.auth.oauth ? sel.provider.id : null;
+ const genericDeviceFlow =
+ sel?.kind === 'oauth' && sel.provider.auth.oauth?.flow === 'device-code';
+ const {
+ deviceCode: genericDeviceCode,
+ clearDeviceCode: clearGenericDeviceCode,
+ beginOwnedLogin: beginGenericOwnedLogin,
+ cancelOwnedLogin: cancelGenericOwnedLogin,
+ } = useProviderOAuthDeviceCode(genericOAuthProviderId, {
+ observeProgress: genericDeviceFlow,
+ });
// Step 3 拉取态
const [step, setStep] = useState<1 | 2 | 3>(entryProvider ? 2 : 1);
const [fetchState, setFetchState] = useState<
- { status: 'idle' } | { status: 'fetching' } | { status: 'done'; failed: boolean }
+ | { status: 'idle' }
+ | { status: 'fetching' }
+ | { status: 'done'; failed: boolean; empty: boolean }
>({ status: 'idle' });
+ const [manualModelIds, setManualModelIds] = useState<Partial<Record<AgentKind, string>>>({});
/**
* 勾选清单:id → { name, checked, recommended, agents }。Map 保序(推荐在前,拉取新增在后)。
* agents = 该模型归属的 runtime:预设推荐模型归属「预设里列出它的那些 runtime」;拉取新增
@@ -346,19 +367,23 @@ export function AddProviderWizard({
const pickOauth = useCallback((provider: ProviderView) => {
fetchSeqRef.current += 1;
+ setManualModelIds({});
setSel({ kind: 'oauth', provider });
setStep(2);
}, []);
const pickPreset = useCallback(
(preset: ProviderPreset) => {
fetchSeqRef.current += 1;
+ setManualModelIds({});
setSel({ kind: 'preset', preset });
setName(presetDisplayName(preset, i18n.language));
setApiKey('');
setPresetBaseUrls(
Object.fromEntries(
- (Object.keys(preset.runtimes) as AgentKind[])
- .map((agent) => [agent, preset.runtimes[agent]?.baseUrl ?? '']),
+ (Object.keys(preset.runtimes) as AgentKind[]).map((agent) => [
+ agent,
+ preset.runtimes[agent]?.baseUrl ?? '',
+ ]),
) as PresetBaseUrls,
);
setStep(2);
@@ -387,46 +412,59 @@ export function AddProviderWizard({
const openaiLoginStartedRef = useRef(false);
// ── OAuth 授权(复用既有鉴权流;成功即完成,无第 3 步)────────────────────
- const handleAuthorize = useCallback(async () => {
- if (!sel || sel.kind !== 'oauth') return;
- const id = sel.provider.id;
- setLoggingIn(true);
- try {
- let ok = false;
- if (id === 'anthropic') {
- const r = await window.electronAPI.maker.claudeOAuthLogin();
- ok = r.ok;
- if (!r.ok && r.reason === 'not_a_subscription') {
- toast.error(t('settings.connections.claude.toast.notSubscription'));
- return;
+ const handleAuthorize = useCallback(
+ async (mode: 'browser' | 'device-code' = 'browser') => {
+ if (!sel || sel.kind !== 'oauth') return;
+ const id = sel.provider.id;
+ clearGenericDeviceCode();
+ setLoggingIn(true);
+ try {
+ let ok = false;
+ if (id === 'anthropic') {
+ const r = await window.electronAPI.maker.claudeOAuthLogin();
+ ok = r.ok;
+ if (!r.ok && r.reason === 'not_a_subscription') {
+ toast.error(t('settings.connections.claude.toast.notSubscription'));
+ return;
+ }
+ if (!r.ok && r.reason === 'login_cancelled') return;
+ } else if (id === 'openai') {
+ openaiLoginStartedRef.current = true;
+ const outcome = await codexAuth.triggerLogin(mode);
+ ok = outcome === 'authenticated';
+ if (outcome === 'cancelled') return;
+ } else if (id === 'xai') {
+ const r = await window.electronAPI.maker.xaiOAuthLogin();
+ ok = r.ok;
+ if (!r.ok && r.reason === 'login_cancelled') return;
+ } else {
+ const ownedLogin = beginGenericOwnedLogin();
+ try {
+ const r = await window.electronAPI.maker.providerOAuthLogin(id, {
+ ownerId: ownedLogin.ownerId,
+ });
+ ok = r.ok;
+ if (!r.ok && r.reason === 'login_cancelled') return;
+ } finally {
+ ownedLogin.finish();
+ }
}
- if (!r.ok && r.reason === 'login_cancelled') return;
- } else if (id === 'openai') {
- openaiLoginStartedRef.current = true;
- const outcome = await codexAuth.triggerLogin();
- ok = outcome === 'authenticated';
- if (outcome === 'cancelled') return;
- } else if (id === 'xai') {
- const r = await window.electronAPI.maker.xaiOAuthLogin();
- ok = r.ok;
- if (!r.ok && r.reason === 'login_cancelled') return;
- } else {
- const r = await window.electronAPI.maker.providerOAuthLogin(id);
- ok = r.ok;
- if (!r.ok && r.reason === 'login_cancelled') return;
- }
- if (ok) {
- toast.success(t('settings.providers.wizard.authorizedToast', { name: sel.provider.name }));
- onDone(id);
- } else {
+ if (ok) {
+ toast.success(
+ t('settings.providers.wizard.authorizedToast', { name: sel.provider.name }),
+ );
+ onDone(id);
+ } else {
+ toast.error(t('settings.providers.wizard.authorizeFailed', { name: sel.provider.name }));
+ }
+ } catch {
toast.error(t('settings.providers.wizard.authorizeFailed', { name: sel.provider.name }));
+ } finally {
+ setLoggingIn(false);
}
- } catch {
- toast.error(t('settings.providers.wizard.authorizeFailed', { name: sel.provider.name }));
- } finally {
- setLoggingIn(false);
- }
- }, [sel, codexAuth, onDone, t]);
+ },
+ [sel, clearGenericDeviceCode, beginGenericOwnedLogin, codexAuth, onDone, t],
+ );
/**
* 取消进行中的 OAuth(与详情头的行为对称):等待授权期间点按钮 / 关弹窗 / 返回
@@ -438,9 +476,10 @@ export function AddProviderWizard({
if (id === 'anthropic') void window.electronAPI.maker.claudeOAuthCancel();
else if (id === 'openai') void codexAuth.cancelLogin();
else if (id === 'xai') void window.electronAPI.maker.xaiOAuthCancel();
- else void window.electronAPI.maker.providerOAuthCancel(id);
+ else cancelGenericOwnedLogin();
+ clearGenericDeviceCode();
setLoggingIn(false);
- }, [sel, codexAuth]);
+ }, [sel, clearGenericDeviceCode, cancelGenericOwnedLogin, codexAuth]);
/** 关闭向导:授权等待中先取消再关,不留挂起的 login runner。 */
const handleClose = useCallback(() => {
@@ -496,6 +535,31 @@ export function AddProviderWizard({
// 并行拉取**每个已配置 runtime** 的列模型端点:双 runtime 预设两端各自发现,
// 返回结果按「实际返回它的端点」归属合并——某模型两端都返回则归属两端。
const agents = Object.keys(preset.runtimes) as AgentKind[];
+ // 同一个 modelsUrl 被多个 runtime 共用、但预设模型集合不同,说明该端点返回的是
+ // 跨协议总目录(OpenCode Go 即如此),响应本身无法判定模型属于 Messages 还是 Chat。
+ // 这类端点只能用于确认预设已有模型,不能扩大其 agent 归属或加入无法分类的新模型。
+ const discoveryAgentsByUrl = new Map<string, AgentKind[]>();
+ for (const agent of agents) {
+ const modelsUrl = preset.runtimes[agent]?.modelsUrl;
+ if (!modelsUrl) continue;
+ discoveryAgentsByUrl.set(modelsUrl, [...(discoveryAgentsByUrl.get(modelsUrl) ?? []), agent]);
+ }
+ const splitDiscoveryUrls = new Set(
+ [...discoveryAgentsByUrl.entries()]
+ .filter(([, owners]) => {
+ if (owners.length < 2) return false;
+ const modelSets = new Set(
+ owners.map((agent) =>
+ (preset.runtimes[agent]?.models ?? [])
+ .map((model) => model.id)
+ .sort()
+ .join('\u0000'),
+ ),
+ );
+ return modelSets.size > 1;
+ })
+ .map(([modelsUrl]) => modelsUrl),
+ );
const results = await Promise.all(
agents.map(async (agent) => {
const rt = preset.runtimes[agent];
@@ -504,6 +568,7 @@ export function AddProviderWizard({
const r = await window.electronAPI.maker.fetchProviderModels({
agent,
baseUrl: presetRuntimeBaseUrl(preset, agent, presetBaseUrls),
+ authMethod: preset.authMethod ?? 'apiKey',
modelsUrl: rt.modelsUrl ?? null,
apiKey: apiKey.trim() || null,
...(rt.headers ? { headers: rt.headers } : {}),
@@ -519,13 +584,15 @@ export function AddProviderWizard({
setPicks((prev) => {
const next = new Map(prev);
for (const { agent, models } of results) {
+ const modelsUrl = preset.runtimes[agent]?.modelsUrl;
+ const preservePresetOwnership = !!modelsUrl && splitDiscoveryUrls.has(modelsUrl);
for (const m of models) {
const existing = next.get(m.id);
if (existing) {
- if (!existing.agents.includes(agent)) {
+ if (!preservePresetOwnership && !existing.agents.includes(agent)) {
next.set(m.id, { ...existing, agents: [...existing.agents, agent] });
}
- } else {
+ } else if (!preservePresetOwnership) {
next.set(m.id, { name: m.name, checked: false, recommended: false, agents: [agent] });
}
}
@@ -533,9 +600,50 @@ export function AddProviderWizard({
return next;
});
// 全部端点都失败才算失败(单端失败仍可按另一端 + 预设推荐完成)。
- setFetchState({ status: 'done', failed: !results.some((r) => r.ok) });
+ setFetchState({
+ status: 'done',
+ failed: !results.some((r) => r.ok),
+ empty: !results.some((r) => r.models.length > 0),
+ });
}, [sel, apiKey, presetBaseUrls]);
+ /**
+ * 零推荐模型的本机代理(例如 LiteLLM)若 `/models` 不可用或返回空清单,仍允许用户
+ * 按 runtime 手填真实模型 ID。归属必须精确到当前 agent,不能把一个 ID 猜测性复制到
+ * 双 runtime;同一 ID 分别加入两端时才合并归属。
+ */
+ const addManualModel = useCallback(
+ (agent: AgentKind) => {
+ if (!sel || sel.kind !== 'preset' || !sel.preset.runtimes[agent]) return;
+ const id = manualModelIds[agent]?.trim() ?? '';
+ if (!id) return;
+ setPicks((prev) => {
+ const next = new Map(prev);
+ const existing = next.get(id);
+ next.set(
+ id,
+ existing
+ ? {
+ ...existing,
+ checked: true,
+ agents: existing.agents.includes(agent)
+ ? existing.agents
+ : [...existing.agents, agent],
+ }
+ : {
+ name: id,
+ checked: true,
+ recommended: false,
+ agents: [agent],
+ },
+ );
+ return next;
+ });
+ setManualModelIds((prev) => ({ ...prev, [agent]: '' }));
+ },
+ [sel, manualModelIds],
+ );
+
// ── 完成创建(预设)────────────────────────────────────────────────────
const handleFinish = useCallback(async () => {
if (!sel || sel.kind !== 'preset') return;
@@ -582,15 +690,22 @@ export function AddProviderWizard({
...(rt.headers ? { headers: rt.headers } : {}),
...(rt.modelsUrl ? { modelsUrl: rt.modelsUrl } : {}),
};
- const k = apiKey.trim();
- if (k) keys[agent] = k;
+ if (preset.authMethod !== 'none') {
+ const k = apiKey.trim();
+ if (k) keys[agent] = k;
+ }
}
if (Object.keys(runtimes).length === 0) {
toast.error(t('settings.providers.wizard.noModelSelected'));
return;
}
await createCustomProvider(
- { id, name: name.trim() || presetDisplayName(preset, i18n.language), runtimes },
+ {
+ id,
+ name: name.trim() || presetDisplayName(preset, i18n.language),
+ ...(preset.authMethod === 'none' ? { auth: { method: 'none' as const } } : {}),
+ runtimes,
+ },
keys,
);
toast.success(
@@ -617,15 +732,6 @@ export function AddProviderWizard({
// 预设单 runtime 时的「仅支持 X」说明(数据驱动的静态灰,见文件头注释)。
const presetAgents =
sel?.kind === 'preset' ? (Object.keys(sel.preset.runtimes) as AgentKind[]) : [];
- const presetBaseUrlsValid =
- sel?.kind !== 'preset'
- || presetAgents.every((agent) => {
- const rt = sel.preset.runtimes[agent];
- return !rt?.baseUrlEditable
- || isValidEditablePresetBaseUrl(
- presetRuntimeBaseUrl(sel.preset, agent, presetBaseUrls),
- );
- });
const presetSingleAgentNote =
sel?.kind === 'preset' && presetAgents.length === 1
? t('settings.providers.wizard.onlyAgentNote', { agent: AGENT_LABEL[presetAgents[0]] })
@@ -636,8 +742,45 @@ export function AddProviderWizard({
agent: AGENT_LABEL[sel.provider.agents[0]],
})
: null;
+ const openAiDeviceLoginPending =
+ sel?.kind === 'oauth' &&
+ sel.provider.id === 'openai' &&
+ loggingIn &&
+ codexAuth.state.kind === 'login-pending' &&
+ codexAuth.state.mode === 'device-code';
+ const openAiDeviceCode =
+ openAiDeviceLoginPending && codexAuth.state.kind === 'login-pending'
+ ? codexAuth.state.deviceCode
+ : undefined;
const checkedCount = [...picks.values()].filter((v) => v.checked).length;
+ const presetHasRecommendedModels =
+ sel?.kind === 'preset' &&
+ presetAgents.some((agent) => (sel.preset.runtimes[agent]?.models.length ?? 0) > 0);
+ const showManualModelFallback =
+ sel?.kind === 'preset' &&
+ fetchState.status === 'done' &&
+ (fetchState.failed || fetchState.empty) &&
+ !presetHasRecommendedModels;
+ const presetNeedsApiKey = sel?.kind === 'preset' && sel.preset.authMethod !== 'none';
+ const presetBaseUrlsValid =
+ sel?.kind === 'preset' &&
+ presetAgents.every((agent) => {
+ const runtime = sel.preset.runtimes[agent];
+ if (!runtime) return false;
+ const value = presetRuntimeBaseUrl(sel.preset, agent, presetBaseUrls);
+ if (sel.preset.authMethod === 'none') {
+ return (
+ isLoopbackProviderUrl(value)
+ && (!runtime.modelsUrl?.trim() || isLoopbackProviderUrl(runtime.modelsUrl.trim()))
+ );
+ }
+ return !runtime.baseUrlEditable || isValidEditablePresetBaseUrl(value);
+ });
+ const presetCanContinue =
+ sel?.kind === 'preset' &&
+ presetBaseUrlsValid &&
+ (!presetNeedsApiKey || apiKey.trim().length > 0);
return (
<div className="fixed inset-0 z-[10000] flex items-center justify-center bg-[var(--overlay-modal)]">
@@ -772,7 +915,11 @@ export function AddProviderWizard({
name: presetDisplayName(p, i18n.language),
})}
name={presetDisplayName(p, i18n.language)}
- meta={t('settings.providers.wizard.metaApiKey')}
+ meta={t(
+ p.authMethod === 'none'
+ ? 'settings.providers.wizard.metaNoAuth'
+ : 'settings.providers.wizard.metaApiKey',
+ )}
onClick={() => pickPreset(p)}
/>
))}
@@ -836,32 +983,66 @@ export function AddProviderWizard({
{sel.provider.name}
</span>
<span className="text-12" style={{ color: 'var(--text-tertiary)' }}>
- {t('settings.providers.wizard.oauthDesc')}
+ {t(
+ sel.provider.auth.oauth?.flow === 'device-code'
+ ? 'settings.providers.wizard.deviceOAuthDesc'
+ : 'settings.providers.wizard.oauthDesc',
+ )}
</span>
</div>
</div>
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
{/* 等待授权中按钮变「取消」(与详情头对称),不禁用——浏览器流挂起时用户必须能中止重试。 */}
- <button
- type="button"
- onClick={() => {
- if (loggingIn) cancelAuthorize();
- else void handleAuthorize();
- }}
- className="flex h-9 items-center justify-center gap-2 rounded-full border px-5 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
- style={{
- backgroundColor: 'var(--settings-btn-secondary-bg)',
- borderColor: 'var(--settings-btn-secondary-border)',
- color: 'var(--settings-btn-secondary-text)',
- }}
- >
- {loggingIn && <Spinner size={13} />}
- {t(
- loggingIn
- ? 'settings.providers.button.cancel'
- : 'settings.providers.button.authorize',
- )}
- </button>
+ {loggingIn ? (
+ <button
+ type="button"
+ onClick={cancelAuthorize}
+ className="flex h-9 items-center justify-center gap-2 rounded-full border px-5 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ style={{
+ backgroundColor: 'var(--settings-btn-secondary-bg)',
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ <Spinner size={13} />
+ {t('settings.providers.button.cancel')}
+ </button>
+ ) : (
+ <>
+ <button
+ type="button"
+ onClick={() => void handleAuthorize('browser')}
+ className="flex h-9 items-center justify-center rounded-full border px-5 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ style={{
+ backgroundColor: 'var(--settings-btn-secondary-bg)',
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ {t(
+ sel.provider.id === 'openai'
+ ? 'settings.providers.wizard.authorizeInBrowser'
+ : sel.provider.auth.oauth?.flow === 'device-code'
+ ? 'settings.providers.wizard.authorizeWithDeviceCode'
+ : 'settings.providers.button.authorize',
+ )}
+ </button>
+ {sel.provider.id === 'openai' && (
+ <button
+ type="button"
+ onClick={() => void handleAuthorize('device-code')}
+ className="flex h-9 items-center justify-center rounded-full border px-5 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ style={{
+ backgroundColor: 'transparent',
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ {t('settings.providers.wizard.authorizeWithDeviceCode')}
+ </button>
+ )}
+ </>
+ )}
{/* 替代路径:API 用户没有订阅,OAuth 对其是错误路径——切到该渠道的
官方 API 预设表单(填 key),与从目录选预设完全同一条流水线。
与「授权」并排的次级描边按钮(White Pill):小灰字形态用户根本
@@ -882,6 +1063,10 @@ export function AddProviderWizard({
</button>
)}
</div>
+ {openAiDeviceLoginPending && <OAuthDeviceCodeCard deviceCode={openAiDeviceCode} />}
+ {genericDeviceFlow && loggingIn && (
+ <OAuthDeviceCodeCard deviceCode={genericDeviceCode} />
+ )}
{oauthSingleAgentNote && <InfoLine text={oauthSingleAgentNote} />}
</div>
)}
@@ -904,26 +1089,30 @@ export function AddProviderWizard({
}}
/>
</div>
- <div className="flex flex-col gap-1.5">
- <label className="text-12 font-medium" style={{ color: 'var(--text-secondary)' }}>
- {t('settings.providers.custom.fields.apiKey')}
- </label>
- <input
- type="password"
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- placeholder="sk-…"
- autoComplete="off"
- className="h-9 rounded-full border px-4 font-mono text-13 outline-none focus:ring-2 focus:ring-[var(--focus-ring)]"
- style={{
- borderColor: 'var(--border-default)',
- backgroundColor: 'var(--surface-elevated)',
- color: 'var(--settings-section-title)',
- }}
- />
- </div>
- {/* 官方渠道 URL 只读;本机/自托管预设可在创建时改 host/port。
- codex + openai-chat 上游标注「Cindy 桥接」,让用户明确该通道是协议转换而非原生。 */}
+ {presetNeedsApiKey ? (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-12 font-medium" style={{ color: 'var(--text-secondary)' }}>
+ {t('settings.providers.custom.fields.apiKey')}
+ </label>
+ <input
+ type="password"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ placeholder="sk-…"
+ autoComplete="off"
+ className="h-9 rounded-full border px-4 font-mono text-13 outline-none focus:ring-2 focus:ring-[var(--focus-ring)]"
+ style={{
+ borderColor: 'var(--border-default)',
+ backgroundColor: 'var(--surface-elevated)',
+ color: 'var(--settings-section-title)',
+ }}
+ />
+ </div>
+ ) : (
+ <InfoLine text={t('settings.providers.wizard.noAuthNote')} />
+ )}
+ {/* 官方端点默认只读;本机 / 自托管代理预设可编辑。codex + openai-chat
+ 上游标注「Cindy 桥接」,让用户明确该通道是协议转换而非原生。 */}
<div className="flex flex-col gap-2">
{presetAgents.map((agent) => {
const rt = sel.preset.runtimes[agent];
@@ -933,16 +1122,23 @@ export function AddProviderWizard({
const valid = isValidEditablePresetBaseUrl(value.trim());
return (
<label key={agent} className="flex flex-col gap-1.5">
- <span className="text-12 font-medium" style={{ color: 'var(--text-secondary)' }}>
- {t('settings.providers.custom.fields.baseUrl')} · {AGENT_LABEL[agent]}
+ <span
+ className="text-12 font-medium"
+ style={{ color: 'var(--text-secondary)' }}
+ >
+ {t('settings.providers.wizard.endpointLabel', {
+ agent: AGENT_LABEL[agent],
+ })}
</span>
<input
type="url"
value={value}
- onChange={(event) => setPresetBaseUrls((prev) => ({
- ...prev,
- [agent]: event.target.value,
- }))}
+ onChange={(event) =>
+ setPresetBaseUrls((prev) => ({
+ ...prev,
+ [agent]: event.target.value,
+ }))
+ }
aria-invalid={!valid}
className="h-9 rounded-full border px-4 font-mono text-12 outline-none focus:ring-2 focus:ring-[var(--focus-ring)]"
style={{
@@ -1001,76 +1197,134 @@ export function AddProviderWizard({
{fetchState.status === 'done' && fetchState.failed && (
<InfoLine text={t('settings.providers.wizard.fetchFailed')} />
)}
- <div
- className="flex flex-col overflow-hidden rounded-xl border"
- style={{ borderColor: 'var(--border-default)' }}
- >
- {[...picks.entries()].map(([id, v], i) => (
- <button
- key={id}
- type="button"
- onClick={() =>
- setPicks((prev) => {
- const next = new Map(prev);
- const cur = next.get(id);
- if (cur) next.set(id, { ...cur, checked: !cur.checked });
- return next;
- })
- }
- className={cn(
- 'flex items-center gap-2.5 px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--surface-hover)]',
- i > 0 && 'border-t',
- )}
- style={{ borderColor: 'var(--border-default)' }}
- >
- <span
- className="flex h-4 w-4 shrink-0 items-center justify-center rounded border"
- style={
- v.checked
- ? {
- backgroundColor: 'var(--accent-cta-bg)',
- borderColor: 'var(--accent-cta-bg)',
- color: 'var(--surface-on-card)',
- }
- : { borderColor: 'var(--text-tertiary)' }
+ {picks.size > 0 && (
+ <div
+ className="flex flex-col overflow-hidden rounded-xl border"
+ style={{ borderColor: 'var(--border-default)' }}
+ >
+ {[...picks.entries()].map(([id, v], i) => (
+ <button
+ key={id}
+ type="button"
+ onClick={() =>
+ setPicks((prev) => {
+ const next = new Map(prev);
+ const cur = next.get(id);
+ if (cur) next.set(id, { ...cur, checked: !cur.checked });
+ return next;
+ })
}
+ className={cn(
+ 'flex items-center gap-2.5 px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--surface-hover)]',
+ i > 0 && 'border-t',
+ )}
+ style={{ borderColor: 'var(--border-default)' }}
>
- {v.checked && <Check size={11} strokeWidth={3} />}
- </span>
- <span
- className="min-w-0 flex-1 truncate text-13"
- style={{ color: 'var(--settings-section-title)' }}
- >
- {v.name}
- </span>
- {/* 双 runtime 预设里单端归属的模型,标注能力事实(与管理页同措辞)。 */}
- {presetAgents.length > 1 && v.agents.length === 1 && (
<span
- className="shrink-0 text-12"
- style={{ color: 'var(--text-tertiary)' }}
+ className="flex h-4 w-4 shrink-0 items-center justify-center rounded border"
+ style={
+ v.checked
+ ? {
+ backgroundColor: 'var(--accent-cta-bg)',
+ borderColor: 'var(--accent-cta-bg)',
+ color: 'var(--surface-on-card)',
+ }
+ : { borderColor: 'var(--text-tertiary)' }
+ }
>
- {t('settings.providers.models.capabilityNote', {
- agent:
- AGENT_LABEL[
- v.agents[0] === 'claude-code' ? 'codex' : 'claude-code'
- ],
- })}
+ {v.checked && <Check size={11} strokeWidth={3} />}
</span>
- )}
- {v.recommended && (
<span
- className="flex h-[18px] shrink-0 items-center rounded-full px-2 text-11 font-medium"
- style={{
- backgroundColor: 'var(--surface-chip)',
- color: 'var(--text-secondary)',
- }}
+ className="min-w-0 flex-1 truncate text-13"
+ style={{ color: 'var(--settings-section-title)' }}
>
- {t('settings.providers.wizard.recommended')}
+ {v.name}
</span>
- )}
- </button>
- ))}
- </div>
+ {/* 双 runtime 预设里单端归属的模型,标注能力事实(与管理页同措辞)。 */}
+ {presetAgents.length > 1 && v.agents.length === 1 && (
+ <span
+ className="shrink-0 text-12"
+ style={{ color: 'var(--text-tertiary)' }}
+ >
+ {t('settings.providers.models.capabilityNote', {
+ agent:
+ AGENT_LABEL[
+ v.agents[0] === 'claude-code' ? 'codex' : 'claude-code'
+ ],
+ })}
+ </span>
+ )}
+ {v.recommended && (
+ <span
+ className="flex h-[18px] shrink-0 items-center rounded-full px-2 text-11 font-medium"
+ style={{
+ backgroundColor: 'var(--surface-chip)',
+ color: 'var(--text-secondary)',
+ }}
+ >
+ {t('settings.providers.wizard.recommended')}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ )}
+ {showManualModelFallback && (
+ <div
+ className="flex flex-col gap-3 rounded-xl border p-3.5"
+ style={{ borderColor: 'var(--border-default)' }}
+ >
+ <InfoLine text={t('settings.providers.wizard.manualModelHint')} />
+ {presetAgents.map((agent) => (
+ <label key={agent} className="flex flex-col gap-1.5">
+ <span
+ className="text-12 font-medium"
+ style={{ color: 'var(--text-secondary)' }}
+ >
+ {t('settings.providers.wizard.manualModelLabel', {
+ agent: AGENT_LABEL[agent],
+ })}
+ </span>
+ <span className="flex items-center gap-2">
+ <input
+ type="text"
+ value={manualModelIds[agent] ?? ''}
+ onChange={(event) =>
+ setManualModelIds((prev) => ({
+ ...prev,
+ [agent]: event.target.value,
+ }))
+ }
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter') return;
+ event.preventDefault();
+ addManualModel(agent);
+ }}
+ placeholder={t('settings.providers.wizard.manualModelPlaceholder')}
+ className="h-9 min-w-0 flex-1 rounded-full border px-4 font-mono text-12 outline-none focus:ring-2 focus:ring-[var(--focus-ring)]"
+ style={{
+ borderColor: 'var(--border-default)',
+ backgroundColor: 'var(--surface-elevated)',
+ color: 'var(--settings-section-title)',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => addManualModel(agent)}
+ disabled={!manualModelIds[agent]?.trim()}
+ className="flex h-9 shrink-0 items-center justify-center rounded-full border px-4 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)] disabled:opacity-50"
+ style={{
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ {t('settings.providers.wizard.addManualModel')}
+ </button>
+ </span>
+ </label>
+ ))}
+ </div>
+ )}
<p className="text-11 leading-snug" style={{ color: 'var(--text-tertiary)' }}>
{t('settings.providers.wizard.modelsHint')}
</p>
@@ -1122,12 +1376,10 @@ export function AddProviderWizard({
<button
type="button"
onClick={() => void startFetch()}
- disabled={apiKey.trim().length === 0 || !presetBaseUrlsValid}
+ disabled={!presetCanContinue}
className={cn(
'flex h-9 items-center justify-center rounded-full px-5 text-13 font-medium transition-opacity',
- apiKey.trim().length === 0 || !presetBaseUrlsValid
- ? 'cursor-not-allowed opacity-50'
- : 'hover:opacity-90',
+ !presetCanContinue ? 'cursor-not-allowed opacity-50' : 'hover:opacity-90',
)}
style={{ backgroundColor: 'var(--accent-cta-bg)', color: 'var(--surface-on-card)' }}
>
diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
index 151ac79781..b39206d388 100644
--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
@@ -12,7 +12,18 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Check, ChevronDown, Eye, EyeOff, Plug, Plus, RefreshCw, Sparkles, Trash2, X } from 'lucide-react';
+import {
+ Check,
+ ChevronDown,
+ Eye,
+ EyeOff,
+ Plug,
+ Plus,
+ RefreshCw,
+ Sparkles,
+ Trash2,
+ X,
+} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
@@ -29,8 +40,15 @@ import {
type RuntimeKeys,
} from '@/lib/customProviders';
import { uniqueCustomProviderId } from '@/lib/customProviderId';
+import {
+ areProviderRequestUrlsAllowed,
+ providerConnectionTestRequestSignature,
+ providerModelFetchRequestSignature,
+ stripCredentialHeaders,
+ type CustomProviderAuthMode,
+} from '@/lib/providerModelFetch';
-import { sortPresetsForLocale } from '@cindy/model-providers';
+import { isProviderRequestPath, sortPresetsForLocale } from '@cindy/model-providers';
import type {
AgentKind,
CustomProviderConfig,
@@ -43,18 +61,19 @@ const AGENTS: AgentKind[] = ['claude-code', 'codex'];
const VISIBLE_AGENTS: AgentKind[] = AGENTS;
-const TAB_META: Record<AgentKind, { Mark: typeof ClaudeMark; labelKey: string; helpKey: string }> = {
- 'claude-code': {
- Mark: ClaudeMark,
- labelKey: 'settings.providers.custom.protocol.claude',
- helpKey: 'settings.providers.custom.protocol.claudeDesc',
- },
- codex: {
- Mark: CodexMark,
- labelKey: 'settings.providers.custom.protocol.codex',
- helpKey: 'settings.providers.custom.protocol.codexDesc',
- },
-};
+const TAB_META: Record<AgentKind, { Mark: typeof ClaudeMark; labelKey: string; helpKey: string }> =
+ {
+ 'claude-code': {
+ Mark: ClaudeMark,
+ labelKey: 'settings.providers.custom.protocol.claude',
+ helpKey: 'settings.providers.custom.protocol.claudeDesc',
+ },
+ codex: {
+ Mark: CodexMark,
+ labelKey: 'settings.providers.custom.protocol.codex',
+ helpKey: 'settings.providers.custom.protocol.codexDesc',
+ },
+ };
interface CustomProviderDialogProps {
initial?: CustomProviderConfig;
@@ -71,6 +90,7 @@ interface HeaderRow {
}
interface RuntimeFields {
baseUrl: string;
+ requestPath: string;
apiKey: string;
wireProtocol: ProviderWireProtocol;
models: ModelRow[];
@@ -91,6 +111,7 @@ const IDLE_TEST: TestState = { status: 'idle' };
function emptyRuntime(agent: AgentKind): RuntimeFields {
return {
baseUrl: '',
+ requestPath: '',
apiKey: '',
wireProtocol: agent === 'claude-code' ? 'anthropic-messages' : 'openai-responses',
models: [{ id: '', name: '' }],
@@ -110,8 +131,10 @@ function initRuntimes(initial?: CustomProviderConfig): Record<AgentKind, Runtime
if (!rc) continue;
out[a] = {
baseUrl: rc.baseUrl,
+ requestPath: rc.requestPath ?? '',
apiKey: '',
- wireProtocol: rc.wireProtocol ?? (a === 'claude-code' ? 'anthropic-messages' : 'openai-responses'),
+ wireProtocol:
+ rc.wireProtocol ?? (a === 'claude-code' ? 'anthropic-messages' : 'openai-responses'),
models: rc.models.length ? rc.models.map((m) => ({ ...m })) : [{ id: '', name: '' }],
headers:
rc.headers && Object.keys(rc.headers).length > 0
@@ -259,9 +282,15 @@ function PresetDropdown({
// ── 主组件 ─────────────────────────────────────────────────────────────────
-export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }: CustomProviderDialogProps) {
+export function CustomProviderDialog({
+ initial,
+ existingIds,
+ onSaved,
+ onClose,
+}: CustomProviderDialogProps) {
const { t, i18n } = useTranslation();
const editing = !!initial;
+ const initialOAuth = initial?.auth?.method === 'oauth' ? initial.auth.oauth : undefined;
const [name, setName] = useState(initial?.name ?? '');
const [rt, setRt] = useState<Record<AgentKind, RuntimeFields>>(() => initRuntimes(initial));
@@ -269,17 +298,35 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
() => (initial && VISIBLE_AGENTS.find((a) => initial.runtimes[a])) || 'claude-code',
);
const [showKey, setShowKey] = useState(false);
- const [hasKey, setHasKey] = useState<Record<AgentKind, boolean>>({ 'claude-code': false, codex: false });
+ const [hasKey, setHasKey] = useState<Record<AgentKind, boolean>>({
+ 'claude-code': false,
+ codex: false,
+ });
const [saving, setSaving] = useState(false);
- // 鉴权形态:apiKey(默认)/ oauth(订阅授权,走通用 OAuth Runner)。
- const [authMode, setAuthMode] = useState<'apiKey' | 'oauth'>(
- initial?.auth?.method === 'oauth' ? 'oauth' : 'apiKey',
+ // 鉴权形态:API key(默认)/ OAuth / 无鉴权(本机或受信自托管代理)。
+ const [authMode, setAuthModeState] = useState<CustomProviderAuthMode>(
+ initial?.auth?.method === 'oauth'
+ ? 'oauth'
+ : initial?.auth?.method === 'none'
+ ? 'none'
+ : 'apiKey',
+ );
+ const authModeRef = useRef(authMode);
+ const setAuthMode = useCallback((mode: CustomProviderAuthMode) => {
+ authModeRef.current = mode;
+ setAuthModeState(mode);
+ }, []);
+ const [oauthFlow, setOauthFlow] = useState<'authorization-code' | 'device-code'>(
+ initialOAuth?.flow === 'device-code' ? 'device-code' : 'authorization-code',
);
const [oauthFields, setOauthFields] = useState({
- authorizeUrl: initial?.auth?.oauth?.authorizeUrl ?? '',
- tokenUrl: initial?.auth?.oauth?.tokenUrl ?? '',
- clientId: initial?.auth?.oauth?.clientId ?? '',
- scopes: initial?.auth?.oauth?.scopes ?? '',
+ authorizeUrl:
+ initialOAuth && initialOAuth.flow !== 'device-code' ? initialOAuth.authorizeUrl : '',
+ deviceAuthorizationUrl:
+ initialOAuth?.flow === 'device-code' ? initialOAuth.deviceAuthorizationUrl : '',
+ tokenUrl: initialOAuth?.tokenUrl ?? '',
+ clientId: initialOAuth?.clientId ?? '',
+ scopes: initialOAuth?.scopes ?? '',
});
// OAuth 模式下模型 / 请求头收进默认折叠的「高级配置」——模型授权后自动发现,普通用户无需碰。
const [showAdvanced, setShowAdvanced] = useState(false);
@@ -340,35 +387,41 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
}, [editing, i18n.language]);
/** 应用预设:预填显示名 + 各 runtime 的 baseUrl / 模型 / headers(创建时快照,之后与预设脱钩)。 */
- const applyPreset = useCallback((p: ProviderPreset) => {
- setAppliedPreset(p.id);
- setName(p.name);
- setRtSynced((prev) => {
- const next = { ...prev };
- for (const a of AGENTS) {
- const rc = p.runtimes[a];
- if (!rc) {
- next[a] = emptyRuntime(a);
- continue;
+ const applyPreset = useCallback(
+ (p: ProviderPreset) => {
+ setAppliedPreset(p.id);
+ setName(p.name);
+ setAuthMode(p.authMethod ?? 'apiKey');
+ setRtSynced((prev) => {
+ const next = { ...prev };
+ for (const a of AGENTS) {
+ const rc = p.runtimes[a];
+ if (!rc) {
+ next[a] = emptyRuntime(a);
+ continue;
+ }
+ next[a] = {
+ baseUrl: rc.baseUrl,
+ requestPath: rc.requestPath ?? '',
+ apiKey: prev[a].apiKey, // 已填的 key 保留
+ wireProtocol:
+ rc.wireProtocol ?? (a === 'claude-code' ? 'anthropic-messages' : 'openai-responses'),
+ models: rc.models.length ? rc.models.map((m) => ({ ...m })) : [{ id: '', name: '' }],
+ headers:
+ rc.headers && Object.keys(rc.headers).length > 0
+ ? Object.entries(rc.headers).map(([n, v]) => ({ name: n, value: v }))
+ : [{ name: '', value: '' }],
+ modelsUrl: rc.modelsUrl ?? '',
+ };
}
- next[a] = {
- baseUrl: rc.baseUrl,
- apiKey: prev[a].apiKey, // 已填的 key 保留
- wireProtocol: rc.wireProtocol ?? (a === 'claude-code' ? 'anthropic-messages' : 'openai-responses'),
- models: rc.models.length ? rc.models.map((m) => ({ ...m })) : [{ id: '', name: '' }],
- headers:
- rc.headers && Object.keys(rc.headers).length > 0
- ? Object.entries(rc.headers).map(([n, v]) => ({ name: n, value: v }))
- : [{ name: '', value: '' }],
- modelsUrl: rc.modelsUrl ?? '',
- };
- }
- return next;
- });
- setTest({ 'claude-code': IDLE_TEST, codex: IDLE_TEST });
- const first = AGENTS.find((a) => p.runtimes[a]);
- if (first) setActiveTab(first);
- }, [setRtSynced]);
+ return next;
+ });
+ setTest({ 'claude-code': IDLE_TEST, codex: IDLE_TEST });
+ const first = AGENTS.find((a) => p.runtimes[a]);
+ if (first) setActiveTab(first);
+ },
+ [setRtSynced],
+ );
// 编辑态:回填各已配置 runtime 的已存明文密钥(用户本机自己的 key)——
// 让密钥框「能看」(eye 显形 / 可核对),而非空白遮罩;据此点亮「已保存」徽标。
@@ -404,6 +457,7 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
const patch = useCallback(
(agent: AgentKind, fn: (f: RuntimeFields) => RuntimeFields) => {
setRtSynced((prev) => ({ ...prev, [agent]: fn(prev[agent]) }));
+ setTest((prev) => ({ ...prev, [agent]: IDLE_TEST }));
},
[setRtSynced],
);
@@ -432,11 +486,17 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
toast.error(t('settings.providers.custom.test.needFields'));
return;
}
+ if (!areProviderRequestUrlsAllowed(authMode, baseUrl)) {
+ toast.error(t('settings.providers.custom.errors.baseUrlInvalid'));
+ return;
+ }
const headers: Record<string, string> = {};
for (const h of rf.headers) {
const n = h.name.trim();
if (n) headers[n] = h.value.trim();
}
+ const requestHeaders = authMode === 'none' ? stripCredentialHeaders(headers) : headers;
+ const requestSig = providerConnectionTestRequestSignature(rf, authMode);
setTest((prev) => ({ ...prev, [agent]: { status: 'testing' } }));
try {
const result = await window.electronAPI.maker.testProviderConnection({
@@ -445,11 +505,18 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
agent,
baseUrl,
modelId: firstModel,
+ authMethod: authMode,
wireProtocol: rf.wireProtocol,
- apiKey: rf.apiKey.trim() || null,
- ...(Object.keys(headers).length > 0 ? { headers } : {}),
+ ...(rf.requestPath.trim() ? { requestPath: rf.requestPath.trim() } : {}),
+ apiKey: authMode === 'apiKey' ? rf.apiKey.trim() || null : null,
+ ...(Object.keys(requestHeaders).length > 0 ? { headers: requestHeaders } : {}),
},
});
+ if (
+ providerConnectionTestRequestSignature(rtRef.current[agent], authModeRef.current) !==
+ requestSig
+ )
+ return;
setTest((prev) => ({
...prev,
[agent]: result.ok
@@ -457,28 +524,21 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
: { status: 'fail', code: result.code ?? 'UNKNOWN' },
}));
} catch (e) {
+ if (
+ providerConnectionTestRequestSignature(rtRef.current[agent], authModeRef.current) !==
+ requestSig
+ )
+ return;
const ipc = extractIpcError(e);
setTest((prev) => ({ ...prev, [agent]: { status: 'fail', code: 'UNKNOWN' } }));
if (ipc?.message) toast.error(ipc.message);
}
- }, [activeTab, rt, t]);
+ }, [activeTab, authMode, rt, t]);
// 拉取单飞:任一 runtime 在途时两个 Tab 的拉取按钮都禁用——两个并发请求会竞争同一个
// 勾选弹层(后到的覆盖先开的、确认还会写进另一个 runtime),单飞直接消掉这类竞态。
const anyFetching = fetchingModels['claude-code'] || fetchingModels.codex;
- /** runtime 里参与拉取请求的字段的规范化签名(过期响应判据:签名变了 = 响应作废)。 */
- const fetchRequestSignature = (f: RuntimeFields): string =>
- JSON.stringify({
- b: f.baseUrl.trim(),
- m: f.modelsUrl.trim(),
- k: f.apiKey.trim(),
- h: f.headers
- .map((h) => [h.name.trim(), h.value.trim()])
- .filter(([n]) => n)
- .sort((a, b) => (a[0]! < b[0]! ? -1 : a[0]! > b[0]! ? 1 : 0)),
- });
-
/** 获取模型列表:用当前 Tab 表单值 GET 列模型端点(key 仅内存透传),成功后开勾选弹层。 */
const handleFetchModels = useCallback(async () => {
const agent = activeTab;
@@ -489,24 +549,33 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
toast.error(t('settings.providers.custom.fetch.needBaseUrl'));
return;
}
+ if (!areProviderRequestUrlsAllowed(authMode, baseUrl, rf.modelsUrl)) {
+ toast.error(t('settings.providers.custom.errors.baseUrlInvalid'));
+ return;
+ }
const headers: Record<string, string> = {};
for (const h of rf.headers) {
const n = h.name.trim();
if (n) headers[n] = h.value.trim();
}
+ const requestHeaders = authMode === 'none' ? stripCredentialHeaders(headers) : headers;
// 请求参数签名:响应回来时若该 runtime 的端点/凭证/请求头已被改动,响应按过期丢弃——
// 不能把旧端点的模型清单当成新端点的填进表单(成功和失败 toast 都不展示)。
- const requestSig = fetchRequestSignature(rf);
+ const requestSig = providerModelFetchRequestSignature(rf, authMode);
setFetchingModels((prev) => ({ ...prev, [agent]: true }));
try {
const result = await window.electronAPI.maker.fetchProviderModels({
agent,
baseUrl,
+ authMethod: authMode,
modelsUrl: rf.modelsUrl.trim() || null,
- apiKey: rf.apiKey.trim() || null,
- ...(Object.keys(headers).length > 0 ? { headers } : {}),
+ apiKey: authMode === 'apiKey' ? rf.apiKey.trim() || null : null,
+ ...(Object.keys(requestHeaders).length > 0 ? { headers: requestHeaders } : {}),
});
- if (fetchRequestSignature(rtRef.current[agent]) !== requestSig) return; // 过期响应,静默丢弃
+ if (
+ providerModelFetchRequestSignature(rtRef.current[agent], authModeRef.current) !== requestSig
+ )
+ return; // 过期响应,静默丢弃
if (result.ok && result.models && result.models.length > 0) {
// 用**响应到达时**的最新表单行构建弹层(rtRef),不是请求发出时的 rf 快照。
const current = rtRef.current[agent].models
@@ -529,9 +598,7 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
return {
id: m.id,
name: cur?.name || m.name,
- ...(cur?.contextWindow !== undefined
- ? { contextWindow: cur.contextWindow }
- : {}),
+ ...(cur?.contextWindow !== undefined ? { contextWindow: cur.contextWindow } : {}),
...(cur?.defaultEnabled === false ? { defaultEnabled: false } : {}),
};
}),
@@ -544,13 +611,16 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
toast.error(t(`providerError.${result.code ?? 'UNKNOWN'}`));
}
} catch (e) {
- if (fetchRequestSignature(rtRef.current[agent]) !== requestSig) return; // 过期失败同样静默
+ if (
+ providerModelFetchRequestSignature(rtRef.current[agent], authModeRef.current) !== requestSig
+ )
+ return; // 过期失败同样静默
const ipc = extractIpcError(e);
toast.error(ipc?.message ?? t('settings.providers.custom.fetch.failed'));
} finally {
setFetchingModels((prev) => ({ ...prev, [agent]: false }));
}
- }, [activeTab, rt, fetchingModels, t]);
+ }, [activeTab, authMode, rt, fetchingModels, t]);
/**
* 勾选弹层确认:勾选集写回该 runtime 的模型行。基于**确认时的最新表单行**合并,
@@ -621,6 +691,11 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
toast.error(t('settings.providers.custom.errors.baseUrlInvalid'));
return;
}
+ if (!areProviderRequestUrlsAllowed(authMode, rf.baseUrl, rf.modelsUrl)) {
+ setActiveTab(a);
+ toast.error(t('settings.providers.custom.errors.baseUrlInvalid'));
+ return;
+ }
const models = rf.models
.map((m) => ({
id: m.id.trim(),
@@ -629,6 +704,12 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
}))
.filter((m) => m.id && m.name);
+ const requestPath = rf.requestPath.trim();
+ if (requestPath && !isProviderRequestPath(requestPath)) {
+ setActiveTab(a);
+ toast.error(t('settings.providers.custom.errors.requestPathInvalid'));
+ return;
+ }
// OAuth 形态模型可留空——授权成功后自动发现并持久化(与内置订阅统一)。
if (models.length === 0 && authMode !== 'oauth') {
setActiveTab(a);
@@ -640,12 +721,14 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
const n = h.name.trim();
if (n) headers[n] = h.value.trim();
}
+ const savedHeaders = authMode === 'none' ? stripCredentialHeaders(headers) : headers;
const defaultProtocol = a === 'claude-code' ? 'anthropic-messages' : 'openai-responses';
runtimes[a] = {
baseUrl: rf.baseUrl.trim(),
+ ...(requestPath ? { requestPath } : {}),
...(rf.wireProtocol !== defaultProtocol ? { wireProtocol: rf.wireProtocol } : {}),
models,
- ...(Object.keys(headers).length > 0 ? { headers } : {}),
+ ...(Object.keys(savedHeaders).length > 0 ? { headers: savedHeaders } : {}),
...(rf.modelsUrl.trim() ? { modelsUrl: rf.modelsUrl.trim() } : {}),
};
// OAuth 形态不收集 per-runtime API key(鉴权走 Runner 的 Bearer)。
@@ -658,30 +741,83 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
// OAuth 形态:四个必填字段 + 端点必须 https(与 main 侧校验同规则,先在表单挡住)。
let auth: CustomProviderConfig['auth'];
if (authMode === 'oauth') {
- const o = {
- authorizeUrl: oauthFields.authorizeUrl.trim(),
- tokenUrl: oauthFields.tokenUrl.trim(),
- clientId: oauthFields.clientId.trim(),
- scopes: oauthFields.scopes.trim(),
- };
+ const tokenUrl = oauthFields.tokenUrl.trim();
+ const clientId = oauthFields.clientId.trim();
+ const scopes = oauthFields.scopes.trim();
const httpsOk = (u: string) => {
try {
- return new URL(u).protocol === 'https:';
+ const url = new URL(u);
+ return url.protocol === 'https:' && !url.username && !url.password;
} catch {
return false;
}
};
- if (!o.authorizeUrl || !o.tokenUrl || !o.clientId || !o.scopes || !httpsOk(o.authorizeUrl) || !httpsOk(o.tokenUrl)) {
+ const flowUrl =
+ oauthFlow === 'device-code'
+ ? oauthFields.deviceAuthorizationUrl.trim()
+ : oauthFields.authorizeUrl.trim();
+ if (
+ !flowUrl ||
+ !tokenUrl ||
+ !clientId ||
+ !scopes ||
+ !httpsOk(flowUrl) ||
+ !httpsOk(tokenUrl)
+ ) {
toast.error(t('settings.providers.custom.errors.oauthInvalid'));
return;
}
- auth = { method: 'oauth', oauth: o };
+ auth = {
+ method: 'oauth',
+ oauth:
+ oauthFlow === 'device-code'
+ ? {
+ ...(initialOAuth?.flow === 'device-code' && initialOAuth.extraDeviceParams
+ ? { extraDeviceParams: { ...initialOAuth.extraDeviceParams } }
+ : {}),
+ ...(initialOAuth?.modelsDiscoveryUrl
+ ? { modelsDiscoveryUrl: initialOAuth.modelsDiscoveryUrl }
+ : {}),
+ flow: 'device-code',
+ deviceAuthorizationUrl: flowUrl,
+ tokenUrl,
+ clientId,
+ scopes,
+ }
+ : {
+ ...(initialOAuth && initialOAuth.flow !== 'device-code'
+ ? {
+ ...(initialOAuth.redirectPort !== undefined
+ ? { redirectPort: initialOAuth.redirectPort }
+ : {}),
+ ...(initialOAuth.extraAuthParams
+ ? { extraAuthParams: { ...initialOAuth.extraAuthParams } }
+ : {}),
+ }
+ : {}),
+ ...(initialOAuth?.modelsDiscoveryUrl
+ ? { modelsDiscoveryUrl: initialOAuth.modelsDiscoveryUrl }
+ : {}),
+ flow: 'authorization-code',
+ authorizeUrl: flowUrl,
+ tokenUrl,
+ clientId,
+ scopes,
+ },
+ };
+ } else if (authMode === 'none') {
+ auth = { method: 'none' };
}
const id =
editing && initial
? initial.id
: uniqueCustomProviderId(trimmedName, new Set(existingIds ?? []));
- const config: CustomProviderConfig = { id, name: trimmedName, ...(auth ? { auth } : {}), runtimes };
+ const config: CustomProviderConfig = {
+ id,
+ name: trimmedName,
+ ...(auth ? { auth } : {}),
+ runtimes,
+ };
setSaving(true);
try {
if (editing) {
@@ -699,7 +835,19 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
toast.error(ipc?.message ?? t('settings.providers.custom.toast.saveFailed'));
setSaving(false); // 仅失败时复位:弹窗仍在,允许改后重试
}
- }, [name, rt, authMode, oauthFields, editing, initial, existingIds, onSaved, t]);
+ }, [
+ name,
+ rt,
+ authMode,
+ oauthFlow,
+ oauthFields,
+ initialOAuth,
+ editing,
+ initial,
+ existingIds,
+ onSaved,
+ t,
+ ]);
const keyPlaceholder = hasKey[activeTab]
? t('settings.providers.custom.fields.apiKeyEditPlaceholder')
@@ -765,22 +913,27 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
/>
</div>
- {/* 鉴权形态:API 密钥(默认)/ OAuth 订阅授权(通用 Runner,凭证本机 safeStorage) */}
+ {/* 鉴权形态:API 密钥 / OAuth / 无鉴权。 */}
<div className="flex flex-col gap-2">
<FieldLabel>{t('settings.providers.custom.authMode.label')}</FieldLabel>
- <div className="flex gap-1.5">
- {(['apiKey', 'oauth'] as const).map((m) => (
+ <div className="flex flex-wrap gap-1.5">
+ {(['apiKey', 'oauth', 'none'] as const).map((m) => (
<button
key={m}
type="button"
- onClick={() => setAuthMode(m)}
+ onClick={() => {
+ setAuthMode(m);
+ setTest({ 'claude-code': IDLE_TEST, codex: IDLE_TEST });
+ }}
className={cn(
'rounded-full border px-3 py-1.5 text-12 font-medium transition-colors',
authMode === m
? 'border-[var(--settings-input-border-focus)] text-[var(--settings-section-title)]'
: 'border-[var(--settings-input-border)] text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]',
)}
- style={authMode === m ? { backgroundColor: 'var(--surface-elevated)' } : undefined}
+ style={
+ authMode === m ? { backgroundColor: 'var(--surface-elevated)' } : undefined
+ }
>
{t(`settings.providers.custom.authMode.${m}`)}
</button>
@@ -791,16 +944,48 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
<span className="text-12 leading-snug text-[var(--text-tertiary)]">
{t('settings.providers.custom.authMode.oauthHelp')}
</span>
+ <div className="flex flex-col gap-[7px]">
+ <FieldLabel>{t('settings.providers.custom.authMode.flowLabel')}</FieldLabel>
+ <div className="flex gap-1.5">
+ {(['authorization-code', 'device-code'] as const).map((flow) => (
+ <button
+ key={flow}
+ type="button"
+ onClick={() => setOauthFlow(flow)}
+ className={cn(
+ 'rounded-full border px-3 py-1.5 text-12 font-medium transition-colors',
+ oauthFlow === flow
+ ? 'border-[var(--settings-input-border-focus)] text-[var(--settings-section-title)]'
+ : 'border-[var(--settings-input-border)] text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]',
+ )}
+ style={
+ oauthFlow === flow
+ ? { backgroundColor: 'var(--surface-elevated)' }
+ : undefined
+ }
+ >
+ {t(`settings.providers.custom.authMode.flow.${flow}`)}
+ </button>
+ ))}
+ </div>
+ </div>
{(
[
- ['authorizeUrl', 'https://auth.example.com/oauth2/authorize'],
+ [
+ oauthFlow === 'device-code' ? 'deviceAuthorizationUrl' : 'authorizeUrl',
+ oauthFlow === 'device-code'
+ ? 'https://auth.example.com/oauth2/device'
+ : 'https://auth.example.com/oauth2/authorize',
+ ],
['tokenUrl', 'https://auth.example.com/oauth2/token'],
['clientId', 'client_id'],
['scopes', 'openid offline_access ...'],
] as const
).map(([field, ph]) => (
<div key={field} className="flex flex-col gap-[7px]">
- <FieldLabel>{t(`settings.providers.custom.authMode.fields.${field}`)}</FieldLabel>
+ <FieldLabel>
+ {t(`settings.providers.custom.authMode.fields.${field}`)}
+ </FieldLabel>
<TextInput
value={oauthFields[field]}
onChange={(v) => setOauthFields((prev) => ({ ...prev, [field]: v }))}
@@ -810,10 +995,14 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
))}
</>
)}
+ {authMode === 'none' && (
+ <span className="text-12 leading-snug text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.authMode.noneHelp')}
+ </span>
+ )}
</div>
- {/* Runtime 分段 Tab —— Codex 暂时关闭(VISIBLE_AGENTS 只剩 Claude Code),Tab 栏减少为一个,
- 但仍保留显示。 */}
+ {/* Runtime 分段 Tab:Claude Code 与 Codex 各自维护端点、协议、模型与凭证。 */}
<div className="flex flex-col gap-2">
<FieldLabel>{t('settings.providers.custom.fields.protocols')}</FieldLabel>
<div
@@ -887,14 +1076,22 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
? 'border-[var(--settings-input-border-focus)] text-[var(--settings-section-title)]'
: 'border-[var(--settings-input-border)] text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]',
)}
- style={f.wireProtocol === protocol ? { backgroundColor: 'var(--surface-elevated)' } : undefined}
+ style={
+ f.wireProtocol === protocol
+ ? { backgroundColor: 'var(--surface-elevated)' }
+ : undefined
+ }
>
- {t(`settings.providers.custom.wireProtocol.${protocol === 'openai-responses' ? 'responses' : 'chat'}`)}
+ {t(
+ `settings.providers.custom.wireProtocol.${protocol === 'openai-responses' ? 'responses' : 'chat'}`,
+ )}
</button>
))}
</div>
<span className="text-12 leading-snug text-[var(--text-tertiary)]">
- {t(`settings.providers.custom.wireProtocol.${f.wireProtocol === 'openai-chat' ? 'chatHelp' : 'responsesHelp'}`)}
+ {t(
+ `settings.providers.custom.wireProtocol.${f.wireProtocol === 'openai-chat' ? 'chatHelp' : 'responsesHelp'}`,
+ )}
</span>
</div>
)}
@@ -909,45 +1106,66 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
/>
</div>
- {/* API 密钥(OAuth 形态隐藏——鉴权走 Runner 的 Bearer,不收集 key) */}
- {authMode === 'apiKey' && (
+ {/* 精确推理路径:给非标准兼容端点使用;留空仍按所选协议推导。 */}
<div className="flex flex-col gap-[7px]">
- <div className="flex items-center gap-2">
- <FieldLabel>{t('settings.providers.custom.fields.apiKey')}</FieldLabel>
- {/* 已存密钥时给明确徽标 —— 编辑态字段是遮罩空白(留空=不改),无徽标会让人误以为没存上。 */}
- {hasKey[activeTab] && (
- <span
- className="flex items-center gap-1 rounded-full px-2 py-0.5 text-11 font-medium"
- style={{
- backgroundColor: 'var(--settings-btn-secondary-bg)',
- color: 'var(--settings-section-desc)',
- }}
- >
- <Check size={11} strokeWidth={2.5} />
- {t('settings.providers.custom.fields.apiKeySaved')}
- </span>
- )}
- </div>
+ <FieldLabel>{t('settings.providers.custom.fields.requestPath')}</FieldLabel>
<TextInput
- value={f.apiKey}
- onChange={(v) => patch(activeTab, (x) => ({ ...x, apiKey: v }))}
- placeholder={keyPlaceholder}
- type={showKey ? 'text' : 'password'}
- trailing={
- <button
- type="button"
- onClick={() => setShowKey((v) => !v)}
- className="absolute right-[12px] top-1/2 -translate-y-1/2 text-[var(--settings-eye-icon)] transition-colors hover:text-[var(--settings-eye-icon-hover)]"
- aria-label={showKey ? t('settings.apiKey.hideKey') : t('settings.apiKey.showKey')}
- >
- {showKey ? <Eye size={16} /> : <EyeOff size={16} />}
- </button>
+ value={f.requestPath}
+ onChange={(v) => patch(activeTab, (x) => ({ ...x, requestPath: v }))}
+ placeholder={
+ activeTab === 'claude-code'
+ ? '/v1/messages'
+ : f.wireProtocol === 'openai-chat'
+ ? '/chat/completions'
+ : '/responses'
}
/>
- <span className="text-12 text-[var(--text-tertiary)]">
- {t('settings.providers.custom.fields.apiKeyHelp')}
+ <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' && (
+ <div className="flex flex-col gap-[7px]">
+ <div className="flex items-center gap-2">
+ <FieldLabel>{t('settings.providers.custom.fields.apiKey')}</FieldLabel>
+ {/* 已存密钥时给明确徽标 —— 编辑态字段是遮罩空白(留空=不改),无徽标会让人误以为没存上。 */}
+ {hasKey[activeTab] && (
+ <span
+ className="flex items-center gap-1 rounded-full px-2 py-0.5 text-11 font-medium"
+ style={{
+ backgroundColor: 'var(--settings-btn-secondary-bg)',
+ color: 'var(--settings-section-desc)',
+ }}
+ >
+ <Check size={11} strokeWidth={2.5} />
+ {t('settings.providers.custom.fields.apiKeySaved')}
+ </span>
+ )}
+ </div>
+ <TextInput
+ value={f.apiKey}
+ onChange={(v) => patch(activeTab, (x) => ({ ...x, apiKey: v }))}
+ placeholder={keyPlaceholder}
+ type={showKey ? 'text' : 'password'}
+ trailing={
+ <button
+ type="button"
+ onClick={() => setShowKey((v) => !v)}
+ className="absolute right-[12px] top-1/2 -translate-y-1/2 text-[var(--settings-eye-icon)] transition-colors hover:text-[var(--settings-eye-icon-hover)]"
+ aria-label={
+ showKey ? t('settings.apiKey.hideKey') : t('settings.apiKey.showKey')
+ }
+ >
+ {showKey ? <Eye size={16} /> : <EyeOff size={16} />}
+ </button>
+ }
+ />
+ <span className="text-12 text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.fields.apiKeyHelp')}
+ </span>
+ </div>
)}
{/* OAuth 形态:模型清单授权成功后自动发现(与内置订阅统一),模型 / 请求头
@@ -971,173 +1189,187 @@ export function CustomProviderDialog({ initial, existingIds, onSaved, onClose }:
</div>
)}
- {(authMode === 'apiKey' || showAdvanced) && (
- <>
- {/* 模型 */}
- <div className="flex flex-col gap-2">
- <FieldLabel>{t('settings.providers.custom.fields.models')}</FieldLabel>
- {f.models.map((m, i) => (
- <div key={i} className="flex items-center gap-2">
- <div className="flex-1">
- <TextInput
- value={m.id}
- onChange={(v) =>
- patch(activeTab, (x) => ({
- ...x,
- models: x.models.map((y, j) => (
- j === i ? replaceCustomProviderModelId(y, v) : y
- )),
- }))
- }
- placeholder={t('settings.providers.custom.fields.modelIdPlaceholder')}
- />
- </div>
- <div className="flex-1">
- <TextInput
- value={m.name}
- onChange={(v) =>
- patch(activeTab, (x) => ({
- ...x,
- models: x.models.map((y, j) => (j === i ? { ...y, name: v } : y)),
- }))
- }
- placeholder={t('settings.providers.custom.fields.modelNamePlaceholder')}
- />
- </div>
+ {(authMode !== 'oauth' || showAdvanced) && (
+ <>
+ {/* 模型 */}
+ <div className="flex flex-col gap-2">
+ <FieldLabel>{t('settings.providers.custom.fields.models')}</FieldLabel>
+ {f.models.map((m, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <div className="flex-1">
+ <TextInput
+ value={m.id}
+ onChange={(v) =>
+ patch(activeTab, (x) => ({
+ ...x,
+ models: x.models.map((y, j) =>
+ j === i ? replaceCustomProviderModelId(y, v) : y,
+ ),
+ }))
+ }
+ placeholder={t('settings.providers.custom.fields.modelIdPlaceholder')}
+ />
+ </div>
+ <div className="flex-1">
+ <TextInput
+ value={m.name}
+ onChange={(v) =>
+ patch(activeTab, (x) => ({
+ ...x,
+ models: x.models.map((y, j) => (j === i ? { ...y, name: v } : y)),
+ }))
+ }
+ placeholder={t('settings.providers.custom.fields.modelNamePlaceholder')}
+ />
+ </div>
+ <button
+ type="button"
+ onClick={() =>
+ patch(activeTab, (x) => ({
+ ...x,
+ models: x.models.filter((_, j) => j !== i),
+ }))
+ }
+ className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)]"
+ aria-label={t('settings.providers.custom.fields.removeRow')}
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ ))}
<button
type="button"
onClick={() =>
- patch(activeTab, (x) => ({ ...x, models: x.models.filter((_, j) => j !== i) }))
+ patch(activeTab, (x) => ({
+ ...x,
+ models: [...x.models, { id: '', name: '' }],
+ }))
}
- className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)]"
- aria-label={t('settings.providers.custom.fields.removeRow')}
+ className="flex items-center gap-1.5 self-start py-0.5 text-13 font-medium text-[var(--settings-section-title)]"
>
- <Trash2 size={16} />
+ <Plus size={14} className="text-[var(--settings-section-desc)]" />
+ {t('settings.providers.custom.fields.addModel')}
</button>
</div>
- ))}
- <button
- type="button"
- onClick={() => patch(activeTab, (x) => ({ ...x, models: [...x.models, { id: '', name: '' }] }))}
- className="flex items-center gap-1.5 self-start py-0.5 text-13 font-medium text-[var(--settings-section-title)]"
- >
- <Plus size={14} className="text-[var(--settings-section-desc)]" />
- {t('settings.providers.custom.fields.addModel')}
- </button>
- </div>
- {/* 请求头(可选) */}
- <div className="flex flex-col gap-2">
- <FieldLabel>{t('settings.providers.custom.fields.headers')}</FieldLabel>
- {f.headers.map((h, i) => (
- <div key={i} className="flex items-center gap-2">
- <div className="flex-1">
- <TextInput
- value={h.name}
- onChange={(v) =>
- patch(activeTab, (x) => ({
- ...x,
- headers: x.headers.map((y, j) => (j === i ? { ...y, name: v } : y)),
- }))
- }
- placeholder={t('settings.providers.custom.fields.headerNamePlaceholder')}
- />
- </div>
- <div className="flex-1">
- <TextInput
- value={h.value}
- onChange={(v) =>
- patch(activeTab, (x) => ({
- ...x,
- headers: x.headers.map((y, j) => (j === i ? { ...y, value: v } : y)),
- }))
- }
- placeholder={t('settings.providers.custom.fields.headerValuePlaceholder')}
- />
- </div>
+ {/* 请求头(可选) */}
+ <div className="flex flex-col gap-2">
+ <FieldLabel>{t('settings.providers.custom.fields.headers')}</FieldLabel>
+ {f.headers.map((h, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <div className="flex-1">
+ <TextInput
+ value={h.name}
+ onChange={(v) =>
+ patch(activeTab, (x) => ({
+ ...x,
+ headers: x.headers.map((y, j) => (j === i ? { ...y, name: v } : y)),
+ }))
+ }
+ placeholder={t('settings.providers.custom.fields.headerNamePlaceholder')}
+ />
+ </div>
+ <div className="flex-1">
+ <TextInput
+ value={h.value}
+ onChange={(v) =>
+ patch(activeTab, (x) => ({
+ ...x,
+ headers: x.headers.map((y, j) => (j === i ? { ...y, value: v } : y)),
+ }))
+ }
+ placeholder={t('settings.providers.custom.fields.headerValuePlaceholder')}
+ />
+ </div>
+ <button
+ type="button"
+ onClick={() =>
+ patch(activeTab, (x) => ({
+ ...x,
+ headers: x.headers.filter((_, j) => j !== i),
+ }))
+ }
+ className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)]"
+ aria-label={t('settings.providers.custom.fields.removeRow')}
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ ))}
<button
type="button"
onClick={() =>
- patch(activeTab, (x) => ({ ...x, headers: x.headers.filter((_, j) => j !== i) }))
+ patch(activeTab, (x) => ({
+ ...x,
+ headers: [...x.headers, { name: '', value: '' }],
+ }))
}
- className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)]"
- aria-label={t('settings.providers.custom.fields.removeRow')}
+ className="flex items-center gap-1.5 self-start py-0.5 text-13 font-medium text-[var(--settings-section-title)]"
>
- <Trash2 size={16} />
+ <Plus size={14} className="text-[var(--settings-section-desc)]" />
+ {t('settings.providers.custom.fields.addHeader')}
</button>
</div>
- ))}
- <button
- type="button"
- onClick={() => patch(activeTab, (x) => ({ ...x, headers: [...x.headers, { name: '', value: '' }] }))}
- className="flex items-center gap-1.5 self-start py-0.5 text-13 font-medium text-[var(--settings-section-title)]"
- >
- <Plus size={14} className="text-[var(--settings-section-desc)]" />
- {t('settings.providers.custom.fields.addHeader')}
- </button>
- </div>
- </>
+ </>
)}
{/* 测试连接:用当前 Tab 表单值发最小探测请求(与真实会话同路由口径,未保存也能测)。
OAuth 形态隐藏——登录前无凭证可测,保存并授权后可在供应商行验证。 */}
- {authMode === 'apiKey' && (
- <div className="flex min-h-[32px] flex-wrap items-center gap-2.5">
- <button
- type="button"
- onClick={() => void handleTest()}
- disabled={test[activeTab].status === 'testing'}
- className={cn(
- 'inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-12 font-medium transition-colors active:scale-[0.98]',
- 'border-[var(--settings-input-border)] text-[var(--settings-section-title)] hover:bg-[var(--surface-hover)]',
- test[activeTab].status === 'testing' && 'cursor-not-allowed opacity-60',
- )}
- >
- {test[activeTab].status === 'testing' ? (
- <Spinner size={13} />
- ) : (
- <Plug size={13} />
- )}
- {test[activeTab].status === 'testing'
- ? t('settings.providers.custom.test.testing')
- : t('settings.providers.custom.test.button')}
- </button>
- {/* 获取模型列表:GET 该供应商的列模型端点,成功后开勾选弹层填进上方模型行。
+ {authMode !== 'oauth' && (
+ <div className="flex min-h-[32px] flex-wrap items-center gap-2.5">
+ <button
+ type="button"
+ onClick={() => void handleTest()}
+ disabled={test[activeTab].status === 'testing'}
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-12 font-medium transition-colors active:scale-[0.98]',
+ 'border-[var(--settings-input-border)] text-[var(--settings-section-title)] hover:bg-[var(--surface-hover)]',
+ test[activeTab].status === 'testing' && 'cursor-not-allowed opacity-60',
+ )}
+ >
+ {test[activeTab].status === 'testing' ? (
+ <Spinner size={13} />
+ ) : (
+ <Plug size={13} />
+ )}
+ {test[activeTab].status === 'testing'
+ ? t('settings.providers.custom.test.testing')
+ : t('settings.providers.custom.test.button')}
+ </button>
+ {/* 获取模型列表:GET 该供应商的列模型端点,成功后开勾选弹层填进上方模型行。
disabled 用 anyFetching(单飞):另一 Tab 在途时本 Tab 也不许发起。 */}
- <button
- type="button"
- onClick={() => void handleFetchModels()}
- disabled={anyFetching}
- className={cn(
- 'inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-12 font-medium transition-colors active:scale-[0.98]',
- 'border-[var(--settings-input-border)] text-[var(--settings-section-title)] hover:bg-[var(--surface-hover)]',
- anyFetching && 'cursor-not-allowed opacity-60',
+ <button
+ type="button"
+ onClick={() => void handleFetchModels()}
+ disabled={anyFetching}
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-12 font-medium transition-colors active:scale-[0.98]',
+ 'border-[var(--settings-input-border)] text-[var(--settings-section-title)] hover:bg-[var(--surface-hover)]',
+ anyFetching && 'cursor-not-allowed opacity-60',
+ )}
+ >
+ {fetchingModels[activeTab] ? <Spinner size={13} /> : <RefreshCw size={13} />}
+ {fetchingModels[activeTab]
+ ? t('settings.providers.custom.fetch.fetching')
+ : t('settings.providers.custom.fetch.button')}
+ </button>
+ {test[activeTab].status === 'ok' && (
+ <span
+ className="flex items-center gap-1 text-12"
+ style={{ color: 'var(--remote-status-ready)' }}
+ >
+ <Check size={13} strokeWidth={2.5} />
+ {t('settings.providers.custom.test.ok', { ms: test[activeTab].latencyMs ?? 0 })}
+ </span>
)}
- >
- {fetchingModels[activeTab] ? (
- <Spinner size={13} />
- ) : (
- <RefreshCw size={13} />
+ {test[activeTab].status === 'fail' && (
+ <span className="text-12 text-[var(--error-fg)]">
+ {t(`providerError.${test[activeTab].code ?? 'UNKNOWN'}`)}
+ </span>
)}
- {fetchingModels[activeTab]
- ? t('settings.providers.custom.fetch.fetching')
- : t('settings.providers.custom.fetch.button')}
- </button>
- {test[activeTab].status === 'ok' && (
- <span className="flex items-center gap-1 text-12" style={{ color: 'var(--remote-status-ready)' }}>
- <Check size={13} strokeWidth={2.5} />
- {t('settings.providers.custom.test.ok', { ms: test[activeTab].latencyMs ?? 0 })}
- </span>
- )}
- {test[activeTab].status === 'fail' && (
- <span className="text-12 text-[var(--error-fg)]">
- {t(`providerError.${test[activeTab].code ?? 'UNKNOWN'}`)}
- </span>
- )}
- </div>
+ </div>
)}
</div>
-
</div>
{/* Footer */}
@@ -1190,7 +1422,12 @@ function ModelPickerOverlay({
onClose,
}: {
picker: { agent: AgentKind; models: ModelRow[]; selected: Set<string>; query: string };
- onChange: (next: { agent: AgentKind; models: ModelRow[]; selected: Set<string>; query: string }) => void;
+ onChange: (next: {
+ agent: AgentKind;
+ models: ModelRow[];
+ selected: Set<string>;
+ query: string;
+ }) => void;
onConfirm: () => void;
onClose: () => void;
}) {
@@ -1312,7 +1549,9 @@ function ModelPickerOverlay({
{m.name}
</span>
{m.name !== m.id && (
- <span className="max-w-[45%] truncate text-11 text-[var(--text-tertiary)]">{m.id}</span>
+ <span className="max-w-[45%] truncate text-11 text-[var(--text-tertiary)]">
+ {m.id}
+ </span>
)}
</button>
);
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 75564d258e..61bf1d1a1e 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -558,16 +558,19 @@ function GenericOAuthHeader({
const [loggingIn, setLoggingIn] = useState(false);
const connected = provider.connected;
const deviceFlow = provider.auth.oauth?.flow === 'device-code';
- const { deviceCode, clearDeviceCode, beginOwnedLogin } = useProviderOAuthDeviceCode(
- deviceFlow ? provider.id : null,
+ const { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } = useProviderOAuthDeviceCode(
+ provider.id,
+ { observeProgress: deviceFlow },
);
const handleLogin = useCallback(async () => {
clearDeviceCode();
setLoggingIn(true);
- const finishOwnedLogin = beginOwnedLogin();
+ const ownedLogin = beginOwnedLogin();
try {
- const r = await window.electronAPI.maker.providerOAuthLogin(provider.id);
+ const r = await window.electronAPI.maker.providerOAuthLogin(provider.id, {
+ ownerId: ownedLogin.ownerId,
+ });
if (r.ok) {
toast.success(t('settings.providers.genericOAuth.toast.loggedIn', { name: provider.name }));
onChanged();
@@ -581,7 +584,7 @@ function GenericOAuthHeader({
} catch {
toast.error(t('settings.providers.genericOAuth.toast.loginFailed', { name: provider.name }));
} finally {
- finishOwnedLogin();
+ ownedLogin.finish();
setLoggingIn(false);
}
}, [beginOwnedLogin, clearDeviceCode, onChanged, provider.id, provider.name, t]);
@@ -630,7 +633,7 @@ function GenericOAuthHeader({
}
onClick={() => {
if (loggingIn) {
- void window.electronAPI.maker.providerOAuthCancel(provider.id);
+ cancelOwnedLogin();
clearDeviceCode();
setLoggingIn(false);
} else {
@@ -849,8 +852,9 @@ function CustomProviderHeader({
const [loggingIn, setLoggingIn] = useState(false);
const isOAuth = provider.auth.method === 'oauth' && !!provider.auth.oauth;
const deviceFlow = provider.auth.oauth?.flow === 'device-code';
- const { deviceCode, clearDeviceCode, beginOwnedLogin } = useProviderOAuthDeviceCode(
- deviceFlow ? provider.id : null,
+ const { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } = useProviderOAuthDeviceCode(
+ isOAuth ? provider.id : null,
+ { observeProgress: deviceFlow },
);
const handleOAuthClick = useCallback(async () => {
if (provider.connected) {
@@ -867,16 +871,18 @@ function CustomProviderHeader({
return;
}
if (loggingIn) {
- void window.electronAPI.maker.providerOAuthCancel(provider.id);
+ cancelOwnedLogin();
clearDeviceCode();
setLoggingIn(false);
return;
}
clearDeviceCode();
setLoggingIn(true);
- const finishOwnedLogin = beginOwnedLogin();
+ const ownedLogin = beginOwnedLogin();
try {
- const r = await window.electronAPI.maker.providerOAuthLogin(provider.id);
+ const r = await window.electronAPI.maker.providerOAuthLogin(provider.id, {
+ ownerId: ownedLogin.ownerId,
+ });
if (r.ok)
toast.success(t('settings.providers.genericOAuth.toast.loggedIn', { name: provider.name }));
else if (r.reason !== 'login_cancelled') {
@@ -887,10 +893,10 @@ function CustomProviderHeader({
} catch {
toast.error(t('settings.providers.genericOAuth.toast.loginFailed', { name: provider.name }));
} finally {
- finishOwnedLogin();
+ ownedLogin.finish();
setLoggingIn(false);
}
- }, [beginOwnedLogin, clearDeviceCode, loggingIn, provider.connected, provider.id, provider.name, t]);
+ }, [beginOwnedLogin, cancelOwnedLogin, clearDeviceCode, loggingIn, provider.connected, provider.id, provider.name, t]);
const trailing = (
<div className="flex shrink-0 items-center gap-1">
@@ -1266,10 +1272,16 @@ export function ProvidersSection() {
for (const agent of p.agents) {
const rt = config.runtimes[agent];
if (!rt?.baseUrl) continue;
- const apiKey = await readCustomProviderKey(p.id, agent);
+ const authMethod =
+ p.auth.method === 'none' ? 'none'
+ : p.auth.method === 'oauth' ? 'oauth'
+ : 'apiKey';
+ const apiKey =
+ authMethod === 'apiKey' ? await readCustomProviderKey(p.id, agent) : null;
const r = await window.electronAPI.maker.fetchProviderModels({
agent,
baseUrl: rt.baseUrl,
+ authMethod,
modelsUrl: rt.modelsUrl ?? null,
apiKey,
...(rt.headers ? { headers: rt.headers } : {}),
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx
index d3e46259cd..c4e8e8eacb 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx
@@ -53,6 +53,7 @@ vi.mock('@/hooks/useProviders', () => ({
name: 'Anthropic',
connected: true,
agents: ['claude-code'],
+ routing: { 'claude-code': {} },
models: {
'claude-code': providersMock.claudeModels,
codex: [],
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
index e46ede09e6..01a75fa917 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
@@ -88,12 +88,21 @@ vi.mock('@/hooks/useAgentCapabilities', () => ({
}));
vi.mock('@/hooks/useProviders', () => ({
- useProviders: () => ({ providers: mocks.localProviders, loading: mocks.providersLoading }),
+ useProviders: () => ({
+ providers: mocks.localProviders.map((provider) => ({
+ ...provider,
+ routing: Object.fromEntries(provider.agents.map((agent) => [agent, {}])),
+ })),
+ loading: mocks.providersLoading,
+ }),
}));
vi.mock('@/hooks/useDeviceProviders', () => ({
useDeviceProviders: () => ({
- providers: mocks.remoteProviders,
+ providers: mocks.remoteProviders.map((provider) => ({
+ ...provider,
+ routing: Object.fromEntries(provider.agents.map((agent) => [agent, {}])),
+ })),
loading: mocks.providersLoading,
error: null,
}),
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts
index 4309b4ee6f..66eee10a0b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts
@@ -26,6 +26,7 @@ const provider = (
name: id,
connected,
agents: [agent],
+ routing: { [agent]: {} },
models: {
[agent]: models.map((entry) => ({ ...entry, name: entry.displayName })),
},
diff --git a/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts b/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts
new file mode 100644
index 0000000000..41c2dfb211
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts
@@ -0,0 +1,196 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+describe('triggerCodexLoginOnce', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ it('coalesces only the same mode and serializes a conflicting mode after cancellation', async () => {
+ const browser = deferred<{ authenticated: boolean }>();
+ const triggerLogin = vi.fn((_: string, options?: { mode?: string; ownerId?: string }) =>
+ options?.mode === 'device-code'
+ ? Promise.resolve({ authenticated: true })
+ : browser.promise,
+ );
+ const cancelLogin = vi.fn(async () => undefined);
+ Object.assign(window, {
+ electronAPI: {
+ maker: { auth: { triggerLogin, cancelLogin } },
+ },
+ });
+ const { triggerCodexLoginOnce } = await import('../codexAuthLogin');
+
+ const first = triggerCodexLoginOnce('browser');
+ const duplicate = triggerCodexLoginOnce('browser');
+ const deviceCode = triggerCodexLoginOnce('device-code');
+ await Promise.resolve();
+
+ expect(duplicate).toBe(first);
+ expect(cancelLogin).toHaveBeenCalledWith('codex', {
+ releaseOwner: true,
+ ownerId: triggerLogin.mock.calls[0]?.[1]?.ownerId,
+ });
+ expect(triggerLogin).toHaveBeenCalledTimes(1);
+
+ browser.resolve({ authenticated: false });
+ await expect(first).resolves.toEqual({ authenticated: false });
+ await expect(deviceCode).resolves.toEqual({ authenticated: true });
+ expect(triggerLogin).toHaveBeenNthCalledWith(
+ 2,
+ 'codex',
+ expect.objectContaining({ mode: 'device-code', ownerId: expect.any(String) }),
+ );
+ });
+
+ it('does not start a queued mode switch after renderer cancellation', async () => {
+ const browser = deferred<{ authenticated: boolean }>();
+ const triggerLogin = vi.fn(() => browser.promise);
+ const cancelLogin = vi.fn(async () => undefined);
+ Object.assign(window, {
+ electronAPI: {
+ maker: { auth: { triggerLogin, cancelLogin } },
+ },
+ });
+ const { invalidatePendingCodexLogin, triggerCodexLoginOnce } =
+ await import('../codexAuthLogin');
+
+ const first = triggerCodexLoginOnce('browser');
+ const queued = triggerCodexLoginOnce('device-code');
+ invalidatePendingCodexLogin();
+ browser.resolve({ authenticated: false });
+
+ await expect(first).resolves.toEqual({ authenticated: false });
+ await expect(queued).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ expect(triggerLogin).toHaveBeenCalledTimes(1);
+ });
+
+ it('continues a mode switch when cancellation throws synchronously', async () => {
+ const browser = deferred<{ authenticated: boolean }>();
+ const triggerLogin = vi.fn((_: string, options?: { mode?: string; ownerId?: string }) =>
+ options?.mode === 'device-code'
+ ? Promise.resolve({ authenticated: true })
+ : browser.promise,
+ );
+ const cancelLogin = vi.fn(() => {
+ throw new Error('bridge unavailable');
+ });
+ Object.assign(window, {
+ electronAPI: {
+ maker: { auth: { triggerLogin, cancelLogin } },
+ },
+ });
+ const { triggerCodexLoginOnce } = await import('../codexAuthLogin');
+
+ const first = triggerCodexLoginOnce('browser');
+ let deviceCode!: Promise<{ authenticated: boolean }>;
+ expect(() => {
+ deviceCode = triggerCodexLoginOnce('device-code');
+ }).not.toThrow();
+
+ browser.resolve({ authenticated: false });
+ await expect(first).resolves.toEqual({ authenticated: false });
+ await expect(deviceCode).resolves.toEqual({ authenticated: true });
+ expect(triggerLogin).toHaveBeenNthCalledWith(
+ 2,
+ 'codex',
+ expect.objectContaining({ mode: 'device-code', ownerId: expect.any(String) }),
+ );
+ });
+
+ it('cancels a shared login only after its last explicit owner releases', async () => {
+ const login = deferred<{ authenticated: boolean; errorReason?: string }>();
+ const triggerLogin = vi.fn(() => login.promise);
+ const cancelLogin = vi.fn(async () => undefined);
+ Object.assign(window, {
+ electronAPI: {
+ maker: { auth: { triggerLogin, cancelLogin } },
+ },
+ });
+ const { acquireCodexLogin } = await import('../codexAuthLogin');
+
+ const first = acquireCodexLogin('device-code');
+ const second = acquireCodexLogin('device-code');
+ expect(first.promise).toBe(second.promise);
+ expect(triggerLogin).toHaveBeenCalledOnce();
+
+ first.release({ cancelIfLastOwner: true });
+ expect(cancelLogin).not.toHaveBeenCalled();
+
+ second.release({ cancelIfLastOwner: true });
+ expect(cancelLogin).toHaveBeenCalledOnce();
+ expect(cancelLogin).toHaveBeenCalledWith('codex', {
+ releaseOwner: true,
+ ownerId: expect.any(String),
+ });
+
+ login.resolve({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(first.promise).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+
+ it('does not let an old-mode owner cleanup cancel the queued new-mode login', async () => {
+ const browser = deferred<{ authenticated: boolean; errorReason?: string }>();
+ const deviceCode = deferred<{ authenticated: boolean; errorReason?: string }>();
+ const triggerLogin = vi.fn((_: string, options?: { mode?: string; ownerId?: string }) =>
+ options?.mode === 'device-code' ? deviceCode.promise : browser.promise,
+ );
+ const cancelLogin = vi.fn(async () => undefined);
+ Object.assign(window, {
+ electronAPI: {
+ maker: { auth: { triggerLogin, cancelLogin } },
+ },
+ });
+ const { acquireCodexLogin } = await import('../codexAuthLogin');
+
+ const browserOwner = acquireCodexLogin('browser');
+ const deviceOwner = acquireCodexLogin('device-code');
+ expect(cancelLogin).toHaveBeenCalledOnce();
+ expect(cancelLogin).toHaveBeenLastCalledWith('codex', {
+ releaseOwner: true,
+ ownerId: triggerLogin.mock.calls[0]?.[1]?.ownerId,
+ });
+
+ browserOwner.release({ cancelIfLastOwner: true });
+ expect(cancelLogin).toHaveBeenCalledOnce();
+
+ browser.resolve({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(browserOwner.promise).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ await vi.waitFor(() =>
+ expect(triggerLogin).toHaveBeenNthCalledWith(
+ 2,
+ 'codex',
+ expect.objectContaining({ mode: 'device-code', ownerId: expect.any(String) }),
+ ),
+ );
+
+ deviceOwner.release({ cancelIfLastOwner: true });
+ expect(cancelLogin).toHaveBeenCalledTimes(2);
+ expect(cancelLogin).toHaveBeenLastCalledWith('codex', {
+ releaseOwner: true,
+ ownerId: expect.any(String),
+ });
+ deviceCode.resolve({ authenticated: false, errorReason: 'login_cancelled' });
+ await expect(deviceOwner.promise).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
index 36e1faadc2..36e738e7d7 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
@@ -56,7 +56,16 @@ function stateChangedListener(auth: ReturnType<typeof installAuthApi>) {
function loginProgressListener(auth: ReturnType<typeof installAuthApi>) {
const calls = auth.onLoginProgress.mock.calls as unknown as Array<
- [(payload: { agentKind: string; phase: string; detail?: string }) => void]
+ [(
+ payload: {
+ agentKind: string;
+ phase: string;
+ mode?: 'browser' | 'device-code';
+ detail?: string;
+ verificationUrl?: string;
+ userCode?: string;
+ },
+ ) => void]
>;
return calls[0][0];
}
@@ -115,6 +124,39 @@ describe('useCodexAuth lifecycle', () => {
expect(result.current.state.kind).toBe('unauthenticated');
});
+ it('reconciles and surfaces a failed durable cancellation instead of claiming disconnect', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.cancelLogin.mockRejectedValue(
+ new Error('[INTERNAL] failed to persist Codex disconnect state'),
+ );
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth' as const,
+ })
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth' as const,
+ });
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('authenticated'));
+ await act(async () => {
+ await result.current.cancelLogin();
+ });
+
+ expect(auth.cancelLogin).toHaveBeenCalledWith('codex');
+ expect(auth.getState).toHaveBeenCalledTimes(2);
+ expect(result.current.state).toEqual({
+ kind: 'authenticated',
+ identity: '[email protected]',
+ expiresAt: undefined,
+ authSource: 'oauth',
+ });
+ });
+
it('returns failed while retaining a generic main-process login reason', async () => {
const auth = installAuthApi(async () => undefined);
auth.triggerLogin.mockResolvedValue({ authenticated: false, errorReason: 'login_timeout' });
@@ -204,7 +246,7 @@ describe('useCodexAuth lifecycle', () => {
act(() => {
loginProgressListener(auth)({ agentKind: 'codex', phase: 'login-pending' });
});
- expect(result.current.state).toEqual({ kind: 'login-pending' });
+ expect(result.current.state).toEqual({ kind: 'login-pending', mode: 'browser' });
await act(async () => {
initialState.resolve({
@@ -215,7 +257,7 @@ describe('useCodexAuth lifecycle', () => {
await initialState.promise;
});
- expect(result.current.state).toEqual({ kind: 'login-pending' });
+ expect(result.current.state).toEqual({ kind: 'login-pending', mode: 'browser' });
act(() => {
stateChangedListener(auth)({
@@ -282,7 +324,118 @@ describe('useCodexAuth lifecycle', () => {
await expect(firstOutcome).resolves.toBe('authenticated');
await expect(secondOutcome).resolves.toBe('authenticated');
});
- expect(auth.triggerLogin).toHaveBeenCalledWith('codex');
+ expect(auth.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ ownerId: expect.any(String) }),
+ );
+ });
+
+ it('keeps a shared owned login until the last owner unmounts and ignores observers', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const login = deferred<TestAuthState>();
+ auth.triggerLogin.mockImplementation(() => login.promise);
+ const firstOwner = renderHook(() => useCodexAuth());
+ const secondOwner = renderHook(() => useCodexAuth());
+ const observer = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(firstOwner.result.current.state.kind).toBe('authenticated'));
+ await waitFor(() => expect(secondOwner.result.current.state.kind).toBe('authenticated'));
+ await waitFor(() => expect(observer.result.current.state.kind).toBe('authenticated'));
+
+ let firstOutcome!: ReturnType<typeof firstOwner.result.current.triggerLogin>;
+ let secondOutcome!: ReturnType<typeof secondOwner.result.current.triggerLogin>;
+ act(() => {
+ firstOutcome = firstOwner.result.current.triggerLogin('device-code');
+ secondOutcome = secondOwner.result.current.triggerLogin('device-code');
+ });
+ await waitFor(() =>
+ expect(auth.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ mode: 'device-code', ownerId: expect.any(String) }),
+ ),
+ );
+ expect(auth.triggerLogin).toHaveBeenCalledOnce();
+
+ observer.unmount();
+ firstOwner.unmount();
+ expect(auth.cancelLogin).not.toHaveBeenCalled();
+
+ secondOwner.unmount();
+ expect(auth.cancelLogin).toHaveBeenCalledOnce();
+ expect(auth.cancelLogin).toHaveBeenCalledWith('codex', {
+ releaseOwner: true,
+ ownerId: expect.any(String),
+ });
+
+ // 即使 bridge 取消失败、main 最终回了成功,已卸载 owner 也只能观察到 cancelled,
+ // 不能在关闭向导后迟到弹出“连接成功”或更新卸载组件。
+ login.resolve({ authenticated: true, authSource: 'oauth' });
+ await act(async () => {
+ await expect(firstOutcome).resolves.toBe('cancelled');
+ await expect(secondOutcome).resolves.toBe('cancelled');
+ });
+ });
+
+ it('does not start a login through a retained callback after its owner unmounts', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const owner = renderHook(() => useCodexAuth());
+ await waitFor(() => expect(owner.result.current.state.kind).toBe('authenticated'));
+ const triggerAfterUnmount = owner.result.current.triggerLogin;
+
+ owner.unmount();
+ await expect(triggerAfterUnmount('device-code')).resolves.toBe('cancelled');
+
+ expect(auth.triggerLogin).not.toHaveBeenCalled();
+ expect(auth.cancelLogin).not.toHaveBeenCalled();
+ });
+
+ it('keeps the device code visible while later waiting output arrives', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const login = deferred<TestAuthState>();
+ auth.triggerLogin.mockImplementation(() => login.promise);
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('authenticated'));
+ let attempt!: Promise<string>;
+ act(() => {
+ attempt = result.current.triggerLogin('device-code');
+ });
+ await waitFor(() =>
+ expect(auth.triggerLogin).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ mode: 'device-code', ownerId: expect.any(String) }),
+ ),
+ );
+
+ act(() => {
+ loginProgressListener(auth)({
+ agentKind: 'codex',
+ phase: 'device-code',
+ mode: 'device-code',
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'RUH2-7E2VH',
+ });
+ loginProgressListener(auth)({
+ agentKind: 'codex',
+ phase: 'login-pending',
+ mode: 'device-code',
+ detail: 'Waiting for authorization',
+ });
+ });
+
+ expect(result.current.state).toEqual({
+ kind: 'login-pending',
+ mode: 'device-code',
+ deviceCode: {
+ verificationUrl: 'https://auth.openai.com/codex/device',
+ userCode: 'RUH2-7E2VH',
+ },
+ });
+
+ login.resolve({ authenticated: false, errorReason: 'login_cancelled' });
+ await act(async () => {
+ await expect(attempt).resolves.toBe('cancelled');
+ });
});
it('does not treat a Cindy AI API key as a connected ChatGPT account', () => {
@@ -359,6 +512,27 @@ describe('useCodexAuth lifecycle', () => {
expect(result.current.state).toEqual({ kind: 'unauthenticated' });
});
+ it('lets an observer-only window leave login-pending when main broadcasts cancellation', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState.mockResolvedValueOnce({ authenticated: false });
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('unauthenticated'));
+ act(() => {
+ loginProgressListener(auth)({ agentKind: 'codex', phase: 'login-pending' });
+ });
+ expect(result.current.state).toEqual({ kind: 'login-pending', mode: 'browser' });
+
+ act(() => {
+ stateChangedListener(auth)({
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+ expect(result.current.state).toEqual({ kind: 'unauthenticated' });
+ });
+
it('keeps reconnect-required after a reconnection attempt is cancelled', async () => {
const auth = installAuthApi(async () => undefined);
auth.getState.mockResolvedValueOnce({
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.ts
index c7ed0cb850..4ecc675253 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.ts
@@ -81,15 +81,52 @@ describe('useProviderOAuthDeviceCode', () => {
{ initialProps: { providerId: 'provider-a' as string | null } },
);
- result.current.beginOwnedLogin();
+ const owned = result.current.beginOwnedLogin();
rerender({ providerId: 'provider-b' });
expect(cancel).toHaveBeenCalledOnce();
- expect(cancel).toHaveBeenCalledWith('provider-a');
+ expect(cancel).toHaveBeenCalledWith('provider-a', {
+ releaseOwner: true,
+ ownerId: owned.ownerId,
+ });
+
+ const nextOwned = result.current.beginOwnedLogin();
+ nextOwned.finish();
+ unmount();
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+
+ it('owns and cancels authorization-code login without subscribing to device progress', () => {
+ const onProgress = window.electronAPI.maker.onProviderOAuthProgress as ReturnType<typeof vi.fn>;
+ const { result, unmount } = renderHook(() =>
+ useProviderOAuthDeviceCode('provider-a', { observeProgress: false }),
+ );
- result.current.beginOwnedLogin();
- const finish = result.current.beginOwnedLogin();
- finish();
+ expect(onProgress).not.toHaveBeenCalled();
+ const owned = result.current.beginOwnedLogin();
unmount();
+
expect(cancel).toHaveBeenCalledOnce();
+ expect(cancel).toHaveBeenCalledWith('provider-a', {
+ releaseOwner: true,
+ ownerId: owned.ownerId,
+ });
+ });
+
+ it('ignores a synchronous cancellation failure during cleanup', async () => {
+ cancel.mockImplementationOnce(() => {
+ throw new Error('sync cancellation failure');
+ });
+ const { result, unmount } = renderHook(() => useProviderOAuthDeviceCode('provider-a'));
+
+ const owned = result.current.beginOwnedLogin();
+ expect(() => unmount()).not.toThrow();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(cancel).toHaveBeenCalledWith('provider-a', {
+ releaseOwner: true,
+ ownerId: owned.ownerId,
+ });
});
});
diff --git a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
index 0aee1421d1..65e6d3afac 100644
--- a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
+++ b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
@@ -7,7 +7,62 @@ export type CodexLoginResult = {
authSource?: 'oauth' | 'api-key';
};
-let pendingCodexLogin: Promise<CodexLoginResult> | null = null;
+type PendingCodexLogin = {
+ mode: 'browser' | 'device-code';
+ ownerId: string;
+ promise: Promise<CodexLoginResult>;
+};
+
+export type CodexLoginLease = {
+ promise: Promise<CodexLoginResult>;
+ release: (options?: { cancelIfLastOwner?: boolean }) => void;
+};
+
+type CodexLoginOwnership = {
+ ownerId: string;
+ owners: number;
+ settled: boolean;
+};
+
+let pendingCodexLogin: PendingCodexLogin | null = null;
+let loginGeneration = 0;
+let loginOwnerSequence = 0;
+const loginOwnership = new Map<Promise<CodexLoginResult>, CodexLoginOwnership>();
+const loginOwnerPrefix = (() => {
+ try {
+ const uuid = globalThis.crypto?.randomUUID?.();
+ if (uuid) return uuid;
+ const entropy = new Uint32Array(4);
+ globalThis.crypto?.getRandomValues?.(entropy);
+ if (entropy.some((value) => value !== 0)) {
+ return `renderer-${[...entropy].map((value) => value.toString(16)).join('-')}`;
+ }
+ } catch {
+ // Older Electron/jsdom may not expose the Web Crypto methods.
+ }
+ // The token is also bound to event.sender in Main, so this fallback supplies uniqueness only.
+ return `renderer-${Date.now().toString(36)}`;
+})();
+
+const cancelledLoginResult = (): CodexLoginResult => ({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+});
+
+function nextLoginOwnerId(): string {
+ loginOwnerSequence += 1;
+ return `${loginOwnerPrefix}:${loginOwnerSequence}`;
+}
+
+function invokeCodexLogin(
+ mode: 'browser' | 'device-code',
+ ownerId: string,
+): Promise<CodexLoginResult> {
+ return window.electronAPI.maker.auth.triggerLogin(
+ 'codex',
+ mode === 'device-code' ? { mode, ownerId } : { ownerId },
+ );
+}
/**
* 合并 renderer 内所有 ChatGPT 连接入口的并发请求。
@@ -15,14 +70,106 @@ let pendingCodexLogin: Promise<CodexLoginResult> | null = null;
* main adapter 也会复用正在运行的 CLI 登录,但在 renderer 先合并可以避免设置页、
* 会话横幅等入口重复发 IPC,并避免同一结果重复执行 main handler 的刷新与广播收尾。
*/
-export function triggerCodexLoginOnce(): Promise<CodexLoginResult> {
- if (pendingCodexLogin) return pendingCodexLogin;
-
- const run = Promise.resolve()
- .then(() => window.electronAPI.maker.auth.triggerLogin('codex'))
- .finally(() => {
- if (pendingCodexLogin === run) pendingCodexLogin = null;
- });
- pendingCodexLogin = run;
- return run;
+function getOrStartCodexLogin(
+ mode: 'browser' | 'device-code' = 'browser',
+): PendingCodexLogin {
+ if (pendingCodexLogin) {
+ if (pendingCodexLogin.mode === mode) return pendingCodexLogin;
+
+ const previous = pendingCodexLogin.promise;
+ const previousOwnerId = pendingCodexLogin.ownerId;
+ const generation = ++loginGeneration;
+ const ownerId = nextLoginOwnerId();
+ try {
+ void window.electronAPI.maker.auth
+ .cancelLogin('codex', { releaseOwner: true, ownerId: previousOwnerId })
+ .catch(() => undefined);
+ } catch {
+ // Cancellation is best-effort; synchronous bridge failures must not abort mode switching.
+ }
+ const queued: Promise<CodexLoginResult> = previous
+ .catch(() => undefined)
+ .then(() =>
+ generation === loginGeneration ? invokeCodexLogin(mode, ownerId) : cancelledLoginResult(),
+ )
+ .finally(() => {
+ if (pendingCodexLogin?.promise === queued) pendingCodexLogin = null;
+ });
+ pendingCodexLogin = { mode, ownerId, promise: queued };
+ return pendingCodexLogin;
+ }
+
+ ++loginGeneration;
+ const ownerId = nextLoginOwnerId();
+ const run: Promise<CodexLoginResult> = invokeCodexLogin(mode, ownerId).finally(() => {
+ if (pendingCodexLogin?.promise === run) pendingCodexLogin = null;
+ });
+ pendingCodexLogin = { mode, ownerId, promise: run };
+ return pendingCodexLogin;
+}
+
+export function triggerCodexLoginOnce(
+ mode: 'browser' | 'device-code' = 'browser',
+): Promise<CodexLoginResult> {
+ return getOrStartCodexLogin(mode).promise;
+}
+
+/**
+ * 获取共享 Codex 登录的一份 owner lease。
+ *
+ * 同一 renderer 内多个显式入口会复用一个登录 promise;组件卸载时只有最后一个 owner
+ * 才能取消它。lease 绑定具体 promise,因此旧模式的 cleanup 不会误杀已排队的新模式。
+ */
+export function acquireCodexLogin(
+ mode: 'browser' | 'device-code' = 'browser',
+): CodexLoginLease {
+ const pending = getOrStartCodexLogin(mode);
+ const { ownerId, promise } = pending;
+ let ownership = loginOwnership.get(promise);
+ if (!ownership) {
+ ownership = { ownerId, owners: 0, settled: false };
+ loginOwnership.set(promise, ownership);
+ const markSettled = () => {
+ ownership!.settled = true;
+ if (ownership!.owners === 0 && loginOwnership.get(promise) === ownership) {
+ loginOwnership.delete(promise);
+ }
+ };
+ void promise.then(markSettled, markSettled);
+ }
+ ownership.owners += 1;
+
+ let released = false;
+ return {
+ promise,
+ release(options) {
+ if (released) return;
+ released = true;
+ ownership!.owners = Math.max(0, ownership!.owners - 1);
+ if (ownership!.owners !== 0) return;
+ if (loginOwnership.get(promise) === ownership) loginOwnership.delete(promise);
+ if (
+ options?.cancelIfLastOwner !== true ||
+ ownership!.settled ||
+ pendingCodexLogin?.promise !== promise
+ ) {
+ return;
+ }
+
+ invalidatePendingCodexLogin();
+ try {
+ void window.electronAPI.maker.auth
+ .cancelLogin('codex', { releaseOwner: true, ownerId: ownership!.ownerId })
+ .catch(() => undefined);
+ } catch {
+ // Teardown cancellation is best-effort; a synchronous bridge failure must not escape React.
+ }
+ },
+ };
+}
+
+/** 让尚未开始的模式切换失效;main 侧正在运行的登录仍由调用方显式取消。 */
+export function invalidatePendingCodexLogin(): void {
+ ++loginGeneration;
+ pendingCodexLogin = null;
}
diff --git a/apps/desktop/src/renderer/hooks/useCodexAuth.ts b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
index dd6fa3ff6f..3760a50cf3 100644
--- a/apps/desktop/src/renderer/hooks/useCodexAuth.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
@@ -10,13 +10,22 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
-import { triggerCodexLoginOnce, type CodexLoginResult } from './codexAuthLogin';
+import {
+ acquireCodexLogin,
+ invalidatePendingCodexLogin,
+ type CodexLoginLease,
+ type CodexLoginResult,
+} from './codexAuthLogin';
import { isCodexOAuthReconnectRequired } from './codexAuthRecovery';
export type CodexUiState =
| { kind: 'loading' }
| { kind: 'unauthenticated' }
- | { kind: 'login-pending' }
+ | {
+ kind: 'login-pending';
+ mode: 'browser' | 'device-code';
+ deviceCode?: { verificationUrl: string; userCode: string };
+ }
| {
kind: 'authenticated';
identity?: string;
@@ -44,7 +53,11 @@ type CodexAuthMachineEvent =
| { type: 'initial-state-failed'; requestedAt: InitialSnapshotRevision }
| { type: 'observer-disabled' }
| { type: 'state-changed'; result: CodexLoginResult }
- | { type: 'login-pending' }
+ | {
+ type: 'login-pending';
+ mode: 'browser' | 'device-code';
+ deviceCode?: { verificationUrl: string; userCode: string };
+ }
| { type: 'login-progress-error'; message: string }
| { type: 'login-result'; result: CodexLoginResult }
| { type: 'login-threw'; message: string }
@@ -176,8 +189,14 @@ function reduceCodexAuthMachine(
if (next.kind === 'error') return restoreReconnectOr(machine, next);
return replaceUi(machine, next, 'auth');
}
- case 'login-pending':
- return replaceUi(machine, { kind: 'login-pending' }, 'event');
+ case 'login-pending': {
+ const deviceCode =
+ event.deviceCode ??
+ (machine.ui.kind === 'login-pending' && machine.ui.mode === event.mode
+ ? machine.ui.deviceCode
+ : undefined);
+ return replaceUi(machine, { kind: 'login-pending', mode: event.mode, deviceCode }, 'event');
+ }
case 'login-progress-error': {
const next = toCodexUiState({ authenticated: false, errorReason: event.message }, true);
if (next.kind === 'reconnect-required') return replaceUi(machine, next, 'event');
@@ -221,11 +240,63 @@ export function isChatGptConnectionConnected(
return state.kind === 'authenticated' && state.authSource === 'oauth';
}
+/**
+ * 将共享 Codex 登录绑定到真实发起它的 React owner。
+ *
+ * 观察型 useCodexAuth 实例不会获得 lease,因此卸载时不会取消别的窗口发起的登录。
+ */
+export function useOwnedCodexLogin(): (
+ mode?: 'browser' | 'device-code',
+) => Promise<CodexLoginResult> {
+ const leasesRef = useRef(new Set<CodexLoginLease>());
+ const mountedRef = useRef(true);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ for (const lease of leasesRef.current) {
+ lease.release({ cancelIfLastOwner: true });
+ }
+ leasesRef.current.clear();
+ };
+ }, []);
+
+ return useCallback((mode: 'browser' | 'device-code' = 'browser') => {
+ if (!mountedRef.current) {
+ return Promise.resolve({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ }
+ const lease = acquireCodexLogin(mode);
+ leasesRef.current.add(lease);
+ return lease.promise
+ .then(
+ (result) =>
+ mountedRef.current
+ ? result
+ : { authenticated: false, errorReason: 'login_cancelled' },
+ (error) => {
+ if (!mountedRef.current) {
+ return { authenticated: false, errorReason: 'login_cancelled' };
+ }
+ throw error;
+ },
+ )
+ .finally(() => {
+ if (!leasesRef.current.delete(lease)) return;
+ lease.release();
+ });
+ }, []);
+}
+
export function useCodexAuth(options?: { enabled?: boolean }) {
const enabled = options?.enabled ?? true;
const { t } = useTranslation();
const [machine, setMachine] = useState<CodexAuthMachineState>(createInitialMachineState);
const machineRef = useRef(machine);
+ const triggerOwnedLogin = useOwnedCodexLogin();
const transition = useCallback((event: CodexAuthMachineEvent) => {
const current = machineRef.current;
@@ -253,8 +324,24 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
if (!enabled) return undefined;
const off = window.electronAPI.maker.auth.onLoginProgress((progress) => {
if (progress.agentKind !== AGENT_KIND) return;
- if (progress.phase === 'login-pending') {
- transition({ type: 'login-pending' });
+ if (
+ progress.phase === 'device-code' &&
+ progress.verificationUrl &&
+ progress.userCode
+ ) {
+ transition({
+ type: 'login-pending',
+ mode: 'device-code',
+ deviceCode: {
+ verificationUrl: progress.verificationUrl,
+ userCode: progress.userCode,
+ },
+ });
+ } else if (progress.phase === 'login-pending') {
+ transition({
+ type: 'login-pending',
+ mode: progress.mode === 'device-code' ? 'device-code' : 'browser',
+ });
} else if (progress.phase === 'login-error') {
transition({ type: 'login-progress-error', message: progress.detail ?? 'unknown' });
}
@@ -284,10 +371,12 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
};
}, [enabled, transition]);
- const triggerLogin = useCallback(async (): Promise<CodexLoginOutcome> => {
- transition({ type: 'login-pending' });
+ const triggerLogin = useCallback(async (
+ mode: 'browser' | 'device-code' = 'browser',
+ ): Promise<CodexLoginOutcome> => {
+ transition({ type: 'login-pending', mode });
try {
- const result = await triggerCodexLoginOnce();
+ const result = await triggerOwnedLogin(mode);
transition({ type: 'login-result', result });
if (result.authenticated) {
toast.success(t('logic.toasts.codexConnected'));
@@ -299,14 +388,29 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
transition({ type: 'login-threw', message });
return message.includes('login_cancelled') ? 'cancelled' : 'failed';
}
- }, [t, transition]);
+ }, [t, transition, triggerOwnedLogin]);
const cancelLogin = useCallback(async () => {
- await window.electronAPI.maker.auth.cancelLogin(AGENT_KIND).catch(() => undefined);
- transition({ type: 'cancelled' });
+ invalidatePendingCodexLogin();
+ try {
+ await window.electronAPI.maker.auth.cancelLogin(AGENT_KIND);
+ transition({ type: 'cancelled' });
+ } catch (error) {
+ // Cancel may race with a just-persisted OAuth token. If durable cleanup failed,
+ // keep the UI aligned with Main's authoritative state instead of claiming that
+ // the account disconnected.
+ try {
+ const raw = await window.electronAPI.maker.auth.getState(AGENT_KIND);
+ transition({ type: 'refreshed-state', result: raw as CodexLoginResult });
+ } catch {
+ const message = error instanceof Error ? error.message : 'cancel_login_failed';
+ transition({ type: 'login-threw', message });
+ }
+ }
}, [transition]);
const logout = useCallback(async () => {
+ invalidatePendingCodexLogin();
try {
await window.electronAPI.maker.auth.logout(AGENT_KIND);
transition({ type: 'logout-success' });
diff --git a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
index de7158a023..0fd2530bbe 100644
--- a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
@@ -1,9 +1,9 @@
-import { useCallback, useRef } from 'react';
+import { useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { toast } from '@/lib/toast';
-import { triggerCodexLoginOnce } from './codexAuthLogin';
+import { useOwnedCodexLogin } from './useCodexAuth';
import { isCodexOAuthReconnectRequired } from './codexAuthRecovery';
export const isCodexSessionExpiredError = isCodexOAuthReconnectRequired;
@@ -16,13 +16,24 @@ export function useCodexSessionExpiredPrompt(options?: {
}): (error: string) => boolean {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
+ const triggerOwnedLogin = useOwnedCodexLogin();
const promptedForErrorRef = useRef<string | null>(null);
const promptActiveRef = useRef(false);
+ const mountedRef = useRef(true);
const onAuthenticatedRef = useRef(options?.onAuthenticated);
const onPromptClosedRef = useRef(options?.onPromptClosed);
onAuthenticatedRef.current = options?.onAuthenticated;
onPromptClosedRef.current = options?.onPromptClosed;
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ promptedForErrorRef.current = null;
+ promptActiveRef.current = false;
+ };
+ }, []);
+
return useCallback(
(error: string) => {
if (!isCodexSessionExpiredError(error)) return false;
@@ -45,6 +56,7 @@ export function useCodexSessionExpiredPrompt(options?: {
cancelText: t('chat.errorBanner.codexSessionExpiredDialog.cancel'),
autoFocusConfirm: true,
});
+ if (!mountedRef.current) return;
if (!shouldReconnect) {
closePrompt();
return;
@@ -52,7 +64,8 @@ export function useCodexSessionExpiredPrompt(options?: {
}
try {
- const result = await triggerCodexLoginOnce();
+ const result = await triggerOwnedLogin();
+ if (!mountedRef.current) return;
if (result.authenticated) {
onAuthenticatedRef.current?.(error);
toast.success(t('logic.toasts.codexConnected'));
@@ -60,13 +73,15 @@ export function useCodexSessionExpiredPrompt(options?: {
toast.error(t('settings.connections.codex.toast.loginFailed'));
}
} catch {
- toast.error(t('settings.connections.codex.toast.loginFailed'));
+ if (mountedRef.current) {
+ toast.error(t('settings.connections.codex.toast.loginFailed'));
+ }
} finally {
- closePrompt();
+ if (mountedRef.current) closePrompt();
}
})();
return true;
},
- [confirm, options?.confirmBeforeLogin, t],
+ [confirm, options?.confirmBeforeLogin, t, triggerOwnedLogin],
);
}
diff --git a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts
index b6a368e16a..c1e4826609 100644
--- a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts
+++ b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts
@@ -13,6 +13,7 @@
*/
import { useEffect, useState } from 'react';
+import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';
import type { ProviderView } from '@cindy/model-providers';
import { createLogger } from '@/lib/logger';
@@ -33,12 +34,19 @@ function getDeviceLink(): DeviceLinkShape | null {
}
// 缓存按被控设备隔离;代际同 useAgentCapabilities(evict 时自增,作废在途 fetch 的回写)。
-const cache = new Map<string, ProviderView[]>();
-const inflight = new Map<string, Promise<ProviderView[]>>();
+export interface DeviceProvidersPayload {
+ providers: ProviderView[];
+ /** 被控端「模型显示/隐藏」override 快照;undefined = 旧被控端,不过滤。 */
+ modelVisibilityOverrides?: Record<string, boolean>;
+}
+
+const EMPTY_PAYLOAD: DeviceProvidersPayload = { providers: [] };
+const cache = new Map<string, DeviceProvidersPayload>();
+const inflight = new Map<string, Promise<DeviceProvidersPayload>>();
const deviceGen = new Map<string, number>();
export type DeviceProvidersEvent =
| { status: 'loading' }
- | { status: 'ready'; providers: ProviderView[] }
+ | ({ status: 'ready' } & DeviceProvidersPayload)
| { status: 'error'; error: string };
const listeners = new Map<string, Set<(event: DeviceProvidersEvent) => void>>();
@@ -60,7 +68,7 @@ export function subscribeDeviceProviders(
};
}
-async function fetchDeviceProviders(deviceId: string): Promise<ProviderView[]> {
+async function fetchDeviceProviders(deviceId: string): Promise<DeviceProvidersPayload> {
const cached = cache.get(deviceId);
if (cached) return cached;
const ip = inflight.get(deviceId);
@@ -73,16 +81,23 @@ async function fetchDeviceProviders(deviceId: string): Promise<ProviderView[]> {
const dl = getDeviceLink();
if (!dl) throw new Error('device-link IPC not available');
const p = (
- dl.invoke(deviceId, 'maker:provider:list', []) as Promise<{ providers: ProviderView[] }>
+ dl.invoke(deviceId, 'maker:provider:list', [{
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ }]) as Promise<DeviceProvidersPayload>
)
.then((res) => {
- const providers = res?.providers ?? [];
+ const payload: DeviceProvidersPayload = {
+ providers: res?.providers ?? [],
+ ...(res?.modelVisibilityOverrides !== undefined
+ ? { modelVisibilityOverrides: res.modelVisibilityOverrides }
+ : {}),
+ };
if (isCurrent()) {
- cache.set(deviceId, providers);
+ cache.set(deviceId, payload);
inflight.delete(deviceId);
- notifyDeviceProviders(deviceId, { status: 'ready', providers });
+ notifyDeviceProviders(deviceId, { status: 'ready', ...payload });
}
- return providers;
+ return payload;
})
.catch((e) => {
if (isCurrent()) {
@@ -100,21 +115,23 @@ async function fetchDeviceProviders(deviceId: string): Promise<ProviderView[]> {
export interface UseDeviceProvidersResult {
providers: ProviderView[];
+ /** 被控端「模型显示/隐藏」override 快照;undefined = 旧被控端,不过滤。 */
+ modelVisibilityOverrides?: Record<string, boolean>;
loading: boolean;
/** 非 null = 拉取失败(典型:旧版被控端不识别通道);调用方据此回退扁平列表。 */
error: string | null;
}
export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult {
- const [providers, setProviders] = useState<ProviderView[]>(
- deviceId ? (cache.get(deviceId) ?? []) : [],
+ const [payload, setPayload] = useState<DeviceProvidersPayload>(
+ deviceId ? (cache.get(deviceId) ?? EMPTY_PAYLOAD) : EMPTY_PAYLOAD,
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!deviceId) {
- setProviders([]);
+ setPayload(EMPTY_PAYLOAD);
setError(null);
return;
}
@@ -132,19 +149,24 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult
setError(event.error);
return;
}
- setProviders(event.providers);
+ setPayload({
+ providers: event.providers,
+ ...(event.modelVisibilityOverrides !== undefined
+ ? { modelVisibilityOverrides: event.modelVisibilityOverrides }
+ : {}),
+ });
setError(null);
setLoading(false);
});
const cached = cache.get(deviceId);
if (cached) {
- setProviders(cached);
+ setPayload(cached);
setError(null);
setLoading(false);
return unsubscribe;
}
// cache miss:先清空,避免 fetch 解析前(失败则永远)残留上一设备的供应商。
- setProviders([]);
+ setPayload(EMPTY_PAYLOAD);
setLoading(true);
setError(null);
const remoteGeneration = deviceGen.get(deviceId) ?? 0;
@@ -164,7 +186,14 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult
};
}, [deviceId]);
- return { providers, loading, error };
+ return {
+ providers: payload.providers,
+ ...(payload.modelVisibilityOverrides !== undefined
+ ? { modelVisibilityOverrides: payload.modelVisibilityOverrides }
+ : {}),
+ loading,
+ error,
+ };
}
/** device-link:订阅某被控设备时预取其供应商目录(与 prefetchDeviceCapabilities 并列调用)。 */
@@ -181,7 +210,7 @@ export async function prefetchDeviceProviders(deviceId: string): Promise<void> {
}
/** device-link:被控设备下线 / 断链时驱逐其供应商缓存(只清该设备的 key + 代际自增)。 */
-export function getCachedDeviceProviders(deviceId: string): ProviderView[] | null {
+export function getCachedDeviceProviders(deviceId: string): DeviceProvidersPayload | null {
return cache.get(deviceId) ?? null;
}
diff --git a/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.ts b/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.ts
index 139df28823..71a26f95da 100644
--- a/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.ts
+++ b/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.ts
@@ -6,42 +6,97 @@ export interface ProviderOAuthDeviceCode {
expiresAt?: number;
}
+type OwnedProviderOAuthLogin = {
+ providerId: string;
+ ownerId: string;
+};
+
+let providerOAuthOwnerSequence = 0;
+const providerOAuthOwnerPrefix = (() => {
+ try {
+ const uuid = globalThis.crypto?.randomUUID?.();
+ if (uuid) return uuid;
+ const entropy = new Uint32Array(4);
+ globalThis.crypto?.getRandomValues?.(entropy);
+ if (entropy.some((value) => value !== 0)) {
+ return `provider-oauth-${[...entropy].map((value) => value.toString(16)).join('-')}`;
+ }
+ } catch {
+ // Older Electron/jsdom may not expose the Web Crypto methods.
+ }
+ // Main also binds this token to event.sender; fallback uniqueness is not an auth boundary.
+ return `provider-oauth-${Date.now().toString(36)}`;
+})();
+
+function nextProviderOAuthOwnerId(): string {
+ providerOAuthOwnerSequence += 1;
+ return `${providerOAuthOwnerPrefix}:${providerOAuthOwnerSequence}`;
+}
+
/**
- * 订阅某个通用 OAuth 供应商的 Device Grant 短期代码。
+ * 管理某个通用 OAuth 登录的组件 ownership;Device Grant 流可同时订阅短期代码。
* 代码只在组件内存中保留;切换供应商、取消或卸载都会清空。
*/
-export function useProviderOAuthDeviceCode(providerId: string | null) {
+export function useProviderOAuthDeviceCode(
+ providerId: string | null,
+ options?: { observeProgress?: boolean },
+) {
+ const observeProgress = options?.observeProgress ?? true;
const [deviceCode, setDeviceCode] = useState<ProviderOAuthDeviceCode | null>(null);
- const ownedLoginRef = useRef<{ providerId: string; token: symbol } | null>(null);
+ const ownedLoginRef = useRef<OwnedProviderOAuthLogin | null>(null);
+
+ const releaseOwnedLogin = useCallback((owned: OwnedProviderOAuthLogin) => {
+ if (ownedLoginRef.current !== owned) return;
+ ownedLoginRef.current = null;
+ try {
+ void Promise.resolve(
+ window.electronAPI.maker.providerOAuthCancel(owned.providerId, {
+ releaseOwner: true,
+ ownerId: owned.ownerId,
+ }),
+ ).catch(() => undefined);
+ } catch {
+ // Cleanup is best-effort; synchronous bridge failures must not escape effect teardown.
+ }
+ }, []);
useEffect(() => {
setDeviceCode(null);
if (!providerId) return undefined;
- const unsubscribe = window.electronAPI.maker.onProviderOAuthProgress((progress) => {
- if (progress.providerId !== providerId || progress.phase !== 'device-code') return;
- setDeviceCode({
- verificationUrl: progress.verificationUrl,
- userCode: progress.userCode,
- expiresAt: progress.expiresAt,
- });
- });
+ const unsubscribe = observeProgress
+ ? window.electronAPI.maker.onProviderOAuthProgress((progress) => {
+ if (progress.providerId !== providerId || progress.phase !== 'device-code') return;
+ setDeviceCode({
+ verificationUrl: progress.verificationUrl,
+ userCode: progress.userCode,
+ expiresAt: progress.expiresAt,
+ });
+ })
+ : undefined;
return () => {
- unsubscribe();
- if (ownedLoginRef.current?.providerId === providerId) {
- ownedLoginRef.current = null;
- void window.electronAPI.maker.providerOAuthCancel(providerId).catch(() => undefined);
- }
+ unsubscribe?.();
+ const owned = ownedLoginRef.current;
+ if (owned?.providerId === providerId) releaseOwnedLogin(owned);
};
- }, [providerId]);
+ }, [observeProgress, providerId, releaseOwnedLogin]);
const beginOwnedLogin = useCallback(() => {
- if (!providerId) return () => undefined;
- const owned = { providerId, token: Symbol(providerId) };
+ if (!providerId) return { ownerId: undefined, finish: () => undefined };
+ const previous = ownedLoginRef.current;
+ if (previous) releaseOwnedLogin(previous);
+ const owned = { providerId, ownerId: nextProviderOAuthOwnerId() };
ownedLoginRef.current = owned;
- return () => {
- if (ownedLoginRef.current === owned) ownedLoginRef.current = null;
+ return {
+ ownerId: owned.ownerId,
+ finish: () => {
+ if (ownedLoginRef.current === owned) ownedLoginRef.current = null;
+ },
};
- }, [providerId]);
+ }, [providerId, releaseOwnedLogin]);
+ const cancelOwnedLogin = useCallback(() => {
+ const owned = ownedLoginRef.current;
+ if (owned) releaseOwnedLogin(owned);
+ }, [releaseOwnedLogin]);
const clearDeviceCode = useCallback(() => setDeviceCode(null), []);
- return { deviceCode, clearDeviceCode, beginOwnedLogin };
+ return { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin };
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 353b80a9dd..1a966cd764 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1213,6 +1213,8 @@
"wireProtocol": "Upstream protocol",
"baseUrl": "Base URL",
"baseUrlPlaceholder": "https://api.myprovider.com/v1",
+ "requestPath": "Exact request path (optional)",
+ "requestPathHelp": "Leave empty to use the standard path for the selected protocol. Enter a path beginning with / only when the provider uses a non-standard inference endpoint.",
"apiKey": "API key",
"apiKeyPlaceholder": "API key",
"apiKeyEditPlaceholder": "Unchanged (saved)",
@@ -1244,8 +1246,9 @@
"nameRequired": "Display name is required",
"runtimeRequired": "Configure at least one runtime (its base URL and models)",
"baseUrlInvalid": "Base URL must be a valid http(s) address",
+ "requestPathInvalid": "Begin the exact request path with a single /. Do not use fragments or . and .. path segments; percent-encode spaces and unsafe characters.",
"modelRequired": "Add at least one model",
- "oauthInvalid": "Incomplete OAuth config: all four fields are required and both endpoints must be https URLs"
+ "oauthInvalid": "Incomplete OAuth config: all fields are required and both endpoints must be secure https URLs"
},
"toast": {
"created": "Provider added",
@@ -1287,9 +1290,17 @@
"label": "Authentication",
"apiKey": "API key",
"oauth": "OAuth subscription",
- "oauthHelp": "For subscription providers offering OAuth sign-in. After saving, click \"Authorize\" in the provider list to sign in via browser. Credentials are stored encrypted on this device only.",
+ "none": "No authentication",
+ "noneHelp": "For local or trusted self-hosted proxies. Cindy removes the CLI's subscription credentials and account headers before forwarding requests.",
+ "oauthHelp": "For providers offering OAuth sign-in. Choose a browser callback or device code flow, then authorize from the provider list. Credentials are stored encrypted on this device only.",
+ "flowLabel": "OAuth flow",
+ "flow": {
+ "authorization-code": "Browser callback (PKCE)",
+ "device-code": "Device code"
+ },
"fields": {
"authorizeUrl": "Authorize URL",
+ "deviceAuthorizationUrl": "Device authorization URL",
"tokenUrl": "Token URL",
"clientId": "Client ID",
"scopes": "Scopes (space-separated)"
@@ -1377,14 +1388,17 @@
"stepModels": "Choose models",
"searchPlaceholder": "Search providers…",
"groupSubscription": "Subscription sign-in · recommended",
- "groupApiKey": "API key providers · presets update with the catalog",
+ "groupApiKey": "API and self-hosted proxies · presets update with the catalog",
"groupCustom": "Custom",
"metaOAuth": "Subscription (OAuth)",
"metaApiKey": "API key",
+ "metaNoAuth": "Local / self-hosted · no authentication",
"customTitle": "Custom endpoint",
"customMeta": "Connect any OpenAI / Anthropic compatible source",
"pickHint": "The sign-in method is defined by each provider; OAuth endpoints and base URLs come from presets — nothing to fill in by hand.",
"oauthDesc": "Authorize your subscription in the browser — no API key needed",
+ "deviceOAuthDesc": "Authorize on the provider's verification page with a one-time device code",
+ "authorizeInBrowser": "Authorize in browser",
"authorizeWithDeviceCode": "Use device code",
"preparingDeviceCode": "Preparing a device code…",
"deviceCodePrompt": "Enter this one-time device code on the verification page:",
@@ -1398,10 +1412,16 @@
"authorizeFailed": "Failed to authorize {{name}}. Please try again",
"nameLabel": "Display name",
"onlyAgentNote": "This provider only supports {{agent}}",
+ "endpointLabel": "{{agent}} base URL",
+ "noAuthNote": "This proxy needs no client key; Cindy removes CLI subscription credentials before forwarding.",
"bridgedNote": "Cindy bridge (Chat Completions)",
"docsLink": "View setup docs",
"fetching": "Verifying connection and fetching models…",
"fetchFailed": "Couldn't fetch the model list — you can finish with the preset's recommended models and refresh later in details",
+ "manualModelHint": "No models were discovered. Enter the exact model ID exposed by this proxy.",
+ "manualModelLabel": "{{agent}} model ID",
+ "manualModelPlaceholder": "e.g. local-model",
+ "addManualModel": "Add model",
"recommended": "Recommended",
"modelsHint": "Checked models appear in the chat model picker and apply to every CLI where they're available; adjust anytime in provider details.",
"noModelSelected": "Select at least one model",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a064395f35..2eb2dcee5d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1213,6 +1213,8 @@
"wireProtocol": "上流プロトコル",
"baseUrl": "ベース URL",
"baseUrlPlaceholder": "https://api.myprovider.com/v1",
+ "requestPath": "正確なリクエストパス(任意)",
+ "requestPathHelp": "空欄の場合は選択したプロトコルの標準パスを使用します。プロバイダーが標準外の推論エンドポイントを使う場合のみ、/ で始まるパスを入力してください。",
"apiKey": "API キー",
"apiKeyPlaceholder": "API キー",
"apiKeyEditPlaceholder": "変更しない(保存済み)",
@@ -1244,8 +1246,9 @@
"nameRequired": "表示名を入力してください",
"runtimeRequired": "Runtime を 1 つ以上設定してください(ベース URL とモデル)",
"baseUrlInvalid": "ベース URL は有効な http(s) アドレスである必要があります",
+ "requestPathInvalid": "正確なリクエストパスは 1 つの / で始め、フラグメントや .、.. のパスセグメントを含めないでください。空白や安全でない文字はパーセントエンコードしてください。",
"modelRequired": "モデルを 1 つ以上追加してください",
- "oauthInvalid": "OAuth 設定が不完全です:4 つの項目はすべて必須で、両エンドポイントは https である必要があります"
+ "oauthInvalid": "OAuth 設定が不完全です。すべての項目が必須で、両方のエンドポイントは安全な https URL である必要があります"
},
"toast": {
"created": "プロバイダーを追加しました",
@@ -1287,9 +1290,17 @@
"label": "認証方式",
"apiKey": "API キー",
"oauth": "OAuth サブスクリプション認証",
- "oauthHelp": "OAuth ログインを提供するサブスクリプション型プロバイダー向けです。保存後、プロバイダー一覧の「認証」からブラウザでログインしてください。認証情報はこの端末にのみ暗号化保存されます。",
+ "none": "認証なし",
+ "noneHelp": "ローカルまたは信頼できるセルフホスト型プロキシ向けです。Cindy は転送前に CLI のサブスクリプション認証情報とアカウントヘッダーを削除します。",
+ "oauthHelp": "OAuth ログインを提供するプロバイダー向けです。ブラウザコールバックまたはデバイスコード方式を選び、保存後にプロバイダー一覧から認証します。認証情報はこのデバイスにのみ暗号化して保存されます。",
+ "flowLabel": "OAuth フロー",
+ "flow": {
+ "authorization-code": "ブラウザコールバック(PKCE)",
+ "device-code": "デバイスコード"
+ },
"fields": {
"authorizeUrl": "認可エンドポイント (Authorize URL)",
+ "deviceAuthorizationUrl": "デバイス認証エンドポイント (Device Authorization URL)",
"tokenUrl": "トークンエンドポイント (Token URL)",
"clientId": "Client ID",
"scopes": "Scopes(スペース区切り)"
@@ -1376,14 +1387,17 @@
"stepModels": "モデルを選択",
"searchPlaceholder": "プロバイダーを検索…",
"groupSubscription": "サブスクリプション認証 · おすすめ",
- "groupApiKey": "API キープロバイダー · プリセットはカタログと同期",
+ "groupApiKey": "API とセルフホスト型プロキシ · プリセットはカタログと同期",
"groupCustom": "カスタム",
"metaOAuth": "サブスクリプション認証",
"metaApiKey": "API キー",
+ "metaNoAuth": "ローカル / セルフホスト · 認証なし",
"customTitle": "カスタムエンドポイント",
"customMeta": "OpenAI / Anthropic 互換の任意のモデルソースを接続",
"pickHint": "認証方式はプロバイダーの定義で決まります。OAuth エンドポイントとベース URL はプリセットに含まれ、手入力は不要です。",
"oauthDesc": "ブラウザでサブスクリプション認証を完了します。API キーは不要です",
+ "deviceOAuthDesc": "ワンタイムデバイスコードを使い、プロバイダーの認証ページで認証します",
+ "authorizeInBrowser": "ブラウザで認証",
"authorizeWithDeviceCode": "デバイスコードを使用",
"preparingDeviceCode": "デバイスコードを準備しています…",
"deviceCodePrompt": "認証ページで、次のワンタイムデバイスコードを入力してください:",
@@ -1397,10 +1411,16 @@
"authorizeFailed": "「{{name}}」の認証に失敗しました。もう一度お試しください",
"nameLabel": "表示名",
"onlyAgentNote": "このプロバイダーは {{agent}} のみ対応です",
+ "endpointLabel": "{{agent}} ベース URL",
+ "noAuthNote": "このプロキシにクライアントキーは不要です。Cindy は転送前に CLI のサブスクリプション認証情報を削除します。",
"bridgedNote": "Cindy ブリッジ(Chat Completions)",
"docsLink": "接続ドキュメントを見る",
"fetching": "接続を確認してモデル一覧を取得しています…",
"fetchFailed": "モデル一覧を取得できませんでした。プリセットの推奨モデルで追加を完了し、あとで詳細から更新できます",
+ "manualModelHint": "モデルを検出できませんでした。このプロキシが提供する正確なモデル ID を入力してください。",
+ "manualModelLabel": "{{agent}} モデル ID",
+ "manualModelPlaceholder": "例: local-model",
+ "addManualModel": "モデルを追加",
"recommended": "推奨",
"modelsHint": "チェックしたモデルはチャットのモデル選択に表示され、利用可能なすべての CLI に同時に適用されます。プロバイダー詳細からいつでも調整できます。",
"noModelSelected": "モデルを 1 つ以上選択してください",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index cc054346d4..5e1507b505 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1213,6 +1213,8 @@
"wireProtocol": "업스트림 프로토콜",
"baseUrl": "기본 URL",
"baseUrlPlaceholder": "https://api.myprovider.com/v1",
+ "requestPath": "정확한 요청 경로(선택 사항)",
+ "requestPathHelp": "비워 두면 선택한 프로토콜의 표준 경로를 사용합니다. 제공자가 비표준 추론 엔드포인트를 사용할 때만 /로 시작하는 경로를 입력하세요.",
"apiKey": "API 키",
"apiKeyPlaceholder": "API 키",
"apiKeyEditPlaceholder": "변경 안 함(저장됨)",
@@ -1244,8 +1246,9 @@
"nameRequired": "표시 이름을 입력하세요",
"runtimeRequired": "Runtime을 하나 이상 구성하세요(기본 URL과 모델)",
"baseUrlInvalid": "기본 URL은 유효한 http(s) 주소여야 합니다",
+ "requestPathInvalid": "정확한 요청 경로는 단일 /로 시작해야 하며 프래그먼트나 . 또는 .. 경로 세그먼트를 포함하면 안 됩니다. 공백과 안전하지 않은 문자는 퍼센트 인코딩하세요.",
"modelRequired": "모델을 하나 이상 추가하세요",
- "oauthInvalid": "OAuth 설정이 불완전합니다: 네 항목 모두 필수이며 두 엔드포인트는 https 주소여야 합니다"
+ "oauthInvalid": "OAuth 설정이 불완전합니다. 모든 필드는 필수이며 두 엔드포인트는 안전한 https URL이어야 합니다"
},
"toast": {
"created": "제공자를 추가했습니다",
@@ -1287,9 +1290,17 @@
"label": "인증 방식",
"apiKey": "API 키",
"oauth": "OAuth 구독 인증",
- "oauthHelp": "OAuth 로그인을 제공하는 구독형 제공자용입니다. 저장 후 제공자 목록에서 \"인증\"을 눌러 브라우저로 로그인하세요. 자격 증명은 이 기기에만 암호화되어 저장됩니다.",
+ "none": "인증 없음",
+ "noneHelp": "로컬 또는 신뢰할 수 있는 자체 호스팅 프록시용입니다. Cindy는 전달 전에 CLI의 구독 자격 증명과 계정 헤더를 제거합니다.",
+ "oauthHelp": "OAuth 로그인을 제공하는 제공자용입니다. 브라우저 콜백 또는 기기 코드 방식을 선택하고 저장한 뒤 제공자 목록에서 인증하세요. 인증 정보는 이 기기에만 암호화되어 저장됩니다.",
+ "flowLabel": "OAuth 흐름",
+ "flow": {
+ "authorization-code": "브라우저 콜백 (PKCE)",
+ "device-code": "기기 코드"
+ },
"fields": {
"authorizeUrl": "인증 엔드포인트 (Authorize URL)",
+ "deviceAuthorizationUrl": "기기 인증 엔드포인트 (Device Authorization URL)",
"tokenUrl": "토큰 엔드포인트 (Token URL)",
"clientId": "Client ID",
"scopes": "Scopes(공백 구분)"
@@ -1376,14 +1387,17 @@
"stepModels": "모델 선택",
"searchPlaceholder": "제공자 검색…",
"groupSubscription": "구독 인증 · 추천",
- "groupApiKey": "API 키 제공자 · 프리셋은 카탈로그와 함께 업데이트",
+ "groupApiKey": "API 및 자체 호스팅 프록시 · 프리셋은 카탈로그와 함께 업데이트",
"groupCustom": "사용자 지정",
"metaOAuth": "구독 인증",
"metaApiKey": "API 키",
+ "metaNoAuth": "로컬 / 자체 호스팅 · 인증 없음",
"customTitle": "사용자 지정 엔드포인트",
"customMeta": "OpenAI / Anthropic 호환 모델 소스를 연결",
"pickHint": "인증 방식은 제공자 정의에 따라 결정됩니다. OAuth 엔드포인트와 기본 URL은 프리셋에 포함되어 직접 입력할 필요가 없습니다.",
"oauthDesc": "브라우저에서 구독 인증을 완료합니다. API 키가 필요 없습니다",
+ "deviceOAuthDesc": "일회용 기기 코드를 사용해 제공자 인증 페이지에서 인증하세요",
+ "authorizeInBrowser": "브라우저에서 인증",
"authorizeWithDeviceCode": "기기 코드 사용",
"preparingDeviceCode": "기기 코드를 준비하는 중…",
"deviceCodePrompt": "인증 페이지에 다음 일회용 기기 코드를 입력하세요:",
@@ -1397,10 +1411,16 @@
"authorizeFailed": "{{name}} 인증에 실패했습니다. 다시 시도해 주세요",
"nameLabel": "표시 이름",
"onlyAgentNote": "이 제공자는 {{agent}}만 지원합니다",
+ "endpointLabel": "{{agent}} 기본 URL",
+ "noAuthNote": "이 프록시는 클라이언트 키가 필요하지 않습니다. Cindy는 전달 전에 CLI 구독 자격 증명을 제거합니다.",
"bridgedNote": "Cindy 브리지 (Chat Completions)",
"docsLink": "연동 문서 보기",
"fetching": "연결을 확인하고 모델 목록을 가져오는 중…",
"fetchFailed": "모델 목록을 가져오지 못했습니다. 프리셋 추천 모델로 추가를 완료한 뒤 나중에 상세에서 새로고침할 수 있습니다",
+ "manualModelHint": "검색된 모델이 없습니다. 이 프록시가 제공하는 정확한 모델 ID를 입력하세요.",
+ "manualModelLabel": "{{agent}} 모델 ID",
+ "manualModelPlaceholder": "예: local-model",
+ "addManualModel": "모델 추가",
"recommended": "추천",
"modelsHint": "선택한 모델은 대화 모델 선택기에 표시되며 사용 가능한 모든 CLI에 동시에 적용됩니다. 제공자 상세에서 언제든지 조정할 수 있습니다.",
"noModelSelected": "모델을 하나 이상 선택해 주세요",
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 a2c725eda6..f1072777e5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1213,6 +1213,8 @@
"wireProtocol": "上游协议",
"baseUrl": "基础 URL",
"baseUrlPlaceholder": "https://api.myprovider.com/v1",
+ "requestPath": "精确请求路径(可选)",
+ "requestPathHelp": "留空会使用所选协议的标准路径。只有供应商使用非标准推理接口时,才填写以 / 开头的路径。",
"apiKey": "API 密钥",
"apiKeyPlaceholder": "API 密钥",
"apiKeyEditPlaceholder": "保持不变(已保存)",
@@ -1244,8 +1246,9 @@
"nameRequired": "请填写显示名称",
"runtimeRequired": "请至少配置一个 Runtime(填写它的基础 URL 和模型)",
"baseUrlInvalid": "基础 URL 必须是合法的 http(s) 地址",
+ "requestPathInvalid": "精确请求路径需以单个 / 开头,不含片段标识或 .、.. 路径段;空格和不安全字符请使用百分号编码",
"modelRequired": "请至少添加一个模型",
- "oauthInvalid": "OAuth 配置不完整:四个字段均必填,且两个端点必须是 https 地址"
+ "oauthInvalid": "OAuth 配置不完整:所有字段均必填,且两个端点必须是安全的 https 地址"
},
"toast": {
"created": "已添加供应商",
@@ -1287,9 +1290,17 @@
"label": "鉴权方式",
"apiKey": "API 密钥",
"oauth": "OAuth 订阅授权",
- "oauthHelp": "适用于提供 OAuth 登录的订阅制供应商。保存后在供应商列表点「授权」完成浏览器登录,凭证仅加密存储在本机。",
+ "none": "无需鉴权",
+ "noneHelp": "适用于本机或受信任的自托管 Proxy。Cindy 会移除 CLI 自带的订阅凭证和账号头,再把请求发往该端点。",
+ "oauthHelp": "适用于提供 OAuth 登录的供应商。可选择浏览器回调或设备码流程,保存后从供应商列表发起授权。凭证仅加密存储在本机。",
+ "flowLabel": "OAuth 流程",
+ "flow": {
+ "authorization-code": "浏览器回调(PKCE)",
+ "device-code": "设备码"
+ },
"fields": {
"authorizeUrl": "授权端点 (Authorize URL)",
+ "deviceAuthorizationUrl": "设备授权端点 (Device Authorization URL)",
"tokenUrl": "令牌端点 (Token URL)",
"clientId": "Client ID",
"scopes": "Scopes(空格分隔)"
@@ -1376,14 +1387,17 @@
"stepModels": "选择模型",
"searchPlaceholder": "搜索供应商…",
"groupSubscription": "订阅授权 · 推荐",
- "groupApiKey": "API Key 供应商 · 预设随目录更新",
+ "groupApiKey": "API 与自托管 Proxy · 预设随目录更新",
"groupCustom": "自定义",
"metaOAuth": "订阅授权",
"metaApiKey": "API Key",
+ "metaNoAuth": "本机 / 自托管 · 无需鉴权",
"customTitle": "自定义端点",
"customMeta": "接入任意 OpenAI / Anthropic 兼容的模型来源",
"pickHint": "鉴权方式由供应商定义决定;OAuth 端点与基础 URL 由预设携带,无需手填。",
"oauthDesc": "通过浏览器完成订阅授权,无需 API Key",
+ "deviceOAuthDesc": "使用一次性设备码,在供应商验证页面完成授权",
+ "authorizeInBrowser": "在浏览器中授权",
"authorizeWithDeviceCode": "使用设备码",
"preparingDeviceCode": "正在生成设备码…",
"deviceCodePrompt": "请在验证页面输入以下一次性设备码:",
@@ -1397,10 +1411,16 @@
"authorizeFailed": "「{{name}}」授权失败,请重试",
"nameLabel": "显示名称",
"onlyAgentNote": "此供应商仅支持 {{agent}}",
+ "endpointLabel": "{{agent}} 基础 URL",
+ "noAuthNote": "此 Proxy 无需客户端密钥;Cindy 会在转发前移除 CLI 的订阅凭证。",
"bridgedNote": "Cindy 桥接(Chat Completions)",
"docsLink": "查看接入文档",
"fetching": "正在验证连接并获取模型列表…",
"fetchFailed": "模型列表获取失败——可先按预设推荐模型完成添加,稍后在详情里刷新",
+ "manualModelHint": "未发现可用模型,请填写此 Proxy 实际提供的模型 ID。",
+ "manualModelLabel": "{{agent}} 模型 ID",
+ "manualModelPlaceholder": "例如 local-model",
+ "addManualModel": "添加模型",
"recommended": "推荐",
"modelsHint": "勾选的模型将出现在对话的模型选择器中,对可用的 CLI 同时生效;之后可在供应商详情里随时调整。",
"noModelSelected": "请至少勾选一个模型",
diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
index df0a98a35a..7b75b0dc4b 100644
--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
@@ -1,12 +1,17 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
appendDiscoveredCustomProviderModels,
+ createCustomProvider,
customProviderModelConfigFromCatalogModel,
providerViewToCustomProviderConfig,
replaceCustomProviderModelId,
+ updateCustomProvider,
} from '../customProviders';
import type { ProviderView } from '@cindy/model-providers';
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
describe('replaceCustomProviderModelId', () => {
it('drops hidden metadata when the model id changes', () => {
@@ -135,3 +140,116 @@ describe('appendDiscoveredCustomProviderModels', () => {
});
});
});
+
+describe('custom provider credential lifecycle', () => {
+ it('submits create config and keys through one main-process mutation', async () => {
+ const create = vi.fn(async () => ({ ok: true }));
+ vi.stubGlobal('window', {
+ electronAPI: {
+ maker: { createCustomProvider: create },
+ },
+ });
+
+ const config = {
+ id: 'new-provider',
+ name: 'New provider',
+ auth: { method: 'apiKey' as const },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'model', name: 'Model' }],
+ },
+ },
+ };
+ const keys = { codex: 'new-key' };
+ await createCustomProvider(config, keys);
+
+ expect(create).toHaveBeenCalledWith(config, keys);
+ });
+
+ it('surfaces an atomic main-process create failure', async () => {
+ vi.stubGlobal('window', {
+ electronAPI: {
+ maker: {
+ createCustomProvider: vi.fn().mockRejectedValue(
+ new Error('credential staging failed'),
+ ),
+ },
+ },
+ });
+ const config = {
+ id: 'partial-create',
+ name: 'Partial create',
+ auth: { method: 'apiKey' as const },
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'claude-model', name: 'Claude model' }],
+ },
+ codex: {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'codex-model', name: 'Codex model' }],
+ },
+ },
+ };
+
+ await expect(createCustomProvider(config, {
+ 'claude-code': 'first-key',
+ codex: 'second-key',
+ })).rejects.toThrow('credential staging failed');
+ });
+
+ it('submits replacement keys with the config through one main-process mutation', async () => {
+ const update = vi.fn(async () => ({ ok: true }));
+ vi.stubGlobal('window', {
+ electronAPI: {
+ maker: { updateCustomProvider: update },
+ },
+ });
+
+ const config = {
+ id: 'switch-to-key',
+ name: 'Switch to key',
+ auth: { method: 'apiKey' as const },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'm1', name: 'M1' }],
+ },
+ },
+ };
+ await updateCustomProvider(
+ config,
+ { codex: 'replacement-key' },
+ );
+
+ expect(update).toHaveBeenCalledWith(config, { codex: 'replacement-key' });
+ });
+
+ it('surfaces an atomic main-process update failure', async () => {
+ vi.stubGlobal('window', {
+ electronAPI: {
+ maker: {
+ updateCustomProvider: vi.fn().mockRejectedValue(new Error('credential rollback failed')),
+ },
+ },
+ });
+
+ await expect(
+ updateCustomProvider(
+ {
+ id: 'switch-to-key',
+ name: 'Switch to key',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://api.example/v1',
+ models: [{ id: 'm1', name: 'M1' }],
+ },
+ },
+ },
+ { codex: 'replacement-key' },
+ ),
+ ).rejects.toThrow('credential rollback failed');
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts
new file mode 100644
index 0000000000..df8ea20307
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ areProviderRequestUrlsAllowed,
+ providerConnectionTestRequestSignature,
+ providerModelFetchRequestSignature,
+} from '../providerModelFetch';
+
+const fields = {
+ baseUrl: ' https://api.example/v1 ',
+ requestPath: ' /responses ',
+ modelsUrl: ' /models ',
+ apiKey: ' secret-a ',
+ headers: [
+ { name: 'Authorization', value: 'Bearer stale' },
+ { name: 'X-Tenant', value: 'acme' },
+ ],
+};
+
+describe('providerModelFetchRequestSignature', () => {
+ it('invalidates an in-flight result when the auth mode changes', () => {
+ expect(providerModelFetchRequestSignature(fields, 'apiKey')).not.toBe(
+ providerModelFetchRequestSignature(fields, 'oauth'),
+ );
+ expect(providerModelFetchRequestSignature(fields, 'oauth')).not.toBe(
+ providerModelFetchRequestSignature(fields, 'none'),
+ );
+ });
+
+ it('tracks only the API key that is effective for the selected auth mode', () => {
+ const changed = { ...fields, apiKey: 'secret-b' };
+ expect(providerModelFetchRequestSignature(fields, 'apiKey')).not.toBe(
+ providerModelFetchRequestSignature(changed, 'apiKey'),
+ );
+ expect(providerModelFetchRequestSignature(fields, 'oauth')).toBe(
+ providerModelFetchRequestSignature(changed, 'oauth'),
+ );
+ });
+
+ it('uses credential-stripped headers when credentials are not supplied from the form', () => {
+ const changedCredential = {
+ ...fields,
+ headers: [
+ { name: 'Authorization', value: 'Bearer changed' },
+ { name: 'X-Tenant', value: 'acme' },
+ ],
+ };
+ const changedEffectiveHeader = {
+ ...fields,
+ headers: [
+ { name: 'Authorization', value: 'Bearer stale' },
+ { name: 'X-Tenant', value: 'other' },
+ ],
+ };
+ for (const authMode of ['oauth', 'none'] as const) {
+ expect(providerModelFetchRequestSignature(fields, authMode)).toBe(
+ providerModelFetchRequestSignature(changedCredential, authMode),
+ );
+ expect(providerModelFetchRequestSignature(fields, authMode)).not.toBe(
+ providerModelFetchRequestSignature(changedEffectiveHeader, authMode),
+ );
+ }
+ });
+});
+
+describe('providerConnectionTestRequestSignature', () => {
+ const connectionFields = {
+ ...fields,
+ wireProtocol: 'openai-responses',
+ models: [{ id: ' model-a ' }, { id: 'model-b' }],
+ };
+
+ it('invalidates a probe when request path, protocol, model, or auth changes', () => {
+ const original = providerConnectionTestRequestSignature(connectionFields, 'apiKey');
+ expect(
+ providerConnectionTestRequestSignature(
+ { ...connectionFields, requestPath: '/chat/completions' },
+ 'apiKey',
+ ),
+ ).not.toBe(original);
+ expect(
+ providerConnectionTestRequestSignature(
+ { ...connectionFields, wireProtocol: 'openai-chat' },
+ 'apiKey',
+ ),
+ ).not.toBe(original);
+ expect(
+ providerConnectionTestRequestSignature(
+ { ...connectionFields, models: [{ id: 'model-c' }] },
+ 'apiKey',
+ ),
+ ).not.toBe(original);
+ expect(providerConnectionTestRequestSignature(connectionFields, 'none')).not.toBe(original);
+ });
+});
+
+describe('areProviderRequestUrlsAllowed', () => {
+ it('keeps unsaved no-auth probes and model discovery on loopback', () => {
+ expect(
+ areProviderRequestUrlsAllowed(
+ 'none',
+ 'http://127.0.0.1:4000/v1',
+ 'http://localhost:4000/v1/models',
+ ),
+ ).toBe(true);
+ expect(areProviderRequestUrlsAllowed('none', 'https://proxy.example/v1')).toBe(false);
+ expect(
+ areProviderRequestUrlsAllowed(
+ 'none',
+ 'http://localhost:4000/v1',
+ 'https://models.example/v1/models',
+ ),
+ ).toBe(false);
+ });
+
+ it('does not apply the loopback restriction to authenticated requests', () => {
+ expect(areProviderRequestUrlsAllowed('apiKey', 'https://api.example/v1')).toBe(true);
+ expect(areProviderRequestUrlsAllowed('oauth', 'https://api.example/v1')).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.ts
index 6e5deb4db2..b2f089e254 100644
--- a/apps/desktop/src/renderer/lib/customProviders.ts
+++ b/apps/desktop/src/renderer/lib/customProviders.ts
@@ -5,9 +5,8 @@
* 本地加密,与内置 XD 网关 key 同机制;main 路由 resolve 时按 (id, agent) 读出注入鉴权头)。
*
* 顺序约定:
- * - create:先写配置(IPC 在重名 / 非法时 reject,避免误覆盖既有同 id 的 key),成功后存各 runtime 的密钥。
- * - update:先写配置,成功后仅覆盖**用户填了新密钥**的 runtime(留空 = 不改,遵循设计)。
- * - delete:先删配置,再清所有 runtime 的密钥(幂等)。
+ * - create / update / delete:配置 + 密钥一次提交给 main,由 main 的 per-provider queue
+ * 串行暂存 / 回滚,跨窗口 mutation 不会被较早请求的迟到回滚覆盖。
*/
import { customProviderSecretStorageKey } from '@/../shared/providerSecrets';
@@ -21,8 +20,6 @@ import type {
ProviderRuntimeModelConfig,
} from '@cindy/model-providers';
-const ALL_AGENTS: readonly AgentKind[] = ['claude-code', 'codex'];
-
/** per-runtime 密钥输入:键为 agent,值为该 runtime 的 API key(空串 = 不改 / 不存)。 */
export type RuntimeKeys = Partial<Record<AgentKind, string>>;
@@ -119,42 +116,23 @@ export async function readCustomProviderKey(
}
}
-/** 写入各 runtime 的密钥(仅非空的)。 */
-async function saveKeys(providerId: string, keys: RuntimeKeys): Promise<void> {
- for (const agent of ALL_AGENTS) {
- const key = keys[agent]?.trim();
- if (key) {
- await window.electronAPI.safeStorageStore(customProviderSecretStorageKey(providerId, agent), key);
- }
- }
-}
-
-/** 新建:先写配置(reject 时不碰密钥),成功后存各 runtime 密钥(非空才存)。 */
+/** 新建:配置与 runtime 密钥交给 main 的同一 provider mutation queue。 */
export async function createCustomProvider(
config: CustomProviderConfig,
keys: RuntimeKeys,
): Promise<void> {
- await window.electronAPI.maker.createCustomProvider(config);
- await saveKeys(config.id, keys);
+ await window.electronAPI.maker.createCustomProvider(config, keys);
}
-/** 编辑:先写配置,成功后仅覆盖填了新密钥的 runtime(留空 = 不改)。 */
+/** 编辑:main 在同一 provider mutation queue 内提交配置与 runtime 密钥。 */
export async function updateCustomProvider(
config: CustomProviderConfig,
keys: RuntimeKeys,
): Promise<void> {
- await window.electronAPI.maker.updateCustomProvider(config);
- await saveKeys(config.id, keys);
+ await window.electronAPI.maker.updateCustomProvider(config, keys);
}
-/** 删除:先删配置,再清所有 runtime 密钥(幂等,失败忽略)。 */
+/** 删除:main 在同一 provider mutation queue 内清配置与所有凭证。 */
export async function deleteCustomProvider(providerId: string): Promise<void> {
await window.electronAPI.maker.deleteCustomProvider(providerId);
- for (const agent of ALL_AGENTS) {
- try {
- await window.electronAPI.safeStorageRemove(customProviderSecretStorageKey(providerId, agent));
- } catch {
- /* 密钥清理失败无害:孤儿 .enc 不会被任何 provider 引用。 */
- }
- }
}
diff --git a/apps/desktop/src/renderer/lib/providerModelFetch.ts b/apps/desktop/src/renderer/lib/providerModelFetch.ts
new file mode 100644
index 0000000000..dc331745dd
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/providerModelFetch.ts
@@ -0,0 +1,77 @@
+import { isLoopbackProviderUrl } from '@cindy/model-providers';
+
+export type CustomProviderAuthMode = 'apiKey' | 'oauth' | 'none';
+
+export interface ProviderModelFetchSignatureFields {
+ baseUrl: string;
+ requestPath: string;
+ modelsUrl: string;
+ apiKey: string;
+ headers: ReadonlyArray<{ name: string; value: string }>;
+}
+
+export interface ProviderConnectionTestSignatureFields extends ProviderModelFetchSignatureFields {
+ wireProtocol: string;
+ models: ReadonlyArray<{ id: string }>;
+}
+
+export function stripCredentialHeaders(headers: Record<string, string>): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(headers).filter(([name]) => {
+ const normalized = name.toLowerCase();
+ return normalized !== 'authorization' && normalized !== 'x-api-key';
+ }),
+ );
+}
+
+/**
+ * 无鉴权请求在任何「落盘前」动作里也必须保持 loopback-only。测试连接和模型发现会直接
+ * 使用尚未保存的表单值,不能只依赖保存时与 main store 的最终校验。
+ */
+export function areProviderRequestUrlsAllowed(
+ authMode: CustomProviderAuthMode,
+ baseUrl: string,
+ modelsUrl?: string,
+): boolean {
+ if (authMode !== 'none') return true;
+ return (
+ isLoopbackProviderUrl(baseUrl.trim()) &&
+ (!modelsUrl?.trim() || isLoopbackProviderUrl(modelsUrl.trim()))
+ );
+}
+
+/**
+ * 模型发现请求的完整有效输入签名。只在当前对话框闭包内短暂比较,不持久化、不记录。
+ * 鉴权模式变化会改变实际请求,即使表单里的 key/header 文本没有变化也必须作废旧响应。
+ */
+export function providerModelFetchRequestSignature(
+ fields: ProviderModelFetchSignatureFields,
+ authMode: CustomProviderAuthMode,
+): string {
+ const headers: Record<string, string> = {};
+ for (const header of fields.headers) {
+ const name = header.name.trim();
+ if (name) headers[name] = header.value.trim();
+ }
+ const effectiveHeaders = authMode === 'apiKey' ? headers : stripCredentialHeaders(headers);
+ return JSON.stringify({
+ authMode,
+ baseUrl: fields.baseUrl.trim(),
+ requestPath: fields.requestPath.trim(),
+ modelsUrl: fields.modelsUrl.trim(),
+ apiKey: authMode === 'apiKey' ? fields.apiKey.trim() : null,
+ headers: Object.entries(effectiveHeaders).sort(([a], [b]) => a.localeCompare(b)),
+ });
+}
+
+/** 测试连接还取决于实际推理协议与首个有效模型;任一变化都必须让旧探测响应失效。 */
+export function providerConnectionTestRequestSignature(
+ fields: ProviderConnectionTestSignatureFields,
+ authMode: CustomProviderAuthMode,
+): string {
+ return JSON.stringify({
+ request: providerModelFetchRequestSignature(fields, authMode),
+ wireProtocol: fields.wireProtocol,
+ modelId: fields.models.map((model) => model.id.trim()).find(Boolean) ?? null,
+ });
+}
diff --git a/apps/desktop/src/renderer/lib/providerModels.ts b/apps/desktop/src/renderer/lib/providerModels.ts
index 8ff1b29b57..8fe6682805 100644
--- a/apps/desktop/src/renderer/lib/providerModels.ts
+++ b/apps/desktop/src/renderer/lib/providerModels.ts
@@ -12,6 +12,7 @@
*/
import {
+ isModelVisible,
providerOffersModel,
providersForAgent,
sessionModelSupportsFastMode,
@@ -91,6 +92,23 @@ export function providerMonogram(name: string): string {
return ch.toUpperCase();
}
+/**
+ * 被控端模型可见性判定。override 缺失表示旧被控端,保持历史 fail-open;
+ * 现代被控端则复用共享的「显式 override 优先,否则目录默认值」口径。
+ */
+export function isDeviceModelVisible(
+ overrides: Record<string, boolean> | undefined,
+ agent: AgentKind,
+ providerId: string,
+ model: Pick<CatalogModel, 'id' | 'defaultEnabled'>,
+): boolean {
+ if (overrides === undefined) return true;
+ return isModelVisible(
+ overrides[`${agent}:${providerId}:${model.id}`],
+ model.defaultEnabled,
+ );
+}
+
/** Whether a provider relies on the local Responses-to-Chat handler for Codex. */
export function isChatBridgedCodexProvider(provider: ProviderView): boolean {
return provider.routing?.codex?.wireProtocol === 'openai-chat';
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index fc8562609e..82b6a75050 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3473,12 +3473,14 @@ interface ElectronAPI {
// 模型供应商目录(只读)—— 内置目录元数据 + 各供应商实时连接状态。
listProviders: () => Promise<{ providers: import('@cindy/model-providers').ProviderView[] }>;
- // 自定义供应商配置 CRUD(密钥另走通用 safeStorage IPC,不经这里)。
+ // 自定义供应商配置 CRUD(配置与 runtime 密钥均由 main 原子排队)。
createCustomProvider: (
config: import('@cindy/model-providers').CustomProviderConfig,
+ keys: Partial<Record<'claude-code' | 'codex', string>>,
) => Promise<{ ok: true }>;
updateCustomProvider: (
config: import('@cindy/model-providers').CustomProviderConfig,
+ keys: Partial<Record<'claude-code' | 'codex', string>>,
) => Promise<{ ok: true }>;
deleteCustomProvider: (providerId: string) => Promise<{ ok: true }>;
/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */
@@ -3493,6 +3495,7 @@ interface ElectronAPI {
agent: 'claude-code' | 'codex';
baseUrl: string;
modelId: string;
+ authMethod: 'apiKey' | 'oauth' | 'none';
wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;
requestPath?: string;
apiKey?: string | null;
@@ -3510,6 +3513,7 @@ interface ElectronAPI {
fetchProviderModels: (input: {
agent: 'claude-code' | 'codex';
baseUrl: string;
+ authMethod: 'apiKey' | 'oauth' | 'none';
modelsUrl?: string | null;
apiKey?: string | null;
headers?: Record<string, string>;
@@ -3555,9 +3559,15 @@ interface ElectronAPI {
/** 自定义 MCP 变更广播订阅(返回 off)。 */
onMcpChanged: (cb: () => void) => () => void;
/** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动)登录 / 登出 / 取消。 */
- providerOAuthLogin: (providerId: string) => Promise<{ ok: boolean; reason?: string }>;
+ providerOAuthLogin: (
+ providerId: string,
+ options?: { ownerId?: string },
+ ) => Promise<{ ok: boolean; reason?: string }>;
providerOAuthLogout: (providerId: string) => Promise<{ ok: true }>;
- providerOAuthCancel: (providerId: string) => Promise<{ ok: true }>;
+ providerOAuthCancel: (
+ providerId: string,
+ options?: { releaseOwner?: boolean; ownerId?: string },
+ ) => Promise<{ ok: true }>;
onProviderOAuthProgress: (
cb: (progress: {
providerId: string;
@@ -4231,14 +4241,27 @@ interface ElectronAPI {
/* ── Agent 鉴权 (取代老 codex.auth.*) ── */
auth: {
getState: (agentKind: 'claude-code' | 'codex') => Promise<CodexAuthState>;
- triggerLogin: (agentKind: 'claude-code' | 'codex') => Promise<CodexAuthState>;
- cancelLogin: (agentKind: 'claude-code' | 'codex') => Promise<void>;
+ triggerLogin: (
+ agentKind: 'claude-code' | 'codex',
+ options?: { mode?: 'browser' | 'device-code'; ownerId?: string },
+ ) => Promise<CodexAuthState>;
+ cancelLogin: (
+ agentKind: 'claude-code' | 'codex',
+ options?: { releaseOwner?: boolean; ownerId?: string },
+ ) => Promise<void>;
logout: (agentKind: 'claude-code' | 'codex') => Promise<void>;
onStateChanged: (
cb: (s: { agentKind: 'claude-code' | 'codex' } & CodexAuthState) => void,
) => () => void;
onLoginProgress: (
- cb: (p: { agentKind: 'claude-code' | 'codex'; phase: string; detail?: string }) => void,
+ cb: (p: {
+ agentKind: 'claude-code' | 'codex';
+ phase: string;
+ mode?: 'browser' | 'device-code';
+ detail?: string;
+ verificationUrl?: string;
+ userCode?: string;
+ }) => void,
) => () => void;
};
diff --git a/apps/mobile/src/__tests__/agentAuthGate.test.ts b/apps/mobile/src/__tests__/agentAuthGate.test.ts
index aa5256ac6e..13a67a4352 100644
--- a/apps/mobile/src/__tests__/agentAuthGate.test.ts
+++ b/apps/mobile/src/__tests__/agentAuthGate.test.ts
@@ -13,7 +13,12 @@ function provider(patch: Partial<ProviderView> & Pick<ProviderView, 'id' | 'agen
name: patch.id,
source: 'builtin',
auth: { method: 'api-key' },
- routing: {},
+ routing: Object.fromEntries(
+ patch.agents.map((agent) => [
+ agent,
+ { upstream: 'https://example.test', authStrategy: 'api-key-header' },
+ ]),
+ ),
models: {},
...patch,
} as ProviderView;
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 45aebceaa1..b98287285a 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
-import { REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';
+import {
+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
+ REMOTE_INVOKE_ALLOWLIST,
+} from '@cindy/device-link';
import {
createMobileMakerTransport,
MOBILE_MAKER_CHANNELS,
@@ -209,7 +212,9 @@ describe('mobile maker transport', () => {
expect(calls).toEqual([{
deviceId: 'dev-1',
channel: 'maker:provider:list',
- args: [],
+ args: [{
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ }],
}]);
});
diff --git a/apps/mobile/src/__tests__/mobileProviderLogo.test.ts b/apps/mobile/src/__tests__/mobileProviderLogo.test.ts
index 16436b59fc..2ee7d60899 100644
--- a/apps/mobile/src/__tests__/mobileProviderLogo.test.ts
+++ b/apps/mobile/src/__tests__/mobileProviderLogo.test.ts
@@ -20,7 +20,7 @@ describe('MobileProviderMark', () => {
const source = readSource('src/session/MobileProviderMark.tsx');
expect(source).toContain("from '@cindy/model-providers/branding';");
- expect(source).toContain("logoKind ?? resolveProviderLogoKind(providerId ?? '', routing)");
+ expect(source).toContain('isProviderLogoKind(logoKind) ? logoKind : resolveProviderLogoKind(');
expect(source).toContain('<Path d={PROVIDER_LOGO_PATHS[kind]} fill={fill} />');
expect(source).toContain('{providerMonogram(name)}');
expect(source).not.toContain('switch (providerId)');
@@ -51,4 +51,15 @@ describe('MobileProviderMark', () => {
expect(session).toContain('routing={composerPillSourceProvider?.routing}');
expect(session).toContain('logoKind={composerPillSourceProvider?.logoKind}');
});
+
+ it('advertises the full-logo capability on refresh and subscription frames', () => {
+ const context = readSource('src/device-link/DeviceLinkContext.tsx');
+
+ expect(context).toContain(
+ "'maker:provider:list', [{ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] }]",
+ );
+ expect(context).toContain(
+ 'capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2]',
+ );
+ });
});
diff --git a/apps/mobile/src/__tests__/providerModelSections.test.ts b/apps/mobile/src/__tests__/providerModelSections.test.ts
index 2e34cfe7c2..90e6322333 100644
--- a/apps/mobile/src/__tests__/providerModelSections.test.ts
+++ b/apps/mobile/src/__tests__/providerModelSections.test.ts
@@ -39,6 +39,7 @@ function provider(
id,
name: id,
agents: opts.agents ?? ['codex'],
+ routing: Object.fromEntries((opts.agents ?? ['codex']).map((agent) => [agent, {}])),
connected: opts.connected ?? true,
models: { codex: opts.codex, 'claude-code': opts.cc },
} as unknown as ProviderView;
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 466d820b5c..861907054f 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -3,6 +3,7 @@ import { AppState, Platform } from 'react-native';
import {
DeviceLinkClient,
DeviceLinkError,
+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
DL_SUBSCRIBE_CHANNEL,
DL_UNSUBSCRIBE_CHANNEL,
FILE_BROWSER_EVENT_CHANNEL,
@@ -466,7 +467,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
client,
deviceId,
'maker:provider:list',
- [],
+ [{ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] }],
)
).catch(() => { /* 下次进入选择器或重连补齐时继续重试。 */ });
void refreshDeviceCapabilities(client, deviceId);
@@ -787,6 +788,7 @@ async function sendOpenLink(client: DeviceLinkClient, deviceId: string): Promise
controllerName: mobileDeviceName(),
protocolVersion: PROTOCOL_VERSION,
appVersion: Constants.expoConfig?.version ?? '0.0.0',
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
});
// link-accept 只证明链路层活着,不证明 invoke 路径健康(review P1):事故形态
// 正是 link-open 在被控端 IPC/DB 路径之外应答正常、invoke 全部挂死——若凭
@@ -882,7 +884,11 @@ async function sendSubscribe(
try {
result = await client.invoke(deviceId, {
channel: DL_SUBSCRIBE_CHANNEL,
- args: [{ topics, controllerName: mobileDeviceName() }],
+ args: [{
+ topics,
+ controllerName: mobileDeviceName(),
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ }],
});
} catch (err) {
settleDeviceSend(deviceId, slot, classifyDeviceSendFailure(err));
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 26a92b5a5e..a8c2238ef5 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -16,6 +16,7 @@ import {
DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL,
MOBILE_REMOTE_INVOKE_CHANNELS,
} from '@cindy/maker-shared/device-link-contract';
+import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';
import type {
MobileGoalLimitsInput,
MobileGoalStatusPayload,
@@ -522,7 +523,9 @@ export function createMobileMakerTransport({
return {
createSession: (opts) => call('maker:create-session', [opts]),
getCapabilities: (agentKind) => call('maker:get-capabilities', [agentKind]),
- listProviders: () => call('maker:provider:list', []),
+ listProviders: () => call('maker:provider:list', [{
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ }]),
getSession: (sessionId) => call('local-db:sessions:get', [sessionId]),
patchSessionMeta: (sessionId, patch) => call('local-db:sessions:patch-meta', [sessionId, patch]),
dismissErrorMessage: (sessionId, clientId) =>
diff --git a/apps/mobile/src/session/MobileProviderMark.tsx b/apps/mobile/src/session/MobileProviderMark.tsx
index af3e333c59..dc805e4029 100644
--- a/apps/mobile/src/session/MobileProviderMark.tsx
+++ b/apps/mobile/src/session/MobileProviderMark.tsx
@@ -22,8 +22,8 @@ import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight as fontWeightToken, radius, typeScale } from '@/theme/tokens';
import {
PROVIDER_LOGO_PATHS,
+ isProviderLogoKind,
resolveProviderLogoKind,
- type ProviderLogoKind,
type ProviderLogoRouting,
} from '@cindy/model-providers/branding';
import { resolveModelIconKind } from '@cindy/model-providers/sections';
@@ -65,7 +65,7 @@ export interface MobileProviderMarkProps {
/** 用户重命名 provider 后用持久化 upstream 继续识别品牌。 */
routing?: ProviderLogoRouting;
/** 被控端剥离 routing 前解析出的非敏感品牌;device-link 场景优先使用。 */
- logoKind?: ProviderLogoKind;
+ logoKind?: string;
/** 供应商展示名(monogram 取首字母;官方 mark 分支不消费)。 */
name: string;
/** mark 单色;缺省 textSecondary(列表行口径,trigger 场景可传 textPrimary)。 */
@@ -80,7 +80,9 @@ export function MobileProviderMark({ providerId, routing, logoKind, name, color
// 官方 mark 比 monogram 容器缩一档(桌面同比:行内 mark ≈ 12.3 vs 容器 18),避免视觉过重。
const glyph = 13;
- const kind = logoKind ?? resolveProviderLogoKind(providerId ?? '', routing);
+ const kind = isProviderLogoKind(logoKind)
+ ? logoKind
+ : resolveProviderLogoKind(providerId ?? '', routing);
switch (kind) {
case 'anthropic':
@@ -138,7 +140,7 @@ export interface MobileModelIconMarkProps {
/** 回落用的来源供应商 id / 展示名(与 MobileProviderMark 同语义)。 */
providerId?: string;
routing?: ProviderLogoRouting;
- logoKind?: ProviderLogoKind;
+ logoKind?: string;
name: string;
color?: string;
}
diff --git a/docs/legal/notices/THIRD-PARTY-NOTICES.txt b/docs/legal/notices/THIRD-PARTY-NOTICES.txt
index 1ffc933715..3d2dbdc26c 100644
--- a/docs/legal/notices/THIRD-PARTY-NOTICES.txt
+++ b/docs/legal/notices/THIRD-PARTY-NOTICES.txt
@@ -3111,7 +3111,7 @@ necessary. Here is a sample; alter the names:
That's all there is to it!
------------------------------------------------------------------------------
-Code Island NotchPanelShape & mascot parameters (adapted) adapted
+Code Island NotchPanelShape & mascot parameters (adapted)
License: MIT
Source: https://github.com/wxtsky/CodeIsland
------------------------------------------------------------------------------
@@ -3683,6 +3683,33 @@ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
------------------------------------------------------------------------------
Lobe Icons SVG paths (vendored) 5.14.0
License: MIT
diff --git a/docs/legal/notices/desktop-linux.txt b/docs/legal/notices/desktop-linux.txt
index 98abf8058b..881dcc82af 100644
--- a/docs/legal/notices/desktop-linux.txt
+++ b/docs/legal/notices/desktop-linux.txt
@@ -965,6 +965,33 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
==============================================================================
SECTION 2: npm packages (781 packages)
==============================================================================
diff --git a/docs/legal/notices/desktop-macos.txt b/docs/legal/notices/desktop-macos.txt
index 551f6c6b91..290ff9bacd 100644
--- a/docs/legal/notices/desktop-macos.txt
+++ b/docs/legal/notices/desktop-macos.txt
@@ -966,7 +966,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-Code Island NotchPanelShape & mascot parameters (adapted) adapted
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+------------------------------------------------------------------------------
+Code Island NotchPanelShape & mascot parameters (adapted)
License: MIT
Source: https://github.com/wxtsky/CodeIsland
------------------------------------------------------------------------------
diff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txt
index ac06def9f4..c84da2ebcd 100644
--- a/docs/legal/notices/desktop-win.txt
+++ b/docs/legal/notices/desktop-win.txt
@@ -892,6 +892,33 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
------------------------------------------------------------------------------
Android SDK Platform-Tools (bundled binaries) 32.0.0
License: LicenseRef-Android-Platform-Tools-Notice
diff --git a/docs/legal/notices/mobile-android.txt b/docs/legal/notices/mobile-android.txt
index 58dd36549e..1b96db6ce9 100644
--- a/docs/legal/notices/mobile-android.txt
+++ b/docs/legal/notices/mobile-android.txt
@@ -23,6 +23,60 @@ Restricted or proprietary components are disclosed in the companion file.
SECTION 1: Bundled components (non-npm)
==============================================================================
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+------------------------------------------------------------------------------
+Lobe Icons SVG paths (vendored) 5.14.0
+License: MIT
+Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2023 LobeHub
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
------------------------------------------------------------------------------
JetBrains Mono fonts bundled
License: OFL-1.1
diff --git a/docs/legal/notices/mobile-ios.txt b/docs/legal/notices/mobile-ios.txt
index 3557360415..ab90651a97 100644
--- a/docs/legal/notices/mobile-ios.txt
+++ b/docs/legal/notices/mobile-ios.txt
@@ -23,6 +23,60 @@ Restricted or proprietary components are disclosed in the companion file.
SECTION 1: Bundled components (non-npm)
==============================================================================
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2026 Berri AI
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+------------------------------------------------------------------------------
+Lobe Icons SVG paths (vendored) 5.14.0
+License: MIT
+Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2023 LobeHub
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
------------------------------------------------------------------------------
JetBrains Mono fonts bundled
License: OFL-1.1
diff --git a/docs/legal/notices/sbom/desktop-linux.spdx.json b/docs/legal/notices/sbom/desktop-linux.spdx.json
index aa76b7a7db..cf979f5033 100644
--- a/docs/legal/notices/sbom/desktop-linux.spdx.json
+++ b/docs/legal/notices/sbom/desktop-linux.spdx.json
@@ -3,7 +3,7 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-desktop-linux",
- "documentNamespace": "https://cindy.app/spdx/desktop-linux/71ca5d23b32ae6e9265183d63607f7fc4dc7376308cfffc4cf746d2dc7918531",
+ "documentNamespace": "https://cindy.app/spdx/desktop-linux/a2a52b563135833de6f30063b0ebe53d9da3b35b98cf4547b31f5257258b127a",
"creationInfo": {
"created": "2026-07-26T02:38:39Z",
"creators": [
@@ -51,6 +51,16 @@
"licenseDeclared": "MIT",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "LiteLLM mascot SVG path (adapted)",
+ "SPDXID": "SPDXRef-Package-5cfa9bdbf62d839b",
+ "versionInfo": "adapted",
+ "downloadLocation": "https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "Lobe Icons SVG paths (vendored)",
"SPDXID": "SPDXRef-Package-82458194310410e0",
@@ -13420,6 +13430,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-e01faf6cc0ab33f1"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-5cfa9bdbf62d839b"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/desktop-macos.spdx.json b/docs/legal/notices/sbom/desktop-macos.spdx.json
index 2c4ade8809..256238747c 100644
--- a/docs/legal/notices/sbom/desktop-macos.spdx.json
+++ b/docs/legal/notices/sbom/desktop-macos.spdx.json
@@ -3,7 +3,7 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-desktop-macos",
- "documentNamespace": "https://cindy.app/spdx/desktop-macos/3b3da6083be54d1a02f211b384e996fe863f75def512829c90ecda5ee685e5dc",
+ "documentNamespace": "https://cindy.app/spdx/desktop-macos/45cd364c70333e33334a8a1dbe4e21a65e4620dbde2a8ac4e377b37c6ab72744",
"creationInfo": {
"created": "2026-07-26T02:38:39Z",
"creators": [
@@ -61,6 +61,16 @@
"licenseDeclared": "MIT",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "LiteLLM mascot SVG path (adapted)",
+ "SPDXID": "SPDXRef-Package-5cfa9bdbf62d839b",
+ "versionInfo": "adapted",
+ "downloadLocation": "https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "Lobe Icons SVG paths (vendored)",
"SPDXID": "SPDXRef-Package-82458194310410e0",
@@ -13435,6 +13445,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-e01faf6cc0ab33f1"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-5cfa9bdbf62d839b"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/desktop-win.spdx.json b/docs/legal/notices/sbom/desktop-win.spdx.json
index f3dfaf21f0..b09a45eb25 100644
--- a/docs/legal/notices/sbom/desktop-win.spdx.json
+++ b/docs/legal/notices/sbom/desktop-win.spdx.json
@@ -3,7 +3,7 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-desktop-win",
- "documentNamespace": "https://cindy.app/spdx/desktop-win/a4ceee438b8b55f4ba8a27d4ec3b154cbe5badce74aeaeda93193b7a3499b1e7",
+ "documentNamespace": "https://cindy.app/spdx/desktop-win/6a5a11919e34e4b8636b7faa8671adc012e09400bcbc5d6a25ef4d7f4ca0533f",
"creationInfo": {
"created": "2026-07-26T02:38:39Z",
"creators": [
@@ -51,6 +51,16 @@
"licenseDeclared": "MIT",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "LiteLLM mascot SVG path (adapted)",
+ "SPDXID": "SPDXRef-Package-5cfa9bdbf62d839b",
+ "versionInfo": "adapted",
+ "downloadLocation": "https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "Lobe Icons SVG paths (vendored)",
"SPDXID": "SPDXRef-Package-82458194310410e0",
@@ -17789,6 +17799,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-e01faf6cc0ab33f1"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-5cfa9bdbf62d839b"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/mobile-android.spdx.json b/docs/legal/notices/sbom/mobile-android.spdx.json
index 44b7176c5a..838208aca4 100644
--- a/docs/legal/notices/sbom/mobile-android.spdx.json
+++ b/docs/legal/notices/sbom/mobile-android.spdx.json
@@ -3,7 +3,7 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-mobile-android",
- "documentNamespace": "https://cindy.app/spdx/mobile-android/7073bd26a8bec4bc519dddb64ad4dec5f8e3314eeb49284f203d4779b32decd0",
+ "documentNamespace": "https://cindy.app/spdx/mobile-android/05efd357f74ac207a075699dbbd457afe65ed99fd574ee594be1d4bb651dc49a",
"creationInfo": {
"created": "2026-07-26T02:38:39Z",
"creators": [
@@ -31,6 +31,26 @@
"licenseDeclared": "OFL-1.1",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "LiteLLM mascot SVG path (adapted)",
+ "SPDXID": "SPDXRef-Package-5cfa9bdbf62d839b",
+ "versionInfo": "adapted",
+ "downloadLocation": "https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
+ {
+ "name": "Lobe Icons SVG paths (vendored)",
+ "SPDXID": "SPDXRef-Package-82458194310410e0",
+ "versionInfo": "5.14.0",
+ "downloadLocation": "https://github.com/lobehub/lobe-icons/tree/v5.14.0",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "@adobe/css-tools",
"SPDXID": "SPDXRef-Package-10a5c5df7c6ba052",
@@ -10260,6 +10280,16 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-4aed76e603981340"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-5cfa9bdbf62d839b"
+ },
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-82458194310410e0"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/mobile-ios.spdx.json b/docs/legal/notices/sbom/mobile-ios.spdx.json
index 9615eb1918..2e287dec0f 100644
--- a/docs/legal/notices/sbom/mobile-ios.spdx.json
+++ b/docs/legal/notices/sbom/mobile-ios.spdx.json
@@ -3,7 +3,7 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-mobile-ios",
- "documentNamespace": "https://cindy.app/spdx/mobile-ios/bcbee371f2714b4c4f18b156d42dd7bfd99ed8e2fd7e7a89d3dd3873c39324cf",
+ "documentNamespace": "https://cindy.app/spdx/mobile-ios/9cae3d29bee1df233432e6dd0978265ea2d61b380b2e50bf92a64c3516a1cccf",
"creationInfo": {
"created": "2026-07-26T02:38:39Z",
"creators": [
@@ -21,6 +21,26 @@
"licenseDeclared": "OFL-1.1",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "LiteLLM mascot SVG path (adapted)",
+ "SPDXID": "SPDXRef-Package-5cfa9bdbf62d839b",
+ "versionInfo": "adapted",
+ "downloadLocation": "https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
+ {
+ "name": "Lobe Icons SVG paths (vendored)",
+ "SPDXID": "SPDXRef-Package-82458194310410e0",
+ "versionInfo": "5.14.0",
+ "downloadLocation": "https://github.com/lobehub/lobe-icons/tree/v5.14.0",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "TapTapSDK/Core",
"SPDXID": "SPDXRef-Package-962056ba719a6ad6",
@@ -10255,6 +10275,16 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-4aed76e603981340"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-5cfa9bdbf62d839b"
+ },
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-82458194310410e0"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index de478381ae..b2c7299d22 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -651,11 +651,11 @@ describe('anthropic-compat-proxy routingTransform', () => {
proxy = await createAnthropicCompatProxy({
upstream: `${custom.url}/base?tenant=acme`,
transformRequest: [],
- routingTransform: () => ({ pathOverride: '/infer?stream=1' }),
+ routingTransform: () => ({ pathOverride: '/infer?stream=1&next=%2fadmin' }),
});
await post(proxy.url, { model: 'custom-model' });
- expect(custom.paths).toEqual(['/base/infer?tenant=acme&stream=1']);
+ expect(custom.paths).toEqual(['/base/infer?tenant=acme&stream=1&next=%2fadmin']);
});
it.each([
@@ -668,10 +668,16 @@ describe('anthropic-compat-proxy routingTransform', () => {
'/infer\u007fmode',
'/infer\u0085mode',
'/café',
+ '/../admin',
+ '/.%2e/admin',
+ '/%2e%2e%2fadmin',
+ '/safe%5Cpart',
+ '/a<b',
'/infer%2',
'/%ZZ',
'/模型',
'/v1\\messages',
+ `/${'a'.repeat(2_048)}`,
])('rejects an unsafe path override before contacting the upstream: %j', async (pathOverride) => {
const custom = await startFakeUpstream((_i, _b, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index 3f757eb901..921a36ec03 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -262,16 +262,28 @@ function respondRoutingFailure(
/** 路由层是最后的信任边界;任何调用方给出的路径覆盖都必须保持同源且不可注入 header。 */
function isSafePathOverride(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ const queryIndex = value.indexOf('?');
+ const pathname = queryIndex === -1 ? value : value.slice(0, queryIndex);
+ const hasEncodedPathSeparator = /%(?:2f|5c)/i.test(pathname);
+ const hasDotSegment = pathname
+ .split('/')
+ .some((segment) => {
+ const normalizedDots = segment.replace(/%2e/gi, '.');
+ return normalizedDots === '.' || normalizedDots === '..';
+ });
return (
- typeof value === 'string'
- && value.length >= 1
+ value.length >= 1
&& value.length <= 2_048
&& value.startsWith('/')
&& !value.startsWith('//')
&& !value.includes('#')
&& !value.includes('\\')
&& !/[^\u0021-\u007e]/.test(value)
+ && /^\/[A-Za-z0-9\-._~%!$&()*+,;=:@/?]*$/.test(value)
&& !/%(?![0-9A-Fa-f]{2})/.test(value)
+ && !hasEncodedPathSeparator
+ && !hasDotSegment
);
}
diff --git a/packages/device-link/README.md b/packages/device-link/README.md
index 5e6f6605d6..14705a0c8e 100644
--- a/packages/device-link/README.md
+++ b/packages/device-link/README.md
@@ -62,6 +62,10 @@
- `link-open`(控制端→被控端):建立「正在被控」链路 → 被控端 arm push 转发 + 弹「正在被控」可见性。`link-accept` 回带 `allowlistHash`(探测两端版本差异)。
- **`invoke` 不依赖 link-open**(只读 listing 可不开链路、不触发被控横幅);进入某会话实时操作时才 `link-open` 升级到「streaming tier」。
+- 控制端的 append-only `capabilities` 除可随 `link-open` 协商,也可随
+ `device-link:subscribe` 的首参或 listing invoke(当前为 `maker:provider:list`)的首参携带;
+ 因此 listing-only 控制端无需先打开控制链路,也能安全接收能力门控的新 wire 字段。被控端
+ 必须把缺失、非数组、超长或非字符串能力值按“不支持”处理。
- `link-close`:任一端解链(`reason: user|toggle-off|shutdown`)。
## 错误模型
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index 1d335cc783..321c1242e8 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -99,8 +99,16 @@ export interface LinkOpenPayload {
controllerName: string;
protocolVersion: number;
appVersion: string;
+ /**
+ * 控制端支持的端到端可选能力(append-only)。旧控制端缺省为空集;
+ * 被控端只有在能力明确声明时才发送对应的新 wire 字段。
+ */
+ capabilities?: string[];
}
+/** 控制端能安全消费完整 ProviderLogoKind(含 #527 新增品牌)的 maker:provider:list 投影。 */
+export const CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 = 'provider-logo-kinds-v2';
+
export interface LinkAcceptPayload {
appVersion: string;
/** 被控端 allowlist 的指纹,便于控制端探测版本差异 */
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index a6728743d6..fd780626b0 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -29,7 +29,7 @@ import {
import type { AgentKind, Effort, PermissionMode, ReasoningDisplay, UserMessage, WorkspaceKind } from '../types/common.js';
import type { Capabilities, EffortDescriptor, ModelDescriptor } from '../types/capabilities.js';
import { NotSupportedError } from '../types/capabilities.js';
-import type { AgentCredentialMode } from '../interfaces/auth-adapter.js';
+import type { AgentCredentialMode, AuthLoginOptions } from '../interfaces/auth-adapter.js';
import type {
MemoryStatus,
MemorySetResult,
@@ -994,7 +994,7 @@ export abstract class BaseAgent {
return this.deps.auth.getState();
}
- triggerLogin(opts?: { onProgress?: (msg: string) => void }) {
+ triggerLogin(opts?: AuthLoginOptions) {
return this.deps.auth.triggerLogin(opts);
}
diff --git a/packages/maker-core/src/interfaces/auth-adapter.ts b/packages/maker-core/src/interfaces/auth-adapter.ts
index ab2cf645be..b585961bd8 100644
--- a/packages/maker-core/src/interfaces/auth-adapter.ts
+++ b/packages/maker-core/src/interfaces/auth-adapter.ts
@@ -9,6 +9,12 @@
import type { AuthState } from '../types/common.js';
export type AgentCredentialMode = 'gateway-key' | 'oauth-bearer' | 'provider-oauth';
+export type AgentLoginMode = 'browser' | 'device-code';
+
+export interface AuthLoginOptions {
+ mode?: AgentLoginMode;
+ onProgress?: (msg: string) => void;
+}
export interface AuthAdapterOptions {
/**
@@ -26,7 +32,7 @@ export interface AuthAdapter {
getState(options?: AuthAdapterOptions): Promise<AuthState>;
/** 触发登录流程(OAuth 跳浏览器 / API key 弹窗 / 报错) */
- triggerLogin(opts?: { onProgress?: (msg: string) => void }): Promise<AuthState>;
+ triggerLogin(opts?: AuthLoginOptions): Promise<AuthState>;
/** 退出登录,清理本地凭证 */
logout(): Promise<void>;
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 218679084d..e6e905f307 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -35,6 +35,7 @@ import type { MemoryStatus, MemorySetResult, MemoryResetResult } from './types/m
import type { ConsumeAccountRateLimitResetCreditParams } from './types/account-rate-limits.js';
import type { SessionStorage, SessionMeta } from './interfaces/session-storage.js';
import type { Logger } from './interfaces/logger.js';
+import type { AuthLoginOptions } from './interfaces/auth-adapter.js';
import type { MakerMemoryManager } from './memory/manager.js';
/**
@@ -677,7 +678,7 @@ export class Maker {
return this.requireAgent(agentKind).getAuthState();
}
- async triggerAgentLogin(agentKind: AgentKind, opts?: { onProgress?: (msg: string) => void }) {
+ async triggerAgentLogin(agentKind: AgentKind, opts?: AuthLoginOptions) {
return this.requireAgent(agentKind).triggerLogin(opts);
}
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 10cbb7e516..e45b1e70bb 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -576,6 +576,436 @@
]
}
}
+ },
+ {
+ "id": "google-gemini-api",
+ "name": "Google Gemini API",
+ "docsUrl": "https://ai.google.dev/gemini-api/docs/openai",
+ "regionHint": "global",
+ "runtimes": {
+ "codex": {
+ "baseUrl": "https://generativelanguage.googleapis.com/v1beta/openai",
+ "wireProtocol": "openai-chat",
+ "modelsUrl": "https://generativelanguage.googleapis.com/v1beta/openai/models",
+ "models": [
+ {
+ "id": "gemini-3.6-flash",
+ "name": "Gemini 3.6 Flash",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "gemini-3.5-flash",
+ "name": "Gemini 3.5 Flash",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "gemini-3.5-flash-lite",
+ "name": "Gemini 3.5 Flash-Lite",
+ "contextWindow": 1000000
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "litellm",
+ "name": "LiteLLM Proxy",
+ "docsUrl": "https://docs.litellm.ai/docs/proxy/quick_start",
+ "authMethod": "none",
+ "runtimes": {
+ "codex": {
+ "baseUrl": "http://127.0.0.1:4000/v1",
+ "baseUrlEditable": true,
+ "models": []
+ }
+ }
+ },
+ {
+ "id": "longcat",
+ "name": "LongCat",
+ "docsUrl": "https://longcat.chat/platform/docs/zh/",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://api.longcat.chat/anthropic",
+ "modelsUrl": "https://api.longcat.chat/openai/v1/models",
+ "models": [
+ {
+ "id": "LongCat-2.0",
+ "name": "LongCat 2.0",
+ "contextWindow": 1000000
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://api.longcat.chat/openai/v1",
+ "modelsUrl": "https://api.longcat.chat/openai/v1/models",
+ "models": [
+ {
+ "id": "LongCat-2.0",
+ "name": "LongCat 2.0",
+ "contextWindow": 1000000
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "zhipu-coding-plan-cn",
+ "name": "智谱 GLM Coding Plan(中国大陆)",
+ "nameEn": "Zhipu GLM Coding Plan (China)",
+ "docsUrl": "https://docs.bigmodel.cn/cn/coding-plan/quick-start",
+ "regionHint": "cn",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://open.bigmodel.cn/api/anthropic",
+ "models": [
+ {
+ "id": "glm-5.2[1m]",
+ "name": "GLM-5.2 (1M)",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "glm-5.2",
+ "name": "GLM-5.2"
+ },
+ {
+ "id": "glm-5.1",
+ "name": "GLM-5.1"
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",
+ "wireProtocol": "openai-chat",
+ "models": [
+ {
+ "id": "glm-5.2",
+ "name": "GLM-5.2"
+ },
+ {
+ "id": "glm-5.1",
+ "name": "GLM-5.1"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "zai-coding-plan-global",
+ "name": "Z.ai GLM Coding Plan (Global)",
+ "docsUrl": "https://docs.z.ai/devpack/overview",
+ "regionHint": "global",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://api.z.ai/api/anthropic",
+ "models": [
+ {
+ "id": "glm-5.2[1m]",
+ "name": "GLM-5.2 (1M)",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "glm-5.2",
+ "name": "GLM-5.2"
+ },
+ {
+ "id": "glm-5.1",
+ "name": "GLM-5.1"
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",
+ "wireProtocol": "openai-chat",
+ "models": [
+ {
+ "id": "glm-5.2",
+ "name": "GLM-5.2"
+ },
+ {
+ "id": "glm-5.1",
+ "name": "GLM-5.1"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "xiaomi-mimo-api-cn",
+ "name": "小米 MiMo API(按量)",
+ "nameEn": "Xiaomi MiMo API (pay as you go)",
+ "docsUrl": "https://mimo.mi.com/docs/zh-CN/quick-start/summary/first-api-call",
+ "regionHint": "cn",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://api.xiaomimimo.com/anthropic",
+ "models": [
+ {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo V2.5 Pro",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "mimo-v2.5",
+ "name": "MiMo V2.5",
+ "contextWindow": 1000000
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://api.xiaomimimo.com/v1",
+ "wireProtocol": "openai-chat",
+ "models": [
+ {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo V2.5 Pro",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "mimo-v2.5",
+ "name": "MiMo V2.5",
+ "contextWindow": 1000000
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "xiaomi-mimo-token-plan-cn",
+ "name": "小米 MiMo Token Plan(包月)",
+ "nameEn": "Xiaomi MiMo Token Plan",
+ "docsUrl": "https://mimo.mi.com/docs/zh-CN/quick-start/summary/first-api-call",
+ "regionHint": "cn",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/anthropic",
+ "models": [
+ {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo V2.5 Pro",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "mimo-v2.5",
+ "name": "MiMo V2.5",
+ "contextWindow": 1000000
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",
+ "wireProtocol": "openai-chat",
+ "models": [
+ {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo V2.5 Pro",
+ "contextWindow": 1000000
+ },
+ {
+ "id": "mimo-v2.5",
+ "name": "MiMo V2.5",
+ "contextWindow": 1000000
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "volcengine-coding-plan",
+ "name": "火山方舟 Coding Plan",
+ "nameEn": "Volcengine Ark Coding Plan",
+ "docsUrl": "https://www.volcengine.com/docs/82379/1925114",
+ "regionHint": "cn",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://ark.cn-beijing.volces.com/api/coding",
+ "models": [
+ {
+ "id": "ark-code-latest",
+ "name": "Ark Code Latest"
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://ark.cn-beijing.volces.com/api/coding/v3",
+ "wireProtocol": "openai-chat",
+ "models": [
+ {
+ "id": "ark-code-latest",
+ "name": "Ark Code Latest"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "tencentcloud-coding-plan",
+ "name": "腾讯云 Coding Plan",
+ "nameEn": "Tencent Cloud Coding Plan",
+ "docsUrl": "https://cloud.tencent.com/document/product/1823/130092",
+ "regionHint": "cn",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://api.lkeap.cloud.tencent.com/coding/anthropic",
+ "models": [
+ {
+ "id": "tc-code-latest",
+ "name": "Tencent Code Latest"
+ },
+ {
+ "id": "glm-5",
+ "name": "GLM-5"
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://api.lkeap.cloud.tencent.com/coding/v3",
+ "wireProtocol": "openai-chat",
+ "models": [
+ {
+ "id": "tc-code-latest",
+ "name": "Tencent Code Latest"
+ },
+ {
+ "id": "glm-5",
+ "name": "GLM-5"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "opencode-go",
+ "name": "OpenCode Go",
+ "docsUrl": "https://opencode.ai/docs/go/",
+ "regionHint": "global",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://opencode.ai/zen/go",
+ "modelsUrl": "https://opencode.ai/zen/go/v1/models",
+ "models": [
+ {
+ "id": "minimax-m3",
+ "name": "MiniMax M3"
+ },
+ {
+ "id": "minimax-m2.7",
+ "name": "MiniMax M2.7"
+ },
+ {
+ "id": "minimax-m2.5",
+ "name": "MiniMax M2.5"
+ },
+ {
+ "id": "qwen3.7-max",
+ "name": "Qwen3.7 Max"
+ },
+ {
+ "id": "qwen3.7-plus",
+ "name": "Qwen3.7 Plus"
+ },
+ {
+ "id": "qwen3.6-plus",
+ "name": "Qwen3.6 Plus"
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://opencode.ai/zen/go/v1",
+ "wireProtocol": "openai-chat",
+ "modelsUrl": "https://opencode.ai/zen/go/v1/models",
+ "models": [
+ {
+ "id": "grok-4.5",
+ "name": "Grok 4.5"
+ },
+ {
+ "id": "glm-5.2",
+ "name": "GLM-5.2"
+ },
+ {
+ "id": "glm-5.1",
+ "name": "GLM-5.1"
+ },
+ {
+ "id": "kimi-k3",
+ "name": "Kimi K3"
+ },
+ {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code"
+ },
+ {
+ "id": "kimi-k2.6",
+ "name": "Kimi K2.6"
+ },
+ {
+ "id": "mimo-v2.5",
+ "name": "MiMo V2.5"
+ },
+ {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo V2.5 Pro"
+ },
+ {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro"
+ },
+ {
+ "id": "deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash"
+ },
+ {
+ "id": "hy3",
+ "name": "Hy3"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "vercel-ai-gateway",
+ "name": "Vercel AI Gateway",
+ "docsUrl": "https://vercel.com/docs/ai-gateway/coding-agents",
+ "regionHint": "global",
+ "runtimes": {
+ "claude-code": {
+ "baseUrl": "https://ai-gateway.vercel.sh",
+ "modelsUrl": "https://ai-gateway.vercel.sh/v1/models",
+ "models": [
+ {
+ "id": "anthropic/claude-sonnet-4.6",
+ "name": "Claude Sonnet 4.6 (Vercel)"
+ },
+ {
+ "id": "openai/gpt-5.4",
+ "name": "GPT-5.4 (Vercel)"
+ },
+ {
+ "id": "xai/grok-4.5",
+ "name": "Grok 4.5 (Vercel)"
+ }
+ ]
+ },
+ "codex": {
+ "baseUrl": "https://ai-gateway.vercel.sh/v1",
+ "modelsUrl": "https://ai-gateway.vercel.sh/v1/models",
+ "models": [
+ {
+ "id": "anthropic/claude-sonnet-4.6",
+ "name": "Claude Sonnet 4.6 (Vercel)"
+ },
+ {
+ "id": "openai/gpt-5.4",
+ "name": "GPT-5.4 (Vercel)"
+ },
+ {
+ "id": "xai/grok-4.5",
+ "name": "Grok 4.5 (Vercel)"
+ }
+ ]
+ }
+ }
}
],
"cindyModelMeta": {
diff --git a/packages/model-providers/src/__tests__/invocation.test.ts b/packages/model-providers/src/__tests__/invocation.test.ts
index d9205597bb..1b8525c6f3 100644
--- a/packages/model-providers/src/__tests__/invocation.test.ts
+++ b/packages/model-providers/src/__tests__/invocation.test.ts
@@ -185,6 +185,7 @@ function providers(): ProviderView[] {
id: 'anthropic',
name: 'anthropic',
agents: ['claude-code'],
+ routing: { 'claude-code': {} },
models: { 'claude-code': [model('claude-opus-5')] },
connected: true,
access: { kind: 'subscription', product: 'Claude.ai' },
@@ -193,6 +194,7 @@ function providers(): ProviderView[] {
id: 'xd',
name: 'xd',
agents: ['claude-code', 'codex'],
+ routing: { 'claude-code': {}, codex: {} },
models: {
'claude-code': [model('claude-opus-5'), model('claude-sonnet-4-6')],
codex: [model('gpt-5.5', { efforts: ['low', 'medium', 'high', 'xhigh'] })],
@@ -204,6 +206,7 @@ function providers(): ProviderView[] {
id: 'openai',
name: 'openai',
agents: ['codex'],
+ routing: { codex: {} },
models: { codex: [model('gpt-5.5')] },
connected: false,
},
@@ -534,6 +537,7 @@ describe('resolveModelInvocation — codex review 三轮:回落保真度', () =>
id: 'pa',
name: 'pa',
agents: ['codex'],
+ routing: { codex: {} },
models: { codex: [] },
connected: true,
},
@@ -541,6 +545,7 @@ describe('resolveModelInvocation — codex review 三轮:回落保真度', () =>
id: 'pb',
name: 'pb',
agents: ['claude-code'],
+ routing: { 'claude-code': {} },
models: { 'claude-code': [model('claude-sonnet-4-6'), model('gpt-5.5')] },
connected: true,
},
@@ -564,6 +569,7 @@ describe('resolveModelInvocation — codex review 三轮:回落保真度', () =>
id: 'anthropic',
name: 'anthropic',
agents: ['claude-code'],
+ routing: { 'claude-code': {} },
models: { 'claude-code': [model('a-first')] },
connected: true,
},
@@ -571,6 +577,7 @@ describe('resolveModelInvocation — codex review 三轮:回落保真度', () =>
id: 'xd',
name: 'xd',
agents: ['claude-code'],
+ routing: { 'claude-code': {} },
models: { 'claude-code': [model('xd-first'), model('a-first')] },
connected: true,
},
@@ -620,6 +627,7 @@ describe('resolveModelInvocation — codex review 四轮:无点名路径与 prov
id: 'pa',
name: 'pa',
agents: ['codex'],
+ routing: { codex: {} },
models: { codex: [] },
connected: true,
},
@@ -627,6 +635,7 @@ describe('resolveModelInvocation — codex review 四轮:无点名路径与 prov
id: 'pb',
name: 'pb',
agents: ['claude-code'],
+ routing: { 'claude-code': {} },
models: { 'claude-code': [model('claude-sonnet-4-6')] },
connected: true,
},
diff --git a/packages/model-providers/src/__tests__/modelList.test.ts b/packages/model-providers/src/__tests__/modelList.test.ts
index ec071a8038..b06c76e460 100644
--- a/packages/model-providers/src/__tests__/modelList.test.ts
+++ b/packages/model-providers/src/__tests__/modelList.test.ts
@@ -94,6 +94,7 @@ function provider(
id,
name: id,
agents,
+ routing: Object.fromEntries(agents.map((agent) => [agent, {}])),
models,
connected: true,
...extra,
diff --git a/packages/model-providers/src/__tests__/presets.test.ts b/packages/model-providers/src/__tests__/presets.test.ts
index 6a0fa865dc..65692762aa 100644
--- a/packages/model-providers/src/__tests__/presets.test.ts
+++ b/packages/model-providers/src/__tests__/presets.test.ts
@@ -89,6 +89,49 @@ describe('sanitizePresets', () => {
expect(p.runtimes['claude-code']?.modelsUrl).toBeUndefined();
}
});
+
+ it('authMethod / baseUrlEditable 只接受受支持的枚举与布尔值', () => {
+ const valid = {
+ ...VALID_PRESET,
+ id: 'local-proxy',
+ authMethod: 'none',
+ runtimes: {
+ codex: {
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ baseUrlEditable: true,
+ models: [{ id: 'local', name: 'Local' }],
+ },
+ },
+ };
+ expect(sanitizePresets([valid])).toEqual([valid]);
+ expect(sanitizePresets([{ ...valid, id: 'bad-auth', authMethod: 'oauth' }])).toEqual([]);
+ expect(sanitizePresets([{
+ ...valid,
+ id: 'bad-editable',
+ runtimes: { codex: { ...valid.runtimes.codex, baseUrlEditable: 'yes' } },
+ }])).toEqual([]);
+ });
+
+ it('requestPath 合法时保留;跨主机、fragment 与 CRLF 形态剥字段但保留预设', () => {
+ const runtime = (requestPath: unknown) => ({
+ codex: {
+ baseUrl: 'https://x.example/v1',
+ models: [{ id: 'm', name: 'M' }],
+ requestPath,
+ },
+ });
+ const out = sanitizePresets([
+ { id: 'good-path', name: 'Good', runtimes: runtime('/custom/infer?tenant=1') },
+ { id: 'authority-path', name: 'Bad', runtimes: runtime('//evil.example/infer') },
+ { id: 'fragment-path', name: 'Bad', runtimes: runtime('/infer#secret') },
+ { id: 'newline-path', name: 'Bad', runtimes: runtime('/infer\r\nx: y') },
+ ]);
+ expect(out).toHaveLength(4);
+ expect(out[0]!.runtimes.codex?.requestPath).toBe('/custom/infer?tenant=1');
+ for (const preset of out.slice(1)) {
+ expect(preset.runtimes.codex?.requestPath).toBeUndefined();
+ }
+ });
});
describe('parseCatalog presets 容错', () => {
@@ -174,6 +217,24 @@ describe('regionHint 归一化与 locale 排序', () => {
);
});
+ it('智谱与 Z.AI Coding Plan 使用同一厂商分组并按 locale 排区域顺序', () => {
+ const presets = sanitizePresets([
+ mk('zai-coding-plan-global', 'global'),
+ mk('zhipu-coding-plan-cn', 'cn'),
+ mk('volcengine-coding-plan'),
+ ]);
+ expect(sortPresetsForLocale(presets, 'zh-CN').map((p) => p.id)).toEqual([
+ 'volcengine-coding-plan',
+ 'zhipu-coding-plan-cn',
+ 'zai-coding-plan-global',
+ ]);
+ expect(sortPresetsForLocale(presets, 'en').map((p) => p.id)).toEqual([
+ 'volcengine-coding-plan',
+ 'zai-coding-plan-global',
+ 'zhipu-coding-plan-cn',
+ ]);
+ });
+
it('内置目录的双端点厂商 cn/global 各有一条', () => {
const presets = BUNDLED_CATALOG.presets ?? [];
for (const vendor of ['zhipu-glm', 'moonshot-kimi', 'minimax']) {
@@ -207,6 +268,20 @@ describe('parseCatalog oauth 描述符校验', () => {
it('完整描述符通过', () => {
expect(() => parseCatalog(catalogWithAuth({ method: 'oauth', oauth }))).not.toThrow();
+ expect(() =>
+ parseCatalog(
+ catalogWithAuth({
+ method: 'oauth',
+ oauth: {
+ flow: 'device-code',
+ deviceAuthorizationUrl: 'https://auth.acme.example/device',
+ tokenUrl: 'https://auth.acme.example/token',
+ clientId: 'device-client',
+ scopes: 'openid',
+ },
+ }),
+ ),
+ ).not.toThrow();
});
it('缺字段 / 非 https / 非法端口 → parse 失败(回退 bundled 的路径)', () => {
@@ -219,6 +294,20 @@ describe('parseCatalog oauth 描述符校验', () => {
expect(() =>
parseCatalog(catalogWithAuth({ method: 'oauth', oauth: { ...oauth, redirectPort: 99999 } })),
).toThrow(/redirectPort/);
+ expect(() =>
+ parseCatalog(
+ catalogWithAuth({
+ method: 'oauth',
+ oauth: {
+ flow: 'device-code',
+ deviceAuthorizationUrl: 'http://auth.acme.example/device',
+ tokenUrl: oauth.tokenUrl,
+ clientId: oauth.clientId,
+ scopes: oauth.scopes,
+ },
+ }),
+ ),
+ ).toThrow(/deviceAuthorizationUrl/);
});
it('扩展参数不能覆盖 OAuth 标准字段', () => {
@@ -255,10 +344,16 @@ describe('BUNDLED_CATALOG 首批预设自检', () => {
expect(sanitizePresets(presets)).toHaveLength(presets.length);
});
- it('内置预设 baseUrl 均为 https', () => {
+ it('内置预设仅允许 https;明确无鉴权且可编辑的回环代理可使用 http', () => {
for (const p of BUNDLED_CATALOG.presets ?? []) {
for (const rt of Object.values(p.runtimes)) {
- expect(rt.baseUrl.startsWith('https://')).toBe(true);
+ const url = new URL(rt.baseUrl);
+ const secureLocal =
+ p.authMethod === 'none'
+ && rt.baseUrlEditable === true
+ && url.protocol === 'http:'
+ && (url.hostname === '127.0.0.1' || url.hostname === 'localhost');
+ expect(url.protocol === 'https:' || secureLocal, `${p.id}: ${rt.baseUrl}`).toBe(true);
}
}
});
@@ -289,3 +384,80 @@ describe('MiniMax OpenAI Responses 预设契约 (issue #345)', () => {
});
});
});
+
+describe('官方渠道预设契约', () => {
+ const preset = (id: string) =>
+ BUNDLED_CATALOG.presets?.find((candidate) => candidate.id === id);
+
+ it('LiteLLM 是可编辑回环端点,并明确走无鉴权而非复用 CLI 订阅凭证', () => {
+ const liteLlm = preset('litellm');
+ expect(liteLlm?.authMethod).toBe('none');
+ expect(liteLlm?.runtimes.codex).toEqual(expect.objectContaining({
+ baseUrl: 'http://127.0.0.1:4000/v1',
+ baseUrlEditable: true,
+ models: [],
+ }));
+ });
+
+ it('LongCat 同时提供 Anthropic Messages 与官方 Codex Responses 端点', () => {
+ expect(preset('longcat')?.runtimes).toEqual({
+ 'claude-code': {
+ baseUrl: 'https://api.longcat.chat/anthropic',
+ modelsUrl: 'https://api.longcat.chat/openai/v1/models',
+ models: [{ id: 'LongCat-2.0', name: 'LongCat 2.0', contextWindow: 1_000_000 }],
+ },
+ codex: {
+ baseUrl: 'https://api.longcat.chat/openai/v1',
+ modelsUrl: 'https://api.longcat.chat/openai/v1/models',
+ models: [{ id: 'LongCat-2.0', name: 'LongCat 2.0', contextWindow: 1_000_000 }],
+ },
+ });
+ });
+
+ it.each([
+ ['zhipu-coding-plan-cn', 'https://open.bigmodel.cn/api/coding/paas/v4'],
+ ['zai-coding-plan-global', 'https://api.z.ai/api/coding/paas/v4'],
+ ['volcengine-coding-plan', 'https://ark.cn-beijing.volces.com/api/coding/v3'],
+ ['tencentcloud-coding-plan', 'https://api.lkeap.cloud.tencent.com/coding/v3'],
+ ])('%s 使用专属 Coding Plan OpenAI Chat 端点', (id, baseUrl) => {
+ expect(preset(id)?.runtimes.codex).toEqual(expect.objectContaining({
+ baseUrl,
+ wireProtocol: 'openai-chat',
+ }));
+ });
+
+ it('小米按量与 Token Plan 凭证不会混用端点', () => {
+ expect(preset('xiaomi-mimo-api-cn')?.runtimes.codex?.baseUrl)
+ .toBe('https://api.xiaomimimo.com/v1');
+ expect(preset('xiaomi-mimo-token-plan-cn')?.runtimes.codex?.baseUrl)
+ .toBe('https://token-plan-cn.xiaomimimo.com/v1');
+ });
+
+ it('OpenCode Go 按官方逐模型协议拆成 Claude Messages 与 Codex Chat 两个 runtime', () => {
+ const go = preset('opencode-go');
+ expect(go?.runtimes['claude-code']?.models.map((model) => model.id)).toContain('minimax-m3');
+ expect(go?.runtimes.codex?.models.map((model) => model.id)).toContain('glm-5.2');
+ expect(go?.runtimes.codex?.wireProtocol).toBe('openai-chat');
+ expect(go?.runtimes['claude-code']?.modelsUrl)
+ .toBe('https://opencode.ai/zen/go/v1/models');
+ });
+
+ it('Vercel AI Gateway 使用 Messages 与 Responses 原生端点', () => {
+ const vercel = preset('vercel-ai-gateway');
+ expect(vercel?.runtimes['claude-code']?.baseUrl).toBe('https://ai-gateway.vercel.sh');
+ expect(vercel?.runtimes.codex?.baseUrl).toBe('https://ai-gateway.vercel.sh/v1');
+ expect(vercel?.runtimes.codex?.wireProtocol).toBeUndefined();
+ });
+
+ it('Google Gemini API 走公开 OpenAI Chat 兼容端点,不依赖 Gemini CLI 私有接口', () => {
+ const gemini = preset('google-gemini-api');
+ expect(gemini?.runtimes['claude-code']).toBeUndefined();
+ expect(gemini?.runtimes.codex).toEqual(expect.objectContaining({
+ baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',
+ wireProtocol: 'openai-chat',
+ modelsUrl: 'https://generativelanguage.googleapis.com/v1beta/openai/models',
+ }));
+ expect(gemini?.runtimes.codex?.models.map((model) => model.id))
+ .toContain('gemini-3.6-flash');
+ });
+});
diff --git a/packages/model-providers/src/__tests__/provider-url.test.ts b/packages/model-providers/src/__tests__/provider-url.test.ts
index f3da202fdb..147027bdd2 100644
--- a/packages/model-providers/src/__tests__/provider-url.test.ts
+++ b/packages/model-providers/src/__tests__/provider-url.test.ts
@@ -1,6 +1,10 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
-import { appendProviderRequestPath, isProviderRequestPath } from '../provider-url.js';
+import {
+ appendProviderRequestPath,
+ isLoopbackProviderUrl,
+ isProviderRequestPath,
+} from '../provider-url.js';
describe('isProviderRequestPath', () => {
it('accepts an encoded same-origin path with query parameters', () => {
@@ -22,6 +26,15 @@ describe('isProviderRequestPath', () => {
'/infer\u007fmode',
'/infer\u0085mode',
'/café',
+ '/a"b',
+ "/a'b",
+ '/a<b',
+ '/a>b',
+ '/a^b',
+ '/a`b',
+ '/a{b',
+ '/a}b',
+ '/a|b',
'/foo%2',
'/%ZZ',
'/./infer',
@@ -30,6 +43,10 @@ describe('isProviderRequestPath', () => {
'/%2E%2e/infer',
'/.%2e/infer',
'/%2e./infer',
+ '/%2e%2e%2fadmin',
+ '/%2E%2E%5Cadmin',
+ '/safe%2Fpart',
+ '/safe%5cpart',
'/模型',
'/v1\\messages',
'responses',
@@ -40,6 +57,43 @@ describe('isProviderRequestPath', () => {
it('does not treat dot-like query values as path segments', () => {
expect(isProviderRequestPath('/infer?next=../other')).toBe(true);
expect(isProviderRequestPath('/infer?next=%2e%2e')).toBe(true);
+ expect(isProviderRequestPath('/infer?next=%2fadmin')).toBe(true);
+ });
+});
+
+describe('isLoopbackProviderUrl', () => {
+ it.each([
+ 'http://localhost:4000/v1',
+ 'https://127.0.0.1/v1',
+ 'http://127.42.0.7:4000/v1',
+ 'http://[::1]:4000/v1',
+ ])('accepts a loopback provider URL: %s', (url) => {
+ expect(isLoopbackProviderUrl(url)).toBe(true);
+ });
+
+ it('accepts runtimes that serialize the IPv6 loopback hostname without brackets', () => {
+ const NativeUrl = URL;
+ vi.stubGlobal('URL', class extends NativeUrl {
+ override get hostname(): string {
+ const hostname = super.hostname;
+ return hostname === '[::1]' ? '::1' : hostname;
+ }
+ });
+ try {
+ expect(isLoopbackProviderUrl('http://[::1]:4000/v1')).toBe(true);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it.each([
+ 'https://litellm.example/v1',
+ 'http://localhost.evil.example/v1',
+ 'http://128.0.0.1/v1',
+ 'http://user:pass@localhost:4000/v1',
+ 'ftp://127.0.0.1/v1',
+ ])('rejects a non-loopback or unsafe provider URL: %s', (url) => {
+ expect(isLoopbackProviderUrl(url)).toBe(false);
});
});
diff --git a/packages/model-providers/src/__tests__/providerBranding.test.ts b/packages/model-providers/src/__tests__/providerBranding.test.ts
index bcdcd24f04..d345fbaa75 100644
--- a/packages/model-providers/src/__tests__/providerBranding.test.ts
+++ b/packages/model-providers/src/__tests__/providerBranding.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import { BUNDLED_CATALOG } from '../catalog.js';
import {
hasProviderLogo,
+ isProviderLogoKind,
PROVIDER_LOGO_PATHS,
resolveProviderLogoKind,
} from '../providerBranding.js';
@@ -29,8 +30,29 @@ describe('provider branding', () => {
expect(PROVIDER_LOGO_PATHS.xai).not.toBe(PROVIDER_LOGO_PATHS.openrouter);
});
+ it('only infers Vercel branding from the exact AI Gateway host', () => {
+ expect(resolveProviderLogoKind('renamed', {
+ codex: { upstream: 'https://ai-gateway.vercel.sh/v1' },
+ })).toBe('vercel');
+ expect(resolveProviderLogoKind('renamed', {
+ codex: { upstream: 'https://my-openrouter-proxy.vercel.sh/v1' },
+ })).toBeNull();
+ expect(resolveProviderLogoKind('renamed', {
+ codex: { upstream: 'https://tenant.ai-gateway.vercel.sh/v1' },
+ })).toBeNull();
+ });
+
+ it('guards runtime logo values before indexing shared paths', () => {
+ expect(isProviderLogoKind('vercel')).toBe(true);
+ expect(isProviderLogoKind('future-brand')).toBe(false);
+ expect(isProviderLogoKind(null)).toBe(false);
+ });
+
it('keeps preset branding after a user-facing provider id changes', () => {
for (const preset of BUNDLED_CATALOG.presets ?? []) {
+ // Self-hosted presets can be moved to any host; after the id is renamed there is
+ // intentionally no trustworthy hostname from which to infer the vendor mark.
+ if (Object.values(preset.runtimes).some((runtime) => runtime?.baseUrlEditable)) continue;
const routing: Record<string, { upstream: string }> = {};
for (const [agent, runtime] of Object.entries(preset.runtimes)) {
if (runtime) routing[agent] = { upstream: runtime.baseUrl };
diff --git a/packages/model-providers/src/__tests__/sections.test.ts b/packages/model-providers/src/__tests__/sections.test.ts
index 06dd030059..90dfd339b5 100644
--- a/packages/model-providers/src/__tests__/sections.test.ts
+++ b/packages/model-providers/src/__tests__/sections.test.ts
@@ -32,7 +32,12 @@ function provider(id: string, name: string, ccModels: CatalogModel[]): ProviderV
source: id === 'xd' || id === 'anthropic' || id === 'openai' ? 'builtin' : 'user',
agents: ['claude-code'],
auth: { method: 'managed' },
- routing: {},
+ routing: {
+ 'claude-code': {
+ upstream: 'https://example.test',
+ authStrategy: 'gateway-key',
+ },
+ },
models: { 'claude-code': ccModels },
connected: true,
};
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index e4d0746226..6587819533 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -335,6 +335,32 @@ describe('registry visibility & sources(运行时注入 fixture)', () => {
expect(connectedProvidersForAgent(views, 'codex').map((p) => p.id)).toEqual(['xd']);
});
+ it('agent selectors and model sources exclude disabled runtimes', () => {
+ const catalog = runtimeCatalog();
+ const xd = catalog.providers.find((provider) => provider.id === 'xd')!;
+ xd.routing.codex = { ...xd.routing.codex!, disabled: true };
+ const disabledViews = buildRegistry(catalog, { xd: true });
+
+ expect(providersForAgent(disabledViews, 'codex').map((provider) => provider.id))
+ .not.toContain('xd');
+ expect(connectedProvidersForAgent(disabledViews, 'codex')).toEqual([]);
+ expect(sourcesForModel(disabledViews, 'gpt-5.5', 'codex')).toEqual([]);
+ expect(connectedProvidersForAgent(disabledViews, 'claude-code').map((provider) => provider.id))
+ .toEqual(['xd']);
+ });
+
+ it('agent selectors and model sources exclude a declared agent with no routing descriptor', () => {
+ const catalog = runtimeCatalog();
+ const xd = catalog.providers.find((provider) => provider.id === 'xd')!;
+ delete xd.routing.codex;
+ const missingRouteViews = buildRegistry(catalog, { xd: true });
+
+ expect(providersForAgent(missingRouteViews, 'codex').map((provider) => provider.id))
+ .not.toContain('xd');
+ expect(connectedProvidersForAgent(missingRouteViews, 'codex')).toEqual([]);
+ expect(sourcesForModel(missingRouteViews, 'gpt-5.5', 'codex')).toEqual([]);
+ });
+
it('providerOffersModel / getModel (agent-scoped)', () => {
const xd = views.find((p) => p.id === 'xd')!;
expect(providerOffersModel(xd, 'gpt-5.5', 'codex')).toBe(true);
@@ -426,6 +452,21 @@ describe('resolveRoute(运行时注入 fixture)', () => {
expect(resolveRoute(views, 'nope', 'claude-opus-4-8', 'claude-code')).toBeNull();
});
+ it('rejects a disabled route even when provider, model, and agent match', () => {
+ const disabledViews = views.map((provider) =>
+ provider.id === 'xai'
+ ? {
+ ...provider,
+ routing: {
+ ...provider.routing,
+ codex: { ...provider.routing.codex!, disabled: true },
+ },
+ }
+ : provider,
+ );
+ expect(resolveRoute(disabledViews, 'xai', 'xai/grok-4.3', 'codex')).toBeNull();
+ });
+
it('动态供应商未注入清单时不解析路由(无可用性证明不路由)', () => {
const bare = buildRegistry(BUNDLED_CATALOG, { xd: true, anthropic: true, openai: true, xai: true });
expect(resolveRoute(bare, 'anthropic', 'claude-opus-4-8', 'claude-code')).toBeNull();
diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.ts
index 533686a476..dfb33892a0 100644
--- a/packages/model-providers/src/__tests__/user-provider.test.ts
+++ b/packages/model-providers/src/__tests__/user-provider.test.ts
@@ -176,6 +176,29 @@ describe('buildUserProvider (per-runtime)', () => {
expect(p.auth).toEqual({ method: 'none' });
expect(p.access).toEqual({ kind: 'api' });
expect(p.routing.codex?.authStrategy).toBe('none');
+ expect(p.routing.codex?.disabled).toBeUndefined();
+ });
+
+ it('keeps a legacy remote no-auth runtime editable but disables its route', () => {
+ const p = buildUserProvider({
+ ...codexOnly,
+ id: 'legacy-remote-no-auth',
+ auth: { method: 'none' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://remote.example/v1',
+ models: [{ id: 'legacy-model', name: 'Legacy model' }],
+ },
+ },
+ });
+
+ expect(p.agents).toEqual(['codex']);
+ expect(p.routing.codex).toMatchObject({
+ upstream: 'https://remote.example/v1',
+ authStrategy: 'none',
+ disabled: true,
+ });
+ expect(p.models.codex?.map((model) => model.id)).toEqual(['legacy-model']);
});
it('supports two runtimes with independent baseUrl + models, stable agent order', () => {
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index 3b470db374..1d9f0bb4ee 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -467,7 +467,9 @@ export function presetDisplayName(
/** 预设的厂商分组键:id 去掉区域后缀(`zhipu-glm-cn`/`zhipu-glm-global` → `zhipu-glm`)。 */
function presetVendorKey(p: ProviderPreset): string {
- return p.id.replace(/-(cn|global)$/, '');
+ const key = p.id.replace(/-(cn|global)$/, '');
+ // 智谱国内品牌沿用 zhipu,海外品牌使用 zai,但仍是同一厂商的区域渠道。
+ return key === 'zai-coding-plan' ? 'zhipu-coding-plan' : key;
}
/**
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index d1d445ddd2..3d5669eb33 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -33,7 +33,11 @@ export type {
export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForLocale } from './catalog.js';
export { buildUserProvider, DEFAULT_CUSTOM_CONTEXT_WINDOW } from './user-provider.js';
-export { appendProviderRequestPath, isProviderRequestPath } from './provider-url.js';
+export {
+ appendProviderRequestPath,
+ isLoopbackProviderUrl,
+ isProviderRequestPath,
+} from './provider-url.js';
export { findReservedOAuthExtraParam } from './provider-oauth.js';
export {
diff --git a/packages/model-providers/src/provider-url.ts b/packages/model-providers/src/provider-url.ts
index 8bc8c98e79..e285ba2aff 100644
--- a/packages/model-providers/src/provider-url.ts
+++ b/packages/model-providers/src/provider-url.ts
@@ -9,6 +9,7 @@ export function isProviderRequestPath(value: unknown): value is string {
if (typeof value !== 'string') return false;
const queryIndex = value.indexOf('?');
const path = queryIndex === -1 ? value : value.slice(0, queryIndex);
+ const hasEncodedPathSeparator = /%(?:2f|5c)/i.test(path);
const hasDotSegment = path
.split('/')
.some((segment) => {
@@ -23,11 +24,43 @@ export function isProviderRequestPath(value: unknown): value is string {
&& !value.includes('#')
&& !value.includes('\\')
&& !/[^\u0021-\u007e]/.test(value)
+ // Keep byte-for-byte parity between WHATWG URL setters and transparent http.request paths.
+ // Characters outside RFC 3986 path/query delimiters must be percent-encoded by the caller.
+ && /^\/[A-Za-z0-9\-._~%!$&()*+,;=:@/?]*$/.test(value)
&& !/%(?![0-9A-Fa-f]{2})/.test(value)
+ && !hasEncodedPathSeparator
&& !hasDotSegment
);
}
+/**
+ * 无鉴权本机代理的 URL 边界。只接受真正的 loopback 主机,避免把 `auth:none`
+ * 配置改成远端地址后让应用静默向第三方发送提示词。
+ */
+export function isLoopbackProviderUrl(value: unknown): value is string {
+ if (typeof value !== 'string' || value.length === 0) return false;
+ try {
+ const url = new URL(value);
+ if (
+ (url.protocol !== 'http:' && url.protocol !== 'https:')
+ || url.username
+ || url.password
+ ) {
+ return false;
+ }
+ const hostname = url.hostname.toLowerCase();
+ if (hostname === 'localhost' || hostname === '[::1]' || hostname === '::1') return true;
+ const octets = hostname.split('.');
+ return (
+ octets.length === 4
+ && octets[0] === '127'
+ && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
+ );
+ } catch {
+ return false;
+ }
+}
+
/**
* 把已验证的精确推理路径追加到 base URL,同时保留 base query。
* requestPath 自带的 query 追加在 base query 后,fragment 一律不进入请求。
diff --git a/packages/model-providers/src/providerBranding.ts b/packages/model-providers/src/providerBranding.ts
index 279308c1b3..0e60a5f8f3 100644
--- a/packages/model-providers/src/providerBranding.ts
+++ b/packages/model-providers/src/providerBranding.ts
@@ -2,10 +2,25 @@
* Provider branding is pure catalog metadata shared by desktop and mobile.
*
* Paths use a 24px viewBox. Simple Icons 16.27.0 paths are CC0-1.0; the xAI
- * and Zhipu Mono paths are from Lobe Icons 5.14.0 under MIT.
+ * and Zhipu Mono paths are from Lobe Icons 5.14.0 under MIT. The LiteLLM
+ * mascot silhouette is adapted from litellm-docs/static/img/logo.svg under MIT.
*/
export const PROVIDER_LOGO_PATHS = {
+ google:
+ 'M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 01-3.81-2.58 12.3 12.3 0 01-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 01-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81',
+ litellm:
+ 'M13.5576 6.8851 L21.96 6.36 V5.16 c0 -1.3255 -1.0745 -2.4 -2.4 -2.4 H8.76 l-0.3 -0.5196 c-0.1334 -0.231 -0.4667 -0.231 -0.6 0 L7.56 2.76 l-0.3 -0.5196 c-0.1333 -0.231 -0.4667 -0.231 -0.6 0 L6.36 2.76 l-0.3 -0.5196 c-0.1333 -0.231 -0.4667 -0.231 -0.6 0 L5.16 2.76 c-0.0026 0 -0.005 0.0004 -0.0078 0.0004 l-0.497 -0.4969 c-0.1884 -0.1885 -0.5102 -0.1024 -0.5794 0.1553 l-0.1643 0.6125 -0.623 -0.167 c-0.2578 -0.069 -0.4933 0.1667 -0.4242 0.4243 l0.1668 0.6232 -0.6122 0.164 c-0.2578 0.0691 -0.344 0.3911 -0.1555 0.5796 l0.497 0.497 c0 0.0025 -0.0004 0.005 -0.0004 0.0077 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 6.36 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 7.56 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 8.76 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 9.96 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 11.16 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 12.36 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 13.56 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 14.76 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 15.96 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 17.16 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 18.36 l-0.5196 0.3 c-0.231 0.1333 -0.231 0.4667 0 0.6 L2.76 19.56 c0 1.3255 1.0745 2.4 2.4 2.4 h14.4 c1.3255 0 2.4 -1.0745 2.4 -2.4 V9.96 l-8.4024 -0.5251 A1.2774 1.2774 0 0 1 12.36 8.16 c0 -0.6745 0.5244 -1.2328 1.1976 -1.2749',
+ longcat:
+ 'M.507 19.883a.507.507 0 01-.489-.642L4.29 3.745a1.013 1.013 0 011.533-.578l5.622 3.687a1.013 1.013 0 001.11 0L18.2 3.165a1.013 1.013 0 011.532.58l4.25 15.497a.506.506 0 01-.49.64H18.07a6.297 6.297 0 001.53-4.115v-.177a6.09 6.09 0 00-1.513-4.017l-.697-3.495a.438.438 0 00-.694-.266L14.07 9.781a.748.748 0 01-.654.121 5.156 5.156 0 00-2.833 0 .746.746 0 01-.653-.121L7.302 7.81a.435.435 0 00-.688.269l-.675 3.652a5.36 5.36 0 00-1.539 3.76v.333c0 1.474.527 2.9 1.488 4.02l.032.038H.507z M9.213 16.843h1.52v-3.546h-1.29l-.23 3.546zm5.573 0h-1.52v-3.546h1.29l.23 3.546z',
+ opencode: 'M16 6H8v12h8V6zm4 16H4V2h16v20z',
+ tencentcloud:
+ 'M20.0483 17.1416c-.3538.3498-1.0613.8745-2.2995.8745H10.143c2.2994-2.1863 4.2451-4.0229 4.422-4.1978.1769-.1749.6191-.6122 1.0613-.962.8844-.7871 1.5919-.8746 2.2109-.8746.8844 0 1.5919.3499 2.2111.8746 1.2381 1.1369 1.2381 3.1484 0 4.2853zm1.5035-5.6846c-.8844-.962-2.211-1.5742-3.6261-1.5742-1.2382 0-2.2994.4373-3.2723 1.1369-.3537.3498-.8844.6997-1.3266 1.2244-.3537.3498-7.9596 7.696-7.9596 7.696.4422.0875.9728.0875 1.415.0875h9.64c.7076 0 1.2382 0 1.7688-.0875 1.1498-.0874 2.2995-.5247 3.2723-1.3992 2.0342-1.9241 2.0342-5.1599.0885-7.0843z M9.1701 10.9323c-.9728-.6997-1.9457-1.0495-3.0954-1.0495-1.4151 0-2.7417.6122-3.6261 1.5742-1.9456 2.0115-1.9456 5.1598.0885 7.1713.8844.7871 1.7688 1.2244 2.8301 1.3118l2.0341-1.924c-.3538 0-.796.0-1.1497.0-1.1498-.0874-1.8573-.4372-2.2995-.8745-1.2381-1.2244-1.2381-3.1484-.0884-4.3728.6191-.6122 1.3266-.8745 2.211-.8745.5306 0 1.3266.0874 2.1226.8745.3538.3498 1.3266 1.0495 1.6803 1.3993h.0885l1.3266-1.3118v-.0875c-.6191-.6122-1.5919-1.3993-2.1226-1.8365z M18.4564 8.7454c-.9728-2.6237-3.5376-4.4602-6.4561-4.4602-3.4492 0-6.1909 2.5362-6.7215 5.6845.2653 0 .5306-.0874.8844-.0874s.7959.0874 1.1497.0874c.4422-2.1863 2.3879-3.7605 4.6874-3.7605 1.9457 0 3.626 1.1369 4.422 2.7986 0 0 .0884.0874.0884 0 .6191-.0875 1.3266-.2624 1.9457-.2624z',
+ vercel: 'M12 0l12 20.785H0L12 0z',
+ volcengine:
+ 'M7.29 5.36L3.148 21.737a.215.215 0 00.203.261h8.29a.214.214 0 00.215-.261L7.7 5.359a.214.214 0 00-.41 0z M4.553 16.18l-1.406 5.558a.214.214 0 00.203.261h2.42-4.551a.214.214 0 01-.214-.26l2.275-8.961a.214.214 0 01.409 0l.864 3.402z M14.44.15a.214.214 0 00-.41 0L8.366 21.739A.214.214 0 008.58 22H19.9a.214.214 0 00.215-.261L14.44.151z M16.694 22h3.207a.215.215 0 00.214-.262l-1.839-6.993 1.164-4.592a.214.214 0 01.411 0l2.951 11.586a.214.214 0 01-.214.261h-5.894z M10.278 7.741L6.685 21.736A.214.214 0 006.899 22h7.17a.216.216 0 00.214-.166.216.216 0 000-.098L10.687 7.742a.214.214 0 00-.409 0z',
+ xiaomimimo:
+ 'M.958 15.936a.459.459 0 01.459.44v2.729a.46.46 0 01-.918 0v-2.729a.459.459 0 01.459-.44zm4.814-2.035a.46.46 0 01.553.45v4.754a.458.458 0 11-.918 0V15.48L3.74 17.202a.462.462 0 01-.655.016.462.462 0 01-.065-.082L.628 14.67a.459.459 0 01.658-.637l2.124 2.187 2.127-2.188a.46.46 0 01.235-.13zm2.068.004a.46.46 0 01.458.445v4.755a.46.46 0 01-.458.458.459.459 0 01-.458-.458V14.35a.459.459 0 01.458-.445zm1.973 2.014a.46.46 0 01.46.457v2.729a.46.46 0 01-.784.324.46.46 0 01-.134-.324v-2.729a.46.46 0 01.458-.458zm.002-2.045a.458.458 0 01.328.157l2.127 2.19 2.125-2.19a.459.459 0 01.784.318v4.756a.46.46 0 01-.455.458.46.46 0 01-.458-.458V15.48l-1.667 1.723a.46.46 0 01-.65.008l-.005-.005-.004-.003-2.455-2.534a.46.46 0 01-.008-.667.461.461 0 01.338-.128zm6.797 1.206a.46.46 0 01.53.651A1.966 1.966 0 0019.81 18.4a.462.462 0 01.623.18.46.46 0 01-.181.624 2.863 2.863 0 01-1.38.353l-.142-.004a2.88 2.88 0 01-2.393-4.263.461.461 0 01.274-.21zm.864-.931a2.884 2.884 0 013.915 3.914.46.46 0 01-.402.24l-.057-.004a.458.458 0 01-.164-.055.46.46 0 01-.182-.622 1.967 1.967 0 00-2.669-2.67.459.459 0 11-.441-.803zM9.59 6.368c1.481 0 1.696 1.202 1.696 1.654v2.648h-.917v-.432c-.26.346-.792.535-1.36.535-.133 0-1.289-.03-1.384-1.136-.082-.932.675-1.61 2.053-1.61h.691c0-.563-.367-.886-.983-.886-.44.013-.864.174-1.2.458l-.36-.664c.484-.379 1.012-.567 1.764-.567zm4.427.1c1.263 0 2.082.97 2.083 2.15 0 1.181-.824 2.154-2.083 2.154-1.26 0-2.084-.972-2.084-2.152 0-1.18.82-2.153 2.084-2.153zm6.801.015c.68 0 1.202.465 1.197 1.548v2.642H21.1V8.29c0-.312-.002-.98-.63-.98s-.628.667-.628.838v2.524h-.89V8.148c0-.17-.001-.838-.63-.838-.628 0-.628.668-.628.98v2.383h-.917v-4.03h.917V7a1.22 1.22 0 01.947-.516c.398 0 .76.193.982.686a1.321 1.321 0 011.195-.686zm-18.093.872l1.457-1.772H5.32L3.311 8.07l2.14 2.602H4.24L2.725 8.796 1.21 10.672H0L2.138 8.07.13 5.583h1.138l1.458 1.772zm4.149 3.317h-.916V6.644h.916v4.028zm16.99 0h-.916V6.644h.916v4.028zM9.925 8.71c-1.055 0-1.359.412-1.326.742.032.329.324.537.757.537a1.013 1.013 0 001.014-.968l.002-.31h-.447zM14.018 7.3c-.663 0-1.184.487-1.184 1.32 0 .832.52 1.32 1.184 1.32.662 0 1.182-.49 1.182-1.32 0-.832-.52-1.32-1.182-1.32z',
xai: 'M6.469 8.776L16.512 23h-4.464L2.005 8.776H6.47zm-.004 7.9l2.233 3.164L6.467 23H2l4.465-6.324zM22 2.582V23h-3.659V7.764L22 2.582zM22 1l-9.952 14.095-2.233-3.163L17.533 1H22z',
openrouter:
'M16.778 1.844v1.919q-.569-.026-1.138-.032-.708-.008-1.415.037c-1.93.126-4.023.728-6.149 2.237-2.911 2.066-2.731 1.95-4.14 2.75-.396.223-1.342.574-2.185.798-.841.225-1.753.333-1.751.333v4.229s.768.108 1.61.333c.842.224 1.789.575 2.185.799 1.41.798 1.228.683 4.14 2.75 2.126 1.509 4.22 2.11 6.148 2.236.88.058 1.716.041 2.555.005v1.918l7.222-4.168-7.222-4.17v2.176c-.86.038-1.611.065-2.278.021-1.364-.09-2.417-.357-3.979-1.465-2.244-1.593-2.866-2.027-3.68-2.508.889-.518 1.449-.906 3.822-2.59 1.56-1.109 2.614-1.377 3.978-1.466.667-.044 1.418-.017 2.278.02v2.176L24 6.014Z',
@@ -24,6 +39,19 @@ export const PROVIDER_LOGO_PATHS = {
export type ProviderLogoKind = keyof typeof PROVIDER_LOGO_PATHS | 'anthropic' | 'openai' | 'xd';
+/** Device-link 等运行时边界不能信任静态 union;未知未来值应安全回退。 */
+export function isProviderLogoKind(value: unknown): value is ProviderLogoKind {
+ return (
+ value === 'anthropic'
+ || value === 'openai'
+ || value === 'xd'
+ || (
+ typeof value === 'string'
+ && Object.prototype.hasOwnProperty.call(PROVIDER_LOGO_PATHS, value)
+ )
+ );
+}
+
export type ProviderLogoRouting = Readonly<
Record<string, { readonly upstream: string } | undefined>
>;
@@ -38,12 +66,24 @@ const PROVIDER_LOGO_KIND_BY_ID: Readonly<Record<string, ProviderLogoKind>> = {
deepseek: 'deepseek',
'zhipu-glm-cn': 'zhipu',
'zhipu-glm-global': 'zai',
+ 'zhipu-coding-plan-cn': 'zhipu',
+ 'zai-coding-plan-global': 'zai',
'moonshot-kimi-cn': 'moonshot',
'moonshot-kimi-global': 'moonshot',
'moonshot-kimi-code': 'moonshot',
'minimax-cn': 'minimax',
'minimax-global': 'minimax',
'aliyun-bailian-coding': 'alibaba',
+ 'google-gemini-api': 'google',
+ litellm: 'litellm',
+ 'litellm-proxy': 'litellm',
+ longcat: 'longcat',
+ 'xiaomi-mimo-api-cn': 'xiaomimimo',
+ 'xiaomi-mimo-token-plan-cn': 'xiaomimimo',
+ 'volcengine-coding-plan': 'volcengine',
+ 'tencentcloud-coding-plan': 'tencentcloud',
+ 'opencode-go': 'opencode',
+ 'vercel-ai-gateway': 'vercel',
};
/** Renamed providers retain stable upstream hosts, matched only on DNS boundaries. */
@@ -61,9 +101,17 @@ const PROVIDER_LOGO_KIND_BY_HOST: readonly (readonly [string, ProviderLogoKind])
['minimaxi.com', 'minimax'],
['minimax.io', 'minimax'],
['dashscope.aliyuncs.com', 'alibaba'],
+ ['generativelanguage.googleapis.com', 'google'],
+ ['longcat.chat', 'longcat'],
+ ['xiaomimimo.com', 'xiaomimimo'],
+ ['volces.com', 'volcengine'],
+ ['cloud.tencent.com', 'tencentcloud'],
+ ['opencode.ai', 'opencode'],
+ ['ai-gateway.vercel.sh', 'vercel'],
];
function hostMatches(hostname: string, brandHost: string): boolean {
+ if (brandHost === 'ai-gateway.vercel.sh') return hostname === brandHost;
return hostname === brandHost || hostname.endsWith(`.${brandHost}`);
}
diff --git a/packages/model-providers/src/registry.ts b/packages/model-providers/src/registry.ts
index 127a39357d..a9b214631b 100644
--- a/packages/model-providers/src/registry.ts
+++ b/packages/model-providers/src/registry.ts
@@ -123,14 +123,20 @@ export function buildRegistry(
});
}
+/** 该供应商的指定 runtime 是否可参与选择 / 路由。 */
+function hasEnabledAgentRuntime(provider: Provider, agent: AgentKind): boolean {
+ const routing = provider.routing?.[agent];
+ return provider.agents.includes(agent) && routing !== undefined && routing.disabled !== true;
+}
+
/** 该 agent 兼容的所有供应商(不论连接与否)—— 供应商页「可用」列表用。 */
export function providersForAgent(views: ProviderView[], agent: AgentKind): ProviderView[] {
- return views.filter((p) => p.agents.includes(agent));
+ return views.filter((p) => hasEnabledAgentRuntime(p, agent));
}
/** 该 agent 已连接的供应商 —— 模型选择器「来源栏」用。 */
export function connectedProvidersForAgent(views: ProviderView[], agent: AgentKind): ProviderView[] {
- return views.filter((p) => p.connected && p.agents.includes(agent));
+ return views.filter((p) => p.connected && hasEnabledAgentRuntime(p, agent));
}
/** 该供应商是否在某 agent 下提供某 model id。 */
@@ -162,7 +168,7 @@ export function sourcesForModel(
return views.filter(
(p) =>
(!onlyConnected || p.connected) &&
- p.agents.includes(agent) &&
+ hasEnabledAgentRuntime(p, agent) &&
providerOffersModel(p, modelId, agent),
);
}
@@ -260,6 +266,6 @@ export function resolveRoute(
const model = getModel(provider, modelId, agent);
if (!model) return null;
const routing = provider.routing[agent];
- if (!routing) return null;
+ if (!routing || routing.disabled) return null;
return { provider, model, routing };
}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 1a055d99ec..5af279a943 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -151,6 +151,11 @@ export interface RoutingDescriptor {
requestPath?: string;
/** 鉴权策略(见 AuthStrategy)。 */
authStrategy: AuthStrategy;
+ /**
+ * 配置保留用于展示/修复,但运行时不得向该上游路由。用于把升级前不再满足安全边界的
+ * 历史配置留在设置页,同时让所有路由解析 fail closed。
+ */
+ disabled?: boolean;
/** 转发上游前还原 model id(如剥掉 `codex/` 前缀)。缺省 = 原样。 */
modelIdRewrite?: { stripPrefix: string };
/** 转发上游前需删除的请求头(如 gateway 路由删 `anthropic-beta`)。 */
diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.ts
index 0e9f1e57e9..5748e258cf 100644
--- a/packages/model-providers/src/user-provider.ts
+++ b/packages/model-providers/src/user-provider.ts
@@ -20,6 +20,7 @@ import type {
ProviderRuntimeModelConfig,
RoutingDescriptor,
} from './types.js';
+import { isLoopbackProviderUrl } from './provider-url.js';
/** 自定义模型缺省上下文窗口(用户不填元数据时的保守默认,仅用于展示)。 */
export const DEFAULT_CUSTOM_CONTEXT_WINDOW = 200_000;
@@ -79,6 +80,11 @@ function toRouting(
const r: RoutingDescriptor = {
upstream: baseUrl,
authStrategy: strategy,
+ ...(strategy === 'none'
+ && (!isLoopbackProviderUrl(baseUrl)
+ || (modelsUrl !== undefined && !isLoopbackProviderUrl(modelsUrl)))
+ ? { disabled: true }
+ : {}),
...(requestPath ? { requestPath } : {}),
...(wireProtocol && wireProtocol !== defaultWireProtocol(agent) ? { wireProtocol } : {}),
};
diff --git a/packages/responses-chat-bridge/src/__tests__/handler.test.ts b/packages/responses-chat-bridge/src/__tests__/handler.test.ts
index 373ba8fa30..2a5de4afaf 100644
--- a/packages/responses-chat-bridge/src/__tests__/handler.test.ts
+++ b/packages/responses-chat-bridge/src/__tests__/handler.test.ts
@@ -81,13 +81,33 @@ describe('createResponsesChatHandler', () => {
) as typeof fetch;
const handler = createResponsesChatHandler({
upstreamBase: 'https://provider.example/gateway?tenant=acme',
- chatCompletionsPath: '/infer?stream=1',
+ chatCompletionsPath: '/infer?stream=1&next=%2fadmin',
buildHeaders: async () => ({}),
}, { fetchImpl });
const res = new FakeResponse();
await handler.handle({ parsedBody: { model: 'm', input: 'hi' }, res: res as never });
expect(fetchImpl).toHaveBeenCalledWith(
- 'https://provider.example/gateway/infer?tenant=acme&stream=1',
+ 'https://provider.example/gateway/infer?tenant=acme&stream=1&next=%2fadmin',
+ expect.anything(),
+ );
+ });
+
+ it('trims a long trailing-slash run in linear time before applying the chat path', async () => {
+ const fetchImpl = vi.fn(async () =>
+ streamResponse([
+ { id: 'chat_1', choices: [{ delta: {}, finish_reason: 'stop' }] },
+ ]),
+ ) as typeof fetch;
+ const handler = createResponsesChatHandler({
+ upstreamBase: `https://provider.example/v1${'/'.repeat(4_096)}`,
+ buildHeaders: async () => ({}),
+ }, { fetchImpl });
+ const res = new FakeResponse();
+
+ await handler.handle({ parsedBody: { model: 'm', input: 'hi' }, res: res as never });
+
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://provider.example/v1/chat/completions',
expect.anything(),
);
});
@@ -98,8 +118,14 @@ describe('createResponsesChatHandler', () => {
['a raw non-ASCII chat path', 'https://provider.example/v1', '/café'],
['a control character in the chat path', 'https://provider.example/v1', '/chat\u007f'],
['a backslash in the chat path', 'https://provider.example/v1', '/v1\\chat'],
+ ['a dot segment in the chat path', 'https://provider.example/v1', '/../admin'],
+ ['an encoded dot segment in the chat path', 'https://provider.example/v1', '/%2e%2e/admin'],
+ ['an encoded slash in the chat path', 'https://provider.example/v1', '/%2e%2e%2fadmin'],
+ ['an encoded backslash in the chat path', 'https://provider.example/v1', '/safe%5Cpart'],
+ ['a WHATWG-normalized character in the chat path', 'https://provider.example/v1', '/a<b'],
['an incomplete percent escape', 'https://provider.example/v1', '/chat%2'],
['an invalid percent escape', 'https://provider.example/v1', '/%ZZ'],
+ ['an oversized chat path', 'https://provider.example/v1', `/${'a'.repeat(2_048)}`],
])('reports %s as configuration failure before fetching', async (_case, upstreamBase, chatCompletionsPath) => {
const fetchImpl = vi.fn() as unknown as typeof fetch;
const buildHeaders = vi.fn(async () => ({ authorization: 'Bearer secret' }));
diff --git a/packages/responses-chat-bridge/src/handler.ts b/packages/responses-chat-bridge/src/handler.ts
index 9ea41a5b31..ea956ada9e 100644
--- a/packages/responses-chat-bridge/src/handler.ts
+++ b/packages/responses-chat-bridge/src/handler.ts
@@ -35,14 +35,33 @@ function writeSse(res: ServerResponse, event: unknown, sequenceNumber: number):
res.write(`event: ${event.type}\ndata: ${JSON.stringify(payload)}\n\n`);
}
+function trimTrailingSlashes(value: string): string {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 0x2f) end -= 1;
+ return value.slice(0, end);
+}
+
function joinUrl(base: string, path: string): string {
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
+ const queryIndex = normalizedPath.indexOf('?');
+ const pathname = queryIndex === -1 ? normalizedPath : normalizedPath.slice(0, queryIndex);
+ const hasEncodedPathSeparator = /%(?:2f|5c)/i.test(pathname);
+ const hasDotSegment = pathname
+ .split('/')
+ .some((segment) => {
+ const normalizedDots = segment.replace(/%2e/gi, '.');
+ return normalizedDots === '.' || normalizedDots === '..';
+ });
if (
- normalizedPath.startsWith('//')
+ normalizedPath.length > 2_048
+ || normalizedPath.startsWith('//')
|| normalizedPath.includes('#')
|| normalizedPath.includes('\\')
|| /[^\u0021-\u007e]/.test(normalizedPath)
+ || !/^\/[A-Za-z0-9\-._~%!$&()*+,;=:@/?]*$/.test(normalizedPath)
|| /%(?![0-9A-Fa-f]{2})/.test(normalizedPath)
+ || hasEncodedPathSeparator
+ || hasDotSegment
) {
throw new TypeError('invalid chat completions path');
}
@@ -54,11 +73,9 @@ function joinUrl(base: string, path: string): string {
) {
throw new TypeError('invalid upstream base URL');
}
- const queryIndex = normalizedPath.indexOf('?');
- const pathname = queryIndex === -1 ? normalizedPath : normalizedPath.slice(0, queryIndex);
const pathQuery = queryIndex === -1 ? '' : normalizedPath.slice(queryIndex + 1);
const baseQuery = url.search.slice(1);
- url.pathname = `${url.pathname.replace(/\/+$/, '')}${pathname}`;
+ url.pathname = `${trimTrailingSlashes(url.pathname)}${pathname}`;
url.search = [baseQuery, pathQuery].filter(Boolean).join('&');
url.hash = '';
return url.toString();
diff --git a/scripts/__tests__/third-party-notices.test.mjs b/scripts/__tests__/third-party-notices.test.mjs
index 7fe6b7ad84..a1a6c675b7 100644
--- a/scripts/__tests__/third-party-notices.test.mjs
+++ b/scripts/__tests__/third-party-notices.test.mjs
@@ -189,6 +189,17 @@ test("desktop resources include both open-source and restricted disclosures", ()
const desktopRestricted = read(
"apps/desktop/resources/THIRD-PARTY-RESTRICTED.txt",
);
+ const assertProviderBrandingOrder = (noticePath) => {
+ const notice = read(noticePath);
+ const liteLlmIndex = notice.indexOf("LiteLLM mascot SVG path (adapted)");
+ const lobeIndex = notice.indexOf("Lobe Icons SVG paths (vendored)");
+ assert.notEqual(liteLlmIndex, -1, `${noticePath} includes the LiteLLM notice`);
+ assert.notEqual(lobeIndex, -1, `${noticePath} includes the Lobe Icons notice`);
+ assert.ok(
+ liteLlmIndex < lobeIndex,
+ `${noticePath} keeps provider branding notices in canonical name order`,
+ );
+ };
assert.match(desktopRestricted, /Claude Code CLI@/);
assert.doesNotMatch(desktopRestricted, /WeChat OpenSDK/);
assert.match(
@@ -199,6 +210,34 @@ test("desktop resources include both open-source and restricted disclosures", ()
read("apps/desktop/resources/THIRD-PARTY-NOTICES.txt"),
/Lobe Icons SVG paths \(vendored\).*Copyright \(c\) 2023 LobeHub/s,
);
+ assert.match(
+ read("apps/desktop/resources/THIRD-PARTY-NOTICES.txt"),
+ /LiteLLM mascot SVG path \(adapted\).*Copyright \(c\) 2026 Berri AI/s,
+ );
+ assert.doesNotMatch(
+ read("apps/desktop/resources/THIRD-PARTY-NOTICES.txt"),
+ /LiteLLM mascot SVG path \(adapted\) adapted/,
+ );
+ assertProviderBrandingOrder(
+ "apps/desktop/resources/THIRD-PARTY-NOTICES.txt",
+ );
+ assertProviderBrandingOrder(
+ "docs/legal/notices/THIRD-PARTY-NOTICES.txt",
+ );
+ for (const platform of ["ios", "android"]) {
+ const mobileNotice = read(
+ `docs/legal/notices/mobile-${platform}.txt`,
+ );
+ assert.match(
+ mobileNotice,
+ /LiteLLM mascot SVG path \(adapted\).*Copyright \(c\) 2026 Berri AI/s,
+ );
+ assert.doesNotMatch(
+ mobileNotice,
+ /LiteLLM mascot SVG path \(adapted\) adapted/,
+ );
+ assertProviderBrandingOrder(`docs/legal/notices/mobile-${platform}.txt`);
+ }
assert.ok(
fs.existsSync(
path.join(repoRoot, "apps/desktop/cindy-updater/src-tauri/Cargo.lock"),
diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjs
index 55530724b8..bf1f969872 100644
--- a/scripts/generate-third-party-notices.mjs
+++ b/scripts/generate-third-party-notices.mjs
@@ -581,6 +581,30 @@ function bundledComponent(component) {
return { ecosystem: "bundled", ...component };
}
+function buildProviderBrandingEntries() {
+ const entries = [
+ bundledComponent({
+ name: "Lobe Icons SVG paths (vendored)",
+ version: "5.14.0",
+ license: "MIT",
+ url: "https://github.com/lobehub/lobe-icons/tree/v5.14.0",
+ licenseText: MIT_TEXT("MIT License\n\nCopyright (c) 2023 LobeHub"),
+ }),
+ bundledComponent({
+ name: "LiteLLM mascot SVG path (adapted)",
+ version: "adapted",
+ license: "MIT",
+ url: "https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg",
+ licenseText: MIT_TEXT("MIT License\n\nCopyright (c) 2026 Berri AI"),
+ }),
+ ];
+ return entries.sort(
+ (a, b) =>
+ (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) ||
+ (a.url < b.url ? -1 : a.url > b.url ? 1 : 0),
+ );
+}
+
function readBundledLicense(relativePath) {
return normalizeNoticeText(
fs.readFileSync(path.join(REPO_ROOT, relativePath), "utf8"),
@@ -769,16 +793,8 @@ function buildDesktopCommonEntries(apacheText, sharpPackageNames) {
}),
);
- // ProviderLogoMark 中随桌面包分发的 xAI / 智谱 SVG 路径。
- entries.push(
- bundledComponent({
- name: "Lobe Icons SVG paths (vendored)",
- version: "5.14.0",
- license: "MIT",
- url: "https://github.com/lobehub/lobe-icons/tree/v5.14.0",
- licenseText: MIT_TEXT("MIT License\n\nCopyright (c) 2023 LobeHub"),
- }),
- );
+ // ProviderLogoMark / MobileProviderMark 共享的上游 SVG path,桌面与移动端均随包分发。
+ entries.push(...buildProviderBrandingEntries());
return entries;
}
@@ -813,6 +829,7 @@ function buildWindowsEntries() {
function buildMobileEntries(apacheText, platform) {
const entries = [
+ ...buildProviderBrandingEntries(),
bundledComponent({
name: "JetBrains Mono fonts",
version: "bundled",
@@ -893,9 +910,13 @@ function buildOutput({
push("SECTION 1: Bundled components (non-npm)");
push("=".repeat(78));
for (const e of manualEntries) {
+ const versionSuffix = `(${e.version})`;
+ const heading = e.name.endsWith(versionSuffix)
+ ? e.name
+ : `${e.name} ${e.version}`;
push();
push("-".repeat(78));
- push(`${e.name} ${e.version}`);
+ push(heading);
push(`License: ${e.license}`);
if (e.url) push(`Source: ${e.url}`);
push("-".repeat(78));