Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(model-providers): mode 优先分类 + chat 准入过滤 (#905)
Chris Zhang2d1a717ebfec
diff --git a/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts b/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.tsindex 1662b87519..da10875ae2 100644--- a/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts+++ b/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts@@ -441,4 +441,165 @@ describe('resolveImSessionDefaults', () => {providerId: null,});});++ // issue #882 第 3 点(2026-07 review):live provider 快照路径原来不做 chat 准入判定,+ // 一个非聊天模型 id 若恰好被保存为默认值,或排序靠前成为兜底,会被当成 IM 新会话的+ // 有效默认模型——发消息必失败。下面两条锁住 hasModel / firstModel 都必须过 isChatEligible。+ it('rejects a saved default that points at a non-chat gateway model even though a provider offers that id', async () => {+ mocks.listProviders.mockResolvedValue([+ {+ ...providers[0],+ models: {+ ...providers[0].models,+ 'claude-code': [+ { ...claudeModels[0], mode: 'chat' },+ { id: 'gpt-image-2', displayName: 'GPT Image 2', contextWindow: 0, efforts: [], defaultEffort: null, mode: 'image_generation' },+ ],+ },+ },+ providers[1],+ ]);+ mocks.readImDefaultSettings.mockReturnValue({+ agentKind: 'claude-code',+ agents: {+ 'claude-code': {+ providerId: null,+ model: 'gpt-image-2', // saved default is a non-chat model — must not be accepted as-is+ effort: 'high',+ },+ codex: { providerId: null, model: 'codex/gpt-5.5', effort: 'high' },+ },+ });++ await expect(resolveImSessionDefaults(config)).resolves.toMatchObject({+ agentKind: 'claude-code',+ model: 'claude-opus-4-8', // falls back to the system default model, not the non-chat id+ });+ });++ it('skips a non-chat model that sorts first when falling back to "first model for the agent"', async () => {+ mocks.listProviders.mockResolvedValue([+ {+ ...providers[0],+ models: {+ ...providers[0].models,+ codex: [+ { id: 'gpt-image-2', displayName: 'GPT Image 2', contextWindow: 0, efforts: [], defaultEffort: null, mode: 'image_generation' },+ ...codexModels,+ ],+ },+ },+ providers[1],+ ]);+ mocks.readImDefaultSettings.mockReturnValue({+ agentKind: 'codex',+ agents: {+ 'claude-code': { providerId: null, model: 'claude-opus-4-8', effort: 'xhigh' },+ codex: { providerId: null, model: 'missing-model', effort: 'high' }, // forces the firstModel() fallback path+ },+ });++ await expect(resolveImSessionDefaults(config)).resolves.toMatchObject({+ agentKind: 'codex',+ model: 'codex/gpt-5.5', // the image model sorts first but must be skipped+ });+ });++ it('reroutes the session to the chat-eligible provider when the saved provider copy of the model is non-chat (2026-07 review: fresh evidence + 第 25 轮)', async () => {+ // Same model id 'shared-id' exists on both providers with DIFFERENT modes:+ // 'xd' (the saved providerId) marks it non-chat; 'openai' marks it chat.+ // hasModel() passes because *some* source is eligible, but resolveProviderId+ // must independently reject binding the session to the specific non-chat source.+ // Returning null is NOT enough: null means implicit default routing, which lands+ // back on the native default source — and 'xd' IS the native default for+ // claude-code, so null would send the request right back to the non-chat copy.+ // The eligible fallback source must be resolved and persisted explicitly.+ mocks.listProviders.mockResolvedValue([+ {+ ...providers[0],+ models: {+ ...providers[0].models,+ 'claude-code': [+ ...claudeModels,+ { id: 'shared-id', displayName: 'Shared', contextWindow: 0, efforts: [], defaultEffort: null, mode: 'image_generation' },+ ],+ },+ },+ {+ ...providers[1],+ agents: ['claude-code'],+ routing: {+ ...providers[1].routing,+ 'claude-code': { upstream: 'https://api.openai.com', authStrategy: 'oauth-passthrough' },+ },+ models: {+ ...providers[1].models,+ 'claude-code': [+ { id: 'shared-id', displayName: 'Shared', contextWindow: 200_000, efforts: [], defaultEffort: null, mode: 'chat' },+ ],+ },+ },+ ]);+ mocks.readImDefaultSettings.mockReturnValue({+ agentKind: 'claude-code',+ agents: {+ 'claude-code': { providerId: 'xd', model: 'shared-id', effort: 'high' },+ codex: { providerId: null, model: 'codex/gpt-5.5', effort: 'high' },+ },+ });++ await expect(resolveImSessionDefaults(config)).resolves.toMatchObject({+ agentKind: 'claude-code',+ model: 'shared-id',+ // must not stay pinned to 'xd' (its copy is not chat-eligible), and must not+ // fall back to null either (implicit routing lands back on 'xd', the native+ // default) — the chat-eligible source must be selected explicitly.+ providerId: 'openai',+ });+ });++ it('resolves effort from the chat-eligible copy of the model, not an earlier non-chat copy with different effort metadata (2026-07 review: fresh evidence)', async () => {+ // 'xd' (checked first) has a non-chat copy with empty efforts; 'openai' (checked+ // second) has the real chat copy with efforts=[low,medium,high]. A requested effort+ // that only the chat copy can validate ('xhigh', unsupported) must be clamped using+ // the chat copy's metadata, not silently accepted via the non-chat copy's empty efforts.+ mocks.listProviders.mockResolvedValue([+ {+ ...providers[0],+ models: {+ ...providers[0].models,+ 'claude-code': [+ { id: 'shared-id', displayName: 'Shared', contextWindow: 0, efforts: [], defaultEffort: null, mode: 'image_generation' },+ ],+ },+ },+ {+ ...providers[1],+ agents: ['claude-code'],+ routing: {+ ...providers[1].routing,+ 'claude-code': { upstream: 'https://api.openai.com', authStrategy: 'oauth-passthrough' },+ },+ models: {+ ...providers[1].models,+ 'claude-code': [+ { id: 'shared-id', displayName: 'Shared', contextWindow: 200_000, efforts: ['low', 'medium', 'high'], defaultEffort: 'medium', mode: 'chat' },+ ],+ },+ },+ ]);+ mocks.readImDefaultSettings.mockReturnValue({+ agentKind: 'claude-code',+ agents: {+ 'claude-code': { providerId: null, model: 'shared-id', effort: 'xhigh' }, // unsupported by the chat copy+ codex: { providerId: null, model: 'codex/gpt-5.5', effort: 'high' },+ },+ });++ await expect(resolveImSessionDefaults(config)).resolves.toMatchObject({+ agentKind: 'claude-code',+ model: 'shared-id',+ effort: 'medium', // clamped using the chat copy's defaultEffort, not silently passed through+ });+ });});diff --git a/apps/desktop/src/main/im/defaultSessionSettings.ts b/apps/desktop/src/main/im/defaultSessionSettings.tsindex 9708ac9e33..a9238f801f 100644--- a/apps/desktop/src/main/im/defaultSessionSettings.ts+++ b/apps/desktop/src/main/im/defaultSessionSettings.ts@@ -8,11 +8,11 @@import type { AgentKind, Effort, PermissionMode } from '@cindy/maker-core';import {+ chatEligibleSourcesForModel,connectedProvidersForAgent,effectiveSourceIdForModel,getModel,- providerOffersModel,- sourcesForModel,+ isAgentSelectableModel,type ProviderView,} from '@cindy/model-providers';@@ -194,7 +194,10 @@ function hasModel(providers: ProviderView[] | null,): boolean {if (providers) {- return sourcesForModel(providers, modelId, agentKind).length > 0;+ // chatEligibleSourcesForModel(不是裸 sourcesForModel):否则一个已下架/从未是+ // 聊天模型的 id(image/embedding/...)会被判定为可用默认值(issue #882 第 3 点,+ // 2026-07 review)。+ return chatEligibleSourcesForModel(providers, modelId, agentKind).length > 0;}return getMaker().getCapabilities(agentKind)@@ -203,9 +206,10 @@ function hasModel(function firstModel(agentKind: AgentKind, providers: ProviderView[] | null): string | null {if (providers) {- // 兜底选模型与宽松降级同口径(pickEnabledFallbackModel):跳过停用条目与能力- // 模型(图像/音频等),否则「保存的默认模型失效 → 取目录第一个」可能落在一份- // 被停用或根本不是对话模型的条目上(PR #744 review 第十轮)。+ // 兜底选模型与宽松降级同口径(pickEnabledFallbackModel):跳过停用条目与非聊天+ // 模型(图像/视频/TTS/STT/实时/Embedding/压缩等,issue #882 第 3 点),否则+ // 「保存的默认模型失效 → 取目录第一个」可能落在一份被停用或根本不是聊天模型+ // 的条目上(PR #744 review 第十轮)。return pickEnabledFallbackModel(providers, agentKind)?.model ?? null;}return getMaker().getCapabilities(agentKind).availableModels[0]?.id ?? null;@@ -262,16 +266,12 @@ function resolveProviderId(const provider = connectedProvidersForAgent(providers, agentKind).find((p) => p.id === providerId,);- if (- !provider ||- !providerOffersModel(provider, modelId, agentKind) ||- // 该 (来源, 模型) 拷贝被停用同样使保存的显式来源失效:B 家启用不豁免 A 家- // 停用拷贝(PR #744 review 第十轮)。- getModel(provider, modelId, agentKind)?.disabled === true- ) {- // 经**启用 rail** 解析替代来源并显式落地,而不是返回 null 走隐式默认 ——- // turnRunner 直建会话不过路由守卫,隐式默认落点可能恰是被停用的那份拷贝- // (provider-route 不查停用标志)。零启用来源 ⇒ null,交给既有失败路径。+ const model = provider ? getModel(provider, modelId, agentKind) : undefined;+ if (!provider || !model || model.disabled === true) {+ // 不存在,或该 (来源, 模型) 拷贝被停用:经**启用 rail** 解析替代来源并显式+ // 落地,而不是返回 null 走隐式默认 —— turnRunner 直建会话不过路由守卫,隐式+ // 默认落点可能恰是被停用的那份拷贝(provider-route 不查停用标志)。零启用+ // 来源 ⇒ null,交给既有失败路径(PR #744 review 第十轮)。const fallback = effectiveSourceIdForModel(providers, null, modelId, agentKind);log.warn('im default provider unavailable; rerouting to enabled source', {agentKind,@@ -281,6 +281,26 @@ function resolveProviderId(});return fallback;}+ if (!isAgentSelectableModel(model, { userProvider: provider.source === 'user' })) {+ // hasModel() 只证明"这个 id 在某个来源上是聊天模型"(any-source),不代表**这个**被+ // 保存的 providerId 本身也是——同一 id 若在不同来源上 mode 不一致(如 A 是+ // image_generation、B 是 chat),model 存在性校验会因 B 通过,但这里若只查+ // providerOffersModel(仅看 id 是否存在,不看 mode),仍会把会话钉死在 A 上+ // (2026-07 review:fresh evidence,与 hasModel 校验的是两件不同的事)。+ // 必须**显式**解析聊天可用的替代来源,不能返回 null 了事:null 的语义是隐式+ // 默认路由,运行时会落回原生默认来源——保存的 providerId 若恰好就是原生默认+ // (如 XD),null 等于原路发回那份非聊天拷贝,什么也没挡住(2026-07 review 第+ // 25 轮)。effectiveSourceIdForModel 走 chat 准入 rail,零可用 ⇒ null 交给既有+ // 失败路径;数据异常本身留 warn 供排查。+ const fallback = effectiveSourceIdForModel(providers, null, modelId, agentKind);+ log.warn('im default provider is non-chat for this model; rerouting to chat-eligible source', {+ agentKind,+ modelId,+ providerId,+ fallback,+ });+ return fallback;+ }return providerId;}@@ -308,14 +328,26 @@ function findModel(providerId?: string | null,) {if (providers) {+ // 显式来源由调用方(resolveProviderId)已经裁决过存在性/停用/chat 准入,这里+ // 直接取该来源自己的拷贝,不重复校验。if (providerId) {const provider = providers.find((p) => p.id === providerId);const model = provider ? getModel(provider, modelId, agentKind) : undefined;if (model) return model;}+ // 隐式(无显式来源):跳过被停用的拷贝(PR #744 review 第二十五轮)与非聊天+ // 来源的同 id 条目(2026-07 review,fresh evidence)——同一 id 若在排序更靠前+ // 的来源上是停用或非聊天(efforts 元数据可能完全不同),这里不挡的话+ // resolveEffort 会拿着错的 efforts/defaultEffort 去校验,即便 resolveProviderId+ // 已经把会话正确路由到了后面那个启用的聊天来源。for (const provider of connectedProvidersForAgent(providers, agentKind)) {const model = getModel(provider, modelId, agentKind);- if (model && model.disabled !== true) return model;+ if (+ model &&+ model.disabled !== true &&+ isAgentSelectableModel(model, { userProvider: provider.source === 'user' })+ )+ return model;}}return getMaker()diff --git a/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts b/apps/desktop/src/main/im/shared/__tests__/authCheck.test.tsindex 2d76d73a48..7be3198844 100644--- a/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts@@ -9,6 +9,7 @@ import {checkImRouteAuth,checkImRouteAuthDetailed,hasAuthForImRoute,+ resolveEffectiveProvider,type ImAuthCheckDeps,} from '../authCheck';@@ -239,3 +240,48 @@ describe('checkImRouteAuth', () => {await expect(hasAuthForImRoute(row(), providerSnapshot, authDeps)).resolves.toBe(true);});});++describe('resolveEffectiveProvider', () => {+ // issue #882 第 3 点(2026-07 review):同一 model id 在不同来源上 mode 不一致时,+ // 鉴权解析不能只看"这个来源提供这个 id",还要看这个来源上这个 id 是不是聊天模型+ // ——否则会去校验一个非聊天来源的凭证,校验"通过"也不代表这个会话真能发聊天请求。+ it('rejects an explicit providerId whose copy of the model is non-chat, even though the id exists there', () => {+ const nonChat = provider({+ id: 'xd',+ strategy: 'gateway-key',+ models: { 'claude-code': [{ ...model('shared-id'), efforts: [] as const, defaultEffort: null, mode: 'image_generation' }] },+ });+ const chat = provider({+ id: 'openai',+ strategy: 'oauth-passthrough',+ models: { 'claude-code': [{ ...model('shared-id'), efforts: [] as const, defaultEffort: null, mode: 'chat' }] },+ });++ expect(+ resolveEffectiveProvider(+ row({ model: 'shared-id', providerId: 'xd' }),+ [nonChat, chat],+ ),+ ).toEqual({ kind: 'explicit-invalid' });+ });++ it('falls back to the chat-eligible source when no explicit providerId is given, skipping a non-chat copy of the same id', () => {+ const nonChat = provider({+ id: 'xd',+ strategy: 'gateway-key',+ models: { 'claude-code': [{ ...model('shared-id'), efforts: [] as const, defaultEffort: null, mode: 'image_generation' }] },+ });+ const chat = provider({+ id: 'openai',+ strategy: 'oauth-passthrough',+ models: { 'claude-code': [{ ...model('shared-id'), efforts: [] as const, defaultEffort: null, mode: 'chat' }] },+ });++ const resolution = resolveEffectiveProvider(+ row({ model: 'shared-id', providerId: null }),+ [nonChat, chat],+ );+ expect(resolution.kind).toBe('provider');+ expect(resolution.kind === 'provider' ? resolution.provider.id : null).toBe('openai');+ });+});diff --git a/apps/desktop/src/main/im/shared/authCheck.ts b/apps/desktop/src/main/im/shared/authCheck.tsindex a76852926d..112c5f3be3 100644--- a/apps/desktop/src/main/im/shared/authCheck.ts+++ b/apps/desktop/src/main/im/shared/authCheck.ts@@ -1,7 +1,8 @@import {+ chatEligibleSourcesForModel,+ getModel,+ isAgentSelectableModel,nativeDefaultSourceId,- providerOffersModel,- sourcesForModel,type ProviderView,} from '@cindy/model-providers';import type { AgentKind } from '@cindy/maker-core';@@ -162,16 +163,22 @@ export function resolveEffectiveProvider(): ProviderResolution {if (!providers) return row.providerId ? { kind: 'explicit-invalid' } : { kind: 'none' };if (row.providerId) {- const explicit = providers.find(- (p) =>- p.id === row.providerId &&- p.connected &&- p.agents.includes(row.agentKind) &&- providerOffersModel(p, row.model, row.agentKind),- );+ // 显式 providerId 命中的这个具体来源上,当前 model id 必须真的是聊天模型才接受+ // (issue #882 第 3 点,2026-07 review):否则鉴权检查会去校验一个非聊天来源的+ // 凭证,校验"通过"也不代表这个会话真能发聊天请求。+ const explicit = providers.find((p) => {+ if (p.id !== row.providerId || !p.connected || !p.agents.includes(row.agentKind)) {+ return false;+ }+ const model = getModel(p, row.model, row.agentKind);+ return (+ model !== undefined &&+ isAgentSelectableModel(model, { userProvider: p.source === 'user' })+ );+ });return explicit ? { kind: 'provider', provider: explicit } : { kind: 'explicit-invalid' };}- const sources = sourcesForModel(providers, row.model, row.agentKind);+ const sources = chatEligibleSourcesForModel(providers, row.model, row.agentKind);const nativeId = nativeDefaultSourceId(sources, row.agentKind);const provider = (nativeId ? sources.find((p) => p.id === nativeId) : sources[0]) ?? null;return provider ? { kind: 'provider', provider } : { kind: 'none' };diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.tsindex e2bc2b8fad..9e4f651217 100644--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts@@ -128,6 +128,29 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {});});+ it('非聊天模型(issue #882 第 3 点)不进任一 agent 的 availableModels,但仍留在完整 catalog 里', () => {+ const cat = injectedCatalog();+ const xd = cat.providers.find((provider) => provider.id === 'xd')!;+ xd.models['claude-code'] = [+ ...(xd.models['claude-code'] ?? []),+ model('gpt-image-2', { name: 'GPT Image 2', mode: 'image_generation', group: undefined }),+ model('text-embedding-3-large', { name: 'Embedding 3 Large' }), // 无 mode,靠 id 正则兜底判定为 embedding+ ];+ xd.models.codex = [+ ...(xd.models.codex ?? []),+ model('gpt-image-2', { name: 'GPT Image 2', mode: 'image_generation' }),+ ];++ const cc = deriveAvailableModels(cat, 'claude-code');+ const codex = deriveAvailableModels(cat, 'codex');+ expect(cc.some((m) => m.id === 'gpt-image-2')).toBe(false);+ expect(cc.some((m) => m.id === 'text-embedding-3-large')).toBe(false);+ expect(codex.some((m) => m.id === 'gpt-image-2')).toBe(false);+ // 完整 catalog(设置页消费的那份)不受 availableModels 派生过滤影响,模型仍在。+ expect(xd.models['claude-code']!.some((m) => m.id === 'gpt-image-2')).toBe(true);+ expect(xd.models['claude-code']!.some((m) => m.id === 'text-embedding-3-large')).toBe(true);+ });+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__/model-route-guard.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.tsindex e0132bb5e3..34f2bf0674 100644--- a/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.ts@@ -122,6 +122,31 @@ describe('checkModelRoute', () => {});});+ it('隐式来源:原生默认拷贝是能力模型而他源有聊天拷贝 ⇒ reroute;显式点名非聊天拷贝仍 reject(2026-07 review 第 26 轮)', () => {+ // xd(原生默认)把 shared-id 标为图像生成,openai 的拷贝是 chat。UI 的发送检查+ // (chatEligibleSourcesForModel)因 openai 判定"能发",守卫若 reject 会与 UI 口径+ // 打架;若 pass 实际路由层又会把请求发进 xd 的图像端点 —— 必须与停用轴同构,+ // 显式改道到聊天拷贝。+ const catalog = {+ providers: [+ provider('xd', [model('shared-id', { mode: 'image_generation' })]),+ provider('openai', [model('shared-id', { mode: 'chat' })]),+ ],+ } as Catalog;+ const v = buildRegistry(catalog, { xd: true, openai: true }, {});+ expect(checkModelRoute(v, 'claude-code', 'shared-id', null)).toEqual({+ kind: 'reroute',+ providerId: 'openai',+ });+ // 显式点名非聊天拷贝:点名是"花谁的钱"的明确表达,不静默换源,照旧 reject。+ expect(checkModelRoute(v, 'claude-code', 'shared-id', 'xd')).toEqual({+ kind: 'reject',+ reason: 'capability-model',+ });+ // 显式选聊天拷贝所在来源:放行。+ expect(checkModelRoute(v, 'claude-code', 'shared-id', 'openai')).toEqual({ kind: 'pass' });+ });+it('能力模型分类按将要路由的拷贝判:未连接来源的对话拷贝不构成豁免', () => {// 同 id 在 xd 是图像模型、在用户自定义 mycorp 是对话模型,但 mycorp 未连接:// 实际路由永远不会落到未连接拷贝,隐式与点名 xd 都必须拒(PR #744 review 第六轮)。@@ -142,7 +167,7 @@ describe('checkModelRoute', () => {});});- it('混源同 id 双连接:分类按选中来源 —— 显式选用户家对话拷贝放行,XD 家能力拷贝与隐式默认都拒', () => {+ it('混源同 id 双连接:分类按选中来源 —— 显式选用户家对话拷贝放行,点名 XD 家能力拷贝拒,隐式默认改道到对话拷贝', () => {const catalog = {providers: [provider('xd', [model('gpt-image-2', { group: 'image' })]),@@ -155,10 +180,12 @@ describe('checkModelRoute', () => {kind: 'reject',reason: 'capability-model',});- // 隐式:原生默认落点是 xd(能力拷贝)—— provider-route 不看分类,必须在边界拒。+ // 隐式:原生默认落点是 xd(能力拷贝),但用户家有已连接的对话拷贝 —— 与停用轴+ // 同构显式改道,不 reject(UI 的发送检查因 mycorp 判"能发",拒会口径打架;+ // 2026-07 review 第 26 轮)。expect(checkModelRoute(v, 'claude-code', 'gpt-image-2', null)).toEqual({- kind: 'reject',- reason: 'capability-model',+ kind: 'reroute',+ providerId: 'mycorp',});});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.tsindex 4ffa07d5ee..3e3028b49d 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts@@ -400,6 +400,41 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {expect(() => resolveSavedProbeSpec('my-relay', 'codex')).toThrow(/no runtime/);});+ it('跳过非聊天模型挑第一个聊天模型探测(issue #882 第 3 点,2026-07 review):探测发的是聊天形状请求,挑到 embedding/image 模型会得到与配置无关的假失败结论', () => {+ const provider = buildUserProvider(config);+ setCustomProviders([+ {+ ...provider,+ models: {+ ...provider.models,+ 'claude-code': [+ { id: 'text-embedding-3-large', name: 'Embedding', contextWindow: 8191, efforts: [], defaultEffort: null, mode: 'embedding' },+ { id: 'glm-5.2', name: 'GLM', contextWindow: 128_000, efforts: [], defaultEffort: null },+ ],+ },+ },+ ]);+ setDiagnosticsKeyReader(() => 'sk-saved');+ expect(resolveSavedProbeSpec('my-relay', 'claude-code').modelId).toBe('glm-5.2');+ });++ it('全是非聊天模型时抛「无聊天模型」错误,而不是静默探测一个 embedding 模型', () => {+ const provider = buildUserProvider(config);+ setCustomProviders([+ {+ ...provider,+ models: {+ ...provider.models,+ 'claude-code': [+ { id: 'text-embedding-3-large', name: 'Embedding', contextWindow: 8191, efforts: [], defaultEffort: null, mode: 'embedding' },+ ],+ },+ },+ ]);+ setDiagnosticsKeyReader(() => 'sk-saved');+ expect(() => resolveSavedProbeSpec('my-relay', 'claude-code')).toThrow(/no chat models/);+ });+it('testProviderConnection(saved) 端到端(注入 fetch 断言 URL 与 key)', async () => {setCustomProviders([buildUserProvider(config)]);setDiagnosticsKeyReader(() => 'sk-saved');diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 421f572291..05cc5c31f0 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -58,9 +58,16 @@ export interface XdGatewayAgentOverride {defaultEnabled?: boolean;}-/** 服务端下发的 XD 网关聊天模型条目(shared/modelAccess ModelAccessGatewayModel 的子集)。 */+/**+ * 服务端下发的 XD 网关模型条目(shared/modelAccess ModelAccessGatewayModel 的子集)。+ * 命名沿用历史("聊天"),但条目本身不保证是聊天模型——是否聊天模型看 mode,+ * 服务端目前只透传已经过它自己 chat 过滤的条目,过滤范围以后可能放开(issue #882);+ * 客户端一律用 isChatEligible 判定,不依赖本类型名字或服务端过滤范围。+ */export interface XdGatewayModelInfo {id: string;+ /** Gateway 原生 mode(issue #882,权威分类字段;缺省时下游按 id 正则兜底)。 */+ mode?: string;/** AIGateway 折扣比例(0..1),折后价 = 原价 × (1 - costDiscount)。 */costDiscount?: number;/** AIGateway 标准 token 单价(per token)。 */@@ -533,6 +540,7 @@ function computeMerged(): Catalog {efforts,defaultEffort,supportsFastMode: ov.supportsFastMode ?? gm.supportsFastMode ?? false,+ ...(gm.mode !== undefined ? { mode: gm.mode } : {}),...(gm.description !== undefined ? { description: gm.description } : {}),...(gm.sortOrder !== undefined ? { sortOrder: gm.sortOrder } : {}),...(defaultEnabled !== undefined ? { defaultEnabled } : {}),diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.tsindex 9c3e0027aa..9c3532e506 100644--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts@@ -7,7 +7,9 @@* BUNDLED_CATALOG 派生每个 agent 的模型列表,经 capabilityAdditions 注入。** union 规则:跳过 `routing[agent].disabled` 的 runtime,再按 `catalog.providers` 数组序- * flatMap 各 provider 的 `models[agent]`,按 id **首见胜出**去重(provider 序即+ * flatMap 各 provider 的 `models[agent]`,跳过非聊天模型(isAgentSelectableModel,issue #882 第 3 点:+ * 网关多返回的图像/视频/TTS/STT/实时/Embedding/压缩模型不进 Agent availableModels,但仍在+ * 模型管理设置页可见——那边走完整 catalog,不走这个函数),按 id **首见胜出**去重(provider 序即* anthropic → openai → xd)。禁用来源不占 seen,同 id 仍可由后续可用来源补上。** 顺序契约(no-break):派生结果必须逐字逐序复现迁移前的有效列表@@ -15,7 +17,7 @@* 由 maker-host 的 catalogDerivedModels.test.ts 守。*/-import type { Catalog, CatalogModel, AgentKind } from '@cindy/model-providers';+import { isAgentSelectableModel, type Catalog, type CatalogModel, type AgentKind } from '@cindy/model-providers';import type { ModelDescriptor } from '@cindy/maker-core';/** Maker 能力读取面的最小形状;保留数组引用以让已创建 Session 同步看到新目录。 */@@ -37,6 +39,7 @@ function toDescriptor(m: CatalogModel): ModelDescriptor {if (m.supportsFastMode !== undefined) d.supportsFastMode = m.supportsFastMode;if (m.group !== undefined) d.group = m.group;if (m.sortOrder !== undefined) d.sortOrder = m.sortOrder;+ if (m.mode !== undefined) d.mode = m.mode;// 默认可见性要透传:渲染层的种子默认模型取「排序第一**且默认可见**」的那个,没有它就会// 把默认收起的 legacy 模型选成默认 —— 用户在选择器里根本看不到自己的默认模型。if (m.defaultEnabled !== undefined) d.defaultEnabled = m.defaultEnabled;@@ -51,6 +54,10 @@ export function deriveAvailableModels(catalog: Catalog, agent: AgentKind): Modelif (provider.routing[agent]?.disabled === true) continue;for (const m of provider.models[agent] ?? []) {if (seen.has(m.id)) continue;+ // provider-aware 谓词:合并目录里 source:'user' 的自定义供应商显式配置的模型带+ // 未知 group,id 撞上能力启发式(如 flux-image-x)时不能被误杀(2026-07 review 第+ // 25 轮)。非聊天模型不占 seen,同 id 若被其它来源标为 chat 仍可补上。+ if (!isAgentSelectableModel(m, { userProvider: provider.source === 'user' })) continue;seen.add(m.id);out.push(toDescriptor(m));}diff --git a/apps/desktop/src/main/maker-host/model-route-guard.ts b/apps/desktop/src/main/maker-host/model-route-guard.tsindex 66663dc299..34ee11cb3b 100644--- a/apps/desktop/src/main/maker-host/model-route-guard.ts+++ b/apps/desktop/src/main/maker-host/model-route-guard.ts@@ -102,7 +102,23 @@ export function checkModelRoute(const wouldRoute = preDisableRail.find((p) => p.id === wouldRouteId);if (!wouldRoute) return { kind: 'pass' };if (!copyAgentSelectable(wouldRoute, modelId, agent)) {- return { kind: 'reject', reason: 'capability-model' };+ // 原生默认落点是能力模型拷贝:与停用轴同构,先解析聊天可用的替代来源+ // (effectiveSourceIdForModel 走 chat 准入 rail,已排除停用),有 ⇒ 显式改道;+ // 无 ⇒ reject。不能直接 reject 了事:UI 的发送检查(chatEligibleSourcesForModel)+ // 会因他源的聊天拷贝判定"能发",创建却被这里拒掉,两个口径打架;也不能 pass ——+ // 实际路由层对隐式来源走原生默认,不查 mode,放行等于把请求发进 image/audio+ // 端点(2026-07 review 第 26 轮)。显式点名非聊天拷贝仍 reject(上方):点名是+ // 明确表达,不静默换源。+ const chatAlternative = effectiveSourceIdForModel([...views], null, modelId, agent);+ const chatAlternativeProvider = chatAlternative+ ? views.find((p) => p.id === chatAlternative)+ : undefined;+ return chatAlternative &&+ chatAlternativeProvider &&+ copyAgentSelectable(chatAlternativeProvider, modelId, agent) &&+ !copyDisabled(chatAlternativeProvider, modelId, agent)+ ? { kind: 'reroute', providerId: chatAlternative }+ : { kind: 'reject', reason: 'capability-model' };}if (!copyDisabled(wouldRoute, modelId, agent)) return { kind: 'pass' };diff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.tsindex da157593d5..9c1076e0bf 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,+ isAgentSelectableModel,isLoopbackProviderUrl,type AgentKind,type ProviderWireProtocol,@@ -316,8 +317,13 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Proconst 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}'`);+ // 探测发的是聊天形状的最小请求(见下方 requestPath/body 组装);挑第一个非聊天模型+ // (image/embedding/...)会把探测发给一个本来就不接受聊天请求的端点,得到的失败结论+ // 和"这个供应商配置是坏的"完全无关(2026-07 review,与 issue #882 第 3 点同一类问题)。+ const model = (provider.models[agent] ?? []).find((m) =>+ isAgentSelectableModel(m, { userProvider: provider.source === 'user' }),+ );+ if (!model) throw new Error(`provider '${providerId}' has no chat models for '${agent}'`);// OAuth 形态:探测凭证用 Runner 持有的 access_token(与 oauth-token 路由同源),未登录时// 无 token → 探测会得到 AUTH_INVALID,这本身就是「先去登录」的正确结论。// token 走 authorization 头而**不走 apiKey 字段**——apiKey 会让 cc 探测同时发diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduleGenerationRoute.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduleGenerationRoute.test.tsindex f34a1738f1..5a8b2d1714 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduleGenerationRoute.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduleGenerationRoute.test.ts@@ -72,6 +72,24 @@ describe('resolveBoundSessionGenerationRoute', () => {: provider),})).toBeNull();});++ it('fails closed when the explicit source only offers a non-chat copy of the persisted model id (issue #882 第 3 点, 2026-07 review 第 17 轮)', () => {+ const providersWithNonChatCopy = providers.map((provider) => provider.id === 'custom-claude'+ ? {+ ...provider,+ models: {+ 'claude-code': [+ { id: 'claude-connect-4-6', name: 'Claude Connect', contextWindow: 200_000, mode: 'embedding' },+ ],+ },+ }+ : provider) as unknown as ProviderView[];+ expect(resolveBoundSessionGenerationRoute({+ session: { agentKind: 'claude-code', model: 'claude-connect-4-6' },+ sessionProviderId: 'custom-claude',+ providers: providersWithNonChatCopy,+ })).toBeNull();+ });});describe('shouldResolveBoundSessionGenerationRoute', () => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 7067840962..ffe11fa8cb 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -6372,10 +6372,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)getProviderRoutingContext: async () => {const views = await getDesktopProviderService().listProviders({ allowSideEffects: true });// 准入过滤与 modelList.ts 标准派生同口径:用户停用的模型(disabled,见- // model-disable-store)与非 agent 分组的能力模型(图像/音频/视频/向量)不进- // 路由可用集 —— MCP create_worker 点名它们会走既有的 INVALID_PARAMS /- // NO_PROVIDER 拒绝路径,而不是静默路由过去。停用的供应商已在- // connectedProvidersForAgent(suspended)一层出局。+ // model-disable-store)与非聊天模型(image/video/tts/stt/realtime/+ // embedding/compression,issue #882 第 3 点)不进路由可用集 —— MCP+ // create_worker 点名它们会走既有的 INVALID_PARAMS / NO_PROVIDER 拒绝路径,+ // 而不是静默路由过去。停用的供应商已在 connectedProvidersForAgent(suspended)+ // 一层出局。isAgentSelectableModel 现在就是 isChatEligible(+ userProvider+ // 例外),这里的 models/fastModels/effortMetaByModel 都是+ // orcaWorkerCreationService 唯一能看到的 provider 快照 —— 一旦某个非聊天+ // mode 的模型混进这份 id 清单,service 内所有 `provider.models.includes(id)`+ // 式的 preflight 都只按 id 存在与否放行,永远不会知道这条模型其实是图片/+ // 语音端点(mode 信息在这一步已经被拍平丢弃),必须在这里先过滤,不能指望+ // 下游 service 补(2026-07 review 第 16 轮:MCP create_worker / 缓存默认+ // 路由都走这条快照,不经过 renderer 侧选择器的过滤)。const routableModels = (provider: ProviderView, agent: AgentKind) =>(provider.models[agent] ?? []).filter((model) =>diff --git a/apps/desktop/src/main/maker-ipc/scheduleGenerationRoute.ts b/apps/desktop/src/main/maker-ipc/scheduleGenerationRoute.tsindex ed275ff448..639c9915f1 100644--- a/apps/desktop/src/main/maker-ipc/scheduleGenerationRoute.ts+++ b/apps/desktop/src/main/maker-ipc/scheduleGenerationRoute.ts@@ -1,5 +1,6 @@import {effectiveSourceIdForModel,+ isAgentSelectableModel,type AgentKind,type ProviderView,} from '@cindy/model-providers';@@ -48,7 +49,13 @@ export function resolveBoundSessionGenerationRoute(input: {? input.providers.find((provider) =>provider.id === explicitProviderId&& provider.agents.includes(agentKind)- && (provider.models[agentKind] ?? []).some((candidate) => candidate.id === model),+ // 只按 id 匹配会漏检 mode:同一 id 在该来源下若是非聊天类型模型的具体条目,+ // 请求会被 fail-open 送进 image/audio/embedding 端点(2026-07 review 第 17 轮)。+ && (provider.models[agentKind] ?? []).some(+ (candidate) =>+ candidate.id === model+ && isAgentSelectableModel(candidate, { userProvider: provider.source === 'user' }),+ ),): undefined;// A session's explicit source is part of its identity. If that source nodiff --git a/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts b/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.tsindex 6417534a72..165744f584 100644--- a/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts+++ b/apps/desktop/src/renderer/__tests__/draftModelCalibration.test.ts@@ -114,6 +114,32 @@ describe('pickConnectedModelForAgent', () => {).toBeNull();});+ it('跳过非聊天模型(issue #882 第 3 点,2026-07 review):唯一调用方已预先过滤,但本函数是导出的公共工具,自己也要防', () => {+ const withNonChat = provider('xd', true, {+ 'claude-code': [+ { ...model('gpt-image-2'), mode: 'image_generation' },+ model('claude-sonnet-5'),+ ],+ });+ // preferredModelId 本身就是非聊天模型 → 不接受,落到第一个聊天模型+ expect(pickId([withNonChat], 'claude-code', 'gpt-image-2')).toBe('claude-sonnet-5');+ // 首个可用模型兜底同样跳过非聊天模型+ expect(pickId([withNonChat], 'claude-code', 'claude-opus-4-8')).toBe('claude-sonnet-5');+ });++ it('用户自定义供应商显式配置的模型不被 id 启发式误杀(2026-07 review 第 25 轮)', () => {+ // flux-image-x 的 id 撞上 /image/ 启发式,但它来自 source:'user' 的自定义供应商且+ // group 是未知的 custom:*,isAgentSelectableModel 有意放行 —— 校准不得把它当能力模型跳过。+ const userProvider = {+ ...provider('custom-p', true, {+ 'claude-code': [model('flux-image-x', { group: 'custom:custom-p' })],+ }),+ source: 'user',+ } as unknown as ProviderView;+ expect(pickId([userProvider], 'claude-code', 'flux-image-x')).toBe('flux-image-x');+ expect(pickId([userProvider], 'claude-code', 'claude-opus-4-8')).toBe('flux-image-x');+ });+it('取该供应商模型里排序第一个,而不是清单里排前面的那个', () => {// 产品定稿:「可用的里面选第一个」= 目录排序第一,不是数组顺序第一。const gateway = provider('xd', true, {diff --git a/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts b/apps/desktop/src/renderer/__tests__/sourceSwitch.test.tsindex e3689ca30d..29ced625c1 100644--- a/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts+++ b/apps/desktop/src/renderer/__tests__/sourceSwitch.test.ts@@ -148,6 +148,61 @@ describe('resolveSourceSwitch', () => {expect(r.reconciledEffort).toBeUndefined();});+ it('reconcile 候选按 mode 准入过滤(issue #882 review):mode 非 chat 且 id 落 categorize 兜底组时不被选中', () => {+ // 故意造一个 id 不含任何非聊天关键词、只能靠 categorize 兜底落 'china' 的场景:+ // 旧实现用纯 id 正则的 categorize 判定候选分组,'china' 在 CHAT_VENDOR_CATEGORY_ORDER+ // 里、会被当成有效候选;换成 mode 优先的 classifyModel 后,mode='embedding' 权威判定+ // 为非聊天,不再落进任何厂商组,候选列表为空。该来源只 offer 这一个模型,+ // 没有别的候选可选 —— 必须不选中它、保持模型不变,而不是"退而求其次"选一个非聊天模型。+ const r = resolveSourceSwitch({+ provider: provider('xd', ['some-vendor-neutral-id']),+ agent: AGENT,+ currentModelId: 'gpt-5.4', // 不被该来源 offer,触发 reconcile+ visibleModels: [{ id: 'some-vendor-neutral-id', efforts: [], mode: 'embedding' }],+ remembered: undefined,+ });+ expect(r.reconciledModelId).toBeUndefined();+ });++ it('候选校验目标 provider 自己的那份数据,不是 visibleModels 并集里的同 id 条目(issue #882,2026-07 review:fresh evidence——并集条目可能来自另一个 provider 的聊天分类,和目标 provider 自己的 mode 不一致)', () => {+ // 目标 provider('xd')上 'shared-id' 是非聊天(image_generation);但 visibleModels+ // 并集里同 id 的条目标了 mode='chat'(模拟它是从另一个 provider 的聊天分类合并过来的)。+ const targetProviderWithNonChatCopy = {+ id: 'xd',+ name: 'xd',+ models: { [AGENT]: [{ id: 'shared-id', mode: 'image_generation' }] },+ } as unknown as ProviderView;++ const r = resolveSourceSwitch({+ provider: targetProviderWithNonChatCopy,+ agent: AGENT,+ currentModelId: 'gpt-5.4', // 不被 xd offer,触发 reconcile+ visibleModels: [{ id: 'shared-id', efforts: ['low', 'high'], mode: 'chat' }],+ remembered: undefined,+ });+ // 不能选中它——目标 provider 自己的这份条目不是聊天模型,即便并集里同 id 条目标了 chat。+ expect(r.reconciledModelId).toBeUndefined();+ });++ it('记忆命中校验目标 provider 自己的那份数据(同上,remembered 分支)', () => {+ const targetProviderWithNonChatCopy = {+ id: 'xd',+ name: 'xd',+ models: { [AGENT]: [{ id: 'shared-id', mode: 'image_generation' }] },+ } as unknown as ProviderView;++ const r = resolveSourceSwitch({+ provider: targetProviderWithNonChatCopy,+ agent: AGENT,+ currentModelId: 'gpt-5.4',+ visibleModels: [{ id: 'shared-id', efforts: ['low', 'high'], mode: 'chat' }],+ remembered: { model: 'shared-id', effort: 'high' },+ });+ // 记忆指向的模型在目标 provider 上不是聊天模型 → 记忆失效,不恢复它;也没有别的候选。+ expect(r.reconciledModelId).toBeUndefined();+ expect(r.reconciledEffort).toBeUndefined();+ });+it('无记忆 + 当前模型仍被 offer:全不动', () => {const r = resolveSourceSwitch({provider: provider('anthropic', ['claude-opus-4-8', 'claude-sonnet-4-6']),@@ -575,4 +630,24 @@ describe('isSelectedSourceDisconnected — 会话显式来源断连判定', () =}),).toBe(false);});++ it('选中来源仍连着,但这个模型在它上面已经不是聊天模型 → true(issue #882 第 3 点,2026-07 review)', () => {+ const nonChatView = {+ id: 'xd',+ name: 'xd',+ connected: true,+ agents: [AGENT],+ routing: { [AGENT]: {} },+ models: { [AGENT]: [{ id: MODEL_ID, mode: 'image_generation' }] },+ } as unknown as ProviderView;+ expect(+ isSelectedSourceDisconnected({+ providers: [nonChatView],+ agent: AGENT,+ modelId: MODEL_ID,+ selectedProviderId: 'xd',+ providersLoading: false,+ }),+ ).toBe(true);+ });});diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex c06fe07fc1..86865fa451 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -183,7 +183,7 @@ import { useAgentCapabilities, type AgentKind } from '@/hooks/useAgentCapabilitiimport { useConnectedSource } from '@/hooks/useConnectedSource';import { useProviders } from '@/hooks/useProviders';import { useDeviceProviders } from '@/hooks/useDeviceProviders';-import { effectiveSourceIdForModel, sourcesForModel } from '@cindy/model-providers';+import { chatEligibleSourcesForModel, effectiveSourceIdForModel } from '@cindy/model-providers';import { deriveModelsFromProviders, filterChatBridgedCodexProviders, resolveFastSupported } from '@/lib/providerModels';import {getProviderModelEffort,@@ -1260,11 +1260,14 @@ export function ChatInput({currentModelAgentKind,activeModel,);- // 已建会话(sessionId 在)按实际路由口径判(includeDisabled):运行中的会话不因- // 停用打断,请求仍走原路由,把停用当「无来源」会误禁 Send(PR #744 review 第十轮)。- // 草稿是新路由选择,保持准入口径(停用拷贝不算可发送来源)。+ // chatEligibleSourcesForModel(不是裸 sourcesForModel):非聊天模型即便"存在于某个+ // 已连接来源"也不算有可发送来源(issue #882 第 3 点,2026-07 review)——否则 Send+ // 会对着一个 image/embedding 端点放行,而不是显示这里的"去连接"空态。已建会话+ // (sessionId 在)按实际路由口径判(includeDisabled):运行中的会话不因停用打断,+ // 请求仍走原路由,把停用当「无来源」会误禁 Send(PR #744 review 第十轮)。草稿是+ // 新路由选择,保持准入口径(停用拷贝不算可发送来源)。const hasConnectedSendSource = currentModelAgentKind- ? sourcesForModel(sendProviders, activeModel, currentModelAgentKind, {+ ? chatEligibleSourcesForModel(sendProviders, activeModel, currentModelAgentKind, {onlyConnected: true,includeDisabled: !!sessionId,}).length > 0@@ -3373,15 +3376,17 @@ export function ChatInput({// 预检(通用、provider-aware): 当前模型在当前 agent 下「一个已连接来源都没有」// 时,不把请求扔给 SDK 等 401,改弹确认框引导用户去「设置 → 模型供应商」连接。// 取代过去仅 cc + 仅 api_key 的写法 —— 现在 OAuth / XD 网关 / 未来自定义供应商- // 都按 ProviderView.connected 统一计入(sourcesForModel onlyConnected),未来加新- // 供应商无需改这里。判定数据来自本地 IPC(useProviders),无网络往返、~ms 级。- // 只有「确实零已连接来源」才拦截;≥1 个直接放行(无弹窗)。currentModelAgentKind- // 解析不出(罕见:capabilities 未就绪)时不拦,交给下游处理,不误伤。+ // 都按 ProviderView.connected 统一计入(chatEligibleSourcesForModel onlyConnected),+ // 未来加新供应商无需改这里。判定数据来自本地 IPC(useProviders),无网络往返、+ // ~ms 级。只有「确实零已连接来源」才拦截;≥1 个直接放行(无弹窗)。+ // currentModelAgentKind 解析不出(罕见:capabilities 未就绪)时不拦,交给下游+ // 处理,不误伤。用 chatEligibleSourcesForModel 而非裸 sourcesForModel:+ // 非聊天来源不该被当成"可以发"放行(issue #882 第 3 点,2026-07 review)。if (currentModelAgentKind) {// 已建会话按实际路由口径判(includeDisabled,与上方 hasConnectedSendSource// 同则):运行中会话不因停用打断,最终 preflight 若按准入 rail 判会在全停时// 弹「去连接来源」把继续发送挡死(PR #744 review 第十八轮)。草稿保持准入口径。- const connectedSources = sourcesForModel(providers, activeModel, currentModelAgentKind, {+ const connectedSources = chatEligibleSourcesForModel(providers, activeModel, currentModelAgentKind, {onlyConnected: true,includeDisabled: !!sessionId,});diff --git a/apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts b/apps/desktop/src/renderer/components/new-chat/sourceSwitch.tsindex 0db27f3016..ff97331462 100644--- a/apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts+++ b/apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts@@ -11,43 +11,39 @@import type { Effort } from '@/lib/userPreferences.types';import type { ProviderModelChoice } from '@/state/providerModelMemory';import {+ CATEGORY_ORDER,+ CHAT_VENDOR_CATEGORY_ORDER,+ categorize,+ chatEligibleSourcesForModel,+ classifyModel,connectedProvidersForAgent,- providerOffersModel,- sourcesForModel,+ getModel,+ groupModelsForDisplay,+ groupOf,+ isAgentSelectableModel,+ isChatEligible,type AgentKind,+ type DisplayModel,+ type ModelCategory,type ProviderView,} from '@cindy/model-providers';-import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../../shared/subscriptionModels';-// 仅用于二级菜单分组展示, 不参与持久化或 onModelChange 数据流。-// 对话厂商组(anthropic..china)在前;非对话类型组(image/audio/video/embedding/other)在后——-// 后者收纳网关多出的图像 / 语音 / 视频 / 向量等模型(它们默认关、不能当 agent 用,仅分类展示)。-export type ModelCategory =- | 'anthropic'- | 'gpt'- | 'gpt-budget'- | 'grok'- | 'google'- | 'china'- | 'image'- | 'audio'- | 'video'- | 'embedding'- | 'other';--export const CATEGORY_ORDER: ModelCategory[] = [- 'anthropic',- 'gpt-budget',- 'gpt',- 'grok',- 'google',- 'china',- 'image',- 'audio',- 'video',- 'embedding',- 'other',-];+/**+ * 厂商分类 / 分组展示 / chat 准入判定的单点权威实现已收口到共享包+ * `@cindy/model-providers`(issue #882:mode 优先分类,id 正则只作兜底)。+ * 这里 re-export 保持 renderer 既有 import 路径(ModelSelector / ChatInput 等)不变,+ * 不再维护第二份 categorize/groupOf 拷贝——两份拷贝曾经各自修 bug、互相漂移。+ */+export {+ CATEGORY_ORDER,+ categorize,+ classifyModel,+ groupModelsForDisplay,+ groupOf,+ isChatEligible,+ type DisplayModel,+ type ModelCategory,+};/*** 厂商分组小标题的 i18n key 表(规则 18)。多处复用:ModelSelector 右栏分组标题、@@ -62,85 +58,26 @@ export const CATEGORY_LABEL_KEY: Record<ModelCategory, string> = {google: 'newChat.modelSelector.category.google',china: 'newChat.modelSelector.category.china',image: 'newChat.modelSelector.category.image',- audio: 'newChat.modelSelector.category.audio',video: 'newChat.modelSelector.category.video',+ tts: 'newChat.modelSelector.category.tts',+ stt: 'newChat.modelSelector.category.stt',+ realtime: 'newChat.modelSelector.category.realtime',embedding: 'newChat.modelSelector.category.embedding',+ compression: 'newChat.modelSelector.category.compression',other: 'newChat.modelSelector.category.other',};-// 按 model.id 前缀粗分类: claude-* → Anthropic, gpt-* → GPT, codex/* → 折扣GPT (gateway 低价路由),-// gemini-* → Google, 其余 (moonshotai/qwen/glm/...) 一律落到 China。新增国产模型不需要改这里。-export function categorize(id: string): ModelCategory {- if (id.startsWith('claude-')) return 'anthropic';- // 非对话类型(向量/图像/音频语音/视频)必须在通用 gpt- / gemini- 厂商规则**之前**判定,- // 否则 gpt-image-2 / gemini-3-pro-image / gpt-4o-transcribe 会被误归到 gpt / google。- // 这些是网关多返回的、不能当 agent 用的模型,默认关、仅按类型归类展示。- if (/embedding/.test(id) || id.startsWith('voyage/')) return 'embedding';- if (/image/.test(id)) return 'image';- if (- id.startsWith('elevenlabs/') ||- id.startsWith('gpt-4o-realtime') ||- /transcribe|audio|speech|tts|whisper|asr|gemini-omni/.test(id)- )- return 'audio';- if (/seedance|happyhorse|video|-t2v|-i2v|-r2v/.test(id)) return 'video';- if (id === 'ai-gateway-doc') return 'other';- // 订阅直连 GPT(chatgpt/ 前缀,经 responses-bridge)与网关 gpt- 同归 GPT 组;前缀常量走- // shared/subscriptionModels 单一入口,防与路由 / 记账 gate 漂移。- if (id.startsWith('gpt-') || id.startsWith(CHATGPT_MODEL_PREFIX)) return 'gpt';- if (id.startsWith('codex/')) return 'gpt-budget';- if (id.startsWith(XAI_MODEL_PREFIX) || id.startsWith('grok')) return 'grok';- if (id.startsWith('gemini-')) return 'google';- return 'china';-}--const KNOWN_CATEGORIES = new Set<string>(CATEGORY_ORDER);-/**- * 决定一个模型的厂商分组 —— **数据优先**:目录里带了合法 `group` 就用它,- * 否则回退到 id 前缀归类(categorize)。未知的 group 值(渲染层没有对应标签)也回退,- * 避免出现没有 i18n 标签的空分组。+ * resolveSourceSwitch 的最小模型形状:id + 该模型支持的 effort 档,外加可选的+ * `group`/`mode`——reconcile 候选过滤要靠 classifyModel 做 mode 优先判定+ * (issue #882 review:只传 id 时 mode 信号会丢,可能把非聊天模型选成 reconcile+ * 目标,见下方 resolveSourceSwitch 用法),不传时行为与历史一致(回退 id 正则)。*/-export function groupOf(model: { id: string; group?: string }): ModelCategory {- if (model.group && KNOWN_CATEGORIES.has(model.group)) return model.group as ModelCategory;- return categorize(model.id);-}--/** groupModelsForDisplay 的最小模型形状(只需 id + 可选 group / sortOrder)。 */-export interface DisplayModel {- id: string;- group?: string;- sortOrder?: number;-}--/**- * 选择器右栏的「分组 + 排序」纯逻辑 —— **完全由目录数据驱动**:- * 1. 先按 `sortOrder` 升序稳定排序(缺省排末尾,相等时保持入参顺序);- * 2. 按 `groupOf`(group 字段优先 / 前缀兜底)分桶;- * 3. 桶的先后 = 桶内首个模型在已排序列表里的出现序(= 该桶最小 sortOrder)。- * 返回有序的 { category, models } 列表;不依赖写死的 CATEGORY_ORDER 决定展示顺序。- */-export function groupModelsForDisplay<T extends DisplayModel>(- models: readonly T[],-): Array<{ category: ModelCategory; models: T[] }> {- const sorted = [...models].sort(- (a, b) =>- (a.sortOrder ?? Number.POSITIVE_INFINITY) - (b.sortOrder ?? Number.POSITIVE_INFINITY),- );- const map = new Map<ModelCategory, T[]>();- for (const m of sorted) {- const cat = groupOf(m);- const list = map.get(cat) ?? [];- list.push(m);- map.set(cat, list);- }- return [...map.entries()].map(([category, list]) => ({ category, models: list }));-}--/** resolveSourceSwitch 的最小模型形状(只需 id + 该模型支持的 effort 档)。 */export interface SwitchModel {id: string;efforts: readonly Effort[];+ group?: string;+ mode?: string;}/**@@ -159,6 +96,27 @@ export interface SwitchModel {* 返回的 reconciledModelId 仅在「模型确实变化」时给出(等于当前模型视为不变,返 undefined);* reconciledEffort 仅在能从记忆恢复时给出。两者都为空 = 调用方保持当前 model/effort。*/+/**+ * 目标 provider 上**这个具体条目**是否是聊天模型(issue #882 第 3 点,2026-07+ * review)。resolveSourceSwitch 决定的是"切到 provider 之后用哪个 model",必须验+ * provider 自己的那份数据——`visibleModels`(跨 provider 的并集)里的同 id 条目可能+ * 来自另一个 provider 的聊天分类,和目标 provider 自己的这份 mode 可能不一致;+ * providerOffersModel 同理只看 id 是否存在,不看 mode。两者都不能替代这个检查。+ */+function isModelChatEligibleOnProvider(+ provider: ProviderView,+ modelId: string,+ agent: AgentKind,+): boolean {+ const model = getModel(provider, modelId, agent);+ // provider-aware 谓词:用户自定义供应商显式配置的模型带未知 group,id 撞上能力+ // 启发式时不能被误杀(2026-07 review 第 25 轮)。+ return (+ model !== undefined &&+ isAgentSelectableModel(model, { userProvider: provider.source === 'user' })+ );+}+export function resolveSourceSwitch(args: {provider: ProviderView;agent: AgentKind;@@ -174,7 +132,7 @@ export function resolveSourceSwitch(args: {const memUsable =!!remembered &&- providerOffersModel(provider, remembered.model, agent) &&+ isModelChatEligibleOnProvider(provider, remembered.model, agent) &&visibleModels.some((m) => m.id === remembered.model) &&isVisible(remembered.model);@@ -182,12 +140,19 @@ export function resolveSourceSwitch(args: {targetModel = remembered.model;const tm = visibleModels.find((m) => m.id === remembered.model);if (tm && tm.efforts.includes(remembered.effort)) targetEffort = remembered.effort;- } else if (currentModelId && !providerOffersModel(provider, currentModelId, agent)) {- const ordered = CATEGORY_ORDER.filter(- (c) => c !== 'image' && c !== 'audio' && c !== 'video' && c !== 'embedding' && c !== 'other',- ).flatMap((c) => visibleModels.filter((m) => categorize(m.id) === c));+ } else if (+ currentModelId &&+ !isModelChatEligibleOnProvider(provider, currentModelId, agent)+ ) {+ // 只在聊天厂商组里找候选(issue #882):非聊天类型(image/video/tts/stt/realtime/+ // embedding/compression/other)不该被 reconcile 选中。用 classifyModel(mode 优先,+ // 无 mode 才回退 id 正则)而不是纯 id 正则的 categorize——否则 mode 标为非聊天、+ // 但 id 落进 categorize 兜底组(如 china)的模型会绕过准入被选中(2026-07 review)。+ const ordered = CHAT_VENDOR_CATEGORY_ORDER.flatMap((c) =>+ visibleModels.filter((m) => classifyModel(m) === c),+ );targetModel = ordered.find(- (m) => providerOffersModel(provider, m.id, agent) && isVisible(m.id),+ (m) => isModelChatEligibleOnProvider(provider, m.id, agent) && isVisible(m.id),)?.id;}@@ -221,11 +186,16 @@ export function isSelectedSourceDisconnected(args: {}): boolean {const { providers, agent, modelId, selectedProviderId, providersLoading } = args;if (providersLoading || !agent || !selectedProviderId) return false;- // 实际路由口径(includeDisabled):本判定只回答「选中来源还连着吗」,服务的是- // **已建会话**的显示与发送门禁。停用(suspended / 该拷贝 disabled)是准入轴,- // 不打断运行中的会话 —— 按准入过滤后的 rail 判会把停用当断开,Send 被误禁- // (PR #744 review 第十轮)。- const sources = sourcesForModel(providers, modelId, agent, { includeDisabled: true });+ // chatEligibleSourcesForModel + includeDisabled:选中来源若还在但这个 id 在它上面+ // 已经不是聊天模型了(mode 变化),也要判"断连"——否则这里说"没断连"、+ // effectiveSourceIdForModel 却解析不出可用来源,界面显示能发、实际发不出去+ // (2026-07 review:UI 可用性判断与路由解析必须同一份口径)。但停用(suspended /+ // 该拷贝 disabled)是**另一根**准入轴,不打断运行中的会话 —— 按准入过滤后的+ // rail 判会把停用当断开,Send 被误禁(PR #744 review 第十轮),故传+ // includeDisabled。+ const sources = chatEligibleSourcesForModel(providers, modelId, agent, {+ includeDisabled: true,+ });return !sources.some((p) => p.id === selectedProviderId);}diff --git a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsxindex fa3b7d4ca5..60a6cc1d4b 100644--- a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx@@ -5,7 +5,7 @@* 静默改写;非 thread 渠道通过 `/new` 显式应用。*/-import { connectedProvidersForAgent, providerOffersModel } from '@cindy/model-providers';+import { connectedProvidersForAgent, getModel, isAgentSelectableModel } from '@cindy/model-providers';import { MessageSquare } from 'lucide-react';import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -118,7 +118,15 @@ export function ImDefaultSettingsSection({const provider = connectedProvidersForAgent(providers, agentKind).find((p) => p.id === providerId,);- return provider && providerOffersModel(provider, modelId, agentKind) ? providerId : null;+ if (!provider) return null;+ // 只看 id 是否存在不够(issue #882 第 3 点,2026-07 review 第 18 轮):该来源这份+ // 具体条目若是非聊天类型,不能落成 IM 渠道的显式默认来源,否则渠道发消息会打进+ // image/audio/embedding 端点。+ const catalogModel = getModel(provider, modelId, agentKind);+ return catalogModel &&+ isAgentSelectableModel(catalogModel, { userProvider: provider.source === 'user' })+ ? providerId+ : null;},[providers],);diff --git a/apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx b/apps/desktop/src/renderer/components/settings/SubagentModelSection.tsxindex 28e32caa2a..544b6b8a36 100644--- a/apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx+++ b/apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx@@ -7,7 +7,7 @@import { useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';-import { connectedProvidersForAgent, providerOffersModel, visibleModelUnion } from '@cindy/model-providers';+import { connectedProvidersForAgent, getModel, isAgentSelectableModel, visibleModelUnion } from '@cindy/model-providers';import { ClaudeMark } from '@/components/icons/ClaudeMark';import { CodexMark } from '@/components/icons/CodexMark';@@ -57,7 +57,13 @@ export function SubagentModelSection() {const provider = connectedProvidersForAgent(providers, 'claude-code').find((p) => p.id === providerId,);- return provider && providerOffersModel(provider, modelId, 'claude-code')+ if (!provider) return null;+ // 只看 id 是否存在不够(issue #882 第 3 点,2026-07 review 第 18 轮):该来源这份+ // 具体条目若是非聊天类型,不能落成子代理模型的显式来源,否则派发会打进+ // image/audio/embedding 端点。+ const catalogModel = getModel(provider, modelId, 'claude-code');+ return catalogModel &&+ isAgentSelectableModel(catalogModel, { userProvider: provider.source === 'user' })? providerId: null;},@@ -119,12 +125,17 @@ export function SubagentModelSection() {const sourceDisconnected = Boolean(!providersLoading &&settings.claudeCodeProviderId &&- !connectedProvidersForAgent(providers, 'claude-code').some(- (p) =>- p.id === settings.claudeCodeProviderId &&- (settings.claudeCode === null ||- providerOffersModel(p, settings.claudeCode, 'claude-code')),- ),+ !connectedProvidersForAgent(providers, 'claude-code').some((p) => {+ if (p.id !== settings.claudeCodeProviderId) return false;+ if (settings.claudeCode === null) return true;+ // 只查 id 会漏掉「该来源这份具体条目已经是非聊天类型」的情况(issue #882+ // 第 3 点,2026-07 review 第 18 轮)——同样算「不可用」,需要断开态提示。+ const catalogModel = getModel(p, settings.claudeCode, 'claude-code');+ return (+ catalogModel !== undefined &&+ isAgentSelectableModel(catalogModel, { userProvider: p.source === 'user' })+ );+ }),);// 「连接来源」CTA 只在「目录层面零可选模型」时接线:零已连接来源,或来源连接着// 但动态模型发现返回空清单 —— 两者面板都是零分段 no-results,需要恢复入口diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsxindex ba2c329411..25cb8a6e5a 100644--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx@@ -60,19 +60,23 @@ const AGENT_LABEL: Record<AgentKind, string> = {};/**- * 分组折叠态(仅 UI 展示,按设备记忆)。非对话类型组(图像/音频/视频/向量/其它)默认折叠——- * 它们是能力模型,不参与对话模型选择,默认收起让列表清爽;对话厂商组默认展开;- * 底部「已停用」分区(key = '__disabled')默认**展开**——区里有东西说明是用户主动停的,- * 找回路径要一眼可见。只存用户显式改过的组(与 modelVisibilityPrefs 同哲学),搜索时强制全展开。+ * 分组折叠态(仅 UI 展示,按设备记忆)。非对话类型组(图像/视频/语音合成/语音转写/+ * 实时音频/向量/压缩/其它)默认折叠——它们是网关多出的、不能当 agent 用的模型,默认+ * 收起让列表清爽;对话厂商组默认展开;底部「已停用」分区(key = '__disabled')默认+ * **展开**——区里有东西说明是用户主动停的,找回路径要一眼可见。只存用户显式改过的组+ * (与 modelVisibilityPrefs 同哲学:未改的跟随默认),搜索时强制全展开。* CAPABILITY_CATEGORIES 同时就是「能力模型组」的判定(成员 = classification 的非 agent 分组)。*/const COLLAPSE_STORAGE_KEY = 'xdt:modelListCollapsedGroups:v1';const DISABLED_GROUP_KEY = '__disabled';const CAPABILITY_CATEGORIES = new Set<ModelCategory>(['image',- 'audio','video',+ 'tts',+ 'stt',+ 'realtime','embedding',+ 'compression','other',]);const DEFAULT_COLLAPSED_CATEGORIES = CAPABILITY_CATEGORIES;diff --git a/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsxindex c4e8e8eacb..5632310167 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/SubagentModelSectionRendering.test.tsx@@ -43,7 +43,10 @@ vi.mock('@/state/modelVisibilityPrefs', () => ({const providersMock = vi.hoisted(() => ({loading: false,// 可按用例清空:provider 连接着但动态模型发现为空清单的场景。- claudeModels: [{ id: 'claude-opus-5' }, { id: 'claude-haiku-4-5' }] as Array<{ id: string }>,+ claudeModels: [{ id: 'claude-opus-5' }, { id: 'claude-haiku-4-5' }] as Array<{+ id: string;+ mode?: string;+ }>,}));vi.mock('@/hooks/useProviders', () => ({useProviders: () => ({@@ -214,6 +217,32 @@ describe('SubagentModelSection standard panel contract', () => {});});+ it('narrows to null when the picked provider only offers a non-chat copy of the model id (issue #882 第 3 点, 2026-07 review 第 18 轮)', async () => {+ // 只查 id 存在(旧 providerOffersModel)会误放行:anthropic 上的 claude-opus-5+ // 这份具体条目已经是非聊天类型,不能落成子代理模型的显式来源。+ providersMock.claudeModels = [+ { id: 'claude-opus-5', mode: 'embedding' },+ { id: 'claude-haiku-4-5' },+ ];+ render(<SubagentModelSection />);+ fireEvent.click(await screen.findByTestId('pick-provider-row'));+ await waitFor(() => expect(settingsSet).toHaveBeenCalledTimes(1));+ expect(settingsSet).toHaveBeenCalledWith({+ claudeCode: 'claude-opus-5',+ claudeCodeProviderId: null,+ });+ });++ it('flags a connected provider as disconnected when its model entry is non-chat (issue #882 第 3 点, 2026-07 review 第 18 轮)', async () => {+ providersMock.claudeModels = [{ id: 'claude-opus-5', mode: 'embedding' }];+ settingsGet.mockResolvedValue(+ makeState({ claudeCode: 'claude-opus-5', claudeCodeProviderId: 'anthropic' }),+ );+ render(<SubagentModelSection />);+ const selector = await screen.findByTestId('model-selector');+ expect(selector.dataset.sourceDisconnected).toBe('true');+ });+it('clears both model and providerId when returning to unspecified', async () => {settingsGet.mockResolvedValue(makeState({ claudeCode: 'claude-opus-5', claudeCodeProviderId: 'anthropic' }),diff --git a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsxindex db7d00f5c5..018bff16d6 100644--- a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx@@ -6,6 +6,7 @@ import {connectedProvidersForAgent,effectiveSourceIdForModel,getModel,+ isAgentSelectableModel,modelSupportsFastMode,providerOffersModel,} from '@cindy/model-providers';@@ -200,7 +201,17 @@ export function CreateWorkerPopover({const provider = routableProviders.find((p) => p.id === candidate);if (!provider || !providerOffersModel(provider, modelId, agent)) return null;const catalogModel = getModel(provider, modelId, agent);- return catalogModel && catalogModel.disabled !== true ? candidate : null;+ // 非聊天模型不该被当成 worker 的有效显式来源(issue #882 第 3 点,2026-07+ // review):providerOffersModel 只看 id 是否存在,不看 mode——记忆来源的这份+ // 具体条目若是非聊天,即便面板列表(activeModels,来自另一个来源的聊天分类)+ // 里还看得到同 id,也不能提交这个来源,否则请求会发到 image/audio 端点。+ // 停用(disabled)判据同上方 routableProviders 注:隐藏不再收窄(2026-07+ // 启用/显示双轴拆分),故不查 isModelEnabled——记忆来源被隐藏仍合法可路由。+ return catalogModel &&+ catalogModel.disabled !== true &&+ isAgentSelectableModel(catalogModel, { userProvider: provider.source === 'user' })+ ? candidate+ : null;},[agent, deviceId, routableProviders],);diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex a97fd1947a..88d290661d 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -296,7 +296,13 @@ function draftEnableOrcaOptions(// 显式路由过去。「隐藏」不再收窄 —— 隐藏只是陈列过滤,记忆来源被隐藏仍然合法可用// (2026-07 启用/显示双轴拆分)。suspended 供应商已被 connectedProvidersForAgent 剔除。const catalogModel = getModel(provider, cfg.model, workerAgent);- return catalogModel && catalogModel.disabled !== true ? cfg.providerId : undefined;+ // 非聊天模型不该被当成持久化草稿的有效来源(issue #882 第 3 点,2026-07 review),+ // 与 CreateWorkerPopover.narrowProviderSource 同规则同理由。+ return catalogModel &&+ catalogModel.disabled !== true &&+ isAgentSelectableModel(catalogModel, { userProvider: provider.source === 'user' })+ ? cfg.providerId+ : undefined;})();return {workerAgent,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.tsxindex 8341842fda..6295e18c63 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@@ -50,6 +50,7 @@ const mocks = vi.hoisted(() => ({supportsFastMode?: boolean;efforts?: string[];defaultEffort?: string | null;+ mode?: string;/** 停用轴(buildRegistry 烘焙的视图层标志;narrowProviderSource 消费)。 */disabled?: boolean;}>@@ -679,6 +680,40 @@ describe('CreateWorkerPopover', () => {);});+ it('narrows a remembered provider whose model entry is non-chat (issue #882 第 3 点, 2026-07 review)', async () => {+ // 记忆来源上这个 model id 的具体条目是非聊天(mode='image_generation')——+ // providerOffersModel 只看 id 是否存在,不会挡住它;narrowProviderSource 必须+ // 自己叠加 isChatEligible,否则会把这个来源提交给 main,请求发到 image 端点。+ window.localStorage.setItem(+ 'workerCreationPrefs',+ JSON.stringify({+ lastAgent: 'codex',+ codex: { model: 'gpt-5.5', effort: 'high', fast: false, providerId: 'openai' },+ }),+ );+ mocks.localProviders = [+ {+ id: 'openai',+ name: 'OpenAI',+ connected: true,+ agents: ['codex'],+ models: { codex: [{ id: 'gpt-5.5', mode: 'image_generation' }], 'claude-code': [] },+ },+ ];+ mocks.modelsByAgent.codex = [model('gpt-5.5')];+ mocks.capabilitiesByAgent.codex = { availableModels: [{ id: 'gpt-5.5' }] };+ const onCreate = vi.fn();++ render(<CreateWorkerPopover open onClose={vi.fn()} onCreate={onCreate} />);+ await waitFor(() =>+ expect(screen.getByTestId('model-selector').dataset.currentProvider).toBe(''),+ );+ fireEvent.click(screen.getByRole('button', { name: 'orca.createWorker.submit' }));+ await waitFor(() =>+ expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({ providerId: null })),+ );+ });+it('resolves Fast against the effective default provider when no explicit source is set', async () => {// 未显式来源时 Fast 能力按生效默认来源自己的条目查,不用拍平并集的首来源值// (codex review:默认来源不支持时不能把 stale true 带到提交)。diff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.tsindex 52b1b69436..6bacd7b696 100644--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts@@ -26,6 +26,12 @@ export interface ModelDescriptor {displayName: string;/** 目录分组 id(如 'gpt-budget'): 折扣版与官方版 displayName 同名, 靠它区分。 */group?: string;+ /**+ * Gateway 原生 mode(issue #882)。availableModels 派生时已经过 isChatEligible+ * 过滤,这里透传只是让下游按 model 二次分类的逻辑(如 resolveSourceSwitch 的+ * classifyModel)拿到 mode,不必回读目录(2026-07 review)。+ */+ mode?: string;description?: string;contextWindow: number;efforts: readonly Effort[];diff --git a/apps/desktop/src/renderer/hooks/useConnectedSource.ts b/apps/desktop/src/renderer/hooks/useConnectedSource.tsindex fccbac84c0..8c904d56d4 100644--- a/apps/desktop/src/renderer/hooks/useConnectedSource.ts+++ b/apps/desktop/src/renderer/hooks/useConnectedSource.ts@@ -16,7 +16,7 @@import { useMemo } from 'react';-import { connectedProvidersForAgent, sourcesForModel, type AgentKind } from '@cindy/model-providers';+import { chatEligibleSourcesForModel, connectedProvidersForAgent, type AgentKind } from '@cindy/model-providers';import { useProviders } from './useProviders';@@ -32,8 +32,12 @@ export function useConnectedSource(agent: AgentKind | null, modelId?: string): Uconst hasConnectedSource = useMemo(() => {if (!agent) return false;+ // chatEligibleSourcesForModel(不是裸 sourcesForModel):非聊天模型不该被判定为+ // "有可用来源"(issue #882 第 3 点,2026-07 review)——本 hook 是整个产品"要不要+ // 进连接来源空态"的唯一真相,漏这个过滤会让 ModelSelector CTA 和 Send 按钮对+ // 一个非聊天模型显示"已连接、可以发"。return modelId- ? sourcesForModel(providers, modelId, agent).length > 0+ ? chatEligibleSourcesForModel(providers, modelId, agent).length > 0: connectedProvidersForAgent(providers, agent).length > 0;},[providers, agent, modelId],diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ee05b4beb8..fe41e5885b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4389,9 +4389,12 @@"google": "Google","china": "Domestic","image": "Image",- "audio": "Audio & Speech","video": "Video",+ "tts": "Text to Speech",+ "stt": "Speech to Text",+ "realtime": "Realtime Audio","embedding": "Embeddings",+ "compression": "Compression","other": "Other"},"search": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 43cb8786e0..b571aebb9a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4388,9 +4388,12 @@"google": "Google","china": "国内","image": "画像",- "audio": "音声","video": "動画",+ "tts": "音声合成",+ "stt": "音声認識",+ "realtime": "リアルタイム音声","embedding": "埋め込み",+ "compression": "圧縮","other": "その他"},"search": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex aada31ef19..b577fa1a70 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4388,9 +4388,12 @@"google": "Google","china": "국내","image": "이미지",- "audio": "오디오·음성","video": "비디오",+ "tts": "음성 합성",+ "stt": "음성 인식",+ "realtime": "실시간 음성","embedding": "임베딩",+ "compression": "압축","other": "기타"},"search": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 02d07140ae..74f3b83665 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4388,9 +4388,12 @@"google": "Google","china": "国内","image": "图像",- "audio": "音频语音","video": "视频",+ "tts": "语音合成",+ "stt": "语音转写",+ "realtime": "实时语音","embedding": "向量",+ "compression": "压缩","other": "其它"},"search": {diff --git a/apps/desktop/src/renderer/lib/draftModelCalibration.ts b/apps/desktop/src/renderer/lib/draftModelCalibration.tsindex 5ef8baf1a5..6c0dd30de4 100644--- a/apps/desktop/src/renderer/lib/draftModelCalibration.ts+++ b/apps/desktop/src/renderer/lib/draftModelCalibration.ts@@ -13,6 +13,7 @@import {connectedProvidersForAgent,+ isAgentSelectableModel,type AgentKind,type CatalogModel,type ProviderView,@@ -39,16 +40,25 @@ function providersByPreference(}/**- * 该供应商在这个 agent 下排序第一的**默认可见**模型。+ * 该供应商在这个 agent 下排序第一的**默认可见的聊天**模型。** 默认收起的模型不参与:它们在选择器里根本不显示,选中了等于让用户面对一个自己找不到的默认* 模型。整组都收起时退回纯排序第一 —— 有个能用的默认,好过让这个供应商整体落空。+ *+ * 聊天准入(isAgentSelectableModel)是硬门槛,不参与"整组收起退回"的放宽:挑到的模型直接被+ * 当成会话默认模型使用,非聊天模型(图像/向量/TTS 等,issue #882 第 3 点)漏进来就是"草稿+ * 默认模型选中一个不能聊天的模型"。用 provider-aware 谓词而非裸 isChatEligible:用户自定义+ * 供应商显式配置的模型(未知 group)是合法聊天模型,id 撞上能力启发式(如 flux-image-x)+ * 不该被误杀(2026-07 review 第 25 轮)。*/function firstModelByOrder(provider: ProviderView, agent: AgentKind): CatalogModel | undefined {- const models = provider.models[agent] ?? [];- if (models.length === 0) return undefined;- const visible = models.filter((m) => m.defaultEnabled !== false);- const pool = visible.length > 0 ? visible : models;+ const userProvider = provider.source === 'user';+ const chatModels = (provider.models[agent] ?? []).filter((m) =>+ isAgentSelectableModel(m, { userProvider }),+ );+ if (chatModels.length === 0) return undefined;+ const visible = chatModels.filter((m) => m.defaultEnabled !== false);+ const pool = visible.length > 0 ? visible : chatModels;// slice() 再 sort:sort 原地改数组,直接排会打乱传入的 ProviderView 的清单顺序。return pool.slice()@@ -86,6 +96,10 @@ export interface PickedConnectedModel {* 提供它」会把它们原样留下,用户继续用一个在默认选择器里根本看不到的模型* (PR #1076 review 第三轮)。真正被用户选过的模型不受影响:那由 `chosenByUser` 在* `calibrateDraftModel` 里更早短路,压根走不到这里。+ *+ * 第 1 步同样卡聊天准入(issue #882 第 3 点):`preferredModelId` 在该来源的拷贝若是+ * 非聊天类型(mode/分类为图像等),不能因"id 存在且默认可见"就保留 —— 挑到的模型直接+ * 被当成会话默认模型使用。用 provider-aware 谓词,理由见 firstModelByOrder。*/export function pickConnectedModelForAgent(providers: readonly ProviderView[],@@ -96,7 +110,11 @@ export function pickConnectedModelForAgent(if (ranked.length === 0) return null;for (const provider of ranked) {const preferred = (provider.models[agent] ?? []).find((m) => m.id === preferredModelId);- if (preferred && preferred.defaultEnabled !== false) {+ if (+ preferred &&+ preferred.defaultEnabled !== false &&+ isAgentSelectableModel(preferred, { userProvider: provider.source === 'user' })+ ) {return { model: preferredModelId, providerId: provider.id };}}diff --git a/apps/desktop/src/renderer/lib/providerModels.ts b/apps/desktop/src/renderer/lib/providerModels.tsindex 8e1274c314..888e1956ec 100644--- a/apps/desktop/src/renderer/lib/providerModels.ts+++ b/apps/desktop/src/renderer/lib/providerModels.ts@@ -40,6 +40,7 @@ function toDescriptor(m: CatalogModel): ModelDescriptor {if (m.description !== undefined) d.description = m.description;if (m.effortDisplayNames !== undefined) d.effortDisplayNames = m.effortDisplayNames;if (m.supportsFastMode !== undefined) d.supportsFastMode = m.supportsFastMode;+ if (m.mode !== undefined) d.mode = m.mode;return d;}@@ -154,6 +155,11 @@ export function deriveModelsFromProviders(if (opts?.admissionFiltered &&(m.disabled === true ||+ // 非聊天模型同样不进 picker(issue #882 第 3 点):isAgentSelectableModel 现在+ // 内部就是 isChatEligible(+ userProvider 例外),与 main 侧+ // catalog-to-descriptors.ts deriveAvailableModels 用的同一份权威判定+ // 保持一致——但只在 admissionFiltered 时生效,不能无条件开(见上方函数+ // 文档:current-model 元数据查询不能被这个轴过滤掉)。!isAgentSelectableModel(m, { userProvider: provider.source === 'user' }))) {continue;diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.tsindex b68919bf9f..7f2b4fdd9b 100644--- a/apps/desktop/src/shared/modelAccess.ts+++ b/apps/desktop/src/shared/modelAccess.ts@@ -153,6 +153,14 @@ export interface ModelGroupPricing {export interface ModelAccessGatewayModel extends ModelGroupPricing {id: string;+ /**+ * Gateway 原生 mode(issue #882:权威分类字段,字段值不改名)。原样透传,可能+ * 缺省(旧缓存 / 服务端尚未覆盖到的模型)——**不代表**本条目已被服务端判定+ * 为聊天模型,是否可进 Agent availableModels 仍由客户端 isChatEligible 判定+ * (mode==='chat' 才算;缺省时回退 classification.ts 的 id 正则兜底),见+ * @cindy/model-providers classifyModel / isChatEligible。+ */+ mode?: string;/*** Gateway 可选的币种声明。当前 Cindy AI 价格目录仍以构建 region 的渠道契约* 为准;该字段仅保留 wire 兼容,不能让同一构建产生混合币种目录。diff --git a/apps/mobile/src/__tests__/providerModelSections.test.ts b/apps/mobile/src/__tests__/providerModelSections.test.tsindex 90e6322333..87e851b359 100644--- a/apps/mobile/src/__tests__/providerModelSections.test.ts+++ b/apps/mobile/src/__tests__/providerModelSections.test.ts@@ -230,6 +230,20 @@ describe('isSelectedSourceDisconnected', () => {error: null,})).toBe(false);});++ it('reports disconnected when the selected source\'s copy of the id is non-chat (issue #882, 2026-07 review: same as desktop sourceSwitch.ts)', () => {+ const nonChatProviders = [+ provider('xd', { codex: [{ ...model('shared-id'), mode: 'image_generation' }] }),+ ];+ expect(isSelectedSourceDisconnected({+ providers: nonChatProviders,+ providerId: 'xd',+ modelId: 'shared-id',+ agentKind: 'codex',+ loading: false,+ error: null,+ })).toBe(true);+ });});describe('resolveRowSelection —— 选行落点(effort 优先级与桌面共享实现同源)', () => {diff --git a/apps/mobile/src/session/providerModelSections.ts b/apps/mobile/src/session/providerModelSections.tsindex c455332c36..5326387c51 100644--- a/apps/mobile/src/session/providerModelSections.ts+++ b/apps/mobile/src/session/providerModelSections.ts@@ -14,12 +14,12 @@*/import {actualSourceIdForModel,+ chatEligibleSourcesForModel,connectedProvidersForAgent,effectiveSourceIdForModel,getModel,modelSupportsFastMode,nativeDefaultSourceId,- sourcesForModel,type ProviderView,} from '@cindy/model-providers/registry';import {@@ -163,9 +163,12 @@ export function isSelectedSourceDisconnected(args: {error: string | null;}): boolean {if (!args.providerId || args.loading || args.error !== null) return false;- // 实际路由口径(includeDisabled):本判定只回答「选中来源还连着吗」,停用是准入轴,- // 不打断已建会话 —— 按准入 rail 判会把停用当断开误报错误态(桌面同款)。- return !sourcesForModel([...args.providers], args.modelId, args.agentKind, {+ // chatEligibleSourcesForModel + includeDisabled(issue #882 第 3 点 与 PR #744+ // 停用轴合流,2026-07 review):与桌面 sourceSwitch.ts 的 isSelectedSourceDisconnected+ // 同一份口径——选中来源若还在但这个 id 在它上面已经不是聊天模型了,也要判"断连",+ // 不能只看 id 是否存在;但停用(disabled/suspended)是**另一根准入轴**,不打断已建+ // 会话 —— 按准入 rail 判会把停用当断开误报错误态(桌面同款),故传 includeDisabled。+ return !chatEligibleSourcesForModel([...args.providers], args.modelId, args.agentKind, {includeDisabled: true,}).some((provider) => provider.id === args.providerId);}diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 85748c6954..6e4fcf9606 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -156,6 +156,22 @@ OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入灵动岛角色皮肤名(设置页「图标皮肤」列表)。角色专名,四语统一保留拉丁原词,不做音译(避免「艾莉卡 / エリカ / 에리카」多套写法)。+### Compression++issue #882:模型管理/新对话选择器的分类标签,对应网关的文档压缩类模型(如 ai-gateway-doc)。此前被硬编码为笼统的 other 分类。++### Realtime Audio++issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mode=realtime 的实时多模态模型(如 gpt-realtime-2、gemini-omni-flash-preview)。++### Speech to Text++issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mode=audio_transcription 的语音转写/ASR 模型(如 gpt-4o-transcribe)。++### Text to Speech++issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mode=audio_speech 的语音合成模型(如 elevenlabs/eleven_v3)。原先与语音转写、实时音频混在一个笼统的「音频语音」分类里,本次拆分为独立类型。+### Not signed in跳过登录后应用内的账号状态名(侧边栏账号胶囊、设置页资料卡、语音服务提示,以及 main 侧不走 locale 的 model-visible 文案——已知 mcp-integrations/ghost.ts 的 GHOST_NOT_FOUND tool result,它会被模型读到并可能回显进对话,#907 review 补上)。**约束范围不限于 locale JSON**:guard 只扫 locale 文件,这类硬编码文案要人工找(见 engineering-conventions §5.1「Slack / IM 侧的文案不在任何 locale 文件里」同类问题)。2026-07-29 产品口径:面向用户只说「未登录」,不再叫「本地模式」——后者听起来像另一种服务端连接方式,实际只是没有登录 Cindy 账号。「本地」仅用于描述数据落在本机(如资料卡副文案「数据仅保存在本机」),不作为状态名。代码内部标识(AuthState mode='local'、authEnterLocal IPC、data owner)不受本条约束,仍用 local。en 侧统一走 not signed in 一种说法(含 settings.userProfile.local 的 exit / exitFailed 两条当前无引用的文案:the not-signed-in state),不与 unauthenticated 混用——PR #907 review 指出过同一状态两种英文说法会让日后启用这些文案时 UI 自相矛盾。status 仍为 proposed:Not signed in 作为状态名尚未与设计侧正式过一遍。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 43fb5066ac..40cb311a31 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -994,6 +994,50 @@"exempt": ["desktop:sessionShare.import.useWorktreeHint"]+ },+ {+ "id": "model-category-tts",+ "status": "proposed",+ "en": "Text to Speech",+ "translations": {+ "zh-CN": "语音合成",+ "ja": "音声合成",+ "ko": "음성 합성"+ },+ "note": "issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mode=audio_speech 的语音合成模型(如 elevenlabs/eleven_v3)。原先与语音转写、实时音频混在一个笼统的「音频语音」分类里,本次拆分为独立类型。"+ },+ {+ "id": "model-category-stt",+ "status": "proposed",+ "en": "Speech to Text",+ "translations": {+ "zh-CN": "语音转写",+ "ja": "音声認識",+ "ko": "음성 인식"+ },+ "note": "issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mode=audio_transcription 的语音转写/ASR 模型(如 gpt-4o-transcribe)。"+ },+ {+ "id": "model-category-realtime",+ "status": "proposed",+ "en": "Realtime Audio",+ "translations": {+ "zh-CN": "实时语音",+ "ja": "リアルタイム音声",+ "ko": "실시간 음성"+ },+ "note": "issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mode=realtime 的实时多模态模型(如 gpt-realtime-2、gemini-omni-flash-preview)。"+ },+ {+ "id": "model-category-compression",+ "status": "proposed",+ "en": "Compression",+ "translations": {+ "zh-CN": "压缩",+ "ja": "圧縮",+ "ko": "압축"+ },+ "note": "issue #882:模型管理/新对话选择器的分类标签,对应网关的文档压缩类模型(如 ai-gateway-doc)。此前被硬编码为笼统的 other 分类。"}]}diff --git a/packages/maker-core/src/types/capabilities.ts b/packages/maker-core/src/types/capabilities.tsindex 311e4cbda9..8c5777911c 100644--- a/packages/maker-core/src/types/capabilities.ts+++ b/packages/maker-core/src/types/capabilities.ts@@ -160,6 +160,14 @@ export interface ModelDescriptor {* 展示排序权重(纯展示元数据,源自目录)。渲染层据此排序;缺省排末尾。maker-core 运行时不读它。*/sortOrder?: number;+ /**+ * Gateway 原生 mode(issue #882,纯展示/判定元数据,源自目录 CatalogModel.mode)。+ * availableModels 派生时已经过 isChatEligible 过滤,这里透传只是为了让下游(如+ * resolveSourceSwitch 之类按 model 二次判定分组的逻辑)拿到 mode 而不必回读目录——+ * 2026-07 review:ModelDescriptor 曾经丢弃 mode,下游对象只能靠 id/group 猜,+ * 与本条目"已经聊天可用"的事实脱节。maker-core 运行时不读它。+ */+ mode?: string;/*** 该模型在选择器里**默认是否可见**(源自目录 `defaultEnabled`,host 派生时透传;* 缺省 ⇒ 可见)。渲染层取种子默认模型时据它跳过默认收起的 legacy 模型 ——diff --git a/packages/model-providers/src/__tests__/classification.test.ts b/packages/model-providers/src/__tests__/classification.test.tsindex 170f41f3fe..860f3ab911 100644--- a/packages/model-providers/src/__tests__/classification.test.ts+++ b/packages/model-providers/src/__tests__/classification.test.ts@@ -13,12 +13,15 @@ import {SUBSCRIPTION_DIRECT_MODEL_PREFIXES,XAI_MODEL_PREFIX,categorize,+ classifyModel,formatContextWindow,groupModelsForDisplay,groupOf,isBudgetModel,+ isChatEligible,isSubscriptionDirectModel,modelBadges,+ type ModelCategory,} from '../classification.js';// ── 原文移植: sourceSwitch.test.ts 的 categorize / groupOf / groupModelsForDisplay ──@@ -35,19 +38,169 @@ describe('categorize', () => {it('非对话类型先于厂商前缀判定(网关杂项模型按类型归组,不误入 gpt/google)', () => {expect(categorize('gpt-image-2')).toBe('image');expect(categorize('gemini-3-pro-image')).toBe('image');- expect(categorize('gpt-4o-transcribe')).toBe('audio');- expect(categorize('elevenlabs/scribe_v2')).toBe('audio');- expect(categorize('gemini-omni-flash-preview')).toBe('audio');expect(categorize('voyage/voyage-context-4')).toBe('embedding');expect(categorize('doubao-seedance-2-0-260128')).toBe('video');expect(categorize('happyhorse-1.1-t2v')).toBe('video');- expect(categorize('ai-gateway-doc')).toBe('other');+ expect(categorize('ai-gateway-doc')).toBe('compression');});it('订阅直连前缀归组: chatgpt/ → gpt,xai/ → grok', () => {expect(categorize(`${CHATGPT_MODEL_PREFIX}gpt-5.5`)).toBe('gpt');expect(categorize(`${XAI_MODEL_PREFIX}grok-4`)).toBe('grok');});++ it('x-ai/ 命名空间前缀(网关侧,与订阅直连 xai/ 是两回事)归 grok,不落 china(issue #882)', () => {+ expect(categorize('x-ai/grok-4.5')).toBe('grok');+ });++ it('gpt-realtime-* 归 realtime,不再落 gpt 聊天组(issue #882)', () => {+ expect(categorize('gpt-realtime-2')).toBe('realtime');+ expect(categorize('gpt-realtime-mini')).toBe('realtime');+ expect(categorize('gpt-realtime-translate')).toBe('realtime');+ expect(categorize('gemini-omni-flash-preview')).toBe('realtime');+ });++ it('gpt-4o-realtime-* 旧一代命名同样归 realtime(2026-07 review 回归:拆分时漏掉了这个前缀)', () => {+ expect(categorize('gpt-4o-realtime-preview-2024-12-17')).toBe('realtime');+ expect(categorize('gpt-4o-realtime-mini')).toBe('realtime');+ });++ it('语音转写/ASR 类归 stt,即使 id 里带 "realtime" 字样也不误入 realtime(issue #882)', () => {+ expect(categorize('gpt-4o-transcribe')).toBe('stt');+ expect(categorize('gpt-4o-mini-transcribe')).toBe('stt');+ expect(categorize('elevenlabs/scribe_v1')).toBe('stt');+ expect(categorize('elevenlabs/scribe_v1_experimental')).toBe('stt');+ expect(categorize('elevenlabs/scribe_v2')).toBe('stt');+ expect(categorize('gpt-realtime-whisper')).toBe('stt');+ expect(categorize('qwen3-asr-flash-realtime')).toBe('stt');+ expect(categorize('fun-asr-realtime-2026-02-28')).toBe('stt');+ });++ it('语音合成(TTS)归 tts,与同前缀的 elevenlabs STT 模型区分(issue #882)', () => {+ expect(categorize('elevenlabs/eleven_v3')).toBe('tts');+ expect(categorize('elevenlabs/eleven_multilingual_v2')).toBe('tts');+ });++ it('非 elevenlabs 前缀的通用语音合成关键词也归 tts(2026-07 review 回归:不能只认 elevenlabs)', () => {+ expect(categorize('gpt-4o-mini-tts')).toBe('tts');+ expect(categorize('qwen-tts')).toBe('tts');+ expect(categorize('some-vendor-speech-model')).toBe('tts');+ });++ it('带音频输入/输出但走 Chat Completions 的聊天模型不误判为 tts(2026-07 review:通用 "audio" 关键词太宽,会误伤真聊天模型)', () => {+ expect(categorize('gpt-4o-audio-preview')).toBe('gpt');+ expect(isChatEligible({ id: 'gpt-4o-audio-preview' })).toBe(true);+ });++ it('视频生成/编辑类归 video(issue #882)', () => {+ expect(categorize('doubao-seedance-2-0-fast-260128')).toBe('video');+ expect(categorize('happyhorse-1.1-i2v')).toBe('video');+ expect(categorize('happyhorse-1.1-r2v')).toBe('video');+ expect(categorize('happyhorse-1.0-video-edit')).toBe('video');+ });++ it('带视频理解能力但走 Chat Completions 的聊天模型不误判为 video(2026-07 review 第 23 轮:通用 "video" 关键词太宽,会误伤真聊天模型,同 audio 关键词收窄同理)', () => {+ expect(categorize('llava-hf/LLaVA-NeXT-Video-7B-hf')).not.toBe('video');+ expect(isChatEligible({ id: 'llava-hf/LLaVA-NeXT-Video-7B-hf' })).toBe(true);+ });++ it('Embedding 类归 embedding(issue #882)', () => {+ expect(categorize('text-embedding-3-large')).toBe('embedding');+ expect(categorize('text-embedding-3-small')).toBe('embedding');+ expect(categorize('gemini-embedding-2-preview')).toBe('embedding');+ expect(categorize('voyage/voyage-code-3')).toBe('embedding');+ expect(categorize('voyage/voyage-4-large')).toBe('embedding');+ expect(categorize('voyage/voyage-4')).toBe('embedding');+ });++ it('embed-*(Cohere,id 里没有 "embedding" 字样)同样归 embedding、不可聊天(2026-07 review 第 17 轮)', () => {+ expect(categorize('embed-english-v3.0')).toBe('embedding');+ expect(categorize('embed-multilingual-v3.0')).toBe('embedding');+ expect(isChatEligible({ id: 'embed-english-v3.0' })).toBe(false);+ expect(isChatEligible({ id: 'embed-multilingual-v3.0' })).toBe(false);+ });++ it('大小写混用的 id(自定义 OAuth 极简发现常见,如 Qwen/Qwen3-Embedding-8B)兜底判定不区分大小写(2026-07 review 第 20 轮)', () => {+ expect(categorize('Qwen/Qwen3-Embedding-8B')).toBe('embedding');+ expect(categorize('Qwen/Qwen3-Reranker-8B')).toBe('other');+ expect(categorize('DALL-E-3')).toBe('image');+ expect(isChatEligible({ id: 'Qwen/Qwen3-Embedding-8B' })).toBe(false);+ expect(isChatEligible({ id: 'Qwen/Qwen3-Reranker-8B' })).toBe(false);+ });++ it('图像生成类归 image(issue #882)', () => {+ expect(categorize('gemini-3.1-flash-image')).toBe('image');+ expect(categorize('gpt-image-1.5')).toBe('image');+ });++ it('id 里不含类型关键词的知名非聊天模型家族(dall-e / sora / veo)也不误判为可聊天(2026-07 review:走 {id,name} 极简发现的自定义 OAuth 供应商没有 mode/group 兜底,全靠这份正则)', () => {+ expect(categorize('dall-e-3')).toBe('image');+ expect(categorize('dall-e-2')).toBe('image');+ expect(categorize('sora-2')).toBe('video');+ expect(categorize('veo-3')).toBe('video');+ expect(isChatEligible({ id: 'dall-e-3' })).toBe(false);+ expect(isChatEligible({ id: 'sora-2' })).toBe(false);+ expect(isChatEligible({ id: 'veo-3' })).toBe(false);+ });++ it('同一批家族加了供应商命名空间前缀(如 openai/dall-e-3)时,锚定 id 开头的判定不漏网(2026-07 review 第 19 轮)', () => {+ expect(categorize('openai/dall-e-3')).toBe('image');+ expect(categorize('openai/sora-2')).toBe('video');+ expect(categorize('google/veo-3')).toBe('video');+ expect(isChatEligible({ id: 'openai/dall-e-3' })).toBe(false);+ expect(isChatEligible({ id: 'openai/sora-2' })).toBe(false);+ expect(isChatEligible({ id: 'google/veo-3' })).toBe(false);+ });++ it('realtime 与遗留 Completions 家族同样要兼容命名空间前缀(如 openai/gpt-realtime-preview、openai/babbage-002,2026-07 review 第 21 轮)', () => {+ expect(categorize('openai/gpt-realtime-preview')).toBe('realtime');+ expect(categorize('openai/gpt-4o-realtime-preview')).toBe('realtime');+ expect(categorize('openai/babbage-002')).toBe('other');+ expect(isChatEligible({ id: 'openai/gpt-realtime-preview' })).toBe(false);+ expect(isChatEligible({ id: 'openai/babbage-002' })).toBe(false);+ });++ it('embed- 前缀家族同样要兼容命名空间前缀(如 cohere/embed-english-v3.0,2026-07 review 第 22 轮)', () => {+ expect(categorize('cohere/embed-english-v3.0')).toBe('embedding');+ expect(isChatEligible({ id: 'cohere/embed-english-v3.0' })).toBe(false);+ });++ it('嵌套多层命名空间(如 gateway/openai/dall-e-3)同样不漏网:stripNamespace 取最后一段而非只剥一层(2026-07 review 第 24 轮)', () => {+ expect(categorize('gateway/openai/dall-e-3')).toBe('image');+ expect(categorize('gateway/openai/sora-2')).toBe('video');+ expect(categorize('org/cohere/embed-english-v3.0')).toBe('embedding');+ expect(categorize('gateway/openai/gpt-4o-realtime-preview')).toBe('realtime');+ expect(categorize('gateway/openai/babbage-002')).toBe('other');+ expect(isChatEligible({ id: 'gateway/openai/dall-e-3' })).toBe(false);+ expect(isChatEligible({ id: 'org/cohere/embed-english-v3.0' })).toBe(false);+ });++ it('moderation 模型不落进厂商兜底组、不被判定为可聊天(2026-07 review:fresh evidence,不是issue 列出的语义类型之一,落 other 保留)', () => {+ expect(categorize('omni-moderation-latest')).toBe('other');+ expect(categorize('text-moderation-latest')).toBe('other');+ expect(isChatEligible({ id: 'omni-moderation-latest' })).toBe(false);+ expect(isChatEligible({ id: 'text-moderation-latest' })).toBe(false);+ });++ it('遗留 Completions 端点与 Rerank 端点不落进厂商兜底组、不被判定为可聊天(2026-07 review 第 15 轮)', () => {+ expect(categorize('babbage-002')).toBe('other');+ expect(categorize('davinci-002')).toBe('other');+ expect(categorize('gpt-3.5-turbo-instruct')).toBe('other');+ expect(categorize('text-davinci-003')).toBe('other');+ expect(categorize('code-davinci-002')).toBe('other');+ expect(categorize('rerank-v3.5')).toBe('other');+ expect(categorize('rerank-english-v3.0')).toBe('other');+ expect(isChatEligible({ id: 'babbage-002' })).toBe(false);+ expect(isChatEligible({ id: 'davinci-002' })).toBe(false);+ expect(isChatEligible({ id: 'rerank-v3.5' })).toBe(false);+ });++ it('"-instruct" 结尾的正常聊天模型不受遗留 Completions 排除规则误杀(2026-07 review 第 15 轮:避免宽泛后缀误伤开源 instruct 模型)', () => {+ expect(categorize('qwen2.5-72b-instruct')).not.toBe('other');+ expect(categorize('llama-3-70b-instruct')).not.toBe('other');+ expect(isChatEligible({ id: 'qwen2.5-72b-instruct' })).toBe(true);+ expect(isChatEligible({ id: 'llama-3-70b-instruct' })).toBe(true);+ });});describe('groupOf — 数据优先,前缀兜底', () => {@@ -63,6 +216,135 @@ describe('groupOf — 数据优先,前缀兜底', () => {});});+describe('classifyModel — mode 权威,缺省时回退 groupOf(issue #882)', () => {+ const NON_CHAT_MODE_CASES: Array<{ id: string; mode: string; category: ModelCategory }> = [+ { id: 'gemini-3.1-flash-image', mode: 'image_generation', category: 'image' },+ { id: 'gemini-3-pro-image', mode: 'image_generation', category: 'image' },+ { id: 'gpt-image-1.5', mode: 'image_generation', category: 'image' },+ { id: 'gpt-image-2', mode: 'image_generation', category: 'image' },+ { id: 'text-embedding-3-large', mode: 'embedding', category: 'embedding' },+ { id: 'text-embedding-3-small', mode: 'embedding', category: 'embedding' },+ { id: 'gemini-embedding-2-preview', mode: 'embedding', category: 'embedding' },+ { id: 'voyage/voyage-code-3', mode: 'embedding', category: 'embedding' },+ { id: 'voyage/voyage-4-large', mode: 'embedding', category: 'embedding' },+ { id: 'voyage/voyage-4', mode: 'embedding', category: 'embedding' },+ { id: 'voyage/voyage-context-4', mode: 'embedding', category: 'embedding' },+ { id: 'elevenlabs/eleven_v3', mode: 'audio_speech', category: 'tts' },+ { id: 'elevenlabs/eleven_multilingual_v2', mode: 'audio_speech', category: 'tts' },+ { id: 'gpt-4o-transcribe', mode: 'audio_transcription', category: 'stt' },+ { id: 'gpt-4o-mini-transcribe', mode: 'audio_transcription', category: 'stt' },+ { id: 'elevenlabs/scribe_v1', mode: 'audio_transcription', category: 'stt' },+ { id: 'elevenlabs/scribe_v1_experimental', mode: 'audio_transcription', category: 'stt' },+ { id: 'elevenlabs/scribe_v2', mode: 'audio_transcription', category: 'stt' },+ { id: 'gpt-realtime-whisper', mode: 'audio_transcription', category: 'stt' },+ { id: 'qwen3-asr-flash-realtime', mode: 'audio_transcription', category: 'stt' },+ { id: 'fun-asr-realtime-2026-02-28', mode: 'audio_transcription', category: 'stt' },+ { id: 'gpt-realtime-2', mode: 'realtime', category: 'realtime' },+ { id: 'gpt-realtime-mini', mode: 'realtime', category: 'realtime' },+ { id: 'gpt-realtime-translate', mode: 'realtime', category: 'realtime' },+ { id: 'gemini-omni-flash-preview', mode: 'realtime', category: 'realtime' },+ { id: 'doubao-seedance-2-0-260128', mode: 'video_generation', category: 'video' },+ { id: 'doubao-seedance-2-0-fast-260128', mode: 'video_generation', category: 'video' },+ { id: 'happyhorse-1.1-t2v', mode: 'video_generation', category: 'video' },+ { id: 'happyhorse-1.1-i2v', mode: 'video_generation', category: 'video' },+ { id: 'happyhorse-1.1-r2v', mode: 'video_generation', category: 'video' },+ { id: 'happyhorse-1.0-video-edit', mode: 'video_generation', category: 'video' },+ ];++ it.each(NON_CHAT_MODE_CASES)(+ '$id: mode=$mode 权威判定为 $category,忽略 id 正则',+ ({ id, mode, category }) => {+ expect(classifyModel({ id, mode })).toBe(category);+ },+ );++ it('未识别的 mode 值不静默丢弃,落 other(issue #882 第 5 点:无损保留新类型)', () => {+ expect(classifyModel({ id: 'ai-gateway-doc', mode: 'doc_rerank' })).toBe('other');+ expect(classifyModel({ id: 'some-future-model', mode: 'brand-new-capability' })).toBe('other');+ });++ it('mode 缺省时回退 groupOf/categorize(旧缓存兜底,同 issue 点名的具体 bug 修复)', () => {+ expect(classifyModel({ id: 'gpt-realtime-2' })).toBe('realtime');+ expect(classifyModel({ id: 'x-ai/grok-4.5' })).toBe('grok');+ expect(classifyModel({ id: 'ai-gateway-doc' })).toBe('compression');+ });++ it("mode='chat' 只确认是聊天模型,厂商分组仍由 group/id 决定(两层判断独立)", () => {+ expect(classifyModel({ id: 'claude-opus-4-8', mode: 'chat' })).toBe('anthropic');+ expect(classifyModel({ id: 'x-ai/grok-4.5', mode: 'chat' })).toBe('grok');+ expect(classifyModel({ id: 'gpt-weird', group: 'china', mode: 'chat' })).toBe('china');+ });++ it("mode='responses' 与 'chat' 同为聊天可用取值(2026-07 review 第 16 轮:Codex 走 Responses API,不是非聊天端点)", () => {+ expect(classifyModel({ id: 'codex/gpt-5.5', mode: 'responses' })).toBe('gpt-budget');+ expect(classifyModel({ id: 'gpt-5.5', mode: 'responses' })).toBe('gpt');+ });+});++describe('isChatEligible — 决定能否进 Agent availableModels(issue #882 第 3 点)', () => {+ it('mode 权威判定为非 chat 的所有类型模型均不可进 availableModels', () => {+ const nonChatIds = [+ 'gemini-3.1-flash-image',+ 'gpt-image-2',+ 'text-embedding-3-large',+ 'voyage/voyage-4',+ 'elevenlabs/eleven_v3',+ 'elevenlabs/scribe_v2',+ 'gpt-4o-transcribe',+ 'qwen3-asr-flash-realtime',+ 'gpt-realtime-2',+ 'gemini-omni-flash-preview',+ 'doubao-seedance-2-0-260128',+ 'happyhorse-1.1-t2v',+ ];+ for (const id of nonChatIds) {+ expect(isChatEligible({ id, mode: 'embedding' })).toBe(false); // 任意非 chat mode 皆不可用+ }+ expect(isChatEligible({ id: 'ai-gateway-doc', mode: 'doc_rerank' })).toBe(false);+ });++ it('mode 缺省时按修正后的 categorize 兜底判定 —— 同样排除这些具体模型', () => {+ for (const id of [+ 'gpt-realtime-2',+ 'gpt-realtime-mini',+ 'gpt-realtime-translate',+ 'gemini-omni-flash-preview',+ 'text-embedding-3-large',+ 'ai-gateway-doc',+ 'elevenlabs/eleven_v3',+ 'elevenlabs/scribe_v2',+ 'gpt-4o-transcribe',+ 'doubao-seedance-2-0-260128',+ ]) {+ expect(isChatEligible({ id })).toBe(false);+ }+ });++ it('聊天模型(含 mode 缺省的网关旧数据)仍判定为可用 —— 回归锁,不能因这次改动消失', () => {+ expect(isChatEligible({ id: 'claude-opus-4-8' })).toBe(true);+ expect(isChatEligible({ id: 'gpt-5.5' })).toBe(true);+ expect(isChatEligible({ id: 'x-ai/grok-4.5' })).toBe(true); // 无 mode 时按修正后的 grok 分组,可用+ expect(isChatEligible({ id: 'moonshotai/kimi-k2' })).toBe(true); // china 兜底组+ expect(isChatEligible({ id: 'some-gateway-chat-model', mode: 'chat' })).toBe(true);+ });++ it("mode='responses' 判定为可用(2026-07 review 第 16 轮:Codex 原生走 Responses API 的语言模型,不是非聊天端点)", () => {+ expect(isChatEligible({ id: 'codex/gpt-5.5', mode: 'responses' })).toBe(true);+ expect(isChatEligible({ id: 'gpt-5.5', mode: 'responses' })).toBe(true);+ });++ it('mode 缺省时不采信 group 品牌标注,只按 id 能力正则判定(2026-07 review)', () => {+ // group 是展示分组/品牌,不是能力类型(issue #882 明确要求两者独立)——网关完全可能把+ // 图像模型的 group 品牌标成 'gpt'(归到 GPT 家族方便浏览),这不代表它能聊天。+ // groupOf({id:'gpt-image-2', group:'gpt'}) 会信 group 返回 'gpt'(展示分组语义没错),+ // 但 isChatEligible 必须不受骗:categorize('gpt-image-2') 正确识别为 image,判定不可用。+ expect(isChatEligible({ id: 'gpt-image-2', group: 'gpt' })).toBe(false);+ expect(isChatEligible({ id: 'text-embedding-3-large', group: 'china' })).toBe(false);+ // 对照组:group 品牌标注和 id 能力判定一致时,不受影响。+ expect(isChatEligible({ id: 'gpt-5.5', group: 'gpt' })).toBe(true);+ });+});+describe('groupModelsForDisplay — sortOrder 升序 + group 分桶 + 桶序按最小 sortOrder', () => {it('按 sortOrder 排序并分桶,桶序 = 桶内首个出现序', () => {const out = groupModelsForDisplay([diff --git a/packages/model-providers/src/__tests__/invocation.test.ts b/packages/model-providers/src/__tests__/invocation.test.tsindex 1b8525c6f3..cdddf621a6 100644--- a/packages/model-providers/src/__tests__/invocation.test.ts+++ b/packages/model-providers/src/__tests__/invocation.test.ts@@ -333,6 +333,24 @@ describe('resolveModelInvocation — 六元组回落链', () => {expect(r.fallbacksApplied).toContain('provider:visible-fallback');});+ it('providerId: 点名来源这份具体条目是非聊天 mode → 不算「真实提供」,收敛到聊天可用的替代源(issue #882 第 3 点,2026-07 review 第 18 轮)', () => {+ // anthropic 的 claude-opus-5 被网关标成非聊天(如 embedding);xd 上同 id 仍是正常+ // 聊天模型 —— 只看 id 存在(旧 providerOffersModel)会误留在 anthropic 上,必须+ // 收敛到 xd。故意不传 ctx.isVisible,复现修复前「无可见性回调时直接放行」的路径。+ const withNonChatCopy: ProviderView[] = providers().map((p) =>+ p.id === 'anthropic'+ ? { ...p, models: { 'claude-code': [model('claude-opus-5', { mode: 'embedding' })] } }+ : p,+ ) as ProviderView[];+ const r = resolveModelInvocation(+ { model: 'claude-opus-5', providerId: 'anthropic' },+ SCENARIO,+ ctx({ providers: withNonChatCopy }),+ );+ expect(r.providerId).toBe('xd');+ expect(r.fallbacksApplied).toContain('provider:visible-fallback');+ });+it('providerId: 目录不可用 → 透传原值(路由层兜底,与 IM/hook 历史降级一致)', () => {const r = resolveModelInvocation({ providerId: 'anthropic' },@@ -682,3 +700,62 @@ describe('resolveModelInvocation — codex review 五轮:native 兜底行级可expect(r.fallbacksApplied).not.toContain('permission:scenario-strictest-fallback');});});++describe('resolveModelInvocation — model 候选清单本身先过 chat 准入(issue #882 第 3 点,2026-07 review 第 20 轮)', () => {+ it('native 源上首模型是非聊天类型 → 跳过它,兜底选该源下一个聊天模型,不是裸 available[0]', () => {+ // xd(native)目录 [opus(非聊天), sonnet]:旧实现的 availableModelsFor 不过滤 mode,+ // has()/fromNative/available[0] 都可能选中 opus;providerId 步骤只能校验"选中的+ // 来源",无法撤销已经选错的模型。+ const provs = providers().map((p) =>+ p.id === 'xd'+ ? {+ ...p,+ models: {+ ...p.models,+ 'claude-code': [+ model('claude-opus-5', { mode: 'embedding' }),+ model('claude-sonnet-4-6'),+ ],+ },+ }+ : p,+ ) as ProviderView[];+ const r = resolveModelInvocation(+ { model: 'gone' },+ { ...SCENARIO, modelFor: () => 'also-gone' },+ { providers: provs, getPermissionModes: PERM_MODES },+ );+ expect(r.model).toBe('claude-sonnet-4-6');+ expect(r.fallbacksApplied).toContain('model:first-available');+ });++ it('显式偏好的模型 id 在所有来源都只以非聊天类型存在 → 不算「可用」,回落场景默认', () => {+ // 两个来源的 claude-opus-5 都改成非聊天,确保没有任何一份聊天可用的同 id 条目+ // 能让 has() 误放行。+ const provs = providers().map((p) => {+ if (p.id === 'anthropic') {+ return { ...p, models: { 'claude-code': [model('claude-opus-5', { mode: 'embedding' })] } };+ }+ if (p.id === 'xd') {+ return {+ ...p,+ models: {+ ...p.models,+ 'claude-code': [+ model('claude-opus-5', { mode: 'embedding' }),+ model('claude-sonnet-4-6'),+ ],+ },+ };+ }+ return p;+ }) as ProviderView[];+ const r = resolveModelInvocation(+ { model: 'claude-opus-5' },+ SCENARIO,+ { providers: provs, getPermissionModes: PERM_MODES },+ );+ expect(r.model).toBe('claude-sonnet-4-6');+ expect(r.fallbacksApplied).toContain('model:scenario-default');+ });+});diff --git a/packages/model-providers/src/__tests__/sections.test.ts b/packages/model-providers/src/__tests__/sections.test.tsindex 90dfd339b5..f2acf7479a 100644--- a/packages/model-providers/src/__tests__/sections.test.ts+++ b/packages/model-providers/src/__tests__/sections.test.ts@@ -119,6 +119,33 @@ describe('buildProviderSections', () => {expect(sections.map((s) => s.provider.id)).toEqual(['xd']);});+ it('非聊天模型(mode 权威判定)不进分段列表(issue #882 第 3 点,2026-07 review:三个调用方——桌面选择器/IM /model 卡片/mobile——都靠这一个函数挡住)', () => {+ const withNonChat = provider('xd', 'XD', [+ model('gpt-5.5', 'GPT-5.5'),+ { ...model('gpt-image-2', 'GPT Image 2'), mode: 'image_generation' },+ ]);+ const sections = buildProviderSections({+ providers: [withNonChat],+ agent: 'claude-code',+ isVisible: () => true,+ });+ expect(sections[0].models.map((m) => m.id)).toEqual(['gpt-5.5']);+ });++ it('非聊天模型即便是"当前选中"也不会被 keepSelected 豁免带回(防御性:选中态不应覆盖能力判定)', () => {+ const withNonChat = provider('xd', 'XD', [+ { ...model('gpt-image-2', 'GPT Image 2'), mode: 'image_generation' },+ ]);+ const sections = buildProviderSections({+ providers: [withNonChat],+ agent: 'claude-code',+ selectedModelId: 'gpt-image-2',+ selectedProviderId: 'xd',+ isVisible: () => false,+ });+ expect(sections).toHaveLength(0);+ });+it('目录条目的 icon(AI Gateway 设定)透传进 SectionModel;缺省不带字段', () => {const withIcon = provider('xd', 'XD', [{ ...model('claude-fable-5', 'Fable 5'), icon: 'claude' },@@ -188,4 +215,14 @@ describe('visibleModelUnion', () => {const out = visibleModelUnion([codexOnly], 'claude-code', () => true);expect(out).toEqual([]);});++ it('非聊天模型不进并集(issue #882 第 3 点,2026-07 review):Orca sub-agent 可用性判定 /' ++ ' Slack /model 卡片 / hook session-runner 共用这一个函数,漏过滤会让非聊天模型被当成可执行模型选中', () => {+ const withNonChat = provider('xd', 'XD', [+ model('gpt-5.5', 'GPT-5.5'),+ { ...model('gpt-image-2', 'GPT Image 2'), mode: 'image_generation' },+ ]);+ const out = visibleModelUnion([withNonChat], 'claude-code', () => true);+ expect(out.map((m) => m.id)).toEqual(['gpt-5.5']);+ });});diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.tsindex 42697bd378..305e92b66d 100644--- a/packages/model-providers/src/__tests__/source-registry.test.ts+++ b/packages/model-providers/src/__tests__/source-registry.test.ts@@ -25,6 +25,7 @@ import {providerOffersModel,getModel,sourcesForModel,+ chatEligibleSourcesForModel,effectiveSourceIdForModel,resolveRoute,} from '../registry.js';@@ -431,6 +432,78 @@ describe('registry visibility & sources(运行时注入 fixture)', () => {effectiveSourceIdForModel(all, 'openai', 'claude-opus-4-8', 'claude-code'),).toBe('xd');});++ it('effectiveSourceIdForModel 不把请求路由到非聊天来源(issue #882 第 3 点,2026-07 review):同一 id 在不同来源上 mode 不一致时,只信聊天来源', () => {+ const mixedModeCatalog: Catalog = {+ version: 'test',+ providers: [+ {+ id: 'xd',+ name: 'XD',+ source: 'builtin',+ agents: ['claude-code'],+ auth: { method: 'managed' },+ routing: { 'claude-code': { upstream: 'https://xd.test', authStrategy: 'gateway-key' } },+ models: {+ 'claude-code': [model('shared-id', { mode: 'image_generation' })],+ },+ },+ {+ id: 'openai',+ name: 'OpenAI',+ source: 'builtin',+ agents: ['claude-code'],+ auth: { method: 'oauth' },+ routing: { 'claude-code': { upstream: 'https://api.openai.com', authStrategy: 'oauth-passthrough' } },+ models: {+ 'claude-code': [model('shared-id', { mode: 'chat' })],+ },+ },+ ],+ };+ const views = buildRegistry(mixedModeCatalog, { xd: true, openai: true });+ // 显式指定的 providerId 恰好是非聊天来源(xd)时,不接受它——落到真正聊天的来源(openai)。+ expect(effectiveSourceIdForModel(views, 'xd', 'shared-id', 'claude-code')).toBe('openai');+ // 未显式指定 providerId 时,默认来源同样只能是聊天来源。+ expect(effectiveSourceIdForModel(views, null, 'shared-id', 'claude-code')).toBe('openai');++ // chatEligibleSourcesForModel 是这份过滤的共享底层——直接断言它自己的输出,+ // 保证 UI 侧的"有没有可发送来源"判断(ChatInput/useConnectedSource/+ // isSelectedSourceDisconnected)与路由解析用的是同一份口径,不会互相打架。+ expect(chatEligibleSourcesForModel(views, 'shared-id', 'claude-code').map((p) => p.id)).toEqual([+ 'openai',+ ]);+ });++ it('chatEligibleSourcesForModel 不误杀用户自定义供应商显式配置的模型(2026-07 review 第 25 轮)', () => {+ // flux-image-x 的 id 撞上 /image/ 启发式,但它来自 source:'user' 的自定义供应商且+ // group 是未知的 custom:*——isAgentSelectableModel 的 userProvider 例外有意放行+ // (用户显式配置的就是聊天模型)。裸 isChatEligible 会把它从路由/发送门禁里删掉,+ // 用户配好的模型 UI 显示"没有已连接的来源"、请求发不出去。+ const userProviderCatalog: Catalog = {+ version: 'test',+ providers: [+ {+ id: 'custom-p',+ name: 'Custom',+ source: 'user',+ agents: ['claude-code'],+ auth: { method: 'api-key' },+ routing: { 'claude-code': { upstream: 'https://custom.test', authStrategy: 'api-key' } },+ models: {+ 'claude-code': [model('flux-image-x', { group: 'custom:custom-p' })],+ },+ },+ ],+ };+ const views = buildRegistry(userProviderCatalog, { 'custom-p': true });+ expect(+ chatEligibleSourcesForModel(views, 'flux-image-x', 'claude-code').map((p) => p.id),+ ).toEqual(['custom-p']);+ expect(effectiveSourceIdForModel(views, 'custom-p', 'flux-image-x', 'claude-code')).toBe(+ 'custom-p',+ );+ });});describe('resolveRoute(运行时注入 fixture)', () => {diff --git a/packages/model-providers/src/classification.ts b/packages/model-providers/src/classification.tsindex 28519c062f..4c79c1337a 100644--- a/packages/model-providers/src/classification.ts+++ b/packages/model-providers/src/classification.ts@@ -36,8 +36,9 @@ export function isSubscriptionDirectModel(model: string | null | undefined): boo}// 仅用于分组展示, 不参与持久化或 onModelChange 数据流。-// 对话厂商组(anthropic..china)在前;非对话类型组(image/audio/video/embedding/other)在后——-// 后者收纳网关多出的图像 / 语音 / 视频 / 向量等模型(它们默认关、不能当 agent 用,仅分类展示)。+// 对话厂商组(anthropic..china)在前;非对话类型组(image/tts/stt/realtime/video/embedding/+// compression/other)在后——后者收纳网关多出的图像/语音/视频/向量/压缩等模型(它们默认关、+// 不能当 agent 用,仅分类展示,见 isChatEligible)。export type ModelCategory =| 'anthropic'| 'gpt'@@ -46,9 +47,12 @@ export type ModelCategory =| 'google'| 'china'| 'image'- | 'audio'| 'video'+ | 'tts'+ | 'stt'+ | 'realtime'| 'embedding'+ | 'compression'| 'other';export const CATEGORY_ORDER: ModelCategory[] = [@@ -59,34 +63,167 @@ export const CATEGORY_ORDER: ModelCategory[] = ['google','china','image',- 'audio','video',+ 'tts',+ 'stt',+ 'realtime','embedding',+ 'compression','other',];+/** 对话厂商组:属于其一即被 isChatEligible 判定为可进 Agent availableModels。 */+const CHAT_VENDOR_CATEGORIES = new Set<ModelCategory>([+ 'anthropic',+ 'gpt',+ 'gpt-budget',+ 'grok',+ 'google',+ 'china',+]);++/**+ * 对话厂商组,按 CATEGORY_ORDER 原有相对顺序派生(供切来源 reconcile 之类+ * 「只在聊天厂商组里找候选」的场景复用,不必各自手写排除非聊天分类的清单——+ * 那份清单每新增一个非聊天分类就要改一处,已经是本次要修的那类耦合)。+ */+export const CHAT_VENDOR_CATEGORY_ORDER: readonly ModelCategory[] = CATEGORY_ORDER.filter((c) =>+ CHAT_VENDOR_CATEGORIES.has(c),+);++/**+ * Gateway 原生 `mode` → 展示分类(issue #882:mode 是权威信号,取值即+ * LiteLLM/AIGateway 侧的原生字符串,未来新增值先落 other 并保留原串,不必+ * 为每个新值改这里的正则)。'chat' 与缺省不出现在这里 —— 它们仍按厂商+ * 前缀走 groupOf/categorize 归到 anthropic/gpt/grok/google/china 等分组,+ * 因为"是聊天模型"和"属于哪个厂商分组"是两个独立问题。+ * 取值以线上 Gateway 实际返回为准;这里先覆盖 LiteLLM 通用常见值,遇到确认+ * 的新取值(如压缩类的真实 mode 字符串)再补充映射,未覆盖时不会丢数据,只是+ * 先落 other 展示原始 mode。+ */+const MODE_TO_CATEGORY: Record<string, ModelCategory> = {+ embedding: 'embedding',+ image_generation: 'image',+ video_generation: 'video',+ audio_speech: 'tts',+ audio_transcription: 'stt',+ realtime: 'realtime',+};++/**+ * mode 取值里同样代表"语言模型、能聊天"的字符串集合 —— 不止字面的 'chat'。+ * `responses` 是 LiteLLM/Gateway 用来标记"该模型只走 OpenAI Responses API+ * (而非 Chat Completions)"的取值,语义仍是可对话的语言模型,只是 wire+ * protocol 不同;Codex 这条 runtime 本来就默认走 openai-responses(见+ * RoutingDescriptor.wireProtocol),不能把这类模型当成非聊天模型过滤掉+ * (2026-07 review 第 16 轮)。+ */+const CHAT_CAPABLE_MODES = new Set(['chat', 'responses']);++/**+ * 去掉 id 的全部 `<namespace>/` 前缀,取最后一段。网关有时会给 id 加供应商命名空间+ * (如 openai/dall-e-3、google/veo-3,catalog 本身就支持 openai/gpt-5.4 这类写法),+ * 且可能嵌套多层(如 gateway/openai/dall-e-3);dall-e/sora/veo- 这几个锚定 id 开头的+ * 关键字判定必须同时认「裸 id」与「去前缀后的尾部」,只剥一层的话嵌套命名空间仍会+ * 漏网(2026-07 review 第 19 轮;多层修正见第 24 轮)。+ */+function stripNamespace(id: string): string {+ const idx = id.lastIndexOf('/');+ return idx === -1 ? id : id.slice(idx + 1);+}+// 按 model.id 前缀粗分类: claude-* → Anthropic, gpt-* → GPT, codex/* → 骨折GPT (gateway 低价路由),// gemini-* → Google, 其余 (moonshotai/qwen/glm/...) 一律落到 China。新增国产模型不需要改这里。-export function categorize(id: string): ModelCategory {+// 这是**没有 mode 时**的兜底(旧缓存 / mode 尚未覆盖到的来源);mode 存在时一律用+// classifyModel,不再猜 id。+export function categorize(rawId: string): ModelCategory {+ // 走 {id,name} 极简发现的自定义 OAuth 供应商常保留原始大小写(如+ // Qwen/Qwen3-Embedding-8B、Qwen/Qwen3-Reranker-8B),下面全部关键词/前缀判定+ // 统一按小写比较,不逐个正则补 i 标记漏改(2026-07 review 第 20 轮)。categorize+ // 只返回分类标签,不回传 id,小写化不影响展示 / 请求用的原始 id。+ const id = rawId.toLowerCase();if (id.startsWith('claude-')) return 'anthropic';- // 非对话类型(向量/图像/音频语音/视频)必须在通用 gpt- / gemini- 厂商规则**之前**判定,+ // 非对话类型(向量/图像/语音/视频/压缩)必须在通用 gpt- / gemini- 厂商规则**之前**判定,// 否则 gpt-image-2 / gemini-3-pro-image / gpt-4o-transcribe 会被误归到 gpt / google。// 这些是网关多返回的、不能当 agent 用的模型,默认关、仅按类型归类展示。- if (/embedding/.test(id) || id.startsWith('voyage/')) return 'embedding';- if (/image/.test(id)) return 'image';+ // embed-english-v3.0 / embed-multilingual-v3.0(Cohere)等 id 里没有 "embedding"+ // 字样,只靠 /embedding/ 关键词兜底会漏网(2026-07 review 第 17 轮,同 dall-e/+ // sora/veo 这类命名不含类型关键词的情况);embed- 锚定 id 开头,带命名空间前缀+ // (如 cohere/embed-english-v3.0)会漏网,同 dall-e/sora/veo- 的命名空间兜底+ // 同理(2026-07 review 第 22 轮)。+ if (+ /embedding/.test(id) ||+ id.startsWith('voyage/') ||+ id.startsWith('embed-') ||+ stripNamespace(id).startsWith('embed-')+ )+ return 'embedding';+ // dall-e(OpenAI 图像)id 里没有 "image" 字样,靠关键词兜底会漏网(2026-07 review:+ // 走 {id,name} 极简发现的自定义 OAuth 供应商没有 mode/group,只能靠这份正则)。+ if (/image/.test(id) || id.startsWith('dall-e') || stripNamespace(id).startsWith('dall-e'))+ return 'image';+ // sora(OpenAI 视频)/ veo(Google 视频)同理,id 里没有 "video" 字样。故意不认通用的+ // "video" 关键词:llava-hf/LLaVA-NeXT-Video-7B-hf 这类视频理解多模态聊天模型 id+ // 里带 "video" 却是走 Chat Completions 的正常聊天模型,不是纯视频生成端点——与+ // 音频判定不认通用 "audio" 关键词同理(2026-07 review 第 23 轮)。只认+ // seedance/happyhorse/-t2v/-i2v/-r2v 这几个真正专指视频生成的关键词。if (- id.startsWith('elevenlabs/') ||- id.startsWith('gpt-4o-realtime') ||- /transcribe|audio|speech|tts|whisper|asr|gemini-omni/.test(id)+ /seedance|happyhorse|-t2v|-i2v|-r2v/.test(id) ||+ /^sora|^veo-/.test(id) ||+ /^sora|^veo-/.test(stripNamespace(id)))- return 'audio';- if (/seedance|happyhorse|video|-t2v|-i2v|-r2v/.test(id)) return 'video';- if (id === 'ai-gateway-doc') return 'other';+ return 'video';+ if (id === 'ai-gateway-doc') return 'compression';+ // moderation(如 omni-moderation-latest / text-moderation-latest)不是issue #882+ // 列出的语义类型之一,落 other 保留原始 id/mode(2026-07 review:走 {id,name} 极简+ // 发现的自定义 OAuth 供应商没有 mode,不挡的话会被 isChatEligible 误判为可聊天——+ // moderation 端点不接受聊天请求)。+ if (/moderation/.test(id)) return 'other';+ // 遗留 Completions 端点(davinci-002/babbage-002/text-davinci-*等,OpenAI 已停售但+ // 部分网关仍会同步)与 Rerank 端点(cohere/voyage 的 rerank-*)不接受 Chat Completions+ // 请求,未列入 issue #882 语义类型,落 other 保留原始 id(2026-07 review:走 {id,name}+ // 极简发现的自定义 OAuth 供应商没有 mode,靠正则兜底,否则会被 isChatEligible 误判为+ // 可聊天)。只匹配这批已停售且无歧义的固定 id/前缀——不用 `-instruct$` 这种宽泛后缀,+ // 因为 mistral/qwen/llama 的 "-instruct" 结尾模型是正常聊天模型,不能误杀。+ if (/rerank/.test(id)) return 'other';+ const LEGACY_COMPLETION_RE =+ /^(babbage-002|davinci-002|gpt-3\.5-turbo-instruct|text-davinci-\d{3}|text-curie-001|text-babbage-001|text-ada-001|code-davinci-002)$/;+ // 精确匹配前后都锚定,带供应商命名空间前缀(如 openai/babbage-002)会漏网,同+ // dall-e/sora/veo- 的命名空间兜底同理(2026-07 review 第 21 轮)。+ if (LEGACY_COMPLETION_RE.test(id) || LEGACY_COMPLETION_RE.test(stripNamespace(id))) return 'other';+ // STT/ASR 必须在 realtime 判定之前:qwen3-asr-flash-realtime / fun-asr-realtime-* /+ // gpt-realtime-whisper 的 id 里都含 "realtime",但语义是语音转写,不是实时多模态。+ // 不能只认 elevenlabs 前缀——否则 gpt-4o-mini-tts / qwen-tts 这类其它厂商的语音模型+ // 会漏网落进 gpt/china,被 isChatEligible 误判为可聊天(2026-07 review)。+ if (id.startsWith('elevenlabs/scribe') || /transcribe|whisper|asr/.test(id)) return 'stt';+ // 故意不认通用的 "audio" 关键词:isChatEligible 现在直接吃 categorize 的分类结果,+ // 落进 tts 就等于判定"不能聊天"——而 gpt-4o-audio-preview 这类模型 id 里带+ // "audio" 却是走 Chat Completions 的正常聊天模型(带音频输入/输出),不是纯语音+ // 合成端点。只认 speech/tts 这两个真正专指语音合成的关键词(2026-07 review:+ // 拆分前 audio 只影响展示分组,拆分后同一份 regex 还要决定聊天准入,精度要求变了)。+ if (id.startsWith('elevenlabs/eleven') || /speech|tts/.test(id)) return 'tts';+ // gpt-realtime-2 / gpt-realtime-mini / gpt-realtime-translate / gpt-4o-realtime-* /+ // gemini-omni-* —— 真正的实时多模态,已排除上面的 STT 特例。gpt-4o-realtime 前缀是+ // 旧一代命名,新一代改成了 gpt-realtime-*,兜底要同时认两种(2026-07 review)。+ // gpt-realtime-/gpt-4o-realtime- 锚定 id 开头,带命名空间前缀(如+ // openai/gpt-realtime-preview)会漏网落进聊天兜底组,同 dall-e/sora/veo- 的+ // 命名空间兜底同理(2026-07 review 第 21 轮);gemini-omni 是子串匹配,已天然+ // 兼容命名空间,不需要额外处理。+ if (+ /^gpt-realtime|^gpt-4o-realtime/.test(id) ||+ /^gpt-realtime|^gpt-4o-realtime/.test(stripNamespace(id)) ||+ /gemini-omni/.test(id)+ )+ return 'realtime';// 订阅直连 GPT(chatgpt/ 前缀,经 responses-bridge)与网关 gpt- 同归 GPT 组;前缀常量与- // 路由 / 记账 gate 同源(本文件顶部),防漂移。+ // 路由 / 记账 gate 同源(本文件顶部),防漂移。两个常量本身已是小写字面量,小写化后+ // 直接比较无需再转换。if (id.startsWith('gpt-') || id.startsWith(CHATGPT_MODEL_PREFIX)) return 'gpt';if (id.startsWith('codex/')) return 'gpt-budget';- if (id.startsWith(XAI_MODEL_PREFIX) || id.startsWith('grok')) return 'grok';+ // x-ai/ 只是网关侧 grok 的命名空间前缀(展示分组用),与 XAI_MODEL_PREFIX+ // ('xai/',订阅直连 bridge 语义)是两件事,不要合并常量。+ if (id.startsWith(XAI_MODEL_PREFIX) || id.startsWith('x-ai/') || id.startsWith('grok'))+ return 'grok';if (id.startsWith('gemini-')) return 'google';return 'china';}@@ -94,21 +231,65 @@ export function categorize(id: string): ModelCategory {const KNOWN_CATEGORIES = new Set<string>(CATEGORY_ORDER);/**- * 能作为 agent 对话模型被选择/路由的厂商分组(anthropic..china)。image / audio / video /- * embedding / other 是网关多返回的**能力模型**:不能当 agent 用,永远不进对话模型选择面板- * (硬排除,与显示开关无关),它们的「启用」只作用于媒体生成等专属链路。+ * 决定一个模型的厂商分组 —— **数据优先**:目录里带了合法 `group` 就用它,+ * 否则回退到 id 前缀归类(categorize)。未知的 group 值(渲染层没有对应标签)也回退,+ * 避免出现没有 i18n 标签的空分组。不感知 `mode`——mode 优先分类见 classifyModel。*/-const AGENT_MODEL_CATEGORIES: ReadonlySet<ModelCategory> = new Set([- 'anthropic',- 'gpt',- 'gpt-budget',- 'grok',- 'google',- 'china',-]);+export function groupOf(model: { id: string; group?: string }): ModelCategory {+ if (model.group && KNOWN_CATEGORIES.has(model.group)) return model.group as ModelCategory;+ return categorize(model.id);+}/**- * 该模型是否属于可被 agent 选择的对话厂商分组(见 AGENT_MODEL_CATEGORIES)。+ * 分类的**权威入口**(issue #882):`mode` 存在且不是聊天可用取值+ * (CHAT_CAPABLE_MODES)时直接按 MODE_TO_CATEGORY 权威判定,忽略 id/group——+ * 网关明确说了这不是聊天模型,不该再让 id 正则有机会猜错(如 gpt-realtime-2+ * 猜成 gpt、x-ai/grok-4.5 猜成 china)。`mode` 缺省或落在 CHAT_CAPABLE_MODES+ * (chat/responses)时,回退 groupOf(数据 group 优先 / id 正则兜底)——+ * "是不是聊天模型"与"聊天模型属于哪个厂商分组"是两层判断,mode 只回答第一层,+ * 第二层仍需 id/group。+ */+export function classifyModel(model: { id: string; group?: string; mode?: string }): ModelCategory {+ if (model.mode !== undefined && !CHAT_CAPABLE_MODES.has(model.mode)) {+ return MODE_TO_CATEGORY[model.mode] ?? 'other';+ }+ return groupOf(model);+}++/**+ * 该模型能不能进 Agent `availableModels` / 新对话模型选择器(issue #882 第 3 点)。+ * `mode` 存在时只信 CHAT_CAPABLE_MODES(chat / responses——Codex 走 Responses+ * API 的语言模型,不是非聊天端点,2026-07 review 第 16 轮)。+ *+ * `mode` 缺省时,`group` 只在**声明已知的非聊天分类**(image/video/tts/stt/+ * realtime/embedding/compression/other)时才采信、直接拒——这个方向上 group+ * 比 id 更可信(PR #744:自定义/网关供应商显式打的能力标签,seedream-5 这类+ * id 本身不含任何类型关键词的合成模型只能靠这个信号判定)。`group` 声明的是+ * 聊天厂商分组(anthropic/gpt/.../china)时**不采信**,仍按 id 正则判——那只是+ * 展示分组/品牌,网关的展示元数据完全可能把 `gpt-image-2` 这类图像模型的+ * `group` 标成 'gpt'(品牌上归类到 GPT 家族,方便浏览),这里若信了会把非聊天+ * 模型误判为可用(2026-07 review)。两种 group 取值的可信方向不对称,不能+ * 一并处理。落进厂商聊天组只用于兜底判断,保证"mode 还没覆盖到、但已经在+ * 正常工作的网关聊天模型"不会因为这次改动突然从 availableModels 消失+ * (见 classification.test.ts 的回归锁)。+ */+export function isChatEligible(model: { id: string; group?: string; mode?: string }): boolean {+ if (model.mode !== undefined) return CHAT_CAPABLE_MODES.has(model.mode);+ if (+ model.group &&+ KNOWN_CATEGORIES.has(model.group) &&+ !CHAT_VENDOR_CATEGORIES.has(model.group as ModelCategory)+ ) {+ return false;+ }+ return CHAT_VENDOR_CATEGORIES.has(categorize(model.id));+}++/**+ * `isChatEligible` 的别名,供「agent 对话模型能不能选」语境下的调用方使用(与 PR #744+ * 的 `AGENT_MODEL_CATEGORIES`/`isAgentSelectableModel` 合流:同一个"能不能进对话选择面板"+ * 判断,不再各自维护一份厂商分组常量——两份常量此前逐字相同,已收口为+ * `CHAT_VENDOR_CATEGORIES` 单一定义)。** `opts.userProvider` = 该条目来自用户自定义供应商(Provider.source === 'user',由* 调用方注入 —— 本模块纯逻辑不持 provider 上下文):此时目录带的**未知 group**@@ -119,39 +300,30 @@ const AGENT_MODEL_CATEGORIES: ReadonlySet<ModelCategory> = new Set([* 例外**只限用户供应商**:网关条目缺 group 时 active-catalog 会补 `custom:xd`* (active-catalog.ts),若无条件放行未知组,无分组下发的网关图像/音频/向量模型会* 绕过能力分类、重新漏进对话清单 —— 正是本过滤要堵的洞(PR #744 review 第二轮)。- * 非用户供应商一律走 groupOf(显式已知组优先,未知/缺省回退 id 启发式)。+ * 非用户供应商一律走 isChatEligible(mode 权威、id 正则兜底)。*/export function isAgentSelectableModel(- model: { id: string; group?: string },+ model: { id: string; group?: string; mode?: string },opts?: { userProvider?: boolean },): boolean {if (opts?.userProvider === true && model.group && !KNOWN_CATEGORIES.has(model.group)) {return true;}- return AGENT_MODEL_CATEGORIES.has(groupOf(model));-}--/**- * 决定一个模型的厂商分组 —— **数据优先**:目录里带了合法 `group` 就用它,- * 否则回退到 id 前缀归类(categorize)。未知的 group 值(渲染层没有对应标签)也回退,- * 避免出现没有 i18n 标签的空分组。- */-export function groupOf(model: { id: string; group?: string }): ModelCategory {- if (model.group && KNOWN_CATEGORIES.has(model.group)) return model.group as ModelCategory;- return categorize(model.id);+ return isChatEligible(model);}-/** groupModelsForDisplay 的最小模型形状(只需 id + 可选 group / sortOrder)。 */+/** groupModelsForDisplay 的最小模型形状(id + 可选 group / mode / sortOrder)。 */export interface DisplayModel {id: string;group?: string;+ mode?: string;sortOrder?: number;}/*** 选择器右栏的「分组 + 排序」纯逻辑 —— **完全由目录数据驱动**:* 1. 先按 `sortOrder` 升序稳定排序(缺省排末尾,相等时保持入参顺序);- * 2. 按 `groupOf`(group 字段优先 / 前缀兜底)分桶;+ * 2. 按 `classifyModel`(mode 优先 / group 字段次之 / id 前缀兜底)分桶;* 3. 桶的先后 = 桶内首个模型在已排序列表里的出现序(= 该桶最小 sortOrder)。* 返回有序的 { category, models } 列表;不依赖写死的 CATEGORY_ORDER 决定展示顺序。*/@@ -164,7 +336,7 @@ export function groupModelsForDisplay<T extends DisplayModel>();const map = new Map<ModelCategory, T[]>();for (const m of sorted) {- const cat = groupOf(m);+ const cat = classifyModel(m);const list = map.get(cat) ?? [];list.push(m);map.set(cat, list);diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex 6ccfae4548..2ba1e8fe73 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -67,6 +67,7 @@ export {providerOffersModel,getModel,sourcesForModel,+ chatEligibleSourcesForModel,resolveRoute,modelSupportsFastMode,sessionModelSupportsFastMode,@@ -119,7 +120,10 @@ export {SUBSCRIPTION_DIRECT_MODEL_PREFIXES,isSubscriptionDirectModel,CATEGORY_ORDER,+ CHAT_VENDOR_CATEGORY_ORDER,categorize,+ classifyModel,+ isChatEligible,groupOf,isAgentSelectableModel,groupModelsForDisplay,diff --git a/packages/model-providers/src/invocation.ts b/packages/model-providers/src/invocation.tsindex 01d684ca65..8c4072f5be 100644--- a/packages/model-providers/src/invocation.ts+++ b/packages/model-providers/src/invocation.ts@@ -22,10 +22,10 @@*/import type { AgentKind, CatalogModel } from './types.js';+import { isAgentSelectableModel } from './classification.js';import {connectedProvidersForAgent,nativeDefaultSourceId,- providerOffersModel,type ProviderView,} from './registry.js';import { reconcileInvocationEffort } from './effortResolution.js';@@ -118,6 +118,13 @@ function availableModelsFor(for (const provider of connectedProvidersForAgent([...ctx.providers], agent)) {for (const m of provider.models[agent] ?? []) {if (seen.has(m.id)) continue;+ // 候选清单本身必须先过 chat 准入(issue #882 第 3 点,2026-07 review 第 20+ // 轮):这里是 model 字段(显式偏好校验 / 场景默认 / 首个可用兜底)唯一的+ // 数据源,不过滤的话非聊天模型会被 has()/fromNative/available[0] 选中当成+ // model,而后面的 providerId 步骤只能校验"选中的来源",无法撤销已经选错+ // 的模型 —— 那时再挡为时已晚。+ if (!isAgentSelectableModel(m, { userProvider: provider.source === 'user' }))+ continue;if (ctx.isVisible && !ctx.isVisible(provider.id, m)) continue;seen.add(m.id);out.push({ id: m.id, efforts: m.efforts, defaultEffort: m.defaultEffort });@@ -218,12 +225,18 @@ export function resolveModelInvocation(const nativeId = nativeDefaultSourceId(rail, agentKind);const native = rail.find((p) => p.id === nativeId);const availableIds = new Set(available.map((m) => m.id));- // 可见性按 **native 源上的那一行**判,不能只看联合清单:某 id 在 native 源被隐藏、- // 他源可见时,选它会让 provider 步骤路由去他源 —— 跳过了 native 源后面还有的- // 可见模型,订阅/计费路由被悄悄换掉(codex review 五轮)。+ // 可见性 / chat 准入都按 **native 源上的那一行**判,不能只看联合清单:某 id+ // 在 native 源被隐藏或是非聊天类型的具体条目、他源可见且聊天可用时,选它会让+ // provider 步骤路由去他源(或选中一个实际不能聊天的 id)—— 跳过了 native 源+ // 后面还有的可见/聊天模型,订阅/计费路由被悄悄换掉(codex review 五轮;mode+ // 校验补于 issue #882 第 3 点,2026-07 review 第 20 轮:availableIds 只证明该+ // id 在**某个**来源聊天可用,不能代表 native 这一份具体条目也是)。fromNative =native?.models[agentKind]?.find(- (m) => availableIds.has(m.id) && (!ctx.isVisible || ctx.isVisible(native.id, m)),+ (m) =>+ availableIds.has(m.id) &&+ isAgentSelectableModel(m, { userProvider: native.source === 'user' }) &&+ (!ctx.isVisible || ctx.isVisible(native.id, m)),)?.id ?? null;}model = fromNative ?? available[0].id;@@ -279,11 +292,22 @@ export function resolveModelInvocation(// 显式点名 A 不能只靠「已连接 + 目录含该模型」就放行 —— 那会绕过 isVisible 的// 来源级契约,路由到用户明确排除的来源(codex review)。const rail = connectedProvidersForAgent([...ctx.providers], agentKind);+ // 「真实提供」还必须含 mode 准入(issue #882 第 3 点,2026-07 review 第 18 轮):+ // providerOffersModel 只看 id 是否存在,不看 mode——同一 id 在这个来源下若是+ // 非聊天类型的具体条目,无人值守派发会把请求发进 image/audio/embedding 端点。+ // 取出该来源自己的这份条目校验 isChatEligible,是下面 visiblyOffers 的基础。+ const chatModelOn = (p: (typeof rail)[number]): CatalogModel | undefined => {+ const cm = p.models[agentKind]?.find((m) => m.id === model);+ return cm !== undefined &&+ isAgentSelectableModel(cm, { userProvider: p.source === 'user' })+ ? cm+ : undefined;+ };const visiblyOffers = (p: (typeof rail)[number]): boolean => {- if (!providerOffersModel(p, model, agentKind)) return false;+ const cm = chatModelOn(p);+ if (cm === undefined) return false;if (!ctx.isVisible) return true;- const cm = p.models[agentKind]?.find((m) => m.id === model);- return cm !== undefined && ctx.isVisible(p.id, cm);+ return ctx.isVisible(p.id, cm);};const named = requestedProvider ? rail.find((p) => p.id === requestedProvider) : undefined;if (requestedProvider && named !== undefined && visiblyOffers(named)) {@@ -307,7 +331,7 @@ export function resolveModelInvocation(// null 会路由进被隐藏的源 —— 仅在这种「下游默认落点不可见」的情况下显式收敛到// 可见源;默认落点本就可见(绝大多数)时维持 null,不改「null=默认路由」契约// (codex review 三轮补全)。- const offering = rail.filter((p) => providerOffersModel(p, model, agentKind));+ const offering = rail.filter((p) => chatModelOn(p) !== undefined);const downstream = offering.find((p) => p.id === nativeDefaultSourceId(offering, agentKind));if (downstream !== undefined && !visiblyOffers(downstream)) {const alternatives = rail.filter(visiblyOffers);diff --git a/packages/model-providers/src/registry.ts b/packages/model-providers/src/registry.tsindex 4a0799bc2c..b08db3b94b 100644--- a/packages/model-providers/src/registry.ts+++ b/packages/model-providers/src/registry.ts@@ -13,6 +13,7 @@*/import type { Catalog, Provider, CatalogModel, AgentKind, RoutingDescriptor } from './types.js';+import { isAgentSelectableModel } from './classification.js';import type { ProviderLogoKind } from './providerBranding.js';import {isModelDisabled,@@ -254,6 +255,31 @@ export function sourcesForModel();}+/**+ * 同 sourcesForModel,但只保留该来源上**这个模型条目本身确实是聊天模型**的来源+ * (issue #882 第 3 点,2026-07 review)。所有"这个来源能不能真的把这个模型发出去"+ * 的判断——路由解析、发送前置校验(空来源拦截)、"选中来源已断连"提示——必须走+ * 同一份口径,否则会出现 UI 说"能发"、resolveRoute 却解析不出可用来源的分裂状态。+ * 只在裸 `sourcesForModel`(仅看 id 是否存在,不看 mode)不够用的场景才需要这个;+ * 纯展示/设置页场景仍应直接用 sourcesForModel,不要在那里过度收紧。+ */+export function chatEligibleSourcesForModel(+ views: ProviderView[],+ modelId: string,+ agent: AgentKind,+ opts: { onlyConnected?: boolean; includeDisabled?: boolean } = {},+): ProviderView[] {+ return sourcesForModel(views, modelId, agent, opts).filter((provider) => {+ const model = getModel(provider, modelId, agent);+ // provider-aware 谓词而非裸 isChatEligible:用户自定义供应商显式配置的模型带未知+ // group,id 撞上能力启发式(如 flux-image-x)时不能被误杀(2026-07 review 第 25 轮)。+ return (+ model !== undefined &&+ isAgentSelectableModel(model, { userProvider: provider.source === 'user' })+ );+ });+}+/*** 某 agent 在已连接来源列表(rail)里的「原生默认来源 id」。* 与模型选择器 activeSourceId 的 nativeDefault 口径一致:@@ -282,7 +308,7 @@ export function effectiveSourceIdForModel(modelId: string,agent: AgentKind,): string | null {- const sources = sourcesForModel(views, modelId, agent);+ const sources = chatEligibleSourcesForModel(views, modelId, agent);if (providerId && sources.some((provider) => provider.id === providerId)) return providerId;return nativeDefaultSourceId(sources, agent);}diff --git a/packages/model-providers/src/sections.ts b/packages/model-providers/src/sections.tsindex e5b235499a..3b815b2885 100644--- a/packages/model-providers/src/sections.ts+++ b/packages/model-providers/src/sections.ts@@ -12,6 +12,7 @@import type { AgentKind, CatalogModel, Effort } from './types.js';import type { ProviderView } from './registry.js';+import { isAgentSelectableModel } from './classification.js';import { deriveModelList, deriveModelSections } from './modelList.js';/**@@ -113,12 +114,20 @@ export function visibleModelUnion(// 2. 条目带 3 个额外可枚举字段(sourceProviderId / sourceConnected / 可选 sourceAccess),// 类型层不可见 —— **禁止把条目整对象 JSON.stringify / spread 进 IPC・协议・持久化**,// 过 wire 前必须显式投影字段(现存 5 个消费方已核查合规;键集有测试锁)。+ // excludeModel: 同 buildProviderSections 的理由(issue #882 第 3 点,2026-07 review)——+ // 现存 5 个调用方(Orca sub-agent 可用性 / 设置页 sub-agent 模型 / 新对话选择器 /+ // Slack `/model` 卡片 / hook session-runner 实际执行)都是"挑一个能聊天/能跑的模型",+ // 非聊天模型不该出现,更不该被 session-runner 当成可执行模型选中。return deriveModelList({providers,agent,providerScope: 'connected-for-agent',isVisible,dedupe: 'first-wins',+ // provider-aware 谓词:用户自定义供应商显式配置的模型带未知 group,id 撞上能力+ // 启发式(如 flux-image-x)时不能被误杀(2026-07 review 第 25 轮)。+ excludeModel: (model, provider) =>+ !isAgentSelectableModel(model, { userProvider: provider.source === 'user' }),});}@@ -136,10 +145,15 @@ export function buildProviderSections(args: {// - 选中豁免仅在 selectedProviderId **非空**时生效(旧实现 provider.id === null// 恒 false,即 flat 语义的「null = 匹配任意行」在这里不适用);// - 字段拷贝保持条件性(undefined 字段不写 key),对象形状逐字节一致。+ // excludeModel:本函数目前的三个调用方(desktop ModelSelector 分段视图 / IM /model+ // 卡片 / mobile 模型选择)都是"挑一个能聊天的模型",不是设置页的完整模型管理——+ // 非聊天模型(issue #882 第 3 点)统一在这里挡掉,调用方不用各自记得过滤(2026-07 review)。const sections = deriveModelSections({providers: args.providers,agent: args.agent,providerScope: 'as-given',+ excludeModel: (model, provider) =>+ !isAgentSelectableModel(model, { userProvider: provider.source === 'user' }),isVisible: (providerId, model) => args.isVisible(providerId, model.id),...(args.selectedModelId !== undefined &&args.selectedProviderId !== undefined &&diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.tsindex a426a96158..f3b2fcf3bb 100644--- a/packages/model-providers/src/types.ts+++ b/packages/model-providers/src/types.ts@@ -219,6 +219,14 @@ export interface CatalogModel {* 缺省时渲染层回退到 id 前缀归类(categorize)。新增未知分组需在渲染层补 i18n 标签。*/group?: string;+ /**+ * Gateway 原生模型能力类型(issue #882:'chat' / 'embedding' / 'image_generation' /+ * 'audio_speech' / ... ,字段值不改名,原样透传)。是否为聊天模型、进哪个+ * ModelMode 展示分类均以此为权威;缺省时回退 id 正则兜底+ * (`classification.ts` classifyModel)。只有 XD 网关来源目前会填充,静态+ * 内置目录留空。+ */+ mode?: string;/*** 展示排序权重(升序)。渲染层按它对模型排序、并据每个分组的最小 sortOrder 决定分组先后。* 缺省排到末尾。仅影响选择器展示顺序,不影响 host 派生的 availableModels 数组序(后者保序)。