Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(model-access): gate paid Cindy AI models (#3430)

bobocbb830cb6aad
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 7b2fb9c36a..cd0efad667 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -61,6 +61,31 @@ describe('maker:event hot path ordering', () => {
expect(wireSessionSource).toContain('installInteractionLifecycleObserver(session, null);');
});
+ it('runs the paid-model fence in the shared Session lifecycle boundary', () => {
+ const wireSessionSource = extractWireSessionSource();
+ const observerStart = wireSessionSource.indexOf('session.setTurnLifecycleObserver({');
+ const observerEnd = wireSessionSource.indexOf('\n });', observerStart);
+ const observerSource = wireSessionSource.slice(observerStart, observerEnd);
+
+ expect(observerStart).toBeGreaterThanOrEqual(0);
+ expect(observerEnd).toBeGreaterThan(observerStart);
+ expect(observerSource).toContain('await verdictForModelRoute(');
+ expect(observerSource).toContain(
+ "if (verdict.kind === 'reroute' && verdict.reason === 'payment-required')",
+ );
+ expect(observerSource).toContain("verdict.reason === 'payment-required'");
+ expectOrder(
+ observerSource,
+ 'await verdictForModelRoute(',
+ 'sessionTurnLeaseTracker.markTurnStarted(',
+ );
+ expectOrder(
+ observerSource,
+ "if (verdict.kind === 'reroute' && verdict.reason === 'payment-required')",
+ 'sessionTurnLeaseTracker.markTurnStarted(',
+ );
+ });
+
it('rejects a fenced leftover terminal before register-side turn effects', () => {
expect(source).toContain('delete rendererEvent.sessionTurnGeneration');
expect(source).toContain('delete rendererEvent.sessionInstanceId');
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index a5e3bd33d4..bbe5885ad9 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -9,7 +9,7 @@
* 1. 执行细节字段(upstream / authStrategy / headerDelete / headerOverride / modelIdRewrite /
* adapter) → 投影后全部消失(安全边界 D3)。
* 2. 即便输入里残留 supportsFastMode → 也一并剥掉(routing 不再承载任何 Fast 信息)。
- * 3. models[agent](含 supportsFastMode 显示门控)原样透传 —— Fast 显隐数据源在这里。
+ * 3. models[agent] 只投影可执行模型并保持旧 Mobile 结构;可用模型的 Fast 字段照常透传。
* 4. disabled runtime 在控制端仍保持禁用,不会被共享 registry 重新列为可选。
* 5. 品牌只以非敏感 logoKind 透传;重命名 preset 仍可识别,upstream 绝不泄漏。
* 只 mock electron(app)+ logger,与同目录 dispatchSendSafety.test 同范式。
@@ -149,16 +149,48 @@ describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {
expect(JSON.stringify(routing)).not.toContain(XD_GATEWAY_BASE_URL);
});
- it('models[agent] 原样透传(Fast 显隐数据源:per-provider supportsFastMode)', () => {
- const { providers } = project({ providers: [xdProviderWithFullRouting()] });
+ it('models[agent] 只投影可执行模型,且不向 Mobile 下发 v5 availability 字段', () => {
+ const provider = xdProviderWithFullRouting();
+ const sourceModels = provider.models['claude-code'] as Array<
+ (typeof provider.models)['claude-code'][number] & {
+ availability?: 'available' | 'requires_payment';
+ }
+ >;
+ sourceModels.push(
+ {
+ id: 'claude-sonnet-available',
+ name: 'Sonnet Available',
+ contextWindow: 200000,
+ efforts: [],
+ defaultEffort: null,
+ supportsFastMode: false,
+ availability: 'available',
+ },
+ {
+ id: 'claude-opus-paid-only',
+ name: 'Opus Paid Only',
+ contextWindow: 200000,
+ efforts: [],
+ defaultEffort: null,
+ supportsFastMode: false,
+ availability: 'requires_payment',
+ },
+ );
+
+ const { providers } = project({ providers: [provider] });
const models = providers[0].models as Record<
string,
- { id: string; supportsFastMode?: boolean }[]
+ { id: string; supportsFastMode?: boolean; availability?: string }[]
>;
expect(models['claude-code'][0]).toMatchObject({
id: 'claude-opus-4-8',
supportsFastMode: true,
});
+ expect(models['claude-code'].map((model) => model.id)).toEqual([
+ 'claude-opus-4-8',
+ 'claude-sonnet-available',
+ ]);
+ expect(models['claude-code'].every((model) => model.availability === undefined)).toBe(true);
});
it('保留模型显示 override 快照并过滤非布尔值', () => {
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 9f81733854..18fe798577 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -360,6 +360,27 @@ function projectRoutingForDisplay(
return out;
}
+/**
+ * Mobile consumes the device-link provider catalog as an executable model list. Paid-only rows are
+ * a Desktop upsell projection, not a cross-device model state: omit them and strip the v5-only
+ * availability marker so both current and independently-updated legacy Mobile clients keep the
+ * published provider model shape.
+ */
+function projectModelsForController(models: unknown): unknown {
+ if (!models || typeof models !== 'object' || Array.isArray(models)) return models;
+ return Object.fromEntries(
+ Object.entries(models as Record<string, unknown>).map(([agent, value]) => {
+ if (!Array.isArray(value)) return [agent, value];
+ const projected = value.flatMap((model) => {
+ if (!model || typeof model !== 'object' || Array.isArray(model)) return [model];
+ const { availability, ...legacyModel } = model as Record<string, unknown>;
+ return availability === 'requires_payment' ? [] : [legacyModel];
+ });
+ return [agent, projected];
+ }),
+ );
+}
+
/**
* 隧道返回投影:`maker:provider:list` 只回「显示用」字段——先从 provider id / upstream
* 解析非敏感 `logoKind`,再剥掉每个 provider 的 `routing` 执行字段(upstream /
@@ -390,6 +411,7 @@ function projectInvokeResultForTunnel(
) {
rest.logoKind = logoKind;
}
+ rest.models = projectModelsForController(p.models);
rest.routing = projectRoutingForDisplay(p.routing);
return rest;
});
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 f0a2b2b0cf..a036cda5da 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
@@ -16,6 +16,7 @@ import { BUNDLED_CATALOG, type CatalogModel } from '@cindy/model-providers';
import {
getActiveCatalog,
getXdGatewayModels,
+ isXdGatewayPaymentRequiredRoute,
resolveXdPiGatewayWireProtocol,
setActiveCatalog,
setAnthropicDiscoveredModels,
@@ -51,6 +52,34 @@ describe('XD 网关权威模型清单重建', () => {
expect(xdModels('codex')).toEqual([]);
});
+ it('刷新失败可隐藏付费行,但派发边界保留最近一次明确拒绝直到成功响应', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setXdGatewayModels([
+ {
+ id: 'paid-only-model',
+ agents: ['claude-code'],
+ availability: 'requires_payment',
+ },
+ ]);
+ expect(isXdGatewayPaymentRequiredRoute('paid-only-model', 'claude-code')).toBe(true);
+
+ setXdGatewayModels([], {
+ authoritative: false,
+ preservePaymentRequiredRoutes: true,
+ });
+ expect(getXdGatewayModels()).toEqual([]);
+ expect(isXdGatewayPaymentRequiredRoute('paid-only-model', 'claude-code')).toBe(true);
+
+ setXdGatewayModels([
+ {
+ id: 'paid-only-model',
+ agents: ['claude-code'],
+ availability: 'available',
+ },
+ ], { authoritative: true });
+ expect(isXdGatewayPaymentRequiredRoute('paid-only-model', 'claude-code')).toBe(false);
+ });
+
it('/models 同时控制 XD chat 与媒体成员,忽略 Catalog 里的旧媒体清单', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as typeof BUNDLED_CATALOG;
const catalogXd = catalog.providers.find((provider) => provider.id === 'xd');
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.ts
index 759ad588f2..57ffb77502 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
@@ -114,6 +114,51 @@ describe('checkModelRoute', () => {
expect(checkModelRoute(v, 'claude-code', 'claude-opus-5', null)).toEqual({ kind: 'pass' });
});
+ it('付费模型实体与刷新失败后 tombstone 都拒绝 XD,且不阻断显式他源', () => {
+ const locked = buildRegistry(
+ {
+ providers: [
+ provider('xd', [model('paid-model', { availability: 'requires_payment' })]),
+ provider('anthropic', [model('paid-model')]),
+ ],
+ } as Catalog,
+ { xd: true, anthropic: true },
+ {},
+ );
+ expect(checkModelRoute(locked, 'claude-code', 'paid-model', 'xd')).toEqual({
+ kind: 'reject',
+ reason: 'payment-required',
+ });
+ expect(checkModelRoute(locked, 'claude-code', 'paid-model', null)).toEqual({
+ kind: 'reroute',
+ providerId: 'anthropic',
+ reason: 'payment-required',
+ });
+
+ const isPaymentRequiredTombstone = (providerId: string | null, modelId: string) =>
+ (providerId === null || providerId === 'xd') && modelId === 'paid-model';
+ const otherSourceOnly = buildRegistry(
+ { providers: [provider('anthropic', [model('paid-model')])] } as Catalog,
+ { anthropic: true },
+ {},
+ );
+ expect(
+ checkModelRoute(otherSourceOnly, 'claude-code', 'paid-model', 'xd', {
+ isPaymentRequiredTombstone,
+ }),
+ ).toEqual({ kind: 'reject', reason: 'payment-required' });
+ expect(
+ checkModelRoute(otherSourceOnly, 'claude-code', 'paid-model', 'anthropic', {
+ isPaymentRequiredTombstone,
+ }),
+ ).toEqual({ kind: 'pass' });
+ expect(
+ checkModelRoute([], 'claude-code', 'paid-model', null, {
+ isPaymentRequiredTombstone,
+ }),
+ ).toEqual({ kind: 'reject', reason: 'payment-required' });
+ });
+
it('能力模型(图像/视频等分组)⇒ reject capability-model(隐式与显式点名同判)', () => {
// 老控制端可经 allowlisted 通道直接点名图像模型当对话模型 —— 选择器的硬排除
// 帮不上,必须在同一边界拒绝(PR #744 review 第四轮)。
diff --git a/apps/desktop/src/main/maker-host/__tests__/subagentModelAccess.test.ts b/apps/desktop/src/main/maker-host/__tests__/subagentModelAccess.test.ts
index 0058d08bf8..f5620fe764 100644
--- a/apps/desktop/src/main/maker-host/__tests__/subagentModelAccess.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/subagentModelAccess.test.ts
@@ -10,7 +10,11 @@ function classify(overrides: Partial<Parameters<typeof classifyClaudeSubagentMod
credentialMode: 'gateway-key',
model: 'sonnet',
gatewayKeyAvailable: true,
- xdSnapshot: { authoritative: true, models: [xdModel('codex/gpt-5.6-sol')] },
+ xdSnapshot: {
+ authoritative: true,
+ models: [xdModel('codex/gpt-5.6-sol')],
+ paymentRequiredModelIds: [],
+ },
providers: [],
...overrides,
});
@@ -20,7 +24,11 @@ describe('Claude subagent model access', () => {
it('denies an absent alias only from the current authoritative XD snapshot', () => {
expect(classify()).toEqual({ status: 'denied' });
expect(classify({
- xdSnapshot: { authoritative: false, models: [xdModel('claude-sonnet-4-6')] },
+ xdSnapshot: {
+ authoritative: false,
+ models: [xdModel('claude-sonnet-4-6')],
+ paymentRequiredModelIds: [],
+ },
}))
.toEqual({ status: 'unknown' });
});
@@ -29,6 +37,7 @@ describe('Claude subagent model access', () => {
const snapshot = {
authoritative: true,
models: [xdModel('claude-sonnet-4-6'), xdModel('xai/grok-4.6')],
+ paymentRequiredModelIds: [],
};
expect(classify({ model: 'sonnet', xdSnapshot: snapshot })).toEqual({ status: 'allowed' });
expect(classify({ model: 'CLAUDE-SONNET-4-6[1m]', xdSnapshot: snapshot }))
@@ -37,6 +46,50 @@ describe('Claude subagent model access', () => {
.toEqual({ status: 'allowed' });
});
+ it('denies a payment-required model from the authoritative XD snapshot', () => {
+ expect(classify({
+ model: 'sonnet',
+ xdSnapshot: {
+ authoritative: true,
+ models: [{
+ ...xdModel('claude-sonnet-4-6'),
+ availability: 'requires_payment',
+ }],
+ paymentRequiredModelIds: ['claude-sonnet-4-6'],
+ },
+ })).toEqual({ status: 'denied' });
+ });
+
+ it('keeps a payment denial while the XD snapshot is non-authoritative', () => {
+ expect(classify({
+ model: 'claude-sonnet-4-6',
+ xdSnapshot: {
+ authoritative: false,
+ models: [],
+ paymentRequiredModelIds: ['claude-sonnet-4-6'],
+ },
+ })).toEqual({ status: 'denied' });
+ });
+
+ it('denies an ambiguous alias when any matching XD generation requires payment', () => {
+ expect(classify({
+ model: 'sonnet',
+ xdSnapshot: {
+ authoritative: true,
+ models: [xdModel('claude-sonnet-4-5')],
+ paymentRequiredModelIds: ['claude-sonnet-4-6'],
+ },
+ })).toEqual({ status: 'denied' });
+ expect(classify({
+ model: 'claude-sonnet-4-5',
+ xdSnapshot: {
+ authoritative: true,
+ models: [xdModel('claude-sonnet-4-5')],
+ paymentRequiredModelIds: ['claude-sonnet-4-6'],
+ },
+ })).toEqual({ status: 'allowed' });
+ });
+
it('does not treat a static or stale non-XD catalog absence as denial', () => {
expect(classify({
providerId: 'anthropic',
@@ -53,7 +106,11 @@ describe('Claude subagent model access', () => {
it('re-evaluates sequential account snapshots instead of retaining a denial', () => {
expect(classify()).toEqual({ status: 'denied' });
expect(classify({
- xdSnapshot: { authoritative: true, models: [xdModel('claude-sonnet-4-6')] },
+ xdSnapshot: {
+ authoritative: true,
+ models: [xdModel('claude-sonnet-4-6')],
+ paymentRequiredModelIds: [],
+ },
})).toEqual({ status: 'allowed' });
});
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 95ba03fc5b..bae127d842 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -143,6 +143,7 @@ export interface XdGatewayAgentOverride {
*/
export interface XdGatewayModelInfo {
id: string;
+ availability?: 'available' | 'requires_payment';
/** Gateway 原生 mode(issue #882,权威分类字段;缺省时下游按 id 正则兜底)。 */
mode?: string;
/** AIGateway 折扣比例(0..1),折后价 = 原价 × (1 - costDiscount)。 */
@@ -187,8 +188,15 @@ export interface XdGatewayModelInfo {
* v3 必需字段在协议边界严格校验;这里不读取公共 Catalog,也不按模型 id 或固定常量补值。
*/
let xdGatewayModels: XdGatewayModelInfo[] = [];
-/** 当前账号最近一次 `/models` 成功响应;false 时空/旧数组都不能作为 deny 证据。 */
+/** 当前账号最近一次 `/models` 成功响应;false 时清单缺席不能作为模型不存在的 deny 证据。 */
let xdGatewayModelsAuthoritative = false;
+/**
+ * 最近一次成功 v5 响应明确拒绝的 XD 对话路由。
+ *
+ * 刷新失败时活动目录会隐藏过期的付费营销行,但既有会话的派发终检仍须保留这份
+ * fail-closed 证据;只有更新的成功响应或账号边界清空才能撤销。
+ */
+let xdGatewayPaymentRequiredRoutes = new Set<string>();
/**
* XD 模型里「由客户端投影给 Codex、但走 Anthropic Messages bridge」的 id 集合。
* Responses → Anthropic Messages bridge,不能误用 XD 的原生 Responses 路由。
@@ -798,6 +806,7 @@ function projectXdGatewayMediaModels(
.map((model) => ({
id: model.id,
name: model.name ?? model.id,
+ ...(model.availability ? { availability: model.availability } : {}),
...(model.modalities ? { modalities: model.modalities } : {}),
}));
const videoModels = gatewayModels
@@ -805,6 +814,7 @@ function projectXdGatewayMediaModels(
.map((model) => ({
id: model.id,
name: model.name ?? model.id,
+ ...(model.availability ? { availability: model.availability } : {}),
...(model.modalities ? { modalities: model.modalities } : {}),
}));
const identity = { ...provider };
@@ -1153,6 +1163,7 @@ function computeMerged(): Catalog {
const contextWindow = ov.contextWindow ?? gm.contextWindow;
const merged: CatalogModel = {
id: gm.id,
+ ...(gm.availability ? { availability: gm.availability } : {}),
// name / contextWindow are required by Model Access v3 and therefore never synthesized.
name: gm.name as string,
...(gm.group !== undefined ? { group: gm.group } : {}),
@@ -1445,12 +1456,21 @@ export function setDiscoveredProviderMediaModels(
*/
export function setXdGatewayModels(
models: XdGatewayModelInfo[],
- options?: { authoritative?: boolean },
+ options?: { authoritative?: boolean; preservePaymentRequiredRoutes?: boolean },
): void {
xdGatewayModels = [...models];
if (options?.authoritative !== undefined) {
xdGatewayModelsAuthoritative = options.authoritative;
}
+ if (options?.preservePaymentRequiredRoutes !== true) {
+ xdGatewayPaymentRequiredRoutes = new Set(
+ models.flatMap((model) =>
+ model.availability === 'requires_payment'
+ ? (model.agents ?? []).map((agent) => `${agent}\n${model.id}`)
+ : [],
+ ),
+ );
+ }
xdCodexAnthropicBridgeModelIds = deriveXdCodexAnthropicBridgeModelIds(models);
markChanged();
}
@@ -1460,12 +1480,27 @@ export function getXdGatewayModels(): readonly XdGatewayModelInfo[] {
return xdGatewayModels;
}
+/** Main 派发边界查询最近一次明确的付费拒绝;不用于 Renderer 营销展示。 */
+export function isXdGatewayPaymentRequiredRoute(modelId: string, agent: AgentKind): boolean {
+ return xdGatewayPaymentRequiredRoutes.has(`${agent}\n${modelId}`);
+}
+
/** 子代理模型预检只在此标记为 true 时,才可把清单缺席解释为权威拒绝。 */
export function getXdGatewayModelAccessSnapshot(): {
authoritative: boolean;
models: readonly XdGatewayModelInfo[];
+ paymentRequiredModelIds: readonly string[];
} {
- return { authoritative: xdGatewayModelsAuthoritative, models: xdGatewayModels };
+ const claudeCodeRoutePrefix = 'claude-code\n';
+ return {
+ authoritative: xdGatewayModelsAuthoritative,
+ models: xdGatewayModels,
+ paymentRequiredModelIds: [...xdGatewayPaymentRequiredRoutes].flatMap((route) =>
+ route.startsWith(claudeCodeRoutePrefix)
+ ? [route.slice(claudeCodeRoutePrefix.length)]
+ : [],
+ ),
+ };
}
/** 新一轮 `/models` 未完成或失败后撤销负向证明,但保留 LKG 供 UI 展示。 */
diff --git a/apps/desktop/src/main/maker-host/model-route-guard-live.ts b/apps/desktop/src/main/maker-host/model-route-guard-live.ts
index 8d83f99f1c..a86c719c6f 100644
--- a/apps/desktop/src/main/maker-host/model-route-guard-live.ts
+++ b/apps/desktop/src/main/maker-host/model-route-guard-live.ts
@@ -27,7 +27,10 @@ import {
} from '@cindy/model-providers';
import { getDesktopProviderService } from './createDesktopProviderService.js';
-import { getActiveCatalog } from './active-catalog.js';
+import {
+ getActiveCatalog,
+ isXdGatewayPaymentRequiredRoute,
+} from './active-catalog.js';
import { readModelDisableOverrides } from './model-disable-store.js';
import {
isRegistryTombstoneForConsumer,
@@ -57,6 +60,9 @@ function tombstoneGuardOptions(
catalog: ReturnType<typeof getActiveCatalog>,
): ModelRouteGuardOptions {
return {
+ isPaymentRequiredTombstone: (providerId, modelId, agent) =>
+ (providerId === null || providerId === 'xd') &&
+ isXdGatewayPaymentRequiredRoute(modelId, agent),
isRetiredTombstone: (providerId, modelId, agent) => {
const providerIds = providerId ? [providerId] : MODEL_PLANE_POLICIES.keys();
return [...providerIds].some((id) =>
diff --git a/apps/desktop/src/main/maker-host/model-route-guard.ts b/apps/desktop/src/main/maker-host/model-route-guard.ts
index b2628bde39..8bc3204e50 100644
--- a/apps/desktop/src/main/maker-host/model-route-guard.ts
+++ b/apps/desktop/src/main/maker-host/model-route-guard.ts
@@ -44,7 +44,12 @@ import {
export type ModelRouteVerdict =
| { kind: 'pass' }
- | { kind: 'reroute'; providerId: string }
+ | {
+ kind: 'reroute';
+ providerId: string;
+ /** 运行中会话的发送终检只强制付费边界;其它 reroute 保持既有 best-effort 语义。 */
+ reason?: 'payment-required';
+ }
| {
kind: 'reject';
reason:
@@ -52,6 +57,7 @@ export type ModelRouteVerdict =
| 'explicit-source-disabled'
| 'capability-model'
| 'model-retired'
+ | 'payment-required'
| 'exclusive-source-unavailable';
};
@@ -156,6 +162,12 @@ export function shouldApplyExclusiveProviderReroute(
export interface ModelRouteGuardOptions {
/** Active Registry tombstones have no CatalogModel entity, so the live shell supplies this. */
isRetiredTombstone?: (providerId: string | null, modelId: string, agent: AgentKind) => boolean;
+ /** 刷新失败后已从展示目录移除、但最近一次成功 v5 明确拒绝的 XD 路由。 */
+ isPaymentRequiredTombstone?: (
+ providerId: string | null,
+ modelId: string,
+ agent: AgentKind,
+ ) => boolean;
}
/** 该来源下这份 (model, agent) 拷贝是否被停用(含供应商级)。 */
@@ -179,6 +191,10 @@ function copyRetired(p: ProviderView, modelId: string, agent: AgentKind): boolea
return getModel(p, modelId, agent)?.status === 'retired';
}
+function copyPaymentRequired(p: ProviderView, modelId: string, agent: AgentKind): boolean {
+ return getModel(p, modelId, agent)?.availability === 'requires_payment';
+}
+
function applyExclusiveRoute(
views: readonly ProviderView[],
agent: AgentKind,
@@ -216,7 +232,17 @@ function checkDisableAxisRoute(
if (providerId && !explicit && options.isRetiredTombstone?.(providerId, modelId, agent)) {
return { kind: 'reject', reason: 'model-retired' };
}
+ if (
+ providerId &&
+ !explicit &&
+ options.isPaymentRequiredTombstone?.(providerId, modelId, agent)
+ ) {
+ return { kind: 'reject', reason: 'payment-required' };
+ }
if (offering.length === 0) {
+ if (options.isPaymentRequiredTombstone?.(null, modelId, agent)) {
+ return { kind: 'reject', reason: 'payment-required' };
+ }
return options.isRetiredTombstone?.(null, modelId, agent)
? { kind: 'reject', reason: 'model-retired' }
: { kind: 'pass' };
@@ -231,6 +257,9 @@ function checkDisableAxisRoute(
if (providerId) {
if (explicit) {
+ if (copyPaymentRequired(explicit, modelId, agent)) {
+ return { kind: 'reject', reason: 'payment-required' };
+ }
if (copyRetired(explicit, modelId, agent)) {
return { kind: 'reject', reason: 'model-retired' };
}
@@ -257,6 +286,13 @@ function checkDisableAxisRoute(
if (!wouldRouteId) return { kind: 'pass' };
const wouldRoute = preDisableRail.find((p) => p.id === wouldRouteId);
if (!wouldRoute) return { kind: 'pass' };
+ if (copyPaymentRequired(wouldRoute, modelId, agent)) {
+ const alternative = effectiveSourceIdForModel([...views], null, modelId, agent);
+ const alternativeProvider = alternative ? views.find((p) => p.id === alternative) : undefined;
+ return alternative && alternativeProvider && !copyPaymentRequired(alternativeProvider, modelId, agent)
+ ? { kind: 'reroute', providerId: alternative, reason: 'payment-required' }
+ : { kind: 'reject', reason: 'payment-required' };
+ }
if (copyRetired(wouldRoute, modelId, agent)) {
const alternative = effectiveSourceIdForModel([...views], null, modelId, agent);
const alternativeProvider = alternative
diff --git a/apps/desktop/src/main/maker-host/subagent-model-access-policy.ts b/apps/desktop/src/main/maker-host/subagent-model-access-policy.ts
index ba1d11230f..809912724a 100644
--- a/apps/desktop/src/main/maker-host/subagent-model-access-policy.ts
+++ b/apps/desktop/src/main/maker-host/subagent-model-access-policy.ts
@@ -24,16 +24,22 @@ function modelMatches(requested: string, candidate: string): boolean {
interface XdAccessModel {
id: string;
agents?: readonly string[];
+ availability?: 'available' | 'requires_payment';
}
interface XdAccessSnapshot {
authoritative: boolean;
models: readonly XdAccessModel[];
+ paymentRequiredModelIds: readonly string[];
}
function xdClaudeCodeModels(models: readonly XdAccessModel[]): readonly string[] {
return models
- .filter((model) => model.agents?.includes('claude-code'))
+ .filter(
+ (model) =>
+ model.availability !== 'requires_payment'
+ && model.agents?.includes('claude-code'),
+ )
.map((model) => model.id);
}
@@ -55,6 +61,13 @@ export function classifyClaudeSubagentModelAccess(input: {
|| (!providerId && input.gatewayKeyAvailable);
if (usesXdGateway) {
+ // A retained payment tombstone is stronger than snapshot freshness. In
+ // particular, aliases may drift to any matching paid generation, so one
+ // known paid candidate must deny the alias before an older free match can
+ // allow it.
+ if (input.xdSnapshot.paymentRequiredModelIds.some(
+ (id) => modelMatches(requested, id),
+ )) return { status: 'denied' };
if (!input.xdSnapshot.authoritative) return { status: 'unknown' };
return xdClaudeCodeModels(input.xdSnapshot.models).some((id) => modelMatches(requested, id))
? { status: 'allowed' }
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 96a98787c5..2e3b12f3ae 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -3874,6 +3874,29 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
session.setTurnLifecycleObserver({
beforeProviderStart: async (turnGeneration) => {
if (session.remoteHostId) return;
+ // 每条本地 Session.send 都经过这一个 Main-owned 边界,包括 renderer、IM、
+ // Goal、Learn、Hook 与 Scheduler。付费权限不能只挂在普通 IPC 发送事务上。
+ const model = session.model;
+ if (model) {
+ const verdict = await verdictForModelRoute(
+ session.agentKind,
+ model,
+ getSessionProvider(session.id),
+ );
+ // beforeProviderStart 已经进入 Session 内部,无法再安全重建跨凭证形态的
+ // runtime。付费 reroute 不能当作 pass,否则 null-provider 仍会落到已锁定
+ // 的 XD 默认来源。普通停用/能力/独占 reroute 属于既有 best-effort 轴,
+ // 运行中会话按 model-route-guard 契约不在这里打断。
+ if (verdict.kind === 'reroute' && verdict.reason === 'payment-required') {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `model "${model}" must switch to provider "${verdict.providerId}" before sending`,
+ );
+ }
+ if (verdict.kind === 'reject' && verdict.reason === 'payment-required') {
+ throwIpcError('PERMISSION_DENIED', `model "${model}" requires paid access`);
+ }
+ }
silentStopTurnLeaseGate.supersede(session.id);
// Keep Review's exact-instance liveness listener lazy. PID-only turn
// leases remain fail-closed until this process actually starts Review.
@@ -7503,6 +7526,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
? `model "${model}" is not an agent chat model`
: verdict.reason === 'model-retired'
? `model "${model}" has been retired from the catalog`
+ : verdict.reason === 'payment-required'
+ ? `model "${model}" requires paid access`
: verdict.reason === 'exclusive-source-unavailable'
? `model "${model}" requires SuperGrok (xAI) and cannot use the default gateway`
: `model "${model}" is disabled in settings`,
diff --git a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts
index 4564634e83..b172e66677 100644
--- a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts
@@ -28,6 +28,7 @@ vi.mock('../../cindy-media/providerMediaRuntime.js', () => ({
import {
fetchMediaInvocationGuide,
+ isMediaModelExecutable,
isMediaModelExecutableForGuide,
listAvailableMediaModels,
listExecutableMediaModels,
@@ -36,12 +37,14 @@ import {
} from '../mediaModels.js';
const payload = {
- schemaVersion: 4 as const,
+ schemaVersion: 5 as const,
+ accountTier: 'free' as const,
models: [
{
id: 'image-without-guide',
name: 'Image Without Guide',
mode: 'image_generation',
+ availability: 'available' as const,
currency: 'CNY' as const,
agents: [],
modalities: { input: ['text'], output: ['image'] },
@@ -50,6 +53,7 @@ const payload = {
id: 'image-with-guide',
name: 'Image With Guide',
mode: 'image_generation',
+ availability: 'available' as const,
currency: 'CNY' as const,
agents: [],
modalities: { input: ['text', 'image'], output: ['image'] },
@@ -58,6 +62,7 @@ const payload = {
id: 'video-without-guide',
name: 'Video Without Guide',
mode: 'video_generation',
+ availability: 'available' as const,
currency: 'CNY' as const,
agents: [],
modalities: { input: ['text', 'image'], output: ['video'] },
@@ -66,6 +71,7 @@ const payload = {
id: 'guide-only-chat',
name: 'Guide Only Chat',
mode: 'chat',
+ availability: 'available' as const,
currency: 'CNY' as const,
contextWindow: 200_000,
agents: ['codex' as const],
@@ -155,6 +161,28 @@ describe('listAvailableMediaModels', () => {
await expect(listAvailableMediaModels()).resolves.toEqual([]);
});
+ it('v5 目录不会把需要付费的媒体模型暴露为可用模型', async () => {
+ serverApiFetchMock.mockResolvedValueOnce({
+ ...payload,
+ models: [
+ payload.models[1],
+ {
+ ...payload.models[0],
+ id: 'paid-image',
+ availability: 'requires_payment',
+ },
+ ],
+ });
+
+ await expect(listAvailableMediaModels('image.generate')).resolves.toMatchObject([
+ { id: 'image-with-guide', availability: 'available' },
+ ]);
+ expect(serverApiFetchMock).toHaveBeenCalledWith(
+ '/api/model-access/models?schemaVersion=5',
+ expect.any(Object),
+ );
+ });
+
it('namespaced modelId 唯一时继承旧裸 ID 的停用项', async () => {
serverApiFetchMock.mockResolvedValueOnce({
...payload,
@@ -288,54 +316,61 @@ describe('listAvailableMediaModels', () => {
it('批量预检缓存 modelId 对应的协议 Guide', async () => {
const modelId = 'openai/image-with-guide';
+ const paidModelId = 'openai/paid-image';
+ const guide = {
+ schemaVersion: 1 as const,
+ guideId: 'openai-images-v1',
+ revision: '2026-08-20.1',
+ connection: { providerId: 'xd' },
+ operations: [
+ {
+ capability: 'image.generate' as const,
+ request: {
+ method: 'POST' as const,
+ path: '/images/generations',
+ bodyEncoding: 'json' as const,
+ bodyModelPath: ['model'],
+ timeoutMs: 1_000,
+ maxRequestBytes: 1_024,
+ maxResponseBytes: 1_024,
+ },
+ response: {
+ mode: 'sync' as const,
+ media: [
+ {
+ path: ['data', '*', 'url'],
+ encoding: 'url' as const,
+ kind: 'image' as const,
+ allowedUrlHosts: ['example.com'],
+ },
+ ],
+ },
+ instructions: '按协议组装请求。',
+ exampleBody: { prompt: 'hello' },
+ inputSchema: { type: 'object' },
+ officialDocs: 'https://example.com/images-api',
+ },
+ ],
+ };
serverApiFetchMock.mockImplementation(async (path: string) => {
if (path.startsWith('/api/model-access/models')) {
return {
...payload,
- models: [{ ...payload.models[1], id: modelId }],
+ models: [
+ { ...payload.models[1], id: modelId },
+ {
+ ...payload.models[1],
+ id: paidModelId,
+ availability: 'requires_payment',
+ },
+ ],
};
}
if (path === '/api/model-access/invocation-guides') {
return {
guides: [
- {
- modelId,
- guide: {
- schemaVersion: 1,
- guideId: 'openai-images-v1',
- revision: '2026-08-20.1',
- connection: { providerId: 'xd' },
- operations: [
- {
- capability: 'image.generate',
- request: {
- method: 'POST',
- path: '/images/generations',
- bodyEncoding: 'json',
- bodyModelPath: ['model'],
- timeoutMs: 1_000,
- maxRequestBytes: 1_024,
- maxResponseBytes: 1_024,
- },
- response: {
- mode: 'sync',
- media: [
- {
- path: ['data', '*', 'url'],
- encoding: 'url',
- kind: 'image',
- allowedUrlHosts: ['example.com'],
- },
- ],
- },
- instructions: '按协议组装请求。',
- exampleBody: { prompt: 'hello' },
- inputSchema: { type: 'object' },
- officialDocs: 'https://example.com/images-api',
- },
- ],
- },
- },
+ { modelId, guide },
+ { modelId: paidModelId, guide: { ...guide, guideId: 'paid-images-v1' } },
],
};
}
@@ -351,5 +386,6 @@ describe('listAvailableMediaModels', () => {
expect(
isMediaModelExecutableForGuide(modelId, 'other-images-v1', 'image.generate'),
).toBe(false);
+ expect(isMediaModelExecutable(paidModelId, 'image.generate')).toBe(false);
});
});
diff --git a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
index aabe46be9b..1a221c9e82 100644
--- a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
+import type { ModelAccessStatus } from '../../../shared/modelAccess.js';
import {
buildModelsSyncRequest,
ensureCredentialsReadyForModelsRefresh,
+ modelsWithoutStalePaymentUpsell,
parseModelsSyncPayload,
+ shouldPreservePaymentRequiredRoutes,
withModelsSyncOverallDeadline,
waitForModelsSyncRefresh,
XD_MODELS_SYNC_TIMEOUT_MS,
@@ -22,13 +25,13 @@ describe('parseModelsSyncPayload', () => {
modalities: { input: ['text'], output: ['text'] },
};
- it('does not downgrade a v4 sync request to a v1 response', () => {
+ it('does not downgrade a v5 sync request to a v1 response', () => {
expect(parseModelsSyncPayload({ schemaVersion: 1, models: [baseModel] })).toMatchObject({
ok: false,
});
});
- it('does not downgrade a v4 sync request to a v2 response', () => {
+ it('does not downgrade a v5 sync request to a v2 response', () => {
const model = {
...baseModel,
newSessionDefault: ['claude-code', 'codex'] as const,
@@ -68,7 +71,7 @@ describe('parseModelsSyncPayload', () => {
it.each([
{
label: 'unknown schema version',
- payload: { schemaVersion: 5, models: [baseModel] },
+ payload: { schemaVersion: 6, models: [baseModel] },
errorPath: 'response.schemaVersion',
},
{
@@ -115,13 +118,15 @@ describe('parseModelsSyncPayload', () => {
});
it.each(['openai-responses', 'anthropic-messages'] as const)(
- 'reads v4 Pi %s routing and filters future agent kinds without rejecting the catalog',
+ 'reads v5 Pi %s routing and filters future agent kinds without rejecting the catalog',
(piWireProtocol) => {
const payload = {
- schemaVersion: 4,
+ schemaVersion: 5,
+ accountTier: 'free',
models: [
{
...baseModel,
+ availability: 'requires_payment',
agents: ['claude-code', 'codex', 'pi', 'future-agent'],
newSessionDefault: ['pi', 'future-agent'],
perAgent: {
@@ -136,9 +141,11 @@ describe('parseModelsSyncPayload', () => {
expect(parseModelsSyncPayload(payload)).toEqual({
ok: true,
+ accountTier: 'free',
models: [
{
...baseModel,
+ availability: 'requires_payment',
agents: ['claude-code', 'codex', 'pi'],
newSessionDefault: ['pi'],
perAgent: {
@@ -153,13 +160,41 @@ describe('parseModelsSyncPayload', () => {
);
});
+describe('modelsWithoutStalePaymentUpsell', () => {
+ it('保留旧快照中的可执行模型,但移除已无法在线确认的付费锁定行', () => {
+ expect(modelsWithoutStalePaymentUpsell([
+ { id: 'available', currency: 'CNY', agents: [], availability: 'available' },
+ { id: 'locked', currency: 'CNY', agents: [], availability: 'requires_payment' },
+ ])).toEqual([
+ { id: 'available', currency: 'CNY', agents: [], availability: 'available' },
+ ]);
+ });
+});
+
+describe('shouldPreservePaymentRequiredRoutes', () => {
+ const status = (state: ModelAccessStatus['state']): ModelAccessStatus => ({
+ state,
+ source: null,
+ endpoint: null,
+ accountTier: null,
+ });
+
+ it('只在同账号凭据临时失败时保留付费拒绝快照', () => {
+ expect(shouldPreservePaymentRequiredRoutes(status('failed'))).toBe(true);
+ expect(shouldPreservePaymentRequiredRoutes(status('disabled'))).toBe(false);
+ expect(shouldPreservePaymentRequiredRoutes(status('unsupported'))).toBe(false);
+ expect(shouldPreservePaymentRequiredRoutes(status('idle'))).toBe(false);
+ });
+});
+
describe('waitForModelsSyncRefresh', () => {
it('gives the shared XD model-list request a finite deadline', () => {
expect(buildModelsSyncRequest('https://model-access.example.com')).toEqual({
- path: '/api/model-access/models?schemaVersion=4',
+ path: '/api/model-access/models?schemaVersion=5',
options: {
baseUrl: 'https://model-access.example.com',
timeoutMs: 20_000,
+ cache: 'no-store',
},
});
expect(Number.isFinite(XD_MODELS_SYNC_TIMEOUT_MS)).toBe(true);
@@ -209,6 +244,7 @@ describe('waitForModelsSyncRefresh', () => {
state: 'failed' as const,
source: null,
endpoint: null,
+ accountTier: null,
};
});
const status = await ensureCredentialsReadyForModelsRefresh({
@@ -216,6 +252,7 @@ describe('waitForModelsSyncRefresh', () => {
state: 'ok',
source: 'server',
endpoint: 'https://gateway.example.com',
+ accountTier: null,
}),
retry,
});
@@ -225,6 +262,7 @@ describe('waitForModelsSyncRefresh', () => {
await expect(
waitForModelsSyncRefresh({
expectedGeneration: 3,
+ minimumAttempt: 9,
schedule: vi.fn(),
snapshot: () => ({ flight: Promise.resolve(), generation: 3, attempt: 9 }),
currentGeneration: () => 3,
@@ -239,11 +277,17 @@ describe('waitForModelsSyncRefresh', () => {
state: 'ok' as const,
source: 'server' as const,
endpoint: 'https://gateway.example.com',
+ accountTier: null,
}));
await expect(
ensureCredentialsReadyForModelsRefresh({
- getStatus: () => ({ state: 'failed', source: null, endpoint: null }),
+ getStatus: () => ({
+ state: 'failed',
+ source: null,
+ endpoint: null,
+ accountTier: null,
+ }),
retry,
}),
).resolves.toMatchObject({ state: 'ok' });
@@ -263,6 +307,7 @@ describe('waitForModelsSyncRefresh', () => {
await expect(
waitForModelsSyncRefresh({
expectedGeneration: 2,
+ minimumAttempt: 5,
schedule: () => {
if (scheduleCalls > 0) index = 1;
scheduleCalls += 1;
@@ -274,6 +319,37 @@ describe('waitForModelsSyncRefresh', () => {
).resolves.toBe('succeeded');
});
+ it('waits through a same-account prepayment flight and requires a newer attempt', async () => {
+ let resolveOldFlight!: () => void;
+ const oldFlight = new Promise<void>((resolve) => {
+ resolveOldFlight = resolve;
+ });
+ const newFlight = Promise.resolve();
+ let snapshot: ModelsSyncFlightSnapshot = {
+ flight: oldFlight,
+ generation: 4,
+ attempt: 8,
+ };
+ let scheduleCalls = 0;
+ const outcome = waitForModelsSyncRefresh({
+ expectedGeneration: 4,
+ minimumAttempt: 9,
+ schedule: () => {
+ if (scheduleCalls > 0) {
+ snapshot = { flight: newFlight, generation: 4, attempt: 9 };
+ }
+ scheduleCalls += 1;
+ },
+ snapshot: () => snapshot,
+ currentGeneration: () => 4,
+ lastSuccessfulAttempt: () => 9,
+ });
+
+ resolveOldFlight();
+ await expect(outcome).resolves.toBe('succeeded');
+ expect(scheduleCalls).toBe(2);
+ });
+
it('stops instead of following a new account when auth changes in flight', async () => {
let resolveFlight!: () => void;
const flight = new Promise<void>((resolve) => {
@@ -282,6 +358,7 @@ describe('waitForModelsSyncRefresh', () => {
let generation = 7;
const outcome = waitForModelsSyncRefresh({
expectedGeneration: 7,
+ minimumAttempt: 3,
schedule: vi.fn(),
snapshot: () => ({ flight, generation: 7, attempt: 3 }),
currentGeneration: () => generation,
@@ -297,6 +374,7 @@ describe('waitForModelsSyncRefresh', () => {
await expect(
waitForModelsSyncRefresh({
expectedGeneration: 3,
+ minimumAttempt: 9,
schedule: vi.fn(),
snapshot: () => ({ flight: Promise.resolve(), generation: 3, attempt: 9 }),
currentGeneration: () => 3,
diff --git a/apps/desktop/src/main/model-access/credentialsSync.ts b/apps/desktop/src/main/model-access/credentialsSync.ts
index fd0f1ed0d9..7b4c65cb43 100644
--- a/apps/desktop/src/main/model-access/credentialsSync.ts
+++ b/apps/desktop/src/main/model-access/credentialsSync.ts
@@ -139,6 +139,7 @@ export function createCredentialsSync(deps: CredentialsSyncDeps): CredentialsSyn
...(errorCode ? { errorCode } : {}),
source: deps.store.getSource(),
endpoint: deps.store.getServerEndpoint(),
+ accountTier: null,
};
}
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index 598fcdfdb1..917816f34b 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -1,4 +1,4 @@
-import { BrowserWindow, ipcMain } from 'electron';
+import { app, BrowserWindow, ipcMain } from 'electron';
import { createLogger } from '../logger.js';
import * as authManager from '../authManager.js';
@@ -12,6 +12,7 @@ import {
cancelCodexAuthModeChange,
} from '../maker-host/index.js';
import {
+ getXdGatewayModels,
markXdGatewayModelAccessUnknown,
setXdGatewayModels,
} from '../maker-host/active-catalog.js';
@@ -21,6 +22,7 @@ import { isPricedGatewayModel } from '../../shared/modelPriceQuote.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import {
MODEL_ACCESS_STATUS_CHANNEL,
+ type ModelAccessAccountTier,
type ModelAccessGatewayModel,
type ModelAccessStatus,
} from '../../shared/modelAccess.js';
@@ -34,7 +36,9 @@ import {
import {
buildModelsSyncRequest,
ensureCredentialsReadyForModelsRefresh,
+ modelsWithoutStalePaymentUpsell,
parseModelsSyncPayload,
+ shouldPreservePaymentRequiredRoutes,
withModelsSyncOverallDeadline,
waitForModelsSyncRefresh,
} from './modelsSyncRefresh.js';
@@ -124,14 +128,27 @@ async function writeXdKeyWithCodexSideEffect(key: string): Promise<boolean> {
return true;
}
+let accountTier: ModelAccessAccountTier | null = null;
+
+function statusWithAccountTier(status: ModelAccessStatus): ModelAccessStatus {
+ return { ...status, accountTier };
+}
+
function broadcastStatus(status: ModelAccessStatus): void {
+ const payload = statusWithAccountTier(status);
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
- win.webContents.send(MODEL_ACCESS_STATUS_CHANNEL, status);
+ win.webContents.send(MODEL_ACCESS_STATUS_CHANNEL, payload);
}
}
}
+function setAccountTier(next: ModelAccessAccountTier | null): void {
+ if (accountTier === next) return;
+ accountTier = next;
+ broadcastStatus(getSync().getStatus());
+}
+
// ─── XD 网关模型目录同步(`/models` 是模型、能力与价格的唯一事实源)─────────
// 凭据同步成功后从 model-access-server 拉现有 GET /models:聊天模型与
// 媒体模型都来自同一份 AIGateway /model-groups 投影。active-catalog 按 agents
@@ -143,6 +160,8 @@ let modelsSyncInflight: Promise<void> | null = null;
/** 模型请求的单调尝试号与最近成功号,供手动刷新区分“旧成功 + 本次失败”。 */
let modelsSyncAttempt = 0;
let lastModelsSyncSucceededAttempt = 0;
+let lastModelsSyncStartedAt = 0;
+export const XD_MODELS_FOREGROUND_REFRESH_INTERVAL_MS = 5 * 60_000;
/** 在途目录请求所属的认证世代。 */
let modelsSyncGen = -1;
/** 旧世代请求在途时新账号的补发标记。 */
@@ -158,12 +177,15 @@ let lastAuthRealm: ReturnType<typeof authManager.getActiveAuthRealm> | null = nu
function applyGatewayModels(
models: ModelAccessGatewayModel[],
- authenticatedUserId?: string,
- authoritative = false,
+ options: {
+ authenticatedUserId?: string;
+ authoritative?: boolean;
+ preservePaymentRequiredRoutes?: boolean;
+ } = {},
): void {
// 同一次 /models 响应建立 XD 模型与价格投影。空成功响应会同时清空模型和价格;请求失败不会调用本函数,
// 因而保留上一份完整成功快照。
- const pricing = replaceGatewayModelPricing(models, authenticatedUserId);
+ const pricing = replaceGatewayModelPricing(models, options.authenticatedUserId);
// 分母只算会产生报价的条目:免费/无价条目按设计不出报价,不该把健康目录
// 也报成覆盖不足。此时覆盖缺口只剩一种成因——币种声明与目录冲突被丢弃,
// 这在 #587 之前是全程静默的,这行日志让现场可判。
@@ -196,7 +218,10 @@ function applyGatewayModels(
});
}
resetExecutableMediaModelCache();
- setXdGatewayModels(models, { authoritative });
+ setXdGatewayModels(models, {
+ authoritative: options.authoritative ?? false,
+ preservePaymentRequiredRoutes: options.preservePaymentRequiredRoutes,
+ });
}
async function runModelsSync(
@@ -215,27 +240,42 @@ async function runModelsSync(
);
const parsed = parseModelsSyncPayload(payload);
if (!parsed.ok) {
- log.warn('xd gateway models response rejected (keeping last valid list)', {
+ log.warn('xd gateway models response rejected (keeping executable last valid list)', {
error: parsed.error,
});
+ if (myGen === authGeneration) {
+ setAccountTier(null);
+ setXdGatewayModels(modelsWithoutStalePaymentUpsell(getXdGatewayModels()), {
+ authoritative: false,
+ preservePaymentRequiredRoutes: true,
+ });
+ }
return;
}
models = parsed.models;
+ if (myGen === authGeneration) setAccountTier(parsed.accountTier);
} catch (err) {
- log.warn('xd gateway models fetch failed (keeping last valid list)', {
+ log.warn('xd gateway models fetch failed (keeping executable last valid list)', {
error: err instanceof Error ? err.message : String(err),
});
+ if (myGen === authGeneration) {
+ setAccountTier(null);
+ setXdGatewayModels(modelsWithoutStalePaymentUpsell(getXdGatewayModels()), {
+ authoritative: false,
+ preservePaymentRequiredRoutes: true,
+ });
+ }
return;
}
if (myGen !== authGeneration) return; // 响应归属旧账号,丢弃
if (models.length === 0) {
log.warn('xd gateway models fetch returned empty list; clearing current list');
- applyGatewayModels([], authenticatedUserId, true);
+ applyGatewayModels([], { authenticatedUserId, authoritative: true });
lastModelsSyncSucceededAttempt = myAttempt;
return;
}
log.info(`xd gateway models synced: ${models.length}`);
- applyGatewayModels(models, authenticatedUserId, true);
+ applyGatewayModels(models, { authenticatedUserId, authoritative: true });
try {
const availability = await listExecutableMediaModels([], {
includeDisabled: true,
@@ -285,6 +325,7 @@ function scheduleModelsSync(): void {
}
modelsSyncGen = gen;
const attempt = ++modelsSyncAttempt;
+ lastModelsSyncStartedAt = Date.now();
modelsSyncInflight = runModelsSync(gen, authenticatedUserId, attempt)
.catch((err) => {
log.warn('xd gateway models sync threw', {
@@ -298,6 +339,7 @@ function scheduleModelsSync(): void {
}
let syncInstance: CredentialsSync | null = null;
+let foregroundRefreshListener: (() => void) | null = null;
function getSync(): CredentialsSync {
if (!syncInstance) {
@@ -308,12 +350,20 @@ function getSync(): CredentialsSync {
writeXdKey: writeXdKeyWithCodexSideEffect,
store: getModelAccessCredentialsStore(),
onStatusChange: (status) => {
+ if (['failed', 'disabled', 'unsupported', 'idle'].includes(status.state)) {
+ accountTier = null;
+ }
broadcastStatus(status);
// 凭据就绪(下发/轮换成功)→ 拉取网关模型目录(XD 模型列表的权威来源)。
if (status.state === 'ok') scheduleModelsSync();
- // 凭据明确不可用时,旧模型清单也不再具备可用性证明。syncing 期间先保留
- // 已成功拉到的清单,最终成功会覆盖、失败会走这里清空。
- else if (['failed', 'disabled', 'unsupported', 'idle'].includes(status.state)) {
+ // failed 是同一账号下的临时同步失败,credentialsSync 明确保留本地 key;隐藏
+ // 过期营销列表的同时必须保留最近一次付费拒绝,避免已有会话绕过路由守卫。
+ // disabled / unsupported / idle 是真实能力边界,清空模型和拒绝快照。
+ else if (status.state === 'failed') {
+ applyGatewayModels([], {
+ preservePaymentRequiredRoutes: shouldPreservePaymentRequiredRoutes(status),
+ });
+ } else if (['disabled', 'unsupported', 'idle'].includes(status.state)) {
applyGatewayModels([]);
}
},
@@ -328,7 +378,7 @@ function getSync(): CredentialsSync {
/** 当前同步状态(renderer 首帧经 IPC 拉;main 内部也可直接读)。 */
export function getModelAccessStatus(): ModelAccessStatus {
- return getSync().getStatus();
+ return statusWithAccountTier(getSync().getStatus());
}
/**
@@ -340,6 +390,10 @@ export async function refreshXdGatewayModels(): Promise<void> {
if (!getAppCapabilities().canUseCindyGateway) {
throwIpcError('PERMISSION_DENIED', 'Cindy AI requires a Cindy account.');
}
+ // Capture the call boundary before credential recovery can schedule a request. A flight that
+ // already existed here may have read entitlement before a just-completed payment; explicit
+ // refresh must wait through it and require a strictly newer attempt.
+ const minimumAttempt = modelsSyncAttempt + 1;
const status = await ensureCredentialsReadyForModelsRefresh(getSync());
if (status.state !== 'ok') {
throwIpcError('MODEL_ACCESS_FAILED', 'Cindy AI credentials are not ready.');
@@ -349,6 +403,7 @@ export async function refreshXdGatewayModels(): Promise<void> {
// 旧账号 flight,先等它作废,再显式补发当前世代并等待当前尝试号的真实结果。
const outcome = await waitForModelsSyncRefresh({
expectedGeneration: gen,
+ minimumAttempt,
schedule: scheduleModelsSync,
snapshot: () => ({
flight: modelsSyncInflight,
@@ -415,6 +470,7 @@ export function initModelAccess(): void {
)
) {
authGeneration++;
+ accountTier = null;
// 旧身份模型清单不能跨账号/区域继续显示;新身份拉取成功后再注入。
applyGatewayModels([]);
}
@@ -435,13 +491,19 @@ export function initModelAccess(): void {
if (initial.isAuthenticated) {
noteAuthState(true, initial.user?.id ?? null, authManager.getActiveAuthRealm());
}
- ipcMain.handle('model-access:get-status', () => sync.getStatus());
+ foregroundRefreshListener = () => {
+ if (!lastAuthUserId || getSync().getStatus().state !== 'ok') return;
+ if (Date.now() - lastModelsSyncStartedAt < XD_MODELS_FOREGROUND_REFRESH_INTERVAL_MS) return;
+ scheduleModelsSync();
+ };
+ app.on('browser-window-focus', foregroundRefreshListener);
+ ipcMain.handle('model-access:get-status', () => getModelAccessStatus());
ipcMain.handle('model-access:retry', async (): Promise<ModelAccessStatus> => {
if (!getAppCapabilities().canUseCindyGateway) {
throwIpcError('PERMISSION_DENIED', 'Cindy AI requires a Cindy account.');
}
- return sync.retry();
+ return statusWithAccountTier(await sync.retry());
});
ipcMain.handle('model-access:rotate', async (): Promise<ModelAccessStatus> => {
@@ -449,7 +511,7 @@ export function initModelAccess(): void {
throwIpcError('PERMISSION_DENIED', 'Cindy AI requires a Cindy account.');
}
try {
- return await sync.rotate();
+ return statusWithAccountTier(await sync.rotate());
} catch (err) {
mapServerError(err);
}
@@ -458,14 +520,20 @@ export function initModelAccess(): void {
/** 仅测试:重置单例。 */
export function resetModelAccessForTest(): void {
+ if (foregroundRefreshListener) {
+ app.removeListener('browser-window-focus', foregroundRefreshListener);
+ foregroundRefreshListener = null;
+ }
syncInstance = null;
modelsSyncInflight = null;
modelsSyncGen = -1;
modelsSyncRerunQueued = false;
modelsSyncAttempt = 0;
lastModelsSyncSucceededAttempt = 0;
+ lastModelsSyncStartedAt = 0;
authGeneration = 0;
lastAuthUserId = null;
lastAuthRealm = null;
+ accountTier = null;
applyGatewayModels([]);
}
diff --git a/apps/desktop/src/main/model-access/mediaModels.ts b/apps/desktop/src/main/model-access/mediaModels.ts
index 3030fac73f..dcb5bda8e4 100644
--- a/apps/desktop/src/main/model-access/mediaModels.ts
+++ b/apps/desktop/src/main/model-access/mediaModels.ts
@@ -1,7 +1,7 @@
import {
isModelDisabledWithUniqueLegacyBasename,
isProviderDisabled,
- MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
MODEL_ACCESS_MODELS_PATH,
parseListModelsResponse,
type MediaCapability,
@@ -25,7 +25,7 @@ const MEDIA_MODEL_REQUEST_TIMEOUT_MS = 20_000;
const MEDIA_GUIDE_PREFLIGHT_TIMEOUT_MS = 5_000;
const CINDY_AI_PROVIDER_ID = 'xd';
const MEDIA_MODELS_PATH =
- `${MODEL_ACCESS_MODELS_PATH}?schemaVersion=${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}` as const;
+ `${MODEL_ACCESS_MODELS_PATH}?schemaVersion=${MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION}` as const;
export type MediaGuideCompatibilityErrorCode =
| 'CLIENT_UPGRADE_REQUIRED'
@@ -70,6 +70,9 @@ export interface ExecutableMediaModelsResult {
}
export type ExecutableMediaModel = ModelCatalogEntry & { providerId: string };
+type GatewayMediaCatalogEntry = ModelCatalogEntry & {
+ availability?: 'available' | 'requires_payment';
+};
interface ExecutableMediaSnapshot {
models: ModelCatalogEntry[];
@@ -157,6 +160,7 @@ export function filterEnabledGatewayMediaModels<
T extends {
id: string;
mode?: string;
+ availability?: 'available' | 'requires_payment';
modalities?: { input: string[]; output: string[] };
},
>(
@@ -167,6 +171,7 @@ export function filterEnabledGatewayMediaModels<
if (isProviderDisabled(access, CINDY_AI_PROVIDER_ID)) return [];
const candidateModelIds = models.map((model) => model.id);
return models.filter((model) => {
+ if (model.availability === 'requires_payment') return false;
if (
isModelDisabledWithUniqueLegacyBasename(
access,
@@ -189,7 +194,7 @@ export function filterEnabledGatewayMediaModels<
* 的实时投影;Gateway mode 决定图片/视频模型类型。Guide 独立按 modelId
* 懒取,不参与模型发现。
*/
-async function fetchGatewayMediaModels(): Promise<ModelCatalogEntry[]> {
+async function fetchGatewayMediaModels(): Promise<GatewayMediaCatalogEntry[]> {
const payload = await serverApiFetch<unknown>(MEDIA_MODELS_PATH, {
baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
timeoutMs: MEDIA_MODEL_REQUEST_TIMEOUT_MS,
@@ -199,11 +204,11 @@ async function fetchGatewayMediaModels(): Promise<ModelCatalogEntry[]> {
typeof payload !== 'object' ||
payload === null ||
!('schemaVersion' in payload) ||
- payload.schemaVersion !== MODEL_ACCESS_CATALOG_SCHEMA_VERSION
+ payload.schemaVersion !== MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION
) {
throw new MediaModelCatalogError(
'媒体模型目录当前不可用,请稍后重试或使用其他工具。',
- `expected schemaVersion ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}`,
+ `expected schemaVersion ${MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION}`,
);
}
const parsed = parseListModelsResponse(payload);
@@ -365,7 +370,12 @@ function unavailableFromGuideError(modelId: string, error: unknown): Unavailable
}
async function buildExecutableMediaSnapshot(): Promise<ExecutableMediaSnapshot> {
- const models = await fetchGatewayMediaModels();
+ // The snapshot is itself an execution authorization source for legacy media
+ // paths, not just a cache behind listExecutableMediaModels. Never record a
+ // v5 paid-only model as executable even when it has a valid invocation Guide.
+ const models = (await fetchGatewayMediaModels()).filter(
+ (model) => model.availability !== 'requires_payment',
+ );
const batch = await fetchMediaInvocationGuideBatch();
const capabilitiesByModel = new Map<string, ReadonlySet<MediaCapability>>();
const guideIdsByModel = new Map<string, string>();
diff --git a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
index 58ab0d158b..01f04b48a8 100644
--- a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
+++ b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
@@ -1,8 +1,9 @@
import {
- MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
parseListModelsResponse,
} from '@cindy/model-providers';
import type {
+ ModelAccessAccountTier,
ModelAccessGatewayModel,
ModelAccessModelsResponse,
ModelAccessStatus,
@@ -12,28 +13,41 @@ import type { CredentialsSync } from './credentialsSync.js';
/** Bound the shared single-flight so a black-hole connection cannot block later refreshes. */
export const XD_MODELS_SYNC_TIMEOUT_MS = 20_000;
export const XD_MODELS_SYNC_PATH =
- `/api/model-access/models?schemaVersion=${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}` as const;
+ `/api/model-access/models?schemaVersion=${MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION}` as const;
export type ModelsSyncPayloadParseResult =
- { ok: true; models: ModelAccessGatewayModel[] } | { ok: false; error: string };
+ | { ok: true; models: ModelAccessGatewayModel[]; accountTier: ModelAccessAccountTier }
+ | { ok: false; error: string };
+
+/** 失败后的 LKG 只保留可执行模型;过期的付费差集不能继续作为升级营销事实。 */
+export function modelsWithoutStalePaymentUpsell(
+ models: readonly ModelAccessGatewayModel[],
+): ModelAccessGatewayModel[] {
+ return models.filter((model) => model.availability !== 'requires_payment');
+}
+
+/** 同账号凭据临时失败会保留本地 key,因此必须继续保留最近一次明确的付费拒绝。 */
+export function shouldPreservePaymentRequiredRoutes(status: ModelAccessStatus): boolean {
+ return status.state === 'failed';
+}
/**
* Validate the actual `/models` wire envelope before it can replace the last-known-good snapshot.
* The client-owned parser is the version boundary: it can validate every published contract,
- * but Desktop sync only accepts the current v4 response instead of partially interpreting an
+ * but Desktop sync only accepts the current v5 response instead of partially interpreting an
* older or unknown version.
*/
export function parseModelsSyncPayload(value: unknown): ModelsSyncPayloadParseResult {
const parsed = parseListModelsResponse(value);
if (!parsed.ok) return parsed;
- if (parsed.value.schemaVersion !== MODEL_ACCESS_CATALOG_SCHEMA_VERSION) {
+ if (parsed.value.schemaVersion !== MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION) {
return {
ok: false,
- error: `response.schemaVersion must be ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION} for Desktop model sync`,
+ error: `response.schemaVersion must be ${MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION} for Desktop model sync`,
};
}
const response: ModelAccessModelsResponse = parsed.value;
- return { ok: true, models: response.models };
+ return { ok: true, models: response.models, accountTier: response.accountTier! };
}
/**
@@ -61,13 +75,15 @@ export function withModelsSyncOverallDeadline<T>(
export function buildModelsSyncRequest(baseUrl: string | (() => string)): {
path: typeof XD_MODELS_SYNC_PATH;
- options: { baseUrl: string | (() => string); timeoutMs: number };
+ options: { baseUrl: string | (() => string); timeoutMs: number; cache: 'no-store' };
} {
return {
path: XD_MODELS_SYNC_PATH,
options: {
baseUrl,
timeoutMs: XD_MODELS_SYNC_TIMEOUT_MS,
+ // 模型权限随订阅权益变化,强制刷新不能命中 Electron HTTP cache。
+ cache: 'no-store',
},
};
}
@@ -103,6 +119,8 @@ export async function ensureCredentialsReadyForModelsRefresh(
export async function waitForModelsSyncRefresh(input: {
expectedGeneration: number;
+ /** The first attempt that is known to have started after this explicit refresh request. */
+ minimumAttempt: number;
schedule(): void;
snapshot(): ModelsSyncFlightSnapshot;
currentGeneration(): number;
@@ -115,6 +133,7 @@ export async function waitForModelsSyncRefresh(input: {
await flight;
if (input.currentGeneration() !== input.expectedGeneration) return 'account-changed';
if (generation !== input.expectedGeneration) continue;
+ if (attempt < input.minimumAttempt) continue;
return input.lastSuccessfulAttempt() === attempt ? 'succeeded' : 'failed';
}
}
diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
index c0128ef75e..13638d0144 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -41,6 +41,7 @@ vi.mock('../../maker-host/generic-oauth.js', () => ({
vi.mock('../../maker-host/active-catalog.js', () => ({
getActiveCatalog: vi.fn(() => ({ providers: [] })),
+ isXdGatewayPaymentRequiredRoute: vi.fn(() => false),
}));
vi.mock('../../maker-host/provider-route.js', () => ({
@@ -80,7 +81,10 @@ import { getChatgptBridgeAuth } from '../../maker-host/anthropic-responses-bridg
import { getValidClaudeAiOAuth } from '../../maker-host/claude-oauth-refresh.js';
import { getGrokAccessToken } from '../../maker-host/grok-oauth-login.js';
import { readCachedGenericOAuthAccessToken } from '../../maker-host/generic-oauth.js';
-import { getActiveCatalog } from '../../maker-host/active-catalog.js';
+import {
+ getActiveCatalog,
+ isXdGatewayPaymentRequiredRoute,
+} from '../../maker-host/active-catalog.js';
import { readModelDisableOverrides } from '../../maker-host/model-disable-store.js';
import { isProviderRouteMutationInProgress } from '../../maker-host/provider-route.js';
import { readCustomProviderKey } from '../../secrets/providerSecretStore.js';
@@ -88,6 +92,7 @@ import { getUtilityModelChainProfiles } from '../UtilityModelSelection.js';
import {
DEDICATED_AUTO_REVIEW_CANDIDATES,
getUtilityTextCandidates,
+ isUtilityRoutePaymentRequired,
requestDedicatedAutoReviewCandidateText,
requestExplicitUtilityText,
requestUtilityText,
@@ -103,6 +108,7 @@ const readGrokToken = vi.mocked(getGrokAccessToken);
const readGenericOAuthToken = vi.mocked(readCachedGenericOAuthAccessToken);
const fetchMock = vi.mocked(undiciFetch);
const activeCatalog = vi.mocked(getActiveCatalog);
+const xdPaymentRequiredRoute = vi.mocked(isXdGatewayPaymentRequiredRoute);
const readDisableOverrides = vi.mocked(readModelDisableOverrides);
const providerRouteMutationInProgress = vi.mocked(isProviderRouteMutationInProgress);
const readCustomKey = vi.mocked(readCustomProviderKey);
@@ -129,6 +135,7 @@ describe('utility one-shot candidates', () => {
readCustomKey.mockReturnValue(null);
readDisableOverrides.mockReturnValue({ disabledModels: {}, disabledProviders: {} });
activeCatalog.mockReturnValue({ providers: [] } as never);
+ xdPaymentRequiredRoute.mockReturnValue(false);
getProfiles.mockReturnValue([
{
id: 'codex-gpt-5.4-mini',
@@ -157,6 +164,51 @@ describe('utility one-shot candidates', () => {
expect(candidates.map((candidate) => candidate.providerId)).toEqual(['litellm-gpt-5.4-mini']);
});
+ it('does not expose or dispatch an XD utility candidate denied by paid availability', async () => {
+ readKey.mockReturnValue('proxy-key');
+ xdPaymentRequiredRoute.mockImplementation((model, agent) =>
+ model === 'gpt-5.4-mini' && agent === 'codex',
+ );
+
+ const result = await requestUtilityText(makerMock(false), 'hello');
+
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'no_candidate',
+ attempts: [
+ expect.objectContaining({ providerId: 'codex-gpt-5.4-mini' }),
+ expect.objectContaining({
+ providerId: 'litellm-gpt-5.4-mini',
+ reason: 'model_unavailable',
+ }),
+ ],
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('applies paid availability only to direct XD LiteLLM utility routes', () => {
+ xdPaymentRequiredRoute.mockImplementation((model) => model === 'paid-model');
+
+ expect(isUtilityRoutePaymentRequired({
+ transport: 'litellm-chat-completions',
+ model: 'paid-model',
+ })).toBe(true);
+ expect(isUtilityRoutePaymentRequired({
+ transport: 'codex-responses',
+ model: 'paid-model',
+ })).toBe(false);
+ });
+
+ it('rechecks paid availability immediately before a previously resolved XD utility dispatch', async () => {
+ readKey.mockReturnValue('proxy-key');
+ const candidates = await getUtilityTextCandidates(makerMock(false));
+ expect(candidates).toHaveLength(1);
+
+ xdPaymentRequiredRoute.mockReturnValue(true);
+ await expect(candidates[0]!.execute('hello')).rejects.toThrow('request_failed');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('returns credential-safe diagnostics when every configured candidate is unavailable', async () => {
const result = await requestUtilityText(makerMock(false), 'hello');
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 99c7a8c5ef..0d8acd5a86 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -17,7 +17,10 @@ import { readCachedGenericOAuthAccessToken } from '../maker-host/generic-oauth.j
// undici 的 fetch,但 per-request 现取系统代理(裸 undici 不吃代理设置)。
import { outboundUndiciFetch as undiciFetch } from '../maker-host/outbound-fetch.js';
import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs.js';
-import { getActiveCatalog } from '../maker-host/active-catalog.js';
+import {
+ getActiveCatalog,
+ isXdGatewayPaymentRequiredRoute,
+} from '../maker-host/active-catalog.js';
import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';
import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';
import { isProviderRouteMutationInProgress } from '../maker-host/provider-route.js';
@@ -35,6 +38,34 @@ import type {
const log = createLogger('utility-model:one-shot');
+const XD_UTILITY_ROUTE_AGENTS: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];
+
+/**
+ * Utility profiles call the XD chat-completions endpoint directly and therefore
+ * have no Session agent rail. A v5 paid deny on any advertised rail is enough
+ * to block the same gateway model id here; availability is account/model scoped.
+ */
+function isXdUtilityModelPaymentRequired(model: string): boolean {
+ return XD_UTILITY_ROUTE_AGENTS.some((agent) =>
+ isXdGatewayPaymentRequiredRoute(model, agent),
+ );
+}
+
+/**
+ * Shared live entitlement predicate for direct utility consumers. Only XD
+ * LiteLLM routes use the Cindy account catalog; Codex and custom BYOK routes
+ * keep their own credential plane. Organization catalogs are not subject to
+ * personal free/paid gating and arrive as not_applicable with every visible
+ * model available, so they never create this deny state.
+ */
+export function isUtilityRoutePaymentRequired(profile: {
+ transport?: string;
+ model: string;
+}): boolean {
+ return profile.transport === 'litellm-chat-completions'
+ && isXdUtilityModelPaymentRequired(profile.model);
+}
+
/**
* 实现了 `Agent.oneShot` 的 agent 集合(当前 claude-code / codex)。PiAgent 继承 BaseAgent
* 的 not-implemented,选中它调 oneShot 会抛错;help 兜底与任务摘要兜底都据此跳过 Pi,避免
@@ -227,6 +258,15 @@ async function resolveUtilityTextCandidates(
attempts.push(skippedAttempt(profile, 'model_unavailable'));
continue;
}
+ if (isUtilityRoutePaymentRequired(profile)) {
+ log.debug('utility text candidate skipped: paid XD route unavailable', {
+ providerId: routeProviderId,
+ profileId: profile.id,
+ model: profile.model,
+ });
+ attempts.push(skippedAttempt(profile, 'model_unavailable'));
+ continue;
+ }
if (!capability.transports.includes(profile.transport)) {
log.debug('utility text candidate skipped: unsupported transport', {
providerId: profile.id,
@@ -502,6 +542,12 @@ async function requestDefaultUtilityText(
attempts.push(skippedAttempt(candidate.profile, 'model_unavailable'));
continue;
}
+ // 前一个 fallback 候选可能运行数十秒;在每个 XD 候选真正执行前重读
+ // owner-scoped v5 deny,避免订阅状态/模型目录刚变化后继续向网关下单。
+ if (isUtilityRoutePaymentRequired(candidate.profile)) {
+ attempts.push(skippedAttempt(candidate.profile, 'model_unavailable'));
+ continue;
+ }
try {
const text = (await candidate.execute(prompt, opts)).trim();
if (!text) throw new UtilityTextExecutionError({ reason: 'empty_response' });
@@ -1169,6 +1215,7 @@ function resolveLiteLlmCandidate(profile: UtilityModelProfile): UtilityTextCandi
timeoutMs: opts?.timeoutMs,
reasoningEffort: opts?.reasoningEffort,
signal: opts?.signal,
+ routeStillAllowed: () => !isUtilityRoutePaymentRequired(profile),
}),
},
};
@@ -1183,6 +1230,8 @@ async function requestLiteLlmText(input: {
timeoutMs?: number;
reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
signal?: AbortSignal;
+ /** Synchronous owner entitlement fence immediately before the HTTP request. */
+ routeStillAllowed?: () => boolean;
}): Promise<string> {
const controller = new AbortController();
const timeoutMs = input.timeoutMs ?? 20_000;
@@ -1191,6 +1240,9 @@ async function requestLiteLlmText(input: {
else input.signal?.addEventListener('abort', abortFromParent, { once: true });
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
+ if (input.routeStillAllowed && !input.routeStillAllowed()) {
+ throw new UtilityTextExecutionError({ reason: 'request_failed' });
+ }
const response = await undiciFetch(joinProxyPath(input.baseUrl, '/v1/chat/completions'), {
method: 'POST',
signal: controller.signal,
diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.ts
index 17e48d52ad..4a831ccffe 100644
--- a/apps/desktop/src/main/voice-input/index.ts
+++ b/apps/desktop/src/main/voice-input/index.ts
@@ -22,6 +22,7 @@ import { createLogger } from '../logger.js';
import {
isProviderModelRouteDisabled,
isUtilityRouteDisabled,
+ isUtilityRoutePaymentRequired,
} from '../utility-model/oneShotCandidates.js';
import { getAppCapabilities } from '../appCapabilities.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
@@ -788,6 +789,16 @@ async function resolveVoiceInputRefinerChainForRuntime(
});
continue;
}
+ // BYOK LiteLLM refinement calls XD directly, outside the Session rail.
+ // Apply the same owner-scoped v5 paid entitlement used by utility one-shot
+ // candidates before admitting the profile into the fallback chain.
+ if (isUtilityRoutePaymentRequired(profile)) {
+ log.info('refiner profile skipped: paid entitlement required', {
+ profileId: profile.id,
+ model: profile.model,
+ });
+ continue;
+ }
refinerChainProfiles.push(profile);
refinerReadinessList.push(readiness);
}
@@ -876,11 +887,11 @@ async function getVoiceInputRefinerReadiness(
}
/**
- * TextModelClient 的停用轴 live 包装(BYOK):每次 requestJson(= 一次精修付费请求)
- * 前按当前 override 重查该档的真实路由,停用即抛错 —— FallbackTextModelClient 将其
- * 视为该档失败,自然落到下一档(PR #744 review 第二十一轮)。
+ * TextModelClient 的 live 可用性包装(BYOK):每次 requestJson(= 一次精修请求)
+ * 前重查设置停用与 Cindy 账号付费权限;不可用即抛错,FallbackTextModelClient
+ * 将其视为该档失败并自然落到下一档。
*/
-function guardRefinerClientAgainstDisable(
+function guardRefinerClientAgainstUnavailableRoute(
profile: VoiceInputRefinerProfile,
client: TextModelClient,
): TextModelClient {
@@ -889,6 +900,12 @@ function guardRefinerClientAgainstDisable(
if (isUtilityRouteDisabled(profile)) {
return Promise.reject(new Error('voice refiner route disabled in settings'));
}
+ // Refinement may start minutes after chain resolution. Re-read the live
+ // owner-scoped catalog immediately before every direct XD request so a
+ // newly denied paid model cannot be dispatched from a retained session.
+ if (isUtilityRoutePaymentRequired(profile)) {
+ return Promise.reject(new Error('voice refiner route requires paid entitlement'));
+ }
return client.requestJson(input);
},
};
@@ -2167,10 +2184,10 @@ export function registerVoiceInputIpc(): void {
const refinerAttempts: FallbackTextModelAttempt[] = readyRefinerProfiles.map((profile) => ({
profileId: profile.id as VoiceInputRefinerProviderKind,
model: profile.model,
- // live 谓词包装(PR #744 review 第二十一轮):精修请求在用户停止说话时才
- // 发出,可能距控制器构造数分钟 —— 每次请求前按当前 override 重查,停用
- // 即抛错让 fallback 落到下一档。
- client: guardRefinerClientAgainstDisable(
+ // live 谓词包装:精修请求在用户停止说话时才发出,可能距控制器构造
+ // 数分钟 —— 每次请求前重查设置停用与付费权限,不可用即让 fallback
+ // 落到下一档。
+ client: guardRefinerClientAgainstUnavailableRoute(
profile,
createVoiceInputTextModelClient(profile, {
timeoutMs: VOICE_INPUT_REFINER_IDLE_TIMEOUT_MS,
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 53c444c9a4..aa480a45c1 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -2338,6 +2338,7 @@ describe('makerChatStore text delta batching', () => {
source: null,
endpoint: null,
errorCode: 'NETWORK_ERROR',
+ accountTier: null,
});
onInputProjection?.(
projection(SESSION_ID, {
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx
index c86231b1b4..1bdd3e6d2d 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx
@@ -205,7 +205,7 @@ describe('ModelSelector codex/ key gate scope (#1568)', () => {
within(row).queryByText('codex/gpt-5.6-sol'),
);
expect(customRow).toBeTruthy();
- expect(customRow?.getAttribute('aria-disabled')).toBe('false');
+ expect(customRow?.hasAttribute('aria-disabled')).toBe(false);
});
it('still disables XD gateway codex/ models without a saved gateway key', async () => {
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorPaymentNavigation.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorPaymentNavigation.test.ts
new file mode 100644
index 0000000000..ac03cf0428
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorPaymentNavigation.test.ts
@@ -0,0 +1,39 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const modelSelectorSource = readFileSync(
+ resolve(__dirname, '..', 'components', 'new-chat', 'ModelSelector.tsx'),
+ 'utf8',
+);
+
+describe('ModelSelector paid model navigation', () => {
+ it('writes the billing deep link to the hash-router location', () => {
+ const start = modelSelectorSource.indexOf('const showPaymentRequired = () => {');
+ expect(start).toBeGreaterThanOrEqual(0);
+
+ const end = modelSelectorSource.indexOf('// ── 单个模型行', start);
+ expect(end).toBeGreaterThan(start);
+
+ const paymentRequiredBlock = modelSelectorSource.slice(start, end);
+ expect(paymentRequiredBlock).toContain(
+ "window.location.hash = '#/settings?tab=billing';",
+ );
+ expect(paymentRequiredBlock).not.toContain('window.history');
+ });
+
+ it('keeps the payment explanation action enabled for assistive technology', () => {
+ const start = modelSelectorSource.indexOf('const renderModelItem =');
+ const end = modelSelectorSource.indexOf('const emptyState =', start);
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(end).toBeGreaterThan(start);
+
+ const modelRowBlock = modelSelectorSource.slice(start, end);
+ expect(modelRowBlock).toContain('aria-disabled={disabled ? true : undefined}');
+ expect(modelRowBlock).toContain(
+ "`${model.displayName} · ${t('newChat.modelSelector.paymentRequired.unlock')}`",
+ );
+ expect(modelRowBlock).not.toContain('aria-disabled={disabled || paymentRequired}');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
index a7d4b6acc3..318ce58be5 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
@@ -22,6 +22,7 @@ vi.mock('react-i18next', async (importOriginal) => ({
const translations: Record<string, string> = {
'settings.providers.anthropic.title': 'Anthropic',
'settings.providers.xd.title': 'Cindy AI',
+ 'settings.providers.xd.accountTier.free': '免费版',
'newChat.modelSelector.trigger.placeholder': '选择模型',
'newChat.modelSelector.trigger.aria': `Select model. Current: ${options?.model ?? ''}`,
'newChat.modelSelector.trigger.ariaWithEffort': `Select model. Current: ${options?.model ?? ''}, effort: ${options?.effort ?? ''}`,
@@ -157,6 +158,18 @@ vi.mock('@/hooks/useModelPricing', () => ({
useReferenceModelPricing: () => ({}),
}));
+const modelAccessState = vi.hoisted(() => ({
+ accountTier: null as 'free' | 'paid' | 'not_applicable' | null,
+}));
+vi.mock('@/hooks/useModelAccessStatus', () => ({
+ useModelAccessStatus: () => ({
+ state: 'ok',
+ source: 'server',
+ endpoint: 'https://gateway.example.com',
+ accountTier: modelAccessState.accountTier,
+ }),
+}));
+
const providersRef = vi.hoisted(() => {
const DEFAULT_PROVIDERS = [
{
@@ -264,6 +277,7 @@ beforeEach(() => {
floatingUiMocks.size.mockClear();
floatingUiMocks.useFloating.mockClear();
providersRef.providers = providersRef.DEFAULT_PROVIDERS;
+ modelAccessState.accountTier = null;
visibleModelsRef.models = [];
(window as unknown as { electronAPI: unknown }).electronAPI = {
maker: { requestProviderModelsAutoRefresh },
@@ -359,6 +373,51 @@ async function waitForSearchInputFocus(): Promise<HTMLElement> {
}
describe('ModelSelector provider groups', () => {
+ it('仅在本机经典 Cindy AI 分组旁显示免费版标签', async () => {
+ providersRef.providers = [
+ ...(providersRef.DEFAULT_PROVIDERS as unknown[]),
+ {
+ id: 'xd',
+ name: 'Cindy AI',
+ source: 'builtin',
+ agents: ['claude-code'],
+ auth: { method: 'apiKey' },
+ routing: { 'claude-code': {} },
+ connected: true,
+ models: {
+ 'claude-code': [
+ {
+ id: 'cindy-free-model',
+ name: 'Cindy Free Model',
+ contextWindow: 200000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ },
+ ],
+ },
+ },
+ ] as unknown[];
+ modelAccessState.accountTier = 'free';
+
+ const view = renderSelector();
+ await openDropdown();
+ const badge = screen.getByTestId('cindy-ai-model-group-free-tier-badge');
+ expect(badge.textContent).toBe('免费版');
+ expect(badge.classList.contains('ml-auto')).toBe(true);
+
+ view.unmount();
+ modelAccessState.accountTier = 'paid';
+ const paidView = renderSelector();
+ await openDropdown();
+ expect(screen.queryByTestId('cindy-ai-model-group-free-tier-badge')).toBeNull();
+
+ paidView.unmount();
+ modelAccessState.accountTier = 'not_applicable';
+ renderSelector();
+ await openDropdown();
+ expect(screen.queryByTestId('cindy-ai-model-group-free-tier-badge')).toBeNull();
+ });
+
it('renders a group heading for each provider', async () => {
renderSelector();
await openDropdown();
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
index 5fcd135261..1083fdf7df 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
@@ -9,7 +9,7 @@
* 4. 正常态版面上不出现「重试 / 重新获取凭据 / 轮换密钥」这类按钮 —— 它们退进「···」菜单。
*/
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import React from 'react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -28,6 +28,7 @@ const { providersState, authState, creditUsageState, modelAccessState, apiKeySta
modelAccessState: {
state: 'ok' as 'ok' | 'failed' | 'unsupported' | 'idle' | 'syncing' | 'disabled',
source: 'server' as string | null,
+ accountTier: null as 'free' | 'paid' | 'not_applicable' | null,
},
apiKeyState: { key: 'sk-live-abcd1234ef2a', hasSavedKey: true },
}),
@@ -137,7 +138,18 @@ function makeXd(): ProviderView {
agents: ['claude-code', 'codex'],
auth: { method: 'managed' },
routing: {},
- models: { 'claude-code': [], codex: [] },
+ models: {
+ 'claude-code': [
+ {
+ id: 'cindy-test-model',
+ name: 'Cindy Test Model',
+ contextWindow: 200000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ },
+ ],
+ codex: [],
+ },
connected: true,
} as unknown as ProviderView;
}
@@ -174,6 +186,7 @@ beforeEach(() => {
creditUsageState.available = '18.42';
modelAccessState.state = 'ok';
modelAccessState.source = 'server';
+ modelAccessState.accountTier = null;
apiKeyState.hasSavedKey = true;
(window as unknown as { electronAPI: unknown }).electronAPI = {
maker: {
@@ -194,6 +207,32 @@ afterEach(() => {
});
describe('ProvidersSection — Cindy AI 账户资产模块', () => {
+ it('仅免费个人账号在 Cindy AI 模型数量后显示身份标签', async () => {
+ modelAccessState.accountTier = 'free';
+ renderSection();
+
+ const badge = await screen.findByTestId('cindy-ai-free-tier-badge');
+ expect(badge.textContent).toBe('settings.providers.xd.accountTier.free');
+ const assetModule = screen.getByTestId('cindy-ai-asset-module');
+ expect(assetModule.contains(badge)).toBe(false);
+ expect(badge.previousElementSibling?.textContent).toBe(
+ 'settings.providers.models.modelCount',
+ );
+ expect(screen.getByTestId('provider-detail-metadata').contains(badge)).toBe(true);
+
+ cleanup();
+ modelAccessState.accountTier = 'paid';
+ renderSection();
+ await screen.findAllByText('settings.providers.xd.title');
+ expect(screen.queryByTestId('cindy-ai-free-tier-badge')).toBeNull();
+
+ cleanup();
+ modelAccessState.accountTier = 'not_applicable';
+ renderSection();
+ await screen.findAllByText('settings.providers.xd.title');
+ expect(screen.queryByTestId('cindy-ai-free-tier-badge')).toBeNull();
+ });
+
it('个人云账号:显示可用余额 + 两个动作,并深链到计费页 / 充值意图', async () => {
renderSection();
@@ -217,6 +256,12 @@ describe('ProvidersSection — Cindy AI 账户资产模块', () => {
const topupButton = screen.getByText('billing.settings.topupCard.action').closest('button');
expect(topupButton?.style.backgroundColor).toBe('var(--accent-cta-bg-pure)');
expect(topupButton?.style.color).toBe('var(--accent-pure-cta-fg)');
+ const usageButton = screen.getByText('settings.providers.xd.asset.viewUsage').closest('button');
+ expect(usageButton?.style.backgroundColor).toBe('var(--settings-btn-secondary-bg)');
+ expect(usageButton?.style.color).toBe('var(--settings-btn-secondary-text)');
+
+ const assetModule = screen.getByTestId('cindy-ai-asset-module');
+ expect(assetModule.children).toHaveLength(2);
});
it('正常态版面上没有重试 / 轮换 / 重新获取凭据按钮(它们退进「···」菜单)', async () => {
@@ -276,9 +321,13 @@ describe('ProvidersSection — Cindy AI 账户资产模块', () => {
// Radix 的 DropdownMenuTrigger 走 pointerdown / 键盘,jsdom 下没有 PointerEvent,
// 用键盘打开(与用户的键盘路径一致)。
- fireEvent.keyDown(await screen.findByLabelText('settings.providers.detail.moreActionsAria'), {
- key: 'Enter',
- });
+ const providerIdentity = await screen.findByTestId('provider-detail-identity');
+ const providerHeader = providerIdentity.parentElement;
+ expect(providerHeader).not.toBeNull();
+ fireEvent.keyDown(
+ within(providerHeader!).getByLabelText('settings.providers.detail.moreActionsAria'),
+ { key: 'Enter' },
+ );
expect(await screen.findByText('settings.providers.xd.sync.refresh')).toBeTruthy();
expect(screen.getByText('settings.providers.xd.sync.rotate')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts b/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts
index d0549de207..382e45032f 100644
--- a/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts
+++ b/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts
@@ -11,9 +11,11 @@ import {
buildUnionRows,
countModelsByAgent,
getHiddenAgents,
+ hasPaymentRequiredDisabledRow,
isCapabilityRow,
isRowDisabled,
isRowDiverged,
+ isRowPaymentRequired,
loadCollapsedMap,
} from '@/components/settings/UnifiedModelList';
import {
@@ -195,6 +197,25 @@ describe('countModelsByAgent', () => {
]);
});
+ it('付费锁定行不进批量显示分母,其历史隐藏偏好不会卡住 allOn', () => {
+ const withPaymentRequired = {
+ ...provider,
+ models: {
+ ...provider.models,
+ codex: [
+ ...(provider.models.codex ?? []),
+ { ...model('paid-model'), availability: 'requires_payment' },
+ ],
+ },
+ } as ProviderView;
+ setModelVisibility('codex', 'p1', 'paid-model', false);
+
+ expect(countModelsByAgent(withPaymentRequired)).toEqual([
+ { agent: 'claude-code', on: 2, total: 2 },
+ { agent: 'codex', on: 2, total: 2 },
+ ]);
+ });
+
it('停用模型与能力模型(image 等)不进「显示 x/y」计数', () => {
const withExtras = {
...provider,
@@ -250,11 +271,38 @@ describe('停用轴(isRowDisabled / isCapabilityRow)', () => {
expect(isRowDisabled(rows[1])).toBe(false);
});
+ it('付费锁定的停用行阻止整组 reset,避免批量入口改写其历史 override', () => {
+ const withLockedDisabled = {
+ ...provider,
+ models: {
+ ...provider.models,
+ codex: [
+ ...(provider.models.codex ?? []),
+ { ...model('paid-disabled'), availability: 'requires_payment', disabled: true },
+ ],
+ },
+ } as ProviderView;
+ const rows = buildUnionRows(withLockedDisabled);
+
+ expect(hasPaymentRequiredDisabledRow(rows)).toBe(true);
+ expect(
+ hasPaymentRequiredDisabledRow(
+ rows,
+ (row) => row.id === 'paid-disabled' ? false : isRowDisabled(row),
+ ),
+ ).toBe(false);
+ });
+
it('专属媒体清单(imageModels/videoModels)合成能力行:可停用、与 agent 清单同 id 去重', () => {
const withMedia = {
...provider,
imageModels: [
- { id: 'gpt-image-2', name: 'GPT Image 2', disabled: true },
+ {
+ id: 'gpt-image-2',
+ name: 'GPT Image 2',
+ disabled: true,
+ availability: 'requires_payment',
+ },
{ id: 'shared', name: '与 agent 清单撞 id(应被去重)' },
],
videoModels: [{ id: 'seedance-fast', name: 'Seedance 快速' }],
@@ -263,6 +311,7 @@ describe('停用轴(isRowDisabled / isCapabilityRow)', () => {
const image = rows.find((r) => r.id === 'gpt-image-2')!;
expect(isCapabilityRow(image, false)).toBe(true);
expect(isRowDisabled(image)).toBe(true);
+ expect(isRowPaymentRequired(image)).toBe(true);
expect(rows.find((r) => r.id === 'seedance-fast')).toBeTruthy();
// 同 id 去重:'shared' 只保留 agent 清单那行(可见性开关照常)。
expect(rows.filter((r) => r.id === 'shared')).toHaveLength(1);
diff --git a/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx b/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx
index 0949688dc7..ab886027b9 100644
--- a/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx
@@ -114,7 +114,8 @@ const providersRef = vi.hoisted(() => ({
contextWindow: 400000,
efforts: ['low', 'medium', 'high'],
defaultEffort: 'medium',
- description: 'A very long English description that must stay on one line and never blow up the panel layout in narrow windows',
+ description:
+ 'A very long English description that must stay on one line and never blow up the panel layout in narrow windows',
},
],
'claude-code': [
@@ -285,8 +286,9 @@ describe('统一模型选择器面板', () => {
expect(triple?.textContent).toContain('中');
});
// 已自定义 → 底栏出现「恢复推荐」。
- expect(within(await screen.findByTestId('unified-model-config-flyout')).getByText('恢复推荐'))
- .toBeTruthy();
+ expect(
+ within(await screen.findByTestId('unified-model-config-flyout')).getByText('恢复推荐'),
+ ).toBeTruthy();
});
it('点 ☆ 把当前生效配置存成收藏副本,收藏区置顶出现', async () => {
@@ -2118,10 +2120,7 @@ describe('统一面板 · 编辑选中的收藏同步到 live', () => {
*/
describe('统一面板 · 恢复推荐删记忆键', () => {
/** 带删除入口的最小记忆实现(本地 providerModelMemory 的形状)。 */
- function makeMemory(seed?: {
- effort?: Record<string, string>;
- fast?: Record<string, boolean>;
- }) {
+ function makeMemory(seed?: { effort?: Record<string, string>; fast?: Record<string, boolean> }) {
const keyOf = (agent: string, providerId: string, modelId: string) =>
`${agent}|${providerId}|${modelId}`;
const effort = new Map<string, string>(Object.entries(seed?.effort ?? {}));
@@ -2202,8 +2201,9 @@ describe('统一面板 · 恢复推荐删记忆键', () => {
// 服务端把 codex 那条的推荐档改成 low —— 记忆表里没有该键,所以行必须跟着变。
// (旧做法把 'high' 快照写进了记忆槽,这里就会仍然显示「高」。)
- const codexModels = (providersRef.providers[2] as { models: { codex: { defaultEffort: string }[] } })
- .models.codex;
+ const codexModels = (
+ providersRef.providers[2] as { models: { codex: { defaultEffort: string }[] } }
+ ).models.codex;
const restore = codexModels[0].defaultEffort;
codexModels[0].defaultEffort = 'low';
try {
@@ -2301,7 +2301,11 @@ describe('统一面板 · 会话内回传收藏锚点', () => {
});
it('跨引擎选中收藏:锚点随切换事务的入参交出去,由调用方按真实结果决定记不记', async () => {
- const uid = addModelFavorite({ providerId: 'anthropic', modelId: 'claude-opus-5', agent: 'cc' });
+ const uid = addModelFavorite({
+ providerId: 'anthropic',
+ modelId: 'claude-opus-5',
+ agent: 'cc',
+ });
const onCrossEngineSelect = vi.fn(() => true);
const onSessionFavoriteAnchorChange = vi.fn();
renderPanel({
@@ -2468,9 +2472,7 @@ describe('统一面板 · 会话内回传收藏锚点', () => {
fireEvent.click(flyout.querySelector('[data-engine-capsule="cc"]') as HTMLElement);
});
// 入参照样带锚点(取消与否是调用方的事),但副本不落、锚点回调不触发。
- expect(onCrossEngineSelect).toHaveBeenCalledWith(
- expect.objectContaining({ favoriteUid: uid }),
- );
+ expect(onCrossEngineSelect).toHaveBeenCalledWith(expect.objectContaining({ favoriteUid: uid }));
expect(listModelFavorites()[0]?.agent).toBe('codex');
expect(onSessionFavoriteAnchorChange).not.toHaveBeenCalled();
});
@@ -2518,7 +2520,12 @@ describe('统一面板 · 新会话选中直通', () => {
});
expect(getModelEngineOverride('xd', 'gpt-5.5')).toBe('cc');
expect(onUnifiedSelect).toHaveBeenCalledWith(
- expect.objectContaining({ providerId: 'xd', modelId: 'gpt-5.5', engine: 'cc', effort: 'medium' }),
+ expect.objectContaining({
+ providerId: 'xd',
+ modelId: 'gpt-5.5',
+ engine: 'cc',
+ effort: 'medium',
+ }),
);
});
@@ -2576,9 +2583,7 @@ describe('统一面板 · 新会话选中直通', () => {
selectedFavoriteUid: uid,
}),
);
- let selected = screen
- .getByRole('listbox')
- .querySelectorAll('[data-model-selected="true"]');
+ let selected = screen.getByRole('listbox').querySelectorAll('[data-model-selected="true"]');
expect(selected).toHaveLength(1);
expect(selected[0].getAttribute('data-unified-anchor')).toBe(`fav::${uid}`);
unmount();
@@ -2623,9 +2628,7 @@ describe('统一面板 · 新会话选中直通', () => {
selectedFavoriteUid: uid,
}),
);
- const selected = screen
- .getByRole('listbox')
- .querySelectorAll('[data-model-selected="true"]');
+ const selected = screen.getByRole('listbox').querySelectorAll('[data-model-selected="true"]');
expect(selected).toHaveLength(1);
expect(selected[0].getAttribute('data-unified-anchor')).toBe(`fav::${uid}`);
});
@@ -2678,8 +2681,9 @@ describe('统一面板 · 实测回归', () => {
fireEvent.pointerEnter(rowFor('GPT-5.5'));
});
const flyout = await screen.findByTestId('unified-model-config-flyout');
- expect(flyout.querySelector('[data-engine-capsule="cc"]')?.getAttribute('data-engine-active'))
- .toBe('true');
+ expect(
+ flyout.querySelector('[data-engine-capsule="cc"]')?.getAttribute('data-engine-active'),
+ ).toBe('true');
await act(async () => {
fireEvent.click(within(flyout).getByText('恢复推荐'));
});
@@ -2688,8 +2692,9 @@ describe('统一面板 · 实测回归', () => {
// 2) 浮层内引擎胶囊回到推荐项(家族主场 codex),底栏不再是「已自定义」
await waitFor(() => {
const current = screen.getByTestId('unified-model-config-flyout');
- expect(current.querySelector('[data-engine-capsule="codex"]')?.getAttribute('data-engine-active'))
- .toBe('true');
+ expect(
+ current.querySelector('[data-engine-capsule="codex"]')?.getAttribute('data-engine-active'),
+ ).toBe('true');
expect(within(current).queryByText('恢复推荐')).toBeNull();
});
// 3) 行内三元组跟着回落
@@ -3008,6 +3013,98 @@ describe('统一面板 · 行内折扣徽标', () => {
});
});
+describe('统一面板 · 付费锁定行', () => {
+ it('保持键盘可达,点击或回车只打开付费提示,不触发选择与配置', async () => {
+ const { UnifiedModelRow } = await import('@/components/new-chat/UnifiedModelRow');
+ const onSelect = vi.fn();
+ const onReveal = vi.fn();
+ const onPaymentRequired = vi.fn();
+ const renderRow = (interactionDisabled: boolean) => (
+ <UnifiedModelRow
+ entry={{
+ providerId: 'xd',
+ modelId: 'paid-model',
+ displayName: 'Paid Model',
+ availability: 'requires_payment',
+ candidates: ['codex'],
+ recommended: 'codex',
+ nativeAgent: 'codex',
+ capabilities: {
+ codex: {
+ agent: 'codex',
+ wireModelId: 'paid-model',
+ efforts: ['medium'],
+ defaultEffort: 'medium',
+ defaultEffortSource: 'catalog',
+ supportsFastMode: false,
+ contextWindow: 200_000,
+ contextWindowVerified: false,
+ },
+ },
+ }}
+ anchor={{ kind: 'model', providerId: 'xd', modelId: 'paid-model' }}
+ config={{
+ engine: 'codex',
+ agent: 'codex',
+ efforts: ['medium'],
+ effort: 'medium',
+ fast: false,
+ fastCapable: false,
+ customized: false,
+ capability: null,
+ wireModelId: 'paid-model',
+ }}
+ selected={false}
+ active={false}
+ isFavoriteRow={false}
+ justFavorited={false}
+ interactionDisabled={interactionDisabled}
+ paymentRequired
+ paymentRequiredLabel="付费"
+ paymentRequiredUnlockLabel="付费解锁"
+ onPaymentRequired={onPaymentRequired}
+ effortLabelOf={(_agent, effort) => effort}
+ providers={[]}
+ onReveal={onReveal}
+ onRevealForKeyboard={vi.fn()}
+ onLeave={vi.fn()}
+ onBlurAway={vi.fn()}
+ onSelect={onSelect}
+ onStar={vi.fn()}
+ />
+ );
+ const row = render(renderRow(false));
+
+ const option = row.getByRole('option');
+ expect(option.hasAttribute('aria-disabled')).toBe(false);
+ expect(option.getAttribute('aria-label')).toBe('Paid Model · 付费解锁');
+ expect(option.hasAttribute('aria-keyshortcuts')).toBe(false);
+ expect(option.getAttribute('tabindex')).toBe('0');
+ const paymentBadge = row.getByText('付费').closest('[data-payment-required-badge]');
+ expect(paymentBadge).not.toBeNull();
+ expect(paymentBadge?.closest('[data-model-row-meta]')).not.toBeNull();
+ const paymentUnlock = row.getByText('付费解锁').closest('[data-payment-required-unlock]');
+ expect(paymentUnlock).not.toBeNull();
+ expect(paymentUnlock?.className).toContain('invisible');
+ expect(paymentUnlock?.className).toContain('group-hover/row:visible');
+ expect(paymentUnlock?.closest('[data-model-row-meta]')).not.toBeNull();
+ fireEvent.pointerEnter(option);
+ fireEvent.focus(option);
+ fireEvent.click(option);
+ fireEvent.keyDown(option, { key: 'Enter' });
+ expect(onReveal).not.toHaveBeenCalled();
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onPaymentRequired).toHaveBeenCalledTimes(2);
+
+ row.rerender(renderRow(true));
+ const disabledOption = row.getByRole('option');
+ expect(disabledOption.getAttribute('aria-disabled')).toBe('true');
+ fireEvent.click(disabledOption);
+ fireEvent.keyDown(disabledOption, { key: 'Enter' });
+ expect(onPaymentRequired).toHaveBeenCalledTimes(2);
+ });
+});
+
describe('列表样式试用开关(badge · v7 引擎徽标行)', () => {
afterEach(async () => {
const { __resetForTest } = await import('@/state/modelPickerLayout');
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index 4ff59788c1..9539999c6b 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -33,6 +33,7 @@ import {
Search,
Unplug,
Zap,
+ Lock,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -41,6 +42,7 @@ import { flashScrollbar } from '@/lib/scrollbarAutoHide';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { MorphPopover } from '@/components/ui/morph-popover';
+import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { AnthropicMark } from '@/components/icons/AnthropicMark';
import { OpenAIMark } from '@/components/icons/OpenAIMark';
import { XDIncMark } from '@/components/icons/XDIncMark';
@@ -65,6 +67,7 @@ import {
import { useApiKey } from '@/hooks/useApiKey';
import { useConnectedSource } from '@/hooks/useConnectedSource';
import { useGatewayModelPricing, useReferenceModelPricing } from '@/hooks/useModelPricing';
+import { useModelAccessStatus } from '@/hooks/useModelAccessStatus';
import { useProviders } from '@/hooks/useProviders';
import { providerDisplayName as sharedProviderDisplayName } from '@/lib/providerDisplayName';
import {
@@ -113,6 +116,7 @@ import {
import { isProviderLogoKind } from '@cindy/model-providers/branding';
import { compactEnglishEffortLabel } from '@cindy/maker-shared/agent-capabilities';
import { getModelPriceQuote } from '../../../shared/modelPriceQuote';
+import type { ModelAccessAccountTier } from '../../../shared/modelAccess';
import { applyProviderOrder } from '../../../shared/providerOrder';
import type { ModelPricingCatalog } from '../../../shared/regionalMoney';
import { buildProviderSections } from './sourceSwitch';
@@ -448,6 +452,7 @@ interface RowModel {
codexCompatibilityWireProtocol?: 'openai-chat' | 'anthropic-messages';
/** 展示图标 id(AI Gateway / 目录设定,SectionModel.icon);flat 列表的 ModelDescriptor 无此字段。 */
icon?: string;
+ availability?: 'available' | 'requires_payment';
}
type Translate = (key: string, options?: { defaultValue?: string }) => string;
@@ -1009,11 +1014,13 @@ export function resolveRemoteModelListStatus({
export function ModelSelectorContent(props: ModelSelectorContentProps) {
const gatewayPricing = useGatewayModelPricing();
const referencePricing = useReferenceModelPricing();
+ const { accountTier } = useModelAccessStatus();
return (
<ModelSelectorContentView
{...props}
gatewayPricing={gatewayPricing}
referencePricing={referencePricing}
+ modelAccessAccountTier={accountTier}
/>
);
}
@@ -1058,10 +1065,13 @@ function ModelSelectorContentView({
interactionDisabled = false,
gatewayPricing,
referencePricing,
+ modelAccessAccountTier,
}: ModelSelectorContentProps & {
gatewayPricing: ModelPricingCatalog | null;
referencePricing: ModelPricingCatalog | null;
+ modelAccessAccountTier: ModelAccessAccountTier | null;
}) {
+ const confirmDialog = useOptionalConfirmDialog();
// 当前来源解析器:已建会话 = 实际路由口径(含停用拷贝),其余 = 准入口径。
const resolveCurrentSourceId = actualRoute ? actualSourceIdForModel : effectiveSourceIdForModel;
const { t, i18n } = useTranslation();
@@ -1510,12 +1520,7 @@ function ModelSelectorContentView({
? resolveCurrentSourceId(providers, currentProviderId, id, priceAgentKind)
: null);
const pricing = effectiveProviderId === 'xd' ? gatewayPricing : referencePricing;
- const quote = getModelPriceQuote(
- pricing,
- effectiveProviderId,
- id,
- priceAgentKind ?? undefined,
- );
+ const quote = getModelPriceQuote(pricing, effectiveProviderId, id, priceAgentKind ?? undefined);
if (effectiveProviderId === 'xd' && (!quote || quote.source === 'gateway')) {
if (!quote && gatewayPricing == null) return null;
const effectiveProvider = providers.find((provider) => provider.id === effectiveProviderId);
@@ -1640,6 +1645,7 @@ function ModelSelectorContentView({
});
},
query,
+ includePaymentRequired: true,
});
// visibilityVersion 仅作刷新触发器(设置页改显示开关后强制重算);deviceId 切换需重算分段。
}, [
@@ -2144,18 +2150,31 @@ function ModelSelectorContentView({
enabled={
editingIsActive
? thinkingEnabled
- : (currentAgentKind && editingProviderId
- ? (modelMemory?.getThinking?.(currentAgentKind, editingProviderId, editingModel.id) ?? true)
- : true)
+ : currentAgentKind && editingProviderId
+ ? (modelMemory?.getThinking?.(
+ currentAgentKind,
+ editingProviderId,
+ editingModel.id,
+ ) ?? true)
+ : true
}
onToggle={() => {
const next = editingIsActive
? !thinkingEnabled
: !(currentAgentKind && editingProviderId
- ? (modelMemory?.getThinking?.(currentAgentKind, editingProviderId, editingModel.id) ?? true)
+ ? (modelMemory?.getThinking?.(
+ currentAgentKind,
+ editingProviderId,
+ editingModel.id,
+ ) ?? true)
: true);
if (currentAgentKind && editingProviderId) {
- modelMemory?.setThinking?.(currentAgentKind, editingProviderId, editingModel.id, next);
+ modelMemory?.setThinking?.(
+ currentAgentKind,
+ editingProviderId,
+ editingModel.id,
+ next,
+ );
}
if (editingIsActive) void onThinkingChange?.(next);
bump();
@@ -2293,6 +2312,24 @@ function ModelSelectorContentView({
</div>
) : null;
+ const showPaymentRequired = () => {
+ if (!confirmDialog) return;
+ void confirmDialog
+ .confirm({
+ title: t('newChat.modelSelector.paymentRequired.title'),
+ description: t('newChat.modelSelector.paymentRequired.description'),
+ confirmText: t('newChat.modelSelector.paymentRequired.action'),
+ cancelText: t('commonUi.confirmDialog.cancel'),
+ })
+ .then((accepted) => {
+ if (!accepted) return;
+ // Desktop 使用 createHashRouter;ModelSelectorContent 同时是可裸渲染的复用组件,
+ // 不能在这里强依赖 Router context。写入 hash 会触发 hashchange,并由正式路由
+ // 切到设置里的计费 tab;直接 pushState(pathname) 不会被 HashRouter 接管。
+ window.location.hash = '#/settings?tab=billing';
+ });
+ };
+
// ── 单个模型行 ───────────────────────────────────────────────────────────
// provider 非空(分段模式)→ 名字前缀该来源的 mark;null(flat / device-link)→ 无前缀。
const renderModelItem = (provider: ProviderView | null, model: RowModel) => {
@@ -2322,6 +2359,7 @@ function ModelSelectorContentView({
defaultEnabled: selectedCatalogModel?.defaultEnabled,
}));
const disabled = interactionDisabled || modelDisabledOf(provider, model.id);
+ const paymentRequired = model.availability === 'requires_payment';
const disabledReason = subscriptionDirectDisabledReason(model.id);
// 只选择模型 id 的入口没有 effort / Fast 语义;继续展示目录默认档会让用户
// 误以为该值可在当前入口调整。选择事务仍由 handleRowSelect 独立解析 effort,
@@ -2348,7 +2386,7 @@ function ModelSelectorContentView({
// session-agent-switch 浏览目标引擎态同样开放:选模型前正需要看描述/上下文/价格/来源;
// 面板内配置写的是**目标引擎**的 per-(来源,模型) 全局预设(currentAgentKind 已随浏览态
// 指向目标引擎),切换确认后由 performAgentSwitch 按预设恢复 effort / Fast。
- const hasOptions = !disabled;
+ const hasOptions = !disabled && !paymentRequired;
const isEditingThis =
!!editing && editing.modelId === model.id && editing.providerId === providerId;
const revealOptions = (anchor: HTMLDivElement) => {
@@ -2399,7 +2437,12 @@ function ModelSelectorContentView({
<div
role="option"
aria-selected={isSelected}
- aria-disabled={disabled}
+ aria-disabled={disabled ? true : undefined}
+ aria-label={
+ paymentRequired
+ ? `${model.displayName} · ${t('newChat.modelSelector.paymentRequired.unlock')}`
+ : undefined
+ }
title={disabledReason ?? undefined}
data-model-selected={isSelected ? 'true' : undefined}
data-model-options-active={isEditingThis ? 'true' : undefined}
@@ -2414,10 +2457,19 @@ function ModelSelectorContentView({
}}
onClick={() => {
if (disabled) return;
+ if (paymentRequired) {
+ showPaymentRequired();
+ return;
+ }
handleRowSelect(providerId, model.id);
}}
onKeyDown={(ev) => {
if (ev.target !== ev.currentTarget || disabled) return;
+ if (paymentRequired && (ev.key === 'Enter' || ev.key === ' ')) {
+ ev.preventDefault();
+ showPaymentRequired();
+ return;
+ }
if (ev.key === 'ArrowLeft' && hasOptions) {
ev.preventDefault();
revealOptions(ev.currentTarget);
@@ -2433,13 +2485,13 @@ function ModelSelectorContentView({
handleRowSelect(providerId, model.id);
}}
className={cn(
- 'flex w-full cursor-pointer items-center justify-between rounded-[8px] px-3 py-2',
+ 'group/row flex w-full cursor-pointer items-center justify-between rounded-[8px] px-3 py-2',
constrainedListMaxHeight !== undefined && 'min-h-9',
'transition-colors duration-100 hover:bg-[var(--model-item-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
isSelected && 'bg-[var(--model-item-hover)]',
isEditingThis &&
'bg-[var(--surface-hover)] ring-1 ring-inset ring-[var(--model-dropdown-border)]',
- disabled && 'cursor-not-allowed opacity-50 hover:bg-transparent',
+ (disabled || paymentRequired) && 'opacity-50',
)}
>
<span className="flex min-w-0 flex-1 items-center gap-2.5">
@@ -2477,8 +2529,28 @@ function ModelSelectorContentView({
/>
)}
</span>
- {(isHiddenSelectedModel || showSubscriptionTag || showPromotionTag) && (
+ {(paymentRequired ||
+ isHiddenSelectedModel ||
+ showSubscriptionTag ||
+ showPromotionTag) && (
<span data-model-tags className="ml-auto flex shrink-0 items-center gap-1.5">
+ {paymentRequired && (
+ <span
+ data-payment-required-unlock
+ className="invisible shrink-0 select-none text-11 font-medium text-[var(--text-secondary)] group-hover/row:visible group-focus-within/row:visible"
+ >
+ {t('newChat.modelSelector.paymentRequired.unlock')}
+ </span>
+ )}
+ {paymentRequired && (
+ <span
+ data-payment-required-badge
+ className="flex shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-11 text-[var(--text-secondary)]"
+ >
+ <Lock size={11} />
+ {t('newChat.modelSelector.paymentRequired.badge')}
+ </span>
+ )}
{isHiddenSelectedModel && (
<span
data-model-hidden-label
@@ -2682,195 +2754,199 @@ function ModelSelectorContentView({
// 在宿主高度**确定**时把面板列钳到宿主内(flex 拉伸 → 列内 min-h-0 让列表收缩滚动),
// 宿主高度不确定时百分比落空为 none,由面板列自己的绝对上限兜底 —— 两个分支各管一头。
<div className="flex max-h-full min-h-0 w-full min-w-0">
- <div
- ref={bindPaneElement}
- data-model-tag-density={modelTagDensity}
- data-unified-model-panel="true"
- className={cn(
- // 设计稿的面板骨架:搜索行贴顶(border-b 分隔)、列表贴边(自带 8px 内距)、
- // footer 用 border-t 分隔 —— 外层不再加统一 padding。
- // grow:stickyWidth 下宿主可能比内容宽(筛选后内容变窄、面板不回缩),
- // 面板列拉伸填满,不在边框内留空条。
- 'flex min-h-0 grow flex-col',
- // 高度上限必须给在**面板**上:不给的话,列表按内容撑到比视口还高,外层
- // popover 裁掉超出部分,用户就翻不到最后几行(2026-08-13 实测)。列表侧配
- // min-h-0 + flex-1 收缩并内部滚动,搜索框与底部 footer 始终露着。
- 'max-h-[min(560px,calc(100vh-120px))]',
- // 宽度自适应(规格 §1.2):长模型名先把面板撑宽,到上限才截断,不硬砍名字。
- // 最小宽只兜「搜索行 + 空态不局促」的底(Chris 2026-08-13:min 460 让短名列表
- // 中间留一条空隙 —— 面板应该贴着最长行收窄,理论最小值可以很小)。
- fluidWidth
- ? 'w-full min-w-0'
- : 'w-max min-w-[300px] max-w-[min(600px,calc(100vw-48px))]',
- )}
- >
- {/* 设计稿 .search-wrap:无框平铺行 + 底部 hairline(不是独立的胶囊输入框)。 */}
<div
+ ref={bindPaneElement}
+ data-model-tag-density={modelTagDensity}
+ data-unified-model-panel="true"
className={cn(
- 'flex shrink-0 items-center gap-2 border-b border-[var(--model-dropdown-border)] px-3.5 py-3',
- interactionDisabled ? 'text-[var(--text-disabled-tertiary)]' : 'text-[var(--text-tertiary)]',
+ // 设计稿的面板骨架:搜索行贴顶(border-b 分隔)、列表贴边(自带 8px 内距)、
+ // footer 用 border-t 分隔 —— 外层不再加统一 padding。
+ // grow:stickyWidth 下宿主可能比内容宽(筛选后内容变窄、面板不回缩),
+ // 面板列拉伸填满,不在边框内留空条。
+ 'flex min-h-0 grow flex-col',
+ // 高度上限必须给在**面板**上:不给的话,列表按内容撑到比视口还高,外层
+ // popover 裁掉超出部分,用户就翻不到最后几行(2026-08-13 实测)。列表侧配
+ // min-h-0 + flex-1 收缩并内部滚动,搜索框与底部 footer 始终露着。
+ 'max-h-[min(560px,calc(100vh-120px))]',
+ // 宽度自适应(规格 §1.2):长模型名先把面板撑宽,到上限才截断,不硬砍名字。
+ // 最小宽只兜「搜索行 + 空态不局促」的底(Chris 2026-08-13:min 460 让短名列表
+ // 中间留一条空隙 —— 面板应该贴着最长行收窄,理论最小值可以很小)。
+ fluidWidth
+ ? 'w-full min-w-0'
+ : 'w-max min-w-[300px] max-w-[min(600px,calc(100vw-48px))]',
)}
>
- <Search size={14} className="shrink-0" />
- <input
- type="text"
- disabled={interactionDisabled}
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={t('newChat.modelSelector.search.placeholderAll')}
+ {/* 设计稿 .search-wrap:无框平铺行 + 底部 hairline(不是独立的胶囊输入框)。 */}
+ <div
className={cn(
- 'min-w-0 flex-1 bg-transparent text-13 outline-none',
+ 'flex shrink-0 items-center gap-2 border-b border-[var(--model-dropdown-border)] px-3.5 py-3',
interactionDisabled
- ? 'cursor-not-allowed text-[var(--text-disabled)] placeholder:text-[var(--text-disabled-tertiary)]'
- : 'text-[var(--model-item-text)] placeholder:text-[var(--text-tertiary)]',
+ ? 'text-[var(--text-disabled-tertiary)]'
+ : 'text-[var(--text-tertiary)]',
)}
- aria-label={t('newChat.modelSelector.search.placeholderAll')}
- />
- </div>
- <UnifiedModelPanel
- providers={providers}
- providerOrder={deviceId ? undefined : localProviders.providerOrder}
- {...(unifiedAgents ? { agents: unifiedAgents } : {})}
- scope={unifiedScope}
- isVisible={unifiedIsVisible}
- {...(unifiedExcludeProvider ? { excludeProvider: unifiedExcludeProvider } : {})}
- {...(unifiedExcludeModel ? { excludeModel: unifiedExcludeModel } : {})}
- sourceVersion={[
- visibilityVersion,
- deviceId ?? '',
- excludeSubscriptionDirect ? 1 : 0,
- excludeChatBridgedCodex ? 1 : 0,
- remoteProviders.modelVisibilityOverrides ? 'ov' : 'no-ov',
- ].join('|')}
- query={query}
- // field 形态的面板宽度绑 trigger,定宽 sizer 无用武之地(见该 prop 说明)。
- panelWidthFluid={fluidWidth}
- selected={{ providerId: activeSourceId, modelId }}
- selectedFavoriteUid={selectedFavoriteUid}
- liveAgentKind={currentAgentKind}
- fastMode={fastMode}
- selectedEffort={effort}
- {...(modelMemory ? { modelMemory } : {})}
- agentFastModeCapable={unifiedAgentFastCapable}
- priceOf={(providerId, id, agent) => pricePresentationOf(providerId, id, agent)}
- providerLabel={unifiedProviderLabel}
- effortLabelOf={unifiedEffortLabel}
- {...(constrainedListMaxHeight !== undefined
- ? { listMaxHeight: constrainedListMaxHeight }
- : {})}
- interactionDisabled={interactionDisabled}
- configurationEnabled={configurationEnabled}
- {...(sessionEngineFilter ? { sessionEngineFilter } : {})}
- {...(followSession ? { followSession } : {})}
- onSelect={(providerId, id, rowEffort, rowConfig) => {
- const rowEffortValue = rowEffort === '' ? undefined : rowEffort;
- // 草稿(M5):整行原样直通给调用方 —— 引擎跟着模型一起落,中途不再被单引擎
- // 链路重解析一次(见 onUnifiedSelect 的说明)。
- if (onUnifiedSelect) {
- onUnifiedSelect({
- providerId,
- modelId: id,
- ...(rowEffortValue ? { effort: rowEffortValue } : {}),
- engine: rowConfig.engine,
- fast: rowConfig.fast,
- favoriteUid: rowConfig.favoriteUid,
- });
- closeOptionsPanel();
- onDismiss?.();
- return;
- }
- // 已建会话(M6):同引擎行照旧走 onProviderChange 直切;跨引擎行在 selectRow
- // 里就已经改道 sessionEngineFilter.onCrossEngineSelect,到不了这里。
- // 「同模型不同配置的收藏」与「锚点只在真的应用后才记」两件事收在
- // applyUnifiedSessionSelect 里(见其头注,M3 / M4)。
- void applyUnifiedSessionSelect({
- providerId,
- wireModelId: id,
- effort: rowEffortValue,
- config: rowConfig,
- });
- }}
- onSelectedFavoriteAnchorClear={(providerId, id, rowEffort, rowConfig) => {
- // 用户在**同模型的普通模型行**上改了实时深度 / Fast:正在跑的配置已经不再等于那份
- // 收藏副本(2026-08-17 review 第五轮 M2)。这里只清锚点 —— 模型 / 引擎一个字没变,
- // 不是一次行选择,**刻意不收面板**(用户还在浮层里继续调)。
- const rowEffortValue = rowEffort === '' ? undefined : rowEffort;
- if (onUnifiedSelect) {
- // 草稿:锚点由这条直通链路的 favoriteUid 承载(草稿层没有第二个清锚入口),
- // 原样把当前 (来源, 模型, 引擎) 连同刚改完的深度 / Fast 重写一遍并置空 uid。
- onUnifiedSelect({
- providerId,
- modelId: id,
- ...(rowEffortValue ? { effort: rowEffortValue } : {}),
- engine: rowConfig.engine,
- fast: rowConfig.fast,
- favoriteUid: null,
- });
- return;
- }
- onSessionFavoriteAnchorChange?.(null);
- }}
- {...(onEffortChange ? { onEffortChangeLive: onEffortChange } : {})}
- {...(onFastModeChange ? { onFastModeChangeLive: onFastModeChange } : {})}
- panelElement={paneElement}
- {...(overlayContentClassName !== undefined
- ? { overlayClassName: overlayContentClassName }
- : {})}
- />
- {/* footer:「连接来源」(与既有面板同规则,device-link 远程隐藏)+ 右侧
- 列表样式试用开关(本机偏好,见 modelPickerLayout;两种样式并存期的入口)。 */}
- <div className="flex shrink-0 items-center justify-between gap-2 border-t border-[var(--model-dropdown-border)] px-3.5 py-[9px]">
- {onNavigateToProviders && !deviceId ? (
- <button
- type="button"
+ >
+ <Search size={14} className="shrink-0" />
+ <input
+ type="text"
disabled={interactionDisabled}
- onClick={onNavigateToProviders}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('newChat.modelSelector.search.placeholderAll')}
className={cn(
- 'flex min-w-0 items-center gap-1.5 text-13 text-[var(--text-secondary)]',
- 'transition-colors hover:text-[var(--text-primary)]',
- interactionDisabled && 'cursor-not-allowed opacity-50',
+ 'min-w-0 flex-1 bg-transparent text-13 outline-none',
+ interactionDisabled
+ ? 'cursor-not-allowed text-[var(--text-disabled)] placeholder:text-[var(--text-disabled-tertiary)]'
+ : 'text-[var(--model-item-text)] placeholder:text-[var(--text-tertiary)]',
)}
- >
- <Plus size={14} className="shrink-0" />
- <span className="truncate">{t('newChat.modelSelector.source.connect')}</span>
- </button>
- ) : (
- <span />
- )}
- {/* 右侧两个文字按钮(三档并存,Chris 2026-08-17):A/B 互切 + 切回老版。 */}
- <div className="flex shrink-0 items-center gap-3">
- <button
- type="button"
- data-layout-toggle
- disabled={interactionDisabled}
- onClick={() =>
- setModelPickerLayout(pickerLayout === 'badge' ? 'classic' : 'badge')
+ aria-label={t('newChat.modelSelector.search.placeholderAll')}
+ />
+ </div>
+ <UnifiedModelPanel
+ providers={providers}
+ providerOrder={deviceId ? undefined : localProviders.providerOrder}
+ {...(unifiedAgents ? { agents: unifiedAgents } : {})}
+ scope={unifiedScope}
+ isVisible={unifiedIsVisible}
+ {...(unifiedExcludeProvider ? { excludeProvider: unifiedExcludeProvider } : {})}
+ {...(unifiedExcludeModel ? { excludeModel: unifiedExcludeModel } : {})}
+ sourceVersion={[
+ visibilityVersion,
+ deviceId ?? '',
+ excludeSubscriptionDirect ? 1 : 0,
+ excludeChatBridgedCodex ? 1 : 0,
+ remoteProviders.modelVisibilityOverrides ? 'ov' : 'no-ov',
+ ].join('|')}
+ query={query}
+ // field 形态的面板宽度绑 trigger,定宽 sizer 无用武之地(见该 prop 说明)。
+ panelWidthFluid={fluidWidth}
+ selected={{ providerId: activeSourceId, modelId }}
+ selectedFavoriteUid={selectedFavoriteUid}
+ liveAgentKind={currentAgentKind}
+ fastMode={fastMode}
+ selectedEffort={effort}
+ {...(modelMemory ? { modelMemory } : {})}
+ agentFastModeCapable={unifiedAgentFastCapable}
+ priceOf={(providerId, id, agent) => pricePresentationOf(providerId, id, agent)}
+ providerLabel={unifiedProviderLabel}
+ effortLabelOf={unifiedEffortLabel}
+ {...(constrainedListMaxHeight !== undefined
+ ? { listMaxHeight: constrainedListMaxHeight }
+ : {})}
+ interactionDisabled={interactionDisabled}
+ includePaymentRequired
+ paymentRequiredLabel={t('newChat.modelSelector.paymentRequired.badge')}
+ paymentRequiredUnlockLabel={t('newChat.modelSelector.paymentRequired.unlock')}
+ onPaymentRequired={showPaymentRequired}
+ configurationEnabled={configurationEnabled}
+ {...(sessionEngineFilter ? { sessionEngineFilter } : {})}
+ {...(followSession ? { followSession } : {})}
+ onSelect={(providerId, id, rowEffort, rowConfig) => {
+ const rowEffortValue = rowEffort === '' ? undefined : rowEffort;
+ // 草稿(M5):整行原样直通给调用方 —— 引擎跟着模型一起落,中途不再被单引擎
+ // 链路重解析一次(见 onUnifiedSelect 的说明)。
+ if (onUnifiedSelect) {
+ onUnifiedSelect({
+ providerId,
+ modelId: id,
+ ...(rowEffortValue ? { effort: rowEffortValue } : {}),
+ engine: rowConfig.engine,
+ fast: rowConfig.fast,
+ favoriteUid: rowConfig.favoriteUid,
+ });
+ closeOptionsPanel();
+ onDismiss?.();
+ return;
}
- className={cn(
- 'shrink-0 whitespace-nowrap text-12 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-secondary)]',
- interactionDisabled && 'cursor-not-allowed opacity-50',
- )}
- >
- {pickerLayout === 'badge'
- ? t('newChat.modelSelector.unified.layoutClassic')
- : t('newChat.modelSelector.unified.layoutBadge')}
- </button>
- <button
- type="button"
- data-layout-original
- disabled={interactionDisabled}
- onClick={() => setModelPickerLayout('original')}
- className={cn(
- 'shrink-0 whitespace-nowrap text-12 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-secondary)]',
- interactionDisabled && 'cursor-not-allowed opacity-50',
- )}
- >
- {t('newChat.modelSelector.unified.layoutOriginal')}
- </button>
+ // 已建会话(M6):同引擎行照旧走 onProviderChange 直切;跨引擎行在 selectRow
+ // 里就已经改道 sessionEngineFilter.onCrossEngineSelect,到不了这里。
+ // 「同模型不同配置的收藏」与「锚点只在真的应用后才记」两件事收在
+ // applyUnifiedSessionSelect 里(见其头注,M3 / M4)。
+ void applyUnifiedSessionSelect({
+ providerId,
+ wireModelId: id,
+ effort: rowEffortValue,
+ config: rowConfig,
+ });
+ }}
+ onSelectedFavoriteAnchorClear={(providerId, id, rowEffort, rowConfig) => {
+ // 用户在**同模型的普通模型行**上改了实时深度 / Fast:正在跑的配置已经不再等于那份
+ // 收藏副本(2026-08-17 review 第五轮 M2)。这里只清锚点 —— 模型 / 引擎一个字没变,
+ // 不是一次行选择,**刻意不收面板**(用户还在浮层里继续调)。
+ const rowEffortValue = rowEffort === '' ? undefined : rowEffort;
+ if (onUnifiedSelect) {
+ // 草稿:锚点由这条直通链路的 favoriteUid 承载(草稿层没有第二个清锚入口),
+ // 原样把当前 (来源, 模型, 引擎) 连同刚改完的深度 / Fast 重写一遍并置空 uid。
+ onUnifiedSelect({
+ providerId,
+ modelId: id,
+ ...(rowEffortValue ? { effort: rowEffortValue } : {}),
+ engine: rowConfig.engine,
+ fast: rowConfig.fast,
+ favoriteUid: null,
+ });
+ return;
+ }
+ onSessionFavoriteAnchorChange?.(null);
+ }}
+ {...(onEffortChange ? { onEffortChangeLive: onEffortChange } : {})}
+ {...(onFastModeChange ? { onFastModeChangeLive: onFastModeChange } : {})}
+ panelElement={paneElement}
+ {...(overlayContentClassName !== undefined
+ ? { overlayClassName: overlayContentClassName }
+ : {})}
+ />
+ {/* footer:「连接来源」(与既有面板同规则,device-link 远程隐藏)+ 右侧
+ 列表样式试用开关(本机偏好,见 modelPickerLayout;两种样式并存期的入口)。 */}
+ <div className="flex shrink-0 items-center justify-between gap-2 border-t border-[var(--model-dropdown-border)] px-3.5 py-[9px]">
+ {onNavigateToProviders && !deviceId ? (
+ <button
+ type="button"
+ disabled={interactionDisabled}
+ onClick={onNavigateToProviders}
+ className={cn(
+ 'flex min-w-0 items-center gap-1.5 text-13 text-[var(--text-secondary)]',
+ 'transition-colors hover:text-[var(--text-primary)]',
+ interactionDisabled && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ <Plus size={14} className="shrink-0" />
+ <span className="truncate">{t('newChat.modelSelector.source.connect')}</span>
+ </button>
+ ) : (
+ <span />
+ )}
+ {/* 右侧两个文字按钮(三档并存,Chris 2026-08-17):A/B 互切 + 切回老版。 */}
+ <div className="flex shrink-0 items-center gap-3">
+ <button
+ type="button"
+ data-layout-toggle
+ disabled={interactionDisabled}
+ onClick={() => setModelPickerLayout(pickerLayout === 'badge' ? 'classic' : 'badge')}
+ className={cn(
+ 'shrink-0 whitespace-nowrap text-12 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-secondary)]',
+ interactionDisabled && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ {pickerLayout === 'badge'
+ ? t('newChat.modelSelector.unified.layoutClassic')
+ : t('newChat.modelSelector.unified.layoutBadge')}
+ </button>
+ <button
+ type="button"
+ data-layout-original
+ disabled={interactionDisabled}
+ onClick={() => setModelPickerLayout('original')}
+ className={cn(
+ 'shrink-0 whitespace-nowrap text-12 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-secondary)]',
+ interactionDisabled && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ {t('newChat.modelSelector.unified.layoutOriginal')}
+ </button>
+ </div>
</div>
</div>
</div>
- </div>
);
}
@@ -2986,8 +3062,16 @@ function ModelSelectorContentView({
aria-label={providerDisplayName(sec.provider, t)}
>
{index > 0 && <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />}
- <div className="truncate px-3 pb-0.5 pt-1 text-11 font-medium text-[var(--text-tertiary)]">
- {providerDisplayName(sec.provider, t)}
+ <div className="flex min-w-0 items-center gap-2 px-3 pb-0.5 pt-1 text-11 font-medium text-[var(--text-tertiary)]">
+ <span className="min-w-0 truncate">{providerDisplayName(sec.provider, t)}</span>
+ {!deviceId && sec.provider.id === 'xd' && modelAccessAccountTier === 'free' && (
+ <span
+ data-testid="cindy-ai-model-group-free-tier-badge"
+ className="ml-auto inline-flex shrink-0 items-center rounded-full bg-[var(--surface-chip)] px-2 py-[1px] text-11 font-medium leading-[1.45] text-[var(--text-secondary)]"
+ >
+ {t('settings.providers.xd.accountTier.free')}
+ </span>
+ )}
</div>
<div className="flex flex-col gap-0.5">
{sec.models.map((m) => renderModelItem(sec.provider, m))}
@@ -3254,6 +3338,7 @@ export function ModelSelector({
const pi = useAgentCapabilities('pi', deviceId);
const gatewayPricing = useGatewayModelPricing();
const referencePricing = useReferenceModelPricing();
+ const { accountTier: modelAccessAccountTier } = useModelAccessStatus();
// trigger 的来源 icon / 当前模型也按来源取:device-link 用被控端供应商目录(否则控制端本地
// 查不到被控端独有模型 → currentModel undefined → label 退成 "Select model")。
const localProviders = useProviders();
@@ -3392,7 +3477,11 @@ export function ModelSelector({
currentAgentKind === 'pi' &&
!!triggerProvider &&
getModel(triggerProvider, modelId, currentAgentKind)?.thinkingToggle === true;
- const showEffort = !fallbackOption?.active && efforts.length > 0 && efforts.includes(effort) && !activeThinkingToggle;
+ const showEffort =
+ !fallbackOption?.active &&
+ efforts.length > 0 &&
+ efforts.includes(effort) &&
+ !activeThinkingToggle;
const fullEffortLabel = showEffort
? labelOf(effort)
: activeThinkingToggle && thinkingEnabled
@@ -3841,6 +3930,7 @@ export function ModelSelector({
interactionDisabled={switching || disabled}
gatewayPricing={gatewayPricing}
referencePricing={referencePricing}
+ modelAccessAccountTier={modelAccessAccountTier}
followSession={
fallbackOption
? {
@@ -3883,10 +3973,7 @@ export function ModelSelector({
}
return (
- <Popover
- open={open || keepOpenForAgentConfirmation}
- onOpenChange={handleOpenChange}
- >
+ <Popover open={open || keepOpenForAgentConfirmation} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
side={popoverSide}
diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx
index 6a540ed184..bf20611a06 100644
--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx
@@ -11,10 +11,7 @@ import {
import type { AgentKind } from '@/hooks/useAgentCapabilities';
import { cn } from '@/lib/utils';
-import {
- modelPriceDiscountLabelValues,
- type ModelPricePresentation,
-} from '@/lib/modelPriceFormat';
+import { modelPriceDiscountLabelValues, type ModelPricePresentation } from '@/lib/modelPriceFormat';
import type { Effort } from '@/lib/userPreferences.types';
import { getModelEngineOverride, useModelEnginePrefsVersion } from '@/state/modelEnginePrefs';
import { useModelPickerLayout } from '@/state/modelPickerLayout';
@@ -146,15 +143,16 @@ export interface UnifiedModelPanelProps {
/** agent 运行时是否具备 Fast 能力(useAgentCapabilities.hasFastMode)。 */
agentFastModeCapable: (agent: AgentKind) => boolean;
/** 价格 / 折扣查询。**modelId 传该引擎的 wire id**(报价表按 wire id 索引)。 */
- priceOf: (
- providerId: string,
- modelId: string,
- agent: AgentKind,
- ) => ModelPricePresentation | null;
+ priceOf: (providerId: string, modelId: string, agent: AgentKind) => ModelPricePresentation | null;
providerLabel: (providerId: string) => string;
effortLabelOf: (agent: AgentKind, effort: Effort) => string;
listMaxHeight?: number;
interactionDisabled?: boolean;
+ /** 保留付费模型为锁定展示行,并把点击交给统一付费提示。 */
+ includePaymentRequired?: boolean;
+ paymentRequiredLabel?: string;
+ paymentRequiredUnlockLabel?: string;
+ onPaymentRequired?: () => void;
/** false = 只选模型,不出配置浮层(设置类入口的 configurationEnabled)。 */
configurationEnabled?: boolean;
/**
@@ -293,6 +291,10 @@ export function UnifiedModelPanel({
effortLabelOf,
listMaxHeight,
interactionDisabled = false,
+ includePaymentRequired = false,
+ paymentRequiredLabel,
+ paymentRequiredUnlockLabel,
+ onPaymentRequired,
configurationEnabled = true,
sessionEngineFilter,
followSession,
@@ -382,6 +384,7 @@ export function UnifiedModelPanel({
predicatesRef.current.excludeProvider?.(provider, agent) ?? false,
excludeModel: (model, provider, agent) =>
predicatesRef.current.excludeModel?.(model, provider, agent) ?? false,
+ includePaymentRequired,
scope,
// 选中行豁免:会话正在用的那一条即便被停用或服务端下架,也必须留在列表里 ——
// 否则选择器一打开就是空选态,用户看不出自己在跑什么、也换不回来。豁免按 agent
@@ -389,7 +392,7 @@ export function UnifiedModelPanel({
...(keepModel ? { keepModel } : {}),
}),
// biome-ignore lint/correctness/useExhaustiveDependencies: 谓词经 ref 读取,刷新信号是 sourceVersion(见其注释);agents 以 agentsKey 表达身份;keepModel 以 keepModelKey 表达身份。
- [providers, agentsKey, scope, sourceVersion, keepModelKey],
+ [providers, agentsKey, scope, sourceVersion, keepModelKey, includePaymentRequired],
);
const railItems = useMemo(
@@ -690,7 +693,14 @@ export function UnifiedModelPanel({
flashScrollbar(el);
});
return () => cancelAnimationFrame(raf);
- }, [ensureSelectedVisible, sections, viewKey, selected.modelId, selected.providerId, selectedFavoriteUid]);
+ }, [
+ ensureSelectedVisible,
+ sections,
+ viewKey,
+ selected.modelId,
+ selected.providerId,
+ selectedFavoriteUid,
+ ]);
// morph 生长 / 窗口变化期间尺寸每变一次就复核一次对齐(仅在途标记置位时做事)。
useEffect(() => {
const el = listRef.current;
@@ -1072,219 +1082,219 @@ export function UnifiedModelPanel({
/>
)}
-
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
- {pickerLayout === 'badge' && stickyLabel && (
+ {pickerLayout === 'badge' && stickyLabel && (
+ <div
+ aria-hidden
+ // 复刻真组头的静止位形,接管瞬间与列表顶部的真组头逐像素重合;收尾照设计稿
+ // .sec:实底渐隐到透明,不画硬线 —— 行从渐变里柔和浮现,不被线拦腰切开。
+ // 高度与渐变止点全部由 BADGE_HEADER_* 派生(见其头注),不在这里另写字面量。
+ className="pointer-events-none absolute inset-x-0 top-0 z-[6] px-[18px] pt-3 text-11 leading-none text-[var(--text-tertiary)]"
+ style={{
+ height: BADGE_HEADER_TOTAL_PX,
+ background: `linear-gradient(180deg, var(--model-dropdown-bg) 0, var(--model-dropdown-bg) ${BADGE_HEADER_SOLID_PX}px, transparent)`,
+ // 顶出位移由滚动位置直接驱动(1:1),不加 transition —— 与滚动逐帧同步,
+ // 补间动画反而会让它滞后于手指。
+ transform: `translateY(${stickyLabel.offset}px)`,
+ }}
+ >
+ <div className="flex items-center gap-1.5">
+ {stickyLabel.providerId && (
+ <ProviderRailMark providerId={stickyLabel.providerId} providers={providers} />
+ )}
+ <span className="truncate">{stickyLabel.label}</span>
+ </div>
+ </div>
+ )}
<div
- aria-hidden
- // 复刻真组头的静止位形,接管瞬间与列表顶部的真组头逐像素重合;收尾照设计稿
- // .sec:实底渐隐到透明,不画硬线 —— 行从渐变里柔和浮现,不被线拦腰切开。
- // 高度与渐变止点全部由 BADGE_HEADER_* 派生(见其头注),不在这里另写字面量。
- className="pointer-events-none absolute inset-x-0 top-0 z-[6] px-[18px] pt-3 text-11 leading-none text-[var(--text-tertiary)]"
- style={{
- height: BADGE_HEADER_TOTAL_PX,
- background: `linear-gradient(180deg, var(--model-dropdown-bg) 0, var(--model-dropdown-bg) ${BADGE_HEADER_SOLID_PX}px, transparent)`,
- // 顶出位移由滚动位置直接驱动(1:1),不加 transition —— 与滚动逐帧同步,
- // 补间动画反而会让它滞后于手指。
- transform: `translateY(${stickyLabel.offset}px)`,
+ ref={listRef}
+ role="listbox"
+ aria-label={t('newChat.modelSelector.modelListAria')}
+ className={cn(
+ // 设计稿 .model-list:8px 内边距、行与行之间无额外间距(行自身 py 8 提供呼吸感)。
+ // 底部加宽到 12px:滚到底时最后一行不贴着面板底边/footer(Chris 2026-08-13:
+ // 「最底部稍微放宽一点高度」)。
+ 'morph-panel-list-scroll flex min-w-0 flex-1 flex-col overflow-y-auto overscroll-contain p-2 pb-3 [scrollbar-gutter:stable]',
+ // min-h-0 是能不能滚到底的关键:flex item 的默认 min-height:auto 会让它按内容
+ // 撑开、拒绝收缩,于是超出面板的部分被外层裁掉且**滚不到**(2026-08-13 实测:
+ // 列表翻不到最下面)。加上 min-h-0 后,面板高度受限时列表自己收缩并内部滚动,
+ // 底部的「连接来源」footer 是同级兄弟,始终留在列表下方、不盖住最后一行。
+ 'min-h-0',
+ )}
+ // 缺省上限只是「内容很少时别把面板撑太高」的软顶,真正的高度由外层面板给;
+ // 二者相加才既不过高、也不会在窄窗口里滚不到底。
+ style={{ maxHeight: `${listMaxHeight ?? 428}px` }}
+ onScroll={() => {
+ // 滚动不派发 pointerleave,浮层会跟着滚出视口的锚点行漂到菜单外 → 一滚就收起。
+ // 程序化的选中行对齐不算用户意图,由 suppressScrollDismissRef 放行一次。
+ if (suppressScrollDismissRef.current) {
+ suppressScrollDismissRef.current = false;
+ return;
+ }
+ // 用户亲手滚动 → 放弃在途的「保证选中行可见」,不跟用户抢滚动条。
+ needsEnsureVisibleRef.current = false;
+ if (flyAnchor) closeFlyout();
}}
+ onScrollCapture={pickerLayout === 'badge' ? updateStickyLabel : undefined}
>
- <div className="flex items-center gap-1.5">
- {stickyLabel.providerId && (
- <ProviderRailMark providerId={stickyLabel.providerId} providers={providers} />
- )}
- <span className="truncate">{stickyLabel.label}</span>
- </div>
- </div>
- )}
- <div
- ref={listRef}
- role="listbox"
- aria-label={t('newChat.modelSelector.modelListAria')}
- className={cn(
- // 设计稿 .model-list:8px 内边距、行与行之间无额外间距(行自身 py 8 提供呼吸感)。
- // 底部加宽到 12px:滚到底时最后一行不贴着面板底边/footer(Chris 2026-08-13:
- // 「最底部稍微放宽一点高度」)。
- 'morph-panel-list-scroll flex min-w-0 flex-1 flex-col overflow-y-auto overscroll-contain p-2 pb-3 [scrollbar-gutter:stable]',
- // min-h-0 是能不能滚到底的关键:flex item 的默认 min-height:auto 会让它按内容
- // 撑开、拒绝收缩,于是超出面板的部分被外层裁掉且**滚不到**(2026-08-13 实测:
- // 列表翻不到最下面)。加上 min-h-0 后,面板高度受限时列表自己收缩并内部滚动,
- // 底部的「连接来源」footer 是同级兄弟,始终留在列表下方、不盖住最后一行。
- 'min-h-0',
- )}
- // 缺省上限只是「内容很少时别把面板撑太高」的软顶,真正的高度由外层面板给;
- // 二者相加才既不过高、也不会在窄窗口里滚不到底。
- style={{ maxHeight: `${listMaxHeight ?? 428}px` }}
- onScroll={() => {
- // 滚动不派发 pointerleave,浮层会跟着滚出视口的锚点行漂到菜单外 → 一滚就收起。
- // 程序化的选中行对齐不算用户意图,由 suppressScrollDismissRef 放行一次。
- if (suppressScrollDismissRef.current) {
- suppressScrollDismissRef.current = false;
- return;
- }
- // 用户亲手滚动 → 放弃在途的「保证选中行可见」,不跟用户抢滚动条。
- needsEnsureVisibleRef.current = false;
- if (flyAnchor) closeFlyout();
- }}
- onScrollCapture={pickerLayout === 'badge' ? updateStickyLabel : undefined}
- >
- {/* 「跟随会话」行(opt-in,仅 scheduler heartbeat):置于最顶,不属于任何分组。 */}
- {followSession && (
- <>
- <button
- type="button"
- disabled={interactionDisabled}
- onClick={() => followSession.onFollow()}
- role="option"
- aria-selected={followSession.active}
- data-follow-session-row
- className={cn(
- 'flex w-full items-center justify-between rounded-[10px] px-2.5 py-2 transition-colors',
- 'hover:bg-[var(--model-item-hover)]',
- followSession.active && 'bg-[var(--model-item-hover)]',
- interactionDisabled && 'cursor-not-allowed opacity-50',
- )}
- >
- <span className="truncate text-13 font-medium text-[var(--model-item-text)]">
- {followSession.label}
- </span>
- {followSession.active && (
- <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
- )}
- </button>
- <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
- </>
- )}
- {/* 跨引擎视图的有损警示(规格 §1.6)—— 一行、可截断、不抢占列表高度。
+ {/* 「跟随会话」行(opt-in,仅 scheduler heartbeat):置于最顶,不属于任何分组。 */}
+ {followSession && (
+ <>
+ <button
+ type="button"
+ disabled={interactionDisabled}
+ onClick={() => followSession.onFollow()}
+ role="option"
+ aria-selected={followSession.active}
+ data-follow-session-row
+ className={cn(
+ 'flex w-full items-center justify-between rounded-[10px] px-2.5 py-2 transition-colors',
+ 'hover:bg-[var(--model-item-hover)]',
+ followSession.active && 'bg-[var(--model-item-hover)]',
+ interactionDisabled && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ <span className="truncate text-13 font-medium text-[var(--model-item-text)]">
+ {followSession.label}
+ </span>
+ {followSession.active && (
+ <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
+ )}
+ </button>
+ <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
+ </>
+ )}
+ {/* 跨引擎视图的有损警示(规格 §1.6)—— 一行、可截断、不抢占列表高度。
只在会话内**离开**同引擎视图时出现:同引擎轨的优先行是无损的,兼容行点下去
走确认事务,轨顶不常驻警示(避免每次打开喊狼)。badge 样式没有同引擎视图
(恒为「全部」),常驻警示同样是喊狼 —— 有损由选中时的确认事务把关。 */}
- {pickerLayout !== 'badge' && sessionEngineFilter && effectiveRail.kind !== 'engine' && (
- <div
- role="note"
- data-cross-engine-warning
- title={t('newChat.modelSelector.unified.crossEngineWarning')}
- className={cn(
- 'flex items-center gap-1.5 px-2.5 pb-1 pt-1.5 text-11 leading-[1.5] text-[var(--warning-fg)]',
- // 警示行**不参与撑宽**(Chris 2026-08-19:切到「全部」时面板又弹开一截)。
- // `truncate` 只管画的时候截断,`max-content` 布局(面板是 w-max)算的却是
- // 全文宽度 —— 这一行因此成了整块面板里最宽的内容。`w-0 min-w-full` 是经典
- // 手法:宽度基数取 0(对 max-content 贡献 0),再用 min-width:100% 在终局
- // 吃满已经定下来的可用宽,视觉上仍是整行。
- 'w-0 min-w-full',
- )}
- >
- <TriangleAlert size={12} className="shrink-0" />
- <span className="truncate">
- {t('newChat.modelSelector.unified.crossEngineWarning')}
- </span>
- </div>
- )}
- {!hasRows ? (
- <div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
- {/* ★ 视图的空态是引导语,不是「没有匹配」(设计稿 favEmpty;★ 常驻后必经)。 */}
- {effectiveRail.kind === 'favorites' && !query.trim()
- ? t('newChat.modelSelector.unified.favoritesEmpty')
- : t('newChat.modelSelector.search.noResults')}
- </div>
- ) : (
- sections.map((section) => (
+ {pickerLayout !== 'badge' && sessionEngineFilter && effectiveRail.kind !== 'engine' && (
<div
- key={section.key}
- role="group"
- aria-label={sectionLabel(section)}
- // badge 样式:组间距放在 section 容器上(组头自身上下衬对称),标签文字
- // 到上一组尾行与到本组首行的距离一致(Chris 2026-08-16:「上下高度对齐」)。
- className={cn(pickerLayout === 'badge' && 'mt-2 first:mt-0')}
+ role="note"
+ data-cross-engine-warning
+ title={t('newChat.modelSelector.unified.crossEngineWarning')}
+ className={cn(
+ 'flex items-center gap-1.5 px-2.5 pb-1 pt-1.5 text-11 leading-[1.5] text-[var(--warning-fg)]',
+ // 警示行**不参与撑宽**(Chris 2026-08-19:切到「全部」时面板又弹开一截)。
+ // `truncate` 只管画的时候截断,`max-content` 布局(面板是 w-max)算的却是
+ // 全文宽度 —— 这一行因此成了整块面板里最宽的内容。`w-0 min-w-full` 是经典
+ // 手法:宽度基数取 0(对 max-content 贡献 0),再用 min-width:100% 在终局
+ // 吃满已经定下来的可用宽,视觉上仍是整行。
+ 'w-0 min-w-full',
+ )}
>
- {/* 设计稿 .group-label:11.5px 常规字重、padding 8/10/4。
+ <TriangleAlert size={12} className="shrink-0" />
+ <span className="truncate">
+ {t('newChat.modelSelector.unified.crossEngineWarning')}
+ </span>
+ </div>
+ )}
+ {!hasRows ? (
+ <div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
+ {/* ★ 视图的空态是引导语,不是「没有匹配」(设计稿 favEmpty;★ 常驻后必经)。 */}
+ {effectiveRail.kind === 'favorites' && !query.trim()
+ ? t('newChat.modelSelector.unified.favoritesEmpty')
+ : t('newChat.modelSelector.search.noResults')}
+ </div>
+ ) : (
+ sections.map((section) => (
+ <div
+ key={section.key}
+ role="group"
+ aria-label={sectionLabel(section)}
+ // badge 样式:组间距放在 section 容器上(组头自身上下衬对称),标签文字
+ // 到上一组尾行与到本组首行的距离一致(Chris 2026-08-16:「上下高度对齐」)。
+ className={cn(pickerLayout === 'badge' && 'mt-2 first:mt-0')}
+ >
+ {/* 设计稿 .group-label:11.5px 常规字重、padding 8/10/4。
badge 样式的"滚动中组名常驻"不用 sticky(sticky 钉在滚动容器
padding 之下,上沿会漏出一条行 —— Chris 2026-08-16 实测),改由
列表视口顶部的覆盖层题头承载(见 stickyLabel),这里保持普通元素。
badge 样式的组头带供应商图标(快捷跳转栏拿掉后渠道归属落在这里)。 */}
- <div
- data-group-label={sectionLabel(section)}
- {...(section.group?.type === 'provider'
- ? { 'data-group-provider': section.group.providerId }
- : {})}
- className={cn(
- 'flex items-center gap-1.5 px-2.5 text-11 text-[var(--text-tertiary)]',
- // badge:上 4 下 12(配合列表 8px 上衬,顶部文字上下净空各约 13px,
- // 与滚动题头卡同一套位形);classic 保持既有 8/4 节奏。
- pickerLayout === 'badge' ? 'pb-3 pt-1 leading-none' : 'pb-1 pt-2',
- )}
- >
- {pickerLayout === 'badge' && section.group?.type === 'provider' && (
- <ProviderRailMark
- providerId={section.group.providerId}
- providers={providers}
- />
- )}
- <span className="truncate">{sectionLabel(section)}</span>
+ <div
+ data-group-label={sectionLabel(section)}
+ {...(section.group?.type === 'provider'
+ ? { 'data-group-provider': section.group.providerId }
+ : {})}
+ className={cn(
+ 'flex items-center gap-1.5 px-2.5 text-11 text-[var(--text-tertiary)]',
+ // badge:上 4 下 12(配合列表 8px 上衬,顶部文字上下净空各约 13px,
+ // 与滚动题头卡同一套位形);classic 保持既有 8/4 节奏。
+ pickerLayout === 'badge' ? 'pb-3 pt-1 leading-none' : 'pb-1 pt-2',
+ )}
+ >
+ {pickerLayout === 'badge' && section.group?.type === 'provider' && (
+ <ProviderRailMark providerId={section.group.providerId} providers={providers} />
+ )}
+ <span className="truncate">{sectionLabel(section)}</span>
+ </div>
+ {section.rows.map((row) => {
+ const config = configOf(row.entry, row.favorite);
+ const key = anchorKey(row.anchor);
+ const { priceDisplay, subscriptionRow } = priceDisplayOf(row.entry, config);
+ return (
+ <UnifiedModelRow
+ key={key}
+ entry={row.entry}
+ anchor={row.anchor}
+ config={config}
+ selected={isSelectedRow(row.anchor, row.entry)}
+ active={sameAnchor(flyAnchor, row.anchor)}
+ isFavoriteRow={!!row.favorite}
+ justFavorited={justFavorited === key}
+ {...(priceDisplay ? { priceDisplay } : {})}
+ {...(subscriptionRow
+ ? { subscriptionLabel: t('settings.providers.models.subscription') }
+ : {})}
+ interactionDisabled={interactionDisabled}
+ paymentRequired={row.entry.availability === 'requires_payment'}
+ {...(paymentRequiredLabel ? { paymentRequiredLabel } : {})}
+ {...(paymentRequiredUnlockLabel ? { paymentRequiredUnlockLabel } : {})}
+ {...(onPaymentRequired ? { onPaymentRequired } : {})}
+ effortLabelOf={effortLabelOf}
+ providers={providers}
+ layout={pickerLayout}
+ // badge 样式:右缘来源字签(providerLabel 既有结果);行首徽标点按
+ // 在候选引擎间快切 —— 与浮层引擎胶囊走**同一条 applyEngine 链路**
+ // (选中行的草稿回写 / 会话跨引擎确认语义因此完全一致)。收藏行不给
+ // 快切(☆ 是配置副本,徽标只作标识,改引擎去浮层改那条收藏)。
+ {...(pickerLayout === 'badge'
+ ? {
+ channelLabel: providerLabel(row.entry.providerId),
+ ...(configurationEnabled &&
+ !row.favorite &&
+ row.entry.candidates.length > 1
+ ? {
+ onEngineCycle: () => {
+ const engines = row.entry.candidates.map(engineOfAgentKind);
+ const next =
+ engines[
+ (engines.indexOf(config.engine) + 1) % engines.length
+ ];
+ if (next) applyEngine(row.anchor, row.entry, config, next);
+ },
+ }
+ : {}),
+ }
+ : {})}
+ onReveal={revealFlyout}
+ onRevealForKeyboard={revealFlyoutForKeyboard}
+ onLeave={scheduleCloseFromRow}
+ onBlurAway={handleRowBlurAway}
+ onSelect={() => selectRow(row.anchor, config, row.favorite)}
+ onStar={() =>
+ row.favorite
+ ? removeFavorite(row.anchor, row.entry)
+ : addFavorite(row.anchor, config)
+ }
+ />
+ );
+ })}
</div>
- {section.rows.map((row) => {
- const config = configOf(row.entry, row.favorite);
- const key = anchorKey(row.anchor);
- const { priceDisplay, subscriptionRow } = priceDisplayOf(row.entry, config);
- return (
- <UnifiedModelRow
- key={key}
- entry={row.entry}
- anchor={row.anchor}
- config={config}
- selected={isSelectedRow(row.anchor, row.entry)}
- active={sameAnchor(flyAnchor, row.anchor)}
- isFavoriteRow={!!row.favorite}
- justFavorited={justFavorited === key}
- {...(priceDisplay ? { priceDisplay } : {})}
- {...(subscriptionRow
- ? { subscriptionLabel: t('settings.providers.models.subscription') }
- : {})}
- interactionDisabled={interactionDisabled}
- effortLabelOf={effortLabelOf}
- providers={providers}
- layout={pickerLayout}
- // badge 样式:右缘来源字签(providerLabel 既有结果);行首徽标点按
- // 在候选引擎间快切 —— 与浮层引擎胶囊走**同一条 applyEngine 链路**
- // (选中行的草稿回写 / 会话跨引擎确认语义因此完全一致)。收藏行不给
- // 快切(☆ 是配置副本,徽标只作标识,改引擎去浮层改那条收藏)。
- {...(pickerLayout === 'badge'
- ? {
- channelLabel: providerLabel(row.entry.providerId),
- ...(configurationEnabled &&
- !row.favorite &&
- row.entry.candidates.length > 1
- ? {
- onEngineCycle: () => {
- const engines = row.entry.candidates.map(engineOfAgentKind);
- const next =
- engines[
- (engines.indexOf(config.engine) + 1) % engines.length
- ];
- if (next) applyEngine(row.anchor, row.entry, config, next);
- },
- }
- : {}),
- }
- : {})}
- onReveal={revealFlyout}
- onRevealForKeyboard={revealFlyoutForKeyboard}
- onLeave={scheduleCloseFromRow}
- onBlurAway={handleRowBlurAway}
- onSelect={() => selectRow(row.anchor, config, row.favorite)}
- onStar={() =>
- row.favorite
- ? removeFavorite(row.anchor, row.entry)
- : addFavorite(row.anchor, config)
- }
- />
- );
- })}
- </div>
- ))
- )}
- </div>
- {/* 定宽 sizer(见 widthSizerSections 的说明):不可见、零高度、不进 listbox,
+ ))
+ )}
+ </div>
+ {/* 定宽 sizer(见 widthSizerSections 的说明):不可见、零高度、不进 listbox,
只为让 `w-max` 从第一帧起就按**最宽视图**(rail=all + 空搜索)量宽。
行复用 `<UnifiedModelRow>` 以求零漂移:handler 全 noop、selected=false
(不带 data-model-selected,自动对齐永远不会挑中它)、interactionDisabled。
@@ -1292,53 +1302,56 @@ export function UnifiedModelPanel({
**纵向 padding 一点不能带**(2026-08-19 预审 P1-2):border-box 下 h-0 只把内容盒
钳到 0,纵向 padding 仍占真实高度 —— 带上真列表的 p-2 pb-3 会让 sizer 占 20px,
把「切视图宽度抖」换成「切视图高度抖」。纵向本来就与量宽无关。 */}
- {widthSizerActive && (
- <div
- aria-hidden
- role="presentation"
- data-width-sizer
- className="invisible h-0 overflow-hidden px-2 [scrollbar-gutter:stable]"
- >
- {widthSizerSections.map((section) => (
- <div key={section.key}>
- {/* 组头也要量:供应商名可能比它组里最长的行还宽。 */}
- <div className="flex items-center gap-1.5 px-2.5 pb-1 pt-2 text-11">
- <span className="truncate">{sectionLabel(section)}</span>
+ {widthSizerActive && (
+ <div
+ aria-hidden
+ role="presentation"
+ data-width-sizer
+ className="invisible h-0 overflow-hidden px-2 [scrollbar-gutter:stable]"
+ >
+ {widthSizerSections.map((section) => (
+ <div key={section.key}>
+ {/* 组头也要量:供应商名可能比它组里最长的行还宽。 */}
+ <div className="flex items-center gap-1.5 px-2.5 pb-1 pt-2 text-11">
+ <span className="truncate">{sectionLabel(section)}</span>
+ </div>
+ {section.rows.map((row) => {
+ const config = configOf(row.entry, row.favorite, RAIL_ALL);
+ const { priceDisplay, subscriptionRow } = priceDisplayOf(row.entry, config);
+ return (
+ <UnifiedModelRow
+ key={anchorKey(row.anchor)}
+ entry={row.entry}
+ anchor={row.anchor}
+ config={config}
+ selected={false}
+ active={false}
+ isFavoriteRow={!!row.favorite}
+ justFavorited={false}
+ {...(priceDisplay ? { priceDisplay } : {})}
+ {...(subscriptionRow
+ ? { subscriptionLabel: t('settings.providers.models.subscription') }
+ : {})}
+ interactionDisabled
+ paymentRequired={row.entry.availability === 'requires_payment'}
+ {...(paymentRequiredLabel ? { paymentRequiredLabel } : {})}
+ {...(paymentRequiredUnlockLabel ? { paymentRequiredUnlockLabel } : {})}
+ effortLabelOf={effortLabelOf}
+ providers={providers}
+ layout={pickerLayout}
+ onReveal={noop}
+ onRevealForKeyboard={noop}
+ onLeave={noop}
+ onBlurAway={noop}
+ onSelect={noop}
+ onStar={noop}
+ />
+ );
+ })}
</div>
- {section.rows.map((row) => {
- const config = configOf(row.entry, row.favorite, RAIL_ALL);
- const { priceDisplay, subscriptionRow } = priceDisplayOf(row.entry, config);
- return (
- <UnifiedModelRow
- key={anchorKey(row.anchor)}
- entry={row.entry}
- anchor={row.anchor}
- config={config}
- selected={false}
- active={false}
- isFavoriteRow={!!row.favorite}
- justFavorited={false}
- {...(priceDisplay ? { priceDisplay } : {})}
- {...(subscriptionRow
- ? { subscriptionLabel: t('settings.providers.models.subscription') }
- : {})}
- interactionDisabled
- effortLabelOf={effortLabelOf}
- providers={providers}
- layout={pickerLayout}
- onReveal={noop}
- onRevealForKeyboard={noop}
- onLeave={noop}
- onBlurAway={noop}
- onSelect={noop}
- onStar={noop}
- />
- );
- })}
- </div>
- ))}
- </div>
- )}
+ ))}
+ </div>
+ )}
</div>
{flyTarget && configurationEnabled && (
@@ -1376,14 +1389,14 @@ export function UnifiedModelPanel({
effortLabelOf={effortLabelOf}
justFavorited={justFavorited === anchorKey(target.anchor)}
disabled={interactionDisabled}
- onEngineChange={(engine) => applyEngine(target.anchor, target.entry, config, engine)}
+ onEngineChange={(engine) =>
+ applyEngine(target.anchor, target.entry, config, engine)
+ }
onEffortChange={(effort) =>
applyEffort(target.anchor, target.entry, config, effort)
}
onFastChange={(enabled) => applyFast(target.anchor, target.entry, config, enabled)}
- onResetToRecommended={() =>
- resetToRecommended(target.anchor, target.entry, config)
- }
+ onResetToRecommended={() => resetToRecommended(target.anchor, target.entry, config)}
onAddFavorite={() => addFavorite(target.anchor, config)}
onRemoveFavorite={() => removeFavorite(target.anchor, target.entry)}
/>
diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx
index 6b302b2bb2..b39e04900b 100644
--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx
@@ -1,4 +1,4 @@
-import { Star, Zap } from 'lucide-react';
+import { Lock, Star, Zap } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type {
FocusEvent as ReactFocusEvent,
@@ -187,6 +187,10 @@ export function UnifiedModelRow({
layout = 'classic',
channelLabel,
onEngineCycle,
+ paymentRequired = false,
+ paymentRequiredLabel,
+ paymentRequiredUnlockLabel,
+ onPaymentRequired,
}: {
entry: UnifiedModelEntry;
anchor: UnifiedAnchor;
@@ -226,34 +230,63 @@ export function UnifiedModelRow({
channelLabel?: string;
/** badge 样式行首徽标点按 = 切到下一个候选引擎;单候选行不传(徽标不可点)。 */
onEngineCycle?: () => void;
+ /** 付费锁定行保留在原位置,可聚焦但不能选中、收藏或打开配置。 */
+ paymentRequired?: boolean;
+ paymentRequiredLabel?: string;
+ paymentRequiredUnlockLabel?: string;
+ onPaymentRequired?: () => void;
}) {
const { t } = useTranslation();
const provider = providers.find((item) => item.id === entry.providerId);
const priceSymbol = priceDisplay?.symbol ?? '$';
const engineOption = agentOptionOf(config.engine);
- const reveal = (event: ReactPointerEvent<HTMLDivElement>) => onReveal(anchor, event.currentTarget);
+ const reveal = (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (!paymentRequired) onReveal(anchor, event.currentTarget);
+ };
const tripleTitle = `${engineOption.label}${
config.effort ? ` · ${effortLabelOf(config.agent, config.effort)}` : ''
}${config.fast ? ' · Fast' : ''}`;
+ const paymentRequiredActionLabel = paymentRequired
+ ? [entry.displayName, paymentRequiredUnlockLabel ?? paymentRequiredLabel]
+ .filter(Boolean)
+ .join(' · ')
+ : undefined;
// 行根节点的交互与语义两种样式完全一致(选中/浮层/键盘),只有布局不同 —— 抽成
// 共享 props,badge 分支不复制一遍手写事件导致行为漂移。
const rowRootProps = {
role: 'option' as const,
'aria-selected': selected,
+ // 付费行不能被选为模型,但它本身是“查看付费说明”的可执行入口;只有真正
+ // 阻断全部交互的状态才声明 disabled,避免读屏软件抑制 Enter / Space 激活。
+ 'aria-disabled': interactionDisabled ? true : undefined,
+ 'aria-label': paymentRequiredActionLabel,
// ← 开配置浮层是这一行唯一的键盘入口,不声明就只有摸索得到(读屏用户尤甚)。
- 'aria-keyshortcuts': 'ArrowLeft',
+ 'aria-keyshortcuts': paymentRequired ? undefined : 'ArrowLeft',
tabIndex: interactionDisabled ? -1 : 0,
'data-model-selected': selected ? ('true' as const) : undefined,
'data-unified-anchor': anchorKey(anchor),
onPointerEnter: reveal,
onPointerMove: reveal,
onPointerLeave: onLeave,
- onFocus: (event: ReactFocusEvent<HTMLDivElement>) => onReveal(anchor, event.currentTarget),
+ onFocus: (event: ReactFocusEvent<HTMLDivElement>) => {
+ if (!paymentRequired) onReveal(anchor, event.currentTarget);
+ },
onBlur: (event: ReactFocusEvent<HTMLDivElement>) => onBlurAway(event.relatedTarget),
- onClick: onSelect,
+ onClick: () => {
+ if (interactionDisabled) return;
+ if (paymentRequired) onPaymentRequired?.();
+ else onSelect();
+ },
onKeyDown: (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.target !== event.currentTarget || interactionDisabled) return;
+ if (paymentRequired) {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onPaymentRequired?.();
+ }
+ return;
+ }
if (event.key === 'ArrowLeft') {
event.preventDefault();
onRevealForKeyboard(anchor, event.currentTarget);
@@ -268,7 +301,7 @@ export function UnifiedModelRow({
const starButton = (
<button
type="button"
- disabled={interactionDisabled}
+ disabled={interactionDisabled || paymentRequired}
onClick={(event) => {
event.stopPropagation();
onStar();
@@ -293,6 +326,25 @@ export function UnifiedModelRow({
<Star size={14} fill={isFavoriteRow || justFavorited ? 'currentColor' : 'none'} />
</button>
);
+ const paymentRequiredBadge =
+ paymentRequired && paymentRequiredLabel ? (
+ <span
+ data-payment-required-badge
+ className="inline-flex shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 py-[1px] text-10 font-normal leading-[1.45] text-[var(--text-secondary)]"
+ >
+ <Lock size={10} />
+ {paymentRequiredLabel}
+ </span>
+ ) : null;
+ const paymentRequiredUnlock =
+ paymentRequired && paymentRequiredUnlockLabel ? (
+ <span
+ data-payment-required-unlock
+ className="invisible shrink-0 select-none text-11 font-medium text-[var(--text-secondary)] group-hover/row:visible group-focus-within/row:visible"
+ >
+ {paymentRequiredUnlockLabel}
+ </span>
+ ) : null;
if (layout === 'badge') {
const tint = ENGINE_BADGE_TINT[config.engine];
@@ -320,12 +372,12 @@ export function UnifiedModelRow({
'group/row flex h-[38px] w-full cursor-pointer items-center gap-2 rounded-[10px] px-2.5 transition-colors duration-100',
'hover:bg-[var(--model-item-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
(selected || active) && 'bg-[var(--model-item-hover)]',
- interactionDisabled && 'cursor-not-allowed opacity-50',
+ (interactionDisabled || paymentRequired) && 'cursor-not-allowed opacity-50',
)}
>
{/* 引擎徽标 = 本样式唯一的图标系统:官方 mark + 品牌色底。可点时在候选引擎间
快切(与浮层引擎胶囊同一条 applyEngine 链路,语义一致);单候选行只作标识。 */}
- {onEngineCycle && !interactionDisabled ? (
+ {onEngineCycle && !interactionDisabled && !paymentRequired ? (
<button
type="button"
data-engine-badge={config.engine}
@@ -351,7 +403,9 @@ export function UnifiedModelRow({
</span>
)}
<span
- title={entry.description ? `${entry.displayName} — ${entry.description}` : entry.displayName}
+ title={
+ entry.description ? `${entry.displayName} — ${entry.description}` : entry.displayName
+ }
className="min-w-0 truncate text-14 font-medium leading-5 text-[var(--model-item-text)]"
>
{entry.displayName}
@@ -391,6 +445,7 @@ export function UnifiedModelRow({
引擎不再进右簇 —— 行首徽标已承载。 */}
<span
title={tripleTitle}
+ data-model-row-meta
// 外侧簇颜色恒定(Chris 2026-08-16 实测:调过思考深度后行右侧不该变色;
// 「已自定义」的信号由浮层底栏承载,不再用行内提亮表达)。
className="ml-auto flex shrink-0 items-center gap-2 text-12 text-[var(--text-tertiary)]"
@@ -404,6 +459,8 @@ export function UnifiedModelRow({
/>
)}
{config.effort && <span>{effortLabelOf(config.agent, config.effort)}</span>}
+ {paymentRequiredUnlock}
+ {paymentRequiredBadge}
{channelLabel && (
<span
data-channel-tag
@@ -424,7 +481,7 @@ export function UnifiedModelRow({
'group/row flex w-full cursor-pointer flex-col rounded-[10px] px-2.5 py-2 transition-colors duration-100',
'hover:bg-[var(--model-item-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
(selected || active) && 'bg-[var(--model-item-hover)]',
- interactionDisabled && 'cursor-not-allowed opacity-50',
+ (interactionDisabled || paymentRequired) && 'cursor-not-allowed opacity-50',
)}
>
<div className="flex items-center gap-2">
@@ -485,22 +542,28 @@ export function UnifiedModelRow({
{starButton}
{/* 常驻三元组:引擎图标 + 推理强度 + ⚡。所有行同构,自定义行整组提亮一档。
设计稿 .l1-right:margin-left auto 把右侧簇推到最右,左侧簇贴名字排。 */}
- <span
- title={tripleTitle}
- data-unified-triple
- // 颜色恒定,不随「已自定义」提亮(Chris 2026-08-16 裁决,同 badge 样式)。
- className="ml-auto flex max-w-[118px] shrink-0 items-center gap-1 truncate text-12 text-[var(--text-tertiary)]"
- >
- <engineOption.Mark size={12} className="shrink-0" />
- {config.effort && <span className="truncate">{effortLabelOf(config.agent, config.effort)}</span>}
- {config.fast && (
- <Zap
- size={11}
- fill="currentColor"
- className="shrink-0"
- aria-label={t('newChat.modelSelector.meta.fastBadge')}
- />
- )}
+ <span data-model-row-meta className="ml-auto flex shrink-0 items-center gap-2">
+ <span
+ title={tripleTitle}
+ data-unified-triple
+ // 颜色恒定,不随「已自定义」提亮(Chris 2026-08-16 裁决,同 badge 样式)。
+ className="flex max-w-[118px] shrink-0 items-center gap-1 truncate text-12 text-[var(--text-tertiary)]"
+ >
+ <engineOption.Mark size={12} className="shrink-0" />
+ {config.effort && (
+ <span className="truncate">{effortLabelOf(config.agent, config.effort)}</span>
+ )}
+ {config.fast && (
+ <Zap
+ size={11}
+ fill="currentColor"
+ className="shrink-0"
+ aria-label={t('newChat.modelSelector.meta.fastBadge')}
+ />
+ )}
+ </span>
+ {paymentRequiredUnlock}
+ {paymentRequiredBadge}
</span>
{/* 行尾不放 ✅(Chris 2026-08-13 裁决:选中已有整行底色,再加勾是重复信号,
还平白吃掉一列宽度);选中态语义由 aria-selected 承载。 */}
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index d7eb5aeedf..daa453bd60 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -309,6 +309,7 @@ function RowIconButton({
function DetailHeader({
icon,
title,
+ modelCountSuffix,
subtitle,
trailing,
provider,
@@ -320,6 +321,8 @@ function DetailHeader({
}: {
icon: ReactNode;
title: string;
+ /** 紧跟模型数量的供应商专属元数据。 */
+ modelCountSuffix?: ReactNode;
subtitle: string;
trailing: ReactNode;
provider?: ProviderView;
@@ -389,6 +392,7 @@ function DetailHeader({
{title}
</span>
{modelCount !== null && <ModelCountChip count={modelCount} />}
+ {modelCountSuffix}
{subscriptionProduct && (
<CustomTag
label={t('settings.providers.models.subscriptionProduct', {
@@ -1396,16 +1400,13 @@ function XdGatewayHeader({
const assetModule =
assetState.kind === 'hidden' ? undefined : (
<div
- className={cn(
- 'flex flex-wrap justify-between gap-x-6 gap-y-4 border-t px-5 py-5',
- assetState.kind === 'fault' ? 'items-center gap-y-3' : 'items-start',
- )}
+ data-testid="cindy-ai-asset-module"
+ className="flex flex-wrap items-end justify-between gap-x-6 gap-y-4 border-t px-5 py-4"
style={{ borderColor: 'var(--settings-theme-card-border)' }}
>
{assetState.kind === 'fault' ? (
<>
- {/* 「本该有、这次拿不到」——讲清发生了什么 + 下一步,并就地给恢复入口
- (DESIGN「Errors = what happened + what to do」)。 */}
+ {/* 「本该有、这次拿不到」——讲清发生了什么 + 下一步,并就地给恢复入口。 */}
<p
className="max-w-[400px] text-13 leading-relaxed"
style={{ color: 'var(--text-secondary)' }}
@@ -1416,7 +1417,7 @@ function XdGatewayHeader({
</>
) : (
<>
- <div className="min-w-0">
+ <div className="min-w-[120px]">
<p className="text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>
{t('billing.balance.title')}
</p>
@@ -1432,16 +1433,12 @@ function XdGatewayHeader({
)}
</p>
</div>
- {/* pt 与金额基线光学对齐(标签 12px + 6px 间距的一半)。 */}
- <div className="flex shrink-0 items-center gap-4 pt-3.5">
- <button
- type="button"
+ {/* 余额充值是主动作;查看用量为同区块内的次动作。 */}
+ <div className="flex shrink-0 items-center gap-3">
+ <PillButton
+ label={t('settings.providers.xd.asset.viewUsage')}
onClick={() => goToBilling()}
- className="text-13 transition-colors hover:text-[var(--text-primary)]"
- style={{ color: 'var(--text-secondary)' }}
- >
- {t('settings.providers.xd.asset.viewUsage')}
- </button>
+ />
<CtaPillButton
label={t('billing.settings.topupCard.action')}
onClick={() => goToBilling('topup')}
@@ -1456,6 +1453,16 @@ function XdGatewayHeader({
<DetailHeader
icon={<XDIncMark size={18} />}
title={t('settings.providers.xd.title')}
+ modelCountSuffix={
+ syncStatus.accountTier === 'free' ? (
+ <span
+ data-testid="cindy-ai-free-tier-badge"
+ className="inline-flex shrink-0 items-center rounded-full bg-[var(--surface-chip)] px-2 py-[1px] text-11 font-medium leading-[1.45] text-[var(--text-secondary)]"
+ >
+ {t('settings.providers.xd.accountTier.free')}
+ </span>
+ ) : undefined
+ }
subtitle={providerSubtitleForDisplay(provider, t('settings.providers.xd.modelLabel'), {
suffix: t('settings.providers.xd.billingLabel'),
fallback: t('settings.providers.xd.subtitle'),
diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
index c8444c07e9..6432386167 100644
--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
@@ -27,7 +27,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { ChevronDown, MoreHorizontal, RefreshCw, Search } from 'lucide-react';
+import { ChevronDown, Lock, MoreHorizontal, RefreshCw, Search } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
@@ -168,7 +168,12 @@ export function buildUnionRows(provider: ProviderView): UnionModelRow[] {
existing.avail.push(agent);
}
} else {
- const row: UnionModelRow = { id: key, name: m.name, byAgent: { [agent]: m }, avail: [agent] };
+ const row: UnionModelRow = {
+ id: key,
+ name: m.name,
+ byAgent: { [agent]: m },
+ avail: [agent],
+ };
byKey.set(key, row);
rows.push(row);
}
@@ -192,6 +197,7 @@ export function buildUnionRows(provider: ProviderView): UnionModelRow[] {
id: string;
name: string;
disabled?: boolean;
+ availability?: CatalogModel['availability'];
group: 'image' | 'video' | 'embedding';
}> = [
...(provider.imageModels ?? []).map((m) => ({ ...m, group: 'image' as const })),
@@ -208,6 +214,7 @@ export function buildUnionRows(provider: ProviderView): UnionModelRow[] {
defaultEffort: null,
group: m.group,
...(m.disabled === true ? { disabled: true } : {}),
+ ...(m.availability !== undefined ? { availability: m.availability } : {}),
};
const row: UnionModelRow = {
id: m.id,
@@ -232,6 +239,18 @@ export function isRowDisabled(row: UnionModelRow): boolean {
return row.avail.some((a) => row.byAgent[a]?.disabled === true);
}
+export function isRowPaymentRequired(row: UnionModelRow): boolean {
+ return row.avail.some((agent) => row.byAgent[agent]?.availability === 'requires_payment');
+}
+
+/** 付费锁定优先于本地停用偏好:命中时任何批量恢复都不得改写该行的历史 override。 */
+export function hasPaymentRequiredDisabledRow(
+ rows: readonly UnionModelRow[],
+ isDisabled: (row: UnionModelRow) => boolean = isRowDisabled,
+): boolean {
+ return rows.some((row) => isDisabled(row) && isRowPaymentRequired(row));
+}
+
/** 该行是否是「能力模型」(图像/音频/视频/向量等,没有显示轴;见头注)。
* `userProvider` = 行来自用户自定义供应商 —— 自定义对话模型的未知 group 不吃 id
* 启发式(`gpt-4o-audio-preview` 是合法对话模型,见 isAgentSelectableModel 注释)。 */
@@ -254,7 +273,8 @@ export function getHiddenAgents(providerId: string, row: UnionModelRow): AgentKi
/**
* 每个 Agent 各自的模型显示数;UI 必须保留 Agent 维度,不能汇总成模型条目总数。
- * 口径 = 对话模型(能力模型没有显示轴)且未停用(停用行不可显示,不计入分母)。
+ * 口径 = 对话模型(能力模型没有显示轴)且未停用、非付费锁定行。付费锁定行与停用行
+ * 都不可写显示偏好,不计入批量开关分母,与 handleBulk targets 保持同一口径。
* `isDisabled` 允许调用方注入停用判定(组件里 = 快照标志叠加 pendingDisabled 乐观
* 覆盖,否则乐观窗口内「全部显示/隐藏」的方向与分母陈旧,PR #744 review);缺省读
* 快照的 model.disabled。
@@ -272,6 +292,7 @@ export function countModelsByAgent(
const models = (provider.models[agent] ?? []).filter(
(model) =>
isAgentSelectableModel(model, { userProvider: provider.source === 'user' }) &&
+ model.availability !== 'requires_payment' &&
!isDisabled(agent, model),
);
return {
@@ -381,6 +402,10 @@ export function UnifiedModelList({
(row: UnionModelRow) => pendingDisabled[row.id] ?? isRowDisabled(row),
[pendingDisabled],
);
+ const hasLockedDisabledRow = useMemo(
+ () => hasPaymentRequiredDisabledRow(unionRows, rowDisabledEffective),
+ [unionRows, rowDisabledEffective],
+ );
/** 写停用轴:乐观覆盖 + IPC;失败回滚并提示(错误 = 发生了什么 + 下一步)。 */
const setRowDisabled = useCallback(
@@ -435,6 +460,9 @@ export function UnifiedModelList({
* 清不掉;若该模型日后回到目录会被静默停用)。乐观覆盖同 setRowDisabled 口径;
* 失败整组回滚(只回滚仍属于本次的乐观值)。 */
const resetDisableOverrides = useCallback(() => {
+ // `kind:'reset'` 会删除整组 override,无法排除付费锁定行;保持 fail-closed,
+ // 让其它非锁定行继续使用逐行恢复入口。
+ if (hasLockedDisabledRow) return;
const rows = unionRows.filter((r) => pendingDisabled[r.id] ?? isRowDisabled(r));
setPendingDisabled((prev) => {
const next = { ...prev };
@@ -453,7 +481,7 @@ export function UnifiedModelList({
});
toast.error(t('settings.providers.models.accessWriteFailed'));
});
- }, [unionRows, pendingDisabled, provider.id, t]);
+ }, [hasLockedDisabledRow, unionRows, pendingDisabled, provider.id, t]);
// 分组(仅未停用的行)+「已停用」分区(停用的行,跨分组沉底)。搜索两边都过滤。
// 分组沿用现有口径:用每行第一个可用 agent 的目录条目作代表参与分组。
@@ -475,9 +503,7 @@ export function UnifiedModelList({
return {
groups: groupModelsForDisplay(reps).map((g) => ({
category: g.category,
- rows: g.models
- .map((m) => repByRow.get(m.id))
- .filter((r): r is UnionModelRow => !!r),
+ rows: g.models.map((m) => repByRow.get(m.id)).filter((r): r is UnionModelRow => !!r),
})),
disabledRows: disabled,
};
@@ -499,7 +525,8 @@ export function UnifiedModelList({
[provider, visibilityVersion, pendingDisabled],
);
const totalModelsAcrossAgents = agentCounts.reduce((sum, count) => sum + count.total, 0);
- const allOn = totalModelsAcrossAgents > 0 && agentCounts.every((count) => count.on === count.total);
+ const allOn =
+ totalModelsAcrossAgents > 0 && agentCounts.every((count) => count.on === count.total);
const refreshLabel = refreshing
? t('settings.providers.models.refreshingAria')
: (refreshIdleLabel ?? t('settings.providers.models.refreshAria'));
@@ -534,6 +561,7 @@ export function UnifiedModelList({
.filter(
(m) =>
isAgentSelectableModel(m, { userProvider: provider.source === 'user' }) &&
+ m.availability !== 'requires_payment' &&
(pendingDisabled[canonicalModelKey(provider, agent, m.id)] ?? m.disabled === true) !==
true,
)
@@ -551,6 +579,7 @@ export function UnifiedModelList({
<button
type="button"
aria-label={t('settings.providers.detail.moreActionsAria')}
+ disabled={isRowPaymentRequired(row)}
className={cn(
'flex h-6 w-6 shrink-0 items-center justify-center rounded-full opacity-0 transition-opacity',
'hover:bg-[var(--surface-hover)] focus-visible:opacity-100 group-hover:opacity-100 data-[state=open]:opacity-100',
@@ -561,12 +590,11 @@ export function UnifiedModelList({
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- {provider.id !== 'xd' &&
- !isCapabilityRow(row, provider.source === 'user') && (
- <DropdownMenuItem onClick={() => setPriceRow(row)}>
- {t('settings.providers.models.priceOverride.menu')}
- </DropdownMenuItem>
- )}
+ {provider.id !== 'xd' && !isCapabilityRow(row, provider.source === 'user') && (
+ <DropdownMenuItem onClick={() => setPriceRow(row)}>
+ {t('settings.providers.models.priceOverride.menu')}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={() => setRowDisabled(row, true)}>
{t('settings.providers.models.disableModel')}
</DropdownMenuItem>
@@ -593,68 +621,81 @@ export function UnifiedModelList({
本机 Ollama 空列表不渲染工具行:没有可显示的模型时,「在模型选择中显示」
没有对象,空间留给下方推荐。 */}
{!compactEmpty && (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-5 py-2.5">
- <span className="shrink-0 text-13 font-medium" style={{ color: 'var(--text-secondary)' }}>
- {t('settings.providers.models.available')}
- </span>
- <span className="min-w-0 flex-1" />
- {showSearch && (
- /* basis 200px 但允许收缩:窄窗口(右栏可被压到 ~270px)时先压缩搜索框,
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-5 py-2.5">
+ <span className="shrink-0 text-13 font-medium" style={{ color: 'var(--text-secondary)' }}>
+ {t('settings.providers.models.available')}
+ </span>
+ <span className="min-w-0 flex-1" />
+ {showSearch && (
+ /* basis 200px 但允许收缩:窄窗口(右栏可被压到 ~270px)时先压缩搜索框,
不让右侧操作被 overflow-hidden 裁掉(PR #1102 review)。 */
- <div
- className="flex h-8 min-w-0 basis-[200px] items-center gap-2 rounded-full px-3"
- style={{ backgroundColor: 'var(--surface-elevated)', border: '1px solid var(--border-default)' }}
- >
- <Search size={14} className="shrink-0" style={{ color: 'var(--text-tertiary)' }} />
- <input
- type="text"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={t('settings.providers.models.search')}
- aria-label={t('settings.providers.models.search')}
- className="min-w-0 flex-1 bg-transparent text-13 outline-none placeholder:text-[var(--text-placeholder)]"
- style={{ color: 'var(--settings-section-title)' }}
- />
- </div>
- )}
- {onRefresh && (
- <button
- type="button"
- onClick={onRefresh}
- disabled={refreshing || refreshDisabled}
- aria-busy={refreshing}
- aria-label={refreshLabel}
- title={refreshLabel}
- className={cn(
- 'flex h-7 w-7 shrink-0 select-none items-center justify-center rounded-full transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
- (refreshing || refreshDisabled) && 'cursor-not-allowed opacity-60',
- )}
- style={{ color: 'var(--text-secondary)' }}
- >
- <Spinner icon={RefreshCw} size={14} spinning={refreshing} />
- </button>
- )}
- {unionRows.length > 0 && multiAgent && (
- <button
- type="button"
- onClick={() => setSplitMode((v) => !v)}
- className="shrink-0 text-12 font-medium transition-opacity hover:opacity-80"
- style={{ color: splitMode ? 'var(--settings-section-title)' : 'var(--text-secondary)' }}
- >
- {t(splitMode ? 'settings.providers.models.splitDone' : 'settings.providers.models.splitAdjust')}
- </button>
- )}
- {unionRows.length > 0 && (
- <button
- type="button"
- onClick={handleBulk}
- className="shrink-0 text-12 font-medium transition-opacity hover:opacity-80"
- style={{ color: 'var(--text-secondary)' }}
- >
- {t(allOn ? 'settings.providers.models.disableAll' : 'settings.providers.models.enableAll')}
- </button>
- )}
- </div>
+ <div
+ className="flex h-8 min-w-0 basis-[200px] items-center gap-2 rounded-full px-3"
+ style={{
+ backgroundColor: 'var(--surface-elevated)',
+ border: '1px solid var(--border-default)',
+ }}
+ >
+ <Search size={14} className="shrink-0" style={{ color: 'var(--text-tertiary)' }} />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('settings.providers.models.search')}
+ aria-label={t('settings.providers.models.search')}
+ className="min-w-0 flex-1 bg-transparent text-13 outline-none placeholder:text-[var(--text-placeholder)]"
+ style={{ color: 'var(--settings-section-title)' }}
+ />
+ </div>
+ )}
+ {onRefresh && (
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={refreshing || refreshDisabled}
+ aria-busy={refreshing}
+ aria-label={refreshLabel}
+ title={refreshLabel}
+ className={cn(
+ 'flex h-7 w-7 shrink-0 select-none items-center justify-center rounded-full transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
+ (refreshing || refreshDisabled) && 'cursor-not-allowed opacity-60',
+ )}
+ style={{ color: 'var(--text-secondary)' }}
+ >
+ <Spinner icon={RefreshCw} size={14} spinning={refreshing} />
+ </button>
+ )}
+ {unionRows.length > 0 && multiAgent && (
+ <button
+ type="button"
+ onClick={() => setSplitMode((v) => !v)}
+ className="shrink-0 text-12 font-medium transition-opacity hover:opacity-80"
+ style={{
+ color: splitMode ? 'var(--settings-section-title)' : 'var(--text-secondary)',
+ }}
+ >
+ {t(
+ splitMode
+ ? 'settings.providers.models.splitDone'
+ : 'settings.providers.models.splitAdjust',
+ )}
+ </button>
+ )}
+ {unionRows.length > 0 && (
+ <button
+ type="button"
+ onClick={handleBulk}
+ className="shrink-0 text-12 font-medium transition-opacity hover:opacity-80"
+ style={{ color: 'var(--text-secondary)' }}
+ >
+ {t(
+ allOn
+ ? 'settings.providers.models.disableAll'
+ : 'settings.providers.models.enableAll',
+ )}
+ </button>
+ )}
+ </div>
)}
{/* 分别模式列头(与行内双列同宽对齐)。 */}
@@ -704,181 +745,219 @@ export function UnifiedModelList({
g.rows.length > 0 &&
g.rows.every((r) => isCapabilityRow(r, userProvider));
return (
- <div key={g.category} className="flex flex-col">
- {showGroupHeaders && (
- <button
- type="button"
- onClick={() => toggleCollapsed(g.category)}
- aria-expanded={!collapsed}
- className="flex items-center gap-1 self-start px-2 pb-0.5 text-left transition-opacity hover:opacity-80"
- >
- {/* chevron 用 transform 旋转(compositor-only,规则 7);折叠时 -90°。 */}
- <span
- className="inline-flex transition-transform duration-150"
- style={{ color: 'var(--text-tertiary)', transform: collapsed ? 'rotate(-90deg)' : 'none' }}
- >
- <ChevronDown size={12} />
- </span>
- <span
- className="text-11 font-medium uppercase"
- style={{ color: 'var(--text-tertiary)', letterSpacing: '0.5px' }}
- >
- {t(CATEGORY_LABEL_KEY[g.category])}
- </span>
- <span
- className="text-11 tabular-nums"
- style={{ color: 'var(--text-tertiary)', opacity: 0.6 }}
- >
- {g.rows.length}
- </span>
- </button>
- )}
- {/* 能力模型组的消歧说明:这组不参与对话模型选择、行内没有显示开关 ——
- 语义与上面的对话模型组不同,必须就地讲清,不能指望用户猜。 */}
- {wholeGroupCapability && !collapsed && (
- <span
- className={cn('pb-1 text-11 leading-snug', showGroupHeaders && 'pl-[24px]')}
- style={{ color: 'var(--text-tertiary)' }}
- >
- {t('settings.providers.models.capabilityGroupHint')}
- </span>
- )}
- {!collapsed &&
- g.rows.map((row) => {
- const rep = row.byAgent[row.avail[0]]!;
- const capability = isCapabilityRow(row, userProvider);
- const diverged = !capability && isRowDiverged(provider.id, row);
- const anyOn = rowAnyEnabled(provider.id, row);
- // 能力注记:多 agent 供应商里缺少任一通道就标(单 agent 供应商头部已说明);
- // 能力模型行不标(它们本来就不参与 agent 维度)。
- const missingAgents = provider.agents.filter(
- (agent) => !row.avail.includes(agent),
- );
- const capNote =
- !capability && multiAgent && missingAgents.length > 0
- ? t('settings.providers.models.capabilityNote', {
- agent: missingAgents.map((agent) => AGENT_LABEL[agent]).join(' / '),
- })
- : null;
- // 上下文窗口取代表值;双端不同用原生 title 提示。
- const ctxValues = row.avail
- .map((a) => row.byAgent[a]?.contextWindow)
- .filter((v): v is number => typeof v === 'number');
- const ctxDiffers = new Set(ctxValues).size > 1;
- const ctxTitle = ctxDiffers
- ? row.avail
- .map((a) => `${AGENT_LABEL[a]} ${formatContextWindow(row.byAgent[a]!.contextWindow)}`)
- .join(' · ')
- : undefined;
- const hiddenAgents = diverged ? getHiddenAgents(provider.id, row) : [];
- const divergedChipLabel =
- hiddenAgents.length > 0
- ? t('settings.providers.models.divergedChip', {
- agent: hiddenAgents.map((agent) => AGENT_LABEL[agent]).join(' / '),
- })
- : '';
- return (
- <div
- key={row.id}
- className="group flex items-center gap-3 rounded-lg px-2 py-[7px] transition-colors hover:bg-[var(--settings-menu-bg-hover)]"
+ <div key={g.category} className="flex flex-col">
+ {showGroupHeaders && (
+ <button
+ type="button"
+ onClick={() => toggleCollapsed(g.category)}
+ aria-expanded={!collapsed}
+ className="flex items-center gap-1 self-start px-2 pb-0.5 text-left transition-opacity hover:opacity-80"
>
+ {/* chevron 用 transform 旋转(compositor-only,规则 7);折叠时 -90°。 */}
<span
- className="min-w-0 truncate text-14 font-medium"
+ className="inline-flex transition-transform duration-150"
style={{
- color:
- capability || anyOn
- ? 'var(--settings-section-title)'
- : 'var(--text-tertiary)',
+ color: 'var(--text-tertiary)',
+ transform: collapsed ? 'rotate(-90deg)' : 'none',
}}
>
- {rep.name}
+ <ChevronDown size={12} />
</span>
- {provider.id === MANAGED_OLLAMA_PROVIDER_ID && (
- <LocalPackagingTag libraryName={row.id} />
- )}
- {capNote && (
- /* 注记可收缩截断:窄栏(最小窗口右栏 ~275px)下先压缩次要
+ <span
+ className="text-11 font-medium uppercase"
+ style={{ color: 'var(--text-tertiary)', letterSpacing: '0.5px' }}
+ >
+ {t(CATEGORY_LABEL_KEY[g.category])}
+ </span>
+ <span
+ className="text-11 tabular-nums"
+ style={{ color: 'var(--text-tertiary)', opacity: 0.6 }}
+ >
+ {g.rows.length}
+ </span>
+ </button>
+ )}
+ {/* 能力模型组的消歧说明:这组不参与对话模型选择、行内没有显示开关 ——
+ 语义与上面的对话模型组不同,必须就地讲清,不能指望用户猜。 */}
+ {wholeGroupCapability && !collapsed && (
+ <span
+ className={cn('pb-1 text-11 leading-snug', showGroupHeaders && 'pl-[24px]')}
+ style={{ color: 'var(--text-tertiary)' }}
+ >
+ {t('settings.providers.models.capabilityGroupHint')}
+ </span>
+ )}
+ {!collapsed &&
+ g.rows.map((row) => {
+ const rep = row.byAgent[row.avail[0]]!;
+ const capability = isCapabilityRow(row, userProvider);
+ const diverged = !capability && isRowDiverged(provider.id, row);
+ const anyOn = rowAnyEnabled(provider.id, row);
+ const paymentRequired = isRowPaymentRequired(row);
+ // 能力注记:多 agent 供应商里缺少任一通道就标(单 agent 供应商头部已说明);
+ // 能力模型行不标(它们本来就不参与 agent 维度)。
+ const missingAgents = provider.agents.filter(
+ (agent) => !row.avail.includes(agent),
+ );
+ const capNote =
+ !capability && multiAgent && missingAgents.length > 0
+ ? t('settings.providers.models.capabilityNote', {
+ agent: missingAgents.map((agent) => AGENT_LABEL[agent]).join(' / '),
+ })
+ : null;
+ // 上下文窗口取代表值;双端不同用原生 title 提示。
+ const ctxValues = row.avail
+ .map((a) => row.byAgent[a]?.contextWindow)
+ .filter((v): v is number => typeof v === 'number');
+ const ctxDiffers = new Set(ctxValues).size > 1;
+ const ctxTitle = ctxDiffers
+ ? row.avail
+ .map(
+ (a) =>
+ `${AGENT_LABEL[a]} ${formatContextWindow(row.byAgent[a]!.contextWindow)}`,
+ )
+ .join(' · ')
+ : undefined;
+ const hiddenAgents = diverged ? getHiddenAgents(provider.id, row) : [];
+ const divergedChipLabel =
+ hiddenAgents.length > 0
+ ? t('settings.providers.models.divergedChip', {
+ agent: hiddenAgents.map((agent) => AGENT_LABEL[agent]).join(' / '),
+ })
+ : '';
+ return (
+ <div
+ key={row.id}
+ className={cn(
+ 'group flex items-center gap-3 rounded-lg px-2 py-[7px] transition-colors hover:bg-[var(--settings-menu-bg-hover)]',
+ paymentRequired && 'opacity-55',
+ )}
+ >
+ <span
+ className="min-w-0 truncate text-14 font-medium"
+ style={{
+ color:
+ capability || anyOn
+ ? 'var(--settings-section-title)'
+ : 'var(--text-tertiary)',
+ }}
+ >
+ {rep.name}
+ </span>
+ {provider.id === MANAGED_OLLAMA_PROVIDER_ID && (
+ <LocalPackagingTag libraryName={row.id} />
+ )}
+ {capNote && (
+ /* 注记可收缩截断:窄栏(最小窗口右栏 ~275px)下先压缩次要
元数据,保住右侧上下文/菜单/开关列(PR #1102 review 第五轮);
截断时悬停可见全文。 */
- <span
- className="min-w-0 truncate text-12"
- style={{ color: 'var(--text-tertiary)' }}
- title={capNote}
- >
- {capNote}
- </span>
- )}
- <span className="min-w-0 flex-1" />
- {!splitMode && diverged && hiddenAgents.length > 0 && (
- <button
- type="button"
- onClick={() => setSplitMode(true)}
- className="flex h-[18px] min-w-0 max-w-32 items-center rounded-full px-2 text-11 font-medium transition-opacity hover:opacity-80"
- style={{
- backgroundColor: 'var(--surface-chip)',
- color: 'var(--text-secondary)',
- }}
- title={divergedChipLabel}
- >
- <span className="truncate">{divergedChipLabel}</span>
- </button>
- )}
- {/* 固定 44px 右对齐列:上下扫读时数字齐成一条线;合成媒体行
+ <span
+ className="min-w-0 truncate text-12"
+ style={{ color: 'var(--text-tertiary)' }}
+ title={capNote}
+ >
+ {capNote}
+ </span>
+ )}
+ <span className="min-w-0 flex-1" />
+ {paymentRequired && (
+ <span
+ data-payment-required-unlock
+ className="invisible shrink-0 select-none text-11 font-medium text-[var(--text-secondary)] group-hover:visible group-focus-within:visible"
+ >
+ {t('settings.providers.models.paymentUnlock')}
+ </span>
+ )}
+ {paymentRequired && (
+ <span
+ data-payment-required-badge
+ className="flex shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-11 font-medium text-[var(--text-secondary)]"
+ >
+ <Lock size={11} />
+ {t('settings.providers.models.paymentRequired')}
+ </span>
+ )}
+ {!splitMode && diverged && hiddenAgents.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setSplitMode(true)}
+ className="flex h-[18px] min-w-0 max-w-32 items-center rounded-full px-2 text-11 font-medium transition-opacity hover:opacity-80"
+ style={{
+ backgroundColor: 'var(--surface-chip)',
+ color: 'var(--text-secondary)',
+ }}
+ title={divergedChipLabel}
+ >
+ <span className="truncate">{divergedChipLabel}</span>
+ </button>
+ )}
+ {/* 固定 44px 右对齐列:上下扫读时数字齐成一条线;合成媒体行
(专属清单下发)没有上下文窗口元数据(=0),留空占位保持列对齐。 */}
- {/* 分别调整模式隐藏上下文列:两列开关 + 菜单在最小窗口
+ {/* 分别调整模式隐藏上下文列:两列开关 + 菜单在最小窗口
(右栏 ~275px)下必须完整可见,上下文是次要元数据,
普通模式仍展示(PR #1102 review 第二轮)。 */}
- {!splitMode && (
- <span
- className="w-11 shrink-0 text-right text-12 tabular-nums"
- style={{ color: 'var(--text-tertiary)' }}
- title={ctxTitle}
- >
- {rep.contextWindow > 0 ? formatContextWindow(rep.contextWindow) : ''}
- </span>
- )}
- {rowMenu(row)}
- {/* 能力模型行没有显示轴 ⇒ 没有开关(全页开关语义唯一 = 显示);
+ {!splitMode && (
+ <span
+ className="w-11 shrink-0 text-right text-12 tabular-nums"
+ style={{ color: 'var(--text-tertiary)' }}
+ title={ctxTitle}
+ >
+ {rep.contextWindow > 0 ? formatContextWindow(rep.contextWindow) : ''}
+ </span>
+ )}
+ {rowMenu(row)}
+ {/* 能力模型行没有显示轴 ⇒ 没有开关(全页开关语义唯一 = 显示);
占同宽空位,保证开关/上下文列跨行对齐。 */}
- {capability && (
- <span
- className="shrink-0"
- style={{ width: splitMode ? provider.agents.length * 80 : 36 }}
- />
- )}
- {!capability &&
- (splitMode ? (
- <div className="flex shrink-0 items-center">
- {provider.agents.map((a) => {
- const m = row.byAgent[a];
- return (
- <span key={a} className="flex w-20 items-center justify-center">
- {m ? (
- <Switch
- checked={isModelEnabled(a, provider.id, m)}
- onCheckedChange={(v) => {
- if (setModelVisibility(a, provider.id, m.id, v) === false) {
- showVisibilityWriteFailure();
- }
- }}
- aria-label={`${rep.name} · ${AGENT_LABEL[a]}`}
- />
- ) : (
- <span className="text-12" style={{ color: 'var(--text-tertiary)' }}>
- —
+ {capability && (
+ <span
+ className="shrink-0"
+ style={{ width: splitMode ? provider.agents.length * 80 : 36 }}
+ />
+ )}
+ {!capability &&
+ (splitMode ? (
+ <div className="flex shrink-0 items-center">
+ {provider.agents.map((a) => {
+ const m = row.byAgent[a];
+ return (
+ <span key={a} className="flex w-20 items-center justify-center">
+ {m ? (
+ <Switch
+ checked={isModelEnabled(a, provider.id, m)}
+ disabled={paymentRequired}
+ onCheckedChange={(v) => {
+ if (
+ setModelVisibility(a, provider.id, m.id, v) === false
+ ) {
+ showVisibilityWriteFailure();
+ }
+ }}
+ aria-label={`${rep.name} · ${AGENT_LABEL[a]}`}
+ />
+ ) : (
+ <span
+ className="text-12"
+ style={{ color: 'var(--text-tertiary)' }}
+ >
+ —
+ </span>
+ )}
</span>
- )}
- </span>
- );
- })}
- </div>
- ) : (
- <Switch checked={anyOn} onCheckedChange={() => toggleRow(row)} aria-label={rep.name} />
- ))}
- </div>
- );
- })}
- </div>
+ );
+ })}
+ </div>
+ ) : (
+ <Switch
+ disabled={paymentRequired}
+ checked={anyOn}
+ onCheckedChange={() => toggleRow(row)}
+ aria-label={rep.name}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </div>
);
})
)}
@@ -889,100 +968,126 @@ export function UnifiedModelList({
下架模型的陈旧条目 —— 逐行启用清不掉它们;configuration-and-overrides.md §4)。
渲染条件独立于当前渲染行:只剩陈旧条目(disabledRows 为空)或搜索过滤后
无匹配行时,恢复入口都不能消失(PR #744 review 第二十六轮)。 */}
- {(disabledRows.length > 0 || (provider.disableOverrideCount ?? 0) > 0) && (() => {
- const collapsed = !query.trim() && isCollapsed(DISABLED_GROUP_KEY);
- return (
- <div className="flex flex-col">
- <div className="flex items-center gap-2 pb-0.5">
- <button
- type="button"
- onClick={() => toggleCollapsed(DISABLED_GROUP_KEY)}
- aria-expanded={!collapsed}
- className="flex items-center gap-1 px-2 text-left transition-opacity hover:opacity-80"
- >
- <span
- className="inline-flex transition-transform duration-150"
- style={{ color: 'var(--text-tertiary)', transform: collapsed ? 'rotate(-90deg)' : 'none' }}
- >
- <ChevronDown size={12} />
- </span>
- <span
- className="text-11 font-medium uppercase"
- style={{ color: 'var(--text-tertiary)', letterSpacing: '0.5px' }}
+ {(disabledRows.length > 0 || (provider.disableOverrideCount ?? 0) > 0) &&
+ (() => {
+ const collapsed = !query.trim() && isCollapsed(DISABLED_GROUP_KEY);
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-2 pb-0.5">
+ <button
+ type="button"
+ onClick={() => toggleCollapsed(DISABLED_GROUP_KEY)}
+ aria-expanded={!collapsed}
+ className="flex items-center gap-1 px-2 text-left transition-opacity hover:opacity-80"
>
- {t('settings.providers.models.disabledGroup')}
- </span>
- <span className="text-11 tabular-nums" style={{ color: 'var(--text-tertiary)', opacity: 0.6 }}>
- {/* 行数为 0 而 override 仍在(陈旧条目 / 搜索过滤)时显示 override 数,
+ <span
+ className="inline-flex transition-transform duration-150"
+ style={{
+ color: 'var(--text-tertiary)',
+ transform: collapsed ? 'rotate(-90deg)' : 'none',
+ }}
+ >
+ <ChevronDown size={12} />
+ </span>
+ <span
+ className="text-11 font-medium uppercase"
+ style={{ color: 'var(--text-tertiary)', letterSpacing: '0.5px' }}
+ >
+ {t('settings.providers.models.disabledGroup')}
+ </span>
+ <span
+ className="text-11 tabular-nums"
+ style={{ color: 'var(--text-tertiary)', opacity: 0.6 }}
+ >
+ {/* 行数为 0 而 override 仍在(陈旧条目 / 搜索过滤)时显示 override 数,
让「还有 N 条停用配置」可感知。 */}
- {disabledRows.length > 0 ? disabledRows.length : provider.disableOverrideCount ?? 0}
- </span>
- </button>
- <button
- type="button"
- onClick={resetDisableOverrides}
- className="rounded-lg px-1.5 py-0.5 text-11 font-medium transition-colors hover:bg-[var(--surface-hover)]"
- style={{ color: 'var(--text-tertiary)' }}
- >
- {t('settings.providers.models.enableAllModels')}
- </button>
- </div>
- {!collapsed &&
- disabledRows.map((row) => {
- const rep = row.byAgent[row.avail[0]]!;
- // 可折行:最小窗口(右栏 ~275px)下「启用此模型」(日文更长)放
- // 不下时换行,恢复入口始终可达(PR #1102 review 第四轮)。
- return (
- <div
- key={row.id}
- className="flex flex-wrap items-center gap-x-3 gap-y-1 px-2 py-[7px]"
+ {disabledRows.length > 0
+ ? disabledRows.length
+ : (provider.disableOverrideCount ?? 0)}
+ </span>
+ </button>
+ {!hasLockedDisabledRow && (
+ <button
+ type="button"
+ onClick={resetDisableOverrides}
+ className="rounded-lg px-1.5 py-0.5 text-11 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ style={{ color: 'var(--text-tertiary)' }}
>
- <span
- className="min-w-0 truncate text-14 font-medium"
- style={{ color: 'var(--text-disabled)' }}
+ {t('settings.providers.models.enableAllModels')}
+ </button>
+ )}
+ </div>
+ {!collapsed &&
+ disabledRows.map((row) => {
+ const rep = row.byAgent[row.avail[0]]!;
+ const paymentRequired = isRowPaymentRequired(row);
+ // 可折行:最小窗口(右栏 ~275px)下「启用此模型」(日文更长)放
+ // 不下时换行,恢复入口始终可达(PR #1102 review 第四轮)。
+ return (
+ <div
+ key={row.id}
+ className="flex flex-wrap items-center gap-x-3 gap-y-1 px-2 py-[7px]"
>
- {rep.name}
- </span>
- {/* 来源分组注记:启用后会回到哪个组,别让用户猜。 */}
- <span className="shrink-0 text-12" style={{ color: 'var(--text-tertiary)' }}>
- {t(CATEGORY_LABEL_KEY[rowCategory(row)])}
- </span>
- <span className="min-w-0 flex-1" />
- {rep.contextWindow > 0 && (
<span
- className="w-11 shrink-0 text-right text-12 tabular-nums"
+ className="min-w-0 truncate text-14 font-medium"
style={{ color: 'var(--text-disabled)' }}
>
- {formatContextWindow(rep.contextWindow)}
+ {rep.name}
</span>
- )}
- <button
- type="button"
- onClick={() => setRowDisabled(row, false)}
- className="ml-auto flex h-6 shrink-0 items-center rounded-full border px-2.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)]"
- style={{
- borderColor: 'var(--settings-btn-secondary-border)',
- color: 'var(--settings-btn-secondary-text)',
- }}
- >
- {t('settings.providers.models.enableModel')}
- </button>
- {provider.id === MANAGED_OLLAMA_PROVIDER_ID && (
- <button
- type="button"
- onClick={() => void deleteInstalledModel(row)}
- className="flex h-6 shrink-0 items-center rounded-full px-2.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)]"
- style={{ color: 'var(--error-fg)' }}
+ {/* 来源分组注记:启用后会回到哪个组,别让用户猜。 */}
+ <span
+ className="shrink-0 text-12"
+ style={{ color: 'var(--text-tertiary)' }}
>
- {t('settings.providers.local.deleteModel')}
- </button>
- )}
- </div>
- );
- })}
- </div>
- );
- })()}
+ {t(CATEGORY_LABEL_KEY[rowCategory(row)])}
+ </span>
+ <span className="min-w-0 flex-1" />
+ {paymentRequired && (
+ <span
+ data-payment-required-badge
+ className="flex shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-11 font-medium text-[var(--text-secondary)]"
+ >
+ <Lock size={11} />
+ {t('settings.providers.models.paymentRequired')}
+ </span>
+ )}
+ {rep.contextWindow > 0 && (
+ <span
+ className="w-11 shrink-0 text-right text-12 tabular-nums"
+ style={{ color: 'var(--text-disabled)' }}
+ >
+ {formatContextWindow(rep.contextWindow)}
+ </span>
+ )}
+ {!paymentRequired && (
+ <button
+ type="button"
+ onClick={() => setRowDisabled(row, false)}
+ className="ml-auto flex h-6 shrink-0 items-center rounded-full border px-2.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ style={{
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ {t('settings.providers.models.enableModel')}
+ </button>
+ )}
+ {provider.id === MANAGED_OLLAMA_PROVIDER_ID && (
+ <button
+ type="button"
+ onClick={() => void deleteInstalledModel(row)}
+ className="flex h-6 shrink-0 items-center rounded-full px-2.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ style={{ color: 'var(--error-fg)' }}
+ >
+ {t('settings.providers.local.deleteModel')}
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+ })()}
</div>
</div>
{priceRow && (
diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
index 83b33dbfc2..ac468edf2b 100644
--- a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
@@ -313,3 +313,12 @@ export function useConfirmDialog(): ConfirmDialogContextValue {
}
return context;
}
+
+/**
+ * 可选读取全局确认框。仅供既能独立渲染、又能挂在完整应用壳内的复用组件使用:
+ * 正式窗口都由 ConfirmDialogProvider 提供共享弹窗;Story / 单测等裸渲染环境返回 null,
+ * 避免为了展示一个纯列表就强制复制整套应用 Provider。
+ */
+export function useOptionalConfirmDialog(): ConfirmDialogContextValue | null {
+ return useContext(ConfirmDialogContext);
+}
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index c93dd4c462..2ebb1581be 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -466,6 +466,12 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
]);
}, [loadBalance, loadOrders, loadSubscription]);
+ const refreshXdModelsAfterEntitlementChange = useCallback(async () => {
+ // 订阅权益会改变 Model Access 按当前用户返回的模型集合。这里必须走 XD 的
+ // 主进程真源刷新,不能只重载 Billing state 后继续使用 active-catalog 的旧快照。
+ await window.electronAPI.maker.refreshBuiltinProviderModels('xd');
+ }, []);
+
useEffect(() => {
void loadBillingState();
}, [loadBillingState]);
@@ -474,7 +480,14 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
const refreshAfterPortal = () => {
if (!subscriptionPortalRefreshPendingRef.current) return;
subscriptionPortalRefreshPendingRef.current = false;
- void loadBillingState();
+ // Stripe Portal can upgrade, downgrade, cancel, or resume a subscription. Billing
+ // state and the XD catalog are separate snapshots, so returning to Cindy must refresh
+ // both explicitly; the app-wide focus refresh is throttled and cannot provide this
+ // entitlement boundary.
+ void Promise.allSettled([
+ loadBillingState(),
+ refreshXdModelsAfterEntitlementChange(),
+ ]);
};
const onVisible = () => {
if (document.visibilityState === 'visible') refreshAfterPortal();
@@ -485,7 +498,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
window.removeEventListener('focus', refreshAfterPortal);
document.removeEventListener('visibilitychange', onVisible);
};
- }, [loadBillingState]);
+ }, [loadBillingState, refreshXdModelsAfterEntitlementChange]);
const closeCheckout = useCallback(() => {
const abandonedIncomplete = checkout.state.subscription?.status === 'INCOMPLETE';
@@ -517,6 +530,11 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
}
if (previousPhase !== 'COMPLETED' && checkout.state.phase === 'COMPLETED') {
void loadBalance();
+ // 服务端的 paid tier 同时认有效订阅和未全额退款的成功充值订单;两类支付
+ // 完成都必须重拉 `/models`,由服务端重算 tier 并收敛 AIGateway access group。
+ if (checkout.state.kind === 'TOPUP' || checkout.state.kind === 'SUBSCRIPTION') {
+ void refreshXdModelsAfterEntitlementChange().catch(() => undefined);
+ }
if (checkout.state.kind === 'SUBSCRIPTION') {
void loadSubscription(checkout.state.subscription);
}
@@ -528,16 +546,19 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
loadBalance,
loadOrders,
loadSubscription,
+ refreshXdModelsAfterEntitlementChange,
]);
const handlePlanChangeSettled = useCallback(
(kind: PlanChangeSettledKind) => {
// APPLIED is the only settle that moves credits; one full reload covers
// subscription, catalog, and balance without a second balance call.
- if (kind === 'APPLIED') void loadBillingState();
- else void loadSubscription();
+ if (kind === 'APPLIED') {
+ void loadBillingState();
+ void refreshXdModelsAfterEntitlementChange().catch(() => undefined);
+ } else void loadSubscription();
},
- [loadBillingState, loadSubscription],
+ [loadBillingState, loadSubscription, refreshXdModelsAfterEntitlementChange],
);
const planChange = usePlanChange(accountId, handlePlanChangeSettled);
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index f7108b89b8..4a1af46e84 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -20,6 +20,13 @@ const uiMocks = vi.hoisted(() => ({
toastSuccess: vi.fn(),
}));
+const modelCatalogMocks = vi.hoisted(() => ({
+ refreshBuiltinProviderModels: vi.fn(async () => ({
+ ok: true as const,
+ providerId: 'xd' as const,
+ })),
+}));
+
const authState = vi.hoisted(() => ({ dataOwnerId: 'account-fixture' as string | null }));
/**
@@ -112,6 +119,7 @@ beforeEach(() => {
uiMocks.confirm.mockReset().mockResolvedValue(false);
uiMocks.toastError.mockReset();
uiMocks.toastSuccess.mockReset();
+ modelCatalogMocks.refreshBuiltinProviderModels.mockClear();
authState.dataOwnerId = 'account-fixture';
routerState.search = '';
});
@@ -389,6 +397,9 @@ describe('BillingPage remote catalog rendering', () => {
listOrders: vi.fn(async () => ({ orders: [], nextCursor: null })),
openPaymentRedirect: vi.fn(async () => ({ success: true })),
},
+ maker: {
+ refreshBuiltinProviderModels: modelCatalogMocks.refreshBuiltinProviderModels,
+ },
openExternal: vi.fn(),
},
});
@@ -690,7 +701,7 @@ describe('BillingPage remote catalog rendering', () => {
expect(window.electronAPI.billing.getBalance).not.toHaveBeenCalled();
});
- it('refreshes the balance once and shows no recovery action when a top-up succeeds', async () => {
+ it('refreshes the balance and XD models once when a top-up succeeds', async () => {
const pendingOrder = {
orderId: 'order_paid',
productCode: 'credit_topup',
@@ -731,6 +742,42 @@ describe('BillingPage remote catalog rendering', () => {
view.rerender(<BillingPage />);
expect(getBalance).toHaveBeenCalledTimes(2);
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledWith('xd');
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledTimes(1);
+ });
+
+ it('force-refreshes the XD model catalog once when a subscription becomes active', async () => {
+ const pendingSubscription = {
+ subscriptionId: 'subscription_pending',
+ status: 'INCOMPLETE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'attempt_subscription',
+ paymentAction: null,
+ };
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase: 'AWAITING_PAYMENT',
+ subscription: pendingSubscription,
+ });
+ const view = render(<BillingPage />);
+ await waitFor(() => expect(window.electronAPI.billing.getBalance).toHaveBeenCalledTimes(1));
+
+ Object.assign(checkout.state, {
+ phase: 'COMPLETED',
+ subscription: { ...pendingSubscription, status: 'ACTIVE' as const },
+ });
+ view.rerender(<BillingPage />);
+
+ await waitFor(() =>
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledWith('xd'),
+ );
+ view.rerender(<BillingPage />);
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledTimes(1);
});
it('switches to the expired hint once the server stops issuing the payment action', async () => {
@@ -1792,7 +1839,13 @@ describe('BillingPage plan change', () => {
const install = (billing: ReturnType<typeof billingMocks>) => {
Object.defineProperty(window, 'electronAPI', {
configurable: true,
- value: { billing, openExternal: vi.fn() },
+ value: {
+ billing,
+ maker: {
+ refreshBuiltinProviderModels: modelCatalogMocks.refreshBuiltinProviderModels,
+ },
+ openExternal: vi.fn(),
+ },
});
return billing;
};
@@ -1853,11 +1906,14 @@ describe('BillingPage plan change', () => {
expect(billing.getCatalog).toHaveBeenCalledTimes(catalogCalls + 1);
expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(subscriptionCalls + 1);
expect(billing.getBalance).toHaveBeenCalledTimes(balanceCalls + 1);
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledWith('xd');
});
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledTimes(1);
await act(async () => resolvePortal({ success: true }));
await act(async () => window.dispatchEvent(new Event('focus')));
expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(subscriptionCalls + 1);
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledTimes(1);
});
it('refreshes billing after a timed-out Stripe portal launch', async () => {
@@ -1880,7 +1936,9 @@ describe('BillingPage plan change', () => {
expect(billing.getCatalog).toHaveBeenCalledTimes(catalogCalls + 1);
expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(subscriptionCalls + 1);
expect(billing.getBalance).toHaveBeenCalledTimes(balanceCalls + 1);
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledWith('xd');
});
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledTimes(1);
});
it('does not show Stripe management in the menu for an Alipay subscription', async () => {
@@ -2186,6 +2244,7 @@ describe('BillingPage plan change', () => {
// APPLIED refreshes subscription, catalog, and balance exactly once more.
await waitFor(() => expect(billing.getBalance).toHaveBeenCalledTimes(2));
expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2);
+ expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledWith('xd');
});
it('quotes the selected same-Product monthly Offer', async () => {
@@ -2772,6 +2831,9 @@ describe('BillingPage order history', () => {
listOrders,
openPaymentRedirect: vi.fn(async () => ({ success: true })),
},
+ maker: {
+ refreshBuiltinProviderModels: modelCatalogMocks.refreshBuiltinProviderModels,
+ },
openExternal: vi.fn(),
},
});
diff --git a/apps/desktop/src/renderer/hooks/useModelAccessStatus.ts b/apps/desktop/src/renderer/hooks/useModelAccessStatus.ts
index 061a24d283..3cf0bc27af 100644
--- a/apps/desktop/src/renderer/hooks/useModelAccessStatus.ts
+++ b/apps/desktop/src/renderer/hooks/useModelAccessStatus.ts
@@ -2,7 +2,12 @@ import { useEffect, useState } from 'react';
import type { ModelAccessStatus } from '../../shared/modelAccess';
-const IDLE: ModelAccessStatus = { state: 'idle', source: null, endpoint: null };
+const IDLE: ModelAccessStatus = {
+ state: 'idle',
+ source: null,
+ endpoint: null,
+ accountTier: null,
+};
/**
* useModelAccessStatus —— 网关凭据自动下发的同步状态(main 侧权威,推送驱动)。
@@ -14,14 +19,19 @@ export function useModelAccessStatus(): ModelAccessStatus {
const [status, setStatus] = useState<ModelAccessStatus>(IDLE);
useEffect(() => {
+ const api = window.electronAPI?.modelAccess;
+ // 辅助窗口与单测可只暴露所需的最小 preload 能力;缺少该 bridge 时保持未知态,
+ // 不能让一枚展示标签扩大所有 Renderer surface 的能力依赖。
+ if (!api?.getStatus || !api.onStatusChange) return;
+
let cancelled = false;
- void window.electronAPI.modelAccess
+ void api
.getStatus()
.then((s) => {
if (!cancelled) setStatus(s);
})
.catch(() => undefined);
- const unsubscribe = window.electronAPI.modelAccess.onStatusChange((s) => setStatus(s));
+ const unsubscribe = api.onStatusChange((s) => setStatus(s));
return () => {
cancelled = true;
unsubscribe();
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e0ca6cffc7..d39b6a1f45 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1421,6 +1421,9 @@
"subtitle": "All models · Claude Code / Codex · billed from your balance per token",
"modelLabel": "All models",
"billingLabel": "billed from your balance per token",
+ "accountTier": {
+ "free": "Free tier"
+ },
"disconnectConfirm": {
"title": "Disconnect Cindy AI?",
"description": "Disconnecting clears the Cindy AI key saved locally. You will need to reconnect to keep using models provided by Cindy AI."
@@ -1684,6 +1687,8 @@
"refreshFailed": "Model list couldn’t be refreshed — try again later",
"refreshFetchDisabled": "Remote model catalog fetching is disabled — refresh skipped",
"disableModel": "Disable This Model",
+ "paymentRequired": "Paid",
+ "paymentUnlock": "Pay to unlock",
"enableModel": "Enable This Model",
"capabilityGroupHint": "Not shown in the chat model picker; used only by features like image generation.",
"accessWriteFailed": "Couldn't save the change. Please try again.",
@@ -5531,7 +5536,7 @@
"provider": "Provider",
"tokens": "Total tokens",
"context": "Context used",
- "lastActive": "Last active"
+ "lastActive": "Last active"
},
"providerTooltip": "The provider currently selected for the session; blank when none is pinned.",
"tokensTooltip": "The session's lifetime total, not the tokens spent within the last 30 days."
@@ -6729,6 +6734,13 @@
},
"modelSelector": {
"budgetNeedsApiKey": "This model needs an API key — configure it in Settings",
+ "paymentRequired": {
+ "badge": "Paid",
+ "unlock": "Pay to unlock",
+ "title": "Pay to Unlock This Model",
+ "description": "Subscribe to a paid plan or top up your balance to use this model.",
+ "action": "View Billing Options"
+ },
"hidden": "Hidden",
"modelListAria": "Model list",
"subscriptionDirectDisabled": {
@@ -8890,7 +8902,15 @@
"custom": "Custom"
},
"weekday": {
- "full": { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday" },
+ "full": {
+ "0": "Sunday",
+ "1": "Monday",
+ "2": "Tuesday",
+ "3": "Wednesday",
+ "4": "Thursday",
+ "5": "Friday",
+ "6": "Saturday"
+ },
"short": { "0": "Su", "1": "Mo", "2": "Tu", "3": "We", "4": "Th", "5": "Fr", "6": "Sa" }
},
"time": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a39fe9e687..06de50cac3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1421,6 +1421,9 @@
"subtitle": "すべてのモデル · Claude Code / Codex 共通 · トークン単位で残高から引き落とし",
"modelLabel": "すべてのモデル",
"billingLabel": "トークン単位で残高から引き落とし",
+ "accountTier": {
+ "free": "無料版"
+ },
"disconnectConfirm": {
"title": "Cindy AI を切断しますか?",
"description": "切断するとローカルに保存された Cindy AI Key が削除されます。Cindy AI のモデルを引き続き使うには再接続が必要です。"
@@ -1683,6 +1686,8 @@
"refreshFailed": "モデル一覧を更新できませんでした。しばらくしてから再試行してください",
"refreshFetchDisabled": "モデルカタログのリモート取得が無効のため、更新をスキップしました",
"disableModel": "このモデルを無効にする",
+ "paymentRequired": "有料",
+ "paymentUnlock": "有料で解放",
"enableModel": "このモデルを有効にする",
"capabilityGroupHint": "チャットのモデル選択には表示されず、画像生成などの機能でのみ使用されます。",
"accessWriteFailed": "変更を保存できませんでした。もう一度お試しください。",
@@ -5529,7 +5534,7 @@
"provider": "プロバイダー",
"tokens": "累計トークン",
"context": "コンテキスト使用率",
- "lastActive": "最終アクティブ"
+ "lastActive": "最終アクティブ"
},
"providerTooltip": "セッションで現在選択されているプロバイダー。未指定の場合は空欄です。",
"tokensTooltip": "セッションの累計値であり、直近 30 日の増分ではありません。"
@@ -6727,6 +6732,13 @@
},
"modelSelector": {
"budgetNeedsApiKey": "このモデルは設定で API key を構成してから使用できます",
+ "paymentRequired": {
+ "badge": "有料",
+ "unlock": "有料で解放",
+ "title": "有料でこのモデルを解放",
+ "description": "有料プランを購読するか、残高をチャージすると、このモデルを利用できます。",
+ "action": "支払い方法を見る"
+ },
"hidden": "非表示",
"modelListAria": "モデル一覧",
"subscriptionDirectDisabled": {
@@ -8878,7 +8890,15 @@
"custom": "カスタム"
},
"weekday": {
- "full": { "0": "日曜日", "1": "月曜日", "2": "火曜日", "3": "水曜日", "4": "木曜日", "5": "金曜日", "6": "土曜日" },
+ "full": {
+ "0": "日曜日",
+ "1": "月曜日",
+ "2": "火曜日",
+ "3": "水曜日",
+ "4": "木曜日",
+ "5": "金曜日",
+ "6": "土曜日"
+ },
"short": { "0": "日", "1": "月", "2": "火", "3": "水", "4": "木", "5": "金", "6": "土" }
},
"time": {
@@ -9375,17 +9395,17 @@
"nightly-test-heal": {
"name": "夜間セルフヒーリングテスト",
"description": "毎晩テストを実行し、失敗項目を分離ワークツリーで最小修正",
- "prompt": "プロジェクトのテストスイートを実行し、失敗があれば隔離された worktree で最小限の修正を試みてください。\n制約:\n- リポジトリのドキュメントまたは package スクリプトから標準のテストコマンドを特定してから、テストスイート全体を実行する\n- 明確な失敗の証拠がある問題だけを修正し、影響範囲が最小の変更を優先して、ついでのリファクタリングは避ける\n- 修正後は関連テストを再実行して成功を確認し、diff 全体をレビューする\n- リポジトリのワークフローに従って修正を提出する(例:ブランチを作成して PR を開く)。main ブランチを直接変更しない\n- 安全に修正できない失敗については、原因、疑わしいファイル、推奨する調査手順を報告する"
+ "prompt": "プロジェクトのテストスイートを実行し、失敗があれば隔離された worktree で最小限の修正を試みてください。\n制約:\n- リポジトリのドキュメントまたは package スクリプトから標準のテストコマンドを特定してから、テストスイート全体を実行する\n- 明確な失敗の証拠がある問題だけを修正し、影響範囲が最小の変更を優先して、ついでのリファクタリングは避ける\n- 修正後は関連テストを再実行して成功を確認し、diff 全体をレビューする\n- リポジトリのワークフローに従って修正を提出する(例:ブランチを作成して PR を開く)。main ブランチを直接変更しない\n- 安全に修正できない失敗については、原因、疑わしいファイル、推奨する調査手順を報告する"
},
"pr-gatekeeper": {
"name": "PR ゲートキーパー",
"description": "平日にオープン PR の新規変更を事前レビューし、重大度別にリスクを報告",
- "prompt": "リポジトリで現在オープンな PR を確認し、新しい変更を事前レビューしてください。\n制約:\n- 過去 24 時間以内に新しいコミットがあるオープン PR を 1 件ずつ確認する(月曜日は週末全体を対象)。PR 番号、ファイルパス、具体的な diff を引用する\n- 正確性、セキュリティ、データ損失、互換性の問題に重点を置き、深刻度別に分類する\n- 証拠で裏付けられる問題だけを報告し、失敗シナリオを説明する。スタイル上の好みだけで指摘しない\n- ユーザーが明示的に許可しない限り、レビュー結果のみを出力し、PR へのコメントやコード変更は行わない"
+ "prompt": "リポジトリで現在オープンな PR を確認し、新しい変更を事前レビューしてください。\n制約:\n- 過去 24 時間以内に新しいコミットがあるオープン PR を 1 件ずつ確認する(月曜日は週末全体を対象)。PR 番号、ファイルパス、具体的な diff を引用する\n- 正確性、セキュリティ、データ損失、互換性の問題に重点を置き、深刻度別に分類する\n- 証拠で裏付けられる問題だけを報告し、失敗シナリオを説明する。スタイル上の好みだけで指摘しない\n- ユーザーが明示的に許可しない限り、レビュー結果のみを出力し、PR へのコメントやコード変更は行わない"
},
"domain-radar": {
"name": "分野レーダー",
"description": "注目分野の最新動向を定期収集し、見解付きサマリーを出力",
- "prompt": "テーマ「{{topic}}」について過去 24 時間の最新動向(月曜日は週末全体)を収集し、見解を含むダイジェストを作成してください。\n制約:\n- Web 検索を使い、複数の情報源で照合してから採用し、各項目に出典リンクを付ける\n- リリース、研究、政策、重要な議論など実質的な進展を優先し、宣伝記事や転載を除外する\n- リンクを並べるだけでなく、各動向に「なぜ注目すべきか」を 1 文で示す\n- 情報が少ない場合や情報源に疑義がある場合は率直に明記し、推測で補わない",
+ "prompt": "テーマ「{{topic}}」について過去 24 時間の最新動向(月曜日は週末全体)を収集し、見解を含むダイジェストを作成してください。\n制約:\n- Web 検索を使い、複数の情報源で照合してから採用し、各項目に出典リンクを付ける\n- リリース、研究、政策、重要な議論など実質的な進展を優先し、宣伝記事や転載を除外する\n- リンクを並べるだけでなく、各動向に「なぜ注目すべきか」を 1 文で示す\n- 情報が少ない場合や情報源に疑義がある場合は率直に明記し、推測で補わない",
"params": {
"topic": {
"label": "注目テーマ",
@@ -9396,7 +9416,7 @@
"competitor-watch": {
"name": "競合ウォッチ",
"description": "競合の製品・市場動向を週次でまとめ、自社への影響を分析",
- "prompt": "次の競合の過去 1 週間の動向を追跡してください:{{competitors}}。\n制約:\n- Web 検索で製品更新、リリース、価格変更、市場動向、ユーザー評価を調べ、出典を示す\n- 公式情報と第三者による情報を区別し、未確認の噂は明示する\n- 重要な動向ごとに、それが自社に何を意味するかを分析し、対応案を示す\n- 実質的な動きがない場合は、水増しせず率直にその旨を伝える",
+ "prompt": "次の競合の過去 1 週間の動向を追跡してください:{{competitors}}。\n制約:\n- Web 検索で製品更新、リリース、価格変更、市場動向、ユーザー評価を調べ、出典を示す\n- 公式情報と第三者による情報を区別し、未確認の噂は明示する\n- 重要な動向ごとに、それが自社に何を意味するかを分析し、対応案を示す\n- 実質的な動きがない場合は、水増しせず率直にその旨を伝える",
"params": {
"competitors": {
"label": "競合リスト",
@@ -9407,12 +9427,12 @@
"weekly-work-draft": {
"name": "週報ドラフトアシスタント",
"description": "作業ディレクトリのドキュメントから今週の作業を整理し、週報ドラフトを生成",
- "prompt": "作業ディレクトリ内で今週変更されたドキュメント、メモ、成果物を基に、週報の下書きを作成してください。\n制約:\n- 作業ディレクトリ内に実際の変更履歴がある内容だけを根拠とし、対応するファイルを示す\n- 「今週完了 / 進行中 / 来週の予定 / 調整が必要」の構成で、そのまま提出できる簡潔な文章にする\n- 実質的な進捗と定常作業を区別し、価値のある成果を強調する\n- 判断材料が足りない箇所には説明付きのプレースホルダーを残し、ユーザーが追記できるようにする"
+ "prompt": "作業ディレクトリ内で今週変更されたドキュメント、メモ、成果物を基に、週報の下書きを作成してください。\n制約:\n- 作業ディレクトリ内に実際の変更履歴がある内容だけを根拠とし、対応するファイルを示す\n- 「今週完了 / 進行中 / 来週の予定 / 調整が必要」の構成で、そのまま提出できる簡潔な文章にする\n- 実質的な進捗と定常作業を区別し、価値のある成果を強調する\n- 判断材料が足りない箇所には説明付きのプレースホルダーを残し、ユーザーが追記できるようにする"
},
"knowledge-freshness": {
"name": "ナレッジベース鮮度チェック",
"description": "毎月ドキュメントを点検し、古い内容や矛盾を洗い出す",
- "prompt": "作業ディレクトリ内のドキュメントを点検し、更新が必要な内容を見つけてください。\n制約:\n- 古い情報(過去の日付、無効なリンク、廃止された手順やツール)、矛盾、重複を確認する\n- 各問題についてファイルパスと具体的な場所を示し、判断理由を説明する\n- 「更新を推奨 / 統合を推奨 / 削除を推奨」に分類し、修正チェックリストを作成する\n- 点検レポートだけを出力し、ドキュメント自体は変更しない"
+ "prompt": "作業ディレクトリ内のドキュメントを点検し、更新が必要な内容を見つけてください。\n制約:\n- 古い情報(過去の日付、無効なリンク、廃止された手順やツール)、矛盾、重複を確認する\n- 各問題についてファイルパスと具体的な場所を示し、判断理由を説明する\n- 「更新を推奨 / 統合を推奨 / 削除を推奨」に分類し、修正チェックリストを作成する\n- 点検レポートだけを出力し、ドキュメント自体は変更しない"
}
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ffb9e35390..271ec38024 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1421,6 +1421,9 @@
"subtitle": "모든 모델 · Claude Code / Codex 공용 · 토큰 단위로 잔액에서 차감",
"modelLabel": "모든 모델",
"billingLabel": "토큰 단위로 잔액에서 차감",
+ "accountTier": {
+ "free": "무료 버전"
+ },
"disconnectConfirm": {
"title": "Cindy AI 연결을 해제할까요?",
"description": "연결을 해제하면 로컬에 저장된 Cindy AI Key가 삭제됩니다. Cindy AI 모델을 계속 사용하려면 다시 연결해야 합니다."
@@ -1683,6 +1686,8 @@
"refreshFailed": "모델 목록을 새로고침하지 못했습니다. 잠시 후 다시 시도해 주세요",
"refreshFetchDisabled": "모델 카탈로그 원격 가져오기가 비활성화되어 새로고침을 건너뛰었습니다",
"disableModel": "이 모델 비활성화",
+ "paymentRequired": "유료",
+ "paymentUnlock": "유료로 잠금 해제",
"enableModel": "이 모델 활성화",
"capabilityGroupHint": "대화 모델 선택에는 표시되지 않으며, 이미지 생성 등 기능에서만 사용됩니다.",
"accessWriteFailed": "변경 사항을 저장하지 못했습니다. 다시 시도해 주세요.",
@@ -5529,7 +5534,7 @@
"provider": "제공자",
"tokens": "누적 토큰",
"context": "컨텍스트 사용률",
- "lastActive": "마지막 활동"
+ "lastActive": "마지막 활동"
},
"providerTooltip": "세션에 현재 선택된 제공자입니다. 지정하지 않은 경우 비워 둡니다.",
"tokensTooltip": "해당 세션의 누적 값이며 최근 30일 증가분이 아닙니다."
@@ -6727,6 +6732,13 @@
},
"modelSelector": {
"budgetNeedsApiKey": "이 모델은 설정에서 API key를 구성해야 사용할 수 있습니다",
+ "paymentRequired": {
+ "badge": "유료",
+ "unlock": "유료로 잠금 해제",
+ "title": "결제 후 이 모델 잠금 해제",
+ "description": "유료 플랜을 구독하거나 잔액을 충전하면 이 모델을 사용할 수 있습니다.",
+ "action": "결제 방법 보기"
+ },
"hidden": "숨김",
"modelListAria": "모델 목록",
"subscriptionDirectDisabled": {
@@ -8878,7 +8890,15 @@
"custom": "사용자 지정"
},
"weekday": {
- "full": { "0": "일요일", "1": "월요일", "2": "화요일", "3": "수요일", "4": "목요일", "5": "금요일", "6": "토요일" },
+ "full": {
+ "0": "일요일",
+ "1": "월요일",
+ "2": "화요일",
+ "3": "수요일",
+ "4": "목요일",
+ "5": "금요일",
+ "6": "토요일"
+ },
"short": { "0": "일", "1": "월", "2": "화", "3": "수", "4": "목", "5": "금", "6": "토" }
},
"time": {
@@ -9375,17 +9395,17 @@
"nightly-test-heal": {
"name": "야간 자가 복구 테스트",
"description": "매일 밤 테스트를 실행하고 실패 항목을 격리 워크트리에서 최소 수정",
- "prompt": "프로젝트의 테스트 스위트를 실행하고, 실패 항목이 있으면 격리된 worktree에서 최소한의 수정을 시도하세요.\n제약 사항:\n- 전체 테스트를 실행하기 전에 저장소 문서나 package 스크립트에서 표준 테스트 명령을 확인합니다\n- 명확한 실패 증거가 있는 문제만 수정하고, 영향 범위가 가장 작은 변경을 우선하며 관련 없는 리팩터링은 피합니다\n- 수정 후 관련 테스트를 다시 실행해 통과 여부를 확인하고 전체 diff를 검토합니다\n- 저장소의 작업 흐름에 따라 수정 사항을 전달합니다(예: 브랜치를 만들고 PR 열기). main 브랜치를 직접 변경하지 않습니다\n- 안전하게 수정할 수 없는 실패 항목은 원인, 의심되는 파일, 권장 조사 단계를 보고합니다"
+ "prompt": "프로젝트의 테스트 스위트를 실행하고, 실패 항목이 있으면 격리된 worktree에서 최소한의 수정을 시도하세요.\n제약 사항:\n- 전체 테스트를 실행하기 전에 저장소 문서나 package 스크립트에서 표준 테스트 명령을 확인합니다\n- 명확한 실패 증거가 있는 문제만 수정하고, 영향 범위가 가장 작은 변경을 우선하며 관련 없는 리팩터링은 피합니다\n- 수정 후 관련 테스트를 다시 실행해 통과 여부를 확인하고 전체 diff를 검토합니다\n- 저장소의 작업 흐름에 따라 수정 사항을 전달합니다(예: 브랜치를 만들고 PR 열기). main 브랜치를 직접 변경하지 않습니다\n- 안전하게 수정할 수 없는 실패 항목은 원인, 의심되는 파일, 권장 조사 단계를 보고합니다"
},
"pr-gatekeeper": {
"name": "PR 게이트키퍼",
"description": "평일마다 오픈 PR의 새 변경을 사전 리뷰하고 심각도별로 위험 보고",
- "prompt": "저장소에서 현재 열려 있는 PR을 확인하고 새 변경 사항을 사전 검토하세요.\n제약 사항:\n- 지난 24시간 동안 새 커밋이 추가된 열린 PR을 하나씩 확인합니다(월요일에는 주말 전체를 확인). PR 번호, 파일 경로, 구체적인 diff를 인용합니다\n- 정확성, 보안, 데이터 손실, 호환성 문제를 중점적으로 찾고 심각도별로 분류합니다\n- 증거로 뒷받침되는 문제만 보고하고 실패 시나리오를 설명합니다. 스타일 취향만으로 지적하지 않습니다\n- 사용자가 명시적으로 허용하지 않는 한 검토 결과만 출력하고 PR에 댓글을 달거나 코드를 변경하지 않습니다"
+ "prompt": "저장소에서 현재 열려 있는 PR을 확인하고 새 변경 사항을 사전 검토하세요.\n제약 사항:\n- 지난 24시간 동안 새 커밋이 추가된 열린 PR을 하나씩 확인합니다(월요일에는 주말 전체를 확인). PR 번호, 파일 경로, 구체적인 diff를 인용합니다\n- 정확성, 보안, 데이터 손실, 호환성 문제를 중점적으로 찾고 심각도별로 분류합니다\n- 증거로 뒷받침되는 문제만 보고하고 실패 시나리오를 설명합니다. 스타일 취향만으로 지적하지 않습니다\n- 사용자가 명시적으로 허용하지 않는 한 검토 결과만 출력하고 PR에 댓글을 달거나 코드를 변경하지 않습니다"
},
"domain-radar": {
"name": "관심 분야 레이더",
"description": "관심 분야의 최신 동향을 정기 수집해 관점 있는 요약 제공",
- "prompt": "주제 \"{{topic}}\"에 관한 지난 24시간의 최신 동향을 수집하고(월요일에는 주말 전체를 확인) 관점이 담긴 요약을 작성하세요.\n제약 사항:\n- Web 검색을 사용하고 여러 출처를 교차 확인한 뒤 정보를 채택하며, 각 항목에 출처 링크를 표시합니다\n- 출시, 연구, 정책, 주요 논의처럼 실질적인 진전을 우선하고 홍보성 글과 중복 게시물은 제외합니다\n- 링크만 나열하지 말고 각 동향이 왜 중요한지 한 문장으로 판단을 덧붙입니다\n- 정보가 부족하거나 출처가 의심스러우면 솔직히 밝히고 지어내지 않습니다",
+ "prompt": "주제 \"{{topic}}\"에 관한 지난 24시간의 최신 동향을 수집하고(월요일에는 주말 전체를 확인) 관점이 담긴 요약을 작성하세요.\n제약 사항:\n- Web 검색을 사용하고 여러 출처를 교차 확인한 뒤 정보를 채택하며, 각 항목에 출처 링크를 표시합니다\n- 출시, 연구, 정책, 주요 논의처럼 실질적인 진전을 우선하고 홍보성 글과 중복 게시물은 제외합니다\n- 링크만 나열하지 말고 각 동향이 왜 중요한지 한 문장으로 판단을 덧붙입니다\n- 정보가 부족하거나 출처가 의심스러우면 솔직히 밝히고 지어내지 않습니다",
"params": {
"topic": {
"label": "관심 주제",
@@ -9396,7 +9416,7 @@
"competitor-watch": {
"name": "경쟁사 동향 추적",
"description": "경쟁사의 제품·시장 동향을 매주 정리하고 영향 분석",
- "prompt": "다음 경쟁사의 지난 일주일간 동향을 추적하세요: {{competitors}}.\n제약 사항:\n- Web 검색으로 제품 업데이트, 출시, 가격 변경, 시장 움직임, 사용자 반응을 조사하고 출처를 표시합니다\n- 공식 정보와 제3자 전언을 구분하고 확인되지 않은 소문은 명확히 표시합니다\n- 중요한 동향마다 우리에게 어떤 의미가 있는지 분석하고 대응 방안을 제안합니다\n- 실질적인 동향이 없다면 내용을 부풀리지 말고 솔직히 밝힙니다",
+ "prompt": "다음 경쟁사의 지난 일주일간 동향을 추적하세요: {{competitors}}.\n제약 사항:\n- Web 검색으로 제품 업데이트, 출시, 가격 변경, 시장 움직임, 사용자 반응을 조사하고 출처를 표시합니다\n- 공식 정보와 제3자 전언을 구분하고 확인되지 않은 소문은 명확히 표시합니다\n- 중요한 동향마다 우리에게 어떤 의미가 있는지 분석하고 대응 방안을 제안합니다\n- 실질적인 동향이 없다면 내용을 부풀리지 말고 솔직히 밝힙니다",
"params": {
"competitors": {
"label": "경쟁사 목록",
@@ -9407,12 +9427,12 @@
"weekly-work-draft": {
"name": "주간 보고서 초안 도우미",
"description": "작업 디렉터리의 문서와 산출물로 주간 보고서 초안 생성",
- "prompt": "작업 디렉터리에서 이번 주에 변경된 문서, 메모, 결과물을 바탕으로 주간 보고서 초안을 작성하세요.\n제약 사항:\n- 작업 디렉터리에 실제 변경 흔적이 있는 내용만 근거로 사용하고 해당 파일을 표시합니다\n- \"이번 주 완료 / 진행 중 / 다음 주 계획 / 협의 필요\" 구조로, 바로 제출할 수 있을 만큼 간결하게 작성합니다\n- 실질적인 진전과 반복 업무를 구분하고 가치 있는 결과물을 강조합니다\n- 판단할 자료가 부족한 부분에는 설명과 함께 자리 표시자를 남겨 사용자가 보완할 수 있게 합니다"
+ "prompt": "작업 디렉터리에서 이번 주에 변경된 문서, 메모, 결과물을 바탕으로 주간 보고서 초안을 작성하세요.\n제약 사항:\n- 작업 디렉터리에 실제 변경 흔적이 있는 내용만 근거로 사용하고 해당 파일을 표시합니다\n- \"이번 주 완료 / 진행 중 / 다음 주 계획 / 협의 필요\" 구조로, 바로 제출할 수 있을 만큼 간결하게 작성합니다\n- 실질적인 진전과 반복 업무를 구분하고 가치 있는 결과물을 강조합니다\n- 판단할 자료가 부족한 부분에는 설명과 함께 자리 표시자를 남겨 사용자가 보완할 수 있게 합니다"
},
"knowledge-freshness": {
"name": "지식 베이스 신선도 점검",
"description": "매월 문서를 점검해 오래된 내용과 모순 찾기",
- "prompt": "작업 디렉터리의 문서를 점검하고 업데이트가 필요한 내용을 찾으세요.\n제약 사항:\n- 오래된 정보(지난 날짜, 끊어진 링크, 폐기된 절차나 도구), 모순, 중복 내용을 확인합니다\n- 각 문제의 파일 경로와 구체적인 위치를 표시하고 판단 근거를 설명합니다\n- \"업데이트 권장 / 병합 권장 / 삭제 권장\"으로 분류하고 수정 체크리스트를 작성합니다\n- 점검 보고서만 출력하고 문서 자체는 수정하지 않습니다"
+ "prompt": "작업 디렉터리의 문서를 점검하고 업데이트가 필요한 내용을 찾으세요.\n제약 사항:\n- 오래된 정보(지난 날짜, 끊어진 링크, 폐기된 절차나 도구), 모순, 중복 내용을 확인합니다\n- 각 문제의 파일 경로와 구체적인 위치를 표시하고 판단 근거를 설명합니다\n- \"업데이트 권장 / 병합 권장 / 삭제 권장\"으로 분류하고 수정 체크리스트를 작성합니다\n- 점검 보고서만 출력하고 문서 자체는 수정하지 않습니다"
}
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b52c065ca5..b8ff79a4a9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1421,6 +1421,9 @@
"subtitle": "全部模型 · Claude Code / Codex 通用 · 按 token 从余额扣费",
"modelLabel": "全部模型",
"billingLabel": "按 token 从余额扣费",
+ "accountTier": {
+ "free": "免费版"
+ },
"disconnectConfirm": {
"title": "断开 Cindy AI?",
"description": "断开后将清除本地保存的 Cindy AI Key,需要重新连接才能继续使用 Cindy AI 提供的模型。"
@@ -1683,6 +1686,8 @@
"refreshFailed": "模型列表刷新失败,请稍后再试",
"refreshFetchDisabled": "模型目录远程拉取未启用,已跳过刷新",
"disableModel": "停用此模型",
+ "paymentRequired": "付费",
+ "paymentUnlock": "付费解锁",
"enableModel": "启用此模型",
"capabilityGroupHint": "不会出现在对话模型选择中,仅供图像生成等功能使用",
"accessWriteFailed": "停用设置未能保存,请重试",
@@ -5521,7 +5526,7 @@
"provider": "供应商",
"tokens": "累计 token",
"context": "上下文占用",
- "lastActive": "最后活跃"
+ "lastActive": "最后活跃"
},
"providerTooltip": "取该任务当前选定的供应商;未指定时留空。",
"tokensTooltip": "该任务的生命周期累计,不是近 30 天内的增量。"
@@ -6719,6 +6724,13 @@
},
"modelSelector": {
"budgetNeedsApiKey": "此模型需先在设置里配置 API key 才能使用",
+ "paymentRequired": {
+ "badge": "付费",
+ "unlock": "付费解锁",
+ "title": "付费后解锁此模型",
+ "description": "订阅付费方案或完成余额充值后,即可使用此模型。",
+ "action": "查看付费方式"
+ },
"hidden": "已隐藏",
"modelListAria": "模型列表",
"subscriptionDirectDisabled": {
@@ -8870,7 +8882,15 @@
"custom": "自定义"
},
"weekday": {
- "full": { "0": "星期日", "1": "星期一", "2": "星期二", "3": "星期三", "4": "星期四", "5": "星期五", "6": "星期六" },
+ "full": {
+ "0": "星期日",
+ "1": "星期一",
+ "2": "星期二",
+ "3": "星期三",
+ "4": "星期四",
+ "5": "星期五",
+ "6": "星期六"
+ },
"short": { "0": "日", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六" }
},
"time": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 3ffdd860dc..cbde914e0a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1421,6 +1421,9 @@
"subtitle": "全部模型 · Claude Code / Codex 通用 · 按 token 從餘額扣費",
"modelLabel": "全部模型",
"billingLabel": "按 token 從餘額扣費",
+ "accountTier": {
+ "free": "免費版"
+ },
"disconnectConfirm": {
"title": "斷開 Cindy AI?",
"description": "斷開後將清除本地儲存的 Cindy AI Key,需要重新連線才能繼續使用 Cindy AI 提供的模型。"
@@ -1683,6 +1686,8 @@
"refreshFailed": "模型列表重新整理失敗,請稍後再試",
"refreshFetchDisabled": "模型目錄遠端擷取未啟用,已跳過重新整理",
"disableModel": "停用此模型",
+ "paymentRequired": "付費",
+ "paymentUnlock": "付費解鎖",
"enableModel": "啟用此模型",
"capabilityGroupHint": "不會出現在對話模型選擇中,僅供影像生成等功能使用",
"accessWriteFailed": "停用設定未能儲存,請重試",
@@ -5521,7 +5526,7 @@
"provider": "供應商",
"tokens": "累計 token",
"context": "上下文佔用",
- "lastActive": "最後活躍"
+ "lastActive": "最後活躍"
},
"providerTooltip": "取該任務目前選定的供應商;未指定時留空。",
"tokensTooltip": "該任務的生命週期累計,不是近 30 天內的增量。"
@@ -6719,6 +6724,13 @@
},
"modelSelector": {
"budgetNeedsApiKey": "此模型需先在設定裡配置 API key 才能使用",
+ "paymentRequired": {
+ "badge": "付費",
+ "unlock": "付費解鎖",
+ "title": "付費後解鎖此模型",
+ "description": "訂閱付費方案或完成餘額儲值後,即可使用此模型。",
+ "action": "查看付費方式"
+ },
"hidden": "已隱藏",
"subscriptionDirectDisabled": {
"chatgpt": "訂閱直連的 GPT 模型協議暫不支援 SSH 遠端會話",
@@ -8870,7 +8882,15 @@
"custom": "自訂"
},
"weekday": {
- "full": { "0": "星期日", "1": "星期一", "2": "星期二", "3": "星期三", "4": "星期四", "5": "星期五", "6": "星期六" },
+ "full": {
+ "0": "星期日",
+ "1": "星期一",
+ "2": "星期二",
+ "3": "星期三",
+ "4": "星期四",
+ "5": "星期五",
+ "6": "星期六"
+ },
"short": { "0": "日", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六" }
},
"time": {
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 5da8d7f936..4dfd60d32d 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -25,6 +25,9 @@ export type ModelAccessSyncState =
/** 当前生效的 XD 网关凭据来源:服务端下发 / 用户手填;null = 无标记(历史手填或未配置)。 */
export type ModelAccessCredentialSource = 'server' | 'manual';
+/** 当前个人账号的 Cindy AI 模型权益;组织与未登录请求不适用个人档位。 */
+export type ModelAccessAccountTier = 'free' | 'paid' | 'not_applicable';
+
export interface ModelAccessStatus {
state: ModelAccessSyncState;
/** state='failed' 时的错误码(ServerApiError code / 'SAFE_STORAGE_UNAVAILABLE')。 */
@@ -33,6 +36,8 @@ export interface ModelAccessStatus {
source: ModelAccessCredentialSource | null;
/** source='server' 时下发的推理 endpoint(展示用;消费一律走 main 侧 getter)。 */
endpoint: string | null;
+ /** 最近一次当前账号 v5 模型目录成功响应的用户级身份;未知或已失效时为 null。 */
+ accountTier: ModelAccessAccountTier | null;
}
/** 当前登录身份在 AIGateway Credit Ledger 中的同一时点余额快照。 */
@@ -165,6 +170,8 @@ export interface ModelGroupPricing {
*/
export interface ModelAccessGatewayModel extends ModelGroupPricing {
id: string;
+ /** v5 entitlement projection; missing only on persisted/legacy snapshots. */
+ availability?: 'available' | 'requires_payment';
/**
* Gateway 原生 mode(issue #882:权威分类字段,字段值不改名)。原样透传,可能
* 缺省(旧缓存 / 服务端尚未覆盖到的模型)——**不代表**本条目已被服务端判定
@@ -218,6 +225,7 @@ export interface ModelAccessGatewayModel extends ModelGroupPricing {
* remain a runtime-parser concern.
*/
export interface ModelAccessModelsResponse {
- schemaVersion: 1 | 2 | 3 | 4;
+ schemaVersion: 1 | 2 | 3 | 4 | 5;
+ accountTier?: ModelAccessAccountTier;
models: ModelAccessGatewayModel[];
}
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 9db34d31e0..7dd2a2544f 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -187,6 +187,10 @@ Cindy 在 X 上发出的那条公开回复。zh-CN 取「回帖」以强调它
模型目录中由服务端显式 group:"china" 标记的来源分组。它描述模型或供应商来自中国,不表示相对于当前用户或发行区域的‘国内’;英文词条保持自然大小写 China,设置页分组头由统一 uppercase 样式显示为 CHINA。
+### Free tier
+
+Cindy AI 个人账号的免费会员身份标签。只在服务端明确下发 accountTier=free 时显示;paid、not_applicable 与未知状态不显示标签。
+
### Cindy Codex home
远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index dd4d6d3e14..967421ed49 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -13,6 +13,18 @@
"desktop:settings.help.qnaFeedbackBodyTemplate"
],
"terms": [
+ {
+ "id": "cindy-ai-free-tier",
+ "status": "proposed",
+ "en": "Free tier",
+ "translations": {
+ "zh-CN": "免费版",
+ "zh-TW": "免費版",
+ "ja": "無料版",
+ "ko": "무료 버전"
+ },
+ "note": "Cindy AI 个人账号的免费会员身份标签。只在服务端明确下发 accountTier=free 时显示;paid、not_applicable 与未知状态不显示标签。"
+ },
{
"id": "harness",
"status": "proposed",
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index 5b546f9690..60b9cf411c 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -694,9 +694,11 @@ describe('provider OAuth and upstream URL validation', () => {
authStrategy: 'oauth-token',
},
};
- catalog.providers[0]!.models = { 'claude-code': [model('m1', { route })] };
+ catalog.providers[0]!.models = {
+ 'claude-code': [model('m1', { route: route as never })],
+ };
} else {
- catalog.providers[0]!.models.codex![0] = model('m1', { route });
+ catalog.providers[0]!.models.codex![0] = model('m1', { route: route as never });
}
expect(() => parseCatalog(catalog)).toThrow(/model\.route invalid/);
});
diff --git a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
index f1b4db14a6..9ef5f6b642 100644
--- a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
+++ b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION,
MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION,
MODEL_ACCESS_MODELS_PATH,
@@ -69,6 +70,15 @@ const VALID_V4_RESPONSE: ListModelsResponse = {
schemaVersion: MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
};
+const VALID_V5_RESPONSE: ListModelsResponse = {
+ schemaVersion: MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
+ accountTier: 'free',
+ models: VALID_V4_RESPONSE.models.map((model) => ({
+ ...model,
+ availability: 'requires_payment',
+ })),
+};
+
const VALID_REGISTRY: ModelRegistry = {
schemaVersion: MODEL_REGISTRY_SCHEMA_VERSION,
updatedAt: '2026-07-31T00:00:00.000Z',
@@ -123,6 +133,21 @@ describe('model access catalog contract', () => {
expect(MODEL_ACCESS_MODELS_PATH).toBe('/api/model-access/models');
});
+ it('parses strict v5 availability and account tier fields', () => {
+ expect(parseListModelsResponse(VALID_V5_RESPONSE)).toEqual({
+ ok: true,
+ value: VALID_V5_RESPONSE,
+ });
+ expectReject({ ...VALID_V5_RESPONSE, accountTier: 'vip' }, 'response.accountTier');
+ expectReject(
+ {
+ ...VALID_V5_RESPONSE,
+ models: [{ ...VALID_V5_RESPONSE.models[0]!, availability: 'unavailable' }],
+ },
+ 'response.models[0].availability',
+ );
+ });
+
it('continues to parse v1 responses, while v1 rejects the v2-only default field', () => {
const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
const legacy = {
@@ -369,7 +394,7 @@ describe('model access catalog contract', () => {
});
it('rejects unsupported schema versions and malformed nested pricing', () => {
- expectReject({ ...VALID_RESPONSE, schemaVersion: 5 }, 'response.schemaVersion');
+ expectReject({ ...VALID_RESPONSE, schemaVersion: 6 }, 'response.schemaVersion');
expectReject(
{
...VALID_RESPONSE,
diff --git a/packages/model-providers/src/__tests__/unifiedSelection.test.ts b/packages/model-providers/src/__tests__/unifiedSelection.test.ts
index fe7f478bd3..0d78bc3c04 100644
--- a/packages/model-providers/src/__tests__/unifiedSelection.test.ts
+++ b/packages/model-providers/src/__tests__/unifiedSelection.test.ts
@@ -922,6 +922,32 @@ describe('unifiedModelEntries', () => {
expect(find(entries, 'zhipu', 'glm-5.2')?.candidates).toEqual(['claude-code', 'codex']);
});
+ it('付费模型仅在显式展示模式下进入联合列表,并保留锁定状态', () => {
+ const gated = view({
+ id: 'xd',
+ models: {
+ 'claude-code': [
+ m('free-model', { availability: 'available' }),
+ m('paid-model', { availability: 'requires_payment' }),
+ ],
+ },
+ });
+
+ expect(
+ unifiedModelEntries({ providers: [gated], isVisible: alwaysVisible }).map(
+ (entry) => entry.modelId,
+ ),
+ ).toEqual(['free-model']);
+
+ const visible = unifiedModelEntries({
+ providers: [gated],
+ isVisible: alwaysVisible,
+ includePaymentRequired: true,
+ });
+ expect(visible.map((entry) => entry.modelId)).toEqual(['free-model', 'paid-model']);
+ expect(find(visible, 'xd', 'paid-model')?.availability).toBe('requires_payment');
+ });
+
it('选中行豁免(keepModel):停用 / retired 的选中条目仍成行,并带上候选与能力', () => {
const mixed = view({
id: 'anthropic',
diff --git a/packages/model-providers/src/classification.ts b/packages/model-providers/src/classification.ts
index 560f38c2f7..c777ab2921 100644
--- a/packages/model-providers/src/classification.ts
+++ b/packages/model-providers/src/classification.ts
@@ -396,12 +396,14 @@ export function isModelSelectableForNewRoute(
mode?: string;
disabled?: boolean;
status?: string;
+ availability?: 'available' | 'requires_payment';
},
opts?: { userProvider?: boolean },
): boolean {
return (
model.disabled !== true &&
model.status !== 'retired' &&
+ model.availability !== 'requires_payment' &&
isAgentSelectableModel(model, opts)
);
}
diff --git a/packages/model-providers/src/modelAccessBean.ts b/packages/model-providers/src/modelAccessBean.ts
index c5dd5f594b..1e8f9f806c 100644
--- a/packages/model-providers/src/modelAccessBean.ts
+++ b/packages/model-providers/src/modelAccessBean.ts
@@ -11,6 +11,7 @@ export const MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION = 1 as const;
export const MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION = 2 as const;
export const MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION = 3 as const;
export const MODEL_ACCESS_CATALOG_SCHEMA_VERSION = 4 as const;
+export const MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION = 5 as const;
export const MODEL_ACCESS_MODELS_PATH = '/api/model-access/models' as const;
export const MODEL_ACCESS_CURRENCIES = ['CNY', 'USD'] as const;
@@ -218,13 +219,22 @@ export interface ModelCatalogEntry extends ModelCatalogEntryBase {
newSessionDefault?: ModelAgent[];
}
+export type ModelAccessAvailability = 'available' | 'requires_payment';
+export type ModelAccessAccountTier = 'free' | 'paid' | 'not_applicable';
+
+export interface ModelCatalogEntryV5 extends ModelCatalogEntry {
+ availability: ModelAccessAvailability;
+}
+
export interface ListModelsResponse {
schemaVersion:
| typeof MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION
| typeof MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION
| typeof MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION
- | typeof MODEL_ACCESS_CATALOG_SCHEMA_VERSION;
+ | typeof MODEL_ACCESS_CATALOG_SCHEMA_VERSION
+ | typeof MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION;
models: ModelCatalogEntry[];
+ accountTier?: ModelAccessAccountTier;
}
export interface ListModelsResponseV1 {
@@ -246,5 +256,11 @@ export interface ListModelsResponseV4 extends ListModelsResponse {
models: Array<ModelCatalogEntry & { name: string }>;
}
+export interface ListModelsResponseV5 extends ListModelsResponse {
+ schemaVersion: typeof MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION;
+ accountTier: ModelAccessAccountTier;
+ models: Array<ModelCatalogEntryV5 & { name: string }>;
+}
+
/** Result returned by local Model Access boundary parsers. */
export type ModelAccessParseResult<T> = { ok: true; value: T } | { ok: false; error: string };
diff --git a/packages/model-providers/src/modelAccessValidator.ts b/packages/model-providers/src/modelAccessValidator.ts
index 811ea412ed..326d5aea85 100644
--- a/packages/model-providers/src/modelAccessValidator.ts
+++ b/packages/model-providers/src/modelAccessValidator.ts
@@ -2,6 +2,7 @@ import {
MODEL_ACCESS_AGENTS,
MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION,
MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION,
MODEL_ACCESS_CURRENCIES,
@@ -666,18 +667,62 @@ export function parseListModelsResponse(
value: unknown,
): ModelAccessParseResult<ListModelsResponse> {
if (!isPlainObject(value)) return fail('response must be an object');
- const unknownField = unknownFieldError(value, LIST_MODELS_RESPONSE_FIELDS, 'response');
- if (unknownField) return fail(unknownField);
if (
value.schemaVersion !== MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION &&
value.schemaVersion !== MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION &&
value.schemaVersion !== MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION &&
- value.schemaVersion !== MODEL_ACCESS_CATALOG_SCHEMA_VERSION
+ value.schemaVersion !== MODEL_ACCESS_CATALOG_SCHEMA_VERSION &&
+ value.schemaVersion !== MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION
) {
return fail(
- `response.schemaVersion must be ${MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION}, ${MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION}, ${MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION}, or ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}`,
+ `response.schemaVersion must be ${MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION}, ${MODEL_ACCESS_CATALOG_V2_SCHEMA_VERSION}, ${MODEL_ACCESS_CATALOG_V3_SCHEMA_VERSION}, ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}, or ${MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION}`,
);
}
+ if (value.schemaVersion === MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION) {
+ const unknownField = unknownFieldError(
+ value,
+ ['schemaVersion', 'accountTier', 'models'],
+ 'response',
+ );
+ if (unknownField) return fail(unknownField);
+ if (!['free', 'paid', 'not_applicable'].includes(String(value.accountTier))) {
+ return fail('response.accountTier must be free, paid, or not_applicable');
+ }
+ if (!Array.isArray(value.models)) return fail('response.models must be an array');
+ const modelIds = new Set<string>();
+ const models: unknown[] = [];
+ for (const [index, raw] of value.models.entries()) {
+ if (!isPlainObject(raw)) return fail(`response.models[${index}] must be an object`);
+ if (raw.availability !== 'available' && raw.availability !== 'requires_payment') {
+ return fail(`response.models[${index}].availability must be available or requires_payment`);
+ }
+ const { availability, ...legacyShape } = raw;
+ const sanitized = sanitizeModelEntryAgents(
+ legacyShape,
+ MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ );
+ if (isPlainObject(sanitized) && typeof sanitized.id === 'string') {
+ if (modelIds.has(sanitized.id)) {
+ return fail(`response.models[${index}].id must be unique`);
+ }
+ modelIds.add(sanitized.id);
+ }
+ const error = modelEntryError(
+ sanitized,
+ `response.models[${index}]`,
+ MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ );
+ if (error) return fail(error);
+ models.push({ ...(sanitized as PlainObject), availability });
+ }
+ return ok({
+ schemaVersion: MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
+ accountTier: value.accountTier,
+ models,
+ } as ListModelsResponse);
+ }
+ const unknownField = unknownFieldError(value, LIST_MODELS_RESPONSE_FIELDS, 'response');
+ if (unknownField) return fail(unknownField);
const schemaVersion = value.schemaVersion as ModelCatalogSchemaVersion;
if (!Array.isArray(value.models)) return fail('response.models must be an array');
const models = value.models.map((model) => sanitizeModelEntryAgents(model, schemaVersion));
diff --git a/packages/model-providers/src/modelList.ts b/packages/model-providers/src/modelList.ts
index 4abfd0bfcd..e8bbfc31a7 100644
--- a/packages/model-providers/src/modelList.ts
+++ b/packages/model-providers/src/modelList.ts
@@ -99,6 +99,8 @@ export interface DeriveModelListOptions {
* 的空选态(分段选择器契约)。providerId 为 null 时按 model id 匹配任意供应商行。
*/
keepSelected?: { providerId: string | null; modelId: string };
+ /** UI-only catalog rows may include paid-locked models; execution callers must keep false. */
+ includePaymentRequired?: boolean;
}
function resolveRail(
@@ -140,6 +142,7 @@ export function deriveModelList(opts: DeriveModelListOptions): ModelListEntry[]
excludeProvider,
excludeModel,
keepSelected,
+ includePaymentRequired = false,
} = opts;
// first-wins 的占坑表直接记「id → 首见行在 out 里的下标」,选中行替换时 O(1) 定位
@@ -162,7 +165,7 @@ export function deriveModelList(opts: DeriveModelListOptions): ModelListEntry[]
return entry;
};
const userProvider = provider.source === 'user';
- const selectable = selected
+ const selectable = selected || (includePaymentRequired && m.availability === 'requires_payment')
? isAgentSelectableModel(m, { userProvider })
: isModelSelectableForNewRoute(m, { userProvider });
if (!selectable) continue;
@@ -210,6 +213,7 @@ export function deriveModelSections(
excludeProvider,
excludeModel,
keepSelected,
+ includePaymentRequired = false,
} = opts;
const q = (opts.query ?? '').trim().toLowerCase();
@@ -221,7 +225,7 @@ export function deriveModelSections(
if (excludeModel?.(m, provider)) continue;
const selected = matchesSelected(keepSelected, provider.id, m.id);
const userProvider = provider.source === 'user';
- const selectable = selected
+ const selectable = selected || (includePaymentRequired && m.availability === 'requires_payment')
? isAgentSelectableModel(m, { userProvider })
: isModelSelectableForNewRoute(m, { userProvider });
if (!selectable) continue;
diff --git a/packages/model-providers/src/sections.ts b/packages/model-providers/src/sections.ts
index e4c04cd4d6..8a71e23f37 100644
--- a/packages/model-providers/src/sections.ts
+++ b/packages/model-providers/src/sections.ts
@@ -45,6 +45,7 @@ export interface SectionModel {
contextWindow: number;
/** 展示图标 id(AI Gateway / 目录设定,见 CatalogModel.icon);缺省回落来源供应商标。 */
icon?: string;
+ availability?: CatalogModel['availability'];
}
export interface ProviderSection {
@@ -143,6 +144,7 @@ export function buildProviderSections(args: {
selectedProviderId?: string | null;
isVisible: (providerId: string, modelId: string) => boolean;
query?: string;
+ includePaymentRequired?: boolean;
}): ProviderSection[] {
// 薄壳: 标准分段派生(modelList.ts)+ SectionModel 字段投影。历史语义逐项保持:
// - providerScope 'as-given': 本函数从不收窄供应商(调用方已自行收窄),薄壳不得
@@ -166,6 +168,7 @@ export function buildProviderSections(args: {
? { keepSelected: { providerId: args.selectedProviderId, modelId: args.selectedModelId } }
: {}),
...(args.query !== undefined ? { query: args.query } : {}),
+ includePaymentRequired: args.includePaymentRequired === true,
});
return sections.map(({ provider, models }) => ({
provider,
@@ -186,6 +189,7 @@ export function buildProviderSections(args: {
sm.codexCompatibilityWireProtocol = m.codexCompatibilityWireProtocol;
}
if (m.icon !== undefined) sm.icon = m.icon;
+ if (m.availability !== undefined) sm.availability = m.availability;
return sm;
}),
}));
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 0e5be112da..5367c97603 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -264,6 +264,8 @@ export interface ModelCost {
export interface CatalogModel {
/** 与 maker-core 现有 model id 一致(如 'claude-opus-4-8' / 'gpt-5.5' / 'codex/gpt-5.5')。 */
id: string;
+ /** Server entitlement state. Paid-locked models remain present for UI but are never routable. */
+ availability?: 'available' | 'requires_payment';
/** Sparse PI protocol override; absence means use PI's bundled model catalog. */
piApi?: PiModelApi;
/** 同一 provider/runtime 内该模型的上游覆盖;缺省使用 provider 级路由。 */
@@ -432,6 +434,7 @@ export interface CatalogModel {
export interface ProviderMediaModel {
id: string;
name: string;
+ availability?: 'available' | 'requires_payment';
modalities?: { input: string[]; output: string[] };
officialDocs?: string;
disabled?: boolean;
diff --git a/packages/model-providers/src/unifiedSelection.ts b/packages/model-providers/src/unifiedSelection.ts
index a0fccbd159..72a0c19866 100644
--- a/packages/model-providers/src/unifiedSelection.ts
+++ b/packages/model-providers/src/unifiedSelection.ts
@@ -482,6 +482,8 @@ export interface UnifiedModelEntry {
sortOrder?: number;
/** 展示图标 id(`CatalogModel.icon`;缺省由渲染层回落供应商标)。 */
icon?: string;
+ /** 服务端 v5 下发的个人模型可用性;requires_payment 只展示,不可作为新路由。 */
+ availability?: CatalogModel['availability'];
/** 候选引擎,按 `UNIFIED_AGENT_PRIORITY` 序。恒 ≥1。 */
candidates: AgentKind[];
/** 推荐引擎,恒 ∈ candidates。 */
@@ -513,6 +515,8 @@ export interface UnifiedModelEntriesOptions {
excludeProvider?: (provider: ProviderView, agent: AgentKind) => boolean;
/** 单模型排除(SSH 远程排除订阅直连前缀等)。 */
excludeModel?: (model: CatalogModel, provider: ProviderView, agent: AgentKind) => boolean;
+ /** 是否把 requires_payment 模型保留为只读展示行;缺省 false。 */
+ includePaymentRequired?: boolean;
/** 来源解析口径,默认 `'draft'`。 */
scope?: SourceResolutionScope;
/**
@@ -585,6 +589,7 @@ export function unifiedModelEntries(opts: UnifiedModelEntriesOptions): UnifiedMo
isVisible,
excludeProvider,
excludeModel,
+ includePaymentRequired = false,
scope = 'draft',
keepModel,
} = opts;
@@ -681,6 +686,7 @@ export function unifiedModelEntries(opts: UnifiedModelEntriesOptions): UnifiedMo
...(keepModel && keepModel.agent === agent
? { keepSelected: { providerId: keepModel.providerId, modelId: keepModel.modelId } }
: {}),
+ includePaymentRequired,
});
for (const row of rows) {
const keyModelId = unifiedModelKeyId(row.id);
@@ -732,7 +738,10 @@ export function unifiedModelEntries(opts: UnifiedModelEntriesOptions): UnifiedMo
const wireId = draft.wireIds[agent];
if (wireId === undefined) continue;
const keptAgent = draft.kept && keepModel?.agent === agent;
- if (!keptAgent) {
+ const paymentRequired =
+ includePaymentRequired &&
+ findCatalogModel(provider, wireId, agent)?.availability === 'requires_payment';
+ if (!keptAgent && !paymentRequired) {
const sourceId = resolveSourceId(providers, draft.providerId, wireId, agent, scope);
if (sourceId !== draft.providerId) continue;
}
@@ -755,6 +764,7 @@ export function unifiedModelEntries(opts: UnifiedModelEntriesOptions): UnifiedMo
...(display?.group !== undefined ? { group: display.group } : {}),
...(display?.sortOrder !== undefined ? { sortOrder: display.sortOrder } : {}),
...(display?.icon !== undefined ? { icon: display.icon } : {}),
+ ...(display?.availability !== undefined ? { availability: display.availability } : {}),
candidates,
recommended,
nativeAgent: nativeAgentForProviderModel(provider, draft.keyModelId),