Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 移除客户端地区模型过滤 (#2791)

Chris Zhang6aa907e67a3e
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts
index 58c56febee..14387dc62b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts
@@ -106,6 +106,38 @@ describe('deriveCindyMediaConfig — 正常目录', () => {
best: 'v1',
});
});
+
+ it('xAI 动态发现的两个视频模型原样进入候选并保留 provider 归属', () => {
+ const xai: CindyMediaProviderSlice = {
+ id: 'xai',
+ videoModels: [
+ { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ { id: 'xai/grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5' },
+ ],
+ };
+
+ expect(deriveCindyMediaConfig([xai], 'video')).toEqual({
+ models: [
+ {
+ id: 'xai/grok-imagine-video',
+ label: 'Grok Imagine Video',
+ providerId: 'xai',
+ supportsEdit: true,
+ },
+ {
+ id: 'xai/grok-imagine-video-1.5',
+ label: 'Grok Imagine Video 1.5',
+ providerId: 'xai',
+ supportsEdit: true,
+ },
+ ],
+ defaults: {
+ standard: 'xai/grok-imagine-video',
+ draft: 'xai/grok-imagine-video',
+ best: 'xai/grok-imagine-video',
+ },
+ });
+ });
});
describe('deriveCindyMediaConfig — 空清单即不可用', () => {
diff --git a/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts b/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts
index e5428bb7b1..c6e8e37fb4 100644
--- a/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts
+++ b/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts
@@ -96,8 +96,8 @@ export function deriveCindyMediaConfig(
// XD 声明的向量清单 —— 非 XD 供应商(远端目录可以给任何 provider 加这个字段)
// 声明了也不能进白名单,否则会长出"界面可选、实际拿 XD 的凭证去计费"的型号,
// 用户以为用的是自己填的 key(PR #1707 review)。
- // 视频出于同一原因在非 Global 构建里整段隐藏;向量这条更严:任何区域都只认 XD,
- // 因为它连"本区域能不能路由"都还谈不上。provider-aware 路由落地后再放开。
+ // 向量在任何区域都只认 XD,因为它连 provider-aware 路由都还没有。
+ // 地区政策由 Gateway 通过目录下发负责,客户端不按构建区域裁剪模型。
if (kind === 'embed' && p.id !== EMBED_DISPATCH_PROVIDER_ID) continue;
const list =
kind === 'image' ? p.imageModels : kind === 'video' ? p.videoModels : p.embeddingModels;
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index ceb6e711f3..2c78f13f5b 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -305,7 +305,6 @@ import {
storeGhostSecret,
} from '../secrets/providerSecretStore.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
-import { projectProviderCatalogForBuildRegion } from '../maker-host/provider-access-policy.js';
import {
getGrokAccessToken,
getGrokOAuthCredentialGeneration,
@@ -3099,7 +3098,7 @@ function getCatalogMediaConfig(kind: CindyCapabilityKind): CindyMediaCatalogConf
// 停用过滤:用户在 设置 → 模型供应商 停用的媒体模型 / 供应商不进候选清单
// (与对话模型的准入口径同源,见 model-disable-store)。
const access = readModelDisableOverrides();
- const catalog = projectProviderCatalogForBuildRegion(getActiveCatalog(), CURRENT_CINDY_REGION);
+ const catalog = getActiveCatalog();
return deriveCindyMediaConfig(
catalog.providers,
kind,
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
index 02700014a1..1eed5d0118 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
@@ -47,12 +47,17 @@ describe('XD 网关权威模型清单重建', () => {
expect(xdModels('codex')).toEqual([]);
});
- it('远端 Catalog 不能覆盖 XD Provider 壳或注入 XD 模型', () => {
+ it('current Catalog controls the XD media shell while /models controls chat membership', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as typeof BUNDLED_CATALOG;
const catalogXd = catalog.providers.find((provider) => provider.id === 'xd');
- const builtinXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');
- if (!catalogXd || !builtinXd) throw new Error('missing XD provider fixture');
+ if (!catalogXd) throw new Error('missing XD provider fixture');
catalogXd.name = 'Catalog-supplied XD';
+ catalogXd.imageModels = [];
+ delete catalogXd.imageDefaults;
+ catalogXd.embeddingModels = [];
+ delete catalogXd.embeddingDefaults;
+ catalogXd.videoModels = [{ id: 'seedance-fast', name: 'Seedance Fast' }];
+ catalogXd.videoDefaults = { standard: 'seedance-fast' };
catalogXd.models['claude-code'] = [
{
id: 'catalog-only-model',
@@ -66,7 +71,10 @@ describe('XD 网关权威模型清单重建', () => {
setActiveCatalog(catalog);
const activeXd = getActiveCatalog().providers.find((provider) => provider.id === 'xd');
- expect(activeXd?.name).toBe(builtinXd.name);
+ expect(activeXd?.name).toBe('Catalog-supplied XD');
+ expect(activeXd?.imageModels).toEqual([]);
+ expect(activeXd?.embeddingModels).toEqual([]);
+ expect(activeXd?.videoModels).toEqual([{ id: 'seedance-fast', name: 'Seedance Fast' }]);
expect(xdModels('claude-code')).toEqual([]);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts
index a82ef8ac89..1f1984f137 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts
@@ -6,7 +6,7 @@ import { deriveAvailableModels } from '../catalog-to-descriptors.js';
import {
filterProviderCatalogForAccount,
isProviderSelectable,
- projectProviderCatalogForBuildRegion,
+ projectUnverifiedCatalogFallbackForBuildRegion,
} from '../provider-access-policy.js';
function model(id: string): CatalogModel {
@@ -96,33 +96,81 @@ describe('provider access policy', () => {
expect(filterProviderCatalogForAccount(input, {})).toBe(input);
});
- it('preserves the full media catalog and object identity for Global', () => {
- const input = catalog();
- expect(projectProviderCatalogForBuildRegion(input, 'global')).toBe(input);
+ it('keeps Gateway and locally connected xAI models verbatim; account-free mode only removes XD', () => {
+ const xai: Provider = {
+ id: 'xai',
+ name: 'xAI',
+ source: 'builtin',
+ agents: ['claude-code'],
+ auth: { method: 'oauth' },
+ routing: {},
+ models: {
+ 'claude-code': [
+ model('xai/grok-4'),
+ { ...model('xai/grok-imagine-image'), group: 'image' },
+ { ...model('xai/grok-imagine-video'), group: 'video' },
+ { ...model('xai/grok-imagine-video-1.5'), group: 'video' },
+ ],
+ },
+ imageModels: [{ id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' }],
+ videoModels: [
+ { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ { id: 'xai/grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5' },
+ ],
+ };
+ const base = catalog();
+ const input: Catalog = { ...base, providers: [...base.providers, xai] };
+
+ expect(filterProviderCatalogForAccount(input, { canUseCindyGateway: true })).toBe(input);
+
+ const local = filterProviderCatalogForAccount(input, { canUseCindyGateway: false });
+ expect(local.providers.map((item) => item.id)).toEqual(['anthropic', 'xai']);
+ expect(local.providers.find((item) => item.id === 'xai')).toBe(xai);
+ expect(xai.models['claude-code']?.map((item) => item.id)).toEqual([
+ 'xai/grok-4',
+ 'xai/grok-imagine-image',
+ 'xai/grok-imagine-video',
+ 'xai/grok-imagine-video-1.5',
+ ]);
+ expect(xai.imageModels?.map((item) => item.id)).toEqual(['xai/grok-imagine-image']);
+ expect(xai.videoModels?.map((item) => item.id)).toEqual([
+ 'xai/grok-imagine-video',
+ 'xai/grok-imagine-video-1.5',
+ ]);
});
- it.each(['cn', 'dev'] as const)(
- 'projects the Cindy AI media catalog to Mainland capabilities for %s',
- (region) => {
- const projected = projectProviderCatalogForBuildRegion(catalog(), region);
- const xd = projected.providers.find((item) => item.id === 'xd');
+ it('projects only unverified XD fallback media in CN/dev and preserves xAI discovery verbatim', () => {
+ const xai: Provider = {
+ id: 'xai',
+ name: 'xAI',
+ source: 'builtin',
+ agents: ['claude-code'],
+ auth: { method: 'oauth' },
+ routing: {},
+ models: {
+ 'claude-code': [
+ { ...model('xai/grok-imagine-image'), group: 'image' },
+ { ...model('xai/grok-imagine-video'), group: 'video' },
+ ],
+ },
+ imageModels: [{ id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' }],
+ videoModels: [{ id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' }],
+ };
+ const input = catalog();
+ input.providers.push(xai);
+ expect(projectUnverifiedCatalogFallbackForBuildRegion(input, 'global')).toBe(input);
+ for (const region of ['cn', 'dev'] as const) {
+ const projected = projectUnverifiedCatalogFallbackForBuildRegion(input, region);
+ const xd = projected.providers.find((item) => item.id === 'xd');
expect(xd?.imageModels).toEqual([]);
- expect(xd?.imageDefaults).toBeUndefined();
- // 向量与图像同口径:整段清空 —— 该 endpoint 后面全是境外模型,
- // 留着清单只会让插件拿到"可选但必失败"的型号。
expect(xd?.embeddingModels).toEqual([]);
- expect(xd?.embeddingDefaults).toBeUndefined();
expect(xd?.videoModels?.map((item) => item.id)).toEqual([
'seedance-fast',
'seedance-pro',
'bytedance/seedance-2.5',
]);
- expect(xd?.videoDefaults).toEqual({
- standard: 'seedance-fast',
- best: 'seedance-pro',
- });
- // 聊天目录里被归到 embedding 的条目也一并滤掉(设置页的「向量」分组同样清空)。
+ expect(xd?.videoDefaults).toEqual({ standard: 'seedance-fast', best: 'seedance-pro' });
expect(xd?.models['claude-code']?.map((item) => item.id)).toEqual([
'shared-model',
'xd-only-model',
@@ -130,138 +178,34 @@ describe('provider access policy', () => {
'seedance-pro',
'bytedance/seedance-2.5',
]);
- expect(xd?.models.codex).toEqual([]);
- },
- );
-});
+ expect(projected.providers.find((item) => item.id === 'xai')).toBe(xai);
+ }
+ });
-describe('projectProviderCatalogForBuildRegion — 用户自有媒体来源', () => {
- it('非 global 区域只投影 Cindy AI,保留用户连接的图像来源', () => {
- const gemini: Provider = {
- id: 'gemini',
- name: 'Google Gemini',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: {},
- models: { 'claude-code': [] },
- imageModels: [{ id: 'gemini/gemini-3-pro-image', name: 'Gemini 3 Pro Image' }],
- };
- const openai: Provider = {
- id: 'openai',
- name: 'OpenAI',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: {},
- models: { 'claude-code': [] },
- imageModels: [{ id: 'openai/gpt-image-2', name: 'GPT Image 2' }],
- // 防御对象:即使未来用户来源声明 defaults,区域投影也不应改写它。
- imageDefaults: { standard: 'openai/gpt-image-2' },
- };
- const base = catalog();
- const projected = projectProviderCatalogForBuildRegion(
- { ...base, providers: [...base.providers, gemini, openai] },
+ it('projects only the XD media fields that were inherited from bundled', () => {
+ const input = catalog();
+ const projected = projectUnverifiedCatalogFallbackForBuildRegion(
+ input,
'cn',
+ new Set(['embedding']),
);
- expect(projected.providers.find((p) => p.id === 'gemini')).toBe(gemini);
- expect(projected.providers.find((p) => p.id === 'openai')).toBe(openai);
- const xd = projected.providers.find((p) => p.id === 'xd');
- expect(xd?.imageModels).toEqual([]);
- expect(xd?.imageDefaults).toBeUndefined();
- expect(xd?.videoModels?.map((m) => m.id)).toEqual([
+ const originalXd = input.providers.find((provider) => provider.id === 'xd');
+ const xd = projected.providers.find((provider) => provider.id === 'xd');
+
+ expect(xd?.imageModels).toEqual(originalXd?.imageModels);
+ expect(xd?.imageDefaults).toEqual(originalXd?.imageDefaults);
+ expect(xd?.videoModels).toEqual(originalXd?.videoModels);
+ expect(xd?.videoDefaults).toEqual(originalXd?.videoDefaults);
+ expect(xd?.embeddingModels).toEqual([]);
+ expect(xd?.embeddingDefaults).toBeUndefined();
+ expect(xd?.models['claude-code']?.map((model) => model.id)).toEqual([
+ 'shared-model',
+ 'xd-only-model',
+ 'gpt-image-2',
'seedance-fast',
'seedance-pro',
'bytedance/seedance-2.5',
+ 'happyhorse',
]);
});
-
- it.each(['cn', 'dev'] as const)(
- '非 xd 供应商在 %s 保留图像与聊天能力,暂不暴露视频能力',
- (region) => {
- const thirdParty: Provider = {
- id: 'third',
- name: 'Third Party',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: {},
- models: {
- 'claude-code': [
- { ...model('seedance-fast'), group: 'video' },
- { ...model('third/image'), group: 'image' },
- model('chat-model'),
- ],
- codex: undefined,
- },
- imageModels: [{ id: 'third/image', name: 'Third Image' }],
- imageDefaults: { standard: 'third/image' },
- videoModels: [{ id: 'seedance-fast', name: 'Seedance Fast' }],
- videoDefaults: { standard: 'seedance-fast' },
- };
- const base = catalog();
- const projected = projectProviderCatalogForBuildRegion(
- { ...base, providers: [...base.providers, thirdParty] },
- region,
- );
- const third = projected.providers.find((p) => p.id === 'third');
- expect(third).not.toBe(thirdParty);
- expect(third?.models['claude-code']?.map((m) => m.id)).toEqual(['third/image', 'chat-model']);
- expect(third?.models.codex).toEqual([]);
- expect(third?.imageModels).toBe(thirdParty.imageModels);
- expect(third?.imageDefaults).toBe(thirdParty.imageDefaults);
- expect(third?.videoModels).toEqual([]);
- expect(third?.videoDefaults).toBeUndefined();
- },
- );
-
- it('mode: image_generation 的用户模型在 cn 区域保持可用', () => {
- const modeOnly: Provider = {
- id: 'xai',
- name: 'xAI',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: {},
- models: {
- 'claude-code': [
- { ...model('xai/aurora'), mode: 'image_generation' },
- model('xai/grok-chat'),
- ],
- },
- };
- const base = catalog();
- const projected = projectProviderCatalogForBuildRegion(
- { ...base, providers: [...base.providers, modeOnly] },
- 'cn',
- );
- const xai = projected.providers.find((p) => p.id === 'xai');
- expect(xai).toBe(modeOnly);
- expect(xai?.models['claude-code']?.map((m) => m.id)).toEqual([
- 'xai/aurora',
- 'xai/grok-chat',
- ]);
- });
-
- it('global 区域原样返回(含新来源的媒体清单)', () => {
- const gemini: Provider = {
- id: 'gemini',
- name: 'Google Gemini',
- source: 'builtin',
- agents: ['claude-code'],
- auth: { method: 'oauth' },
- routing: {},
- models: { 'claude-code': [] },
- imageModels: [{ id: 'gemini/gemini-3-pro-image', name: 'Gemini 3 Pro Image' }],
- };
- const base = catalog();
- const input = { ...base, providers: [...base.providers, gemini] };
- const projected = projectProviderCatalogForBuildRegion(input, 'global');
- expect(projected).toBe(input);
- });
-
- it('目录没有 Cindy AI 时非 global 也保持原对象', () => {
- const input: Catalog = { version: 'test', providers: [] };
- expect(projectProviderCatalogForBuildRegion(input, 'cn')).toBe(input);
- });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
index 260af588ec..369509c941 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
@@ -9,9 +9,14 @@ const h = vi.hoisted(() => ({
endpoint: 'https://model.cn.example',
buildEndpoint: 'https://model.cn.example',
owner: 'owner-default',
+ canUseCindyGateway: true,
loads: [] as Array<{
source: Record<string, unknown>;
- resolve: (catalog: unknown) => void;
+ resolve: (
+ catalog: unknown,
+ capabilityEvidence?: 'current' | 'fallback',
+ unverifiedXdMediaKinds?: readonly ('image' | 'video' | 'embedding')[],
+ ) => void;
}>,
refreshLoads: [] as Array<{
source: Record<string, unknown>;
@@ -34,9 +39,30 @@ vi.mock('@cindy/model-providers', async (importOriginal) => {
return {
...actual,
loadCatalog: vi.fn(
- (source: Record<string, unknown>) =>
+ (
+ source: Record<string, unknown>,
+ _io: unknown,
+ onResolved?: (result: unknown) => void,
+ ) =>
new Promise((resolve) => {
- h.loads.push({ source, resolve });
+ h.loads.push({
+ source,
+ resolve: (
+ catalog,
+ capabilityEvidence = 'current',
+ unverifiedXdMediaKinds = capabilityEvidence === 'current'
+ ? []
+ : ['image', 'video', 'embedding'],
+ ) => {
+ onResolved?.({
+ catalog,
+ source: capabilityEvidence === 'current' ? 'remote' : 'cache',
+ capabilityEvidence,
+ unverifiedXdMediaKinds,
+ });
+ resolve(catalog);
+ },
+ });
}),
),
loadCatalogWithSource: vi.fn(
@@ -72,8 +98,12 @@ vi.mock('../../appSessionState.js', () => ({
ownerScopedUserDataPath: (...segments: string[]) =>
path.join(os.tmpdir(), 'provider-catalog-realm-reload', h.owner, ...segments),
}));
+vi.mock('../../../shared/brandRegion.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../shared/brandRegion.js')>();
+ return { ...actual, CURRENT_CINDY_REGION: 'cn' };
+});
vi.mock('../../appCapabilities.js', () => ({
- getAppCapabilities: () => ({ canUseCindyGateway: false }),
+ getAppCapabilities: () => ({ canUseCindyGateway: h.canUseCindyGateway }),
}));
vi.mock('../../ownerNamespaceMigration.js', () => ({
hasLegacyOwnerNamespaceClaim: () => false,
@@ -139,6 +169,7 @@ import {
type Catalog,
type CustomProviderConfig,
} from '@cindy/model-providers';
+import { deriveCindyMediaConfig } from '../../cindy-brain/cindyMediaCatalog.js';
import {
getActiveCatalog,
commitModelPlaneFromCatalog,
@@ -150,6 +181,7 @@ import {
import {
__testing,
ensureActiveCatalogLoaded,
+ getDesktopSelectableCatalog,
refreshActiveCatalogFromSource,
refreshCustomProvidersIntoCatalog,
reloadActiveCatalogForEndpointChange,
@@ -513,9 +545,19 @@ describe('provider catalog realm reload', () => {
baseUrl: 'https://model.cn.example',
fallbackBaseUrl: 'https://legacy-build-cdn.example',
});
- h.loads[0]!.resolve(catalogNamed('catalog-cn-initial'));
+ h.loads[0]!.resolve(catalogNamed('catalog-cn-initial'), 'current', ['embedding']);
await initial;
expect(activeMarker()).toBe('catalog-cn-initial');
+ const startupXd = getDesktopSelectableCatalog().providers.find(
+ (provider) => provider.id === 'xd',
+ );
+ expect(startupXd?.imageModels).toEqual(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd')?.imageModels,
+ );
+ expect(startupXd?.videoModels).toEqual(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd')?.videoModels,
+ );
+ expect(startupXd?.embeddingModels).toEqual([]);
h.endpoint = 'https://model.global.example';
const globalReload = reloadActiveCatalogForEndpointChange();
@@ -538,10 +580,178 @@ describe('provider catalog realm reload', () => {
expect(activeMarker()).toBe('catalog-cn-latest');
});
+ it('keeps bundled/LKG/waiting catalogs region-safe without hiding discovered xAI media', async () => {
+ const catalogWithXaiMedia = structuredClone(catalogNamed('catalog-with-xai-media'));
+ const xai = catalogWithXaiMedia.providers.find((provider) => provider.id === 'xai');
+ if (!xai) throw new Error('expected xAI provider');
+ xai.imageModels = [
+ { id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' },
+ ];
+ xai.imageDefaults = { standard: 'xai/grok-imagine-image' };
+ xai.videoModels = [
+ { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ { id: 'xai/grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5' },
+ ];
+ xai.videoDefaults = { standard: 'xai/grok-imagine-video' };
+
+ h.endpoint = 'https://model.cn-fallback.example';
+ const fallbackReload = reloadActiveCatalogForEndpointChange();
+
+ // The endpoint-switch window uses bundled data, but it cannot advertise Global XD media.
+ const waitingXd = getDesktopSelectableCatalog().providers.find((provider) => provider.id === 'xd');
+ expect(waitingXd?.imageModels).toEqual([]);
+ expect(waitingXd?.embeddingModels).toEqual([]);
+ expect(waitingXd?.videoModels?.map((model) => model.id)).not.toContain('happyhorse');
+
+ h.loads.at(-1)!.resolve(catalogWithXaiMedia, 'fallback');
+ await fallbackReload;
+
+ const fallbackCatalog = getDesktopSelectableCatalog();
+ const fallbackXd = fallbackCatalog.providers.find((provider) => provider.id === 'xd');
+ expect(fallbackXd?.imageModels).toEqual([]);
+ expect(fallbackXd?.embeddingModels).toEqual([]);
+ expect(fallbackXd?.videoModels?.map((model) => model.id)).not.toContain('happyhorse');
+ expect(
+ fallbackCatalog.providers.find((provider) => provider.id === 'xai')?.videoModels?.map(
+ (model) => model.id,
+ ),
+ ).toEqual(['xai/grok-imagine-video', 'xai/grok-imagine-video-1.5']);
+ expect(deriveCindyMediaConfig(fallbackCatalog.providers, 'embed')).toEqual({
+ models: [],
+ defaults: null,
+ });
+ expect(
+ deriveCindyMediaConfig(fallbackCatalog.providers, 'video').models.map((model) => model.id),
+ ).toContain('xai/grok-imagine-video-1.5');
+
+ h.endpoint = 'https://model.cn-current.example';
+ const currentReload = reloadActiveCatalogForEndpointChange();
+ expect(
+ getDesktopSelectableCatalog()
+ .providers.find((provider) => provider.id === 'xd')
+ ?.videoModels?.map((model) => model.id),
+ ).not.toContain('happyhorse');
+ const currentCatalogWithExplicitXd = structuredClone(catalogWithXaiMedia);
+ const explicitXd = currentCatalogWithExplicitXd.providers.find(
+ (provider) => provider.id === 'xd',
+ );
+ if (!explicitXd) throw new Error('expected XD provider');
+ explicitXd.imageModels = [];
+ delete explicitXd.imageDefaults;
+ explicitXd.embeddingModels = [];
+ delete explicitXd.embeddingDefaults;
+ explicitXd.videoModels = [{ id: 'seedance-fast', name: 'Seedance Fast' }];
+ explicitXd.videoDefaults = { standard: 'seedance-fast' };
+ h.loads.at(-1)!.resolve(currentCatalogWithExplicitXd, 'current');
+ await currentReload;
+
+ const currentCatalog = getDesktopSelectableCatalog();
+ const currentXd = currentCatalog.providers.find((provider) => provider.id === 'xd');
+ expect(currentXd?.imageModels).toEqual([]);
+ expect(currentXd?.embeddingModels).toEqual([]);
+ expect(currentXd?.videoModels).toEqual([{ id: 'seedance-fast', name: 'Seedance Fast' }]);
+ expect(deriveCindyMediaConfig(currentCatalog.providers, 'embed')).toEqual({
+ models: [],
+ defaults: null,
+ });
+ expect(
+ currentCatalog.providers.find((provider) => provider.id === 'xai')?.videoModels?.map(
+ (model) => model.id,
+ ),
+ ).toEqual(['xai/grok-imagine-video', 'xai/grok-imagine-video-1.5']);
+
+ // Restore the baseline expected by the following realm-race tests.
+ h.endpoint = 'https://model.cn.example';
+ const reset = reloadActiveCatalogForEndpointChange();
+ h.loads.at(-1)!.resolve(catalogNamed('catalog-cn-latest'));
+ await reset;
+ });
+
+ it('keeps bundled XD backfill field-scoped across endpoint reload and refresh', async () => {
+ const inheritedAll = structuredClone(catalogNamed('current-with-bundled-xd'));
+ const inheritedXai = inheritedAll.providers.find((provider) => provider.id === 'xai');
+ if (!inheritedXai) throw new Error('expected xAI provider');
+ inheritedXai.imageModels = [
+ { id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' },
+ ];
+ inheritedXai.videoModels = [
+ { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ ];
+
+ h.endpoint = 'https://model.cn-primary-missing-xd.example';
+ const reload = reloadActiveCatalogForEndpointChange();
+ h.loads.at(-1)!.resolve(
+ inheritedAll,
+ 'current',
+ ['image', 'video', 'embedding'],
+ );
+ await reload;
+
+ const projectedAll = getDesktopSelectableCatalog();
+ const projectedAllXd = projectedAll.providers.find((provider) => provider.id === 'xd');
+ expect(projectedAllXd?.imageModels).toEqual([]);
+ expect(projectedAllXd?.embeddingModels).toEqual([]);
+ expect(projectedAllXd?.videoModels?.map((model) => model.id)).not.toContain('happyhorse');
+ expect(projectedAll.providers.find((provider) => provider.id === 'xai')?.videoModels).toEqual(
+ inheritedXai.videoModels,
+ );
+
+ const inheritedEmbedding = structuredClone(inheritedAll);
+ const inheritedEmbeddingXd = inheritedEmbedding.providers.find(
+ (provider) => provider.id === 'xd',
+ );
+ if (!inheritedEmbeddingXd) throw new Error('expected XD provider');
+ inheritedEmbeddingXd.imageModels = [
+ { id: 'gateway-current-image', name: 'Gateway Current Image' },
+ ];
+ inheritedEmbeddingXd.videoModels = [
+ { id: 'gateway-current-video', name: 'Gateway Current Video' },
+ ];
+
+ const partialRefresh = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: inheritedEmbedding,
+ source: 'remote',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: ['embedding'],
+ });
+ await partialRefresh;
+
+ const projectedEmbedding = getDesktopSelectableCatalog().providers.find(
+ (provider) => provider.id === 'xd',
+ );
+ expect(projectedEmbedding?.imageModels).toEqual(inheritedEmbeddingXd.imageModels);
+ expect(projectedEmbedding?.videoModels).toEqual(inheritedEmbeddingXd.videoModels);
+ expect(projectedEmbedding?.embeddingModels).toEqual([]);
+
+ const evidenceUpgrade = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: structuredClone(inheritedEmbedding),
+ source: 'remote',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: [],
+ });
+ await evidenceUpgrade;
+
+ expect(
+ getDesktopSelectableCatalog()
+ .providers.find((provider) => provider.id === 'xd')
+ ?.embeddingModels,
+ ).toEqual(inheritedEmbeddingXd.embeddingModels);
+
+ h.endpoint = 'https://model.cn.example';
+ const reset = reloadActiveCatalogForEndpointChange();
+ h.loads.at(-1)!.resolve(catalogNamed('catalog-cn-latest'));
+ await reset;
+ });
+
it('ignores an automatic refresh response from a superseded realm', async () => {
+ const staleRefreshIndex = h.refreshLoads.length;
const staleRefresh = refreshActiveCatalogFromSource();
await Promise.resolve();
- expect(h.refreshLoads[0]?.source).toMatchObject({
+ expect(h.refreshLoads[staleRefreshIndex]?.source).toMatchObject({
baseUrl: 'https://model.cn.example',
});
@@ -553,24 +763,25 @@ describe('provider catalog realm reload', () => {
);
await globalReload;
+ const currentRefreshIndex = h.refreshLoads.length;
const currentRefresh = refreshActiveCatalogFromSource();
await Promise.resolve();
- expect(h.refreshLoads[1]?.source).toMatchObject({
+ expect(h.refreshLoads[currentRefreshIndex]?.source).toMatchObject({
baseUrl: 'https://model.global.example',
});
- h.refreshLoads[1]!.resolve({
+ h.refreshLoads[currentRefreshIndex]!.resolve({
catalog: catalogNamed('catalog-global-refreshed', '2026-07-31T12:30:00.000Z'),
source: 'remote',
});
await currentRefresh;
- h.refreshLoads[0]!.resolve({
+ h.refreshLoads[staleRefreshIndex]!.resolve({
catalog: catalogNamed('catalog-cn-stale', '2026-07-31T13:00:00.000Z'),
source: 'remote',
});
await staleRefresh;
- expect(activeMarker()).toBe('catalog-global-current');
+ expect(activeMarker()).toBe('catalog-global-refreshed');
expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-07-31T12:30:00.000Z');
});
@@ -606,6 +817,175 @@ describe('provider catalog realm reload', () => {
).toEqual(activeXaiModels);
});
+ it('installs a same-registry fallback snapshot and propagates evidence atomically', async () => {
+ const current = structuredClone(
+ catalogNamed('catalog-current-before-same-registry-fallback', '2026-07-31T12:30:00.000Z'),
+ );
+ setActiveCatalog(current, { capabilityEvidence: 'current' });
+
+ const fallback = structuredClone(current);
+ fallback.providers[0] = {
+ ...fallback.providers[0]!,
+ name: 'catalog-fallback-same-registry',
+ };
+ const fallbackXd = fallback.providers.find((provider) => provider.id === 'xd');
+ const fallbackXai = fallback.providers.find((provider) => provider.id === 'xai');
+ if (!fallbackXd || !fallbackXai) throw new Error('expected fallback providers');
+ fallbackXd.imageModels = [{ id: 'fallback-image', name: 'Fallback Image' }];
+ fallbackXd.videoModels = [{ id: 'fallback-video', name: 'Fallback Video' }];
+ fallbackXd.embeddingModels = [{ id: 'fallback-embedding', name: 'Fallback Embedding' }];
+ fallbackXai.videoModels = [
+ { id: 'xai/grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5' },
+ ];
+
+ const events: number[] = [];
+ setActiveCatalogChangedListener((revision) => events.push(revision));
+ try {
+ const refresh = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: fallback,
+ source: 'cache',
+ capabilityEvidence: 'fallback',
+ });
+ await refresh;
+
+ expect(activeMarker()).toBe('catalog-fallback-same-registry');
+ const projected = getDesktopSelectableCatalog();
+ expect(projected.providers.find((provider) => provider.id === 'xd')).toMatchObject({
+ imageModels: [],
+ videoModels: [],
+ embeddingModels: [],
+ });
+ expect(projected.providers.find((provider) => provider.id === 'xai')?.videoModels).toEqual(
+ fallbackXai.videoModels,
+ );
+ expect(events).toHaveLength(1);
+
+ const exactFallbackRepeat = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: structuredClone(fallback),
+ source: 'cache',
+ capabilityEvidence: 'fallback',
+ });
+ await exactFallbackRepeat;
+
+ expect(events).toHaveLength(1);
+
+ const evidenceUpgrade = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: structuredClone(fallback),
+ source: 'remote',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: ['image'],
+ });
+ await evidenceUpgrade;
+
+ expect(
+ getDesktopSelectableCatalog().providers.find((provider) => provider.id === 'xd'),
+ ).toMatchObject({
+ imageModels: [],
+ videoModels: fallbackXd.videoModels,
+ embeddingModels: fallbackXd.embeddingModels,
+ });
+ expect(events).toHaveLength(2);
+
+ const exactRepeat = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: structuredClone(fallback),
+ source: 'remote',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: ['image'],
+ });
+ await exactRepeat;
+
+ expect(events).toHaveLength(2);
+ } finally {
+ setActiveCatalogChangedListener(null);
+ }
+ });
+
+ it('projects a newer fallback refresh, then promotes identical current evidence', async () => {
+ const current = structuredClone(
+ catalogNamed('catalog-current-before-fallback-refresh', '2026-07-31T12:30:00.000Z'),
+ );
+ setActiveCatalog(current, { capabilityEvidence: 'current' });
+ expect(
+ getDesktopSelectableCatalog()
+ .providers.find((provider) => provider.id === 'xd')
+ ?.embeddingModels?.map((model) => model.id),
+ ).toContain('voyage/voyage-4');
+
+ const fallback = structuredClone(
+ catalogNamed('catalog-fallback-refresh', '2026-07-31T13:00:00.000Z'),
+ );
+ const xai = fallback.providers.find((provider) => provider.id === 'xai');
+ if (!xai) throw new Error('expected xAI provider');
+ xai.imageModels = [{ id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' }];
+ xai.videoModels = [
+ { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ { id: 'xai/grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5' },
+ ];
+
+ const refresh = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: fallback,
+ source: 'cache',
+ capabilityEvidence: 'fallback',
+ });
+ await refresh;
+
+ const projected = getDesktopSelectableCatalog();
+ const xd = projected.providers.find((provider) => provider.id === 'xd');
+ expect(xd?.imageModels).toEqual([]);
+ expect(xd?.embeddingModels).toEqual([]);
+ expect(xd?.videoModels?.map((model) => model.id)).not.toContain('happyhorse');
+ expect(projected.providers.find((provider) => provider.id === 'xai')?.videoModels).toEqual(
+ xai.videoModels,
+ );
+
+ const recoveredCatalog = structuredClone(fallback);
+ recoveredCatalog.providers[0] = {
+ ...recoveredCatalog.providers[0]!,
+ name: 'catalog-current-same-registry',
+ };
+ const recoveredXd = recoveredCatalog.providers.find((provider) => provider.id === 'xd');
+ const recoveredXai = recoveredCatalog.providers.find((provider) => provider.id === 'xai');
+ if (!recoveredXd || !recoveredXai) throw new Error('expected recovered providers');
+ recoveredXd.imageModels = [];
+ delete recoveredXd.imageDefaults;
+ recoveredXd.embeddingModels = [];
+ delete recoveredXd.embeddingDefaults;
+ recoveredXd.videoModels = [{ id: 'seedance-fast', name: 'Seedance Fast' }];
+ recoveredXd.videoDefaults = { standard: 'seedance-fast' };
+ recoveredXai.videoModels = [
+ { id: 'xai/grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5' },
+ ];
+
+ const recovered = refreshActiveCatalogFromSource();
+ await Promise.resolve();
+ h.refreshLoads.at(-1)!.resolve({
+ catalog: recoveredCatalog,
+ source: 'remote',
+ capabilityEvidence: 'current',
+ });
+ await recovered;
+
+ const promoted = getDesktopSelectableCatalog();
+ const promotedXd = promoted.providers.find((provider) => provider.id === 'xd');
+ expect(activeMarker()).toBe('catalog-current-same-registry');
+ expect(promotedXd?.imageModels).toEqual([]);
+ expect(promotedXd?.embeddingModels).toEqual([]);
+ expect(promotedXd?.videoModels).toEqual([{ id: 'seedance-fast', name: 'Seedance Fast' }]);
+ expect(promoted.providers.find((provider) => provider.id === 'xai')?.videoModels).toEqual(
+ recoveredXai.videoModels,
+ );
+ });
+
it('按时间语义守卫 offset/Z 等价 revision,拒收真实旧值和坏值,接受真实新值', async () => {
setActiveCatalog(catalogNamed('current-offset', '2026-08-02T10:00:00+08:00'));
h.warn.mockClear();
@@ -618,13 +998,15 @@ describe('provider catalog realm reload', () => {
};
try {
- // 同一时刻仅 ISO 表示不同:Registry 内容相同,应 no-op 且不误报警。
+ // 同一时刻仅 ISO 表示不同:Registry 关系仍为 same;完整 Catalog 快照不同则
+ // 原子安装 incoming,但不应误报同 revision 冲突。
await refreshWith('equivalent-z', '2026-08-02T02:00:00.000Z');
- expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-08-02T10:00:00+08:00');
+ expect(activeMarker()).toBe('equivalent-z');
+ expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-08-02T02:00:00.000Z');
expect(h.warn).not.toHaveBeenCalled();
await refreshWith('actually-older', '2026-08-02T01:59:59.000Z');
- expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-08-02T10:00:00+08:00');
+ expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-08-02T02:00:00.000Z');
await refreshWith('actually-newer', '2026-08-02T03:00:00.000Z');
expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-08-02T03:00:00.000Z');
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 6d7955f81d..34b01315f6 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -24,19 +24,25 @@
* createDesktopProviderService.ts,这样依赖本 holder 的纯逻辑模块(及其单测)不被 electron 污染。
*/
+import { isDeepStrictEqual } from 'node:util';
+
import {
BUNDLED_CATALOG,
buildUserProvider,
findModelRegistryRoute,
type AgentKind,
type Catalog,
+ type CatalogCapabilityEvidence,
+ type CatalogXdMediaKind,
type CatalogModel,
type CustomProviderConfig,
type Provider,
type ProviderWireProtocol,
} from '@cindy/model-providers';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import { CHATGPT_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
+import { projectUnverifiedCatalogFallbackForBuildRegion } from './provider-access-policy.js';
import {
applyLocalConsumerOverrides,
applyLocalOverridesToRoot,
@@ -58,6 +64,14 @@ import {
/** OSS / bundled 加载来的基础目录;null = 尚未加载(回落 BUNDLED_CATALOG)。 */
let base: Catalog | null = null;
+/** 当前基础目录是否由本次配置的 Catalog 真源明确证明;fallback 只保兼容元数据。 */
+let baseCapabilityEvidence: CatalogCapabilityEvidence = 'fallback';
+/** XD media fields inherited from bundled rather than proven by the current source. */
+let baseUnverifiedXdMediaKinds: ReadonlySet<CatalogXdMediaKind> = new Set([
+ 'image',
+ 'video',
+ 'embedding',
+]);
/** Last trusted Registry used only to re-project user configs; it never changes catalog membership. */
let trustedCustomProviderRegistry: Catalog['modelRegistry'] = BUNDLED_CATALOG.modelRegistry;
/** 用户自定义供应商(已 buildUserProvider 展开的标准 Provider),追加在 base 之后。 */
@@ -675,7 +689,15 @@ function withEmptyModels(p: Provider): Provider {
}
function computeMerged(): Catalog {
- const b = base ?? BUNDLED_CATALOG;
+ const source = base ?? BUNDLED_CATALOG;
+ const b =
+ baseCapabilityEvidence === 'current'
+ ? projectUnverifiedCatalogFallbackForBuildRegion(
+ source,
+ CURRENT_CINDY_REGION,
+ baseUnverifiedXdMediaKinds,
+ )
+ : projectUnverifiedCatalogFallbackForBuildRegion(source, CURRENT_CINDY_REGION);
// Dynamic OpenAI/Anthropic roots are rebuilt from discovery/registry below,
// but the daily OSS catalog may carry sparse PI protocol annotations. Keep
// only that metadata and apply it after existence has been independently
@@ -712,13 +734,24 @@ function computeMerged(): Catalog {
// 作者错误隔离进 warnings,由刷新路径读走打日志,不拖垮其余条目。
const plan = planRegistryRoots(b.modelRegistry);
lastPlanWarnings = plan.warnings;
- // XD Provider 使用随客户端发布的固定壳,远端 Catalog 只能管理非 XD Provider。
- // `/models` 会在下方重建固定壳的全部模型,Catalog 缺失、刷新或异常都不能改变 XD。
- const builtinXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');
+ // XD 的对话模型成员仍由下方 `/models` 权威重建,但 provider 壳中的媒体清单、
+ // 默认项和显式空值必须服从当前 Catalog。只有目录本身缺少 XD(生产加载经
+ // mergeWithBundled 后通常不会发生)才回落与 evidence 同级安全的 bundled 壳。
+ const fallbackXdCatalog =
+ baseCapabilityEvidence === 'current'
+ ? projectUnverifiedCatalogFallbackForBuildRegion(
+ BUNDLED_CATALOG,
+ CURRENT_CINDY_REGION,
+ baseUnverifiedXdMediaKinds,
+ )
+ : projectUnverifiedCatalogFallbackForBuildRegion(BUNDLED_CATALOG, CURRENT_CINDY_REGION);
+ const catalogXd = b.providers.find((provider) => provider.id === 'xd');
+ const xdShell =
+ catalogXd ?? fallbackXdCatalog.providers.find((provider) => provider.id === 'xd');
const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');
const remoteXdIndex = b.providers.findIndex((provider) => provider.id === 'xd');
const providerSources = b.providers.filter((provider) => provider.id !== 'xd');
- if (builtinXd) providerSources.splice(Math.max(0, remoteXdIndex), 0, builtinXd);
+ if (xdShell) providerSources.splice(Math.max(0, remoteXdIndex), 0, xdShell);
let providers: Provider[] = providerSources;
// 先清零已退役的静态 providers.models 段:无论目录来自 bundled 还是远端,
@@ -1006,18 +1039,75 @@ export function getCatalogModelContextWindow(
}
/** 由 host 的目录加载器(ensureActiveCatalogLoaded)在拉取成功后写入基础目录。 */
-export function setActiveCatalog(catalog: Catalog): void {
+function installActiveCatalog(
+ catalog: Catalog,
+ capabilityEvidence: CatalogCapabilityEvidence,
+ unverifiedXdMediaKinds: readonly CatalogXdMediaKind[],
+ force: boolean,
+): boolean {
const previous = base ?? BUNDLED_CATALOG;
+ const nextUnverifiedXdMediaKinds = new Set(unverifiedXdMediaKinds);
+ if (
+ !force &&
+ base !== null &&
+ baseCapabilityEvidence === capabilityEvidence &&
+ isDeepStrictEqual(baseUnverifiedXdMediaKinds, nextUnverifiedXdMediaKinds) &&
+ isDeepStrictEqual(base, catalog)
+ ) {
+ return false;
+ }
const projectionRegistry =
catalog.modelRegistry ?? previous.modelRegistry ?? trustedCustomProviderRegistry;
trustedCustomProviderRegistry = projectionRegistry;
base = catalog;
+ baseCapabilityEvidence = capabilityEvidence;
+ baseUnverifiedXdMediaKinds = nextUnverifiedXdMediaKinds;
if (customConfigs) {
custom = customConfigs.map((config) =>
buildUserProvider(config, { modelRegistry: projectionRegistry }),
);
}
markChanged();
+ return true;
+}
+
+export function setActiveCatalog(
+ catalog: Catalog,
+ options: {
+ capabilityEvidence?: CatalogCapabilityEvidence;
+ unverifiedXdMediaKinds?: readonly CatalogXdMediaKind[];
+ } = {},
+): void {
+ const capabilityEvidence = options.capabilityEvidence ?? 'current';
+ installActiveCatalog(
+ catalog,
+ capabilityEvidence,
+ options.unverifiedXdMediaKinds ??
+ (capabilityEvidence === 'fallback' ? ['image', 'video', 'embedding'] : []),
+ true,
+ );
+}
+
+/**
+ * Atomically install one complete source snapshot and its capability evidence. Refresh
+ * callers use this instead of comparing only modelRegistry: media lists, presets and
+ * explicit empty fields are part of the same catalog truth. Exact no-ops stay silent.
+ */
+export function commitActiveCatalogSnapshot(
+ catalog: Catalog,
+ options: {
+ capabilityEvidence?: CatalogCapabilityEvidence;
+ unverifiedXdMediaKinds?: readonly CatalogXdMediaKind[];
+ } = {},
+): boolean {
+ const capabilityEvidence = options.capabilityEvidence ?? 'current';
+ return installActiveCatalog(
+ catalog,
+ capabilityEvidence,
+ options.unverifiedXdMediaKinds ??
+ (capabilityEvidence === 'fallback' ? ['image', 'video', 'embedding'] : []),
+ false,
+ );
}
/**
@@ -1028,7 +1118,13 @@ export function setActiveCatalog(catalog: Catalog): void {
* 「xai 新表 + registry 旧表」的可观测混态窗口。
* 目标不变量:成功且有变化 = 恰 1 revision / 1 broadcast;no-op/拒收 = 0。
*/
-export function commitModelPlaneFromCatalog(catalog: Catalog): void {
+export function commitModelPlaneFromCatalog(
+ catalog: Catalog,
+ options: {
+ capabilityEvidence?: CatalogCapabilityEvidence;
+ unverifiedXdMediaKinds?: readonly CatalogXdMediaKind[];
+ } = {},
+): void {
const current = base ?? BUNDLED_CATALOG;
const incomingXai = catalog.providers.find((provider) => provider.id === 'xai');
const providers =
@@ -1041,6 +1137,12 @@ export function commitModelPlaneFromCatalog(catalog: Catalog): void {
providers,
...(catalog.modelRegistry ? { modelRegistry: catalog.modelRegistry } : {}),
};
+ baseCapabilityEvidence = options.capabilityEvidence ?? 'current';
+ if (options.unverifiedXdMediaKinds !== undefined) {
+ baseUnverifiedXdMediaKinds = new Set(options.unverifiedXdMediaKinds);
+ } else if (baseCapabilityEvidence === 'fallback') {
+ baseUnverifiedXdMediaKinds = new Set(['image', 'video', 'embedding']);
+ }
if (customConfigs) {
custom = customConfigs.map((config) =>
buildUserProvider(config, { modelRegistry: trustedCustomProviderRegistry }),
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index 407d893934..224767911e 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -31,7 +31,9 @@ import {
parseCatalog,
storedCustomProviderId,
type Catalog,
+ type CatalogCapabilityEvidence,
type CatalogIO,
+ type CatalogLoadResult,
type CatalogSourceConfig,
} from '@cindy/model-providers';
@@ -40,7 +42,7 @@ import { getBaseUrl } from '../manifestService.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { getBuildClientEndpoint, getClientEndpoint } from '../clientEndpointsService.js';
import {
- commitModelPlaneFromCatalog,
+ commitActiveCatalogSnapshot,
getActiveCatalog,
getModelPlaneWarnings,
setActiveCatalog,
@@ -98,12 +100,8 @@ import {
import { clearXaiMediaModels } from './model-discovery/xai-media.js';
import { getAuthState } from '../authManager.js';
import { getActiveAppSession } from '../appSessionState.js';
-import {
- filterProviderCatalogForAccount,
- projectProviderCatalogForBuildRegion,
-} from './provider-access-policy.js';
+import { filterProviderCatalogForAccount } from './provider-access-policy.js';
import { getAppCapabilities } from '../appCapabilities.js';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
claimDetectedNativeProviderAuth,
migrateLegacyNativeProviderAuthBindings,
@@ -482,10 +480,19 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
const sourceKey = catalogSourceKey(source);
// 首次加载时顺手清掉旧版磁盘缓存孤儿(fire-and-forget,每进程一次)。
void cleanupLegacyCatalogCache();
- activeInflight = loadCatalog(source, io)
+ let capabilityEvidence: CatalogCapabilityEvidence = 'fallback';
+ let unverifiedXdMediaKinds: CatalogLoadResult['unverifiedXdMediaKinds'] = [
+ 'image',
+ 'video',
+ 'embedding',
+ ];
+ activeInflight = loadCatalog(source, io, (result) => {
+ capabilityEvidence = result.capabilityEvidence;
+ unverifiedXdMediaKinds = result.unverifiedXdMediaKinds;
+ })
.then(async (catalog) => {
activeCatalogSourceKey = sourceKey;
- setActiveCatalog(catalog);
+ setActiveCatalog(catalog, { capabilityEvidence, unverifiedXdMediaKinds });
syncLocalCatalogOverridesIntoActiveCatalog();
getActiveCatalog();
logModelPlaneWarnings();
@@ -544,10 +551,19 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
const generation = ++endpointReloadGeneration;
activeCatalogSourceKey = null;
// 必须在网络 await 前失效:登录提交后 renderer/agent 可能立即读取目录。
- setActiveCatalog(BUNDLED_CATALOG);
+ setActiveCatalog(BUNDLED_CATALOG, { capabilityEvidence: 'fallback' });
broadcastReferenceModelPricing();
- const flight = loadCatalog(source, io)
+ let capabilityEvidence: CatalogCapabilityEvidence = 'fallback';
+ let unverifiedXdMediaKinds: CatalogLoadResult['unverifiedXdMediaKinds'] = [
+ 'image',
+ 'video',
+ 'embedding',
+ ];
+ const flight = loadCatalog(source, io, (result) => {
+ capabilityEvidence = result.capabilityEvidence;
+ unverifiedXdMediaKinds = result.unverifiedXdMediaKinds;
+ })
.then((catalog) => {
if (
endpointReloadGeneration !== generation ||
@@ -556,7 +572,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
return getActiveCatalog();
}
activeCatalogSourceKey = sourceKey;
- setActiveCatalog(catalog);
+ setActiveCatalog(catalog, { capabilityEvidence, unverifiedXdMediaKinds });
broadcastReferenceModelPricing();
return getActiveCatalog();
})
@@ -574,9 +590,9 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
* 已完成,再复用同一 `loadCatalogWithSource` 源选择;bundled fallback 视为失败保
* LKG。守卫序:realm/generation → updatedAt 时间单调 → 同一时刻规范化 digest
* (同=no-op,异=拒收+告警——线上纠错必须 forward-fix 抬 updatedAt)。通过后经
- * `commitModelPlaneFromCatalog` **单次 swap、单次 markChanged** 提交,成功且有
+ * `commitActiveCatalogSnapshot` **单次 swap、单次 markChanged** 提交,成功且有
* 变化 = 恰 1 revision/1 广播(出口只有 active-catalog changedListener),
- * no-op/失败/拒收 = 0。
+ * fallback → current 会连同完整目录快照一起替换;精确 no-op/失败/拒收 = 0。
*/
export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
await ensureActiveCatalogLoaded();
@@ -596,7 +612,7 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
}
const generation = endpointReloadGeneration;
const flight = loadCatalogWithSource(sourceConfig, io)
- .then(({ catalog, source }) => {
+ .then(({ catalog, source, capabilityEvidence, unverifiedXdMediaKinds }) => {
if (source === 'bundled') {
throw new Error('catalog refresh exhausted configured sources; keeping current snapshot');
}
@@ -611,8 +627,18 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
const incomingRegistry = catalog.modelRegistry;
if (currentRegistry && incomingRegistry) {
const relation = compareModelRegistryRevisions(incomingRegistry, currentRegistry);
- if (relation === 'older' || relation === 'same') {
- // 旧版拒收;同版同内容纯 no-op。两者都不 commit,零 revision 零广播。
+ if (relation === 'older') {
+ // 旧版拒收,不 commit,零 revision 零广播。
+ return getActiveCatalog();
+ }
+ if (relation === 'same') {
+ // Registry 相同不代表 provider media / presets 等完整目录相同;无论本次
+ // 选中 current 还是 fallback,都必须把完整快照与能力证据原子安装。
+ // commitActiveCatalogSnapshot 会保留完整快照与证据均相同的精确 no-op。
+ commitActiveCatalogSnapshot(catalog, {
+ capabilityEvidence,
+ unverifiedXdMediaKinds,
+ });
return getActiveCatalog();
}
if (relation === 'invalid-incoming') {
@@ -634,7 +660,7 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
return getActiveCatalog();
}
}
- commitModelPlaneFromCatalog(catalog);
+ commitActiveCatalogSnapshot(catalog, { capabilityEvidence, unverifiedXdMediaKinds });
// computeMerged 在这里同步完成,确保告警属于刚提交的同一代目录;不能读取
// 上一代惰性缓存留下的 warnings。
const activeCatalog = getActiveCatalog();
@@ -849,11 +875,7 @@ let singleton: ProviderService | null = null;
* Cindy account session keeps the full active catalog.
*/
export function getDesktopSelectableCatalog(): Catalog {
- const regionCatalog = projectProviderCatalogForBuildRegion(
- getActiveCatalog(),
- CURRENT_CINDY_REGION,
- );
- return filterProviderCatalogForAccount(regionCatalog, {
+ return filterProviderCatalogForAccount(getActiveCatalog(), {
canUseCindyGateway: getAppCapabilities().canUseCindyGateway,
});
}
diff --git a/apps/desktop/src/main/maker-host/provider-access-policy.ts b/apps/desktop/src/main/maker-host/provider-access-policy.ts
index 3eade7c8f4..d340449e29 100644
--- a/apps/desktop/src/main/maker-host/provider-access-policy.ts
+++ b/apps/desktop/src/main/maker-host/provider-access-policy.ts
@@ -1,11 +1,18 @@
/**
* provider-access-policy — runtime gates for user-selectable model providers.
*
- * Routing keeps consuming the full active catalog. This projection only controls the
- * providers and models exposed as selectable capabilities to product surfaces.
+ * Routing and product surfaces consume the same active catalog. Successful Gateway
+ * catalogs and local provider discovery are never region-filtered here. The only
+ * regional projection below applies to unverified compatibility fallbacks, which must
+ * not claim that bundled XD media is currently routable by a regional endpoint.
*/
-import { classifyModel, type Catalog, type Provider } from '@cindy/model-providers';
+import {
+ classifyModel,
+ type Catalog,
+ type CatalogXdMediaKind,
+ type Provider,
+} from '@cindy/model-providers';
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
export interface ProviderAccessContext {
@@ -14,13 +21,18 @@ export interface ProviderAccessContext {
}
const CINDY_AI_PROVIDER_ID = 'xd';
-const MAINLAND_VIDEO_MODEL_IDS: ReadonlySet<string> = new Set([
+const MAINLAND_FALLBACK_VIDEO_MODEL_IDS: ReadonlySet<string> = new Set([
'seedance-fast',
'seedance-pro',
'bytedance/seedance-2.5',
]);
+const ALL_XD_MEDIA_KINDS: ReadonlySet<CatalogXdMediaKind> = new Set([
+ 'image',
+ 'video',
+ 'embedding',
+]);
-function projectVideoDefaults(
+function projectFallbackVideoDefaults(
defaults: Provider['videoDefaults'],
allowedIds: ReadonlySet<string>,
): Provider['videoDefaults'] | undefined {
@@ -33,90 +45,63 @@ function projectVideoDefaults(
}
/**
- * Build-region projection for Cindy-managed media capabilities. Global keeps
- * the catalog source verbatim; Mainland China and dev expose only the media
- * capabilities that the regional Cindy service supports.
- *
- * Region is a build-time choice for Cindy-owned services, not a restriction on
- * providers the user connected locally. OpenAI/Codex OAuth, xAI OAuth, Gemini
- * API keys and custom providers therefore keep their image catalog in every
- * build. Video dispatch is not provider-aware yet, so non-XD video capabilities
- * stay hidden outside Global until the runtime can route them by provider.
- *
- * Embedding clears the Cindy-managed list for Mainland China builds, because
- * every model behind that endpoint is an overseas one. Clearing the list (rather
- * than leaving it and failing at dispatch) is what makes the plugin capability
- * report "unavailable" instead of offering models that are guaranteed to fail.
- *
- * Non-XD providers are left untouched *here* on purpose, but that is not the
- * same as exposing them: unlike image, embedding dispatch is not provider-aware
- * yet (one EmbeddingService holding a single XD Gateway base URL and key), so a
- * non-XD `embeddingModels` list would be dispatched with Cindy's credential
- * rather than the user's own. `deriveCindyMediaConfig` therefore drops non-XD
- * embedding lists in *every* region — see the `kind === 'embed'` guard there.
- * This projection stays region-only; the routing constraint lives with the
- * derivation so both builds get it (PR #1707 review).
+ * A bundled/LKG/legacy snapshot is useful for compatibility metadata, but it is not
+ * evidence that the current regional Gateway can execute every XD media model baked
+ * into that snapshot. Keep the historical CN-safe XD subset until the configured
+ * current catalog source succeeds. Non-XD providers are intentionally untouched:
+ * locally connected providers and their discovery results do not belong to Gateway
+ * regional policy.
*/
-export function projectProviderCatalogForBuildRegion(
+export function projectUnverifiedCatalogFallbackForBuildRegion(
catalog: Catalog,
region: CindyRegion,
+ unverifiedKinds: ReadonlySet<CatalogXdMediaKind> = ALL_XD_MEDIA_KINDS,
): Catalog {
- if (region === 'global') return catalog;
+ if (region === 'global' || unverifiedKinds.size === 0) return catalog;
let changed = false;
const providers = catalog.providers.map((provider) => {
- const isCindyAi = provider.id === CINDY_AI_PROVIDER_ID;
- if (!isCindyAi) {
- const models = Object.fromEntries(
- Object.entries(provider.models).map(([agent, list]) => [
- agent,
- (list ?? []).filter((model) => classifyModel(model) !== 'video'),
- ]),
- ) as Provider['models'];
- const hasVideoModels = Object.values(provider.models).some(
- (list) => list?.some((model) => classifyModel(model) === 'video') ?? false,
- );
- const hasVideoCatalog =
- provider.videoModels !== undefined || provider.videoDefaults !== undefined;
- if (!hasVideoModels && !hasVideoCatalog) return provider;
+ if (provider.id !== CINDY_AI_PROVIDER_ID) return provider;
- changed = true;
- const projected: Provider = {
- ...provider,
- models,
- videoModels: [],
- };
- delete projected.videoDefaults;
- return projected;
- }
- changed = true;
-
- const videoModels = (provider.videoModels ?? []).filter((model) =>
- MAINLAND_VIDEO_MODEL_IDS.has(model.id),
- );
- const videoIds = new Set(videoModels.map((model) => model.id));
- const videoDefaults = projectVideoDefaults(provider.videoDefaults, videoIds);
+ const projectImage = unverifiedKinds.has('image');
+ const projectVideo = unverifiedKinds.has('video');
+ const projectEmbedding = unverifiedKinds.has('embedding');
+ const videoModels = projectVideo
+ ? (provider.videoModels ?? []).filter((model) =>
+ MAINLAND_FALLBACK_VIDEO_MODEL_IDS.has(model.id),
+ )
+ : provider.videoModels;
+ const videoIds = new Set((videoModels ?? []).map((model) => model.id));
+ const videoDefaults = projectVideo
+ ? projectFallbackVideoDefaults(provider.videoDefaults, videoIds)
+ : provider.videoDefaults;
const models = Object.fromEntries(
Object.entries(provider.models).map(([agent, list]) => [
agent,
(list ?? []).filter((model) => {
const group = classifyModel(model);
- if (group === 'image' || group === 'embedding') return false;
- return group !== 'video' || MAINLAND_VIDEO_MODEL_IDS.has(model.id);
+ if (group === 'image' && projectImage) return false;
+ if (group === 'embedding' && projectEmbedding) return false;
+ return (
+ group !== 'video' ||
+ !projectVideo ||
+ MAINLAND_FALLBACK_VIDEO_MODEL_IDS.has(model.id)
+ );
}),
]),
) as Provider['models'];
const projected: Provider = {
...provider,
models,
- imageModels: [],
- videoModels,
- embeddingModels: [],
+ ...(projectImage ? { imageModels: [] } : {}),
+ ...(projectVideo ? { videoModels } : {}),
+ ...(projectEmbedding ? { embeddingModels: [] } : {}),
};
- delete projected.imageDefaults;
- delete projected.videoDefaults;
- delete projected.embeddingDefaults;
+ if (projectImage) delete projected.imageDefaults;
+ if (projectVideo) delete projected.videoDefaults;
+ if (projectEmbedding) delete projected.embeddingDefaults;
if (videoDefaults) projected.videoDefaults = videoDefaults;
+ changed = true;
return projected;
});
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index ec71a8b034..e2906e7792 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -417,9 +417,60 @@ describe('loadCatalog', () => {
{ fetchText: vi.fn(async () => { throw new Error('network down'); }) },
);
- expect(local).toMatchObject({ source: 'local', catalog: { version: 'test' } });
- expect(remote).toMatchObject({ source: 'remote', catalog: { version: 'test' } });
- expect(bundled).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });
+ expect(local).toMatchObject({
+ source: 'local',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ catalog: { version: 'test' },
+ });
+ expect(remote).toMatchObject({
+ source: 'remote',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ catalog: { version: 'test' },
+ });
+ expect(bundled).toEqual({
+ source: 'bundled',
+ capabilityEvidence: 'fallback',
+ unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ catalog: BUNDLED_CATALOG,
+ });
+ });
+
+ it('tracks only XD media fields inherited from bundled in a current snapshot', async () => {
+ const bundledXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');
+ if (!bundledXd) throw new Error('missing bundled XD provider');
+ const oldXd = structuredClone(bundledXd);
+ delete oldXd.embeddingModels;
+ delete oldXd.embeddingDefaults;
+
+ const inherited = await loadCatalogWithSource(
+ { url: 'https://catalog.example.test/providers.json' },
+ {
+ fetchText: vi.fn(async () =>
+ JSON.stringify({ version: '2', providers: [oldXd] }),
+ ),
+ },
+ );
+ expect(inherited.capabilityEvidence).toBe('current');
+ expect(inherited.unverifiedXdMediaKinds).toEqual(['embedding']);
+ expect(
+ inherited.catalog.providers.find((provider) => provider.id === 'xd')?.embeddingModels,
+ ).toEqual(bundledXd.embeddingModels);
+
+ const explicitlyDisabled = await loadCatalogWithSource(
+ { url: 'https://catalog.example.test/providers.json' },
+ {
+ fetchText: vi.fn(async () =>
+ JSON.stringify({ version: '2', providers: [{ ...oldXd, embeddingModels: [] }] }),
+ ),
+ },
+ );
+ expect(explicitlyDisabled.unverifiedXdMediaKinds).toEqual([]);
+ expect(
+ explicitlyDisabled.catalog.providers.find((provider) => provider.id === 'xd')
+ ?.embeddingModels,
+ ).toEqual([]);
});
it('only backfills Pi metadata for proven legacy snapshots across local, remote, and cache', async () => {
@@ -486,6 +537,7 @@ describe('loadCatalog', () => {
},
);
expect(cached).toMatchObject({ source: 'cache', catalog: { version: 'test' } });
+ expect(cached.capabilityEvidence).toBe('fallback');
});
it('keeps a newer cached modelRegistry when a valid remote Catalog is stale', async () => {
@@ -528,6 +580,7 @@ describe('loadCatalog', () => {
);
expect(loaded.source).toBe('remote');
+ expect(loaded.capabilityEvidence).toBe('fallback');
expect(loaded.catalog.providers[0]?.name).toBe(MINIMAL.providers[0]?.name);
expect(loaded.catalog.modelRegistry?.updatedAt).toBe(newerUpdatedAt);
expect(
@@ -573,6 +626,7 @@ describe('loadCatalog', () => {
);
expect(loaded.source).toBe('remote');
+ expect(loaded.capabilityEvidence).toBe('fallback');
expect(loaded.catalog.modelRegistry?.models).toHaveLength(registry.models.length);
expect(warns.some((msg) => msg.includes('republished the same updatedAt'))).toBe(true);
});
@@ -605,6 +659,7 @@ describe('loadCatalog', () => {
);
expect(loaded.source).toBe('remote');
+ expect(loaded.capabilityEvidence).toBe('fallback');
expect(loaded.catalog.modelRegistry?.updatedAt).toBe(newerUpdatedAt);
});
@@ -628,7 +683,12 @@ describe('loadCatalog', () => {
readCache: vi.fn(async () => '{"version":"bad","providers":[]}'),
},
);
- expect(invalid).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });
+ expect(invalid).toEqual({
+ source: 'bundled',
+ capabilityEvidence: 'fallback',
+ unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ catalog: BUNDLED_CATALOG,
+ });
});
it('dev: reads local path, skips network', async () => {
@@ -676,6 +736,26 @@ describe('loadCatalog', () => {
);
expect(JSON.parse(writeCache.mock.calls[0]![1])).not.toHaveProperty('cindyModelMeta');
});
+
+ it('marks legacy OSS as fallback evidence even when its HTTP request succeeds', async () => {
+ const fetchText = vi.fn()
+ .mockRejectedValueOnce(new Error('api unavailable'))
+ .mockResolvedValueOnce(JSON.stringify(MINIMAL));
+ const result = await loadCatalogWithSource(
+ {
+ baseUrl: 'https://model-access.example.com',
+ fallbackBaseUrl: 'https://cdn.example.com/cindy',
+ now: () => 0,
+ },
+ { fetchText },
+ );
+
+ expect(result).toMatchObject({
+ source: 'remote',
+ capabilityEvidence: 'fallback',
+ catalog: { version: 'test' },
+ });
+ });
it('falls back from invalid public API payload to legacy OSS before bundled', async () => {
const fetchText = vi.fn()
.mockResolvedValueOnce(
@@ -726,6 +806,7 @@ describe('loadCatalog', () => {
{ fetchText, readCache },
);
expect(result.source).toBe('cache');
+ expect(result.capabilityEvidence).toBe('fallback');
expect(result.catalog.version).toBe('test');
expect(result.catalog).not.toHaveProperty('cindyModelMeta');
});
@@ -838,7 +919,12 @@ describe('loadCatalog', () => {
{ fetchText },
);
- expect(result).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });
+ expect(result).toEqual({
+ source: 'bundled',
+ capabilityEvidence: 'fallback',
+ unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
+ catalog: BUNDLED_CATALOG,
+ });
expect((Object.prototype as { polluted?: unknown }).polluted).toBeUndefined();
});
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index 939e344ff6..96191f3858 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -91,6 +91,8 @@ export * from './modelAccessBean.js';
export type {
CatalogSourceConfig,
CatalogIO,
+ CatalogCapabilityEvidence,
+ CatalogXdMediaKind,
CatalogLoadResult,
CatalogLoadSource,
} from './source.js';
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index cb74f97630..4710cf88c2 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -65,10 +65,36 @@ export interface CatalogIO {
}
export type CatalogLoadSource = 'local' | 'remote' | 'cache' | 'bundled';
+export type CatalogCapabilityEvidence = 'current' | 'fallback';
+export type CatalogXdMediaKind = 'image' | 'video' | 'embedding';
+
+const ALL_XD_MEDIA_KINDS: readonly CatalogXdMediaKind[] = [
+ 'image',
+ 'video',
+ 'embedding',
+];
export interface CatalogLoadResult {
catalog: Catalog;
source: CatalogLoadSource;
+ /**
+ * `current` means this exact snapshot came from the configured current catalog source
+ * (or an explicit local override). `fallback` covers LKG, legacy OSS and bundled data,
+ * which may keep compatibility metadata but cannot prove current regional availability.
+ */
+ capabilityEvidence: CatalogCapabilityEvidence;
+ /**
+ * XD media fields inherited from the bundled compatibility catalog rather than
+ * explicitly supplied by the current source. These fields still need the regional
+ * fallback projection even when the rest of the snapshot has current evidence.
+ */
+ unverifiedXdMediaKinds: readonly CatalogXdMediaKind[];
+}
+
+function unverifiedXdMediaKindsForPrimary(primary: Catalog): readonly CatalogXdMediaKind[] {
+ const xd = primary.providers.find((provider) => provider.id === 'xd');
+ if (!xd) return ALL_XD_MEDIA_KINDS;
+ return xd.embeddingModels === undefined ? ['embedding'] : [];
}
// 去尾部斜杠。不用 /\/+$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。
@@ -411,7 +437,12 @@ export async function loadCatalogWithSource(
if (text != null) {
const parsed = parseCatalog(text);
log(io, 'info', 'loaded catalog from local path', { path: cfg.localPath });
- return { catalog: mergeWithBundled(parsed), source: 'local' };
+ return {
+ catalog: mergeWithBundled(parsed),
+ source: 'local',
+ capabilityEvidence: 'current',
+ unverifiedXdMediaKinds: unverifiedXdMediaKindsForPrimary(parsed),
+ };
}
} catch (err) {
log(io, 'warn', 'local catalog read/parse failed, falling back', { err: String(err) });
@@ -441,6 +472,9 @@ export async function loadCatalogWithSource(
try {
const text = await io.fetchText(remoteUrl, remainingMs);
let parsed = parseRemoteCatalog(text, allowLegacyModelMeta);
+ let capabilityEvidence: CatalogCapabilityEvidence = allowLegacyModelMeta
+ ? 'fallback'
+ : 'current';
// Never propagate the retired compatibility block into a newly written LKG.
let cacheText = allowLegacyModelMeta ? JSON.stringify(parsed) : text;
const remoteRegistryUpdatedAt = registryUpdatedAt(parsed);
@@ -453,6 +487,7 @@ export async function loadCatalogWithSource(
if (selected.catalog !== parsed) {
parsed = selected.catalog;
cacheText = JSON.stringify(selected.catalog);
+ capabilityEvidence = 'fallback';
log(
io,
'warn',
@@ -482,6 +517,7 @@ export async function loadCatalogWithSource(
const selected = preserveNewerCachedCatalog(parsed, committed).catalog;
if (selected !== parsed) {
parsed = selected;
+ capabilityEvidence = 'fallback';
log(io, 'warn', 'serialized LKG commit preserved a newer catalog snapshot', {
url: logUrl,
remoteUpdatedAt: remoteRegistryUpdatedAt,
@@ -497,7 +533,15 @@ export async function loadCatalogWithSource(
}
}
log(io, 'info', 'loaded catalog from remote', { url: logUrl });
- return { catalog: mergeWithBundled(parsed), source: 'remote' };
+ return {
+ catalog: mergeWithBundled(parsed),
+ source: 'remote',
+ capabilityEvidence,
+ unverifiedXdMediaKinds:
+ capabilityEvidence === 'current'
+ ? unverifiedXdMediaKindsForPrimary(parsed)
+ : ALL_XD_MEDIA_KINDS,
+ };
} catch (err) {
log(io, 'warn', 'remote catalog read/parse failed, trying fallback', {
url: logUrl,
@@ -515,7 +559,12 @@ export async function loadCatalogWithSource(
if (cached !== null) {
const parsed = parseRemoteCatalog(cached, allowLegacyModelMeta);
log(io, 'info', 'loaded last-known-good catalog snapshot', { url: logUrl });
- return { catalog: mergeWithBundled(parsed), source: 'cache' };
+ return {
+ catalog: mergeWithBundled(parsed),
+ source: 'cache',
+ capabilityEvidence: 'fallback',
+ unverifiedXdMediaKinds: ALL_XD_MEDIA_KINDS,
+ };
}
} catch (err) {
log(io, 'warn', 'cached catalog read/parse failed, trying fallback', {
@@ -529,10 +578,26 @@ export async function loadCatalogWithSource(
// 3) 兜底:内置 bundled。
log(io, 'info', 'using bundled catalog');
- return { catalog: BUNDLED_CATALOG, source: 'bundled' };
+ return {
+ catalog: BUNDLED_CATALOG,
+ source: 'bundled',
+ capabilityEvidence: 'fallback',
+ unverifiedXdMediaKinds: ALL_XD_MEDIA_KINDS,
+ };
}
/** 启动期兼容入口:接受最终 bundled fallback,只返回目录快照。 */
-export async function loadCatalog(cfg: CatalogSourceConfig, io: CatalogIO): Promise<Catalog> {
- return (await loadCatalogWithSource(cfg, io)).catalog;
+export async function loadCatalog(
+ cfg: CatalogSourceConfig,
+ io: CatalogIO,
+ onResolved?: (result: CatalogLoadResult) => void,
+): Promise<Catalog> {
+ const result = await loadCatalogWithSource(cfg, io);
+ try {
+ onResolved?.(result);
+ } catch {
+ // Compatibility callers expect this helper to return a valid catalog unconditionally.
+ // Hosts that need the metadata must default to fallback-safe behavior if observation fails.
+ }
+ return result.catalog;
}