Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 任务级上下文窗口档位 UI:ContextWindowBudgetChip 与挂载

Zhang Yunjin771f9968e059
diff --git a/apps/desktop/src/renderer/components/status/ContextWindowBudgetChip.tsx b/apps/desktop/src/renderer/components/status/ContextWindowBudgetChip.tsx
new file mode 100644
index 0000000000..9036c18ec6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/status/ContextWindowBudgetChip.tsx
@@ -0,0 +1,933 @@
+/**
+ * ContextWindowBudgetChip — 任务级工作上下文窗口档位选择。
+ *
+ * 语义(与 main 侧 `model-context-settings.ts` 同一口径):
+ * - 档位决定**本任务**的工作窗口(分母);全局的自动压缩阈值百分比不动。
+ * - 「跟随模型默认」= 上报 null,不把当前默认值快照进任务。
+ * - 有效窗口还受用户在同一路由上设过的模型级上限与目录物理上限约束(由 main 收敛),
+ * 所以这里展示的是**选择**,运行时真值仍以圆环的窗口读数为准。
+ *
+ * 生效时机:main 在落库后把新窗口应用到活实例(空闲关 handle、下一条消息冷重建;
+ * 回合中登记 pending,回合结束生效)。菜单文案如实说明,不做「立即生效」的假承诺。
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import type * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { getModelsForVendor } from '@/lib/modelDefinitions';
+import { formatModelPriceAmount } from '@/lib/modelPriceFormat';
+import * as sessionService from '@/lib/sessionService';
+import { toast } from '@/lib/toast';
+import {
+ STATUS_CARD_HOVER_CLOSE_GRACE_MS,
+ STATUS_CARD_HOVER_OPEN_DELAY_MS,
+ registerStatusBarCard,
+ type StatusBarCardHandle,
+} from '@/lib/statusBarCards';
+
+import { cn } from '@/lib/utils';
+import { handOffTabFromCard } from '@/lib/focusTraversal';
+import { extractIpcError } from '@/utils/ipcError';
+import { useGatewayModelPricing, useReferenceModelPricing } from '@/hooks/useModelPricing';
+import { useModelContextLimit } from '@/hooks/useModelContextLimit';
+import {
+ buildContextWindowBudgetOptions,
+ contextWindowBudgetTierPercent,
+ normalizeContextWindowBudget,
+ resolveContextWindowBudgetBase,
+} from '../../../shared/sessionContextWindowBudget';
+import { resolveRouteContextWindowBounds } from '../../../shared/sessionContextWindow';
+import {
+ normalizeSessionContextWindowBounds,
+ type SessionContextWindowBounds,
+} from '../../../shared/sessionContextWindowBounds';
+import type { MakerAgentKindWire } from '../../../shared/agentKindConversion';
+import { getModelPriceQuote } from '../../../shared/modelPriceQuote';
+import type { Catalog } from '@cindy/model-providers';
+import type { ModelPriceQuote } from '../../../shared/regionalMoney';
+
+/**
+ * 触发器上的标记:一枚「上下双向箭头」符号 + 当前档位百分比(用户拍板)—— 底栏不挂文字标签,
+ * 但百分比要看得见(它是「这个任务用多大窗口」的相对口径)。用 ↕ 而不是方括号:方括号语义不明确
+ * (读不出"窗口大小"),↕ 至少表达"可上可下 / 可调"。
+ * 当前档位的绝对值仍进 `aria-label`(`triggerLabel`)与卡片行(`aria-checked` 命中的那一行)。
+ *
+ * 它是普通文本(不是图标、也不是括号),与 `¥`、圆环 `1%` 同基线、同字重、同颜色层
+ * (`opacity-60`,与货币符号完全一致)。
+ *
+ * 字号用 `text-11`(用户拍板,`text-10` 略小):箭头字形天生比数字高 —— 12px 下 `↕` 墨迹 12px
+ * (上缘 11 / 下缘 1),而 `¥` 是 9/0、圆环 `1%` 是 9/1;11px 下墨迹 ≈11px(10.1/0.9),
+ * 与两个邻居同一基线、同一中心线,观感上也和它们的**字面**大小相当。换字形/字号只需改这两行。
+ */
+const CONTEXT_WINDOW_MARKER = '↕';
+
+export interface ContextWindowBudgetChipProps {
+ sessionId: string;
+ /** 运行期上下文占用,用于「换小档位会立刻触发压缩」的提示。 */
+ contextTokens: number;
+ model: string;
+ /** 路由来源;用来查实际报价(网关实价优先,其余用参考价)。 */
+ providerId?: string | null;
+ agentKind: 'cc' | 'codex' | 'pi';
+ /**
+ * 该任务实际路由的一份目录(renderer 侧的 `providers`):
+ * 默认窗口与「上限档」都按**路由**解析,不用 availableModels 扁平表
+ * (同 id 跨 provider 去重后归属已丢,取到的 max 可能属于另一条路由)。
+ * **只在本地任务生效**:device-link 远程任务的路由/上限在被控端,传本地目录会
+ * 造成“看到的档位 ≠ 被控端生效值”,那种情况下降级为「只允许收紧」。
+ * 拿不到时降级为扁平表的默认值 + 只允许收紧。
+ */
+ providers?: Pick<Catalog, 'providers'> | null;
+ /** device-link 远程任务:档位必须按被控端的目录算(模型 id 跨设备不唯一)。 */
+ deviceId?: string;
+ disabled?: boolean;
+}
+
+/** 该窗口落在哪条价带:band 的 maxInputTokens 是开区间,缺价继承报价基准价。 */
+function inputPriceAtTokens(quote: ModelPriceQuote | undefined, tokens: number): string | null {
+ if (!quote) return null;
+ const band = quote.inputTokenPriceBands
+ ?.filter((entry) => tokens >= entry.minInputTokens
+ && (entry.maxInputTokens === undefined || tokens < entry.maxInputTokens))
+ .at(-1);
+ const perMtok = band?.inputPerMtok ?? quote.inputPerMtok;
+ if (typeof perMtok !== 'number' || !Number.isFinite(perMtok) || perMtok <= 0) return null;
+ return formatModelPriceAmount(perMtok, quote.currency);
+}
+
+export function ContextWindowBudgetChip({
+ sessionId,
+ contextTokens,
+ model,
+ providerId,
+ agentKind,
+ providers = null,
+ deviceId,
+ disabled = false,
+}: ContextWindowBudgetChipProps) {
+ const { t } = useTranslation();
+ const [committing, setCommitting] = useState(false);
+ // 卡片开合:**指针悬浮**展开(与货币 chip 的「用量明细」卡同一节奏:延迟 300ms 开、离开宽限
+ // 200ms 关),键盘仍走 Radix 自己的 Enter/Space 开、Esc 关。
+ const [cardOpen, setCardOpen] = useState(false);
+ // 浮层宿主:紧跟触发器之后(见 popover.tsx 的 portalContainer 注释)。
+ const [cardPortalHost, setCardPortalHost] = useState<HTMLDivElement | null>(null);
+ const cardOpenTimerRef = useRef<number | null>(null);
+ const cardCloseTimerRef = useRef<number | null>(null);
+ // 指针打开时 Radix 关闭后会把焦点还给触发器,Chrome 会把这次程序化聚焦判成 `:focus-visible`
+ // → 出现蓝色外圈(键盘用户需要它,鼠标用户不需要)。用指针来源区分:只有指针打开的这一轮
+ // 才在关闭时阻止焦点归还;Tab/Enter 打开时保持原行为。
+ // (写在组件顶部:它有早退 return,hook 不能落在 return 之后。)
+ const openedByPointerRef = useRef(false);
+ // P2:过期刷新经 ref 中转(refreshIfStale 声明在后,useCallback 依赖里直接引用会 TDZ)。
+ const refreshIfStaleRef = useRef<(() => void) | null>(null);
+ const cardPointerInsideRef = useRef(false);
+ // 悬浮打开时不要把焦点抢进卡片(键盘打开才需要)。指针是否在卡片区域内决定"要不要抢焦点"。
+ const cardOpenSourceRef = useRef<'hover' | 'focus'>('hover');
+ // 互斥协调器的本实例句柄(分屏可能同时挂载两个 chip,认实例而不是认种类)。
+ const cardHandleRef = useRef<StatusBarCardHandle | null>(null);
+ // 档位行的 Tab 停靠点(roving tabindex):单选组只占一个 Tab 位,方向键在组内移动焦点。
+ const tierRowRefs = useRef<Array<HTMLButtonElement | null>>([]);
+ const [tierTabStopIndex, setTierTabStopIndex] = useState(0);
+ const clearCardTimers = useCallback(() => {
+ if (cardOpenTimerRef.current !== null) {
+ window.clearTimeout(cardOpenTimerRef.current);
+ cardOpenTimerRef.current = null;
+ }
+ if (cardCloseTimerRef.current !== null) {
+ window.clearTimeout(cardCloseTimerRef.current);
+ cardCloseTimerRef.current = null;
+ }
+ }, []);
+ useEffect(() => clearCardTimers, [clearCardTimers]);
+ const openCard = useCallback((source: 'hover' | 'focus') => {
+ clearCardTimers();
+ cardOpenSourceRef.current = source;
+ // 过期缓存刷新:悬浮与点击都走这里(键盘路径在 onOpenChange 里已有)。
+ // 刷新函数声明在本组件后部(hook 返回值),经 ref 中转避免 TDZ。
+ refreshIfStaleRef.current?.();
+ // 两卡互斥:自己展开时,用量卡立刻收起(用户要求"该窗体为唯一窗体");
+ // 分屏下同种类的另一张 chip 也在这条路径上被关掉。
+ cardHandleRef.current?.request();
+ setCardOpen(true);
+ }, [clearCardTimers]);
+ const closeCard = useCallback(() => {
+ clearCardTimers();
+ cardHandleRef.current?.release();
+ setCardOpen(false);
+ }, [clearCardTimers]);
+ const scheduleCardOpen = useCallback(() => {
+ clearCardTimers();
+ cardOpenTimerRef.current = window.setTimeout(() => {
+ cardOpenTimerRef.current = null;
+ openCard('hover');
+ }, STATUS_CARD_HOVER_OPEN_DELAY_MS);
+ }, [clearCardTimers, openCard]);
+ const scheduleCardClose = useCallback(() => {
+ clearCardTimers();
+ cardCloseTimerRef.current = window.setTimeout(() => {
+ cardCloseTimerRef.current = null;
+ closeCard();
+ }, STATUS_CARD_HOVER_CLOSE_GRACE_MS);
+ }, [clearCardTimers, closeCard]);
+ const cancelCardClose = useCallback(() => {
+ if (cardCloseTimerRef.current !== null) {
+ window.clearTimeout(cardCloseTimerRef.current);
+ cardCloseTimerRef.current = null;
+ }
+ }, []);
+ // 另一张卡(用量卡或分屏里同种类的另一份)展开时由协调器回调过来 → 立刻收起。
+ useEffect(() => {
+ const handle = registerStatusBarCard('context-window', () => {
+ clearCardTimers();
+ setCardOpen(false);
+ });
+ cardHandleRef.current = handle;
+ return () => {
+ cardHandleRef.current = null;
+ handle.unregister();
+ };
+ }, [clearCardTimers]);
+ // 在飞期间菜单项是 disabled(见 isDisabled)——用户看得见的禁用,而不是静默丢弃;
+ // 跨窗口并发(两个 chip 实例各有自己的 state)由 main 侧的会话锁 + 终值比对负责收敛。
+ // 分档计费模型的档位就是价带:把每条档位的输入单价摆在选项里,用户选的是成本。
+ const gatewayPricing = useGatewayModelPricing();
+ const referencePricing = useReferenceModelPricing();
+
+ // 目录默认窗口与物理上限:拿不到默认值就没有档位可给(例如能力缓存还没到),此时不渲染,
+ // 而不是拿兜底数字造一个用户点不到真值的控件。上限缺省 = 只能收紧(老目录形态)。
+ // 路由级解析优先(唯一候选 + 实际 providerId,Pi/Codex 一视同仁),扁平表只做默认值的
+ // 降级来源;远程任务(deviceId)不用本地目录,只用被控端能力缓存里的默认值。
+ const makerAgent = agentKind === 'cc' ? 'claude-code' : agentKind;
+ const modelEntry = useMemo(
+ () => getModelsForVendor(agentKind, deviceId).find((entry) => entry.id === model),
+ [agentKind, deviceId, model],
+ );
+ const localRouteBounds = useMemo(
+ () => (providers && !deviceId
+ ? resolveRouteContextWindowBounds(providers, makerAgent, providerId ?? null, model)
+ : null),
+ [providers, deviceId, makerAgent, providerId, model],
+ );
+ // **权威边界**:本地由 main 按会话实际路由解析(与运行期收敛同源),远程向被控端拉同一份
+ // 口径的只读查询。拿不到(老被控端/失败)就退回「只允许收紧」+ 下方 renderer 自解析的兜底,
+ // 绝不把「另一条路由」的值当成事实。
+ const {
+ bounds: authoritativeBounds,
+ boundsFetchedAt,
+ refresh: refreshBounds,
+ refreshIfStale: refreshBoundsIfStale,
+ } = useSessionContextWindowBounds(deviceId, sessionId, model, makerAgent, providerId ?? null);
+ // P2-1:把过期刷新交给 ref(openCard 在本 hook 之前定义,直接引用会 TDZ)。
+ useEffect(() => {
+ refreshIfStaleRef.current = refreshBoundsIfStale;
+ return () => {
+ if (refreshIfStaleRef.current === refreshBoundsIfStale) refreshIfStaleRef.current = null;
+ };
+ }, [refreshBoundsIfStale]);
+ // main 的解析优先(它认得隐式来源与模型级上限);未返回前用 renderer 自解析的兜底,
+ // 兜底解不出来源时只会更保守(上限缺省 = 只允许收紧)。
+ const defaultWindow = authoritativeBounds?.defaultWindow
+ ?? localRouteBounds?.defaultWindow
+ ?? (typeof modelEntry?.contextWindow === 'number' && modelEntry.contextWindow > 0
+ ? modelEntry.contextWindow
+ : null);
+ // 上限只信路由级:扁平表跨 provider 去重后归属已丢,不能当上限来源。
+ const maxWindow = authoritativeBounds?.maxWindow ?? localRouteBounds?.maxWindow ?? null;
+ // 同一路由上用户设过的模型级「上下文上限」是更紧的上界(main 侧 tighterBudget 一定会取
+ // 更紧者);不读它会让档位表和生效值分叉。providerId 缺失时用路由解出的来源补上
+ // (与 main 侧的来源解析同口径);远程任务的这个值来自被控端(见 remoteBounds)。
+ const limitProviderId = authoritativeBounds?.providerId
+ ?? localRouteBounds?.providerId
+ ?? (deviceId ? null : providerId ?? null);
+ const modelLimitView = useModelContextLimit(
+ model && limitProviderId && !deviceId
+ ? { agent: makerAgent, providerId: limitProviderId, modelId: model }
+ : null,
+ );
+ // main 返回的 modelLimit 是权威值(它就是 tighterBudget 用的那个);renderer 自读只作兜底。
+ const modelLimit = authoritativeBounds
+ ? (authoritativeBounds.modelLimit ?? null)
+ : (typeof modelLimitView.limit === 'number' && modelLimitView.limit > 0
+ ? modelLimitView.limit
+ : null);
+
+ // 有效默认档 = 「跟随默认」在运行期真正得到的窗口。main 的 resolveConfiguredContextWindow 在
+ // **没有任务预算**时用的就是模型级「上下文上限」(它同时是用户强行解开路由配置的逃生口,
+ // 刻意不按目录夹),只有它为空时才落到目录默认窗口。所以这里不能用 min(默认, 上限):
+ // 自定义连接未声明窗口时目录默认只有 200K 兜底,而会话实际跑在模型级上限 1.05M 上,
+ // 用 min 会让 chip 报 200K、与圆环和运行期打架(用户实测报障)。
+ // 生效窗口以 main / 被控端**申报**的为准(同一套 resolveConfiguredContextWindow 的结果)。
+ //
+ // **老被控端根本不申报这两个字段**(`effectiveWindowsReported === false`):不能把「缺省」
+ // 读成「无上限」—— 目录没声明 contextWindowMax 时那样会让 modelLimit 顶成物理上限,而被控端
+ // 运行期还会被 `contextWindow` 夹一次(实测:200K 的路由,远程菜单却给出 800K 档)。所以
+ // 老端退回保守口径「只允许收紧」:默认档 = min(目录默认, 模型级上限),物理上限 = 目录默认。
+ const effectiveWindowsReported = authoritativeBounds?.effectiveWindowsReported === true;
+ const conservativeWindow = defaultWindow !== null && modelLimit !== null
+ ? Math.min(defaultWindow, modelLimit)
+ : (modelLimit ?? defaultWindow);
+ const effectiveMaxWindow = effectiveWindowsReported
+ ? (authoritativeBounds?.maxEffectiveWindow ?? maxWindow)
+ : (maxWindow ?? defaultWindow);
+ // 百分比分母只看**申报的上限**(生效上限 / 目录申报上限);`maxWindow ?? defaultWindow`
+ // 那个兜底只用来夹已存值 —— 默认窗口不是上限,未核实路由可以真的跑在它之上。
+ const reportedMaxWindow = effectiveWindowsReported
+ ? (authoritativeBounds?.maxEffectiveWindow ?? maxWindow)
+ : maxWindow;
+ const ceiling = [effectiveMaxWindow, modelLimit]
+ .filter((value): value is number => typeof value === 'number' && value > 0)
+ .reduce<number | null>((min, value) => (min === null || value < min ? value : min), null);
+ // 「模型默认」档的真实含义 = 清掉任务预算后跟随默认会得到的窗口,由 main / 被控端算好下发;
+ // 老被控端不申报时取保守值(见上)。
+ const effectiveDefaultWindow = effectiveWindowsReported
+ ? (authoritativeBounds?.defaultEffectiveWindow ?? (modelLimit ?? defaultWindow))
+ : conservativeWindow;
+
+ // 已存值可能来自手改偏好文件(写入口拦不住已存在的数据):先按同一口径归一化,
+ // 否则会在选项里补出一个「点了必失败」的档(update 入口对非整数直接拒绝)。
+ //
+ // 来源是**权威边界**里的 `budget`(main / 被控端从偏好文件读出,与档位表同源):
+ // 预算是 main 侧偏好条目而不是会话列,远程会话拿不到被控端的库,所以不再从会话快照读。
+ // 提交成功后先本地记账(隧道/落盘完成前 UI 立即显示新档),边界刷新回来一致即清除。
+ // 乐观记账只在**同一个会话(同一设备)**内有效:预算是偏好文件里按 sessionId 存的条目、
+ // 与路由无关,所以切模型/来源/引擎不该丢掉它(否则刷新回来前会闪回旧档);但同一张卡被换到
+ // 别的会话/设备时必须立刻失效,否则旧值会一直盖住新上下文的权威 budget。
+ // `confirmedAt` = 写入确实落地的时刻;只有在这之后回来的权威回答才有资格清它 —— 提交前发出、
+ // 之后才回来的那次请求(以及路由切换命中旧缓存)不能把刚写的值改回去。
+ const budgetScopeKey = `${deviceId ?? 'local'}|${sessionId}`;
+ const [optimisticBudget, setOptimisticBudget] = useState<
+ { scopeKey: string; value: number | null; confirmedAt: number } | undefined
+ >(undefined);
+ const storedBudget = useMemo(() => {
+ if (optimisticBudget && optimisticBudget.scopeKey === budgetScopeKey) return optimisticBudget.value;
+ return normalizeContextWindowBudget(authoritativeBounds?.budget ?? null);
+ }, [optimisticBudget, budgetScopeKey, authoritativeBounds?.budget]);
+ useEffect(() => {
+ if (!optimisticBudget) return;
+ if (optimisticBudget.scopeKey !== budgetScopeKey) {
+ setOptimisticBudget(undefined);
+ return;
+ }
+ if (normalizeContextWindowBudget(authoritativeBounds?.budget ?? null) === optimisticBudget.value) {
+ setOptimisticBudget(undefined);
+ return;
+ }
+ // 提交已确认,且这次权威回答发生在确认之后:以权威值收口。对方设备改了值、被夹紧、
+ // 或这条路由的查询失败返回 null(老被控端/隧道抖动)都走这里,避免旧值永久盖着权威值。
+ if (boundsFetchedAt >= optimisticBudget.confirmedAt) setOptimisticBudget(undefined);
+ }, [optimisticBudget, budgetScopeKey, authoritativeBounds?.budget, boundsFetchedAt]);
+
+ // 每行显示的百分比都按**同一个基准**算(与档位推导同源):默认档因此显示 `100% · 1.05M`
+ // 而不是「绝对值在前」,旧值补的当前档也有百分比 —— 行的形态与颜色在整列里保持一个样式。
+ const tierBase = useMemo(() => {
+ // 三个上限(生效上限 / 目录申报上限 / 模型级上限)都没有 = 这条路由**没有已知上限**:
+ // 典型是自定义连接未声明窗口,目录只有 200K 兜底,而未核实路由会照单接受更大的预算。
+ // 这时不能拿默认窗口当分母 —— 已存的更大预算会显示成「500%」,还暗示「默认档就是顶格」。
+ // 基准未知就走既有的「只显绝对值」形态(percent === null 分支)。
+ if (reportedMaxWindow === null && modelLimit === null) return null;
+ const base = resolveContextWindowBudgetBase({
+ defaultWindow: effectiveDefaultWindow,
+ maxWindow: reportedMaxWindow,
+ modelLimit,
+ });
+ // 默认档永远不该超过 100%:万一拿到自相矛盾的边界(默认档 > 上限),取两者更大的一个
+ // 当分母 —— 宁可让上限档显示成不到 100%,也不打出 >100% 的行。
+ return base === null || effectiveDefaultWindow === null
+ ? base
+ : Math.max(base, effectiveDefaultWindow);
+ }, [effectiveDefaultWindow, reportedMaxWindow, modelLimit]);
+
+ const options = useMemo(() => {
+ if (effectiveDefaultWindow === null) return [];
+ // 档位表的上限 = main 会对**显式任务预算**夹的那个数:min(申报上限, 模型级上限)。
+ // 刻意不用 tierBase(它含 max(…, 默认档) 的抬升):未核实路由的默认档可以合法高于
+ // 声明上限(模型级上限是「路由配错了」的逃生口,写 null 就会真的生效),但 main 仍会把
+ // 任何显式预算夹到声明上限 —— 用抬升后的基准出 250K/500K 档,运行期只会得到 200K,
+ // 窗口与输入价带一起说谎(Greptile P1,2026-09-24)。
+ // 默认档高于上限时,只有它那一行的百分比按 max(上限, 默认档) 算(见 tierBase),
+ // 菜单不会出现运行期达不到的档位。
+ // 老被控端维持原口径:只允许收紧,基准就是那个保守上限,不拿默认档去抬。
+ const base = buildContextWindowBudgetOptions(effectiveWindowsReported
+ ? { defaultWindow: effectiveDefaultWindow, maxWindow: reportedMaxWindow, modelLimit }
+ : { defaultWindow: effectiveDefaultWindow, maxWindow: effectiveMaxWindow, modelLimit });
+ // 已保存的预算可能不在当前档位集合里(目录默认值变过、或它来自模型级上限口径)。
+ // 补一条当前档,避免单选组没有匹配项而显示成空;同样按上限夹紧,否则单选组会
+ // 凭空多出比有效值更大的档。
+ // 远程拿不到边界时若已存着一个更大的预算(此前有边界时放大的,或别的控制端写的),
+ // 仍然把它补成当前档:单选组需要一项匹配已存值,否则界面没有选中项;选中它等于无变化、
+ // 不会写库,菜单里的说明针对的是「这里**提供**哪些档」,不是「当前值是多少」。
+ const raw = storedBudget ?? effectiveDefaultWindow;
+ const current = ceiling === null ? raw : Math.min(raw, ceiling);
+ if (base.some((option) => option.tokens === current)) return base;
+ // 已存值可能不在比例档里(旧固定档、或目录上限变过):只按绝对值补一项,
+ // **不套百分比标签**(避免「显示 50%、实际 48.8%」的误导)。
+ return [...base, { tokens: current, kind: 'current' as const }].sort(
+ (a, b) => a.tokens - b.tokens,
+ );
+ }, [storedBudget, effectiveDefaultWindow, effectiveMaxWindow, effectiveWindowsReported, reportedMaxWindow, modelLimit, ceiling]);
+
+ useEffect(() => {
+ if (options.length === 0) return;
+ const raw = authoritativeBounds?.budget;
+ if (raw !== null && raw !== undefined && raw < 1_000) {
+ // 非法值只可能来自手改偏好文件 / 旧数据;运行时会被 main 收敛,这里只留日志线索。
+ console.warn('[context-window-budget] ignoring out-of-range saved budget', { budget: raw });
+ }
+ }, [authoritativeBounds?.budget, options.length]);
+
+ // 当前档位的绝对值(早退之前就算出:Tab 停靠点的 effect 是 hook,必须在早退之前)。
+ const selectedTokens = storedBudget === null
+ ? effectiveDefaultWindow
+ : ceiling === null ? storedBudget : Math.min(storedBudget, ceiling);
+ // 单选组的 Tab 停靠点跟着选中档走(首次打开落在当前档上,而不是永远落在第一行)。
+ useEffect(() => {
+ const checkedIndex = options.findIndex((option) => option.tokens === selectedTokens);
+ if (checkedIndex >= 0) setTierTabStopIndex(checkedIndex);
+ }, [options, selectedTokens]);
+
+ if (effectiveDefaultWindow === null || options.length === 0 || selectedTokens === null) return null;
+
+ const agent = agentKind === 'cc' ? 'claude-code' : agentKind;
+ const quote = getModelPriceQuote(gatewayPricing, providerId, model, agent)
+ ?? getModelPriceQuote(referencePricing, providerId, model, agent);
+
+ // 当前档位占基准的百分比:与卡片行同一口径(默认档 = 100%)。
+ const selectedPercent = contextWindowBudgetTierPercent(selectedTokens, tierBase);
+ /**
+ * 方向键在单选组内移动**焦点**(不提交):`role="radio"` 语义下方向键必须能动,
+ * 而每次提交都会落库并可能触发活实例重建 —— 扫过一遍档位不该连写好几次库。
+ * 选中仍由 Enter / Space / 点击完成(与之前 Radix 菜单的键盘行为一致)。
+ * 焦点可能落在行上(键盘打开 + Tab)或浮层容器上(Radix 默认聚焦内容):
+ * 两种情况都按“当前行 → 选中行 → 停靠点”的顺序推出起点。
+ */
+ const handleTierKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
+ const rows = tierRowRefs.current.filter((row): row is HTMLButtonElement => row !== null);
+ if (rows.length === 0) return;
+ const activeIndex = rows.findIndex((row) => row === document.activeElement);
+ const checkedIndex = options.findIndex((option) => option.tokens === selectedTokens);
+ const base = activeIndex >= 0 ? activeIndex : checkedIndex >= 0 ? checkedIndex : tierTabStopIndex;
+ let next: number | null = null;
+ if (event.key === 'ArrowDown' || event.key === 'ArrowRight') next = base + 1;
+ else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') next = base - 1;
+ else if (event.key === 'Home') next = 0;
+ else if (event.key === 'End') next = rows.length - 1;
+ if (next === null) return;
+ event.preventDefault();
+ const wrapped = ((next % rows.length) + rows.length) % rows.length;
+ setTierTabStopIndex(wrapped);
+ rows[wrapped].focus();
+ };
+ const shrinkWarning = selectedTokens < contextTokens && contextTokens > 0;
+
+ const commit = async (tokens: number): Promise<void> => {
+ // 选中「有效默认档」上报 null(跟随默认,不快照当前值)。
+ const next = tokens === effectiveDefaultWindow ? null : tokens;
+ if (next === storedBudget) return;
+ if (committing) return;
+ setCommitting(true);
+ try {
+ if (deviceId) {
+ // device-link 远程任务:会话的库与运行实例都在被控端,必须走隧道命令;
+ // 写本机的镜像库不会生效,还会被下一次镜像覆盖。
+ await window.electronAPI.deviceLink.invoke(deviceId, 'maker:set-context-window-budget', [
+ sessionId,
+ next,
+ ]);
+ } else {
+ await sessionService.update(sessionId, { contextWindowBudget: next });
+ }
+ // 提交后失效缓存:被控端/主进程可能刚更新了该路由的上限,下次开菜单要拿最新的。
+ // 乐观值打上确认时刻(写入已经落地),随后这次 refresh 的结果(fetchedAt 必定晚于它)
+ // 才有资格把它收口 —— 之前 in-flight 的查询会被 effect 的 cancelled 丢弃,不会误清新值。
+ setOptimisticBudget({ scopeKey: budgetScopeKey, value: next, confirmedAt: Date.now() });
+ refreshBounds();
+ } catch (error) {
+ const unsupported = extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
+ toast.error(
+ unsupported
+ ? t('ccAgent.contextWindowBudget.remoteUnsupported')
+ : t('ccAgent.contextWindowBudget.saveFailed'),
+ );
+ console.warn('[context-window-budget] save failed', {
+ sessionId,
+ remote: Boolean(deviceId),
+ error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setCommitting(false);
+ }
+ };
+
+ const isDisabled = disabled || committing;
+
+
+
+ return (
+ <Popover
+ modal={false}
+ open={cardOpen}
+ onOpenChange={(open) => {
+ if (open) {
+ // 键盘/点击打开(指针不在触发器上)与悬浮打开走同一个开卡入口。
+ if (!cardPointerInsideRef.current) cardOpenSourceRef.current = 'focus';
+ refreshBoundsIfStale();
+ cardHandleRef.current?.request();
+ setCardOpen(true);
+ return;
+ }
+ closeCard();
+ }}
+ >
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ // 刻意不用原生 `disabled`:那会把触发器整个移出 Tab 序列 —— 用户实测 Tab 到左边
+ // 用量卡后就再也回不到本卡。只读任务(readOnly)或提交中不该连「看一眼当前档位」
+ // 都做不到;落档能力由档位行自己 disabled 拦住(与 TodaySpendChip 同一套
+ // 「可聚焦、可展开」的底栏卡片语义)。
+ aria-disabled={isDisabled || undefined}
+ data-context-window-budget-chip
+ onPointerDown={() => { openedByPointerRef.current = true; }}
+ onKeyDown={() => { openedByPointerRef.current = false; }}
+ // 与底栏的用量 chip(TodaySpendChip)保持一致:展开/收起只由 hover、焦点与
+ // outside-click 驱动,**点击不当作开关** —— `preventDefault` 让 Radix 的 toggle
+ // 不执行;否则悬浮展开后一点就收起,两张底栏卡片交互不一致(用户报障)。
+ // 点进来的来源按指针/键盘区分:指针路径必须“不抢焦点”(否则鼠标用户会看到蓝框)。
+ onClick={(event) => {
+ event.preventDefault();
+ openCard(openedByPointerRef.current ? 'hover' : 'focus');
+ }}
+ onPointerEnter={() => {
+ cardPointerInsideRef.current = true;
+ scheduleCardOpen();
+ }}
+ onPointerLeave={() => {
+ cardPointerInsideRef.current = false;
+ scheduleCardClose();
+ }}
+ // 视觉上没有数值,当前值必须进可访问名,否则读屏无从得知现在是多少。
+ aria-label={t('ccAgent.contextWindowBudget.triggerLabel', {
+ window: formatTokenCount(selectedTokens),
+ })}
+ className={cn(
+ // 与右下角用量 chip(`TodaySpendChip`:货币符号 + 金额)同一套视觉:同高 `h-5`、
+ // 同字号字重 `text-12 font-medium leading-none`、同颜色 `--msg-tool-card-chevron`
+ // (hover 提亮到 `foreground`)、同 `tabular-nums`;符号与数值同色,不做双色拼贴。
+ 'inline-flex h-5 shrink-0 items-center rounded-full text-12 font-medium leading-none tabular-nums',
+ 'text-[var(--msg-tool-card-chevron)] transition-colors hover:text-foreground',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ // 只读/提交中仍然可聚焦可展开,但把“不可改”表现在外观上。
+ isDisabled && 'cursor-default opacity-50',
+ )}
+ >
+ {/* `opacity-60` 与货币 chip 的符号完全一致(`TodaySpendChip`:`<span className="tabular-nums
+ opacity-60">{symbol}</span>`)—— 同一个色值再压 40%,两枚符号在底栏里才是同一种灰。
+ 百分比不压暗:它就是这一档的"值",与货币 chip 里金额的位置对应。 */}
+ <span className="shrink-0 text-11 leading-none opacity-60" aria-hidden="true">
+ {CONTEXT_WINDOW_MARKER}
+ </span>
+ {selectedPercent !== null && (
+ <span className="shrink-0">{t('ccAgent.contextWindowBudget.optionPercent', {
+ percent: selectedPercent,
+ })}</span>
+ )}
+ </button>
+ </PopoverTrigger>
+ {/* 浮层挂到触发器**紧跟其后**的宿主:portal 到 body 时卡片在文档最末,焦点一旦
+ 进卡就再 Tab 不回底栏(用户实测)—— DOM 顺序必须与视觉顺序一致。 */}
+ <div ref={setCardPortalHost} className="contents" />
+ <PopoverContent
+ align="end"
+ side="top"
+ sideOffset={8}
+ portalContainer={cardPortalHost}
+ className="min-w-[220px] p-1.5"
+ // Radix 给 FocusScope 写死 `loop: true`:Tab 在卡内永远环回,键盘用户一辈子出不了卡。
+ // 把两个 Tab 边缘接过来(capture 先于 Radix 的 bubble handler):在最后一个/第一个
+ // 可 Tab 元素上把焦点交出卡外,其余卡内 Tab 行为不变。
+ onKeyDownCapture={(event) => {
+ if (event.key !== 'Tab') return;
+ const cardRoot = event.currentTarget;
+ if (!(cardRoot instanceof HTMLElement)) return;
+ if (handOffTabFromCard(cardRoot, event)) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }}
+ // 悬浮打开不抢焦点(鼠标用户不该被移走焦点);键盘打开保持 Radix 默认,方向键照常可用。
+ onOpenAutoFocus={(event) => {
+ if (cardOpenSourceRef.current === 'hover') event.preventDefault();
+ }}
+ // 指针路径(悬浮或点击)关闭时不要把焦点还给触发器:Chrome 会把这次程序化聚焦判成
+ // `:focus-visible`,鼠标用户会看到一圈蓝框(用户报障)。键盘路径保持原行为 ——
+ // focus 指示必须留下,只是不给鼠标。
+ onCloseAutoFocus={(event) => {
+ if (cardOpenSourceRef.current === 'hover' || openedByPointerRef.current) {
+ event.preventDefault();
+ }
+ }}
+ onPointerEnter={() => {
+ cardPointerInsideRef.current = true;
+ cancelCardClose();
+ }}
+ onPointerLeave={() => {
+ cardPointerInsideRef.current = false;
+ scheduleCardClose();
+ }}
+ // 键盘导航挂在浮层上(而不是只挂在单选组上):Radix 打开时把焦点给浮层容器,
+ // 按键会落在容器而不是行上,挂在组上会收不到。
+ onKeyDown={handleTierKeyDown}
+ >
+ <div className="px-2 pb-1.5 pt-1">
+ <p className="text-12 font-medium text-[var(--text-primary)]">
+ {t('ccAgent.contextWindowBudget.menuTitle')}
+ </p>
+ {/* 说明与注解统一用 `--text-secondary`:即「用量明细」卡(货币符号那个界面)里
+ 说明文字的同一档灰(实测 rgb(111,111,111)),面板里只有一种「次要灰」。 */}
+ {/* 字号/字重与「用量明细」卡(货币符号那个界面)同一套:标题 12/500、说明 12/400、
+ 档位行 13/500、注解 12/400 —— 面板与卡片读起来才是同一个系统。 */}
+ <p className="mt-0.5 text-12 font-normal leading-[1.5] text-[var(--text-secondary)]">
+ {t('ccAgent.contextWindowBudget.menuHint')}
+ </p>
+ {deviceId && !authoritativeBounds && (
+ // 没能从被控端拿到该路由的边界(老版本 / 拉取失败):这里只能给出不超过
+ // 本地已知默认值的档位,文案必须如实说明,不能留给用户“能调大”的预期。
+ <p className="mt-0.5 text-12 font-normal leading-[1.5] text-[var(--text-secondary)]">
+ {t('ccAgent.contextWindowBudget.remoteTightenOnly')}
+ </p>
+ )}
+ {disabled && (
+ // 只读任务:卡片照常可展开(能看当前档位与价带),但档位行不可选 —— 给出原因,
+ // 而不是把所有行默默变灰。
+ <p className="mt-0.5 text-12 font-normal leading-[1.5] text-[var(--text-secondary)]">
+ {t('ccAgent.contextWindowBudget.readOnlyHint')}
+ </p>
+ )}
+ </div>
+ <div role="radiogroup" aria-label={t('ccAgent.contextWindowBudget.menuTitle')}>
+ {options.map((option, index) => {
+ const price = inputPriceAtTokens(quote, option.tokens);
+ return (
+ <TierRow
+ key={`${option.kind}-${option.tokens}`}
+ tokens={option.tokens}
+ checked={option.tokens === selectedTokens}
+ disabled={isDisabled}
+ onSelect={() => void commit(option.tokens)}
+ // roving tabindex:单选组只占一个 Tab 位,其余行用方向键抵达。
+ tabIndex={index === tierTabStopIndex ? 0 : -1}
+ buttonRef={(node) => {
+ tierRowRefs.current[index] = node;
+ }}
+ onFocus={() => setTierTabStopIndex(index)}
+ >
+ {(() => {
+ // 形态统一:`百分比 · 绝对值`(默认档 = 100% · 模型默认窗口);百分比与绝对值
+ // 同色(继承行色),不再出现「灰百分比 + 白绝对值」的两色拼贴。基准未知时只显绝对值。
+ const percent = contextWindowBudgetTierPercent(option.tokens, tierBase);
+ const absolute = formatTokenCount(option.tokens);
+ return (
+ <span className="tabular-nums">
+ {percent === null ? absolute : `${t('ccAgent.contextWindowBudget.optionPercent', { percent })} · ${absolute}`}
+ </span>
+ );
+ })()}
+ {option.kind === 'default' && (
+ <span className="ml-1.5 text-12 font-normal text-[var(--text-secondary)]">
+ {t('ccAgent.contextWindowBudget.optionDefault')}
+ </span>
+ )}
+ {price && (
+ <span className="ml-auto pl-3 text-12 font-normal tabular-nums text-[var(--text-secondary)]">
+ {t('ccAgent.contextWindowBudget.inputPrice', { price })}
+ </span>
+ )}
+ </TierRow>
+ );
+ })}
+ </div>
+ {shrinkWarning && (
+ <p className="mx-2 mt-1.5 border-t border-[var(--border-default)] pt-1.5 text-11 leading-[1.5] text-[var(--warning-fg)]">
+ {t('ccAgent.contextWindowBudget.shrinkWarning', {
+ used: formatTokenCount(contextTokens),
+ })}
+ </p>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/**
+ * 档位行:单选语义(`role="radio"` + `aria-checked`)的按钮。
+ *
+ * 为什么不用 Radix 的菜单项:卡片要**指针悬浮**就展开(与货币 chip 的「用量明细」卡同一交互),
+ * 而 Radix 菜单在展开时会把焦点抢进内容 —— 鼠标扫过底栏不该发生这种事;Popover 不抢焦点,
+ * 行的几何/选中标记沿用原菜单项(`pl-8 pr-2 py-1.5 rounded-sm` + 左侧实心圆点)。
+ */
+function TierRow({
+ tokens,
+ checked,
+ disabled,
+ onSelect,
+ tabIndex,
+ buttonRef,
+ onFocus,
+ children,
+}: {
+ tokens: number;
+ checked: boolean;
+ disabled: boolean;
+ onSelect: () => void;
+ /** roving tabindex:只有停靠点为 0,组内其余行为 −1。 */
+ tabIndex: number;
+ buttonRef: (node: HTMLButtonElement | null) => void;
+ onFocus: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={checked}
+ disabled={disabled}
+ data-token={tokens}
+ ref={buttonRef}
+ tabIndex={tabIndex}
+ onFocus={onFocus}
+ onClick={onSelect}
+ className={cn(
+ 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-left text-13 font-medium',
+ 'outline-none transition-colors hover:bg-sidebar-item-hover',
+ 'focus-visible:bg-sidebar-item-hover focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ )}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ {checked && (
+ <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.49991 0.876953C3.84222 0.876953 0.877075 3.8421 0.877075 7.49979C0.877075 11.1575 3.84222 14.123 7.49991 14.123C11.1576 14.123 14.1227 11.1575 14.1227 7.49979C14.1227 3.8421 11.1576 0.876953 7.49991 0.876953ZM7.49991 1.82695C10.6329 1.82695 13.1727 4.3668 13.1727 7.49979C13.1727 10.6328 10.6329 13.173 7.49991 13.173C4.36692 13.173 1.82708 10.6328 1.82708 7.49979C1.82708 4.3668 4.36692 1.82695 7.49991 1.82695ZM7.49991 4.37695C5.77492 4.37695 4.37708 5.77479 4.37708 7.49979C4.37708 9.22479 5.77492 10.623 7.49991 10.623C9.22491 10.623 10.6227 9.22479 10.6227 7.49979C10.6227 5.77479 9.22491 4.37695 7.49991 4.37695Z"
+ fill="currentColor"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ />
+ </svg>
+ )}
+ </span>
+ {children}
+ </button>
+ );
+}
+
+/**
+ * 档位 / chip 的 token 缩写 —— **窗口尺寸口径**:`250000 → "250K"`、`262144 → "262.1K"`、
+ * `1048576 → "1.05M"`。
+ *
+ * 这与**用量族**(`formatCompactTokens`、以及会话页圆环 tooltip 与压缩确认框本地那份:小写或大写
+ * 单位但恒一位小数)刻意不是同一套:窗口尺寸要能分辨量级接近的档位,一位小数会把 1,048,576 读成
+ * "1.0M"、把 1,050,000 读成 "1.1M"(看上去差 10%,实际差 0.14%),用户无从判断真值。
+ * 圆环是**用量指示器**(已用 / 窗口 + 百分比),它的取整属于用量口径,不要拿这份去"统一"它。
+ *
+ * 比例档的值是精确百分比,这里只做显示缩写(K 段一位小数、M 段两位、去掉末尾 0),
+ * 落库与生效的仍是精确整数。
+ */
+function formatTokenCount(n: number): string {
+ if (!Number.isFinite(n) || n <= 0) return '0';
+ const trim = (text: string): string =>
+ text.includes('.') ? text.replace(/0+$/, '').replace(/\.$/, '') : text;
+ if (n >= 1_000_000) return `${trim((n / 1_000_000).toFixed(2))}M`;
+ if (n >= 1_000) {
+ // 进位不跨档:999,999 的一位小数会读成 "1000K"(量级已是 M、单位却还停在 K)。
+ if (n / 1_000 >= 999.95) return `${trim((n / 1_000_000).toFixed(2))}M`;
+ return `${trim((n / 1_000).toFixed(1))}K`;
+ }
+ return String(Math.round(n));
+}
+
+/** 边界有 TTL:被控端(或本机设置)改了模型级上限后,重开菜单能拿到新值而不是永久陈旧。 */
+const BOUNDS_TTL_MS = 60_000;
+
+/**
+ * 缓存条目是否过期(TTL 过 / 无条目)。抽成纯函数供单测:
+ * 「重开菜单必须拉新值」的行为依赖这条判定,时序驱动测试在 fake timers + React
+ * 调度器组合下不稳定(passive effect 提交时机会被 fake 掉)。
+ */
+export function isBoundsCacheEntryStale(
+ entry: { fetchedAt: number } | undefined | null,
+ now: number,
+): boolean {
+ if (!entry) return true;
+ return !(now - entry.fetchedAt < BOUNDS_TTL_MS);
+}
+
+interface CachedBounds {
+ value: SessionContextWindowBounds | null;
+ fetchedAt: number;
+}
+
+/** 同一 (设备, 会话, 引擎, 来源, 模型) 的边界短时缓存,避免每次开合菜单都打一次隧道/主进程。 */
+const boundsCache = new Map<string, CachedBounds>();
+
+function cacheKey(
+ deviceId: string | undefined,
+ sessionId: string,
+ model: string,
+ agentKind: string,
+ providerId: string | null,
+): string {
+ // agentKind 必须进 key:同一会话跨引擎切换且 model 字符串相同时,两个引擎的路由/上限不同。
+ // providerId 同理:同一模型跨来源的物理上限与模型级上限都可能不同(否则会把 A 来源的边界
+ // 当成 B 来源的权威值缓存下来)。
+ return `${deviceId ?? 'local'}${sessionId}${agentKind}${providerId ?? '-'}${model}`;
+}
+
+/** 仅供测试:清掉跨用例的缓存(生产里键包含设备/会话,不会这样复用)。 */
+/** 仅供测试:清空跨实例共享缓存(预算/缓存口径变更时避免用例间串味)。 */
+export function __clearAllBoundsCachesForTest(): void {
+ boundsCache.clear();
+}
+
+/** 仅供测试:把所有缓存条目标记为已过期(TTL+1 前移),用于「过期后重开必拉新」的行为测试。 */
+export function __expireAllBoundsCachesForTest(): void {
+ for (const entry of boundsCache.values()) entry.fetchedAt -= BOUNDS_TTL_MS + 1;
+}
+
+export function resetRemoteContextWindowBoundsCache(): void {
+ boundsCache.clear();
+}
+
+/**
+ * 任务窗口档位表的权威边界。本地经 main 的 `maker:get-context-window-bounds` handler,
+ * 远程经 device-link 的同名 channel(被控端算)——两侧同一口径,所以本地/远程共用一条路径。
+ *
+ * 查询必须带上**界面上正在显示的路由**(`agentKind` / `providerId` / `model`):延迟切换期间
+ * 会话行还是旧路由,不带上路由会被按旧模型回答,档位表与显示值一起停在旧模型上。
+ *
+ * 拿不到时返回 null:调用方必须退回「只允许收紧」,不能拿本机目录的值冒充被控端。
+ */
+/**
+ * 预算提交后的跨实例通知:`refresh` 删缓存 + 重拉只作用于提交的那一个 hook 实例,
+ * 分屏 / 双窗口里的其它卡片实例读的是自己的 boundsState —— 不通知就永远停在旧档位,
+ * 甚至被 `next === storedBudget` 提前跳过、无法真正清除预算(Greptile P2,2026-10-17)。
+ * 提交实例自己跳过(它已经重拉过)。
+ */
+const boundsReloadListeners = new Set<{ id: number; key: string; fire: () => void }>();
+let boundsReloadListenerSeq = 0;
+function notifyBoundsReload(exceptId: number, key: string): void {
+ for (const listener of boundsReloadListeners) {
+ if (listener.id !== exceptId && listener.key === key) listener.fire();
+ }
+}
+
+export function useSessionContextWindowBounds(
+ deviceId: string | undefined,
+ sessionId: string,
+ model: string,
+ agentKind: MakerAgentKindWire,
+ providerId?: string | null,
+): {
+ bounds: SessionContextWindowBounds | null;
+ /** 当前键那份权威回答的落盘时刻(0 = 还没拿到过);调用方用它判断回答是否晚于自己的提交。 */
+ boundsFetchedAt: number;
+ refresh: () => void;
+ refreshIfStale: () => void;
+} {
+ const key = cacheKey(deviceId, sessionId, model, agentKind, providerId ?? null);
+ const [boundsState, setBoundsState] = useState<{
+ key: string;
+ value: SessionContextWindowBounds | null;
+ fetchedAt: number;
+ }>(() => {
+ const cached = boundsCache.get(key);
+ return { key, value: cached?.value ?? null, fetchedAt: cached?.fetchedAt ?? 0 };
+ });
+ // 会话/模型切换时**渲染期**就换锚(缓存命中直接派生,不必等 effect),避免闪现上一个
+ // 会话的上限;in-flight 结果按 key 丢弃。fetchedAt 一并暴露:调用方(chip 的乐观记账)
+ // 要判断「这次权威回答是不是发生在我提交之后」,否则拿旧回答清掉刚写的新值。
+ const bounds = boundsState.key === key
+ ? boundsState.value
+ : (boundsCache.get(key)?.value ?? null);
+ const boundsFetchedAt = boundsState.key === key
+ ? boundsState.fetchedAt
+ : (boundsCache.get(key)?.fetchedAt ?? 0);
+ // 渲染期只读,写入放在 effect 里(并发渲染/StrictMode 重放时渲染期写 ref 是反模式)。
+ const activeKeyRef = useRef(key);
+ const [reloadToken, setReloadToken] = useState(0);
+ // 本 hook 实例的 id:提交实例自己已经重拉,跨实例通知时跳过它。
+ const instanceIdRef = useRef(++boundsReloadListenerSeq);
+ useEffect(() => {
+ const listener = {
+ id: instanceIdRef.current,
+ key,
+ fire: () => setReloadToken((token) => token + 1),
+ };
+ boundsReloadListeners.add(listener);
+ return () => {
+ boundsReloadListeners.delete(listener);
+ };
+ }, [key]);
+
+ useEffect(() => {
+ // eslint-disable-next-line no-console
+ activeKeyRef.current = key;
+ if (!model || !sessionId) {
+ setBoundsState({ key, value: null, fetchedAt: 0 });
+ return;
+ }
+ const cached = boundsCache.get(key);
+ if (cached && reloadToken === 0 && Date.now() - cached.fetchedAt < BOUNDS_TTL_MS) {
+ setBoundsState({ key, value: cached.value, fetchedAt: cached.fetchedAt });
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ // 路由随查询一起上报:被控端/主进程按**显示路由**解析边界,而不是按会话行。
+ const route = { agent: agentKind, providerId: providerId ?? null, model };
+ try {
+ const view = deviceId
+ ? await window.electronAPI.deviceLink.invoke(
+ deviceId, 'maker:get-context-window-bounds', [sessionId, route],
+ )
+ : await window.electronAPI.maker.getSessionContextWindowBounds(sessionId, route);
+ // 已取消的请求不得写共享缓存:否则保存预算触发的**新**查询之后,迟到的旧响应
+ // 会把旧预算写回缓存并盖上新 fetchedAt,后挂载的卡片把旧数据当新数据用
+ // (Greptile P2,2026-10-17)。取消的响应什么都不写。
+ // 已取消的请求不得写共享缓存(Greptile P2):否则保存预算后的新查询之后,
+ // 迟到的旧响应会把旧预算写回缓存并盖上新 fetchedAt。
+ if (cancelled) return;
+ const resolved = normalizeSessionContextWindowBounds(view);
+ const fetchedAt = Date.now();
+ boundsCache.set(key, { value: resolved, fetchedAt });
+ if (!cancelled && activeKeyRef.current === key) setBoundsState({ key, value: resolved, fetchedAt });
+ } catch {
+ // 老被控端 → CHANNEL_NOT_ALLOWED,或隧道/主进程瞬时失败:缓存 null(TTL 内不重试),
+ // UI 退回「只允许收紧」,由菜单里的说明如实告知。
+ if (cancelled) return;
+ const fetchedAt = Date.now();
+ boundsCache.set(key, { value: null, fetchedAt });
+ if (!cancelled && activeKeyRef.current === key) setBoundsState({ key, value: null, fetchedAt });
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [deviceId, key, sessionId, model, agentKind, providerId, reloadToken]);
+
+ const refresh = useCallback(() => {
+ boundsCache.delete(key);
+ setReloadToken((token) => token + 1);
+ // 其它实例(同会话同路由的分屏 / 双窗口卡片)也要重读权威值。
+ notifyBoundsReload(instanceIdRef.current, key);
+ }, [key]);
+ // 开菜单时只在「没缓存 / TTL 过期」才重拉:否则每次开合菜单都是一次隧道 invoke(弱网可感知)。
+ const refreshIfStale = useCallback(() => {
+ if (!isBoundsCacheEntryStale(boundsCache.get(key), Date.now())) return;
+ setReloadToken((token) => token + 1);
+ }, [key]);
+ return { bounds, boundsFetchedAt, refresh, refreshIfStale };
+}
diff --git a/apps/desktop/src/renderer/components/status/__tests__/contextWindowBudgetChip.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/contextWindowBudgetChip.test.tsx
new file mode 100644
index 0000000000..a91a9e543c
--- /dev/null
+++ b/apps/desktop/src/renderer/components/status/__tests__/contextWindowBudgetChip.test.tsx
@@ -0,0 +1,1224 @@
+// @vitest-environment jsdom
+import { resolve } from 'node:path';
+import { readFileSync } from 'node:fs';
+
+import { act, cleanup, fireEvent, render, screen, waitFor, type RenderResult } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mockUpdate = vi.fn();
+const mockGetModelsForVendor = vi.fn();
+const mockToastError = vi.fn();
+const mockGatewayPricing = vi.fn();
+const mockModelContextLimit = vi.fn();
+const mockModelContextLimitTarget = vi.fn();
+
+vi.mock('@/lib/sessionService', () => ({
+ update: (...args: unknown[]) => mockUpdate(...args),
+}));
+vi.mock('@/lib/modelDefinitions', () => ({
+ getModelsForVendor: (...args: unknown[]) => mockGetModelsForVendor(...args),
+}));
+vi.mock('@/lib/toast', () => ({
+ toast: { error: (...args: unknown[]) => mockToastError(...args), success: vi.fn() },
+}));
+vi.mock('@/hooks/useModelPricing', () => ({
+ useGatewayModelPricing: () => mockGatewayPricing(),
+ useReferenceModelPricing: () => null,
+}));
+// 同路由的模型级「上下文上限」:默认未设置,个别用例覆盖。
+vi.mock('@/hooks/useModelContextLimit', () => ({
+ useModelContextLimit: (target: unknown) => {
+ mockModelContextLimitTarget(target);
+ return mockModelContextLimit();
+ },
+}));
+// 本组件不依赖真实词条;翻译 mock 把插值参数原样暴露,断言只落在「档位 / 提交值 / 提示是否出现」。
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, opts?: Record<string, unknown>) =>
+ opts ? `${key}#${JSON.stringify(opts)}` : key,
+ }),
+}));
+// Radix 浮层在 jsdom 里不参与交互;按下拉菜单契约替换成最小可控实现(同仓库其它
+// 浮层单测的做法),让断言只落在「档位集合 / 提交值」上。
+vi.mock('@/components/ui/dropdown-menu', async () => {
+ const React = await import('react');
+ const RadioContext = React.createContext<(value: string) => void>(() => {});
+ return {
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="budget-menu">{children}</div>
+ ),
+ DropdownMenuRadioGroup: ({
+ children,
+ onValueChange,
+ }: {
+ children: React.ReactNode;
+ onValueChange?: (value: string) => void;
+ }) => (
+ <RadioContext.Provider value={onValueChange ?? (() => {})}>
+ <div>{children}</div>
+ </RadioContext.Provider>
+ ),
+ DropdownMenuRadioItem: ({
+ children,
+ value,
+ disabled,
+ }: {
+ children: React.ReactNode;
+ value: string;
+ disabled?: boolean;
+ }) => {
+ const onValueChange = React.useContext(RadioContext);
+ return (
+ <button
+ type="button"
+ data-token={value}
+ disabled={disabled}
+ onClick={() => onValueChange(value)}
+ >
+ {children}
+ </button>
+ );
+ },
+ };
+});
+
+import { ContextWindowBudgetChip, isBoundsCacheEntryStale, resetRemoteContextWindowBoundsCache, __clearAllBoundsCachesForTest, __expireAllBoundsCachesForTest } from '../ContextWindowBudgetChip';
+
+const SESSION_ID = 'session-1';
+
+/** 分档计费:<512K 一条价带,≥512K 另一条(价带切换点正好落在 512K 档)。 */
+const tieredPricingCatalog = {
+ xd: {
+ 'grok-4.6': {
+ providerId: 'xd',
+ modelId: 'grok-4.6',
+ currency: 'USD' as const,
+ source: 'gateway' as const,
+ approximate: false,
+ inputPerMtok: 0.4,
+ outputPerMtok: 1.6,
+ inputTokenPriceBands: [
+ { minInputTokens: 0, maxInputTokens: 512_000, inputPerMtok: 0.4 },
+ { minInputTokens: 512_000, inputPerMtok: 1.2 },
+ ],
+ },
+ },
+};
+
+/** 唯一路由(providerId 已限定)→ 默认窗口与上限都按路由解析。 */
+const routeCatalog = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ { id: 'grok-4.6', name: 'Grok 4.6', contextWindow: 1_000_000, contextWindowVerified: true },
+ ],
+ },
+ },
+ ],
+} as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+
+/**
+ * 打开档位卡并返回档位行:卡片是指针悬浮展开的 `Popover`,**内容只在打开时挂载**;
+ * 行是 `role="radio"`(单选语义),不是普通 button。
+ */
+/** 当前档位行的 token 列表(每次重新查询,`waitFor` 里能看见重渲染后的行)。 */
+function tierTokens(): Array<string | null> {
+ return (screen.queryAllByRole('radio') as HTMLElement[]).map((el) => el.getAttribute('data-token'));
+}
+
+async function openTierCard(): Promise<HTMLElement[]> {
+ const rows = (): HTMLElement[] => screen.queryAllByRole('radio') as HTMLElement[];
+ if (rows().length > 0) return rows();
+ const trigger = document.querySelector('[data-context-window-budget-chip]');
+ if (!trigger) throw new Error('context window chip trigger is missing');
+ fireEvent.click(trigger);
+ await waitFor(() => { expect(rows().length).toBeGreaterThan(0); });
+ return rows();
+}
+
+/** 触发器不再显示数值:当前档位的可读出处是 aria-label(`triggerLabel`)。 */
+function triggerLabel(chip: Element | null): string {
+ return chip?.getAttribute('aria-label') ?? '';
+}
+
+/**
+ * 档位行里出现的百分比(按行序)。i18n 在用例里被换成 `key#{"percent":N}`,
+ * 所以直接从行文本里抓 N;抓不到的行(基准未知、只显绝对值)不计入。
+ */
+function percentsIn(rows: HTMLElement[]): number[] {
+ return rows.flatMap((row) => [...(row.textContent ?? '').matchAll(/"percent":(\d+)/g)]
+ .map((match) => Number(match[1])));
+}
+
+/** 权威边界的形状(本地 `maker:get-context-window-bounds` / 远程 device-link 同名 channel)。 */
+function boundsView(
+ over: Partial<
+ Record<
+ "budget" | "budgetCustomized" | "defaultWindow" | "maxWindow" | "modelLimit" | "defaultEffectiveWindow" | "maxEffectiveWindow" | "effectiveWindowsReported",
+ unknown
+ >
+ > = {},
+) {
+ return {
+ providerId: "xd",
+ defaultWindow: 1_000_000,
+ maxWindow: null,
+ modelLimit: null,
+ budget: null,
+ budgetCustomized: false,
+ defaultEffectiveWindow: null,
+ maxEffectiveWindow: null,
+ // 新主进程/新被控端会显式申报;老端没有这两个字段(用例里显式传 false 模拟)。
+ effectiveWindowsReported: true,
+ ...over,
+ };
+}
+
+/** 装一份带指定 bounds mock 的 electronAPI(本地会话走 maker,远程走 deviceLink)。 */
+function installElectronApi(getBounds: unknown): void {
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ deviceLink: { invoke: vi.fn().mockResolvedValue(null) },
+ maker: { getSessionContextWindowBounds: getBounds },
+ };
+}
+
+
+/** 某容器里 data-token 行的 aria-checked(测试断言「预算生效」用选中态而不是档位存在性)。 */
+function checkedOf(container: HTMLElement | Document, tokens: string): boolean | null {
+ const row = container.querySelector(`[role="radio"][data-token="${tokens}"]`);
+ return row ? row.getAttribute('aria-checked') === 'true' : null;
+}
+
+function renderChip(
+ overrides: Partial<React.ComponentProps<typeof ContextWindowBudgetChip>> & { budget?: number | null } = {},
+) {
+ const { budget, ...rest } = overrides;
+ // 任务预算这次由**权威边界查询**带回(偏好文件里的条目,本地 main / 远程被控端算),
+ // 不再是会话快照上的字段:给了档位就把它放进边界响应里。不给 = 边界不可用,
+ // chip 按 renderer 自解析兑底(未存过任何档)。
+ if (budget) {
+ (
+ window.electronAPI.maker.getSessionContextWindowBounds as unknown as {
+ mockResolvedValue: (value: unknown) => void;
+ }
+ ).mockResolvedValue({
+ providerId: 'xd',
+ defaultWindow: 1_000_000,
+ maxWindow: null,
+ modelLimit: null,
+ budget,
+ budgetCustomized: true,
+ });
+ }
+ return render(
+ <ContextWindowBudgetChip
+ sessionId={SESSION_ID}
+ contextTokens={0}
+ model="grok-4.6"
+ providerId="xd"
+ agentKind="cc"
+ providers={routeCatalog}
+ {...rest}
+ />,
+ );
+}
+
+beforeEach(() => {
+ mockUpdate.mockReset();
+ mockUpdate.mockResolvedValue({ id: SESSION_ID });
+ mockGetModelsForVendor.mockReset();
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 1_000_000 }]);
+ mockToastError.mockReset();
+ mockGatewayPricing.mockReset();
+ mockGatewayPricing.mockReturnValue(null);
+ mockModelContextLimit.mockReset();
+ mockModelContextLimit.mockReturnValue({ limit: null, isCustomized: false });
+ mockModelContextLimitTarget.mockReset();
+ resetRemoteContextWindowBoundsCache();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ // 默认:被控端不支持该只读查询(或返回不可用)→ 远程保持「只允许收紧」。
+ deviceLink: { invoke: vi.fn().mockResolvedValue(null) },
+ maker: { getSessionContextWindowBounds: vi.fn().mockResolvedValue(null) },
+ };
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('ContextWindowBudgetChip', () => {
+ it('renders the catalog default window when no budget is saved', () => {
+ renderChip();
+ const chip = document.querySelector('[data-context-window-budget-chip]');
+ expect(triggerLabel(chip)).toContain('1M');
+ });
+
+ it('offers the ladder plus the model default, and reports an explicit tier', async () => {
+ renderChip();
+ const options = await openTierCard();
+ expect(options.map((el) => el.getAttribute('data-token'))).toEqual([
+ '250000',
+ '500000',
+ '1000000',
+ ]);
+ const defaultOption = options.find((el) => el.getAttribute('data-token') === '1000000');
+ expect(defaultOption?.textContent).toContain('optionDefault');
+
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '500000')!);
+ await waitFor(() => {
+ expect(mockUpdate).toHaveBeenCalledWith(SESSION_ID, { contextWindowBudget: 500_000 });
+ });
+ });
+
+ it('marks the trigger with a text bracket pair plus the current percentage', () => {
+ // 用户拍板:底栏不挂文字标签,但要「窗口框 + 百分比」;百分比与卡片行同口径(默认档 = 100%)。
+ renderChip();
+ const chip = document.querySelector('[data-context-window-budget-chip]');
+ // 文本标记(↕,与 `¥` / `1%` 同字号同基线),不是图标、不是括号。
+ expect(chip?.textContent).toContain('↕');
+ expect(chip?.textContent).toContain('optionPercent#{"percent":100}');
+ expect(chip?.textContent).not.toContain('menuTitle');
+ expect(chip?.querySelector('svg')).toBeNull();
+ // 当前值进可访问名:读屏要能听到绝对窗口。
+ expect(chip?.getAttribute('aria-label')).toBe(
+ 'ccAgent.contextWindowBudget.triggerLabel#{"window":"1M"}',
+ );
+ const cls = String(chip?.className);
+ expect(cls).toContain('text-12');
+ expect(cls).toContain('font-medium');
+ expect(cls).toContain('text-[var(--msg-tool-card-chevron)]');
+ expect(cls).not.toContain('text-[var(--text-tertiary)]');
+ });
+
+ it('keeps the card open when the trigger is clicked after hover opened it', async () => {
+ // 与底栏用量 chip(TodaySpendChip)一致:展开/收起只由 hover、焦点与 outside-click
+ // 驱动,点击不当作开关。用户实测:左边卡片悬浮展开后点击不会收起,本卡却会 —— 两张
+ // 底栏卡片的交互必须一样。
+ renderChip();
+ const trigger = document.querySelector('[data-context-window-budget-chip]')!;
+ // 悬浮路径:打开延迟 300ms(waitFor 轮询等待,不使用真实定时器睡眠)。
+ fireEvent.pointerEnter(trigger);
+ await waitFor(() => {
+ expect(screen.queryAllByRole('radio').length).toBeGreaterThan(0);
+ }, { timeout: 1500 });
+ // 悬浮已展开后点击触发器:卡片必须仍然在(Radix 的 toggle 被 preventDefault 拦住)。
+ // 点击若重新排入关闭定时器,宽限 200ms 后卡片消失 —— 用 waitFor 确认「稳定不关」。
+ fireEvent.click(trigger);
+ await waitFor(() => {
+ expect(screen.queryAllByRole('radio').length).toBeGreaterThan(0);
+ }, { timeout: 400 });
+ });
+
+ it('keeps the trigger focusable when the task is read-only', async () => {
+ // 用户实测:Tab 到左边用量卡后按多少次 Tab 都回不到本卡 —— 原生 `disabled` 会把触发器
+ // 整个移出 Tab 序列(左边用量卡没有这道门)。只读任务仍应能“看一眼当前档位与价带”,
+ // 落档能力由档位行自己禁用拦住,并在卡内说明原因。
+ installElectronApi(vi.fn(async () => boundsView({ budget: 500_000, budgetCustomized: true })));
+ renderChip({ disabled: true, providers: null });
+ const trigger = document.querySelector(
+ '[data-context-window-budget-chip]',
+ ) as HTMLButtonElement | null;
+ expect(trigger).not.toBeNull();
+ // 可聚焦 = 不被 Tab 跳过(原生 disabled 属性必须不存在)。
+ expect(trigger!.disabled).toBe(false);
+ expect(trigger!.getAttribute('aria-disabled')).toBe('true');
+ // 仍可展开;档位行全部不可选,且有「只读」说明。
+ fireEvent.click(trigger!);
+ const rows = screen.queryAllByRole('radio') as HTMLButtonElement[];
+ await waitFor(() => { expect(rows.length).toBeGreaterThan(0); });
+ for (const row of rows) expect(row.disabled).toBe(true);
+ expect(screen.getByText('ccAgent.contextWindowBudget.readOnlyHint')).toBeTruthy();
+ });
+
+ it('keeps the card right after its trigger so the bottom bar stays walkable', async () => {
+ // 结构不变量(用户实测:Tab 到左边用量卡后翻多少次都到不了本卡):浮层必须挂在
+ // 触发器紧跟其后的宿主里,让 DOM 顺序 = 视觉顺序。挂到 body 末尾时,文档内卡片
+ // 之后再没有下一个可 Tab 节点,焦点一旦进卡就回不到底栏。
+ renderChip();
+ const trigger = document.querySelector('[data-context-window-budget-chip]')!;
+ await openTierCard();
+ const wrapper = document.querySelector('[data-radix-popper-content-wrapper]');
+ expect(wrapper).not.toBeNull();
+ const host = wrapper!.parentElement!;
+ expect(host).not.toBe(document.body);
+ expect(host.className).toContain('contents');
+ // 宿主在触发器**之后**(Tab 沿视觉顺序从左到右走)。
+ expect(
+ trigger.compareDocumentPosition(host) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('shows the saved tier percentage next to the marker', async () => {
+ // 存了 25% 档 → 触发器读 `↕ 25%`(绝对值在 aria-label / 卡片里)。
+ // 档位来自权威边界查询(偏好文件里的条目),所以这里要等那次查询回来。
+ renderChip({ budget: 250_000 });
+ const chip = document.querySelector('[data-context-window-budget-chip]');
+ await waitFor(() => {
+ expect(chip?.textContent).toContain('optionPercent#{"percent":25}');
+ });
+ });
+
+ // 乐观记账的作用域与收口(Greptile 复审 P1):预算是「按会话」存的偏好条目、与路由无关,
+ // 所以切模型不该丢掉刚写的值;但同一张卡换到别的会话/设备时必须失效,而且只有**提交之后**
+ // 回来的权威回答才有资格把它收口(保存后的那次 refresh 会丢弃之前 in-flight 的结果)。
+/** 触发器文本(`↕ 25%`):百分比在文本里,绝对值在 aria-label(triggerLabel)里。 */
+function chipText(): string {
+ return document.querySelector('[data-context-window-budget-chip]')?.textContent ?? '';
+}
+
+ it('keeps the saved tier while the post-save authoritative answer is still in flight', async () => {
+ const getBounds = vi
+ .fn()
+ .mockResolvedValueOnce(boundsView({ budget: null }))
+ // 保存后触发的那次查询永不返回:chip 仍要显示刚提交的档位,而不是回退到旧值。
+ .mockImplementation(() => new Promise(() => {}));
+ installElectronApi(getBounds);
+
+ renderChip();
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '250000')!);
+ await waitFor(() => {
+ expect(chipText()).toContain('optionPercent#{"percent":25}');
+ });
+ });
+
+ it('uses the model-level limit as the effective default when the catalog only has a fallback window', async () => {
+ // 自定义连接(未声明窗口)的真实形态:目录 working default 只有兜底 200K,用户把模型级
+ // 「上下文上限」设成了 1.05M。运行期窗口 = 模型级上限(main 的 resolveConfiguredContextWindow
+ // 在无任务预算时就用它,且刻意不按目录夹),所以 chip 的当前档与档位基准都必须是 1.05M ——
+ // 否则会跟圆环报的窗口打架(用户实测报障:圆环 1.0M / chip 200K)。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: null,
+ modelLimit: 1_048_000,
+ defaultEffectiveWindow: 1_048_000,
+ })));
+
+ // providers=null:模拟真实形态里 renderer 侧也拿不到该路由的目录上限(只有 main 的权威边界)。
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ const defaultOption = options.find((el) => el.getAttribute('data-token') === '1048000');
+ expect(defaultOption?.textContent).toContain('optionDefault');
+ await waitFor(() => {
+ expect(chipText()).toContain('optionPercent#{"percent":100}');
+ });
+ });
+
+ it('clamps the effective default to the physical max the way main does', async () => {
+ // Greptile 复审 P1 的形态:已核实路由上模型级上限(1.05M)高于物理上限(200K)时,
+ // main 的 resolveVerifiedContextWindow 会夹到物理上限;chip 不能把 1.05M 当成默认档,
+ // 否则会显示/选中一个运行期根本达不到的窗口。生效窗口由 main 下发,这里只消费。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: 200_000,
+ modelLimit: 1_048_000,
+ defaultEffectiveWindow: 200_000,
+ })));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ expect(tierTokens()).not.toContain('1048000');
+ const defaultOption = options.find((el) => el.getAttribute('data-token') === '200000');
+ expect(defaultOption?.textContent).toContain('optionDefault');
+ await waitFor(() => {
+ expect(chipText()).toContain('optionPercent#{"percent":100}');
+ });
+ });
+
+ it('labels the model-default tier with the window after clearing the task budget', async () => {
+ // Greptile 复审 P1:默认档不能带当前任务预算。目录默认 200K、模型级上限 800K、当前预算是
+ // 500K 时,菜单里的「模型默认」必须是清掉预算后的 200K(选它写 null → 运行期就回到 200K),
+ // 而 500K 只能作为「当前档」出现。
+ // 路由未声明物理上限(自定义连接):目录默认 200K 只是兜底,模型级上限 800K 才是上限。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: null,
+ modelLimit: 800_000,
+ budget: 500_000,
+ budgetCustomized: true,
+ defaultEffectiveWindow: 800_000,
+ })));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ const defaultOption = options.find((el) => el.textContent?.includes('optionDefault'));
+ expect(defaultOption?.getAttribute('data-token')).toBe('800000');
+ // 当前档(500K)仍在,且**不是**「模型默认」——点默认档会写 null,运行期回到 800K。
+ expect(tierTokens()).toContain('500000');
+ expect(options.find((el) => el.getAttribute('data-token') === '500000')?.textContent)
+ .not.toContain('optionDefault');
+ });
+
+ it('caps the ladder by the physical max main applies even when the catalog omits contextWindowMax', async () => {
+ // 已核实但没声明 contextWindowMax 的路由:main 会用 contextWindow 当物理上限
+ // (resolveVerifiedContextWindow 的 contextWindowMax ?? contextWindow)。renderer 看不到
+ // contextWindowVerified,所以基准必须用 main 下发的 maxEffectiveWindow,否则档位表会给出
+ // 运行期被夹回 200K 的 800K 档。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: null,
+ modelLimit: 800_000,
+ maxEffectiveWindow: 200_000,
+ defaultEffectiveWindow: 200_000,
+ })));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ expect(tierTokens()).not.toContain('800000');
+ expect(options.find((el) => el.textContent?.includes('optionDefault'))?.getAttribute('data-token'))
+ .toBe('200000');
+ });
+
+ it('falls back to the conservative (tighten-only) ladder when an old controlled device reports nothing', async () => {
+ // Greptile 复审 P1:老被控端不申报生效窗口时,目录没声明 contextWindowMax 也不能把
+ // modelLimit 当成物理上限 —— 被控端运行期还会被 contextWindow 夹一次(200K),
+ // 本地却按 800K 出档会给出运行期根本达不到的档位与价带。
+ installElectronApi(vi.fn().mockResolvedValue({
+ providerId: 'xd',
+ defaultWindow: 200_000,
+ maxWindow: null,
+ modelLimit: 800_000,
+ budget: null,
+ budgetCustomized: false,
+ // 老端:没有 defaultEffectiveWindow / maxEffectiveWindow。
+ effectiveWindowsReported: false,
+ }));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ expect(tierTokens()).not.toContain('800000');
+ expect(options.find((el) => el.textContent?.includes('optionDefault'))?.getAttribute('data-token'))
+ .toBe('200000');
+ });
+
+ it('lets a post-save authoritative answer override the optimistic tier', async () => {
+ // 别的控制端改过值 / 写被夹紧 → 保存后回来的权威值与本机乐观值不同:以权威值收口。
+ let calls = 0;
+ const getBounds = vi.fn(async () => {
+ calls += 1;
+ return calls === 1
+ ? boundsView({ budget: null })
+ : boundsView({ budget: 500_000, budgetCustomized: true });
+ });
+ installElectronApi(getBounds);
+
+ renderChip();
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '250000')!);
+ await waitFor(() => {
+ expect(chipText()).toContain('optionPercent#{"percent":50}');
+ });
+ });
+
+ it('does not carry the optimistic tier into another task', async () => {
+ installElectronApi(vi.fn(async () => boundsView({ budget: null })));
+
+ const view = renderChip();
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '250000')!);
+ await waitFor(() => {
+ expect(chipText()).toContain('optionPercent#{"percent":25}');
+ });
+
+ // 同一张卡换到另一个会话(新会话未存过档位):乐观值必须失效,显示回默认档。
+ view.rerender(
+ <ContextWindowBudgetChip
+ sessionId="another-session"
+ contextTokens={0}
+ model="grok-4.6"
+ providerId="xd"
+ agentKind="cc"
+ providers={routeCatalog}
+ />,
+ );
+ await waitFor(() => {
+ expect(chipText()).toContain('optionPercent#{"percent":100}');
+ });
+ });
+
+ it('uses the quota-card caption gray for every secondary line in the menu', async () => {
+ // 说明行与注解(模型默认 / 单价)统一走 `--text-secondary` —— 就是「用量明细」卡(货币符号
+ // 那个界面)里说明文字的同一档灰(实测 rgb(111,111,111));面板里只有一种「次要灰」。
+ renderChip();
+ await openTierCard();
+ const hint = screen.getByText('ccAgent.contextWindowBudget.menuHint');
+ const defaultTag = screen.getByText('ccAgent.contextWindowBudget.optionDefault');
+ for (const el of [hint, defaultTag]) {
+ expect(String(el.className)).toContain('text-[var(--text-secondary)]');
+ expect(String(el.className)).not.toContain('text-[var(--text-tertiary)]');
+ expect(String(el.className)).not.toContain('text-[var(--msg-tool-card-chevron)]');
+ }
+ });
+
+ it('renders every row as「percentage · absolute」with the model default at 100%', async () => {
+ // 视觉统一(用户实测反馈):默认档不再「绝对值在前」,比例档不再「百分比单独上色」——
+ // 每一行都是同一个形态、同一种颜色(百分比与绝对值同色,继承行色)。
+ renderChip();
+ const options = await openTierCard();
+ const textOf = (tokens: string): string =>
+ options.find((el) => el.getAttribute('data-token') === tokens)?.textContent ?? '';
+ expect(textOf('250000')).toContain('optionPercent#{"percent":25}');
+ expect(textOf('250000')).toContain('250K');
+ expect(textOf('500000')).toContain('optionPercent#{"percent":50}');
+ expect(textOf('1000000')).toContain('optionPercent#{"percent":100}');
+ expect(textOf('1000000')).toContain('1M');
+ expect(textOf('1000000')).toContain('optionDefault');
+ // 百分比在前、绝对值在后(默认档也一样)。
+ expect(textOf('1000000').indexOf('optionPercent')).toBeLessThan(textOf('1000000').indexOf('1M'));
+ // 百分比与绝对值在同一个文本节点里(同一种颜色),不再拆成两个 span 拼色。
+ expect(String(textOf('250000'))).toBe(
+ 'ccAgent.contextWindowBudget.optionPercent#{"percent":25} · 250K',
+ );
+ });
+
+ it('never renders the model-default tier above 100% when the route has no declared window', async () => {
+ // 用户实测报障(2026-09-22):自定义连接未声明窗口(目录只有 200K 兜底)且用户把模型级
+ // 上限设成 1M。旧口径把 200K 当物理上限下发,基准被钉在 200K,于是「模型默认 1M」被
+ // 算成 500%。这一例用**修好后 main 应下发的诚实边界**(maxWindow=null),
+ // 并补上远程端实测形态:已存任务档 200K 时应看到四行。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: null,
+ modelLimit: 1_000_000,
+ defaultEffectiveWindow: 1_000_000,
+ budget: 200_000,
+ budgetCustomized: true,
+ })));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ // 没有声明上限 → 模型级上限 1M 就是显式预算能买到的最大值:100% 档 = 模型默认。
+ expect(tierTokens()).toEqual(['200000', '250000', '500000', '1000000']);
+ expect(percentsIn(options)).toEqual([20, 25, 50, 100]);
+ const textOf = (tokens: string): string =>
+ options.find((el) => el.getAttribute('data-token') === tokens)?.textContent ?? '';
+ expect(textOf('1000000')).toContain('optionDefault');
+ });
+
+ it('does not offer percent tiers above the ceiling main clamps explicit budgets to', async () => {
+ // Greptile P1(2026-09-24):目录**声明了** contextWindowMax=200K 的未核实路由,用户把
+ // 模型级上限设成 1M。默认档写 null 走模型级逃生口 → 真的生效在 1M;但 main 会把任何
+ // **显式**预算按声明上限夹到 200K,所以菜单不得出现 250K/500K 这种达不到的档
+ // (否则窗口与输入价带一起说谎)。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: 200_000,
+ modelLimit: 1_000_000,
+ defaultEffectiveWindow: 1_000_000,
+ })));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ expect(tierTokens()).toEqual(['200000', '1000000']);
+ expect(tierTokens()).not.toContain('250000');
+ expect(tierTokens()).not.toContain('500000');
+ // 默认档可以合法高于上限:它的百分比按 max(上限, 默认档) 算,不会冒出 >100%。
+ expect(percentsIn(options)).toEqual([20, 100]);
+ const defaultRow = options.find((el) => el.textContent?.includes('optionDefault'));
+ expect(defaultRow?.getAttribute('data-token')).toBe('1000000');
+ });
+
+ it('shows absolute values only when the route has no known ceiling at all', async () => {
+ // 未核实 + 未声明上限 + 没有模型级上限 = main 没有任何上限可报,而已存预算可能大于默认
+ // (旧版本、手改偏好、或另一个控制端写的)。此时没有可信分母,就只显绝对值:
+ // 照旧拿 200K 当分母会把 1M 显示成「500%」。
+ installElectronApi(vi.fn(async () => boundsView({
+ defaultWindow: 200_000,
+ maxWindow: null,
+ modelLimit: null,
+ defaultEffectiveWindow: null,
+ budget: 1_000_000,
+ budgetCustomized: true,
+ })));
+
+ renderChip({ providers: null });
+ const options = await openTierCard();
+ expect(tierTokens()).toContain('1000000');
+ for (const el of options) {
+ expect(el.textContent).not.toContain('optionPercent');
+ }
+ expect(document.querySelector('[data-context-window-budget-chip]')?.textContent)
+ .not.toContain('optionPercent');
+ });
+
+ it('gives the tier that came from a saved value its own percentage too', async () => {
+ // 旧值不在档位集合里时补的「当前档」也走同一形态:按真实占比算百分比。
+ renderChip({ budget: 300_000 });
+ const options = await openTierCard();
+ const current = options.find((el) => el.getAttribute('data-token') === '300000');
+ expect(current?.textContent).toContain('optionPercent#{"percent":30}');
+ expect(current?.textContent).toContain('300K');
+ });
+
+ it('reports null when the model default tier is chosen again', async () => {
+ renderChip({ budget: 300_000 });
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '1000000')!);
+ await waitFor(() => {
+ expect(mockUpdate).toHaveBeenCalledWith(SESSION_ID, { contextWindowBudget: null });
+ });
+ });
+
+ it('does not re-submit the tier that is already saved', async () => {
+ renderChip({ budget: 500_000 });
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '500000')!);
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('warns when the chosen tier is below the current context usage', async () => {
+ renderChip({ budget: 100_000, contextTokens: 400_000 });
+ await openTierCard();
+ expect(screen.getByText(/400K/)).toBeTruthy();
+ });
+
+ it('surfaces a save failure and keeps the previous selection', async () => {
+ mockUpdate.mockRejectedValue(new Error('boom'));
+ renderChip();
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '250000')!);
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalled();
+ });
+ const chip = document.querySelector('[data-context-window-budget-chip]');
+ expect(triggerLabel(chip)).toContain('1M');
+ });
+
+ it('does not render when the route window is unknown', () => {
+ // 路由目录与扁平表都给不出默认窗口 → 没有档位可给,不渲染兜底控件。
+ mockGetModelsForVendor.mockReturnValue([]);
+ renderChip({ providers: null, model: 'other-model' });
+ expect(document.querySelector('[data-context-window-budget-chip]')).toBeNull();
+ });
+
+ it('offers the route max tier so a session can raise the window again', async () => {
+ // 服务端压低过默认值的路由(默认 200K / 上限 1M):不提供上限档就无法“调大”。
+ // 上限必须来自**路由**(providers),不能来自跨 provider 去重的扁平表。
+ const loweredRoute = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'grok-4.6',
+ name: 'Grok 4.6',
+ contextWindow: 200_000,
+ contextWindowMax: 1_000_000,
+ contextWindowVerified: true,
+ },
+ ],
+ },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 200_000 }]);
+ renderChip({ providers: loweredRoute });
+ const options = await openTierCard();
+ expect(options.at(-1)?.getAttribute('data-token')).toBe('1000000');
+ fireEvent.click(options.at(-1)!);
+ await waitFor(() => {
+ expect(mockUpdate).toHaveBeenCalledWith(SESSION_ID, { contextWindowBudget: 1_000_000 });
+ });
+ });
+
+ it('keeps only the clamped default when a tight model-level limit is set', async () => {
+ // 100K 模型级上限 → 基准 100K:25%/50% 都低于 200K 阈值,100% 就是被压住的默认档。
+ mockModelContextLimit.mockReturnValue({ limit: 100_000, isCustomized: true });
+ renderChip();
+ const options = await openTierCard();
+ expect(options.map((el) => el.getAttribute('data-token'))).toEqual(['100000']);
+ });
+
+ it('omits the max tier when the route is ambiguous across providers', async () => {
+ // 同一 model id 由两个 provider 提供且未限定 providerId:取谁的上限都是猜,只能收紧。
+ const ambiguousCatalog = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: { 'claude-code': [{ id: 'grok-4.6', name: 'Grok', contextWindow: 300_000 }] },
+ },
+ {
+ id: 'xai',
+ routing: { 'claude-code': {} },
+ models: { 'claude-code': [{ id: 'grok-4.6', name: 'Grok', contextWindow: 300_000 }] },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 300_000 }]);
+ renderChip({ providers: ambiguousCatalog, providerId: null });
+ const options = await openTierCard();
+ // 无可信基准时退回默认窗口 300K:其 25%/50%(75K/150K)低于 200K 阈值,只给默认档。
+ expect(options.map((el) => el.getAttribute('data-token'))).toEqual(['300000']);
+ });
+
+ it('takes the default from the route for Pi even though the flat table is the only fallback', () => {
+ // resolveSessionContextWindow 对 pi/codex 恒返回 null(那是「运行时上报才可信」的
+ // 快照口径);档位锚点不能用它,否则 Pi/Codex 任务永远显示扁平表(跨 provider 首见)的值。
+ const piRoute = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { pi: {} },
+ models: { pi: [{ id: 'grok-4.6', name: 'Grok', contextWindow: 300_000 }] },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 1_000_000 }]);
+ renderChip({ agentKind: 'pi', providers: piRoute });
+ const chip = document.querySelector('[data-context-window-budget-chip]');
+ expect(triggerLabel(chip)).toContain('300K');
+ expect(triggerLabel(chip)).not.toContain('1M');
+ });
+
+ it('takes the local ladder ceiling from main instead of the renderer-side route guess', async () => {
+ // 跨 provider 同 id:renderer 解不出来源(拿不到模型级上限),main 能 —— 档位表必须读
+ // main 的权威边界,否则会给出 main 一定会夹掉的档(显示 ≠ 生效)。
+ const getBounds = vi.fn().mockResolvedValue({
+ providerId: 'xd',
+ defaultWindow: 200_000,
+ maxWindow: 1_000_000,
+ modelLimit: 100_000,
+ });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ deviceLink: { invoke: vi.fn().mockResolvedValue(null) },
+ maker: { getSessionContextWindowBounds: getBounds },
+ };
+ const ambiguousCatalog = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: { 'claude-code': [{ id: 'grok-4.6', name: 'Grok', contextWindow: 1_000_000 }] },
+ },
+ {
+ id: 'xai',
+ routing: { 'claude-code': {} },
+ models: { 'claude-code': [{ id: 'grok-4.6', name: 'Grok', contextWindow: 1_000_000 }] },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 1_000_000 }]);
+ renderChip({ providerId: null, providers: ambiguousCatalog });
+ await openTierCard();
+ await waitFor(() => {
+ expect(tierTokens()).toEqual(['100000']);
+ });
+ // 查询必须带上**界面上正在显示的路由**:延迟切换期间会话行还是旧路由,
+ // 不带路由会被按旧模型回答。
+ expect(getBounds).toHaveBeenCalledWith(SESSION_ID, {
+ agent: 'claude-code', providerId: null, model: 'grok-4.6',
+ });
+ });
+
+ it('normalizes a dirty saved budget instead of offering an unsavable tier', async () => {
+ // 手改 DB 的浮点值:写入口对非整数直接拒绝,档位表不能把它当成一个可选档。
+ renderChip({ budget: 250_000.4 });
+ const options = await openTierCard();
+ const tokens = options.map((el) => el.getAttribute('data-token'));
+ expect(tokens).toContain('250000');
+ expect(tokens).not.toContain('250000.4');
+ });
+
+ it('falls back to tighten-only when the device answers a malformed bounds payload', async () => {
+ const invoke = vi.fn().mockResolvedValue({ defaultWindow: '200000', maxWindow: -1 });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ deviceLink: { invoke },
+ maker: { getSessionContextWindowBounds: vi.fn().mockResolvedValue(null) },
+ };
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 200_000 }]);
+ renderChip({ deviceId: 'device-1' });
+ await waitFor(() => {
+ expect(invoke).toHaveBeenCalled();
+ });
+ // 畸形值不构成上限:退回默认窗口 200K(其 25%/50% 都低于阈值)→ 只剩默认档,并保留如实说明。
+ const options = await openTierCard();
+ expect(options.at(-1)?.getAttribute('data-token')).toBe('200000');
+ expect(screen.getByText('ccAgent.contextWindowBudget.remoteTightenOnly')).toBeTruthy();
+ });
+
+ it('offers the controlled device bounds when the device answers the read-only query', async () => {
+ const invoke = vi.fn().mockResolvedValue({
+ providerId: 'xd',
+ defaultWindow: 200_000,
+ maxWindow: 1_000_000,
+ modelLimit: null,
+ });
+ (window as unknown as { electronAPI: { deviceLink: { invoke: unknown } } }).electronAPI = {
+ deviceLink: { invoke },
+ };
+ const localCatalog = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ { id: 'grok-4.6', name: 'Grok', contextWindow: 200_000, contextWindowMax: 1_000_000 },
+ ],
+ },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 200_000 }]);
+ renderChip({ deviceId: 'device-1', providers: localCatalog });
+ // 边界来自被控端 → 上限档出现,且不再显示「只能调小」的说明。
+ await openTierCard();
+ await waitFor(() => {
+ expect(tierTokens().at(-1)).toBe('1000000');
+ });
+ // 远程查询同样带上显示路由(被控端按它解析,而不是按可能滞后的会话行)。
+ expect(invoke).toHaveBeenCalledWith('device-1', 'maker:get-context-window-bounds', [
+ SESSION_ID,
+ { agent: 'claude-code', providerId: 'xd', model: 'grok-4.6' },
+ ]);
+ expect(screen.queryByText('ccAgent.contextWindowBudget.remoteTightenOnly')).toBeNull();
+ });
+
+ it('stays tighten-only on a remote task instead of trusting the local catalog', async () => {
+ // device-link 远程任务的路由/上限在被控端:用本机目录会造出「看到的档位 ≠ 被控端生效值」,
+ // 因此只按被控端能力缓存里的默认值允许收紧,不给上限档、也不读本机的模型级上限。
+ const localCatalog = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ { id: 'grok-4.6', name: 'Grok', contextWindow: 200_000, contextWindowMax: 1_000_000 },
+ ],
+ },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ mockGetModelsForVendor.mockReturnValue([{ id: 'grok-4.6', contextWindow: 200_000 }]);
+ renderChip({ deviceId: 'device-1', providers: localCatalog });
+ const options = await openTierCard();
+ expect(options.at(-1)?.getAttribute('data-token')).toBe('200000');
+ expect(mockModelContextLimitTarget).not.toHaveBeenCalledWith(expect.anything());
+ // 文案必须如实说明“只能调小”,不能留给用户“能调大”的预期。
+ expect(screen.getByText('ccAgent.contextWindowBudget.remoteTightenOnly')).toBeTruthy();
+ });
+
+ it('resolves the route provider so the model-level limit still applies without providerId', async () => {
+ mockModelContextLimit.mockReturnValue({ limit: 100_000, isCustomized: true });
+ // 唯一候选 → chip 自己解出来源,与 main 侧 resolveDesktopModelContextProviderId 同口径。
+ const ambiguousFreeCatalog = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: { 'claude-code': [{ id: 'grok-4.6', name: 'Grok', contextWindow: 1_000_000 }] },
+ },
+ ],
+ } as unknown as React.ComponentProps<typeof ContextWindowBudgetChip>['providers'];
+ renderChip({ providerId: null, providers: ambiguousFreeCatalog });
+ expect(mockModelContextLimitTarget).toHaveBeenCalledWith({
+ agent: 'claude-code',
+ providerId: 'xd',
+ modelId: 'grok-4.6',
+ });
+ const options = await openTierCard();
+ expect(options.map((el) => el.getAttribute('data-token'))).toEqual(['100000']);
+ });
+
+ it('shows the price band each tier lands in', async () => {
+ mockGatewayPricing.mockReturnValue(tieredPricingCatalog);
+ renderChip();
+ const options = await openTierCard();
+ const cheap = options.find((el) => el.getAttribute('data-token') === '250000');
+ const boundary = options.find((el) => el.getAttribute('data-token') === '1000000');
+ expect(cheap?.textContent).toMatch(/\$0\.4/);
+ // 512K 及以上进入第二条价带(maxInputTokens 是开区间)。
+ expect(boundary?.textContent).toMatch(/\$1\.2/);
+ });
+
+ it('ships a remote (device-link) change through the tunnel command, not the local DB', async () => {
+ const invoke = vi.fn().mockResolvedValue(undefined);
+ (window as unknown as { electronAPI: { deviceLink: { invoke: typeof invoke } } }).electronAPI = {
+ deviceLink: { invoke },
+ };
+ renderChip({ deviceId: 'device-a' });
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '500000')!);
+ await waitFor(() => {
+ expect(invoke).toHaveBeenCalledWith('device-a', 'maker:set-context-window-budget', [
+ SESSION_ID,
+ 500_000,
+ ]);
+ });
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('tells the user when the controlled device is too old for the tunnel command', async () => {
+ const invoke = vi.fn().mockRejectedValue(
+ Object.assign(new Error('channel not allowed'), {
+ code: 'DEVICE_LINK_CHANNEL_NOT_ALLOWED',
+ }),
+ );
+ (window as unknown as { electronAPI: { deviceLink: { invoke: typeof invoke } } }).electronAPI = {
+ deviceLink: { invoke },
+ };
+ renderChip({ deviceId: 'device-a' });
+ const options = await openTierCard();
+ fireEvent.click(options.find((el) => el.getAttribute('data-token') === '250000')!);
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith(
+ expect.stringContaining('remoteUnsupported'),
+ );
+ });
+ });
+
+ it('answers bounds for the route being displayed, not the lagging session row', async () => {
+ // 用户实测报障:同一引擎内换模型在**发送边界**才落库,期间会话行还是旧模型。
+ // 若边界查询只带 sessionId,被控端/主进程会按旧行回答 —— 262K 的千问切到 1M 的
+ // deepseek 后 chip 与档位表都停在 262.1K(旧模型的唯一档位)。
+ const getBounds = vi.fn(async (_sessionId: string, route?: { model?: string }) =>
+ route?.model === 'deepseek/deepseek-v4.1-flash'
+ ? { providerId: 'commandcode', defaultWindow: 1_000_000, maxWindow: 1_000_000, modelLimit: null }
+ : { providerId: 'commandcode', defaultWindow: 262_144, maxWindow: 262_144, modelLimit: null });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ deviceLink: { invoke: vi.fn().mockResolvedValue(null) },
+ maker: { getSessionContextWindowBounds: getBounds },
+ };
+ mockGetModelsForVendor.mockReturnValue([]);
+ const view = renderChip({ model: 'Qwen/Qwen3.8-27B', providerId: 'commandcode', providers: null });
+ const chip = () => document.querySelector('[data-context-window-budget-chip]');
+ await waitFor(() => {
+ expect(triggerLabel(chip())).toContain('262.1K');
+ });
+
+ // 模型选择器已切到目标模型(会话行还没落库):chip 必须跟着换档位表与显示值。
+ view.rerender(
+ <ContextWindowBudgetChip
+ sessionId={SESSION_ID}
+ contextTokens={0}
+ model="deepseek/deepseek-v4.1-flash"
+ providerId="commandcode"
+ agentKind="pi"
+ providers={null}
+ />,
+ );
+ await waitFor(() => {
+ expect(triggerLabel(chip())).toContain('1M');
+ });
+ await openTierCard();
+ await waitFor(() => {
+ expect(tierTokens()).toEqual(['250000', '500000', '1000000']);
+ });
+ expect(getBounds).toHaveBeenLastCalledWith(SESSION_ID, {
+ agent: 'pi', providerId: 'commandcode', model: 'deepseek/deepseek-v4.1-flash',
+ });
+ });
+
+ it('gives the radio group a single tab stop, starting on the checked tier', async () => {
+ renderChip({ budget: 500_000 });
+ const options = await openTierCard();
+ const stops = options.filter((row) => row.getAttribute('tabindex') === '0');
+ expect(stops).toHaveLength(1);
+ expect(stops[0]?.getAttribute('data-token')).toBe('500000');
+ });
+
+ it('moves focus with arrow keys without committing a new tier', async () => {
+ renderChip();
+ const options = await openTierCard();
+ const [first, second] = options;
+ first.focus();
+ fireEvent.keyDown(first, { key: 'ArrowDown' });
+ await waitFor(() => { expect(document.activeElement).toBe(second); });
+ // 焦点移动不是选择:扫过一遍档位不该连写好几次库。
+ expect(mockUpdate).not.toHaveBeenCalled();
+ expect(second.getAttribute('tabindex')).toBe('0');
+ expect(first.getAttribute('tabindex')).toBe('-1');
+ });
+
+ it('wraps around at both ends and honours Home / End', async () => {
+ renderChip();
+ const options = await openTierCard();
+ const first = options[0];
+ const last = options[options.length - 1];
+ last.focus();
+ fireEvent.keyDown(last, { key: 'ArrowDown' });
+ await waitFor(() => { expect(document.activeElement).toBe(first); });
+ fireEvent.keyDown(first, { key: 'ArrowUp' });
+ await waitFor(() => { expect(document.activeElement).toBe(last); });
+ fireEvent.keyDown(last, { key: 'Home' });
+ await waitFor(() => { expect(document.activeElement).toBe(first); });
+ fireEvent.keyDown(first, { key: 'End' });
+ await waitFor(() => { expect(document.activeElement).toBe(last); });
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('still commits with click / Enter on a focused row', async () => {
+ renderChip();
+ const options = await openTierCard();
+ const target = options[options.length - 2];
+ fireEvent.click(target);
+ await waitFor(() => { expect(mockUpdate).toHaveBeenCalledTimes(1); });
+ });
+
+ it('rekeys the bounds cache when only the provider changes', async () => {
+ // 同一模型跨来源的上限可能不同:缓存键少了 providerId 会把 A 来源的边界当成 B 来源的权威值。
+ const getBounds = vi.fn(async (_sessionId: string, route?: { providerId?: string | null }) =>
+ route?.providerId === 'xd'
+ ? { providerId: 'xd', defaultWindow: 1_000_000, maxWindow: 1_000_000, modelLimit: null }
+ : { providerId: 'cpa', defaultWindow: 200_000, maxWindow: 200_000, modelLimit: null });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ deviceLink: { invoke: vi.fn().mockResolvedValue(null) },
+ maker: { getSessionContextWindowBounds: getBounds },
+ };
+ mockGetModelsForVendor.mockReturnValue([]);
+ const view = renderChip({ providers: null });
+ await waitFor(() => {
+ expect(triggerLabel(document.querySelector('[data-context-window-budget-chip]'))).toContain('1M');
+ });
+
+ view.rerender(
+ <ContextWindowBudgetChip
+ sessionId={SESSION_ID}
+ contextTokens={0}
+ model="grok-4.6"
+ providerId="cpa"
+ agentKind="cc"
+ providers={null}
+ />,
+ );
+ await waitFor(() => {
+ expect(triggerLabel(document.querySelector('[data-context-window-budget-chip]')))
+ .toContain('200K');
+ });
+ });
+});
+
+
+describe('ContextWindowBudgetChip — Greptile 2026-10-17 三条 P2', () => {
+ afterEach(() => {
+ cleanup();
+ __clearAllBoundsCachesForTest();
+ });
+
+ it('reopening the menu after the cache expires pulls fresh values (hover path)', async () => {
+ // P2「重开菜单仍显示旧档位」:过期缓存必须在重开时拉新 —— 验证手段是把缓存
+ // 标记过期(测试助手),断言重开后**选中态**移到新预算(1M 下 500K 档本就存在,
+ // 只有选中态能区分「拉到了新值」与「旧缓存还在」)。
+ let answer = boundsView({ budget: null, defaultEffectiveWindow: 1_000_000 });
+ installElectronApi(vi.fn(async () => { const v = answer; return v; }));
+ renderChip({ providers: null });
+ const trigger = document.querySelector('[data-context-window-budget-chip]')!;
+ // 首次打开:填入缓存(v1:无预算,选中 1M 默认)。
+ fireEvent.pointerEnter(trigger);
+ await waitFor(() => {
+ expect(checkedOf(document, '1000000')).toBe(true);
+ });
+ // 关闭(宽限期后),把缓存标记过期,换成 v2(预算 500K)。
+ fireEvent.pointerLeave(trigger);
+ await waitFor(() => {
+ expect(screen.queryAllByRole('radio').length).toBe(0);
+ });
+ __expireAllBoundsCachesForTest();
+ answer = boundsView({ budget: 500_000, budgetCustomized: true, defaultEffectiveWindow: 1_000_000 });
+ // 重开:必须拉到 v2 —— 500K 选中态点亮,1M 默认熄灭。
+ fireEvent.pointerEnter(trigger);
+ await waitFor(() => {
+ expect(checkedOf(document, '500000')).toBe(true);
+ });
+ expect(checkedOf(document, '1000000')).toBe(false);
+ });
+
+ it('a cancelled bounds query never writes the shared cache', async () => {
+ // P2「旧回答覆盖新缓存」:慢的旧响应回来时若把旧值写进共享缓存并盖上新
+ // fetchedAt,后挂载的卡片会把旧预算当新数据。取消的响应必须什么都不写。
+ let releaseOld: ((v: unknown) => void) | null = null;
+ const oldPending = new Promise<unknown>((resolve) => { releaseOld = resolve; });
+ installElectronApi(vi.fn()
+ .mockImplementationOnce(() => oldPending) // 旧实例的查询挂起
+ .mockResolvedValue(boundsView({ budget: 500_000, budgetCustomized: true }))); // 新实例立刻回
+ // 实例 A(挂起中)
+ const a = render(<ContextWindowBudgetChip sessionId={SESSION_ID} contextTokens={0}
+ model="grok-4.6" providerId="xd" agentKind="cc" providers={null} />);
+ // 实例 B(同 key):拿到新答案
+ const shellB = render(<ContextWindowBudgetChip sessionId={SESSION_ID} contextTokens={0}
+ model="grok-4.6" providerId="xd" agentKind="cc" providers={null} />);
+ const triggerB = shellB.container.querySelector('[data-context-window-budget-chip]')!;
+ fireEvent.click(triggerB);
+ await waitFor(() => {
+ const tokens = [...shellB.container.querySelectorAll('[role=radio]')]
+ .map((el) => el.getAttribute('data-token'));
+ expect(tokens).toContain('500000');
+ });
+ // A 卸载 → 它的在飞查询被取消 → 此时才 resolve 旧答案
+ a.unmount();
+ releaseOld!(boundsView({ budget: null }));
+ await act(async () => { await Promise.resolve(); });
+ // 新挂载的实例必须拿到**新**答案:500K 档在 1M 窗口下本来就在,**选中态**
+ // 才能区分 —— budget=500K 时选中 500K;被旧响应覆盖回 null 时选中 1M 默认。
+ const shellC = render(<ContextWindowBudgetChip sessionId={SESSION_ID} contextTokens={0}
+ model="grok-4.6" providerId="xd" agentKind="cc" providers={null} />);
+ const triggerC = shellC.container.querySelector('[data-context-window-budget-chip]')!;
+ fireEvent.click(triggerC);
+ await waitFor(() => {
+ expect(checkedOf(shellC.container, '500000')).toBe(true);
+ });
+ expect(checkedOf(shellC.container, '1000000')).not.toBe(true);
+ });
+
+ it('a budget commit in one instance syncs the other instance for the same session', async () => {
+ // P2「多视图档位不同步」:A 实例提交 500K 后,同 key 的 B 实例必须重读权威值
+ // (否则 B 仍显示「模型默认」,点默认档又被 next===storedBudget 跳过、清不掉)。
+ let answer = boundsView({ budget: null, defaultEffectiveWindow: 1_000_000 });
+ installElectronApi(vi.fn(async () => { const v = answer; return v; }));
+ // 两实例先后渲染;注意两卡有互斥协调器("唯一窗体")—— 同屏只检查当前打开的那张。
+ const shellA = render(<ContextWindowBudgetChip sessionId={SESSION_ID} contextTokens={0}
+ model="grok-4.6" providerId="xd" agentKind="cc" providers={null} />);
+ const shellB = render(<ContextWindowBudgetChip sessionId={SESSION_ID} contextTokens={0}
+ model="grok-4.6" providerId="xd" agentKind="cc" providers={null} />);
+
+ // ① 打开 A:500K 档在 1M 窗口下本来就在(50%),选中态是「1M 默认」。
+ const triggerA = shellA.container.querySelector('[data-context-window-budget-chip]')!;
+ fireEvent.click(triggerA);
+ await waitFor(() => {
+ expect(shellA.container.querySelectorAll('[role=radio]').length).toBeGreaterThan(0);
+ });
+
+ // ② 在 A 里提交 500K:写链路必须真实发生(这是跨实例通知的前提)。
+ answer = boundsView({ budget: 500_000, budgetCustomized: true, defaultEffectiveWindow: 1_000_000 });
+ const fiveHundred = shellA.container.querySelector('[role="radio"][data-token="500000"]');
+ expect(fiveHundred).not.toBeNull();
+ fireEvent.click(fiveHundred!);
+ await waitFor(() => {
+ expect(mockUpdate).toHaveBeenCalledWith(SESSION_ID, { contextWindowBudget: 500_000 });
+ });
+
+ // ③ 打开 B:因跨实例通知重读权威值,500K 的**选中态**必须点亮 ——
+ // 只断言「行存在」不足以证明同步(500K 行本来就存在);1M 默认行不得同时选中。
+ const triggerB = shellB.container.querySelector('[data-context-window-budget-chip]')!;
+ fireEvent.click(triggerB);
+ await waitFor(() => {
+ expect(checkedOf(shellB.container, '500000')).toBe(true);
+ });
+ // 1M 默认行若在则不得同时选中(行本身是否渲染属档位集合口径,不作强断言)。
+ expect(checkedOf(shellB.container, '1000000')).not.toBe(true);
+ });
+});
+
+
+describe('isBoundsCacheEntryStale(重开菜单刷新判定的纯函数)', () => {
+ it('无条目 = 过期(必须拉新)', () => {
+ expect(isBoundsCacheEntryStale(undefined, 1_000)).toBe(true);
+ expect(isBoundsCacheEntryStale(null, 1_000)).toBe(true);
+ });
+ it('TTL 内新鲜、超过 TTL 过期(边界含等号取保守:满 60s 即过期)', () => {
+ const entry = { fetchedAt: 10_000 };
+ expect(isBoundsCacheEntryStale(entry, 10_000 + 59_999)).toBe(false);
+ expect(isBoundsCacheEntryStale(entry, 10_000 + 60_000)).toBe(true);
+ expect(isBoundsCacheEntryStale(entry, 10_000 + 61_000)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 0ee0b7d997..e862738dc0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -165,6 +165,7 @@ import { useAnimatedNumber } from '@/hooks/useAnimatedNumber';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { useSilentEncryptedRetry } from '@/hooks/useSilentEncryptedRetry';
import { TodaySpendChip } from '@/components/status/TodaySpendChip';
+import { ContextWindowBudgetChip } from '@/components/status/ContextWindowBudgetChip';
import { TopRightChipStack, TopRightChipStackProvider } from '@/components/chat/TopRightChipStack';
import { ChatDisplaySnapshotProvider } from '@/components/chat/ChatDisplaySnapshotContext';
import { useCCAgentChat } from '@/hooks/useCCAgentChat';
@@ -6306,6 +6307,25 @@ function CCAgentSessionContent({
deviceLinkDeviceId={remoteDeviceId ?? null}
usageAccount={usageAccount}
/>
+ {/* device-link 远程任务的档位走 maker:set-context-window-budget 隧道命令,
+ 在偏好文件落盘并应用到活实例;老被控端不支持时由 chip 提示版本不支持。
+ 当前档位与可选档位一起来自权威边界查询(本地 main / 远程被控端)。 */}
+ {sessionId && (
+ <ContextWindowBudgetChip
+ sessionId={sessionId}
+ contextTokens={agentStatus.contextTokens}
+ model={agentSwitchIntent?.model ?? session?.model ?? ''}
+ providerId={
+ agentSwitchIntent
+ ? agentSwitchIntent.providerId
+ : (session?.providerId ?? null)
+ }
+ agentKind={normalizeDbAgentKind(displayAgentKind)}
+ providers={{ providers }}
+ deviceId={remoteDeviceId}
+ disabled={readOnly || !session}
+ />
+ )}
<ContextCapacityRing
isRunning={agentStatus.isRunning}
sessionId={sessionId}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b61283eeac..6ff77aa1b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -12665,6 +12665,19 @@
}
},
"ccAgent": {
+ "contextWindowBudget": {
+ "menuTitle": "Task context window",
+ "triggerLabel": "Task context window, currently {{window}}",
+ "menuHint": "Affects this task only. Applies from the next message.",
+ "optionDefault": "Model default",
+ "optionPercent": "{{percent}}%",
+ "inputPrice": "input {{price}}/M",
+ "remoteUnsupported": "The controlled device does not support changing this task's context window",
+ "remoteTightenOnly": "The controlled device ceiling is unavailable, so only smaller tiers are offered here.",
+ "readOnlyHint": "Read-only task: you can review the tiers and price bands, but not change them.",
+ "shrinkWarning": "{{used}} already in use — a smaller window compacts or rolls over first.",
+ "saveFailed": "Failed to save the context window tier"
+ },
"agentStatus": {
"readingMemory": "Reading memory…",
"savingMemory": "Saving memory…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 436267ff7f..5dd49b2e0b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -12611,6 +12611,19 @@
}
},
"ccAgent": {
+ "contextWindowBudget": {
+ "menuTitle": "このタスクのコンテキストウィンドウ",
+ "triggerLabel": "タスクのコンテキストウィンドウ、現在 {{window}}",
+ "menuHint": "このタスクのみ。次のメッセージから適用。",
+ "optionDefault": "モデル既定",
+ "optionPercent": "{{percent}}%",
+ "inputPrice": "入力 {{price}}/M",
+ "remoteUnsupported": "被制御デバイスのバージョンではこのタスクのコンテキストウィンドウを変更できません",
+ "remoteTightenOnly": "接続先の上限が読めないため、縮小方向のみ提示します。",
+ "readOnlyHint": "読み取り専用のタスクです。段階と価格帯は確認できますが、変更はできません。",
+ "shrinkWarning": "現在 {{used}} 使用中。小さいウィンドウにすると先に圧縮または切り替えが発生します。",
+ "saveFailed": "コンテキストウィンドウの保存に失敗しました"
+ },
"agentStatus": {
"readingMemory": "記憶を読んでいます…",
"savingMemory": "記憶を保存しています…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6e525bda8c..e8e64b1562 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -12611,6 +12611,19 @@
}
},
"ccAgent": {
+ "contextWindowBudget": {
+ "menuTitle": "이 작업의 컨텍스트 창",
+ "triggerLabel": "작업 컨텍스트 창, 현재 {{window}}",
+ "menuHint": "이 작업에만 적용됩니다. 다음 메시지부터 적용됩니다.",
+ "optionDefault": "모델 기본값",
+ "optionPercent": "{{percent}}%",
+ "inputPrice": "입력 {{price}}/M",
+ "remoteUnsupported": "피제어 기기 버전에서는 이 작업의 컨텍스트 창을 변경할 수 없습니다",
+ "remoteTightenOnly": "피제어 기기 상한을 읽을 수 없어 축소 방향만 제공합니다.",
+ "readOnlyHint": "읽기 전용 작업입니다. 단계와 요금 구간은 볼 수 있지만 변경할 수는 없습니다.",
+ "shrinkWarning": "현재 {{used}} 사용 중 — 더 작은 창은 먼저 압축하거나 새 창으로 전환합니다.",
+ "saveFailed": "컨텍스트 창 저장에 실패했습니다"
+ },
"agentStatus": {
"readingMemory": "기억을 읽고 있어요…",
"savingMemory": "기억을 저장하고 있어요…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 60fd88602c..1e426be306 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12611,6 +12611,19 @@
}
},
"ccAgent": {
+ "contextWindowBudget": {
+ "menuTitle": "任务上下文窗口",
+ "triggerLabel": "任务上下文窗口,当前 {{window}}",
+ "menuHint": "只影响本任务,下一条消息生效。",
+ "optionDefault": "模型默认",
+ "optionPercent": "{{percent}}%",
+ "inputPrice": "输入 {{price}}/M",
+ "remoteUnsupported": "被控设备版本不支持调整任务上下文窗口",
+ "remoteTightenOnly": "被控端上限不可用,这里只提供调小档。",
+ "readOnlyHint": "只读任务:可以查看档位与价带,但不能修改。",
+ "shrinkWarning": "当前已用 {{used}},换到更小档位会先触发压缩或换窗。",
+ "saveFailed": "保存上下文窗口档位失败"
+ },
"agentStatus": {
"readingMemory": "正在读取记忆…",
"savingMemory": "正在保存记忆…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 1d515fb6fb..6c322e7573 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12611,6 +12611,19 @@
}
},
"ccAgent": {
+ "contextWindowBudget": {
+ "menuTitle": "任務上下文視窗",
+ "triggerLabel": "任務上下文視窗,目前 {{window}}",
+ "menuHint": "只影響本任務,下一則訊息生效。",
+ "optionDefault": "模型預設",
+ "optionPercent": "{{percent}}%",
+ "inputPrice": "輸入 {{price}}/M",
+ "remoteUnsupported": "被控裝置版本不支援調整任務上下文視窗",
+ "remoteTightenOnly": "被控裝置的上限無法讀取,這裡只提供調小檔。",
+ "readOnlyHint": "唯讀任務:可以查看檔位與價差,但不能修改。",
+ "shrinkWarning": "目前已用 {{used}},換到更小檔位會先觸發壓縮或換窗。",
+ "saveFailed": "儲存上下文視窗檔位失敗"
+ },
"agentStatus": {
"readingMemory": "正在讀取記憶…",
"savingMemory": "正在儲存記憶…",