Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 修复自定义网关 codex 模型置灰 (#1750)

DavidShenXD2f2be5699701
diff --git a/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts b/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts
index 6e6f231b50..97c3139c31 100644
--- a/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import type { AgentKind } from '@cindy/maker-core';
-import type { ProviderView } from '@cindy/model-providers';
+import type { CatalogModel, ProviderView } from '@cindy/model-providers';
import { ui as discordUi } from '../../discord/uiText';
import { ui as feishuUi } from '../../feishu/uiText';
@@ -35,7 +35,7 @@ function row(overrides: Partial<AuthRow> = {}): AuthRow {
};
}
-function model(id: string) {
+function model(id: string): CatalogModel {
return {
id,
name: id,
@@ -94,6 +94,45 @@ describe('checkImRouteAuth', () => {
expect(message).not.toContain('/new');
});
+ it('uses the selected user-provider route for codex/ models without an XD gateway key', async () => {
+ const providerSnapshot = [
+ provider({
+ id: 'custom-litellm',
+ source: 'user',
+ strategy: 'api-key-header',
+ agentKind: 'codex',
+ modelId: 'codex/foo',
+ routing: {
+ codex: {
+ upstream: 'https://litellm.example.test',
+ authStrategy: 'api-key-header',
+ headerOverride: { authorization: 'Bearer configured-by-provider' },
+ },
+ },
+ models: { codex: [model('codex/foo')] },
+ }),
+ ];
+
+ // 自定义供应商的 host 注入鉴权不应回落到 codex/ 的 XD 网关 key gate。
+ await expect(
+ checkImRouteAuth(
+ row({ agentKind: 'codex', model: 'codex/foo', providerId: 'custom-litellm' }),
+ providerSnapshot,
+ deps(),
+ ),
+ ).resolves.toEqual({ ok: true, missing: null });
+ });
+
+ it('reports gateway-key for an implicit codex/ route without an XD gateway key', async () => {
+ const providerSnapshot = [
+ provider({ id: 'xd', strategy: 'gateway-key', agentKind: 'codex', modelId: 'codex/foo' }),
+ ];
+
+ await expect(
+ checkImRouteAuth(row({ agentKind: 'codex', model: 'codex/foo' }), providerSnapshot, deps()),
+ ).resolves.toEqual({ ok: false, missing: 'gateway-key' });
+ });
+
it('reports gateway-key when a gateway route has no XD key', async () => {
const providerSnapshot = [provider({ id: 'xd', strategy: 'gateway-key' })];
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx
new file mode 100644
index 0000000000..c86231b1b4
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx
@@ -0,0 +1,220 @@
+// @vitest-environment jsdom
+
+/**
+ * modelSelectorCustomProviderCodexGate.test.tsx
+ * ---------------------------------------------------------------------------
+ * #1568 回归:未登录(hasSavedKey=false)时,codex/ 前缀的本机 key gate 只应作用于
+ * XD 网关折扣路由;自定义(user)供应商目录里的同前缀模型按其供应商自身状态判定,
+ * 不得因缺少 Cindy AI 网关 key 被置灰。
+ */
+
+import { act, fireEvent, render, screen, within } from '@testing-library/react';
+import React from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('react-i18next')>()),
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, string>) => {
+ const translations: Record<string, string> = {
+ 'settings.providers.xd.title': 'Cindy AI',
+ 'newChat.modelSelector.trigger.placeholder': '选择模型',
+ 'newChat.modelSelector.trigger.aria': `Select model. Current: ${options?.model ?? ''}`,
+ 'newChat.modelSelector.trigger.ariaWithEffort': `Select model. Current: ${options?.model ?? ''}, effort: ${options?.effort ?? ''}`,
+ 'newChat.modelSelector.search.noResults': '无匹配模型',
+ 'newChat.modelSelector.pricing.free': '限时免费',
+ 'newChat.modelSelector.source.disconnected': '已断开',
+ };
+ return translations[key] ?? options?.defaultValue ?? key;
+ },
+ }),
+}));
+
+vi.mock('@/components/ui/popover', async () => {
+ const React = await import('react');
+ const OpenContext = React.createContext<{
+ open: boolean;
+ onOpenChange?: (open: boolean) => void;
+ }>({ open: true });
+ return {
+ Popover: ({
+ children,
+ open,
+ onOpenChange,
+ }: {
+ children: React.ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ }) =>
+ React.createElement(
+ OpenContext.Provider,
+ { value: { open: open ?? true, onOpenChange } },
+ children,
+ ),
+ PopoverTrigger: ({ children }: { children: React.ReactNode }) => {
+ const state = React.useContext(OpenContext);
+ const child = children as React.ReactElement<{ onClick?: React.MouseEventHandler }>;
+ return React.cloneElement(child, {
+ onClick: (event: React.MouseEvent) => {
+ child.props.onClick?.(event);
+ state.onOpenChange?.(!state.open);
+ },
+ });
+ },
+ PopoverAnchor: ({ children }: { children: React.ReactNode }) => children,
+ PopoverContent: ({ children }: { children: React.ReactNode }) => {
+ const state = React.useContext(OpenContext);
+ return state.open
+ ? React.createElement('div', { 'data-testid': 'model-options-popover' }, children)
+ : null;
+ },
+ };
+});
+
+vi.mock('@/lib/scrollbarAutoHide', () => ({ flashScrollbar: vi.fn() }));
+
+vi.mock('@/hooks/useAgentCapabilities', () => ({
+ evictDeviceCapabilities: vi.fn(),
+ prefetchDeviceCapabilities: vi.fn(async () => {}),
+ useAgentCapabilities: () => ({ capabilities: null, loading: false, error: null }),
+}));
+
+// 未登录:本机没有 Cindy AI/XD 网关 key。
+vi.mock('@/hooks/useApiKey', () => ({
+ useApiKey: () => ({ hasSavedKey: false }),
+}));
+
+vi.mock('@/hooks/useConnectedSource', () => ({
+ useConnectedSource: () => ({ hasConnectedSource: true, loading: false }),
+}));
+
+vi.mock('@/hooks/useModelPricing', () => ({
+ useGatewayModelPricing: () => ({}),
+ useReferenceModelPricing: () => ({}),
+}));
+
+const providersRef = vi.hoisted(() => {
+ const codexModel = (id: string, name: string) => ({
+ id,
+ name,
+ contextWindow: 200000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'high',
+ });
+ const DEFAULT_PROVIDERS = [
+ {
+ id: 'xd',
+ name: 'Cindy AI',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: { method: 'api-key' },
+ routing: { codex: {} },
+ connected: true,
+ models: { codex: [codexModel('codex/gpt-5.5', 'GPT-5.5')] },
+ },
+ {
+ id: 'custom-litellm',
+ name: '自建 LiteLLM',
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'api-key' },
+ routing: { codex: {} },
+ connected: true,
+ models: { codex: [codexModel('codex/gpt-5.6-sol', 'codex/gpt-5.6-sol')] },
+ },
+ ] as unknown[];
+ return { DEFAULT_PROVIDERS, providers: DEFAULT_PROVIDERS };
+});
+vi.mock('@/hooks/useProviders', () => ({
+ useProviders: () => ({ providers: providersRef.providers, providerOrder: [] }),
+}));
+
+vi.mock('@/hooks/useDeviceProviders', () => ({
+ evictDeviceProviders: vi.fn(),
+ prefetchDeviceProviders: vi.fn(async () => {}),
+ useDeviceProviders: () => ({
+ providers: [],
+ loading: false,
+ error: null,
+ unsupported: false,
+ }),
+}));
+
+vi.mock('@/lib/providerModels', () => ({
+ providerMonogram: (name: string) => name.slice(0, 1).toUpperCase(),
+ isChatBridgedCodexProvider: () => false,
+ filterChatBridgedCodexProviders: (providers: unknown[]) => providers,
+ resolveVisibleModelAgentKind: ({ agentKind }: { agentKind: string | null }) =>
+ agentKind ?? 'codex',
+ selectVisibleModels: () => [],
+}));
+
+vi.mock('@/state/modelVisibilityPrefs', () => ({
+ isModelEnabled: () => true,
+ useModelVisibilityVersion: () => 0,
+}));
+
+vi.mock('@/state/providerModelMemory', () => ({
+ useProviderModelMemoryVersion: () => 0,
+}));
+
+vi.mock('@/state/deviceLinkModelMirror', () => ({
+ useDeviceLinkModelMirrorVersion: () => 0,
+}));
+
+import { ModelSelector } from '@/components/new-chat/ModelSelector';
+
+const requestProviderModelsAutoRefresh = vi.fn(async () => ({ ok: true as const }));
+
+beforeEach(() => {
+ requestProviderModelsAutoRefresh.mockClear();
+ providersRef.providers = providersRef.DEFAULT_PROVIDERS;
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: { requestProviderModelsAutoRefresh },
+ };
+});
+
+function renderSelector(props: Partial<React.ComponentProps<typeof ModelSelector>> = {}) {
+ return render(
+ React.createElement(ModelSelector, {
+ modelId: 'codex/gpt-5.5',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'codex',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ ...props,
+ }),
+ );
+}
+
+async function openDropdown(): Promise<void> {
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Select model/ }));
+ });
+}
+
+describe('ModelSelector codex/ key gate scope (#1568)', () => {
+ it('keeps custom-provider codex/ models selectable without a saved gateway key', async () => {
+ renderSelector();
+ await openDropdown();
+ const popover = screen.getByTestId('model-options-popover');
+ const options = within(popover).getAllByRole('option');
+ const customRow = options.find((row) =>
+ within(row).queryByText('codex/gpt-5.6-sol'),
+ );
+ expect(customRow).toBeTruthy();
+ expect(customRow?.getAttribute('aria-disabled')).toBe('false');
+ });
+
+ it('still disables XD gateway codex/ models without a saved gateway key', async () => {
+ renderSelector();
+ await openDropdown();
+ const popover = screen.getByTestId('model-options-popover');
+ const options = within(popover).getAllByRole('option');
+ const gatewayRow = options.find((row) => within(row).queryByText('GPT-5.5'));
+ expect(gatewayRow).toBeTruthy();
+ expect(gatewayRow?.getAttribute('aria-disabled')).toBe('true');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
index a2f8369162..dcdbdf074d 100644
--- a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
@@ -50,12 +50,14 @@ describe('remote Orca Worker creation context', () => {
it('never uses the controller API key to gate a remote model row', () => {
const selector = read('components/new-chat/ModelSelector.tsx');
- // 本地会话仍只按 codex/ + hasSavedKey 准入;SSH 远程额外按订阅直连前缀禁用
- // (不可路由)。device-link 远程在目录未就绪或真实读取失败时禁用旧行,
+ // 本地会话按 codex/ + hasSavedKey 准入,但该 key gate 只属于 XD 网关折扣路由,
+ // 自定义(user)供应商的同前缀模型不受 Cindy 登录门禁(#1568);SSH 远程额外按订阅
+ // 直连前缀禁用(不可路由)。device-link 远程在目录未就绪或真实读取失败时禁用旧行,
// 只有明确判定老被控端不支持 provider:list 时才回退 capabilities flat list;
// 任一远程路径都不得回退到 controller key 判定。
expect(selector).toContain('if (!deviceId) {');
expect(selector).toContain('if (subscriptionDirectDisabledReason(id)) return true;');
+ expect(selector).toContain("if (provider?.source === 'user') return false;");
expect(selector).toContain("return id.startsWith('codex/') && !hasSavedKey;");
expect(selector).toContain("if (remoteModelListStatus !== 'ready') return true;");
expect(selector).toContain(
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index 0c3c3bc042..07be4c3866 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -1010,9 +1010,14 @@ function ModelSelectorContentView({
? t('newChat.modelSelector.subscriptionDirectDisabled.xai')
: t('newChat.modelSelector.subscriptionDirectDisabled.generic');
};
- const modelDisabledOf = (id: string): boolean => {
+ const modelDisabledOf = (provider: ProviderView | null, id: string): boolean => {
if (!deviceId) {
if (subscriptionDirectDisabledReason(id)) return true;
+ // codex/ 的本机 key gate 只属于 XD 网关折扣路由。自定义(user)供应商目录里的
+ // 同前缀模型由该供应商自身配置路由(codex-proxy-host 按会话显式供应商解析,
+ // 不按前缀落网关),不依赖 Cindy 登录/网关 key(#1568)。flat 列表(provider
+ // 为 null,无供应商概念)与内置来源保持原前缀判定。
+ if (provider?.source === 'user') return false;
return id.startsWith('codex/') && !hasSavedKey;
}
if (remoteModelListStatus !== 'ready') return true;
@@ -1601,7 +1606,7 @@ function ModelSelectorContentView({
const providerId = provider?.id ?? null;
const isSelected = isSelectedRow(providerId, model.id);
const isSubscriptionModel = provider?.access?.kind === 'subscription';
- const disabled = interactionDisabled || modelDisabledOf(model.id);
+ const disabled = interactionDisabled || modelDisabledOf(provider, model.id);
const disabledReason = subscriptionDirectDisabledReason(model.id);
const rowEffort = rowEffortOf(providerId, model);
const rowFastOn = fastOnOf(providerId, model);