Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(remote-agent): 用量余量读 Agent 所在电脑的账号

Lizi4967ef4e6c43
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index 098f9d05d9..f9ea1817cb 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -61,9 +61,15 @@ describe('TodaySpendChip dashboard routing', () => {
});
it('renders device-link remote sessions data-driven without local-account classification', () => {
- // device-link 远程会话:计费形态事实在被控端,本机 route 观察 / 账号状态一律不用。
+ // device-link 远程会话 / 远程 Agent:计费形态事实在账号所在电脑,本机 route 观察 / 账号
+ // 状态一律不用。账号所在电脑缺省是任务所在电脑(被控端),远程 Agent 时是 Agent 那台。
expect(compact(source)).toContain(
- compact('const isDeviceLinkRemote = Boolean(deviceLinkDeviceId);'),
+ compact(
+ "usageAccount.kind === 'task' ? (deviceLinkDeviceId ?? null)",
+ ),
+ );
+ expect(compact(source)).toContain(
+ compact('const isDeviceLinkRemote = Boolean(accountDeviceId) || accountUnreadable;'),
);
// 本机 Codex runtime route 观察对 device-link 关闭(否则按控制端账号形态张冠李戴)
expect(compact(source)).toContain(
@@ -82,7 +88,7 @@ describe('TodaySpendChip dashboard routing', () => {
);
expect(compact(source)).toContain(compact('const isDeviceLinkRemoteClaudeSubscription ='));
expect(compact(source)).toContain(
- compact('isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge ? (deviceLinkDeviceId ?? null) : null,'),
+ compact('isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge ? accountDeviceId : null,'),
);
// 本机订阅快照 hook 对 device-link 关闭(两个 hook 的 enabled 互斥)
expect(compact(source)).toContain(
@@ -114,10 +120,10 @@ describe('TodaySpendChip dashboard routing', () => {
expect(compact(source)).toContain(
compact("const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);"),
);
- // SSH(remoteHostId)与 device-link(deviceLinkDeviceId)远程会话都抑制本机账户快照读取
+ // SSH(remoteHostId)与 device-link / 远程 Agent(账号不在本机)都抑制本机账户快照读取
expect(compact(source)).toContain(compact('deviceLinkDeviceId?: string | null'));
expect(compact(source)).toContain(
- compact('const isAnyRemoteSession = Boolean(remoteHostId) || Boolean(deviceLinkDeviceId);'),
+ compact('const isAnyRemoteSession = Boolean(remoteHostId) || isDeviceLinkRemote;'),
);
expect(compact(source)).toContain(
compact(
@@ -240,12 +246,12 @@ describe('TodaySpendChip dashboard routing', () => {
);
expect(compact(source)).toContain(compact('requestCodexAccountRefresh(providerId ?? undefined);'));
expect(compact(source)).toContain(compact("requestXaiSubscriptionRefresh(providerId ?? 'xai');"));
- // 悬念期催刷按会话来源分路:远程订阅会话催被控端(隧道,被控端节流兜底),
+ // 悬念期催刷按账号所在分路:远程订阅会话 / 远程 Agent 催账号所在电脑(隧道,那台节流兜底),
// 本机订阅会话催本机;不得拿本机通道替远程会话催刷(账号不同)。
expect(compact(source)).toContain(
compact(
- 'if (isDeviceLinkRemoteClaudeSubscription && deviceLinkDeviceId) {\n' +
- " requestRemoteClaudeSubscriptionRefresh(deviceLinkDeviceId, providerId ?? 'anthropic');\n" +
+ 'if (isDeviceLinkRemoteClaudeSubscription && accountDeviceId) {\n' +
+ " requestRemoteClaudeSubscriptionRefresh(accountDeviceId, providerId ?? 'anthropic');\n" +
' } else if (!isDeviceLinkRemote) {\n' +
" requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');\n" +
' }',
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 40b5448e7a..cfbd0cc2c7 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -20,6 +20,7 @@ import type { TFunction } from 'i18next';
import { summarizeCodexRateLimitReset } from '@cindy/maker-shared/session-controls';
import { cn } from '@/lib/utils';
+import { TASK_USAGE_ACCOUNT, type UsageAccountLocation } from '@/lib/usageAccountLocation';
import {
DAILY_SOFT_LIMIT_FACTOR,
formatCompactMoney,
@@ -748,6 +749,11 @@ interface TodaySpendChipProps {
* 必须抑制本地账号读取(否则 chip 显示的是控制端账号的用量,张冠李戴)。
*/
deviceLinkDeviceId?: string | null;
+ /**
+ * 本轮消耗哪台电脑的账号额度(远程 Agent 让 Agent 在另一台电脑运行,见 usageAccountLocation)。
+ * 缺省 = 任务所在电脑:本机任务读本机,deviceLinkDeviceId 非空时读被控端。
+ */
+ usageAccount?: UsageAccountLocation;
}
export function TodaySpendChip({
@@ -760,12 +766,24 @@ export function TodaySpendChip({
sessionInitialTokens,
remoteHostId,
deviceLinkDeviceId,
+ usageAccount = TASK_USAGE_ACCOUNT,
}: TodaySpendChipProps) {
const { t, i18n } = useTranslation();
const formatterLocale = i18n.resolvedLanguage ?? i18n.language;
- // device-link 远程会话:turn 跑在被控端、消耗被控端账号,计费形态(订阅/网关)与账号
- // 余量的事实都在被控端 —— 本机的 route 观察 / 账号快照与之无关,一律不读、不据此分类。
- const isDeviceLinkRemote = Boolean(deviceLinkDeviceId);
+ // 账号余量从哪台电脑读:Agent 在任务所在电脑时就是那台(本机,或 deviceLinkDeviceId 的被控端);
+ // 远程 Agent 在另一台电脑时是那台(经 device-link 读它的镜像,与模型选择器同一份)。
+ // 读不到那份账号(别人分享的供应商等)时本机与远端都不读,只显示任务价值。
+ const accountDeviceId =
+ usageAccount.kind === 'device'
+ ? usageAccount.deviceId
+ : usageAccount.kind === 'task'
+ ? (deviceLinkDeviceId ?? null)
+ : null;
+ const accountUnreadable = usageAccount.kind === 'unreadable';
+ // 账号不在本机(device-link 远程会话 / 远程 Agent):turn 消耗另一台电脑的账号,计费形态
+ // (订阅/网关)与账号余量的事实都在那台 —— 本机的 route 观察 / 账号快照与之无关,一律不读、
+ // 不据此分类。
+ const isDeviceLinkRemote = Boolean(accountDeviceId) || accountUnreadable;
const { authInjection: codexAuthInjection } = useCodexRuntimeRoute({
enabled: vendorKey === 'codex' && !isDeviceLinkRemote,
refreshKey: sessionId,
@@ -798,20 +816,22 @@ export function TodaySpendChip({
observedClaudeRoute == null &&
(gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null));
const { providers: localQuotaProviders } = useProviders();
- const { providers: deviceQuotaProviders } = useDeviceProviders(deviceLinkDeviceId ?? undefined);
+ const { providers: deviceQuotaProviders } = useDeviceProviders(accountDeviceId ?? undefined);
const quotaProviders = isDeviceLinkRemote ? deviceQuotaProviders : localQuotaProviders;
const selectedQuotaProvider = quotaProviders.find((provider) => provider.id === providerId);
const isClaudeAccount =
providerId === 'anthropic' || selectedQuotaProvider?.auth?.native === 'claude';
const isXaiAccount = providerId === 'xai' || selectedQuotaProvider?.auth?.native === 'xai';
- // Remote provider ids belong to the controlled device. Reuse its existing provider
+ // Remote provider ids belong to the device running the Agent. Reuse its existing provider
// catalog (also used by the model selector), never the controller's same-named account.
const isDeviceLinkRemoteBridgeModel =
typeof modelId === 'string' &&
(modelId.startsWith(CHATGPT_MODEL_PREFIX) || modelId.startsWith(XAI_MODEL_PREFIX));
+ // 默认路由只在被控端自己跑 Agent 时有观察值:远程 Agent 必带来源(没来源按读不到处理),
+ // 走不到这里。
const remoteClaudeRoute = useRemoteClaudeSessionRoute(
isDeviceLinkRemote && vendorKey === 'cc' && providerId == null && !isDeviceLinkRemoteBridgeModel
- ? (deviceLinkDeviceId ?? null)
+ ? accountDeviceId
: null,
sessionId,
);
@@ -893,9 +913,9 @@ export function TodaySpendChip({
// codex-oauth 与 cc+chatgpt/ bridge 共用同一 ChatGPT 账户 → 同一套限额窗口 chip 渲染。
const usesCodexQuotaForm = isCodexOauth || isChatgptBridge;
const usesXaiQuotaForm = isCodexXaiProvider || isXaiBridge;
- // 远程会话不读本机账户快照 —— 额度事实在远端:SSH 用 remoteHostId 判,device-link 用
- // deviceLinkDeviceId 判(两者互斥,任一非空即远程,turn 消耗的是远端账号的额度)。
- const isAnyRemoteSession = Boolean(remoteHostId) || Boolean(deviceLinkDeviceId);
+ // 远程会话不读本机账户快照 —— 额度事实在远端:SSH 用 remoteHostId 判,device-link 与
+ // 远程 Agent 用 isDeviceLinkRemote 判(任一成立即远程,turn 消耗的是远端账号的额度)。
+ const isAnyRemoteSession = Boolean(remoteHostId) || isDeviceLinkRemote;
// Model Access 配额只属于实际走 XD/Cindy AI Gateway 的本地会话。显式自定义供应商即使
// 复用了 env-key / oauth-bearer host,也不能据 host 的启动凭证把 /v2/user/info 串进来。
const isClaudeGateway =
@@ -946,7 +966,8 @@ export function TodaySpendChip({
isCodexApi ||
isCodexSubscription ||
isSubscriptionBridge ||
- isDeviceLinkRemote
+ isDeviceLinkRemote ||
+ Boolean(deviceLinkDeviceId)
? sessionId
: undefined,
sessionInitialTokens,
@@ -963,10 +984,10 @@ export function TodaySpendChip({
modelId,
providerId ?? 'openai',
);
- // device-link 远程 codex / chatgpt-bridge:被控端权威组合 payload 镜像,选槽 / 选桶
+ // device-link 远程 codex / chatgpt-bridge:账号所在电脑的权威组合 payload 镜像,选槽 / 选桶
// 与本机同口径在消费点执行(selectRemoteCodexAccountUsage)。
const remoteCodexAccountPayload = useRemoteCodexAccountUsage(
- isDeviceLinkRemote && usesCodexQuotaForm ? (deviceLinkDeviceId ?? null) : null,
+ isDeviceLinkRemote && usesCodexQuotaForm ? accountDeviceId : null,
providerId ?? 'openai',
);
const accountUsage = isDeviceLinkRemote
@@ -983,8 +1004,7 @@ export function TodaySpendChip({
// xAI 限流快照同为本机 main 抓的 —— SSH 远程仍抑制回落价值估算;device-link 远程
// 走被控端镜像(订阅周用量 invoke + push,限流头 push-only,与本机同语义降级)。
// 本机侧按所选供应商账号取(多账号供应商,#4197 / #4246:限流 hook 同样带 providerId)。
- const remoteXaiDeviceId =
- isDeviceLinkRemote && usesXaiQuotaForm ? (deviceLinkDeviceId ?? null) : null;
+ const remoteXaiDeviceId = isDeviceLinkRemote && usesXaiQuotaForm ? accountDeviceId : null;
const localXaiRateLimit = useXaiRateLimit(
usesXaiQuotaForm && !isAnyRemoteSession,
providerId ?? 'xai',
@@ -1006,7 +1026,7 @@ export function TodaySpendChip({
// 均只展示各自的额度/本地会话统计,不读取 Model Access 账号配额。
const localClaudeQuota = useClaudeAccountUsage(usesGatewayQuota);
const remoteClaudeQuota = useRemoteClaudeAccountUsage(
- isDeviceLinkRemoteGateway ? (deviceLinkDeviceId ?? null) : null,
+ isDeviceLinkRemoteGateway ? accountDeviceId : null,
);
const claudeQuota = isDeviceLinkRemote ? remoteClaudeQuota : localClaudeQuota;
// 个人租户的额度事实在 Gateway 三池账本里(推理入口不提供管理面接口), 与上面的
@@ -1014,16 +1034,14 @@ export function TodaySpendChip({
const creditUsage = useModelAccessCreditUsage(usesGatewayQuota);
const creditTotals = React.useMemo(() => resolveCreditTotals(creditUsage), [creditUsage]);
// Claude 订阅账号余量 (5h/周/分模型窗口, 端点 + proxy 旁路 headers 双源)。bridge 模型形态
- // 优先(不消耗 Claude 订阅额度),此时不读。device-link 远程会话读被控端镜像,
- // 本机快照与其无关(额度事实在被控端),两个 hook 的 enabled 互斥。
+ // 优先(不消耗 Claude 订阅额度),此时不读。device-link 远程会话 / 远程 Agent 读账号所在
+ // 电脑的镜像,本机快照与其无关(额度事实在那台),两个 hook 的 enabled 互斥。
const localClaudeSubscriptionUsage = useClaudeSubscriptionUsage(
isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote,
providerId ?? 'anthropic',
);
const remoteClaudeSubscriptionUsage = useRemoteClaudeSubscriptionUsage(
- isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge
- ? (deviceLinkDeviceId ?? null)
- : null,
+ isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge ? accountDeviceId : null,
providerId ?? 'anthropic',
);
const claudeSubscriptionUsage = isDeviceLinkRemote
@@ -1126,7 +1144,8 @@ export function TodaySpendChip({
modelId,
vendorKey,
remoteHostId,
- deviceLinkDeviceId,
+ accountDeviceId,
+ accountUnreadable,
usesCodexQuotaForm,
usesXaiQuotaForm,
isClaudeSubscription,
@@ -1141,7 +1160,8 @@ export function TodaySpendChip({
modelId,
vendorKey,
remoteHostId,
- deviceLinkDeviceId,
+ accountDeviceId,
+ accountUnreadable,
usesCodexQuotaForm,
usesXaiQuotaForm,
isClaudeSubscription,
@@ -1165,7 +1185,8 @@ export function TodaySpendChip({
modelId,
vendorKey,
remoteHostId,
- deviceLinkDeviceId,
+ accountDeviceId,
+ accountUnreadable,
usesCodexQuotaForm,
usesXaiQuotaForm,
isClaudeSubscription,
@@ -1291,7 +1312,7 @@ export function TodaySpendChip({
// 礼花按供应商共享去重,不依赖任务组件的挂载或数字滚动状态。
const chipRef = React.useRef<HTMLDivElement | null>(null);
const celebrationProvider = JSON.stringify([
- isDeviceLinkRemote ? deviceLinkDeviceId : 'local',
+ isDeviceLinkRemote ? accountDeviceId : 'local',
providerId ?? (usesCodexQuotaForm ? 'openai' : usesXaiQuotaForm ? 'xai' : 'anthropic'),
]);
const quotaSnapshotUpdatedAt = usesCodexQuotaForm
@@ -1364,25 +1385,25 @@ export function TodaySpendChip({
usesXaiQuotaForm && !isXaiWeeklyUsageCurrent(xaiSubscriptionUsage, windowLabelNowMs);
React.useEffect(() => {
if (!hasPendingResetWindow && !xaiNeedsWeeklyRefresh) return;
- // 悬念期催刷按会话来源分路:device-link 远程催被控端(经隧道,被控端节流兜底),
- // 本机催本机(按所选供应商账号,#4197);不得拿本机通道替远程会话催刷(账号不同)。
+ // 悬念期催刷按账号所在分路:device-link 远程 / 远程 Agent 催账号所在电脑(经隧道,那台
+ // 节流兜底),本机催本机(按所选供应商账号,#4197);不得拿本机通道替远程会话催刷(账号不同)。
if (isChatgptBridge || (isDeviceLinkRemote && usesCodexQuotaForm)) {
if (isDeviceLinkRemote) {
- if (deviceLinkDeviceId)
- requestRemoteCodexAccountRefresh(deviceLinkDeviceId, providerId ?? 'openai');
+ if (accountDeviceId)
+ requestRemoteCodexAccountRefresh(accountDeviceId, providerId ?? 'openai');
} else {
requestCodexAccountRefresh(providerId ?? undefined);
}
} else if (usesXaiQuotaForm) {
if (isDeviceLinkRemote) {
- if (deviceLinkDeviceId)
- requestRemoteXaiSubscriptionRefresh(deviceLinkDeviceId, providerId ?? 'xai');
+ if (accountDeviceId)
+ requestRemoteXaiSubscriptionRefresh(accountDeviceId, providerId ?? 'xai');
} else {
requestXaiSubscriptionRefresh(providerId ?? 'xai');
}
} else if (isClaudeSubscription && !usesCodexQuotaForm) {
- if (isDeviceLinkRemoteClaudeSubscription && deviceLinkDeviceId) {
- requestRemoteClaudeSubscriptionRefresh(deviceLinkDeviceId, providerId ?? 'anthropic');
+ if (isDeviceLinkRemoteClaudeSubscription && accountDeviceId) {
+ requestRemoteClaudeSubscriptionRefresh(accountDeviceId, providerId ?? 'anthropic');
} else if (!isDeviceLinkRemote) {
requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');
}
@@ -1394,7 +1415,7 @@ export function TodaySpendChip({
isClaudeSubscription,
isDeviceLinkRemote,
isDeviceLinkRemoteClaudeSubscription,
- deviceLinkDeviceId,
+ accountDeviceId,
usesCodexQuotaForm,
usesXaiQuotaForm,
providerId,
@@ -1407,11 +1428,13 @@ export function TodaySpendChip({
void window.electronAPI.openExternal(usageDashboardUrl);
};
- // device-link 远程形态已解析 = 走与本机一致的对应分支(数据全部来自被控端镜像);
- // 未解析(默认路由无观察值 / 老被控端)才落占位分支。
+ // device-link 远程形态已解析 = 走与本机一致的对应分支(数据全部来自账号所在电脑的镜像);
+ // 未解析(默认路由无观察值 / 老被控端)或那份账号读不到(分享来的供应商等)才落占位分支。
const deviceLinkRemoteFormResolved =
- isDeviceLinkRemoteClaudeSubscription ||
- (isDeviceLinkRemote && (usesCodexQuotaForm || usesXaiQuotaForm || isDeviceLinkRemoteGateway));
+ !accountUnreadable &&
+ (isDeviceLinkRemoteClaudeSubscription ||
+ (isDeviceLinkRemote &&
+ (usesCodexQuotaForm || usesXaiQuotaForm || isDeviceLinkRemoteGateway)));
let labelNode: React.ReactNode;
let account: UsageCardAccount = { title: t('quotaCard.usageTitle'), windows: [] };
if (isDeviceLinkRemote && !deviceLinkRemoteFormResolved) {
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
index d28f1624f7..1f383180f6 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
@@ -427,6 +427,129 @@ describe('TodaySpendChip device-link remote sessions', () => {
});
+// 远程 Agent:Agent 在另一台电脑上用那台的登录运行,余量读那台(2026-10-09 用户反馈:远程供应商
+// 的任务一直「等待配额数据更新」—— chip 拿任务所在电脑的同名账号去读)。
+describe('TodaySpendChip remote Agent account', () => {
+ const agentSnapshot: ClaudeSubscriptionUsageSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 12 },
+ sevenDay: { utilization: 25 },
+ };
+
+ it('本机任务的 Agent 在另一台电脑:读那台的镜像,不读本机同名账号', () => {
+ mocks.localClaudeSnapshot = { source: 'oauth-endpoint', fiveHour: { utilization: 90 } };
+ mocks.remoteClaudeSnapshot = agentSnapshot;
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="anthropic"
+ modelId="claude-fable-5[1m]"
+ sessionId="session-local-remote-agent"
+ usageAccount={{ kind: 'device', deviceId: 'device-agent' }}
+ />,
+ );
+
+ expect(container.textContent).toContain('5h 剩余 88%');
+ expect(container.textContent).not.toContain('剩余 10%');
+ expect(mocks.remoteHookDeviceIds).toContain('device-agent');
+ });
+
+ it('远程控制的任务把 Agent 放在第三台电脑:读第三台,不读被控电脑', () => {
+ mocks.remoteClaudeSnapshot = agentSnapshot;
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="anthropic"
+ modelId="claude-fable-5[1m]"
+ sessionId="session-controlled-remote-agent"
+ deviceLinkDeviceId="device-abc"
+ usageAccount={{ kind: 'device', deviceId: 'device-agent' }}
+ />,
+ );
+
+ expect(container.textContent).toContain('5h 剩余 88%');
+ expect(mocks.remoteHookDeviceIds.filter(Boolean)).toEqual(
+ expect.arrayContaining(['device-agent']),
+ );
+ expect(mocks.remoteHookDeviceIds).not.toContain('device-abc');
+ });
+
+ it('远程 Agent 的 codex 账号同样读那台', () => {
+ mocks.remoteCodexPayload = {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ appServerBuckets: {
+ codex: {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ },
+ },
+ webSnapshot: null,
+ };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="codex"
+ providerId="openai"
+ modelId="gpt-5.6-sol"
+ sessionId="session-remote-agent-codex"
+ usageAccount={{ kind: 'device', deviceId: 'device-agent' }}
+ />,
+ );
+
+ expect(container.textContent).toContain('剩余 88%');
+ expect(mocks.remoteCodexDeviceIds).toContain('device-agent');
+ });
+
+ it('远程控制的任务把 Agent 放在本机:读本机账号', () => {
+ mocks.localProviders = [{ id: 'anthropic', auth: { native: 'claude' } }];
+ mocks.localClaudeSnapshot = agentSnapshot;
+ mocks.remoteClaudeSnapshot = { source: 'oauth-endpoint', fiveHour: { utilization: 90 } };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="anthropic"
+ modelId="claude-fable-5[1m]"
+ sessionId="session-controlled-agent-here"
+ deviceLinkDeviceId="device-abc"
+ usageAccount={{ kind: 'local' }}
+ />,
+ );
+
+ expect(container.textContent).toContain('5h 剩余 88%');
+ expect(mocks.remoteHookDeviceIds.filter(Boolean)).toHaveLength(0);
+ });
+
+ it('读不到那份账号(分享来的供应商等):只显示任务价值,不等数据、不拿别的账号凑数', () => {
+ mocks.localClaudeSnapshot = agentSnapshot;
+ mocks.remoteClaudeSnapshot = agentSnapshot;
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="anthropic"
+ modelId="claude-fable-5[1m]"
+ sessionId="session-shared-provider"
+ usageAccount={{ kind: 'unreadable' }}
+ />,
+ );
+
+ expect(container.textContent).not.toContain('剩余');
+ expect(mocks.remoteHookDeviceIds.filter(Boolean)).toHaveLength(0);
+ const trigger = screen.getByRole('button', { name: 'quotaCard.usageTitle' });
+ fireEvent.mouseEnter(trigger);
+ act(() => vi.advanceTimersByTime(300));
+ const card = screen.getByTestId('quota-hover-card');
+ expect(card.textContent).not.toContain('等待额度数据');
+ expect(within(card).queryAllByRole('progressbar')).toHaveLength(0);
+ });
+});
+
describe('existing UI with remote account data', () => {
it('renders the same subscription label and classes for identical local and remote data', () => {
const snapshot: ClaudeSubscriptionUsageSnapshot = {
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index a40bbfbfea..ef9e34cd53 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -171,6 +171,7 @@ import {
controlledTaskSupportsAgentLocation,
selectControlledTaskAgentDevices,
} from '@/lib/controlledTaskAgentLocation';
+import { resolveUsageAccountLocation } from '@/lib/usageAccountLocation';
import { useProviderShareAgentDevices } from '@/features/provider-share/useProviderShareAgentDevices';
import {
canExposeWritableDirsChange,
@@ -2168,6 +2169,31 @@ export function CCAgentSessionView({
selectableDevices.find((device) => device.deviceId === remoteDeviceId)?.name ||
null)
: null;
+ // 底部用量 chip 按意图显示下一轮的模型与来源;余量同样读下一轮 Agent 所在那台的账号
+ // (远程 Agent,本机任务或远程控制的任务都一样),不读任务所在电脑的同名账号。
+ const usageChipProviderId = agentSwitchIntent
+ ? agentSwitchIntent.providerId
+ : (session?.providerId ?? null);
+ const usageAccount = useMemo(
+ () =>
+ resolveUsageAccountLocation({
+ taskDeviceId: remoteDeviceId,
+ agentDeviceId: session?.agentDeviceId,
+ pendingAgentDeviceId,
+ providerId: usageChipProviderId,
+ selfDeviceId,
+ sharedTaskGuest: !!remoteDeviceId && isSharedTaskPeer(remoteDeviceId),
+ remoteHostId: session?.remoteHostId,
+ }),
+ [
+ remoteDeviceId,
+ session?.agentDeviceId,
+ pendingAgentDeviceId,
+ usageChipProviderId,
+ selfDeviceId,
+ session?.remoteHostId,
+ ],
+ );
const catalogDeviceId = controlledAgentDeviceId ?? remoteDeviceId ?? agentDeviceId;
const { providers: deviceProviders } = useDeviceProviders(catalogDeviceId);
const providers = catalogDeviceId ? deviceProviders : localProviders;
@@ -5816,17 +5842,14 @@ export function CCAgentSessionView({
<TodaySpendChip
vendorKey={normalizeDbAgentKind(displayAgentKind)}
modelId={agentSwitchIntent?.model ?? session?.model ?? null}
- providerId={
- agentSwitchIntent
- ? agentSwitchIntent.providerId
- : (session?.providerId ?? null)
- }
+ providerId={usageChipProviderId}
sessionId={sessionId}
sessionInitialMoney={session?.totalMoney ?? null}
sessionInitialCostUsd={session?.totalCostUsd ?? null}
sessionInitialTokens={session?.totalTokenUsage ?? null}
remoteHostId={session?.remoteHostId ?? null}
deviceLinkDeviceId={remoteDeviceId ?? null}
+ usageAccount={usageAccount}
/>
<ContextCapacityRing
isRunning={agentStatus.isRunning}
diff --git a/apps/desktop/src/renderer/lib/__tests__/usageAccountLocation.test.ts b/apps/desktop/src/renderer/lib/__tests__/usageAccountLocation.test.ts
new file mode 100644
index 0000000000..1472fc315f
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/usageAccountLocation.test.ts
@@ -0,0 +1,148 @@
+/**
+ * 底部用量 chip 读哪台电脑的账号余量(场景:2026-10-09 用户反馈远程供应商的任务一直显示
+ * 「等待配额数据更新」—— chip 拿任务所在电脑的同名账号去读,Agent 实际在另一台电脑)。
+ */
+import { describe, expect, it } from 'vitest';
+
+import { resolveUsageAccountLocation } from '../usageAccountLocation';
+
+const SELF = 'device-self';
+
+describe('resolveUsageAccountLocation', () => {
+ it('Agent 就在任务所在电脑:沿用任务所在电脑(本机或被控电脑)', () => {
+ for (const taskDeviceId of [null, 'device-controlled']) {
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId,
+ agentDeviceId: null,
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'task' });
+ }
+ // 旧版被控电脑不投影 agentDeviceId(undefined),同样按被控电脑本身。
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: 'device-controlled',
+ agentDeviceId: undefined,
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'task' });
+ });
+
+ it('本机任务的 Agent 在同账号另一台电脑:读那台', () => {
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: null,
+ agentDeviceId: 'device-agent',
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'device', deviceId: 'device-agent' });
+ });
+
+ it('远程控制的任务把 Agent 放在第三台电脑:读第三台,不读被控电脑', () => {
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: 'device-controlled',
+ agentDeviceId: 'device-agent',
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'device', deviceId: 'device-agent' });
+ });
+
+ it('远程控制的任务把 Agent 放在本机:读本机', () => {
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: 'device-controlled',
+ agentDeviceId: SELF,
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'local' });
+ });
+
+ it('跟随挂着的换位置意图(undefined = 位置不变,null = 换回任务所在电脑)', () => {
+ const base = { taskDeviceId: null, providerId: 'anthropic', selfDeviceId: SELF };
+ expect(
+ resolveUsageAccountLocation({
+ ...base,
+ agentDeviceId: null,
+ pendingAgentDeviceId: 'device-agent',
+ }),
+ ).toEqual({ kind: 'device', deviceId: 'device-agent' });
+ expect(
+ resolveUsageAccountLocation({
+ ...base,
+ agentDeviceId: 'device-agent',
+ pendingAgentDeviceId: null,
+ }),
+ ).toEqual({ kind: 'task' });
+ expect(
+ resolveUsageAccountLocation({
+ ...base,
+ agentDeviceId: 'device-agent',
+ pendingAgentDeviceId: undefined,
+ }),
+ ).toEqual({ kind: 'device', deviceId: 'device-agent' });
+ });
+
+ it('别人分享的供应商、共享任务访客、没指定来源:读不到,不拿别的账号凑数', () => {
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: null,
+ agentDeviceId: 'share:share-1',
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: 'device-controlled',
+ agentDeviceId: 'share:share-1',
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: 'shared-task-peer',
+ agentDeviceId: 'device-owner-other',
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ sharedTaskGuest: true,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: null,
+ agentDeviceId: 'device-agent',
+ providerId: null,
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ // 空白来源与手机端同口径,按没指定来源处理。
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: null,
+ agentDeviceId: 'device-agent',
+ providerId: ' ',
+ selfDeviceId: SELF,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ });
+
+ it('SSH 远程工作区忽略残留的 agentDeviceId(与 main 同口径)', () => {
+ expect(
+ resolveUsageAccountLocation({
+ taskDeviceId: null,
+ agentDeviceId: 'device-agent',
+ providerId: 'anthropic',
+ selfDeviceId: SELF,
+ remoteHostId: 'ssh-host',
+ }),
+ ).toEqual({ kind: 'task' });
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/usageAccountLocation.ts b/apps/desktop/src/renderer/lib/usageAccountLocation.ts
new file mode 100644
index 0000000000..3ef2e125c7
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/usageAccountLocation.ts
@@ -0,0 +1,51 @@
+/**
+ * 本轮消耗的是哪台电脑的账号额度 —— 任务底部用量 chip 读谁的订阅余量。
+ *
+ * 远程 Agent(协议见 docs/dev-rules/protocol-compatibility.md「远程 Agent」)让 Agent 在另一台
+ * 电脑上用那台的登录与供应商发模型请求,余量事实也只在那台。任务所在电脑(本机,或远程控制的
+ * 被控电脑)的账号与这一轮无关,不能拿来展示。
+ */
+import { isProviderShareAgentDeviceId } from '../../shared/providerShare';
+
+export type UsageAccountLocation =
+ /** Agent 就在任务所在电脑:本机任务读本机,远程控制的任务读被控电脑(原有行为)。 */
+ | { kind: 'task' }
+ /** 远程控制的任务把 Agent 挪到了本机:读本机账号。 */
+ | { kind: 'local' }
+ /** Agent 在同账号的另一台电脑:经 device-link 读那台的余量镜像(与模型选择器同一份)。 */
+ | { kind: 'device'; deviceId: string }
+ /**
+ * 读不到那份账号:别人分享的供应商(分享者的余量不对受邀者开放)、共享任务访客(Agent 在任务主人
+ * 的其他电脑上),或没指定来源(那台按自己的默认规则挑,本机无从得知用的哪个账号)。
+ * 只显示任务价值,不拿本机或被控电脑的账号凑数。
+ */
+ | { kind: 'unreadable' };
+
+export const TASK_USAGE_ACCOUNT: UsageAccountLocation = { kind: 'task' };
+
+export function resolveUsageAccountLocation(input: {
+ /** 远程控制的任务所在的被控电脑;本机任务为 null / undefined。 */
+ taskDeviceId: string | null | undefined;
+ /** 任务记录的 Agent 所在电脑(null / undefined = 任务所在电脑)。 */
+ agentDeviceId: string | null | undefined;
+ /** 挂着的换位置意图:undefined = 位置不变,null = 换回任务所在电脑。chip 按意图显示下一轮。 */
+ pendingAgentDeviceId?: string | null;
+ /** chip 展示的来源(意图期内为意图的来源)。 */
+ providerId: string | null | undefined;
+ selfDeviceId: string | null | undefined;
+ /** 任务属于别人账号的共享任务(本机是访客)。 */
+ sharedTaskGuest?: boolean;
+ /** SSH 远程工作区:Agent 跑在远端主机上,与 main 同口径忽略残留的 agentDeviceId。 */
+ remoteHostId?: string | null;
+}): UsageAccountLocation {
+ if (input.remoteHostId) return TASK_USAGE_ACCOUNT;
+ const agent =
+ input.pendingAgentDeviceId !== undefined ? input.pendingAgentDeviceId : input.agentDeviceId;
+ if (!agent || agent === input.taskDeviceId) return TASK_USAGE_ACCOUNT;
+ if (!input.taskDeviceId && agent === input.selfDeviceId) return TASK_USAGE_ACCOUNT;
+ if (isProviderShareAgentDeviceId(agent) || input.sharedTaskGuest || !input.providerId?.trim()) {
+ return { kind: 'unreadable' };
+ }
+ if (agent === input.selfDeviceId) return { kind: 'local' };
+ return { kind: 'device', deviceId: agent };
+}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index cac499e0d6..c246b1fb95 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -366,6 +366,7 @@ import {
supportsMobileSessionAgentSwitch,
type MobileSessionAgentKind,
} from '@/session/sessionAgentSwitch';
+import { formatProviderAccountLabel, resolveSessionUsageAccount } from '@/session/sessionUsageAccount';
import { useRemoteAgentCatalogs } from '@/session/useRemoteAgentCatalogs';
import {
drainComposerAnnotationSubmissions,
@@ -2155,14 +2156,10 @@ export default function SessionScreen() {
const accountProvider = composerDeviceProviders.ready
? composerDeviceProviders.providers.find((provider) => provider.id === currentSession?.providerId)
: undefined;
- const providerAccountIdentity = accountProvider?.openAiAccount?.identity?.trim()
- || accountProvider?.subscriptionAccount?.identity?.trim();
- const providerDisplayName = accountProvider?.name?.trim();
- const providerAccountLabel = providerDisplayName && providerAccountIdentity
- && !providerDisplayName.includes(providerAccountIdentity)
- ? `${providerDisplayName} · ${providerAccountIdentity}`
- : providerDisplayName;
- const localCodexRateLimitControl = canUseLocalCodexRateLimitControl(currentSession, accountProvider);
+ // Codex 限额读取 / 重置作用于被控电脑的账号:Agent 在另一台电脑运行时(远程 Agent)这一轮消耗的
+ // 是那台的账号,被控电脑的控件与之无关(余量改由任务菜单读那台,见 sessionUsageAccount)。
+ const localCodexRateLimitControl = !sessionAgentRunsOnOtherComputer(currentSession)
+ && canUseLocalCodexRateLimitControl(currentSession, accountProvider);
const accountProviderId = currentSession?.providerId ?? 'openai';
const accountControlScope = `${deviceId}\0${sessionId}\0${accountProviderId}`;
const accountControlScopeRef = useRef(accountControlScope);
@@ -2626,6 +2623,26 @@ export default function SessionScreen() {
() => agentCatalogFor(nextAgentDeviceId),
[agentCatalogFor, nextAgentDeviceId],
);
+ // 任务菜单的账号余量读 Agent 现在所在那台(远程 Agent):手机直接经 device-link 读它,与读它的
+ // 模型目录同一条路;分享来的供应商等读不到,只显示任务价值。任务价值与上下文仍读被控电脑。
+ const usageAccount = resolveSessionUsageAccount({
+ agentDeviceId: currentAgentDeviceId,
+ providerId: currentSession?.providerId,
+ sharedTaskGuest: isSharedTaskPeer(deviceId),
+ remoteHostId: currentSession?.remoteHostId,
+ });
+ const agentAccountMaker = useMobileMakerTransport(
+ usageAccount.kind === 'device' ? usageAccount.deviceId : deviceId,
+ );
+ const menuAccountReader = usageAccount.kind === 'host'
+ ? maker
+ : usageAccount.kind === 'device' ? agentAccountMaker : null;
+ /** 菜单上的来源与登录身份:Agent 在另一台电脑时按那台的目录,不借被控电脑的同名来源。 */
+ const menuAccountProvider = usageAccount.kind !== 'host'
+ ? (currentAgentCatalog.loading
+ ? undefined
+ : currentAgentCatalog.providers.find((provider) => provider.id === currentSession?.providerId))
+ : accountProvider;
const runtimeOptions = useMemo(
() => currentSession ? buildSessionRuntimeOptions(currentSession, capabilities) : null,
[capabilities, currentSession],
@@ -9325,7 +9342,7 @@ export default function SessionScreen() {
setSettingsOpen(false);
guardedPush({ pathname: '/shared-session', params: { sessionId, deviceId } });
}}
- providerName={providerAccountLabel}
+ providerName={formatProviderAccountLabel(menuAccountProvider)}
modelLabel={sessionModelDisplayName}
messageOnly={sessionManagedByHost}
onOpenSearch={() => {
@@ -9333,7 +9350,8 @@ export default function SessionScreen() {
setSettingsOpen(false);
}}
usageReader={maker}
- accountProvider={accountProvider}
+ accountUsageReader={menuAccountReader}
+ accountProvider={menuAccountProvider}
accountUsage={localCodexRateLimitControl ? accountUsage : null}
busy={controlBusy}
codexRateLimits={localCodexRateLimitControl ? codexRateLimits : null}
diff --git a/apps/mobile/src/__tests__/sessionUsageAccount.test.ts b/apps/mobile/src/__tests__/sessionUsageAccount.test.ts
new file mode 100644
index 0000000000..ebb40b01bd
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionUsageAccount.test.ts
@@ -0,0 +1,77 @@
+/**
+ * 任务菜单的账号余量读哪台电脑(2026-10-09 用户反馈:远程供应商的任务看不到余量 —— 读的是被控
+ * 电脑的同名账号,Agent 实际在另一台电脑)。
+ */
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatProviderAccountLabel,
+ resolveSessionUsageAccount,
+} from '@/session/sessionUsageAccount';
+
+describe('resolveSessionUsageAccount', () => {
+ it('Agent 就在被控电脑上:读被控电脑', () => {
+ expect(
+ resolveSessionUsageAccount({ agentDeviceId: null, providerId: 'anthropic', sharedTaskGuest: false }),
+ ).toEqual({ kind: 'host' });
+ });
+
+ it('Agent 在同账号另一台电脑:读那台', () => {
+ expect(
+ resolveSessionUsageAccount({
+ agentDeviceId: 'device-agent',
+ providerId: 'anthropic',
+ sharedTaskGuest: false,
+ }),
+ ).toEqual({ kind: 'device', deviceId: 'device-agent' });
+ });
+
+ it('分享来的供应商、共享任务访客、没指定来源:读不到', () => {
+ expect(
+ resolveSessionUsageAccount({
+ agentDeviceId: 'share:share-1',
+ providerId: 'anthropic',
+ sharedTaskGuest: false,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ expect(
+ resolveSessionUsageAccount({
+ agentDeviceId: 'device-owner-other',
+ providerId: 'anthropic',
+ sharedTaskGuest: true,
+ }),
+ ).toEqual({ kind: 'unreadable' });
+ expect(
+ resolveSessionUsageAccount({ agentDeviceId: 'device-agent', providerId: ' ', sharedTaskGuest: false }),
+ ).toEqual({ kind: 'unreadable' });
+ });
+
+ it('SSH 远程工作区忽略残留的 agentDeviceId(与电脑端同口径)', () => {
+ expect(
+ resolveSessionUsageAccount({
+ agentDeviceId: 'device-agent',
+ providerId: 'anthropic',
+ sharedTaskGuest: false,
+ remoteHostId: 'ssh-host',
+ }),
+ ).toEqual({ kind: 'host' });
+ });
+});
+
+describe('formatProviderAccountLabel', () => {
+ it('来源名后接登录身份,名称里已含身份时不重复', () => {
+ expect(
+ formatProviderAccountLabel({
+ name: 'Claude',
+ subscriptionAccount: { source: 'oauth', identity: '[email protected]' },
+ }),
+ ).toBe('Claude · [email protected]');
+ expect(
+ formatProviderAccountLabel({
+ name: 'ChatGPT [email protected]',
+ openAiAccount: { source: 'oauth', identity: '[email protected]' },
+ }),
+ ).toBe('ChatGPT [email protected]');
+ expect(formatProviderAccountLabel(undefined)).toBeUndefined();
+ });
+});
diff --git a/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx b/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
index b81a5b0fda..4124f927e9 100644
--- a/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
+++ b/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
@@ -246,3 +246,62 @@ describe("menu usage refresh lifecycle", () => {
expect(h.value.loading).toBe(false);
});
});
+
+// 远程 Agent:Agent 在另一台电脑上用那台的登录运行,账号余量读那台;任务价值仍读被控电脑。
+describe("menu usage with a remote Agent account", () => {
+ async function renderWith(
+ host: SessionMenuUsageReader,
+ accountReader: SessionMenuUsageReader | null,
+ task: RemoteSession,
+ ) {
+ let value!: ReturnType<typeof useSessionMenuUsage>;
+ function Probe() {
+ value = useSessionMenuUsage(task, host, true, null, undefined, accountReader);
+ return null;
+ }
+ root = createRoot(document.createElement("div"));
+ await act(async () => root!.render(createElement(Probe)));
+ return () => value;
+ }
+
+ it("reads the account from the Agent's computer and the task value from the host", async () => {
+ const host = reader();
+ const agent = reader();
+ vi.mocked(agent.getSubscriptionUsage).mockResolvedValue({
+ subscriptionType: "max",
+ fiveHour: { utilization: 12 },
+ });
+ const task = {
+ ...session("a"),
+ agentKind: "cc",
+ model: "claude-fable-5",
+ providerId: "anthropic",
+ agentDeviceId: "device-agent",
+ } as RemoteSession;
+ const value = await renderWith(host, agent, task);
+ expect(value().account?.source).toBe("claude");
+ expect(value().account?.windows[0]?.remainingPercent).toBe(88);
+ expect(value().estimate?.amount).toBe(12);
+ expect(agent.getSubscriptionUsage).toHaveBeenCalledWith("claude", "anthropic");
+ expect(host.getSubscriptionUsage).not.toHaveBeenCalled();
+ expect(host.getSessionEstimatedValue).toHaveBeenCalledWith("a");
+ expect(agent.getSessionEstimatedValue).not.toHaveBeenCalled();
+ });
+
+ it("shows an unreadable account as unavailable without borrowing the host's account", async () => {
+ const host = reader();
+ const task = {
+ ...session("a"),
+ agentKind: "cc",
+ model: "claude-fable-5",
+ providerId: "anthropic",
+ agentDeviceId: "share:share-1",
+ } as RemoteSession;
+ const value = await renderWith(host, null, task);
+ expect(value().account?.source).toBe("unavailable");
+ expect(value().account?.windows).toEqual([]);
+ expect(value().estimate?.amount).toBe(12);
+ expect(host.getSubscriptionUsage).not.toHaveBeenCalled();
+ expect(host.getCodexRateLimits).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsx
index 8074e1ccc7..1fedf9c9da 100644
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@ -66,7 +66,11 @@ import {
summarizeCodexRateLimitReset,
summarizeContextUsage,
} from '@/session/sessionControls';
-import { useSessionMenuUsage, type SessionMenuUsageReader } from '@/session/useSessionMenuUsage';
+import {
+ useSessionMenuUsage,
+ type SessionMenuAccountReader,
+ type SessionMenuUsageReader,
+} from '@/session/useSessionMenuUsage';
import { useSessionMenuContextUsage } from '@/session/useSessionMenuContextUsage';
import { SessionUsageSummary } from '@/session/SessionUsageSummary';
import {
@@ -119,6 +123,11 @@ export interface SessionMenuSheetProps {
onOpenSearch?: () => void;
accountProvider?: OpenAiAccountProvider;
usageReader: SessionMenuUsageReader & Pick<MobileMakerTransport, 'getContextUsage'>;
+ /**
+ * 账号余量从哪台电脑读(远程 Agent 时是 Agent 所在那台,见 sessionUsageAccount)。缺省 = usageReader
+ * (被控电脑);null = 读不到那份账号,只显示任务价值。
+ */
+ accountUsageReader?: SessionMenuAccountReader | null;
visible: boolean;
/** 打开时落在哪个视图(header 用量入口可直达 info)。 */
initialView: SessionMenuView;
@@ -169,6 +178,7 @@ export function SessionMenuSheet({
messageOnly = false,
onOpenSearch,
usageReader,
+ accountUsageReader = usageReader,
accountProvider,
visible,
initialView,
@@ -202,7 +212,14 @@ export function SessionMenuSheet({
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
- const menuUsage = useSessionMenuUsage(session, usageReader, visible && !messageOnly, codexRateLimits, accountProvider);
+ const menuUsage = useSessionMenuUsage(
+ session,
+ usageReader,
+ visible && !messageOnly,
+ codexRateLimits,
+ accountProvider,
+ accountUsageReader,
+ );
const { height: windowHeight } = useWindowDimensions();
const insets = useSafeAreaInsets();
diff --git a/apps/mobile/src/session/readSessionMenuAccountUsage.ts b/apps/mobile/src/session/readSessionMenuAccountUsage.ts
index 2005bb95c1..652336b35f 100644
--- a/apps/mobile/src/session/readSessionMenuAccountUsage.ts
+++ b/apps/mobile/src/session/readSessionMenuAccountUsage.ts
@@ -74,6 +74,10 @@ const empty = (
windows: [],
amounts: [],
});
+/** An account this device cannot read (e.g. a provider shared by another account). */
+export function unavailableSessionMenuAccountUsage(): SessionMenuAccountUsage {
+ return empty("unavailable");
+}
const finite = (value: unknown): value is number =>
typeof value === "number" && Number.isFinite(value);
const record = (value: unknown): Record<string, unknown> =>
diff --git a/apps/mobile/src/session/sessionUsageAccount.ts b/apps/mobile/src/session/sessionUsageAccount.ts
new file mode 100644
index 0000000000..5bddf50423
--- /dev/null
+++ b/apps/mobile/src/session/sessionUsageAccount.ts
@@ -0,0 +1,47 @@
+/**
+ * 任务菜单的账号余量读哪台电脑(与桌面 apps/desktop/src/renderer/lib/usageAccountLocation.ts 同口径)。
+ *
+ * 远程 Agent 让 Agent 在另一台电脑上用那台的登录与供应商发模型请求,余量事实也只在那台。被控电脑上
+ * 同名的账号与这一轮无关,不能拿来展示。任务价值、上下文等任务数据仍在被控电脑上读。
+ */
+import type { ProviderView } from '@cindy/model-providers/registry';
+
+import { isProviderShareAgentDeviceId } from './remoteAgentCatalogs';
+
+export type SessionUsageAccount =
+ /** Agent 就在被控电脑上:读被控电脑(原有行为)。 */
+ | { kind: 'host' }
+ /** Agent 在同账号的另一台电脑:手机直接经 device-link 读那台(与读它的模型目录同一条路)。 */
+ | { kind: 'device'; deviceId: string }
+ /**
+ * 读不到那份账号:别人分享的供应商(分享者的余量不对外开放)、共享任务访客(Agent 在任务主人的
+ * 其他电脑上),或没指定来源(那台按自己的默认规则挑,无从得知用的哪个账号)。只显示任务价值。
+ */
+ | { kind: 'unreadable' };
+
+export function resolveSessionUsageAccount(input: {
+ /** Agent 现在所在的电脑(null = 被控电脑本身)。 */
+ agentDeviceId: string | null;
+ providerId: string | null | undefined;
+ /** 任务属于别人账号的共享任务(手机是访客)。 */
+ sharedTaskGuest: boolean;
+ /** SSH 远程工作区:Agent 跑在远端主机上,与电脑端同口径忽略残留的 agentDeviceId。 */
+ remoteHostId?: string | null;
+}): SessionUsageAccount {
+ const agent = input.agentDeviceId;
+ if (!agent || input.remoteHostId?.trim()) return { kind: 'host' };
+ if (isProviderShareAgentDeviceId(agent) || input.sharedTaskGuest || !input.providerId?.trim()) {
+ return { kind: 'unreadable' };
+ }
+ return { kind: 'device', deviceId: agent };
+}
+
+/** 用量卡上的来源名:名称后接登录身份(名称里已含身份时不重复)。 */
+export function formatProviderAccountLabel(
+ provider: Pick<ProviderView, 'name' | 'openAiAccount' | 'subscriptionAccount'> | undefined,
+): string | undefined {
+ const identity = provider?.openAiAccount?.identity?.trim()
+ || provider?.subscriptionAccount?.identity?.trim();
+ const name = provider?.name?.trim();
+ return name && identity && !name.includes(identity) ? `${name} · ${identity}` : name;
+}
diff --git a/apps/mobile/src/session/useSessionMenuUsage.ts b/apps/mobile/src/session/useSessionMenuUsage.ts
index a384373a22..6c6fb0f179 100644
--- a/apps/mobile/src/session/useSessionMenuUsage.ts
+++ b/apps/mobile/src/session/useSessionMenuUsage.ts
@@ -5,6 +5,7 @@ import { normalizeRemoteMoney, type RemoteMoney } from "@/session/remoteMoney";
import type { RemoteSession } from "@/session/types";
import {
readSessionMenuAccountUsage,
+ unavailableSessionMenuAccountUsage,
type SessionMenuAccountUsage,
} from "./readSessionMenuAccountUsage";
import {
@@ -12,14 +13,19 @@ import {
type MobileCodexRateLimitsResult,
} from "@cindy/maker-shared/device-link-contract";
-export type SessionMenuUsageReader = Pick<
+/**
+ * Reads of the account this task's Agent consumes. With a remote Agent it is another computer
+ * than the task host (see sessionUsageAccount.ts); task data is still read from the host.
+ */
+export type SessionMenuAccountReader = Pick<
MobileMakerTransport,
- | "getSessionEstimatedValue"
| "getCodexRateLimits"
| "getAccountUsage"
| "getSubscriptionUsage"
| "getClaudeSessionRoute"
>;
+export type SessionMenuUsageReader = SessionMenuAccountReader &
+ Pick<MobileMakerTransport, "getSessionEstimatedValue">;
interface UsageState {
account: SessionMenuAccountUsage | null;
@@ -45,6 +51,8 @@ export function sessionMenuUsageScope(session: RemoteSession): string {
session.providerId,
session.agentKind,
session.remoteHostId,
+ // A remote Agent consumes the account of the computer it runs on; moving it changes owner.
+ session.agentDeviceId,
session.clearedAt,
session.runtimeGeneration,
].join("\0");
@@ -57,6 +65,8 @@ export function useSessionMenuUsage(
visible: boolean,
codexRateLimits: MobileCodexRateLimitsResult | null = null,
provider?: OpenAiAccountProvider,
+ /** Defaults to the task host; null = this account cannot be read from here (shown unavailable). */
+ accountReader: SessionMenuAccountReader | null = reader,
) {
const taskScope = [
session.deviceLinkDeviceId,
@@ -101,7 +111,10 @@ export function useSessionMenuUsage(
inFlight = true;
update({ loading: true });
await Promise.allSettled([
- readSessionMenuAccountUsage(session, reader, provider).then(
+ (accountReader
+ ? readSessionMenuAccountUsage(session, accountReader, provider)
+ : Promise.resolve(unavailableSessionMenuAccountUsage())
+ ).then(
(account) => update({ account, accountFailed: false }),
(error) =>
update({
@@ -146,6 +159,7 @@ export function useSessionMenuUsage(
scope,
taskScope,
reader,
+ accountReader,
visible,
refreshKey,
session.id,
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1cc7a31556..144a0abd62 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -577,6 +577,12 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
`agentDeviceId`(与桌面新建同一参数,A 已接受);只有 A 的 `maker:provider:list` 带 `remoteInvocationEnabled`
布尔标记时才提供(该标记与远程 Agent 同一版加入,旧 A 不列)。手机不按 A 的目录与登录校准这份选择,由运行 Agent
的那台在首条消息时核对;协同草稿与之互斥。
+- **账号余量**(2026-10-09):这一轮消耗的是 Agent 所在那台(B)的账号,桌面底部用量 chip 与手机任务菜单都改读 B 的
+ 余量,不读任务所在电脑(本机或被控电脑)的同名账号。直接经 device-link 调 B 已有的 `maker:usage:*` 读取与推送
+ (与模型选择器读 B 的余量同一份镜像),不新增 channel;任务价值与上下文仍读任务所在电脑。远程控制的任务把 Agent
+ 放在第三台电脑时读第三台,放在控制端自己时读本机;挂着换位置意图时桌面 chip 按意图里的电脑显示。分享来的供应商、
+ 共享任务访客与没指定来源的远程 Agent 读不到那份账号,只显示任务价值。桌面判定见
+ `apps/desktop/src/renderer/lib/usageAccountLocation.ts`,手机见 `apps/mobile/src/session/sessionUsageAccount.ts`。
- **供应商分享(另一个账号用 B 的供应商)**:契约见 `docs/provider-sharing-contract.md`,产品规则见
`docs/product-rules/provider-sharing.md`。relay 新增 `Envelope.providerShare` 范围与能力 `provider-share-v1`
(`packages/device-link-protocol/src/providerShare.ts`,两仓同文件),与 `sharedTask` 并列、同一帧不能同时带两种范围;