Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 设置页模型列表补价格与折扣,复杂配置收进高级设置抽屉
Chris28c35913a57b
diff --git a/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.tsnew file mode 100644index 0000000000..52d008e14e--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts@@ -0,0 +1,183 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { beforeEach, describe, expect, it, vi } from 'vitest';++const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-model-context-limit-'));++vi.mock('electron', () => ({+ app: { getPath: vi.fn(() => tempRoot) },+}));++vi.mock('../logger-adapter.js', () => ({+ desktopMakerLogger: {+ child: () => ({ info: vi.fn(), warn: vi.fn() }),+ },+}));++vi.mock('../../appSessionState.js', () => ({+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'test-owner', generation: 1 }),+ ownerScopedUserDataPath: (...parts: string[]) => path.join(tempRoot, ...parts),+}));++import {+ __testing,+ applyModelContextLimit,+ isModelContextLimitCustomized,+ modelContextLimitKey,+ readModelContextLimit,+ readModelContextLimits,+ resetModelContextLimits,+ writeModelContextLimit,+} from '../model-context-limit-store';++const PREFS = path.join(tempRoot, 'model-context-limit-prefs.json');++function writeRawPrefs(value: unknown): void {+ fs.writeFileSync(PREFS, JSON.stringify(value), 'utf-8');+ __testing.invalidate();+}++describe('model context limit store', () => {+ beforeEach(() => {+ fs.mkdirSync(tempRoot, { recursive: true });+ if (fs.existsSync(PREFS)) fs.unlinkSync(PREFS);+ __testing.invalidate();+ });++ it('未设置时不落盘、不视为自定义', () => {+ expect(readModelContextLimit('claude-code', 'anthropic', 'claude-opus-5')).toBeNull();+ expect(isModelContextLimitCustomized('claude-code', 'anthropic', 'claude-opus-5')).toBe(false);+ expect(fs.existsSync(PREFS)).toBe(false);+ });++ it('写入后只存 override 条目,不快照默认值', () => {+ writeModelContextLimit('claude-code', 'anthropic', 'claude-opus-5', 500_000);+ expect(readModelContextLimit('claude-code', 'anthropic', 'claude-opus-5')).toBe(500_000);+ expect(isModelContextLimitCustomized('claude-code', 'anthropic', 'claude-opus-5')).toBe(true);+ const raw: unknown = JSON.parse(fs.readFileSync(PREFS, 'utf-8'));+ expect(raw).toEqual({+ limits: { [modelContextLimitKey('claude-code', 'anthropic', 'claude-opus-5')]: 500_000 },+ });+ });++ it('键含 agent:同一模型在不同引擎下互不影响', () => {+ writeModelContextLimit('claude-code', 'xd', 'gpt-5.6-sol', 500_000);+ expect(readModelContextLimit('codex', 'xd', 'gpt-5.6-sol')).toBeNull();+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 272_000);+ expect(readModelContextLimit('claude-code', 'xd', 'gpt-5.6-sol')).toBe(500_000);+ expect(readModelContextLimit('codex', 'xd', 'gpt-5.6-sol')).toBe(272_000);+ });++ it('写 null = 恢复默认:删条目而不是写一个默认值快照', () => {+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 272_000);+ expect(writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', null)).toBeNull();+ expect(isModelContextLimitCustomized('codex', 'xd', 'gpt-5.6-sol')).toBe(false);+ // 最后一个条目被删掉后整份 override 文件应当消失(= 完全跟随默认)。+ expect(fs.existsSync(PREFS)).toBe(false);+ });++ it('删掉一个条目不影响其它条目', () => {+ writeModelContextLimit('codex', 'xd', 'a', 100_000);+ writeModelContextLimit('codex', 'xd', 'b', 200_000);+ writeModelContextLimit('codex', 'xd', 'a', null);+ expect(readModelContextLimit('codex', 'xd', 'a')).toBeNull();+ expect(readModelContextLimit('codex', 'xd', 'b')).toBe(200_000);+ });++ it('低于下限的值不落盘(会让压缩在第一条消息就触发)', () => {+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 10);+ expect(readModelContextLimit('codex', 'xd', 'gpt-5.6-sol')).toBeNull();+ expect(fs.existsSync(PREFS)).toBe(false);+ });++ it('小数取整、荒谬量级收敛到上限', () => {+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 272_000.6);+ expect(readModelContextLimit('codex', 'xd', 'gpt-5.6-sol')).toBe(272_001);+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 1e12);+ expect(readModelContextLimit('codex', 'xd', 'gpt-5.6-sol')).toBe(__testing.MAX_LIMIT_TOKENS);+ });++ it('不 clamp 到模型窗口:路由配错时用户能强行往上填', () => {+ // 上游窗口 272K,用户填 1M —— 必须原样存下来(UI 侧给警示,不在这里拦)。+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 1_024_000);+ expect(readModelContextLimit('codex', 'xd', 'gpt-5.6-sol')).toBe(1_024_000);+ expect(applyModelContextLimit(272_000, 'codex', 'xd', 'gpt-5.6-sol')).toBe(272_000);+ });++ it('手改文件后下一次读取生效(隐藏配置也是正式契约)', () => {+ writeRawPrefs({ limits: { [modelContextLimitKey('codex', 'xd', 'm')]: 300_000 } });+ expect(readModelContextLimit('codex', 'xd', 'm')).toBe(300_000);+ });++ it('文件里的坏条目被丢弃 = 跟随默认,不污染同文件其它条目', () => {+ writeRawPrefs({+ limits: {+ [modelContextLimitKey('codex', 'xd', 'ok')]: 300_000,+ [modelContextLimitKey('codex', 'xd', 'nan')]: 'not-a-number',+ [modelContextLimitKey('codex', 'xd', 'zero')]: 0,+ [modelContextLimitKey('codex', 'xd', 'negative')]: -5,+ '': 400_000,+ },+ });+ expect(readModelContextLimit('codex', 'xd', 'ok')).toBe(300_000);+ expect(readModelContextLimit('codex', 'xd', 'nan')).toBeNull();+ expect(readModelContextLimit('codex', 'xd', 'zero')).toBeNull();+ expect(readModelContextLimit('codex', 'xd', 'negative')).toBeNull();+ expect(Object.keys(readModelContextLimits())).toHaveLength(1);+ });++ it('整体 reset 清空全部 override', () => {+ writeModelContextLimit('codex', 'xd', 'a', 100_000);+ writeModelContextLimit('claude-code', 'anthropic', 'b', 200_000);+ resetModelContextLimits();+ expect(readModelContextLimits()).toEqual({});+ expect(fs.existsSync(PREFS)).toBe(false);+ });+});++/**+ * 这一组是本轮唯一会改变现有运行时行为的点,必须锁死:**没有 override 的用户,+ * 窗口值逐位不变**。否则所有未自定义用户的压缩时机都会被静默改掉。+ */+describe('applyModelContextLimit:未自定义用户行为不变', () => {+ beforeEach(() => {+ if (fs.existsSync(PREFS)) fs.unlinkSync(PREFS);+ __testing.invalidate();+ });++ it('无 override 时原样返回上游窗口', () => {+ for (const window of [200_000, 272_000, 1_000_000, 1_048_576, 1_050_000]) {+ expect(applyModelContextLimit(window, 'codex', 'xd', 'gpt-5.6-sol')).toBe(window);+ }+ });++ it('有 override 时取两者更小值', () => {+ writeModelContextLimit('claude-code', 'anthropic', 'claude-opus-5', 500_000);+ expect(applyModelContextLimit(1_000_000, 'claude-code', 'anthropic', 'claude-opus-5')).toBe(+ 500_000,+ );+ // 上限比窗口大时不放大窗口 —— 只能收紧,不能凭 override 声称模型能装更多。+ expect(applyModelContextLimit(200_000, 'claude-code', 'anthropic', 'claude-opus-5')).toBe(+ 200_000,+ );+ });++ it('override 属于另一个引擎时不生效', () => {+ writeModelContextLimit('claude-code', 'anthropic', 'claude-opus-5', 500_000);+ expect(applyModelContextLimit(1_000_000, 'codex', 'anthropic', 'claude-opus-5')).toBe(+ 1_000_000,+ );+ });++ it('目标信息不全或窗口本身不可用时原样返回,不拿上限顶替', () => {+ writeModelContextLimit('codex', 'xd', 'gpt-5.6-sol', 100_000);+ expect(applyModelContextLimit(1_000_000, null, 'xd', 'gpt-5.6-sol')).toBe(1_000_000);+ expect(applyModelContextLimit(1_000_000, 'codex', null, 'gpt-5.6-sol')).toBe(1_000_000);+ expect(applyModelContextLimit(1_000_000, 'codex', 'xd', null)).toBe(1_000_000);+ expect(applyModelContextLimit(0, 'codex', 'xd', 'gpt-5.6-sol')).toBe(0);+ expect(applyModelContextLimit(-1, 'codex', 'xd', 'gpt-5.6-sol')).toBe(-1);+ expect(applyModelContextLimit(Number.NaN, 'codex', 'xd', 'gpt-5.6-sol')).toBeNaN();+ });+});diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 0dcc6e9c14..d208f5f352 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -110,6 +110,7 @@ import {resolvePiGatewayDescriptorProviderId,resolveVerifiedContextWindow,} from './catalog-to-descriptors.js';+import { applyModelContextLimit } from './model-context-limit-store.js';import { buildPiAgent } from './pi-host.js';import {captureLocalPiPackageRuntimeInvalidationSnapshot,@@ -981,8 +982,20 @@ export function getMaker(): Maker {capabilityAdditions: {availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'claude-code'),},- resolveVerifiedContextWindow: (providerId, modelId) =>- resolveVerifiedContextWindow(getDesktopSelectableCatalog(), 'claude-code', providerId, modelId),+ // 用户在「模型高级设置 → 上下文上限」填的值在这里收敛进去:窗口是自动压缩比例的+ // 分母,调小它就等于让压缩按用户设的长度提前触发(阈值百分比不动)。没设过时+ // applyModelContextLimit 逐位返回原值 —— 未自定义用户行为完全不变。+ resolveVerifiedContextWindow: (providerId, modelId) => {+ const verified = resolveVerifiedContextWindow(+ getDesktopSelectableCatalog(),+ 'claude-code',+ providerId,+ modelId,+ );+ return verified === null+ ? null+ : applyModelContextLimit(verified, 'claude-code', providerId, modelId);+ },// SDK PreToolUse / PostToolUse 等 in-process hook 注入点。host 自己定义 hook// 实现 (./claude-hooks/*.ts), maker-core 不感知具体逻辑。//@@ -1297,8 +1310,18 @@ export function getMaker(): Maker {// 把 app-server 上报的上下文窗口收敛到该**路由**真实上限。每次调用读 live 目录:// 模型发现 / 切账号 / 自定义 provider 增删改都要即时反映。按 providerId 定夺而不是// 让 agent 按 id 回查 availableModels —— 那张表去重后 provider 归属已丢。- resolveVerifiedContextWindow: (providerId, modelId) =>- resolveVerifiedContextWindow(getDesktopSelectableCatalog(), 'codex', providerId, modelId),+ // 同 claude-code 那一路:用户上限在这里收敛进窗口(见该处注释)。+ resolveVerifiedContextWindow: (providerId, modelId) => {+ const verified = resolveVerifiedContextWindow(+ getDesktopSelectableCatalog(),+ 'codex',+ providerId,+ modelId,+ );+ return verified === null+ ? null+ : applyModelContextLimit(verified, 'codex', providerId, modelId);+ },onCodexLocalModelsListed: (models) => {setDiscoveredCodexModels(mapCodexAppServerModelsToCatalog(models));},diff --git a/apps/desktop/src/main/maker-host/model-context-limit-store.ts b/apps/desktop/src/main/maker-host/model-context-limit-store.tsnew file mode 100644index 0000000000..6133b9ff00--- /dev/null+++ b/apps/desktop/src/main/maker-host/model-context-limit-store.ts@@ -0,0 +1,219 @@+/**+ * model-context-limit-store —— 「单模型上下文上限」override 的持久化(main 侧唯一真源)。+ *+ * File: <userData>/model-context-limit-prefs.json+ * 形态:{ limits: { "<agent>:<providerId>:<modelId>": 272000 } }+ *+ * ## 这个设置解决什么+ *+ * 自动压缩的触发是「已用 token / 上下文窗口 ≥ 阈值百分比」。阈值百分比用户能调+ * (设置 → 个性化,compaction-settings-store,默认 90),但**分母**是模型窗口,由路由钉死:+ * Claude 给 1M、GPT 给 272K,用户想「这个模型我只想用到 500K 就开始压缩」无从下手 ——+ * 调百分比会同时影响所有模型,且换算成 token 数还得自己算。+ *+ * 所以这里存的是**分母的用户上限**:运行期窗口取 min(上游回报窗口, 用户上限),+ * 比例随之变大,压缩按用户设的长度提前发生。阈值百分比不动。+ *+ * ## 为什么在 main 而不是 renderer localStorage+ *+ * 与 model-disable-store 同一条理由:它参与**运行期判定**,而判定发生在 main+ * (runtime-configs 的窗口评估),renderer 窗口可能根本不存在(MCP / IM hook / scheduler+ * 起的会话)。对比 modelVisibilityPrefs —— 那个纯粹影响 renderer 的选择器陈列,留在+ * renderer 是对的。+ *+ * ## override 语义(docs/dev-rules/configuration-and-overrides.md)+ *+ * - 只存用户显式设过的条目;缺席 = 跟随路由窗口。新模型、路由改窗口都天然跟随新默认。+ * - 「恢复默认」= 删除该条目(不是写一个当前默认值的快照),所以上游把窗口从 272K 放到+ * 1M 时,没自定义过的用户直接吃到 1M。+ * - `isCustomizedFor()` 让 UI 能区分「跟随默认」与「用户设过且刚好等于默认」。+ *+ * ## 为什么不设硬上限+ *+ * 值只 clamp 下限(见 MIN_LIMIT_TOKENS),**不 clamp 到模型窗口**:路由把窗口配错(下发+ * 值小于模型实际能力)时,用户得能强行往上填把自己解开;UI 侧超过上游窗口会给警示。+ * 上限只挡明显荒谬的量级(MAX_LIMIT_TOKENS),避免写进一个天文数字让比例判定失效。+ */++import type { AgentKind } from '@cindy/model-providers';++import { desktopMakerLogger } from './logger-adapter.js';+import { createOverrideSettingsFile } from './override-settings-file.js';+import { ownerScopedUserDataPath } from '../appSessionState.js';++const log = desktopMakerLogger.child('model-context-limit');++/** 低于这个数压缩会在第一条消息就触发,等于让会话不可用 —— 视为误输入。 */+const MIN_LIMIT_TOKENS = 1_000;+/**+ * 上限只挡量级荒谬(比当前最大窗口高两个数量级以上)。它不是「模型能力上限」——+ * 那个由 UI 提示,不由这里拦(见头注「为什么不设硬上限」)。+ */+const MAX_LIMIT_TOKENS = 100_000_000;+/**+ * 条目总量硬上限(深防线,同 model-disable-store):正常路径有 IPC 边界校验,这里兜的是+ * 「绕过 IPC 直改文件 / 未来新增写入口漏校验」,防止这份同步读写的 JSON 无界膨胀拖死+ * main。取目录现实规模(数百条路由 × 3 引擎)的一个数量级以上。+ */+const MAX_ENTRIES = 4096;++export interface ModelContextLimitPrefs {+ limits: Record<string, number>;+}++const DEFAULTS: ModelContextLimitPrefs = { limits: {} };++/** 键含 agent —— 同一模型在不同引擎下窗口本就可能不同(registry 的 perAgent.contextWindow)。 */+export function modelContextLimitKey(+ agent: AgentKind,+ providerId: string,+ modelId: string,+): string {+ return `${agent}:${providerId}:${modelId}`;+}++function clampLimit(value: unknown): number | null {+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;+ const rounded = Math.round(value);+ if (rounded < MIN_LIMIT_TOKENS) return null;+ return Math.min(MAX_LIMIT_TOKENS, rounded);+}++/**+ * 只收「非空 key + 可 clamp 成合法 token 数」的条目;其它形态一律丢弃 = 跟随默认。+ * 读入也截断:写入路径的上限挡不住手改 / 灌大文件,不截断的话超大 map 会被完整持有+ * 并在下次 writePatch 原样重写放大。超限部分按遍历序丢弃(= 跟随默认,无副作用)。+ */+function sanitizeLimits(raw: unknown): Record<string, number> {+ const out: Record<string, number> = {};+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {+ let kept = 0;+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {+ if (!key) continue;+ const limit = clampLimit(value);+ if (limit === null) continue;+ if (kept >= MAX_ENTRIES) {+ log.warn('model context limit prefs truncated at hard cap on read', { cap: MAX_ENTRIES });+ break;+ }+ out[key] = limit;+ kept += 1;+ }+ }+ return out;+}++function normalize(raw: unknown): ModelContextLimitPrefs {+ if (!raw || typeof raw !== 'object') return { limits: {} };+ return { limits: sanitizeLimits((raw as { limits?: unknown }).limits) };+}++const store = createOverrideSettingsFile<ModelContextLimitPrefs>({+ filePath: () => ownerScopedUserDataPath('model-context-limit-prefs.json'),+ defaults: DEFAULTS,+ normalize,+ log,+ label: 'model-context-limit',+});++function readPrefs(): ModelContextLimitPrefs {+ // 隐藏配置层级的文件也是正式契约:mtime 守卫让「直接手改文件」在下一次读取生效。+ store.invalidateIfChanged();+ return store.read();+}++/** 全部 override 快照。 */+export function readModelContextLimits(): Record<string, number> {+ return readPrefs().limits;+}++/** 某个 (引擎, 供应商, 模型) 的用户上限;未设过返回 null。 */+export function readModelContextLimit(+ agent: AgentKind,+ providerId: string,+ modelId: string,+): number | null {+ if (!providerId || !modelId) return null;+ return readPrefs().limits[modelContextLimitKey(agent, providerId, modelId)] ?? null;+}++/** UI 用:这一条是否被用户显式设过(区分「跟随默认」与「设了一个刚好等于默认的值」)。 */+export function isModelContextLimitCustomized(+ agent: AgentKind,+ providerId: string,+ modelId: string,+): boolean {+ if (!providerId || !modelId) return false;+ return modelContextLimitKey(agent, providerId, modelId) in readPrefs().limits;+}++/**+ * 运行期窗口收敛:把用户上限套到上游回报的窗口上。+ *+ * **没有 override 时必须逐位返回原窗口** —— 这是「未自定义用户行为完全不变」的唯一+ * 保证点,单测锁住它。上游窗口本身不可用(0 / 负 / 非数)时也原样返回,不拿用户上限+ * 顶替:那种情况下调用方另有兜底,这里替它决定会掩盖真实问题。+ */+export function applyModelContextLimit(+ contextWindow: number,+ agent: AgentKind | null | undefined,+ providerId: string | null | undefined,+ modelId: string | null | undefined,+): number {+ if (!Number.isFinite(contextWindow) || contextWindow <= 0) return contextWindow;+ if (!agent || !providerId || !modelId) return contextWindow;+ const limit = readModelContextLimit(agent, providerId, modelId);+ if (limit === null) return contextWindow;+ return Math.min(contextWindow, limit);+}++/**+ * 写一条上限。`limit === null` = 恢复默认(删除条目),与「恢复默认 = 删 override」一致。+ * 返回落盘后该条目的有效值(null = 已跟随默认)。+ */+export function writeModelContextLimit(+ agent: AgentKind,+ providerId: string,+ modelId: string,+ limit: number | null,+): number | null {+ if (!providerId || !modelId) return null;+ store.invalidateIfChanged();+ const key = modelContextLimitKey(agent, providerId, modelId);+ const limits = { ...store.read().limits };+ if (limit === null) {+ if (!(key in limits)) return null;+ delete limits[key];+ store.writePatch({ limits });+ log.info('model context limit cleared', { agent, providerId });+ return null;+ }+ const next = clampLimit(limit);+ if (next === null) {+ log.warn('model context limit rejected: not a usable token count', { agent, providerId });+ return limits[key] ?? null;+ }+ if (limits[key] === next) return next;+ if (!(key in limits) && Object.keys(limits).length >= MAX_ENTRIES) {+ log.warn('model context limit dropped: at hard cap', { agent, providerId, cap: MAX_ENTRIES });+ return null;+ }+ limits[key] = next;+ store.writePatch({ limits });+ log.info('model context limit written', { agent, providerId, limit: next });+ return next;+}++/** 清空全部上限 override(供应商级 / 整体「恢复默认」用)。 */+export function resetModelContextLimits(): void {+ store.reset();+}++export const __testing = {+ MIN_LIMIT_TOKENS,+ MAX_LIMIT_TOKENS,+ MAX_ENTRIES,+ invalidate(): void {+ store.invalidateIfChanged();+ },+};diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 7df09fed6b..4bf8234493 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -253,6 +253,15 @@ export const MAKER_INVOKE = {MODEL_PRICE_OVERRIDE_GET: 'maker:model-price-override:get',MODEL_PRICE_OVERRIDE_SET: 'maker:model-price-override:set',MODEL_PRICE_OVERRIDE_RESET: 'maker:model-price-override:reset',+ /**+ * 单模型上下文上限 override(设置 → 模型 → 高级设置)。窗口是自动压缩比例的分母,+ * 调小它让压缩按用户设的长度提前触发。与价格 override 同一个 (providerId, agent,+ * modelId) 目标形状。设置类写操作:仅本机主页面可调,**不进 device-link allowlist**+ * (远程改被控端全局设置越权)。+ */+ MODEL_CONTEXT_LIMIT_GET: 'maker:model-context-limit:get',+ MODEL_CONTEXT_LIMIT_SET: 'maker:model-context-limit:set',+ MODEL_CONTEXT_LIMIT_RESET: 'maker:model-context-limit:reset',// 附加只读引用目录 — 走 closure 推送; DB 持久化由 renderer 同步调// local-db:sessions:update (跟 SET_MODEL / sessionService.update 双 IPC 协调先例一致)SET_EXTRA_DIRS: 'maker:set-extra-dirs',diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 7a11419d84..dd5dae22cb 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -391,6 +391,20 @@ export interface ProviderHandlerDeps {clearModelPriceOverride(target: ModelPriceOverrideTarget): void;stageClearProviderModelPriceOverrides?(providerId: string): () => boolean;broadcastPricingChanged(): void;+ /**+ * 单模型上下文上限 override。与价格 override 共用 target 形状 (providerId, agent, modelId)。+ * read 返回 `{ limit, isCustomized }`:limit=null 表示跟随路由窗口;isCustomized 让 UI+ * 能区分「跟随默认」与「设了一个刚好等于默认的值」。write 传 null = 恢复默认(删 override)。+ * 可选 —— 未注入(单测最小桩)时对应 handler 报 INTERNAL 而不是静默成功。+ */+ readModelContextLimit?(target: ModelPriceOverrideTarget): ModelContextLimitView;+ writeModelContextLimit?(target: ModelPriceOverrideTarget, limit: number | null): void;+}++/** 上下文上限的读回视图(与写入返回同形,UI 一次拿齐当前值与是否自定义)。 */+export interface ModelContextLimitView {+ limit: number | null;+ isCustomized: boolean;}/** 校验 PROVIDER_TEST_CONNECTION 入参形状(确定性代码校验,非法直接 INVALID_PARAMS)。 */@@ -1439,6 +1453,96 @@ export function registerProviderHandlers();});+ // ── 单模型上下文上限 ────────────────────────────────────────────────────────+ // 复用价格 override 的 target 解析与写入串行队列:两者都是 (provider, agent, model)+ // 粒度的设置类写入,同一把队列避免两种 override 交错落盘。+ const requireContextLimitDeps = (): {+ read: NonNullable<ProviderHandlerDeps['readModelContextLimit']>;+ write: NonNullable<ProviderHandlerDeps['writeModelContextLimit']>;+ } => {+ if (!deps.readModelContextLimit || !deps.writeModelContextLimit) {+ throwIpcError('INTERNAL', 'model context limit override is not wired');+ }+ return { read: deps.readModelContextLimit, write: deps.writeModelContextLimit };+ };++ registry.handle(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_GET, async (event, input: unknown) => {+ assertTrustedProviderMutationSender(event);+ const target = parsePriceTarget(input);+ const { read } = requireContextLimitDeps();+ // 读不做目录成员校验:目录漂移后 UI 仍要能显示并清掉指向已下架 id 的陈旧 override。+ return read(target);+ });++ registry.handle(+ MAKER_INVOKE.MODEL_CONTEXT_LIMIT_SET,+ async (event, targetInput: unknown, limitInput: unknown) => {+ assertTrustedProviderMutationSender(event);+ const target = parsePriceTarget(targetInput);+ const { read, write } = requireContextLimitDeps();+ // null = 恢复默认(删 override)。数值只挡「不是可用 token 数」这一类形状错误;+ // **不 clamp 到模型窗口** —— 路由把窗口配错时用户得能强行往上填(UI 侧给警示)。+ if (+ limitInput !== null &&+ (typeof limitInput !== 'number' || !Number.isFinite(limitInput) || limitInput <= 0)+ ) {+ throwIpcError('INVALID_PARAMS', 'context limit must be a positive number or null');+ }+ const limit = limitInput as number | null;+ const ownerAtIngress = captureProviderOwnerSession();+ return withProviderConfigMutation(target.providerId, () =>+ enqueuePriceMutation(async () => {+ // 写入才校验目标在目录里:挡「合法长度但不存在的 id」被批量预埋进这份+ // 无界 key-value 文件(与停用轴同一条防线)。+ if (limit !== null) await requirePriceTargetModel(target);+ assertProviderMutationOwner(+ ownerAtIngress,+ 'active account changed before persisting context limit override',+ );+ try {+ write(target, limit);+ } catch (err) {+ log.warn('model context limit persist failed', {+ providerId: target.providerId,+ agent: target.agent,+ modelId: target.modelId,+ error: err instanceof Error ? err.message : String(err),+ });+ throwIpcError('INTERNAL', 'failed to persist model context limit');+ }+ return read(target);+ }),+ );+ },+ );++ registry.handle(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_RESET, async (event, input: unknown) => {+ assertTrustedProviderMutationSender(event);+ const target = parsePriceTarget(input);+ const { read, write } = requireContextLimitDeps();+ const ownerAtIngress = captureProviderOwnerSession();+ return withProviderConfigMutation(target.providerId, () =>+ enqueuePriceMutation(async () => {+ assertProviderMutationOwner(+ ownerAtIngress,+ 'active account changed before resetting context limit override',+ );+ try {+ write(target, null);+ } catch (err) {+ log.warn('model context limit reset failed', {+ providerId: target.providerId,+ agent: target.agent,+ modelId: target.modelId,+ error: err instanceof Error ? err.message : String(err),+ });+ throwIpcError('INTERNAL', 'failed to reset model context limit');+ }+ return read(target);+ }),+ );+ });+registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE,async (event, input: unknown, keyInput?: unknown, optionsInput?: unknown) => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 3d4ca82af3..43ae5c0af0 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -833,6 +833,11 @@ import {import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';import { readCompactionPct } from '../maker-host/compaction-settings-store.js';import { resolveVerifiedContextWindow } from '../maker-host/catalog-to-descriptors.js';+import {+ isModelContextLimitCustomized,+ readModelContextLimit,+ writeModelContextLimit,+} from '../maker-host/model-context-limit-store.js';import { refreshXaiMediaModels } from '../maker-host/model-discovery/xai-media.js';import { testProviderConnection } from '../maker-host/provider-diagnostics.js';import { fetchProviderModels } from '../maker-host/provider-model-fetch.js';@@ -7152,6 +7157,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)clearModelPriceOverride,stageClearProviderModelPriceOverrides: stageProviderModelPriceOverridesClear,broadcastPricingChanged: broadcastReferenceModelPricing,+ // 上下文上限:不广播 —— 它不改任何已展示的目录字段,只影响**下一次**窗口评估+ // (resolveVerifiedContextWindow 每次调用现读 store)。写完 renderer 用返回值就地更新。+ readModelContextLimit: (target) => ({+ limit: readModelContextLimit(target.agent, target.providerId, target.modelId),+ isCustomized: isModelContextLimitCustomized(+ target.agent,+ target.providerId,+ target.modelId,+ ),+ }),+ writeModelContextLimit: (target, limit) => {+ writeModelContextLimit(target.agent, target.providerId, target.modelId, limit);+ },// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。oauthLogin: async (providerId, isCurrent) => {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 18c1eee7a8..5c840ac17d 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5736,6 +5736,24 @@ contextBridge.exposeInMainWorld('electronAPI', {target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,): Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView> =>ipcRenderer.invoke('maker:model-price-override:reset', target),+ /**+ * 单模型上下文上限 override(设置 → 模型 → 高级设置)。窗口是自动压缩比例的分母,+ * 调小它让压缩按用户设的长度提前触发。target 与价格 override 同形。+ * set 传 null = 恢复默认(删 override);返回落盘后的有效值与是否自定义。+ */+ getModelContextLimit: (+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,+ ): Promise<import('../shared/modelContextLimit').ModelContextLimitView> =>+ ipcRenderer.invoke('maker:model-context-limit:get', target),+ setModelContextLimit: (+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,+ limit: number | null,+ ): Promise<import('../shared/modelContextLimit').ModelContextLimitView> =>+ ipcRenderer.invoke('maker:model-context-limit:set', target, limit),+ resetModelContextLimit: (+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,+ ): Promise<import('../shared/modelContextLimit').ModelContextLimitView> =>+ ipcRenderer.invoke('maker:model-context-limit:reset', target),// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session。openSessionInNewWindow: (sessionId: string, deviceId?: string | null): Promise<void> =>diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex dc5564ad21..bb0b533fec 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -75,11 +75,8 @@ import {prefetchDeviceProviders,useDeviceProviders,} from '@/hooks/useDeviceProviders';-import {- modelPriceDiscountLabelValues,- modelPriceDetailRows,- modelPricePresentation,-} from '@/lib/modelPriceFormat';+import { modelPriceDiscountLabelValues, modelPriceDetailRows } from '@/lib/modelPriceFormat';+import { resolveModelPricePresentation } from '@/lib/modelPricePresentation';import {filterChatBridgedCodexProviders,isChatBridgedCodexProvider,@@ -115,7 +112,6 @@ import {} from '@cindy/model-providers';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';@@ -1503,8 +1499,9 @@ function ModelSelectorContentView({};// ── 模型单价 ─────────────────────────────────────────────────────────────- // XD 实际报价与非 XD Catalog 参考价是两份独立快照。这里只按行来源选择快照,- // 相同 modelId 不跨 Provider 复用或兜底。+ // 快照选择与折扣叠加的规则在 `lib/modelPricePresentation.ts`,与设置页 → 模型列表共用+ // 同一份实现(那三条判断复制一份就会漂,见该文件头注)。这里只做选择器特有的两件事:+ // 远程会话不展示价格,以及「行来源未知时回溯解析」。// agentOverride:统一面板的行各自有自己的生效引擎(不共用面板级 currentAgentKind),// 报价必须按**该行的引擎**查(同一 id 跨引擎可以是两条不同的路由 / 两份不同的价)。const pricePresentationOf = (@@ -1521,20 +1518,14 @@ function ModelSelectorContentView({(priceAgentKind? resolveCurrentSourceId(providers, currentProviderId, id, priceAgentKind): null);- const pricing = effectiveProviderId === 'xd' ? gatewayPricing : referencePricing;- 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);- const effectiveCost =- effectiveProvider && priceAgentKind- ? getModel(effectiveProvider, id, priceAgentKind)?.cost- : undefined;- return modelPricePresentation(quote ?? null, effectiveCost);- }- if (!quote) return null;- const displayQuote = quote.approximate ? { ...quote, approximate: false } : quote;- return modelPricePresentation(displayQuote, undefined);+ return resolveModelPricePresentation({+ providerId: effectiveProviderId,+ modelId: id,+ agent: priceAgentKind,+ providers,+ gatewayPricing,+ referencePricing,+ });};// SSH 远程会话里订阅直连模型(chatgpt/ / xai/)不可路由:远端 cc 不经本地// compat-proxy 的 responses-bridge,选了必失败。保留在列表但置灰 + 原因提示,diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsxindex b39e04900b..7dded05bac 100644--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx@@ -12,7 +12,6 @@ import type { AgentKind } from '@/hooks/useAgentCapabilities';import { cn } from '@/lib/utils';import type { Effort } from '@/lib/userPreferences.types';-import { EFFORT_TIER_COLORS, PRICE_TIER_COLORS } from '@/themes/effortTierColors';import { ClaudeMark } from '@/components/icons/ClaudeMark';import { CodexMark } from '@/components/icons/CodexMark';@@ -22,6 +21,14 @@ import type { ModelPickerLayout } from '@/state/modelPickerLayout';import { agentOptionOf } from './agentOptions';// 图标规则(模型条目 icon 优先、缺省回落来源供应商标)只有一份实现,复用它而不是抄一份。import { ModelIconMark } from './ModelSelector';+// 价格档串与设置页 → 模型列表共用同一份实现(见 priceTierMarks.tsx 头注)。+import {+ litFractionalMarks,+ litWholeMarks,+ PriceFreeBadge,+ PriceTierMarks,+ type UnifiedRowPriceDisplay,+} from './priceTierMarks';import {anchorKey,type UnifiedAnchor,@@ -43,126 +50,10 @@ const ENGINE_BADGE_TINT: Record<UnifiedEngine, string> = {};/**- * 行内价格展示(设计稿 v4 定稿的 F 样式):- * - `free` → 「限时免费」淡染小徽标;- * - `tier` → $ 档串($×1-3);**有折扣时**按折扣比例点亮,灰格是省掉的部分,尾随- * 「↓X%」淡染小字。- * 颜色语义(Chris 2026-08-14 裁决,第二版):**颜色只由点亮格数决定** —— 亮 1 格绿、- * 2 格黄、3 格红,与模型档位无关。$$$ 打六折亮两格就是黄,$$ 打六折亮一格就是绿;- * 无折扣行全亮,自然落回档位色。精确省幅由 ↓X% 与悬停说明表达。- * 不传 = 无报价,行内不渲染任何价格节点(别把每行都加宽)。- */-export interface UnifiedRowPriceDisplay {- kind: 'free' | 'tier';- /** 符号个数:按标准价分档(折扣不改变)。 */- tier?: 1 | 2 | 3;- /**- * 档串用的货币符号,按**该行报价的币种**取(CNY → ¥、USD → $)。设计稿里中文报价- * 是 ¥¥¥,写死 $ 会让国内用户看到一串对不上账单的美元号。- */- symbol?: string;- /** 折扣行:折后价占比(0-100,亮段宽度);无折扣不传。 */- paidPct?: number;- /** 折扣行:↓X% 的 X。 */- discountPct?: number;- /** 已本地化的悬停说明(折扣幅度全文)。 */- title?: string;-}--/**- * $ 档串节点 —— classic 与 badge **共用同一份结构**,两套样式的差别只有三处,全部参数化:- * 点亮量公式、亮段裁切百分比的字符串格式、要不要把点亮量暴露成 `data-price-lit`。- * (抽出来之前是逐字复制的两段 ~55 行,改一处必漏另一处。)- */-function PriceTierMarks({- priceDisplay,- symbol,- tier,- litOf,- formatClipPct,- exposeLit,-}: {- priceDisplay: UnifiedRowPriceDisplay;- symbol: string;- tier: 1 | 2 | 3;- /** 点亮量(单位:字符数)。classic 整格(≥1),badge 允许半格(≥0.5)。 */- litOf: (paidPct: number, tier: 1 | 2 | 3) => number;- /** 亮段裁切百分比的字符串格式:classic 不带小数,badge 一位小数(既有 DOM 断言按此)。 */- formatClipPct: (pct: number) => string;- /** badge 才把点亮量暴露成 `data-price-lit`(调试 / 测试锚点)。 */- exposeLit: boolean;-}) {- const marks = symbol.repeat(tier);- const { paidPct, discountPct } = priceDisplay;- return (- <span- data-price-tier- className="flex shrink-0 items-center gap-1"- {...(priceDisplay.title ? { title: priceDisplay.title } : {})}- >- {paidPct !== undefined && discountPct !== undefined ? (- (() => {- const lit = litOf(paidPct, tier);- // 颜色按点亮字符数四舍五入取 1 绿 / 2 黄 / 3 红(见 UnifiedRowPriceDisplay 头注)。- const colorTier = Math.min(3, Math.max(1, Math.round(lit))) as 1 | 2 | 3;- return (- <>- <span- aria-hidden- className="relative inline-block text-11 font-semibold leading-none tracking-[0.5px]"- >- <span className="invisible">{marks}</span>- <span className="absolute inset-0 text-[var(--text-tertiary)] opacity-55">- {marks}- </span>- <span- {...(exposeLit ? { 'data-price-lit': lit.toFixed(2) } : {})}- className="absolute inset-0"- style={{- color: PRICE_TIER_COLORS[`t${colorTier}`],- clipPath: `inset(0 ${formatClipPct(100 - (lit / tier) * 100)}% 0 0)`,- }}- >- {marks}- </span>- </span>- <span- data-discount-badge- // 设计稿 `.badge.save-tint`:淡染胶囊(14% 底 + 同色字),不是裸绿字 ——- // 裸字在长模型名旁边会被读成名字的一部分。- className="inline-flex shrink-0 items-center rounded-full px-2 py-[1px] text-10 font-medium leading-[1.45]"- style={{- color: EFFORT_TIER_COLORS.low,- backgroundColor: `color-mix(in srgb, ${EFFORT_TIER_COLORS.low} 14%, transparent)`,- }}- >- {`↓${discountPct}%`}- </span>- </>- );- })()- ) : (- // 无折扣:全格点亮 → 颜色按格数(1 绿 / 2 黄 / 3 红),与折扣行同一条规则。- <span- className="text-11 font-semibold leading-none tracking-[0.5px]"- style={{ color: PRICE_TIER_COLORS[`t${tier}`] }}- >- {marks}- </span>- )}- </span>- );-}--/** 整格点亮(classic,Chris 2026-08-14 第二版):亮几格 = round(实付比例 × 格数),至少 1 格。 */-const litWholeMarks = (paidPct: number, tier: 1 | 2 | 3): number =>- Math.min(tier, Math.max(1, Math.round((paidPct / 100) * tier)));-/**- * 按比例点亮(badge,Chris 2026-08-16 裁决):亮宽 = 档数 × 实付比例,**下限 0.5 个字符**- * (↓85% 这类只按比例会剩一条彩缝,太少上色很怪)。+ * 行内价格展示(设计稿 v4 定稿的 F 样式)的类型与档串组件已抽到 `./priceTierMarks`,+ * 与设置页 → 模型列表共用一份实现。这里 re-export 供既有 import 路径继续可用。*/-const litFractionalMarks = (paidPct: number, tier: 1 | 2 | 3): number =>- Math.min(tier, Math.max(0.5, (paidPct / 100) * tier));+export type { UnifiedRowPriceDisplay };/** 单行(双行布局):L1 图标 · 名称 · ☆ · 三元组 · 勾;L2 一句描述。 */export function UnifiedModelRow({@@ -419,16 +310,7 @@ export function UnifiedModelRow({</span>)}{priceDisplay?.kind === 'free' && (- <span- data-price-free- className="inline-flex shrink-0 items-center rounded-full px-2 py-[1px] text-10 font-medium leading-[1.45]"- style={{- color: EFFORT_TIER_COLORS.low,- backgroundColor: `color-mix(in srgb, ${EFFORT_TIER_COLORS.low} 14%, transparent)`,- }}- >- {t('newChat.modelSelector.pricing.free')}- </span>+ <PriceFreeBadge label={t('newChat.modelSelector.pricing.free')} />)}{priceDisplay?.kind === 'tier' && priceDisplay.tier !== undefined && (<PriceTierMarks@@ -517,16 +399,7 @@ export function UnifiedModelRow({</span>)}{priceDisplay?.kind === 'free' && (- <span- data-price-free- className="inline-flex shrink-0 items-center rounded-full px-2 py-[1px] text-10 font-medium leading-[1.45]"- style={{- color: EFFORT_TIER_COLORS.low,- backgroundColor: `color-mix(in srgb, ${EFFORT_TIER_COLORS.low} 14%, transparent)`,- }}- >- {t('newChat.modelSelector.pricing.free')}- </span>+ <PriceFreeBadge label={t('newChat.modelSelector.pricing.free')} />)}{priceDisplay?.kind === 'tier' && priceDisplay.tier !== undefined && (<PriceTierMarksdiff --git a/apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx b/apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsxnew file mode 100644index 0000000000..38d263945c--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx@@ -0,0 +1,150 @@+/**+ * 行内价格档串 —— 模型选择器与设置页 → 模型列表**共用同一份实现**。+ *+ * 原先只长在 `UnifiedModelRow.tsx` 里。设置页要显示同样的价格档时,如果各写一份,+ * 两边必然漂(点亮公式、裁切基准、徽标底色浓度都是容易各自微调的地方),而这一列的+ * 产品要求恰恰是「和选择器一模一样」。所以抽到这里,两处都从这里 import。+ *+ * 语义(Chris 2026-08-14 裁决,第二版):**颜色只由点亮格数决定** —— 亮 1 格绿、+ * 2 格黄、3 格红,与模型档位无关。`$$$` 打六折亮两格就是黄,`$$` 打六折亮一格就是绿;+ * 无折扣行全亮,自然落回档位色。精确省幅由 ↓X% 与悬停说明表达。+ */++import { EFFORT_TIER_COLORS, PRICE_TIER_COLORS } from '@/themes/effortTierColors';++/**+ * 不传 = 无报价,调用方**不要渲染任何价格节点**(别把每行都加宽)。+ */+export interface UnifiedRowPriceDisplay {+ kind: 'free' | 'tier';+ /** 符号个数:按标准价分档(折扣不改变)。 */+ tier?: 1 | 2 | 3;+ /**+ * 档串用的货币符号,按**该行报价的币种**取(CNY → ¥、USD → $)。设计稿里中文报价+ * 是 ¥¥¥,写死 $ 会让国内用户看到一串对不上账单的美元号。+ */+ symbol?: string;+ /** 折扣行:折后价占比(0-100,亮段宽度);无折扣不传。 */+ paidPct?: number;+ /** 折扣行:↓X% 的 X。 */+ discountPct?: number;+ /** 已本地化的悬停说明(折扣幅度全文)。 */+ title?: string;+}++/**+ * $ 档串节点 —— classic 与 badge **共用同一份结构**,两套样式的差别只有三处,全部参数化:+ * 点亮量公式、亮段裁切百分比的字符串格式、要不要把点亮量暴露成 `data-price-lit`。+ * (抽出来之前是逐字复制的两段 ~55 行,改一处必漏另一处。)+ */+export function PriceTierMarks({+ priceDisplay,+ symbol,+ tier,+ litOf,+ formatClipPct,+ exposeLit,+}: {+ priceDisplay: UnifiedRowPriceDisplay;+ symbol: string;+ tier: 1 | 2 | 3;+ /** 点亮量(单位:字符数)。classic 整格(≥1),badge 允许半格(≥0.5)。 */+ litOf: (paidPct: number, tier: 1 | 2 | 3) => number;+ /** 亮段裁切百分比的字符串格式:classic 不带小数,badge 一位小数(既有 DOM 断言按此)。 */+ formatClipPct: (pct: number) => string;+ /** badge 才把点亮量暴露成 `data-price-lit`(调试 / 测试锚点)。 */+ exposeLit: boolean;+}) {+ const marks = symbol.repeat(tier);+ const { paidPct, discountPct } = priceDisplay;+ return (+ <span+ data-price-tier+ className="flex shrink-0 items-center gap-1"+ {...(priceDisplay.title ? { title: priceDisplay.title } : {})}+ >+ {paidPct !== undefined && discountPct !== undefined ? (+ (() => {+ const lit = litOf(paidPct, tier);+ // 颜色按点亮字符数四舍五入取 1 绿 / 2 黄 / 3 红(见 UnifiedRowPriceDisplay 头注)。+ const colorTier = Math.min(3, Math.max(1, Math.round(lit))) as 1 | 2 | 3;+ return (+ <>+ <span+ aria-hidden+ className="relative inline-block text-11 font-semibold leading-none tracking-[0.5px]"+ >+ <span className="invisible">{marks}</span>+ <span className="absolute inset-0 text-[var(--text-tertiary)] opacity-55">+ {marks}+ </span>+ <span+ {...(exposeLit ? { 'data-price-lit': lit.toFixed(2) } : {})}+ className="absolute inset-0"+ style={{+ color: PRICE_TIER_COLORS[`t${colorTier}`],+ // 裁切百分比必须以**档串自身宽度**为基准。曾经给档串套过一层定宽外层+ // 做表格对齐,裁切基准跟着变成外层,↓50% 只灰掉一小截。+ clipPath: `inset(0 ${formatClipPct(100 - (lit / tier) * 100)}% 0 0)`,+ }}+ >+ {marks}+ </span>+ </span>+ <span+ data-discount-badge+ // 设计稿 `.badge.save-tint`:淡染胶囊(14% 底 + 同色字),不是裸绿字 ——+ // 裸字在长模型名旁边会被读成名字的一部分。+ className="inline-flex shrink-0 items-center rounded-full px-2 py-[1px] text-10 font-medium leading-[1.45]"+ style={{+ color: EFFORT_TIER_COLORS.low,+ backgroundColor: `color-mix(in srgb, ${EFFORT_TIER_COLORS.low} 14%, transparent)`,+ }}+ >+ {`↓${discountPct}%`}+ </span>+ </>+ );+ })()+ ) : (+ // 无折扣:全格点亮 → 颜色按格数(1 绿 / 2 黄 / 3 红),与折扣行同一条规则。+ <span+ className="text-11 font-semibold leading-none tracking-[0.5px]"+ style={{ color: PRICE_TIER_COLORS[`t${tier}`] }}+ >+ {marks}+ </span>+ )}+ </span>+ );+}++/** 整格点亮(classic,Chris 2026-08-14 第二版):亮几格 = round(实付比例 × 格数),至少 1 格。 */+export const litWholeMarks = (paidPct: number, tier: 1 | 2 | 3): number =>+ Math.min(tier, Math.max(1, Math.round((paidPct / 100) * tier)));++/**+ * 按比例点亮(badge,Chris 2026-08-16 裁决):亮宽 = 档数 × 实付比例,**下限 0.5 个字符**+ * (↓85% 这类只按比例会剩一条彩缝,太少上色很怪)。+ */+export const litFractionalMarks = (paidPct: number, tier: 1 | 2 | 3): number =>+ Math.min(tier, Math.max(0.5, (paidPct / 100) * tier));++/**+ * 「限时免费」淡染徽标 —— 与折扣胶囊同一套形制(14% 底 + 同色字),两处都要用,+ * 所以也收在这里。文案由调用方传(i18n 在组件外解析)。+ */+export function PriceFreeBadge({ label }: { label: string }) {+ return (+ <span+ data-price-free+ className="inline-flex shrink-0 items-center rounded-full px-2 py-[1px] text-10 font-medium leading-[1.45]"+ style={{+ color: EFFORT_TIER_COLORS.low,+ backgroundColor: `color-mix(in srgb, ${EFFORT_TIER_COLORS.low} 14%, transparent)`,+ }}+ >+ {label}+ </span>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsxnew file mode 100644index 0000000000..cec30cbe71--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx@@ -0,0 +1,604 @@+/**+ * ModelAdvancedDrawer —— 单个模型的全部只读事实与可配置项,从供应商详情面板右侧滑出。+ *+ * 为什么是抽屉而不是弹窗:这里要放的是「左标签右值 + 细分隔线」的定义列表,纵向空间比+ * 横向重要得多;弹窗宽而矮,同样的内容会被压成两栏或需要滚动两屏。+ *+ * 为什么行尾只有这一个入口:它替代了原先的「⋯」菜单。那个菜单里三项(自定义报价 /+ * 停用此模型 / 删除本机模型)全部搬进本抽屉 —— 一项能力都没减,但用户不必先猜「配置藏在+ * 哪个菜单里」。+ *+ * 分段职责:+ * - 标识 / 规格 / 能力 / 报价 = **只读事实**,由目录与报价快照决定,用户改不了。+ * - 默认推理强度 / 上下文上限 / 引擎支持 = **可配置项**,各自写入不同的既有存储+ * (providerModelMemory / model-context-limit-store / modelVisibilityPrefs)。+ * - 底部动作区 = 准入轴(停用)与本机文件(删除),与上面的显示轴严格分开。+ *+ * 「显示」与「停用」是两根正交的轴,语义见 UnifiedModelList 头注:开关管陈列,+ * 停用管准入。抽屉把它们放在视觉上分离的位置(引擎支持 vs 底部动作区),不混成一个控件。+ */++import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { AlertTriangle, Trash2, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import { toast } from '@/lib/toast';+import { Switch } from '@/components/ui/switch';+import { ClaudeMark } from '@/components/icons/ClaudeMark';+import { CodexMark } from '@/components/icons/CodexMark';+import { PiMark } from '@/components/icons/PiMark';+import { useModelContextLimit } from '@/hooks/useModelContextLimit';+import { modelPriceDetailRows, type ModelPricePresentation } from '@/lib/modelPriceFormat';+import {+ isModelEnabled,+ setModelVisibility,+ useModelVisibilityVersion,+} from '@/state/modelVisibilityPrefs';+import {+ getProviderModelEffort,+ setProviderModelEffort,+ useProviderModelMemoryVersion,+} from '@/state/providerModelMemory';+import { EFFORT_TIER_COLORS } from '@/themes/effortTierColors';++import { classifyVisionCapability, EFFORT_VALUES } from '@cindy/model-providers';+import type { AgentKind, CatalogModel, Effort, ProviderView } from '@cindy/model-providers';++import { MANAGED_OLLAMA_PROVIDER_ID } from '../../../shared/localModelRuntime';+import { ModelPriceOverrideDialog } from './ModelPriceOverrideDialog';+import type { UnionModelRow } from './UnifiedModelList';++const AGENT_LABEL: Record<AgentKind, string> = {+ 'claude-code': 'Claude Code',+ codex: 'Codex',+ pi: 'Pi',+};++const AGENT_MARK: Record<AgentKind, (size: number) => ReactNode> = {+ 'claude-code': (size) => <ClaudeMark size={size} />,+ codex: (size) => <CodexMark size={size} />,+ pi: (size) => <PiMark size={size} />,+};++const AGENT_MARK_COLOR: Record<AgentKind, string> = {+ 'claude-code': 'var(--engine-badge-cc)',+ codex: 'var(--engine-badge-codex)',+ pi: 'var(--engine-badge-pi)',+};++/** 抽屉里的档位顺序 = 目录枚举顺序(弱到强)。ultra 只在模型真的提供时出现。 */+const EFFORT_ORDER = EFFORT_VALUES;++/**+ * K / M 缩写在真实数据里是**歧义的**:contextWindow 同时存在 1,000,000、1,050,000、+ * 1,048,576 三种写法,都会被印成「1M」。所以详情处一律给带千分位的准确 token 数,+ * 括注里才给约数 —— 列表那种空间紧的位置继续用缩写。+ */+function formatExactTokens(tokens: number, locale: string): string {+ return tokens.toLocaleString(locale);+}++function approxTokens(tokens: number): string {+ if (tokens >= 1_000_000) {+ const m = tokens / 1_000_000;+ return `${Number.isInteger(m) ? m : Number(m.toFixed(2))}M`;+ }+ if (tokens >= 1000) return `${Math.round(tokens / 1000)}K`;+ return String(tokens);+}++/** 定义列表的一行:左标签右值 + 细分隔线。 */+function Row({+ label,+ children,+ muted,+}: {+ label: string;+ children: React.ReactNode;+ muted?: boolean;+}) {+ return (+ <div className="flex min-h-[34px] items-center justify-between gap-4 border-b border-[var(--settings-theme-card-border)] py-2 last:border-b-0">+ <span className="shrink-0 text-13 text-[var(--text-secondary)]">{label}</span>+ <span+ className={cn(+ 'min-w-0 truncate text-right text-13',+ muted ? 'text-[var(--text-tertiary)]' : 'text-[var(--text-primary)]',+ )}+ >+ {children}+ </span>+ </div>+ );+}++function Section({+ title,+ hint,+ children,+}: {+ title: string;+ hint?: string;+ children: React.ReactNode;+}) {+ return (+ <section className="pt-5 first:pt-1">+ <h4 className="text-11 font-medium uppercase tracking-[0.5px] text-[var(--text-tertiary)]">+ {title}+ </h4>+ {hint && (+ <p className="mt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">{hint}</p>+ )}+ <div className="mt-1.5">{children}</div>+ </section>+ );+}++interface Props {+ provider: ProviderView;+ row: UnionModelRow | null;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** 该行的报价展示(与列表同一份派生结果,避免抽屉自己再算一遍算出别的)。 */+ pricePresentationOf: (agent: AgentKind, model: CatalogModel) => ModelPricePresentation | null;+ /** 准入轴:停用此模型(main 侧 model-disable-store)。 */+ onDisable: (row: UnionModelRow) => void;+ /** 本机 Ollama 专有:删除磁盘上的模型文件。 */+ onDeleteLocal?: (row: UnionModelRow) => void;+ /** 该行当前是否已被停用(用于底部动作区的方向)。 */+ disabled: boolean;+ /** 付费锁定行不给写入入口(与列表行同一判定)。 */+ paymentRequired: boolean;+}++export function ModelAdvancedDrawer({+ provider,+ row,+ open,+ onOpenChange,+ pricePresentationOf,+ onDisable,+ onDeleteLocal,+ disabled,+ paymentRequired,+}: Props) {+ const { t, i18n } = useTranslation();+ const locale = i18n.resolvedLanguage ?? i18n.language ?? 'en';+ const [priceDialogOpen, setPriceDialogOpen] = useState(false);+ // 开关/档位写的是 renderer 本地存储,订阅 version 才能在写后重渲染。+ useModelVisibilityVersion();+ useProviderModelMemoryVersion();++ /**+ * 主展示引擎:该模型可用引擎里的第一个。只读事实(上下文、报价、能力)按它取 ——+ * 同一模型跨引擎的元数据可能不同,抽屉顶部标注了这一点,逐引擎差异在「引擎支持」段展开。+ */+ const primaryAgent = row?.avail[0] ?? null;+ const primaryModel = row && primaryAgent ? (row.byAgent[primaryAgent] ?? null) : null;++ const contextTarget = useMemo(+ () =>+ primaryAgent && primaryModel+ ? { providerId: provider.id, agent: primaryAgent, modelId: primaryModel.id }+ : null,+ [primaryAgent, primaryModel, provider.id],+ );+ const ctx = useModelContextLimit(open ? contextTarget : null);++ // 输入框是受控字符串:直接绑数字会让「删到空」变成 0 而不是空。+ const [ctxDraft, setCtxDraft] = useState('');+ const ctxDirtyRef = useRef(false);+ const routeWindow = primaryModel?.contextWindow ?? 0;+ const effectiveLimit = ctx.limit ?? (routeWindow > 0 ? routeWindow : null);+ useEffect(() => {+ // 加载完成或切换模型时把草稿同步成真值;用户正在输入时不要打断。+ if (ctx.loading || ctxDirtyRef.current) return;+ setCtxDraft(effectiveLimit === null ? '' : String(Math.round(effectiveLimit / 1000)));+ }, [ctx.loading, effectiveLimit]);+ useEffect(() => {+ ctxDirtyRef.current = false;+ }, [contextTarget]);++ const commitCtxDraft = useCallback(+ (raw: string) => {+ ctxDirtyRef.current = true;+ setCtxDraft(raw);+ const trimmed = raw.trim();+ if (!trimmed) return; // 空 = 还没填完,不写盘+ const k = Number(trimmed);+ if (!Number.isFinite(k) || k <= 0) return;+ ctx.setLimit(Math.round(k * 1000));+ },+ [ctx],+ );++ const resetCtx = useCallback(() => {+ ctxDirtyRef.current = false;+ void ctx.reset();+ }, [ctx]);++ if (!row || !primaryAgent || !primaryModel) {+ return (+ <Dialog.Root open={false} onOpenChange={onOpenChange}>+ <Dialog.Portal />+ </Dialog.Root>+ );+ }++ const vision = classifyVisionCapability(primaryModel.id);+ const price = pricePresentationOf(primaryAgent, primaryModel);+ const draftK = Number(ctxDraft.trim());+ const overRouteWindow =+ routeWindow > 0 && Number.isFinite(draftK) && draftK > 0 && draftK * 1000 > routeWindow;++ const efforts = primaryModel.efforts ?? [];+ const currentEffort =+ getProviderModelEffort(primaryAgent, provider.id, primaryModel.id) ??+ primaryModel.defaultEffort ??+ null;+ const shownEfforts = EFFORT_ORDER.filter(+ (effort) => effort !== 'ultra' || efforts.includes('ultra'),+ );+ /**+ * 推理强度的存储是 per (agent, provider, model) 的。这里按显示轴同一条哲学+ * **一次写该模型全部可用引擎** —— 用户在这个面板里选的是「这个模型默认想多用力」,+ * 而不是「它在 Codex 下用力、在 Claude Code 下不用力」。逐引擎覆盖是目录的事+ * (perAgent.defaultEffort),在下方引擎行标注出来。+ */+ const applyEffort = (effort: Effort) => {+ for (const agent of row.avail) {+ const model = row.byAgent[agent];+ if (!model) continue;+ if (!(model.efforts ?? []).includes(effort)) continue;+ setProviderModelEffort(agent, provider.id, model.id, effort);+ }+ };++ const isLocalOllama = provider.id === MANAGED_OLLAMA_PROVIDER_ID;++ return (+ <>+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay+ className={cn(+ 'fixed inset-0 z-[10001] bg-[var(--overlay-modal)]',+ 'data-[state=open]:animate-confirm-overlay-in',+ 'data-[state=closed]:animate-confirm-overlay-out',+ )}+ />+ <Dialog.Content+ className={cn(+ 'fixed right-0 top-0 z-[10001] flex h-full w-[436px] max-w-[92vw] flex-col',+ 'border-l border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',+ // 从右缘推进来。Radix 自己管 mount 与 data-state 的时序,所以不需要+ // 手动延迟一帧加 class —— 直接带终态入 DOM 会让过渡不播,这是纯 DOM+ // 实现里最容易踩的坑。+ 'data-[state=open]:animate-drawer-in-right',+ 'data-[state=closed]:animate-drawer-out-right',+ )}+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}+ aria-describedby={undefined}+ >+ <header className="flex items-start gap-3 border-b border-[var(--settings-theme-card-border)] px-5 pb-3 pt-4">+ <div className="min-w-0 flex-1">+ <Dialog.Title className="truncate text-15 font-medium text-[var(--text-primary)]">+ {primaryModel.name}+ </Dialog.Title>+ <p className="mt-0.5 truncate text-12 text-[var(--text-tertiary)]">+ {primaryModel.description ?? t('settings.providers.models.advanced.noDescription')}+ </p>+ </div>+ <Dialog.Close+ className="-mr-1 -mt-1 shrink-0 rounded-lg p-1.5 text-[var(--text-secondary)] transition-colors hover:bg-[var(--settings-menu-bg-hover)] hover:text-[var(--text-primary)]"+ aria-label={t('common.close')}+ >+ <X size={16} />+ </Dialog.Close>+ </header>++ <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-6">+ <Section title={t('settings.providers.models.advanced.identity')}>+ <Row label={t('settings.providers.models.advanced.modelId')}>+ <code className="text-12">{primaryModel.id}</code>+ </Row>+ <Row label={t('settings.providers.models.advanced.providerLabel')} muted>+ {provider.name}+ </Row>+ {primaryModel.group && (+ <Row label={t('settings.providers.models.advanced.group')} muted>+ <code className="text-12">{primaryModel.group}</code>+ </Row>+ )}+ <Row label={t('settings.providers.models.advanced.status')} muted>+ {primaryModel.status ?? t('settings.providers.models.advanced.statusUnset')}+ </Row>+ <Row label={t('settings.providers.models.advanced.defaultEnabled')} muted>+ {primaryModel.defaultEnabled === false+ ? t('settings.providers.models.advanced.defaultEnabledOff')+ : t('settings.providers.models.advanced.defaultEnabledOn')}+ </Row>+ </Section>++ <Section title={t('settings.providers.models.advanced.spec')}>+ <Row label={t('settings.providers.models.advanced.contextWindow')}>+ {routeWindow > 0 ? (+ <>+ {formatExactTokens(routeWindow, locale)}+ <span className="ml-1 text-11 text-[var(--text-tertiary)]">+ {t('settings.providers.models.advanced.tokensApprox', {+ approx: approxTokens(routeWindow),+ })}+ </span>+ </>+ ) : (+ <span className="text-[var(--text-tertiary)]">+ {t('settings.providers.models.advanced.catalogMissing')}+ </span>+ )}+ </Row>+ </Section>++ <Section+ title={t('settings.providers.models.advanced.capability')}+ hint={t('settings.providers.models.advanced.capabilityHint')}+ >+ <Row label={t('settings.providers.models.advanced.imageInput')}>+ <span title={t(`settings.providers.models.advanced.visionSource.${vision}`)}>+ {t(`settings.providers.models.advanced.vision.${vision}`)}+ </span>+ </Row>+ <Row label="Fast" muted>+ {primaryModel.supportsFastMode === true+ ? t('settings.providers.models.advanced.supported')+ : primaryModel.supportsFastMode === false+ ? t('settings.providers.models.advanced.unsupported')+ : t('settings.providers.models.advanced.undeclared')}+ </Row>+ </Section>++ <Section title={t('settings.providers.models.advanced.pricing')}>+ {price === null ? (+ <Row label={t('settings.providers.models.advanced.pricingLabel')} muted>+ {t('settings.providers.models.advanced.noPricing')}+ </Row>+ ) : price.kind === 'free' ? (+ <Row label={t('settings.providers.models.advanced.pricingLabel')}>+ {t('newChat.modelSelector.pricing.free')}+ </Row>+ ) : (+ modelPriceDetailRows(price.current, price.original).map((detail) => (+ <Row+ key={detail.kind}+ label={t(`settings.providers.models.advanced.price.${detail.kind}`)}+ >+ {/* 有折扣时给**实付价**,标准价划掉跟在后面:只写标准价再另起一行+ 「折扣 40%」等于让人自己乘一遍,而实付才是他要判断的数。 */}+ {detail.value}+ {detail.originalValue && (+ <span className="ml-1.5 text-11 text-[var(--text-tertiary)] line-through">+ {detail.originalValue}+ </span>+ )}+ <span className="ml-1 text-11 text-[var(--text-tertiary)]">+ {t('settings.providers.models.advanced.perMtok')}+ </span>+ </Row>+ ))+ )}+ {price?.kind === 'priced' && price.discount !== undefined && (+ <Row label={t('settings.providers.models.advanced.discount')}>+ <span+ className="inline-flex items-center rounded-full px-2 py-[1px] text-10 font-medium"+ style={{+ color: EFFORT_TIER_COLORS.low,+ backgroundColor: `color-mix(in srgb, ${EFFORT_TIER_COLORS.low} 14%, transparent)`,+ }}+ >+ {`↓${Math.round(price.discount * 100)}%`}+ </span>+ </Row>+ )}+ {/* 自定义报价:原「⋯」菜单的一项,搬到它真正相关的段落里。+ XD 网关的价格由服务端定,不给覆盖入口(与 IPC 侧的拒绝一致)。 */}+ {provider.id !== 'xd' && !paymentRequired && (+ <button+ type="button"+ onClick={() => setPriceDialogOpen(true)}+ className="mt-2 text-12 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)]"+ >+ {t('settings.providers.models.priceOverride.menu')}+ </button>+ )}+ </Section>++ {efforts.length > 0 && (+ <Section+ title={t('settings.providers.models.advanced.defaultEffort')}+ hint={t('settings.providers.models.advanced.defaultEffortHint')}+ >+ <div className="mt-1 flex rounded-lg border border-[var(--settings-theme-card-border)] p-[3px]">+ {shownEfforts.map((effort) => {+ const available = efforts.includes(effort);+ const active = currentEffort === effort;+ return (+ <button+ key={effort}+ type="button"+ disabled={!available || paymentRequired}+ onClick={() => applyEffort(effort)}+ className={cn(+ 'flex-1 rounded-md py-1 text-12 transition-colors',+ active+ ? 'bg-[var(--settings-menu-bg-hover)] text-[var(--text-primary)]'+ : available+ ? 'text-[var(--text-secondary)] hover:text-[var(--text-primary)]'+ : 'cursor-not-allowed text-[var(--text-tertiary)] opacity-45',+ )}+ >+ {t(`effortLevels.${effort}`)}+ </button>+ );+ })}+ </div>+ </Section>+ )}++ {routeWindow > 0 && (+ <Section+ title={t('settings.providers.models.advanced.contextLimit')}+ hint={t('settings.providers.models.advanced.contextLimitHint')}+ >+ <div className="mt-1 flex items-center gap-2.5">+ <span+ className={cn(+ 'inline-flex h-7 items-center gap-1 rounded-lg border px-2',+ overRouteWindow+ ? 'border-[var(--warning-fg)]'+ : 'border-[var(--settings-theme-card-border)]',+ )}+ >+ <input+ value={ctxDraft}+ onChange={(event) => commitCtxDraft(event.target.value)}+ inputMode="numeric"+ disabled={paymentRequired}+ aria-label={t('settings.providers.models.advanced.contextLimitAria')}+ className="w-11 bg-transparent text-center text-13 tabular-nums text-[var(--text-primary)] outline-none"+ />+ <span className="text-11 text-[var(--text-tertiary)]">K</span>+ </span>+ <span className="min-w-0 flex-1 truncate text-11 tabular-nums text-[var(--text-tertiary)]">+ {t('settings.providers.models.advanced.contextLimitRoute', {+ tokens: formatExactTokens(routeWindow, locale),+ })}+ </span>+ {ctx.isCustomized && (+ <button+ type="button"+ onClick={resetCtx}+ className="shrink-0 text-11 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-primary)]"+ >+ {t('settings.providers.models.advanced.restoreDefault')}+ </button>+ )}+ </div>+ {overRouteWindow && (+ <p className="mt-1.5 flex items-start gap-1.5 text-11 leading-[1.5] text-[var(--warning-fg)]">+ <AlertTriangle size={12} className="mt-0.5 shrink-0" />+ {t('settings.providers.models.advanced.contextLimitOverWindow')}+ </p>+ )}+ </Section>+ )}++ <Section+ title={t('settings.providers.models.advanced.engines')}+ hint={t('settings.providers.models.advanced.enginesHint')}+ >+ {provider.agents.map((agent) => {+ const model = row.byAgent[agent];+ const supported = Boolean(model);+ const notes: string[] = [];+ if (model) {+ // 同一模型在不同引擎下的元数据差异如实标出来 —— 这些值来自目录的+ // perAgent 覆盖,用户看到「Codex 下 272K / 6 档」才知道差异是真的。+ if (model.contextWindow > 0 && model.contextWindow !== routeWindow) {+ notes.push(approxTokens(model.contextWindow));+ }+ if (model.defaultEffort && model.defaultEffort !== primaryModel.defaultEffort) {+ notes.push(+ t('settings.providers.models.advanced.engineDefaultEffort', {+ effort: t(`effortLevels.${model.defaultEffort}`),+ }),+ );+ }+ if (+ model.supportsFastMode === false &&+ primaryModel.supportsFastMode === true+ ) {+ notes.push(t('settings.providers.models.advanced.engineNoFast'));+ }+ }+ return (+ <div+ key={agent}+ className={cn(+ 'flex min-h-[34px] items-center gap-2.5 border-b border-[var(--settings-theme-card-border)] py-2 last:border-b-0',+ !supported && 'opacity-50',+ )}+ >+ <span+ className="shrink-0"+ style={{ color: AGENT_MARK_COLOR[agent] }}+ aria-hidden+ >+ {AGENT_MARK[agent](14)}+ </span>+ <span className="shrink-0 text-13 text-[var(--text-primary)]">+ {AGENT_LABEL[agent]}+ </span>+ <span className="min-w-0 flex-1 truncate text-right text-11 text-[var(--text-tertiary)]">+ {supported+ ? notes.join(' · ')+ : t('settings.providers.models.advanced.engineUnsupported')}+ </span>+ <Switch+ checked={supported ? isModelEnabled(agent, provider.id, model!) : false}+ disabled={!supported || paymentRequired}+ onCheckedChange={(next) => {+ if (!model) return;+ if (setModelVisibility(agent, provider.id, model.id, next) === false) {+ toast.error(t('settings.providers.models.visibilityWriteFailed'));+ }+ }}+ aria-label={`${primaryModel.name} · ${AGENT_LABEL[agent]}`}+ />+ </div>+ );+ })}+ </Section>++ {/* 动作区:准入轴与本机文件。与上面的显示轴刻意隔开一段留白 ——+ 它们不是同一件事,放在一起会让人以为关了开关就等于停用。 */}+ {!paymentRequired && (+ <div className="mt-7 flex flex-col gap-2 border-t border-[var(--settings-theme-card-border)] pt-4">+ <button+ type="button"+ onClick={() => onDisable(row)}+ className="h-8 rounded-lg border border-[var(--settings-btn-secondary-border)] text-13 text-[var(--settings-btn-secondary-text)] transition-colors hover:bg-[var(--settings-menu-bg-hover)]"+ >+ {disabled+ ? t('settings.providers.models.enableModel')+ : t('settings.providers.models.disableModel')}+ </button>+ {isLocalOllama && onDeleteLocal && (+ <button+ type="button"+ onClick={() => onDeleteLocal(row)}+ className="flex h-8 items-center justify-center gap-1.5 rounded-lg text-13 text-[var(--error-flat)] transition-colors hover:bg-[var(--settings-menu-bg-hover)]"+ >+ <Trash2 size={13} />+ {t('settings.providers.local.deleteModel')}+ </button>+ )}+ </div>+ )}+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>++ {priceDialogOpen && (+ <ModelPriceOverrideDialog+ provider={provider}+ row={row}+ open={priceDialogOpen}+ onOpenChange={setPriceDialogOpen}+ />+ )}+ </>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex c0ccf27e83..f39c814ded 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -77,6 +77,13 @@ import {requestXaiSubscriptionRefresh,useXaiSubscriptionUsage,} from '@/hooks/useXaiSubscriptionUsage';+// 订阅余量:三家各有一个既有 hook,呈现收敛到本文件的 SubscriptionUsageModule。+import { useClaudeSubscriptionUsage } from '@/hooks/useClaudeSubscriptionUsage';+import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';+import {+ formatClaudeSubscriptionPlanLabel,+ formatCodexPlanLabel,+} from '@/lib/subscriptionPlanLabel';import {formatXaiProductLabel,isXaiWeeklyUsageCurrent,@@ -554,6 +561,7 @@ function AnthropicHeader({})}trailing={trailing}provider={provider}+ assetModule={<ClaudeAssetModule connected={connected} />}/>);}@@ -695,6 +703,7 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan</div>) : undefined}+ assetModule={<CodexAssetModule connected={connected} />}/>);}@@ -803,10 +812,11 @@ function ImageApiKeyRow({}// ----------------------------------------------------------------------------// xAI —— OAuth(SuperGrok 订阅),复用 maker.xaiOAuth*。+// 订阅用量模块(xAI / Anthropic / OpenAI 共用形制)// ----------------------------------------------------------------------------function formatXaiResetLabel(resetsAt: number | null | undefined, locale: string): string | null {+/** epoch 秒 → 本地「月/日 时:分」。三家的 reset 时间都是 epoch 秒,共用一份。 */+function formatResetLabel(resetsAt: number | null | undefined, locale: string): string | null {if (typeof resetsAt !== 'number' || !Number.isFinite(resetsAt) || resetsAt <= 0) return null;try {return new Date(resetsAt * 1000).toLocaleString(locale, {@@ -820,6 +830,193 @@ function formatXaiResetLabel(resetsAt: number | null | undefined, locale: string}}+/**+ * 订阅余量的统一呈现:套餐名 → 一个大数字 → 一到两行补充 → 右侧文字链接。+ *+ * 刻意做成**一块留白而不是卡片**:这里已经在 DetailHeader 的 assetModule 槽位里,+ * 外面有一条 1px 发丝线分隔,再套边框就是框中框(DESIGN §2 layer rule)。+ * 也刻意**不画进度条** —— 它会把「42% 已使用」这一个事实重复说两遍,而百分比本身+ * 已经是最紧凑的表达;进度条只在需要比较多个池子时才有额外信息量。+ *+ * 三家的数据语义完全不同(xAI 信用点周窗口 / Anthropic 5h + 7d 双窗口 /+ * ChatGPT primary + secondary 限额),但**用户要看的东西是同一个**:还剩多少、什么时候+ * 恢复。所以收敛成同一个形状,各家只负责把自己的快照映射成这三样。+ */+function SubscriptionUsageModule({+ planLabel,+ primary,+ notes,+ link,+}: {+ planLabel: string;+ /** 最该看的那个值,如「42% 已使用」。拿不到就整块不渲染,不画占位。 */+ primary: string;+ /** 一到两行小灰补充:重置时刻、次级窗口、分模型占比等。 */+ notes: string[];+ link?: { label: string; onClick: () => void };+}) {+ return (+ <div+ data-testid="provider-usage-module"+ className="flex flex-wrap justify-between gap-x-6 gap-y-4 border-t px-5 py-5"+ style={{ borderColor: 'var(--settings-theme-card-border)' }}+ >+ <div className="min-w-0">+ <p className="text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>+ {planLabel}+ </p>+ <p+ className="mt-1.5 text-20 font-medium leading-[1.3] tracking-[-0.02em] tabular-nums"+ style={{ color: 'var(--text-primary)' }}+ >+ {primary}+ </p>+ {notes.map((note) => (+ <p+ key={note}+ className="mt-1 text-12 leading-tight tabular-nums"+ style={{ color: 'var(--text-secondary)' }}+ >+ {note}+ </p>+ ))}+ </div>+ {link && (+ <div className="flex shrink-0 items-center pt-3.5">+ <button+ type="button"+ onClick={link.onClick}+ className="text-13 transition-colors hover:text-[var(--text-primary)]"+ style={{ color: 'var(--text-secondary)' }}+ >+ {link.label}+ </button>+ </div>+ )}+ </div>+ );+}++/**+ * Anthropic 订阅余量。数据来自既有 `useClaudeSubscriptionUsage`(5h 滚动窗口 + 总周限 ++ * 分模型周窗口),此前只有状态栏 chip 消费它 —— 供应商详情页一直是空的。+ *+ * 主指标取 5h 窗口:它是最容易被撞到、也最容易恢复的那个,用户来这一页多半是想知道+ * 「现在还能不能用」。周限与分模型占比作为补充行。+ */+function ClaudeAssetModule({ connected }: { connected: boolean }) {+ const { t, i18n } = useTranslation();+ const locale = i18n.resolvedLanguage ?? i18n.language;+ const usage = useClaudeSubscriptionUsage(connected);+ if (!connected || !usage) return null;++ const fiveHour = usage.fiveHour;+ const fiveHourPct =+ fiveHour && Number.isFinite(fiveHour.utilization) ? Math.round(fiveHour.utilization) : null;+ const sevenDayPct =+ usage.sevenDay && Number.isFinite(usage.sevenDay.utilization)+ ? Math.round(usage.sevenDay.utilization)+ : null;+ // 两个窗口都没有数据就整块不渲染 —— 只有套餐名的一块留白没有信息量。+ if (fiveHourPct === null && sevenDayPct === null) return null;++ const notes: string[] = [];+ const resetLabel = formatResetLabel(fiveHour?.resetsAt, locale);+ const resetPart = resetLabel+ ? t('settings.providers.usage.resetsAt', { at: resetLabel })+ : null;+ const weeklyPart =+ sevenDayPct !== null+ ? t('settings.providers.usage.claudeWeekly', { percent: sevenDayPct })+ : null;+ const firstLine = [resetPart, weeklyPart].filter(Boolean).join(' · ');+ if (firstLine) notes.push(firstLine);+ const scoped = (usage.scoped ?? [])+ .filter((window) => Number.isFinite(window.utilization))+ .map((window) =>+ t('settings.providers.usage.scopedModel', {+ model: window.modelDisplayName,+ percent: Math.round(window.utilization),+ }),+ );+ if (scoped.length > 0) notes.push(scoped.join(' · '));++ return (+ <SubscriptionUsageModule+ planLabel={+ formatClaudeSubscriptionPlanLabel(usage.subscriptionType)+ ? `Claude ${formatClaudeSubscriptionPlanLabel(usage.subscriptionType)}`+ : t('settings.providers.usage.claudePlanFallback')+ }+ primary={t('settings.providers.usage.percentUsed', {+ percent: fiveHourPct ?? sevenDayPct ?? 0,+ })}+ notes={notes}+ link={{+ label: t('settings.providers.usage.openClaudeUsage'),+ onClick: () => void window.electronAPI.openExternal('https://claude.ai/settings/usage'),+ }}+ />+ );+}++/**+ * ChatGPT / Codex 订阅余量。数据来自既有 `useCodexRateLimits`(app-server 上报的+ * primary / secondary 限额窗口 + 限额重置券),此前只有状态栏 chip 与移动端消费。+ *+ * 主指标取 primary 窗口(通常是短窗口),secondary 与重置券数量作为补充行。+ */+function CodexAssetModule({ connected }: { connected: boolean }) {+ const { t, i18n } = useTranslation();+ const locale = i18n.resolvedLanguage ?? i18n.language;+ const { snapshot } = useCodexRateLimits(connected);+ if (!connected || !snapshot) return null;++ const primaryWindow = snapshot.rateLimits.primary;+ const primaryPct =+ primaryWindow && Number.isFinite(primaryWindow.usedPercent)+ ? Math.round(primaryWindow.usedPercent)+ : null;+ if (primaryPct === null) return null;++ const notes: string[] = [];+ const resetLabel = formatResetLabel(primaryWindow?.resetsAt, locale);+ const secondary = snapshot.rateLimits.secondary;+ const secondaryPct =+ secondary && Number.isFinite(secondary.usedPercent) ? Math.round(secondary.usedPercent) : null;+ const firstLine = [+ resetLabel ? t('settings.providers.usage.resetsAt', { at: resetLabel }) : null,+ secondaryPct !== null+ ? t('settings.providers.usage.codexSecondary', { percent: secondaryPct })+ : null,+ ]+ .filter(Boolean)+ .join(' · ');+ if (firstLine) notes.push(firstLine);+ const credits = snapshot.rateLimitResetCredits?.availableCount ?? 0;+ if (credits > 0) {+ notes.push(t('settings.providers.usage.codexResetCredits', { count: credits }));+ }++ return (+ <SubscriptionUsageModule+ planLabel={+ formatCodexPlanLabel(snapshot.account.planType ?? snapshot.rateLimits.planType)+ ? `ChatGPT ${formatCodexPlanLabel(+ snapshot.account.planType ?? snapshot.rateLimits.planType,+ )}`+ : t('settings.providers.usage.codexPlanFallback')+ }+ primary={t('settings.providers.usage.percentUsed', { percent: primaryPct })}+ notes={notes}+ />+ );+}++// ---------------------------------------------------------------------------+// xAI —— OAuth(SuperGrok 订阅),复用 maker.xaiOAuth*。+// ---------------------------------------------------------------------------+function XaiAssetModule({ connected }: { connected: boolean }) {const { t, i18n } = useTranslation();const usage = useXaiSubscriptionUsage(connected);@@ -836,60 +1033,35 @@ function XaiAssetModule({ connected }: { connected: boolean }) {}, [connected, usage, nowMs]);if (!connected || !usage) return null;const hasWeekly = isXaiWeeklyUsageCurrent(usage, nowMs);- if (!usage.planLabel && !hasWeekly) return null;- const resetLabel = formatXaiResetLabel(usage.resetsAt, i18n.resolvedLanguage ?? i18n.language);+ // 没有周窗口数据时整块不渲染:只有一个套餐名的留白没有信息量(改用共用组件前+ // 这里会渲染成一个孤零零的套餐名)。+ if (!hasWeekly) return null;+ const resetLabel = formatResetLabel(usage.resetsAt, i18n.resolvedLanguage ?? i18n.language);+ const notes = [+ ...(resetLabel ? [t('settings.providers.xai.asset.resetsAt', { at: resetLabel })] : []),+ ...(usage.productUsage ?? []).map((product) =>+ t('settings.providers.xai.asset.productLine', {+ product: formatXaiProductLabel(product.product),+ percent: Math.round(product.usagePercent),+ }),+ ),+ ];return (- <div- className="flex flex-wrap justify-between gap-x-6 gap-y-4 border-t px-5 py-5"- style={{ borderColor: 'var(--settings-theme-card-border)' }}- >- <div className="min-w-0">- <p className="text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>- {usage.planLabel ?? t('settings.providers.xai.asset.weeklyTitle')}- </p>- {hasWeekly && (- <p- className="mt-1.5 text-20 font-medium leading-[1.3] tracking-[-0.02em] tabular-nums"- style={{ color: 'var(--text-primary)' }}- >- {t('settings.providers.xai.asset.weeklyUsed', {- percent: Math.round(usage.creditUsagePercent ?? 0),- })}- </p>- )}- {hasWeekly && resetLabel && (- <p className="mt-1 text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>- {t('settings.providers.xai.asset.resetsAt', { at: resetLabel })}- </p>- )}- {hasWeekly &&- (usage.productUsage ?? []).map((product) => (- <p- key={product.product}- className="mt-1 text-12 leading-tight tabular-nums"- style={{ color: 'var(--text-secondary)' }}- >- {t('settings.providers.xai.asset.productLine', {- product: formatXaiProductLabel(product.product),- percent: Math.round(product.usagePercent),- })}- </p>- ))}- </div>- <div className="flex shrink-0 items-center pt-3.5">- <button- type="button"- onClick={() => void window.electronAPI.openExternal('https://grok.com')}- className="text-13 transition-colors hover:text-[var(--text-primary)]"- style={{ color: 'var(--text-secondary)' }}- >- {t('settings.providers.xai.asset.openUsage')}- </button>- </div>- </div>+ <SubscriptionUsageModule+ planLabel={usage.planLabel ?? t('settings.providers.xai.asset.weeklyTitle')}+ primary={t('settings.providers.xai.asset.weeklyUsed', {+ percent: Math.round(usage.creditUsagePercent ?? 0),+ })}+ notes={notes}+ link={{+ label: t('settings.providers.xai.asset.openUsage'),+ onClick: () => void window.electronAPI.openExternal('https://grok.com'),+ }}+ />);}+function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged: () => void }) {const { t } = useTranslation();const { confirm } = useConfirmDialog();diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsxindex 6432386167..55a2b21cfc 100644--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx@@ -27,19 +27,24 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { ChevronDown, Lock, MoreHorizontal, RefreshCw, Search } from 'lucide-react';+import { ChevronDown, Lock, RefreshCw, Search, SlidersHorizontal } from 'lucide-react';import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';import { Switch } from '@/components/ui/switch';import { Spinner } from '@/components/ui/spinner';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { ProviderLogoMark } from '@/components/icons/ProviderLogoMark';import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';+ litWholeMarks,+ PriceFreeBadge,+ PriceTierMarks,+ type UnifiedRowPriceDisplay,+} from '@/components/new-chat/priceTierMarks';+import { priceTierOf } from '@/components/new-chat/unifiedModelSelection';+import { useGatewayModelPricing, useReferenceModelPricing } from '@/hooks/useModelPricing';+import { modelPriceDiscountLabelValues } from '@/lib/modelPriceFormat';+import { resolveModelPricePresentation } from '@/lib/modelPricePresentation';import { MANAGED_OLLAMA_PROVIDER_ID } from '../../../shared/localModelRuntime';import {groupModelsForDisplay,@@ -54,6 +59,7 @@ import {useModelVisibilityVersion,} from '@/state/modelVisibilityPrefs';import { LocalPackagingTag } from './LocalPackagingTag';+import { ModelAdvancedDrawer } from './ModelAdvancedDrawer';import { ModelPriceOverrideDialog } from './ModelPriceOverrideDialog';import { isAgentSelectableModel } from '@cindy/model-providers';@@ -359,11 +365,75 @@ export function UnifiedModelList({// 分组与「已停用」分区之间的迁移一次到位,不出现回跳帧(规则 7)。新快照到达即清空。const [pendingDisabled, setPendingDisabled] = useState<Record<string, boolean>>({});const [priceRow, setPriceRow] = useState<UnionModelRow | null>(null);+ /** 高级设置抽屉的目标行。切供应商时清掉 —— 抽屉里的 row 属于旧 provider。 */+ const [advancedRow, setAdvancedRow] = useState<UnionModelRow | null>(null);+ /** 类型筛选(全部 / 对话 / 图像 / 视频…):只有该来源真存在多类时才渲染整条。 */+ const [kindFilter, setKindFilter] = useState<ModelCategory | 'all'>('all');useEffect(() => {setPendingDisabled({});setPriceRow(null);+ setAdvancedRow(null);+ setKindFilter('all');}, [provider]);+ // 报价快照:与模型选择器同两份来源(XD 实付价 / 非 XD 参考价),派生逻辑共用+ // lib/modelPricePresentation.ts —— 设置页与选择器显示的必须是同一个价。+ const gatewayPricing = useGatewayModelPricing();+ const referencePricing = useReferenceModelPricing();+ const providersForPricing = useMemo(() => [provider], [provider]);+ const pricePresentationOf = useCallback(+ (agent: AgentKind, model: CatalogModel) =>+ resolveModelPricePresentation({+ providerId: provider.id,+ modelId: model.id,+ agent,+ providers: providersForPricing,+ gatewayPricing,+ referencePricing,+ }),+ [gatewayPricing, provider.id, providersForPricing, referencePricing],+ );++ /**+ * 行内档串的展示参数。口径与 UnifiedModelPanel.priceDisplayOf 一致:+ * 格数按**标准价**分档(折扣不改档位),点亮宽度按折后比例;订阅接入且拿不到按量报价的+ * 行不画档串(那类模型走套餐额度,画钱会被读成按量计费)。+ */+ const rowPriceDisplay = useCallback(+ (row: UnionModelRow): UnifiedRowPriceDisplay | null => {+ const agent = row.avail[0];+ const model = agent ? row.byAgent[agent] : undefined;+ if (!agent || !model) return null;+ const price = pricePresentationOf(agent, model);+ const subscriptionRow =+ provider.access?.kind === 'subscription' &&+ (price === null ||+ price.kind !== 'priced' ||+ price.current.source === 'subscription-reference');+ if (subscriptionRow) return null;+ if (price?.kind === 'free') return { kind: 'free' };+ if (price?.kind !== 'priced') return null;+ const basis = price.original ?? price.current;+ const discountPct = price.discount !== undefined ? Math.round(price.discount * 100) : 0;+ return {+ kind: 'tier',+ tier: priceTierOf(basis.outputPerMtok, basis.currency),+ symbol: basis.currency === 'CNY' ? '¥' : '$',+ ...(discountPct > 0 && discountPct < 100+ ? {+ discountPct,+ paidPct: 100 - discountPct,+ title: t(+ 'newChat.modelSelector.pricing.discount',+ modelPriceDiscountLabelValues(price.discount ?? 0),+ ),+ }+ : {}),+ };+ },+ [pricePresentationOf, provider.access?.kind, t],+ );+// 折叠态:分组用 ModelCategory 作 key,「已停用」分区用 DISABLED_GROUP_KEY(默认展开)。const isCollapsed = useCallback((key: string) =>@@ -483,13 +553,32 @@ export function UnifiedModelList({});}, [hasLockedDisabledRow, unionRows, pendingDisabled, provider.id, t]);+ /**+ * 该来源真实存在的类型。**只有一类时整条筛选不渲染** —— 那种情况下「全部」和那一类+ * 完全等价,给一个永远不改变结果的控件只是噪音。实测本机四个来源里只有 xAI 同时有+ * 对话 / 图像 / 视频三类,其余三家全是对话模型,这排 chip 一次都不出现。+ */+ const presentCategories = useMemo(() => {+ const present = new Set<ModelCategory>();+ for (const row of unionRows) {+ const rep = row.byAgent[row.avail[0]];+ if (rep) present.add(rowCategory(row));+ }+ return [...present];+ }, [unionRows]);+ const showKindFilter = presentCategories.length > 1;+// 分组(仅未停用的行)+「已停用」分区(停用的行,跨分组沉底)。搜索两边都过滤。// 分组沿用现有口径:用每行第一个可用 agent 的目录条目作代表参与分组。const { groups, disabledRows } = useMemo(() => {const q = query.trim().toLowerCase();- const matched = q+ const searched = q? unionRows.filter((r) => r.name.toLowerCase().includes(q) || r.id.toLowerCase().includes(q)): unionRows;+ const matched =+ showKindFilter && kindFilter !== 'all'+ ? searched.filter((r) => rowCategory(r) === kindFilter)+ : searched;const active = matched.filter((r) => !rowDisabledEffective(r));const disabled = matched.filter((r) => rowDisabledEffective(r));const repByRow = new Map<string, UnionModelRow>();@@ -507,7 +596,7 @@ export function UnifiedModelList({})),disabledRows: disabled,};- }, [unionRows, query, rowDisabledEffective]);+ }, [unionRows, query, rowDisabledEffective, showKindFilter, kindFilter]);const showGroupHeaders = groups.length > 1;const showSearch = unionRows.length > 8;@@ -572,42 +661,29 @@ export function UnifiedModelList({}}, [allOn, provider, pendingDisabled, showVisibilityWriteFailure]);- /** 行级「⋯」菜单(hover 显现;菜单打开期间保持可见):停用动作的唯一入口。 */- const rowMenu = (row: UnionModelRow) => (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <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',- )}- style={{ color: 'var(--text-tertiary)' }}- >- <MoreHorizontal size={14} />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- {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>- {provider.id === MANAGED_OLLAMA_PROVIDER_ID && (- <DropdownMenuItem- className="text-[var(--error-fg)] focus:text-[var(--error-fg)]"- onClick={() => void deleteInstalledModel(row)}- >- {t('settings.providers.local.deleteModel')}- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>+ /**+ * 行尾「高级设置」(hover 显现;抽屉打开期间保持可见)。+ *+ * 它替代了原先的「⋯」菜单:那个菜单里三项(自定义报价 / 停用此模型 / 删除本机模型)+ * 全部搬进抽屉,一项能力都没减。换掉的理由是那个菜单只有一个真入口值得点开 ——+ * 多一层点击只是把配置藏起来,而抽屉本身就是配置该去的地方。+ */+ const rowAdvancedButton = (row: UnionModelRow) => (+ <button+ type="button"+ aria-label={t('settings.providers.models.advanced.openAria', { name: row.name })}+ title={t('settings.providers.models.advanced.open')}+ disabled={isRowPaymentRequired(row)}+ onClick={() => setAdvancedRow(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',+ advancedRow?.id === row.id && 'opacity-100',+ )}+ style={{ color: 'var(--text-tertiary)' }}+ >+ <SlidersHorizontal size={14} />+ </button>);const listEmpty = groups.length === 0 && disabledRows.length === 0 && !query.trim();@@ -625,6 +701,33 @@ export function UnifiedModelList({<span className="shrink-0 text-13 font-medium" style={{ color: 'var(--text-secondary)' }}>{t('settings.providers.models.available')}</span>+ {showKindFilter && (+ <div+ className="flex shrink-0 items-center gap-0.5 rounded-full p-0.5"+ style={{ backgroundColor: 'var(--surface-elevated)' }}+ role="group"+ aria-label={t('settings.providers.models.kindFilter.aria')}+ >+ {(['all', ...presentCategories] as Array<ModelCategory | 'all'>).map((kind) => (+ <button+ key={kind}+ type="button"+ onClick={() => setKindFilter(kind)}+ aria-pressed={kindFilter === kind}+ className={cn(+ 'h-6 rounded-full px-2.5 text-12 transition-colors',+ kindFilter === kind+ ? 'bg-[var(--surface-hover)] font-medium text-[var(--text-primary)]'+ : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)]',+ )}+ >+ {kind === 'all'+ ? t('settings.providers.models.kindFilter.all')+ : t(CATEGORY_LABEL_KEY[kind])}+ </button>+ ))}+ </div>+ )}<span className="min-w-0 flex-1" />{showSearch && (/* basis 200px 但允许收缩:窄窗口(右栏可被压到 ~270px)时先压缩搜索框,@@ -805,19 +908,6 @@ export function UnifiedModelList({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@@ -833,8 +923,17 @@ export function UnifiedModelList({paymentRequired && 'opacity-55',)}>+ {/* 行首供应商标:与模型选择器的行形态对齐(那边也是「厂标 · 名字 ·+ 价格」)。registry 的 name 不含厂牌字样(是「Opus 5」不是+ 「Claude Opus 5」),厂牌信息只能靠图标承载。 */}+ <ProviderLogoMark+ providerId={provider.id}+ routing={provider.routing}+ size={15}+ className="shrink-0 text-[var(--text-secondary)]"+ /><span- className="min-w-0 truncate text-14 font-medium"+ className="min-w-0 shrink-0 truncate text-14 font-medium"style={{color:capability || anyOn@@ -844,6 +943,29 @@ export function UnifiedModelList({>{rep.name}</span>+ {/* 价格档与折扣紧跟模型名(不单独成列):这一列不是用来纵向比价的,+ 是用来在读到某个模型名时顺手知道它贵不贵。拿不到报价就整个+ 不渲染 —— 不画假的「$」也不画「—」。 */}+ {(() => {+ const priceDisplay = rowPriceDisplay(row);+ if (!priceDisplay) return null;+ if (priceDisplay.kind === 'free') {+ return (+ <PriceFreeBadge label={t('newChat.modelSelector.pricing.free')} />+ );+ }+ if (priceDisplay.tier === undefined) return null;+ return (+ <PriceTierMarks+ priceDisplay={priceDisplay}+ symbol={priceDisplay.symbol ?? '$'}+ tier={priceDisplay.tier}+ litOf={litWholeMarks}+ formatClipPct={(pct) => String(pct)}+ exposeLit={false}+ />+ );+ })()}{provider.id === MANAGED_OLLAMA_PROVIDER_ID && (<LocalPackagingTag libraryName={row.id} />)}@@ -891,21 +1013,12 @@ export function UnifiedModelList({<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)}+ {/* 上下文窗口已移进高级设置抽屉的「规格」段:它是「查一次就够」+ 的属性,常驻列表只会让每行更碎,而真正要决策的是「这个模型贵不贵、+ 开没开」。抽屉里给的还是带千分位的准确 token 数 —— 列表这种紧凑+ 位置的 1M / 128K 缩写在真实数据里是歧义的(1,000,000 /+ 1,048,576 / 1,050,000 都印成 1M)。 */}+ {rowAdvancedButton(row)}{/* 能力模型行没有显示轴 ⇒ 没有开关(全页开关语义唯一 = 显示);占同宽空位,保证开关/上下文列跨行对齐。 */}{capability && (@@ -1100,6 +1213,30 @@ export function UnifiedModelList({}}/>)}+ <ModelAdvancedDrawer+ provider={provider}+ row={advancedRow}+ open={advancedRow !== null}+ onOpenChange={(next) => {+ if (!next) setAdvancedRow(null);+ }}+ pricePresentationOf={pricePresentationOf}+ disabled={advancedRow ? rowDisabledEffective(advancedRow) : false}+ paymentRequired={advancedRow ? isRowPaymentRequired(advancedRow) : false}+ onDisable={(row) => {+ // 抽屉里的停用/启用与列表行同一条写入路径(乐观覆盖 + IPC),不另开一套。+ setRowDisabled(row, !rowDisabledEffective(row));+ setAdvancedRow(null);+ }}+ {...(provider.id === MANAGED_OLLAMA_PROVIDER_ID+ ? {+ onDeleteLocal: (row: UnionModelRow) => {+ setAdvancedRow(null);+ void deleteInstalledModel(row);+ },+ }+ : {})}+ /></div>);}diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsxindex de672456e3..9e2530b741 100644--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx@@ -9,6 +9,7 @@ import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { computeQuotaPace, type QuotaPace } from '@/lib/quotaPace';+import { formatClaudeSubscriptionPlanLabel } from '@/lib/subscriptionPlanLabel';import { cn } from '@/lib/utils';import type {ClaudeSubscriptionUsageSnapshot,@@ -104,23 +105,6 @@ function effectiveQuotaSeverity(window: ClaudeUsageWindow): QuotaSeverity {: localSeverity;}-/** 未知套餐保留原始拼写,只补齐首字母大写;非字符串脏值按缺失处理。 */-function formatPlanType(subscriptionType: unknown): string | null {- if (typeof subscriptionType !== 'string') return null;- const trimmed = subscriptionType.trim();- if (!trimmed) return null;-- const knownPlans: Record<string, string> = {- max: 'Max',- pro: 'Pro',- team: 'Team',- enterprise: 'Enterprise',- };- return (- knownPlans[trimmed.toLowerCase()] ?? `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`- );-}-/** reset 时间按本地时区展示:当天仅时分,跨天补月日。 */function formatResetAt(resetsAt: number | null | undefined,@@ -415,7 +399,7 @@ export function QuotaHoverCard({const { t, i18n } = useTranslation();// 测试可只注入 t;运行时再优先跟随应用当前语言格式化日期。const locale = i18n?.resolvedLanguage ?? i18n?.language;- const planLabel = formatPlanType(snapshot?.subscriptionType);+ const planLabel = formatClaudeSubscriptionPlanLabel(snapshot?.subscriptionType);// utilization 是 updatedAt 时刻的观测值,用观测时刻算节奏,避免旧快照随渲染时间自漂移;// 缺有效观测时刻则不算节奏——回退渲染时刻会让趋势随倒计时重渲染无新数据自跳档。const paceNowMs = snapshotdiff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex e8279e8f45..2d477ae1d5 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -74,6 +74,7 @@ import {} from '@/hooks/useClaudeAccountUsage';import { useModelAccessCreditUsage } from '@/hooks/useModelAccessCreditUsage';import { resolveCreditTotals, type CreditTotals } from '@/lib/creditPoolTotals';+import { formatCodexPlanLabel } from '@/lib/subscriptionPlanLabel';import {requestClaudeSubscriptionRefresh,useClaudeSubscriptionUsage,@@ -148,21 +149,6 @@ const QUOTA_POPOVER_CLOSE_GRACE_MS = 200;const DEFAULT_MONEY_SYMBOL = DEFAULT_USAGE_CURRENCY === 'CNY' ? '¥' : '$';const DEFAULT_MONEY_PLACEHOLDER = `${DEFAULT_MONEY_SYMBOL}—`;-const PLAN_TYPE_LABELS: Record<string, string> = {- free: 'Free',- go: 'Go',- plus: 'Plus',- pro: 'Pro',- prolite: 'Pro Lite',- team: 'Team',- self_serve_business_usage_based: 'Self Serve Business Usage Based',- business: 'Business',- enterprise_cbp_usage_based: 'Enterprise CBP Usage Based',- enterprise: 'Enterprise',- edu: 'Edu',- unknown: 'Unknown',-};-// 软日限额系数 + 紧凑金额格式化已抽到 lib/usageFormat.ts (与首页仪表盘共用同口径)。/** chip / tooltip 共用: 一个 metric 的最终展示形态。 */@@ -262,16 +248,6 @@ function parseCreditBalance(balance: string | null | undefined): {return { formatted };}-function formatPlanType(planType: string | null | undefined): string | null {- const trimmed = planType?.trim();- if (!trimmed) return null;- const knownLabel = PLAN_TYPE_LABELS[trimmed];- if (knownLabel) return knownLabel;- return trimmed- .replace(/[_-]+/g, ' ')- .replace(/\b\w/g, (char) => char.toUpperCase());-}-function clampPercent(value: number): number {if (!Number.isFinite(value)) return 0;return Math.min(100, Math.max(0, value));@@ -557,7 +533,7 @@ function buildCodexTooltipNode(return buildTooltipNode(lines);}- const planLabel = formatPlanType(snapshot.planType);+ const planLabel = formatCodexPlanLabel(snapshot.planType);const credits = snapshot.credits;const parsedCredits = parseCreditBalance(credits?.balance);diff --git a/apps/desktop/src/renderer/hooks/useModelContextLimit.ts b/apps/desktop/src/renderer/hooks/useModelContextLimit.tsnew file mode 100644index 0000000000..8f704a37c8--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useModelContextLimit.ts@@ -0,0 +1,159 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';++import { createLogger } from '@/lib/logger';++import type { AgentKind } from '@cindy/model-providers';++import type { ModelContextLimitView } from '../../shared/modelContextLimit';+import type { ModelPriceOverrideTarget } from '../../shared/modelPriceOverride';++const log = createLogger('UseModelContextLimit');++/**+ * 输入框边打字边写盘会把每个按键都变成一次 IPC + 落盘。300ms 与+ * `useCompactionSettings` 同口径。+ */+const WRITE_DEBOUNCE_MS = 300;++export interface ModelContextLimitState {+ /** 用户设定的上限(token 数);null = 跟随路由窗口。加载完成前也是 null。 */+ limit: number | null;+ isCustomized: boolean;+ /** 首次读取尚未回来 —— 输入框在此期间不该显示成「未自定义」而闪一下。 */+ loading: boolean;+ /** 就地设值(debounce 落盘)。传 null 立即恢复默认。 */+ setLimit: (next: number | null) => void;+ /** 恢复默认(删 override)。 */+ reset: () => Promise<void>;+}++/**+ * 单模型上下文上限的读写。main 侧是唯一真源(`model-context-limit-store`),+ * 这里不缓存副本:写入返回落盘后的有效值,直接用它更新,避免「UI 显示的和实际生效的」+ * 分叉。+ *+ * target 为 null(未选中模型 / 抽屉关着)时 hook 空转,不发 IPC。+ */+export function useModelContextLimit(+ target: { providerId: string; agent: AgentKind; modelId: string } | null,+): ModelContextLimitState {+ const key = target ? `${target.agent}:${target.providerId}:${target.modelId}` : null;+ // 依赖用扁平 key 而不是对象:调用方多半在渲染里现构造 target 字面量,+ // 用对象做依赖会每帧重新发 IPC。+ const stableTarget = useMemo<ModelPriceOverrideTarget | null>(+ () =>+ target+ ? { providerId: target.providerId, agent: target.agent, modelId: target.modelId }+ : null,+ // eslint-disable-next-line react-hooks/exhaustive-deps -- key 是 target 三元组的完整投影+ [key],+ );++ const [limit, setLimitState] = useState<number | null>(null);+ const [isCustomized, setIsCustomized] = useState(false);+ const [loading, setLoading] = useState(stableTarget !== null);+ const mountedRef = useRef(false);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const pendingRef = useRef<{ target: ModelPriceOverrideTarget; limit: number | null } | null>(+ null,+ );++ const apply = useCallback((view: ModelContextLimitView) => {+ if (!mountedRef.current) return;+ setLimitState(view.limit);+ setIsCustomized(view.isCustomized);+ }, []);++ const reload = useCallback(async () => {+ if (!stableTarget) {+ setLimitState(null);+ setIsCustomized(false);+ setLoading(false);+ return;+ }+ setLoading(true);+ try {+ apply(await window.electronAPI.maker.getModelContextLimit(stableTarget));+ } catch (err) {+ log.warn('getModelContextLimit failed', err);+ if (mountedRef.current) {+ setLimitState(null);+ setIsCustomized(false);+ }+ } finally {+ if (mountedRef.current) setLoading(false);+ }+ }, [apply, stableTarget]);++ const commit = useCallback(+ async (t: ModelPriceOverrideTarget, next: number | null) => {+ try {+ apply(await window.electronAPI.maker.setModelContextLimit(t, next));+ } catch (err) {+ // 写失败要回到磁盘真值,不能让 UI 停在一个没落盘的乐观值上。+ log.warn('setModelContextLimit failed', err);+ await reload();+ }+ },+ [apply, reload],+ );++ const flushPending = useCallback(() => {+ if (timerRef.current) {+ clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ const pending = pendingRef.current;+ pendingRef.current = null;+ return pending;+ }, []);++ const setLimit = useCallback(+ (next: number | null) => {+ if (!stableTarget) return;+ setLimitState(next);+ setIsCustomized(next !== null);+ if (next === null) {+ // 恢复默认是个明确动作,不 debounce —— 用户点了「恢复默认」就该立刻生效。+ flushPending();+ void commit(stableTarget, null);+ return;+ }+ pendingRef.current = { target: stableTarget, limit: next };+ if (timerRef.current) clearTimeout(timerRef.current);+ timerRef.current = setTimeout(() => {+ timerRef.current = null;+ const pending = pendingRef.current;+ pendingRef.current = null;+ if (pending) void commit(pending.target, pending.limit);+ }, WRITE_DEBOUNCE_MS);+ },+ [commit, flushPending, stableTarget],+ );++ const reset = useCallback(async () => {+ if (!stableTarget) return;+ flushPending();+ try {+ apply(await window.electronAPI.maker.resetModelContextLimit(stableTarget));+ } catch (err) {+ log.warn('resetModelContextLimit failed', err);+ await reload();+ }+ }, [apply, flushPending, reload, stableTarget]);++ useEffect(() => {+ mountedRef.current = true;+ void reload();+ return () => {+ mountedRef.current = false;+ // 卸载(关抽屉 / 切模型)时把 debounce 中的值补落盘 —— 用户填完就关抽屉是常见操作,+ // 丢掉这次输入会让人以为「设了但没生效」。+ const pending = flushPending();+ if (pending)+ void window.electronAPI.maker.setModelContextLimit(pending.target, pending.limit);+ };+ }, [flushPending, reload]);++ return { limit, isCustomized, loading, setLimit, reset };+}diff --git a/apps/desktop/src/renderer/hooks/useModelPricing.ts b/apps/desktop/src/renderer/hooks/useModelPricing.tsindex ac542f4a25..7c54b6515b 100644--- a/apps/desktop/src/renderer/hooks/useModelPricing.ts+++ b/apps/desktop/src/renderer/hooks/useModelPricing.ts@@ -100,16 +100,55 @@ function isValidCatalog(value: unknown, kind: PricingKind): value is ModelPricin);}+/**+ * 报价读写都经过这一层防御性取值:preload 面缺这几个方法时**降级为「没有报价」**,+ * 而不是让整个消费页崩掉。+ *+ * 为什么必须在这里挡:`load()` 下面那个 `.catch` 抓不到 —— 直接解引用+ * `usage.getModelPricing` 是**同步抛出**,发生在 `.then` 链建立之前。同理+ * `subscribePricing` 一抛就会打断 effect,连卸载清理都不会注册。+ *+ * 什么时候真会缺:升级窗口期的旧 preload,以及只投影部分能力的宿主。同一条哲学见+ * `useCodexRateLimits` 的 `readCodexRateLimitsSafely`(「Missing/older preload ...+ * degrade to no extra tooltip rows」)——价格是**装饰性信息**,拿不到就不显示,+ * 不该把它的缺失升级成页面级故障。+ */+function pricingApi(): {+ getModelPricing?: () => Promise<unknown>;+ getReferenceModelPricing?: () => Promise<unknown>;+ onModelPricingChanged?: (listener: (pricing: unknown) => void) => () => void;+ onReferenceModelPricingChanged?: (listener: (pricing: unknown) => void) => () => void;+} | null {+ return (+ (+ window as unknown as {+ electronAPI?: { maker?: { usage?: ReturnType<typeof pricingApi> } };+ }+ ).electronAPI?.maker?.usage ?? null+ );+}+function readPricing(kind: PricingKind): Promise<unknown> {- return kind === 'gateway'- ? window.electronAPI.maker.usage.getModelPricing()- : window.electronAPI.maker.usage.getReferenceModelPricing();+ const api = pricingApi();+ const read = kind === 'gateway' ? api?.getModelPricing : api?.getReferenceModelPricing;+ if (typeof read !== 'function') return Promise.resolve(null);+ try {+ return Promise.resolve(read.call(api));+ } catch {+ return Promise.resolve(null);+ }}function subscribePricing(kind: PricingKind, listener: (pricing: unknown) => void): () => void {- return kind === 'gateway'- ? window.electronAPI.maker.usage.onModelPricingChanged(listener)- : window.electronAPI.maker.usage.onReferenceModelPricingChanged(listener);+ const api = pricingApi();+ const subscribe =+ kind === 'gateway' ? api?.onModelPricingChanged : api?.onReferenceModelPricingChanged;+ if (typeof subscribe !== 'function') return () => {};+ try {+ return subscribe.call(api, listener) ?? (() => {});+ } catch {+ return () => {};+ }}function load(diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex efa8439346..090f271d88 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1764,6 +1764,62 @@"invalid": "Enter valid non-negative input and output prices","loadFailed": "Couldn’t load the price estimate. Please try again.","saveFailed": "Couldn’t save the price estimate. Please try again."+ },+ "advanced": {+ "open": "Advanced settings",+ "openAria": "Advanced settings for {{name}}",+ "noDescription": "No description in the catalog",+ "identity": "Identity",+ "modelId": "Model ID",+ "providerLabel": "Provider",+ "group": "Group",+ "status": "Status",+ "statusUnset": "Not labeled",+ "defaultEnabled": "Enabled by default",+ "defaultEnabledOn": "Yes",+ "defaultEnabledOff": "No",+ "spec": "Specs",+ "contextWindow": "Context window",+ "tokensApprox": "tokens (~{{approx}})",+ "catalogMissing": "Not in the catalog",+ "capability": "Capabilities",+ "capabilityHint": "Determined by the model itself, not configurable. There is no local data source for audio / video / document input — image input is the only one with evidence.",+ "imageInput": "Image input",+ "supported": "Supported",+ "unsupported": "Not supported",+ "undeclared": "Not declared",+ "pricing": "Pricing",+ "pricingLabel": "Pricing",+ "noPricing": "No pricing data for this route",+ "perMtok": "/ million tokens",+ "discount": "Discount",+ "defaultEffort": "Default reasoning effort",+ "defaultEffortHint": "The starting level when a new task picks this model; you can still change it inside a task. Grayed-out levels are not offered by this model.",+ "contextLimit": "Context limit",+ "contextLimitHint": "Auto-compaction triggers past this length; lower it to compact earlier. The field is in K = 1,000 tokens.",+ "contextLimitAria": "Context limit (thousands of tokens)",+ "contextLimitRoute": "Upstream max {{tokens}} tokens",+ "contextLimitOverWindow": "Above the upstream maximum — requests may be truncated. Only set this if you know the route is misconfigured.",+ "restoreDefault": "Restore default",+ "engines": "Engine support",+ "enginesHint": "Whether this model appears in the model picker under each engine. Turning it off hides it only for that engine.",+ "engineUnsupported": "Not supported",+ "engineNoFast": "No Fast",+ "engineDefaultEffort": "default {{effort}}",+ "vision": {+ "vision": "Supported",+ "no-vision": "Not supported",+ "unknown": "Unknown"+ },+ "visionSource": {+ "vision": "Evidence: the local prefix list marks this model as vision-capable",+ "no-vision": "Evidence: the local prefix list marks this model as not vision-capable",+ "unknown": "Not on the list — the catalog has no modality field, so this stays unknown"+ }+ },+ "kindFilter": {+ "all": "All",+ "aria": "Filter by model type"}},"genericOAuth": {@@ -2067,6 +2123,17 @@"cleared": "Image generation API key cleared","clearFailed": "Failed to clear image generation API key"}+ },+ "usage": {+ "percentUsed": "{{percent}}% used",+ "resetsAt": "Resets {{at}}",+ "claudePlanFallback": "Claude subscription",+ "claudeWeekly": "7-day window {{percent}}%",+ "scopedModel": "{{model}} {{percent}}%",+ "openClaudeUsage": "Open usage page",+ "codexPlanFallback": "ChatGPT subscription",+ "codexSecondary": "Secondary window {{percent}}%",+ "codexResetCredits": "{{count}} limit reset credits"}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d3e7f103f1..0f91557f65 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1763,6 +1763,62 @@"invalid": "0 以上の有効な入力・出力料金を入力してください","loadFailed": "料金見積もりを読み込めませんでした。もう一度お試しください。","saveFailed": "料金見積もりを保存できませんでした。もう一度お試しください。"+ },+ "advanced": {+ "open": "詳細設定",+ "openAria": "{{name}} の詳細設定",+ "noDescription": "カタログに説明がありません",+ "identity": "識別情報",+ "modelId": "モデル ID",+ "providerLabel": "プロバイダー",+ "group": "グループ",+ "status": "ステータス",+ "statusUnset": "未設定",+ "defaultEnabled": "既定で有効",+ "defaultEnabledOn": "はい",+ "defaultEnabledOff": "いいえ",+ "spec": "仕様",+ "contextWindow": "コンテキストウィンドウ",+ "tokensApprox": "tokens(約 {{approx}})",+ "catalogMissing": "カタログに情報なし",+ "capability": "機能",+ "capabilityHint": "モデル自体で決まり、設定はできません。音声 / 動画 / ドキュメント入力はローカルにデータソースがなく、画像入力だけ判定材料があります。",+ "imageInput": "画像入力",+ "supported": "対応",+ "unsupported": "非対応",+ "undeclared": "宣言なし",+ "pricing": "料金",+ "pricingLabel": "料金",+ "noPricing": "このルートの料金データがありません",+ "perMtok": "/ 100万 tokens",+ "discount": "割引",+ "defaultEffort": "既定の推論強度",+ "defaultEffortHint": "新しいタスクでこのモデルを選んだときの初期レベルです。タスク内でも一時的に変更できます。グレーのレベルはこのモデルでは使えません。",+ "contextLimit": "コンテキスト上限",+ "contextLimitHint": "この長さを超えると自動圧縮が始まります。小さくすると圧縮が早く起きます。入力欄の単位は K = 1,000 tokens です。",+ "contextLimitAria": "コンテキスト上限(千 tokens)",+ "contextLimitRoute": "上流の最大 {{tokens}} tokens",+ "contextLimitOverWindow": "上流の上限を超えています。リクエストが切り詰められる可能性があります —— ルート設定が誤っていると分かっている場合にだけ指定してください。",+ "restoreDefault": "既定に戻す",+ "engines": "エンジン対応",+ "enginesHint": "各エンジンでこのモデルをモデル選択に表示するかどうか。オフにしてもそのエンジンでのみ非表示になります。",+ "engineUnsupported": "非対応",+ "engineNoFast": "Fast なし",+ "engineDefaultEffort": "既定 {{effort}}",+ "vision": {+ "vision": "対応",+ "no-vision": "非対応",+ "unknown": "不明"+ },+ "visionSource": {+ "vision": "根拠: ローカルの接頭辞リストで画像入力対応と判定",+ "no-vision": "根拠: ローカルの接頭辞リストで画像入力非対応と判定",+ "unknown": "リストに未収録 —— カタログにモダリティ項目がないため不明のまま"+ }+ },+ "kindFilter": {+ "all": "すべて",+ "aria": "モデル種別で絞り込み"}},"genericOAuth": {@@ -2066,6 +2122,17 @@"cleared": "画像生成 API key をクリアしました","clearFailed": "画像生成 API key のクリアに失敗しました"}+ },+ "usage": {+ "percentUsed": "{{percent}}% 使用済み",+ "resetsAt": "{{at}} にリセット",+ "claudePlanFallback": "Claude サブスクリプション",+ "claudeWeekly": "7 日ウィンドウ {{percent}}%",+ "scopedModel": "{{model}} {{percent}}%",+ "openClaudeUsage": "使用量ページを開く",+ "codexPlanFallback": "ChatGPT サブスクリプション",+ "codexSecondary": "副ウィンドウ {{percent}}%",+ "codexResetCredits": "上限リセット券 {{count}} 枚"}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 9c92387acf..73cb82d530 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1763,6 +1763,62 @@"invalid": "0 이상의 올바른 입력 및 출력 가격을 입력하세요","loadFailed": "가격 추정치를 불러오지 못했습니다. 다시 시도하세요.","saveFailed": "가격 추정치를 저장하지 못했습니다. 다시 시도하세요."+ },+ "advanced": {+ "open": "고급 설정",+ "openAria": "{{name}} 고급 설정",+ "noDescription": "카탈로그에 설명이 없습니다",+ "identity": "식별 정보",+ "modelId": "모델 ID",+ "providerLabel": "제공자",+ "group": "그룹",+ "status": "상태",+ "statusUnset": "표시되지 않음",+ "defaultEnabled": "기본 사용",+ "defaultEnabledOn": "예",+ "defaultEnabledOff": "아니요",+ "spec": "사양",+ "contextWindow": "컨텍스트 윈도우",+ "tokensApprox": "tokens (약 {{approx}})",+ "catalogMissing": "카탈로그에 없음",+ "capability": "기능",+ "capabilityHint": "모델 자체로 정해지며 설정할 수 없습니다. 오디오 / 비디오 / 문서 입력은 로컬에 데이터 출처가 없고, 이미지 입력만 판단 근거가 있습니다.",+ "imageInput": "이미지 입력",+ "supported": "지원",+ "unsupported": "지원 안 함",+ "undeclared": "선언되지 않음",+ "pricing": "가격",+ "pricingLabel": "가격",+ "noPricing": "이 경로의 가격 데이터가 없습니다",+ "perMtok": "/ 100만 tokens",+ "discount": "할인",+ "defaultEffort": "기본 추론 강도",+ "defaultEffortHint": "새 작업에서 이 모델을 선택할 때의 초기 단계입니다. 작업 안에서 임시로 바꿀 수 있습니다. 회색 단계는 이 모델이 제공하지 않습니다.",+ "contextLimit": "컨텍스트 상한",+ "contextLimitHint": "이 길이를 넘으면 자동 압축이 시작됩니다. 낮추면 압축이 더 일찍 일어납니다. 입력란 단위는 K = 1,000 tokens입니다.",+ "contextLimitAria": "컨텍스트 상한(천 tokens)",+ "contextLimitRoute": "업스트림 최대 {{tokens}} tokens",+ "contextLimitOverWindow": "업스트림 최대치를 넘었습니다. 요청이 잘릴 수 있습니다 —— 경로 설정이 잘못됐다고 확인한 경우에만 이렇게 입력하세요.",+ "restoreDefault": "기본값 복원",+ "engines": "엔진 지원",+ "enginesHint": "각 엔진에서 이 모델을 모델 선택기에 표시할지 여부입니다. 끄면 해당 엔진에서만 숨겨집니다.",+ "engineUnsupported": "지원 안 함",+ "engineNoFast": "Fast 없음",+ "engineDefaultEffort": "기본 {{effort}}",+ "vision": {+ "vision": "지원",+ "no-vision": "지원 안 함",+ "unknown": "알 수 없음"+ },+ "visionSource": {+ "vision": "근거: 로컬 접두어 목록에서 이미지 입력 지원으로 판정",+ "no-vision": "근거: 로컬 접두어 목록에서 이미지 입력 미지원으로 판정",+ "unknown": "목록에 없음 —— 카탈로그에 모달리티 항목이 없어 알 수 없음으로 둡니다"+ }+ },+ "kindFilter": {+ "all": "전체",+ "aria": "모델 유형으로 필터"}},"genericOAuth": {@@ -2066,6 +2122,17 @@"cleared": "이미지 생성 API key를 지웠습니다","clearFailed": "이미지 생성 API key 지우기에 실패했습니다"}+ },+ "usage": {+ "percentUsed": "{{percent}}% 사용",+ "resetsAt": "{{at}} 초기화",+ "claudePlanFallback": "Claude 구독",+ "claudeWeekly": "7일 창 {{percent}}%",+ "scopedModel": "{{model}} {{percent}}%",+ "openClaudeUsage": "사용량 페이지 열기",+ "codexPlanFallback": "ChatGPT 구독",+ "codexSecondary": "보조 창 {{percent}}%",+ "codexResetCredits": "한도 초기화 크레딧 {{count}}장"}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 11137b42b2..2151713f5b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1763,6 +1763,62 @@"invalid": "请输入有效且不小于 0 的输入、输出价格","loadFailed": "API 估价加载失败,请重试","saveFailed": "API 估价保存失败,请重试"+ },+ "advanced": {+ "open": "高级设置",+ "openAria": "{{name}} 的高级设置",+ "noDescription": "目录未提供说明",+ "identity": "标识",+ "modelId": "模型 ID",+ "providerLabel": "供应商",+ "group": "分组",+ "status": "状态",+ "statusUnset": "未标注",+ "defaultEnabled": "默认启用",+ "defaultEnabledOn": "是",+ "defaultEnabledOff": "否",+ "spec": "规格",+ "contextWindow": "上下文窗口",+ "tokensApprox": "tokens(约 {{approx}})",+ "catalogMissing": "目录未提供",+ "capability": "能力",+ "capabilityHint": "由模型本身决定,不可配置。音频 / 视频 / 文档输入本地没有数据源,只有图片输入这一项有判据。",+ "imageInput": "图片输入",+ "supported": "支持",+ "unsupported": "不支持",+ "undeclared": "未声明",+ "pricing": "报价",+ "pricingLabel": "报价",+ "noPricing": "该路由没有报价数据",+ "perMtok": "/ 百万 tokens",+ "discount": "折扣",+ "defaultEffort": "默认推理强度",+ "defaultEffortHint": "新任务选中该模型时的初始档位,任务内仍可临时调整。灰掉的档位该模型不提供。",+ "contextLimit": "上下文上限",+ "contextLimitHint": "超过这个长度触发自动压缩,调小可让压缩提前发生。输入框单位 K = 1,000 tokens。",+ "contextLimitAria": "上下文上限(千 tokens)",+ "contextLimitRoute": "上游最大 {{tokens}} tokens",+ "contextLimitOverWindow": "已超过上游最大长度,请求可能被截断——仅在确认路由配置有误时这么填。",+ "restoreDefault": "恢复默认",+ "engines": "引擎支持",+ "enginesHint": "该模型在各引擎下是否出现在模型选择器中。关闭后仅在这个引擎里隐藏,其他引擎不受影响。",+ "engineUnsupported": "不支持",+ "engineNoFast": "无 Fast",+ "engineDefaultEffort": "默认 {{effort}}",+ "vision": {+ "vision": "支持",+ "no-vision": "不支持",+ "unknown": "未知"+ },+ "visionSource": {+ "vision": "判据:本地前缀名单判定为支持看图",+ "no-vision": "判据:本地前缀名单判定为不支持看图",+ "unknown": "名单未覆盖 —— 目录没有模态字段,只能判未知"+ }+ },+ "kindFilter": {+ "all": "全部",+ "aria": "按模型类型筛选"}},"genericOAuth": {@@ -2066,6 +2122,17 @@"cleared": "已清除图像生成 API key","clearFailed": "清除图像生成 API key 失败"}+ },+ "usage": {+ "percentUsed": "{{percent}}% 已使用",+ "resetsAt": "{{at}} 重置",+ "claudePlanFallback": "Claude 订阅",+ "claudeWeekly": "7 天窗口 {{percent}}%",+ "scopedModel": "{{model}} {{percent}}%",+ "openClaudeUsage": "打开用量页面",+ "codexPlanFallback": "ChatGPT 订阅",+ "codexSecondary": "次级窗口 {{percent}}%",+ "codexResetCredits": "限额重置券 {{count}} 张"}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex f461ac7b92..70f4a97cb7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1763,6 +1763,62 @@"invalid": "請輸入有效且不小於 0 的輸入、輸出價格","loadFailed": "API 估價載入失敗,請重試","saveFailed": "API 估價儲存失敗,請重試"+ },+ "advanced": {+ "open": "進階設定",+ "openAria": "{{name}} 的進階設定",+ "noDescription": "目錄未提供說明",+ "identity": "識別",+ "modelId": "模型 ID",+ "providerLabel": "供應商",+ "group": "分組",+ "status": "狀態",+ "statusUnset": "未標註",+ "defaultEnabled": "預設啟用",+ "defaultEnabledOn": "是",+ "defaultEnabledOff": "否",+ "spec": "規格",+ "contextWindow": "上下文視窗",+ "tokensApprox": "tokens(約 {{approx}})",+ "catalogMissing": "目錄未提供",+ "capability": "能力",+ "capabilityHint": "由模型本身決定,無法設定。音訊 / 視訊 / 文件輸入本機沒有資料來源,只有圖片輸入這一項有判準。",+ "imageInput": "圖片輸入",+ "supported": "支援",+ "unsupported": "不支援",+ "undeclared": "未宣告",+ "pricing": "報價",+ "pricingLabel": "報價",+ "noPricing": "此路由沒有報價資料",+ "perMtok": "/ 百萬 tokens",+ "discount": "折扣",+ "defaultEffort": "預設推理強度",+ "defaultEffortHint": "新任務選中此模型時的初始檔位,任務內仍可臨時調整。灰掉的檔位此模型不提供。",+ "contextLimit": "上下文上限",+ "contextLimitHint": "超過這個長度觸發自動壓縮,調小可讓壓縮提前發生。輸入框單位 K = 1,000 tokens。",+ "contextLimitAria": "上下文上限(千 tokens)",+ "contextLimitRoute": "上游最大 {{tokens}} tokens",+ "contextLimitOverWindow": "已超過上游最大長度,請求可能被截斷——僅在確認路由設定有誤時這麼填。",+ "restoreDefault": "恢復預設",+ "engines": "引擎支援",+ "enginesHint": "此模型在各引擎下是否出現在模型選擇器中。關閉後僅在這個引擎裡隱藏,其他引擎不受影響。",+ "engineUnsupported": "不支援",+ "engineNoFast": "無 Fast",+ "engineDefaultEffort": "預設 {{effort}}",+ "vision": {+ "vision": "支援",+ "no-vision": "不支援",+ "unknown": "未知"+ },+ "visionSource": {+ "vision": "判準:本機前綴名單判定為支援看圖",+ "no-vision": "判準:本機前綴名單判定為不支援看圖",+ "unknown": "名單未涵蓋 —— 目錄沒有模態欄位,只能判未知"+ }+ },+ "kindFilter": {+ "all": "全部",+ "aria": "依模型類型篩選"}},"genericOAuth": {@@ -2066,6 +2122,17 @@"cleared": "已清除影像生成 API key","clearFailed": "清除影像生成 API key 失敗"}+ },+ "usage": {+ "percentUsed": "{{percent}}% 已使用",+ "resetsAt": "{{at}} 重設",+ "claudePlanFallback": "Claude 訂閱",+ "claudeWeekly": "7 天視窗 {{percent}}%",+ "scopedModel": "{{model}} {{percent}}%",+ "openClaudeUsage": "開啟用量頁面",+ "codexPlanFallback": "ChatGPT 訂閱",+ "codexSecondary": "次級視窗 {{percent}}%",+ "codexResetCredits": "限額重設券 {{count}} 張"}},"experimental": {diff --git a/apps/desktop/src/renderer/lib/modelPricePresentation.ts b/apps/desktop/src/renderer/lib/modelPricePresentation.tsnew file mode 100644index 0000000000..64ab1d3d7b--- /dev/null+++ b/apps/desktop/src/renderer/lib/modelPricePresentation.ts@@ -0,0 +1,58 @@+/**+ * 按「行来源 + 行引擎」解析出这一行该显示的报价 —— 模型选择器与设置页 → 模型列表共用。+ *+ * 为什么必须共用而不是各写一份:这段逻辑里有三条**看不出来但错了就会显示假价**的判断,+ * 复制一份必然漂:+ * 1. XD 实际报价与非 XD 的 Catalog 参考价是**两份独立快照**,只按行来源选快照,+ * 相同 modelId 不跨 provider 复用或兜底。+ * 2. XD 且报价来自 gateway 时要叠 `CatalogModel.cost`(服务端下发的折后展示价),+ * 由 `modelPricePresentation` 与标准价跑比例一致性校验后才认定为折扣。+ * 3. 非 XD 的 `approximate` 报价在展示时抹掉近似标记(`displayQuote`)——+ * 参考价本身就是估算,再挂一次「近似」是重复表达。+ *+ * device-link 远程与「行来源未知需回溯解析」这两件事留在调用方:前者是选择器特有的+ * 协议缺口(控制端价格不能与被控端 cost 拼成一个结果),后者需要面板级的当前来源上下文。+ * 设置页两者都不涉及——它永远知道自己在哪个供应商面板、哪个引擎。+ */++import type { AgentKind } from '@/hooks/useAgentCapabilities';+import { modelPricePresentation, type ModelPricePresentation } from '@/lib/modelPriceFormat';++import { getModel, type ProviderView } from '@cindy/model-providers';++import { getModelPriceQuote } from '../../shared/modelPriceQuote';+import type { ModelPricingCatalog } from '../../shared/regionalMoney';++export interface ModelPricePresentationInput {+ /** 该行的来源供应商 id;已由调用方解析完毕(null = 无供应商概念的 flat 列表)。 */+ providerId: string | null;+ /** 查报价用的模型 id:有 wire id 就传 wire id(同一逻辑模型换引擎可能换一条报价)。 */+ modelId: string;+ /** 该行的**生效引擎**,不是面板级的当前引擎。 */+ agent: AgentKind | null;+ providers: ProviderView[];+ gatewayPricing: ModelPricingCatalog | null;+ referencePricing: ModelPricingCatalog | null;+}++export function resolveModelPricePresentation({+ providerId,+ modelId,+ agent,+ providers,+ gatewayPricing,+ referencePricing,+}: ModelPricePresentationInput): ModelPricePresentation | null {+ const pricing = providerId === 'xd' ? gatewayPricing : referencePricing;+ const quote = getModelPriceQuote(pricing, providerId, modelId, agent ?? undefined);+ if (providerId === 'xd' && (!quote || quote.source === 'gateway')) {+ // 网关快照还没到(null)且这一行也没有 quote:什么都不画,别先画一个错的。+ if (!quote && gatewayPricing == null) return null;+ const provider = providers.find((item) => item.id === providerId);+ const effectiveCost = provider && agent ? getModel(provider, modelId, agent)?.cost : undefined;+ return modelPricePresentation(quote ?? null, effectiveCost);+ }+ if (!quote) return null;+ const displayQuote = quote.approximate ? { ...quote, approximate: false } : quote;+ return modelPricePresentation(displayQuote, undefined);+}diff --git a/apps/desktop/src/renderer/lib/subscriptionPlanLabel.ts b/apps/desktop/src/renderer/lib/subscriptionPlanLabel.tsnew file mode 100644index 0000000000..7c1d6a73f3--- /dev/null+++ b/apps/desktop/src/renderer/lib/subscriptionPlanLabel.ts@@ -0,0 +1,53 @@+/**+ * 订阅套餐名的显示形态 —— 状态栏 chip / 悬停卡与设置页的供应商用量模块共用。+ *+ * 抽出来的原因:同一套「已知拼写查表 → 未知就规范化大小写」的逻辑原先在+ * `QuotaHoverCard`(Claude subscriptionType)与 `TodaySpendChip`(Codex planType)+ * 各有一份私有副本。设置页要显示第三处,再抄一遍就成三份 —— 三份必然漂,而套餐名是+ * 用户在两个不同界面里核对同一件事时最容易发现不一致的地方。+ *+ * 两个函数分开是因为**两家的取值域不同**,不是同一张表:Anthropic 给 pro / max /+ * team / enterprise,ChatGPT 还有 go / plus / prolite / *_usage_based 这类。合成一张表+ * 会让任一家的未知值悄悄命中另一家的条目。+ */++/** Anthropic 订阅(凭证 blob 的 subscriptionType)。未知套餐保留原始拼写,只补首字母大写。 */+export function formatClaudeSubscriptionPlanLabel(subscriptionType: unknown): string | null {+ if (typeof subscriptionType !== 'string') return null;+ const trimmed = subscriptionType.trim();+ if (!trimmed) return null;++ const knownPlans: Record<string, string> = {+ max: 'Max',+ pro: 'Pro',+ team: 'Team',+ enterprise: 'Enterprise',+ };+ return (+ knownPlans[trimmed.toLowerCase()] ?? `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`+ );+}++const CODEX_PLAN_TYPE_LABELS: Record<string, string> = {+ free: 'Free',+ go: 'Go',+ plus: 'Plus',+ pro: 'Pro',+ prolite: 'Pro Lite',+ team: 'Team',+ self_serve_business_usage_based: 'Self Serve Business Usage Based',+ business: 'Business',+ enterprise_cbp_usage_based: 'Enterprise CBP Usage Based',+ enterprise: 'Enterprise',+ edu: 'Edu',+ unknown: 'Unknown',+};++/** ChatGPT / Codex 套餐(app-server 的 planType)。未知值按 snake/kebab → Title Case。 */+export function formatCodexPlanLabel(planType: string | null | undefined): string | null {+ const trimmed = planType?.trim();+ if (!trimmed) return null;+ const known = CODEX_PLAN_TYPE_LABELS[trimmed];+ if (known) return known;+ return trimmed.replace(/[_-]+/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase());+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 6fdebc8608..f489386a23 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5173,6 +5173,21 @@ interface ElectronAPI {resetModelPriceOverride: (target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,) => Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView>;+ /**+ * 单模型上下文上限 override(设置 → 模型 → 高级设置)。窗口是自动压缩比例的分母,+ * 调小它让压缩按用户设的长度提前触发。target 与价格 override 同形。+ * set 传 null = 恢复默认(删 override)。+ */+ getModelContextLimit: (+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,+ ) => Promise<import('../shared/modelContextLimit').ModelContextLimitView>;+ setModelContextLimit: (+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,+ limit: number | null,+ ) => Promise<import('../shared/modelContextLimit').ModelContextLimitView>;+ resetModelContextLimit: (+ target: import('../shared/modelPriceOverride').ModelPriceOverrideTarget,+ ) => Promise<import('../shared/modelContextLimit').ModelContextLimitView>;// 「在新窗口打开」会话多开openSessionInNewWindow: (sessionId: string, deviceId?: string | null) => Promise<void>;diff --git a/apps/desktop/src/shared/modelContextLimit.ts b/apps/desktop/src/shared/modelContextLimit.tsnew file mode 100644index 0000000000..79532c96e8--- /dev/null+++ b/apps/desktop/src/shared/modelContextLimit.ts@@ -0,0 +1,19 @@+/**+ * 单模型上下文上限 override 的跨进程形状。+ *+ * 目标三元组复用 `modelPriceOverride` 的 `ModelPriceOverrideTarget`+ * (providerId × agent × modelId)—— 两者是同一粒度的设置类 override,+ * 再定义一份同形类型只会让 IPC 两侧各自漂。+ *+ * 语义与存储见 main 侧 `maker-host/model-context-limit-store.ts` 头注。+ */++export interface ModelContextLimitView {+ /** 用户设定的上限(token 数);null = 跟随路由窗口。 */+ limit: number | null;+ /**+ * 是否被用户显式设过。与 `limit !== null` 不等价的意义在于:UI 要能区分+ * 「跟随默认」和「设了一个刚好等于默认的值」——后者在上游改窗口后不该被静默带走。+ */+ isCustomized: boolean;+}diff --git a/apps/desktop/tailwind.config.ts b/apps/desktop/tailwind.config.tsindex c903107976..7cd2d99514 100644--- a/apps/desktop/tailwind.config.ts+++ b/apps/desktop/tailwind.config.ts@@ -138,6 +138,16 @@ const config: Config = {from: { opacity: '1', transform: 'scale(1)' },to: { opacity: '0', transform: 'scale(0.95)' },},+ // 右侧抽屉:纯 translateX(compositor-only,同 §14.4 约束)。不带 opacity ——+ // 面板贴着右缘滑入,淡入会让它看起来"从内容里浮现"而不是"从边缘推进来"。+ 'drawer-in-right': {+ from: { transform: 'translateX(100%)' },+ to: { transform: 'translateX(0)' },+ },+ 'drawer-out-right': {+ from: { transform: 'translateX(0)' },+ to: { transform: 'translateX(100%)' },+ },},animation: {// 功能性 loading spinner 使用 DESIGN.md §14.4 明确登记的语义循环 token;@@ -165,6 +175,12 @@ const config: Config = {'confirm-content-layout-in var(--motion-enter, 250ms) cubic-bezier(0, 0, 0.2, 1)','confirm-content-layout-out':'confirm-content-layout-out var(--motion-exit, 150ms) cubic-bezier(0.4, 0, 1, 1)',+ // 进场用「起步快、收尾稳」的曲线(与系统抽屉手感一致);退场略快。+ // forwards 同 float-out:Radix 等 animationend 才卸载,不驻留会闪回原位。+ 'drawer-in-right':+ 'drawer-in-right var(--motion-enter, 250ms) cubic-bezier(0.32, 0.72, 0, 1)',+ 'drawer-out-right':+ 'drawer-out-right var(--motion-exit, 150ms) cubic-bezier(0.4, 0, 1, 1) forwards',},},},