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(device-link): 修复远程 session 剩余用量显示 (#3789)

FicoWangd7c7da1c087b
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index e91f25d288..b5544a5fef 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -32,6 +32,8 @@ import {
markRemoteSettingPersistedInsideHandler,
runInvoke,
setRemoteReviewInputGuard,
+ setRemoteClaudeSubscriptionUsageReader,
+ setRemoteXaiSubscriptionUsageReader,
setRemoteWorkingDirGuard,
setRemoteSettingsPersist,
handleControllerOffline,
@@ -2749,3 +2751,31 @@ describe('远程 set-* 持久化回流', () => {
expect(r).toMatchObject({ ok: true });
});
});
+
+
+describe('remote subscription data reads', () => {
+ it.each([
+ ['maker:usage:claude-subscription', setRemoteClaudeSubscriptionUsageReader],
+ ['maker:usage:xai-subscription', setRemoteXaiSubscriptionUsageReader],
+ ] as const)('%s uses the local reader with the selected account after authorization', async (channel, setReader) => {
+ const reader = vi.fn(async () => ({ fiveHour: { utilization: 12 } }));
+ const ipcHandler = vi.fn(() => { throw new Error('Untrusted synthetic sender'); });
+ registry.register(channel, ipcHandler);
+ setReader(reader);
+ await expect(runInvoke('ctrl', { channel, args: ['account-2'] })).resolves.toEqual({
+ ok: true, result: { providerId: 'account-2', fiveHour: { utilization: 12 } },
+ });
+ expect(reader).toHaveBeenCalledWith('account-2');
+ expect(ipcHandler).not.toHaveBeenCalled();
+ reader.mockClear();
+ await expect(runInvoke('ctrl', { channel, args: [42] })).resolves.toMatchObject({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('[INVALID_PARAMS]') } });
+ expect(reader).not.toHaveBeenCalled();
+ remoteControlEnabled = false;
+ await expect(runInvoke('ctrl', { channel, args: ['account-2'] })).resolves.toMatchObject({ ok: false, error: { code: 'REMOTE_DISABLED' } });
+ expect(reader).not.toHaveBeenCalled();
+ remoteControlEnabled = true;
+ revokedControllers = ['ctrl'];
+ await expect(runInvoke('ctrl', { channel, args: ['account-2'] })).resolves.toMatchObject({ ok: false, error: { code: 'ACCESS_REVOKED' } });
+ expect(reader).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts
index a3ae0408b7..3ffe75fcf9 100644
--- a/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts
+++ b/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts
@@ -10,11 +10,15 @@ const mocks = vi.hoisted(() => ({
queryOne: vi.fn(),
exec: vi.fn(async () => undefined),
getCurrentDbClientUserId: vi.fn(() => 'user-1'),
+ tapWindowBroadcast: vi.fn(),
}));
vi.mock('electron', () => ({
BrowserWindow: { getAllWindows: () => [] },
}));
+vi.mock('../device-link/broadcast-tap.js', () => ({
+ tapWindowBroadcast: mocks.tapWindowBroadcast,
+}));
vi.mock('../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
@@ -43,6 +47,7 @@ describe('claude subscription snapshot hydration race', () => {
mocks.queryOne.mockReset();
mocks.exec.mockReset().mockResolvedValue(undefined);
mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
+ mocks.tapWindowBroadcast.mockReset();
});
it('does not drop the very first snapshot after main start (owner init is not invalidation)', async () => {
@@ -268,4 +273,94 @@ describe('claude subscription snapshot hydration race', () => {
const current = await broadcaster.readClaudeSubscriptionUsageSnapshot();
expect(current).toBeNull();
});
+
+ it('taps record and clear broadcasts for device-link forwarding (merged snapshot / null)', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ mocks.queryOne.mockResolvedValue(null);
+
+ await broadcaster.recordClaudeSubscriptionUsageSnapshot({
+ fiveHour: { utilization: 10 }, source: 'unified-headers', updatedAt: 1,
+ });
+ const tapped = mocks.tapWindowBroadcast.mock.calls.find(
+ ([channel]) => channel === 'usage:claude-subscription-changed',
+ );
+ expect(tapped?.[1]).toMatchObject({ fiveHour: { utilization: 10 } });
+
+ mocks.tapWindowBroadcast.mockClear();
+ await broadcaster.clearClaudeSubscriptionUsageSnapshot();
+ // 登出 / 换号清除也要同步到控制端(null 让远程 chip 回占位态)。
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith(
+ 'usage:claude-subscription-changed',
+ null,
+ );
+ });
+
+ it('taps codex account broadcasts with the authoritative combined payload', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ mocks.queryOne.mockResolvedValue(null);
+
+ await broadcaster.recordCodexAccountUsageSnapshot({
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 3, windowMinutes: 10_080 },
+ });
+
+ const tapped = mocks.tapWindowBroadcast.mock.calls.find(
+ ([channel]) => channel === 'usage:codex-account-changed',
+ );
+ // 转发的是组合 payload(远程镜像按整帧替换消费)。
+ expect(tapped?.[1]).toMatchObject({ limitId: 'codex' });
+ });
+
+ it('taps xai rate-limit record and clear broadcasts', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+
+ broadcaster.recordXaiRateLimitSnapshot({ source: 'cli-chat-proxy' } as never);
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith(
+ 'usage:xai-rate-limit-changed',
+ expect.objectContaining({ updatedAt: expect.any(Number) }),
+ );
+
+ mocks.tapWindowBroadcast.mockClear();
+ broadcaster.clearXaiRateLimitSnapshot();
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith('usage:xai-rate-limit-changed', null);
+ });
+
+ // MagicLizi P1 (#3789): independent xAI accounts must never write into or clear the builtin
+ // remote mirror; they forward on the provider-scoped channel like Codex named accounts.
+ it('keeps independent xAI account rate-limit record and clear off the builtin channel', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ mocks.tapWindowBroadcast.mockClear();
+
+ broadcaster.recordXaiRateLimitSnapshot({ source: 'cli-chat-proxy' } as never, 'xai-second');
+ expect(mocks.tapWindowBroadcast).not.toHaveBeenCalledWith('usage:xai-rate-limit-changed', expect.anything());
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith(
+ 'usage:xai-provider-rate-limit-changed',
+ { providerId: 'xai-second', snapshot: expect.objectContaining({ updatedAt: expect.any(Number) }) },
+ );
+
+ mocks.tapWindowBroadcast.mockClear();
+ broadcaster.clearXaiRateLimitSnapshot('xai-second');
+ expect(mocks.tapWindowBroadcast).not.toHaveBeenCalledWith('usage:xai-rate-limit-changed', expect.anything());
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith(
+ 'usage:xai-provider-rate-limit-changed',
+ { providerId: 'xai-second', snapshot: null },
+ );
+ });
+});
+
+
+it('keeps named Codex and subscription pushes in their provider-scoped channels', async () => {
+ vi.resetModules();
+ mocks.tapWindowBroadcast.mockClear();
+ mocks.queryOne.mockResolvedValue(null);
+ const broadcaster = await import('../usageBroadcaster');
+ await broadcaster.recordCodexAccountUsageSnapshot({ source: 'codex-app-server',
+ primary: { usedPercent: 70 } }, 'second-account');
+ expect(mocks.tapWindowBroadcast).not.toHaveBeenCalledWith('usage:codex-account-changed', expect.anything());
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith('usage:codex-provider-account-changed',
+ expect.objectContaining({ providerId: 'second-account', snapshot: expect.objectContaining({ primary: { usedPercent: 70 } }) }));
+ broadcaster.broadcastSubscriptionAccountUsage('claude-2', null);
+ expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith('usage:subscription-provider-account-changed',
+ { providerId: 'claude-2', snapshot: null });
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 1bb20105f1..504f79cbea 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -72,6 +72,7 @@ import {
} from './mainWindowMaximizeRecovery';
import { prewarmMacComputerPermissionGuideHelper } from './computer-permission-guide/MacComputerPermissionGuideNativeHost.js';
import { handleOpenChatGPTApp } from './chatgpt-app.js';
+import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
import {
waitForTurnChangeSetActions,
waitForTurnChangeSetPersistence,
@@ -4834,6 +4835,9 @@ const registerIpcHandlers = () => {
/* no-op */
}
}
+ // device-link:payload 顶层 sessionId → session:<id> topic,打开该远程会话的
+ // 控制端据此实时切换订阅 / 网关显示形态(每会话生命周期通常仅一次,极低频)。
+ tapWindowBroadcast(MAKER_PUSH.CLAUDE_SESSION_ROUTE_CHANGED, { sessionId, route });
});
// ── 本机 Claude Code 订阅:只管理 Cindy 的使用许可 ─────────────────────────
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 21f68385d9..09d41a7781 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -290,6 +290,26 @@ export function setRemoteReviewInputGuard(guard: RemoteReviewInputGuard | null):
remoteReviewInputGuard = guard;
}
+/**
+ * xAI 订阅余量读取器(register.ts 在 usage 面就绪后注入)。该 channel 的 ipcMain
+ * handler 挂了 assertTrustedSender(合成 event 必然不可信,那道闸不为远程放宽),
+ * 与 telegram:* 同先例由 dispatch 拦截直读;走注入而非静态 import —— dispatch 的
+ * 模块图保持纯净(usage 面会拖进 runtime-configs 等 app 依赖,纯 dispatch 单测只
+ * mock 极小 Electron 面)。
+ */
+type RemoteSubscriptionUsageReader = (providerId?: string) => Promise<unknown | null>;
+let remoteXaiSubscriptionUsageReader: RemoteSubscriptionUsageReader | null = null;
+let remoteClaudeSubscriptionUsageReader: RemoteSubscriptionUsageReader | null = null;
+export function setRemoteClaudeSubscriptionUsageReader(reader: RemoteSubscriptionUsageReader | null): void {
+ remoteClaudeSubscriptionUsageReader = reader;
+}
+
+export function setRemoteXaiSubscriptionUsageReader(
+ reader: RemoteSubscriptionUsageReader | null,
+): void {
+ remoteXaiSubscriptionUsageReader = reader;
+}
+
/** 从 args[0] 里取待收敛的路径字段(见 PATH_GUARDED_CHANNELS);取不到返回 null。 */
function extractGuardedPath(args: unknown[], field: 'workingDir' | 'baseRepo'): string | null {
const o = args[0];
@@ -3447,6 +3467,32 @@ export async function runInvoke(
// assertTrustedAppRendererEvent, 合成 event 必然不可信 —— 那道闸不该为远程下线
// 放宽), 故在此拦截。已过三道 gate, 等同受信本地访问。只切轮询、不碰凭证:
// 远程能让它停收消息, 但拿不走也删不掉绑定(解绑仍只能本机操作)。
+ // Subscription IPC validates local senders (Claude for named accounts, xAI always).
+ // Keep that check; authorized device-link reads use the same injected data readers.
+ // 直读注入的 usage reader(cached-first,只读快照,无副作用)。已过三道 gate。
+ if (payload.channel === 'maker:usage:xai-subscription' || payload.channel === 'maker:usage:claude-subscription') {
+ const reader = payload.channel === 'maker:usage:xai-subscription'
+ ? remoteXaiSubscriptionUsageReader : remoteClaudeSubscriptionUsageReader;
+ const providerId = (payload.args ?? [])[0];
+ if (providerId !== undefined && (typeof providerId !== 'string' || providerId.trim().length === 0)) {
+ return { ok: false, error: { code: 'IPC_ERROR', message: '[INVALID_PARAMS] providerId must be a non-empty string' } };
+ }
+ if (!reader) {
+ // usage 面尚未注入(启动窗口):非 CHANNEL_NOT_ALLOWED —— 控制端不得据此
+ // 进入「老被控端」负缓存,保留现值稍后重试即可。
+ return { ok: false, error: { code: 'IPC_ERROR', message: 'subscription usage reader not ready' } };
+ }
+ try {
+ const snapshot = await reader(providerId as string | undefined);
+ const result = snapshot && providerId ? { ...snapshot as object, providerId } : snapshot;
+ return { ok: true, result };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.warn(`subscription usage read failed from ${shortId(src)}: ${message}`);
+ return { ok: false, error: { code: 'IPC_ERROR', message } };
+ }
+ }
+
if (payload.channel === DL_TELEGRAM_STATUS_CHANNEL) {
return { ok: true, result: readTelegramRemoteStatus() };
}
@@ -3692,6 +3738,8 @@ export const __testing = {
setBroadcastTapListener(null);
presenceOfflineCheck = null;
remoteReviewInputGuard = null;
+ remoteXaiSubscriptionUsageReader = null;
+ remoteClaudeSubscriptionUsageReader = null;
},
getActiveControllers,
getUpdateRelaunchControllers,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 04e5088e35..528fb4365a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -576,7 +576,7 @@ import {
issuePiPackageMutationGrant,
piPackageMutationNeedsGrant,
} from '../maker-host/pi-package-mutation-grant.js';
-
+import { readXaiSubscriptionUsageSnapshotForDeviceLink, readClaudeSubscriptionUsageSnapshotForDeviceLink } from './usage.js';
import { requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';
import { applyPersistedCindyMakeMarker } from './cindyMakeSessionStart.js';
import { CINDY_MAKE_SESSION_SOURCE } from '../../shared/cindyMakeSession.js';
@@ -1001,6 +1001,8 @@ import {
setRemoteReviewInputGuard as setDeviceLinkRemoteReviewInputGuard,
setRemoteWorkingDirGuard as setDeviceLinkRemoteWorkingDirGuard,
setRemoteSettingsPersist as setDeviceLinkRemoteSettingsPersist,
+ setRemoteXaiSubscriptionUsageReader as setDeviceLinkRemoteXaiSubscriptionUsageReader,
+ setRemoteClaudeSubscriptionUsageReader as setDeviceLinkRemoteClaudeSubscriptionUsageReader,
} from '../device-link/dispatch.js';
import {
deviceLinkInvokeControllerSupports,
@@ -4762,6 +4764,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 必须是本机当前可访问的目录,挡掉控制端用任意路径越权起进程或执行 git。
setDeviceLinkRemoteWorkingDirGuard(checkRemoteWorkingDir);
setDeviceLinkRemoteReviewInputGuard(assertReviewExternalInputAllowed);
+ // 远程 xAI 订阅余量只读:该 channel 的 ipcMain handler 挂 assertTrustedSender,
+ // device-link 由 dispatch 拦截直读注入的 reader(见 dispatch.ts 同名 setter 注释)。
+ setDeviceLinkRemoteXaiSubscriptionUsageReader(readXaiSubscriptionUsageSnapshotForDeviceLink);
+ setDeviceLinkRemoteClaudeSubscriptionUsageReader(readClaudeSubscriptionUsageSnapshotForDeviceLink);
// device-link 远程 set-* 持久化回流:effort/permission/fastMode/extraDirs 等
// runtime-only handler 经这个注入写被控端 DB + 广播 patched。SET_MODEL 是例外:
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index 01fc326b47..33fe45f3d3 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -6,6 +6,7 @@
* handler 时拉起 Electron / runtime config 副作用。
*/
+import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage.js';
import { scryptSync } from 'node:crypto';
import { readSubscriptionAccountUsage, triggerSubscriptionAccountUsage, syncSubscriptionAccountUsage, setSubscriptionAccountUsageBroadcaster } from '../usage/subscriptionAccountUsage.js';
import { broadcastSubscriptionAccountUsage, clearXaiRateLimitSnapshot } from '../usageBroadcaster.js';
@@ -221,6 +222,25 @@ export function triggerXaiSubscriptionUsageRefresh(providerId?: string): void {
xaiSubscriptionUsageReader.triggerRefresh();
}
+/**
+ * device-link dispatch 专用的 xAI 订阅余量读取出口。ipcMain 面的
+ * USAGE_XAI_SUBSCRIPTION 挂了 assertTrustedSender(合成 event 必然不可信,那道闸
+ * 不为远程放宽)—— 与 device-link:telegram:* 同先例,被控端 dispatch 过三道 gate
+ * (被控开关 + 撤销黑名单 + allowlist)后直读本函数,不进 ipcMain。cached-first,
+ * 与本机 renderer 读到的快照同形。
+ */
+export async function readXaiSubscriptionUsageSnapshotForDeviceLink(providerId?: string): Promise<XaiSubscriptionUsageSnapshot | null> {
+ if (!providerId || providerId === 'xai') return xaiSubscriptionUsageReader.read();
+ if (subscriptionAccountKind(providerId) !== 'xai') return null;
+ return await readSubscriptionAccountUsage(providerId) as XaiSubscriptionUsageSnapshot | null;
+}
+
+export async function readClaudeSubscriptionUsageSnapshotForDeviceLink(providerId?: string): Promise<import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot | null> {
+ if (!providerId || providerId === 'anthropic') return claudeSubscriptionUsageReader.read();
+ if (subscriptionAccountKind(providerId) !== 'claude') return null;
+ return await readSubscriptionAccountUsage(providerId) as import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot | null;
+}
+
/** SuperGrok 登录 / 登出 / 换号后强制同步(先清再拉)。调用方应 await 后再广播连接态。 */
export function syncXaiSubscriptionUsageForAuthChange(providerId?: string): Promise<void> {
if (providerId && providerId !== 'xai') return syncSubscriptionAccountUsage(providerId);
@@ -332,16 +352,8 @@ export function registerMakerUsageIpc(maker: Maker): void {
return { ...result, providerId: providerId ?? 'openai',
rateLimits: result.rateLimits ? { ...result.rateLimits, providerId: providerId ?? 'openai' } : null };
},
- readClaudeSubscriptionUsageSnapshot: async (providerId) => {
- if (!providerId || providerId === 'anthropic') return claudeSubscriptionUsageReader.read();
- if (subscriptionAccountKind(providerId) !== 'claude') return null;
- return await readSubscriptionAccountUsage(providerId) as import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot | null;
- },
- readXaiSubscriptionUsageSnapshot: async (providerId) => {
- if (!providerId || providerId === 'xai') return xaiSubscriptionUsageReader.read();
- if (subscriptionAccountKind(providerId) !== 'xai') return null;
- return await readSubscriptionAccountUsage(providerId) as import('../../shared/xaiSubscriptionUsage.js').XaiSubscriptionUsageSnapshot | null;
- },
+ readClaudeSubscriptionUsageSnapshot: readClaudeSubscriptionUsageSnapshotForDeviceLink,
+ readXaiSubscriptionUsageSnapshot: readXaiSubscriptionUsageSnapshotForDeviceLink,
assertTrustedSender: (event) => {
assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
},
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 198fc37c38..43f26d7bd0 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -44,6 +44,7 @@ import { BrowserWindow } from 'electron';
import type { MoneyCurrency } from '../../shared/regionalMoney';
import { getAuthState } from '../authManager';
+import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';
import { createLogger } from '../logger';
import { readClaudeApiKey } from '../maker-host/auth-adapters';
import { outboundFetch } from '../maker-host/outbound-fetch';
@@ -307,4 +308,7 @@ function broadcast(payload: ClaudeAccountUsageSnapshot): void {
win.webContents.send(USAGE_CLAUDE_ACCOUNT_CHANGED, payload);
}
}
+ // device-link:控制端远程网关形态会话 chip 镜像被控端 daily/monthly 配额
+ // (刷新自带 10s 节流 + turn-done 触发,低频;无 active 链路时 O(1) no-op)。
+ tapWindowBroadcast(USAGE_CLAUDE_ACCOUNT_CHANGED, payload);
}
diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.ts
index e28864e6c2..9d863131bd 100644
--- a/apps/desktop/src/main/usageBroadcaster.ts
+++ b/apps/desktop/src/main/usageBroadcaster.ts
@@ -43,6 +43,7 @@ import {
} from '@cindy/maker-shared/codex-usage-buckets';
import { createLogger } from './logger';
+import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
import type { RegionalMoney } from '../shared/regionalMoney.js';
const log = createLogger('usageBroadcaster');
@@ -55,6 +56,8 @@ export const USAGE_TODAY_TOKENS_CHANGED = 'usage:today-tokens-changed';
export const USAGE_CODEX_ACCOUNT_CHANGED = 'usage:codex-account-changed';
/** IPC channel: main → renderer 推 xAI(SuperGrok bridge)上游限流快照变化。 */
export const USAGE_XAI_RATE_LIMIT_CHANGED = 'usage:xai-rate-limit-changed';
+/** 独立 xAI 账号(providerId ≠ 'xai')的限流头推送:{ providerId, snapshot },与本机 hook 同形。 */
+export const USAGE_XAI_PROVIDER_RATE_LIMIT_CHANGED = 'usage:xai-provider-rate-limit-changed';
/** IPC channel: main → renderer 推 Claude 订阅账号余量变化 (端点刷新 / headers 旁路)。 */
export const USAGE_CLAUDE_SUBSCRIPTION_CHANGED = 'usage:claude-subscription-changed';
/** IPC channel: main → renderer 推 SuperGrok 账号周用量快照。 */
@@ -798,9 +801,13 @@ export function recordXaiRateLimitSnapshot(info: Omit<XaiRateLimitSnapshot, 'upd
for (const win of BrowserWindow.getAllWindows()) {
if (isTrustedAppRendererWindow(win)) {
if (providerId === 'xai') win.webContents.send(USAGE_XAI_RATE_LIMIT_CHANGED, snapshot);
- else win.webContents.send('usage:xai-provider-rate-limit-changed', { providerId, snapshot });
+ else win.webContents.send(USAGE_XAI_PROVIDER_RATE_LIMIT_CHANGED, { providerId, snapshot });
}
}
+ // device-link:tooltip 尽力显示被控端限流头(bridge 每成功请求至多一帧,低频)。
+ // 与 broadcastCodexAccountUsage 同口径按账号分路:独立账号绝不写进内置远程缓存。
+ if (providerId === 'xai') tapWindowBroadcast(USAGE_XAI_RATE_LIMIT_CHANGED, snapshot);
+ else tapWindowBroadcast(USAGE_XAI_PROVIDER_RATE_LIMIT_CHANGED, { providerId, snapshot });
}
/**
@@ -811,9 +818,13 @@ export function clearXaiRateLimitSnapshot(providerId = 'xai'): void {
for (const win of BrowserWindow.getAllWindows()) {
if (isTrustedAppRendererWindow(win)) {
if (providerId === 'xai') win.webContents.send(USAGE_XAI_RATE_LIMIT_CHANGED, null);
- else win.webContents.send('usage:xai-provider-rate-limit-changed', { providerId, snapshot: null });
+ else win.webContents.send(USAGE_XAI_PROVIDER_RATE_LIMIT_CHANGED, { providerId, snapshot: null });
}
}
+ // device-link:登出 / 换号清除同步给控制端(远程 tooltip 不得挂旧账号余量);
+ // 独立账号的清除只清它自己的镜像,不得清空仍登录的内置账号。
+ if (providerId === 'xai') tapWindowBroadcast(USAGE_XAI_RATE_LIMIT_CHANGED, null);
+ else tapWindowBroadcast(USAGE_XAI_PROVIDER_RATE_LIMIT_CHANGED, { providerId, snapshot: null });
}
@@ -1156,6 +1167,10 @@ function broadcastCodexAccountUsage(payload: RateLimitSnapshot | null, providerI
else win.webContents.send('usage:codex-provider-account-changed', { providerId, snapshot: payload });
}
}
+ // device-link:控制端远程 codex / chatgpt-bridge 会话 chip 镜像被控端限额窗口。
+ // 频率上限:app-server 每 turn 记录一次、WHAM 刷新 10s 节流;无链路时 O(1) no-op。
+ if (providerId === 'openai') tapWindowBroadcast(USAGE_CODEX_ACCOUNT_CHANGED, payload);
+ else tapWindowBroadcast('usage:codex-provider-account-changed', { providerId, snapshot: payload });
}
function broadcastClaudeSubscriptionUsage(payload: ClaudeSubscriptionUsageSnapshot | null): void {
@@ -1164,6 +1179,9 @@ function broadcastClaudeSubscriptionUsage(payload: ClaudeSubscriptionUsageSnapsh
win.webContents.send(USAGE_CLAUDE_SUBSCRIPTION_CHANGED, payload);
}
}
+ // device-link:控制端远程订阅会话的 chip 镜像被控端余量。频率上限由上游保证
+ // (headers 观察器签名去抖 + 端点 180s 节流),无 active 链路时 tap 是 O(1) no-op。
+ tapWindowBroadcast(USAGE_CLAUDE_SUBSCRIPTION_CHANGED, payload);
}
export function broadcastSubscriptionAccountUsage(providerId: string, snapshot: ClaudeSubscriptionUsageSnapshot | XaiSubscriptionUsageSnapshot | null): void {
@@ -1171,6 +1189,7 @@ export function broadcastSubscriptionAccountUsage(providerId: string, snapshot:
if (!isTrustedAppRendererWindow(win)) continue;
win.webContents.send('usage:subscription-provider-account-changed', { providerId, snapshot });
}
+ tapWindowBroadcast('usage:subscription-provider-account-changed', { providerId, snapshot });
}
function broadcastXaiSubscriptionUsage(payload: XaiSubscriptionUsageSnapshot | null): void {
@@ -1178,4 +1197,6 @@ function broadcastXaiSubscriptionUsage(payload: XaiSubscriptionUsageSnapshot | n
if (!isTrustedAppRendererWindow(win)) continue;
win.webContents.send(USAGE_XAI_SUBSCRIPTION_CHANGED, payload);
}
+ // device-link:控制端远程 xai 形态会话 chip 镜像被控端周用量(账号级,低频)。
+ tapWindowBroadcast(USAGE_XAI_SUBSCRIPTION_CHANGED, payload);
}
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index eee5e2653f..bbfc1c9afb 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -74,13 +74,36 @@ describe('TodaySpendChip dashboard routing', () => {
"vendorKey === 'cc' && !isRemoteClaudeSession && !isDeviceLinkRemote && providerId == null",
),
);
- // 订阅形态分类整体排除 device-link(专属分支接管渲染)
+ // 订阅形态分类的本机启发式整体排除 device-link;显式 anthropic / 被控端路由观察为
+ // 订阅的远程会话走被控端镜像快照(useRemoteClaudeSubscriptionUsage),不读本机账号状态。
expect(compact(source)).toContain(
- compact("const isClaudeSubscription = !isDeviceLinkRemote &&"),
+ compact("const isClaudeSubscription = isDeviceLinkRemoteClaudeSubscription || (!isDeviceLinkRemote &&"),
);
+ expect(compact(source)).toContain(compact('const isDeviceLinkRemoteClaudeSubscription ='));
+ expect(compact(source)).toContain(
+ compact('isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge ? (deviceLinkDeviceId ?? null) : null,'),
+ );
+ // 本机订阅快照 hook 对 device-link 关闭(两个 hook 的 enabled 互斥)
+ expect(compact(source)).toContain(
+ compact('isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote,'),
+ );
+ // 形态未解析(默认路由无观察值 / 老被控端)的远程会话走占位分支:估算价值 / 累计 cost
+ // 有哪个显哪个,不显示本机限额窗口;形态已解析的走对应形态分支,用被控端镜像渲染同一套卡片。
+ expect(compact(source)).toContain(compact('const deviceLinkRemoteFormResolved ='));
+ expect(compact(source)).toContain(
+ compact('if (isDeviceLinkRemote && !deviceLinkRemoteFormResolved) {'),
+ );
+ // 只有 SSH 远程(无镜像)不构建账号卡片;device-link 用镜像快照构建
+ expect(compact(source)).toContain(compact('if (!remoteHostId) {'));
+ expect(compact(source)).toContain(
+ compact('if (usesGatewayQuota || isDeviceLinkRemoteGateway) {'),
+ );
+ // cc 默认路由的远程形态判定只认被控端路由观察镜像,不做本机启发式。
+ expect(compact(source)).toContain(
+ compact('const remoteClaudeRoute = useRemoteClaudeSessionRoute('),
+ );
+ // #4197 多账号:本机 Claude 账号判定经 isClaudeAccount(providerId / auth.native),pi 与 codex 同口径
expect(compact(source)).toContain(compact("((vendorKey === 'pi' || vendorKey === 'codex') && !remoteHostId && isClaudeAccount)"));
- // 渲染走专属分支:估算价值 / 累计 cost 有哪个显哪个,不显示本机限额窗口
- expect(compact(source)).toContain(compact('if (isDeviceLinkRemote) {'));
// 看板链接对 device-link 落 null(额度属于被控端账号,本机浏览器打开的是控制端账号)
expect(source).toMatch(/usageDashboardUrl: string \| null = isDeviceLinkRemote\s*\?\s*null/);
});
@@ -193,15 +216,20 @@ describe('TodaySpendChip dashboard routing', () => {
// 悬念期催刷通道必须与 chip 显示的配额槽一致: bridge 形态催 WHAM; Codex CLI
// 形态显示 app-server 槽, WHAM 刷新帮不上它(靠 turn 事件 / 悬念超时兜底),
// 不得催 —— WHAM 桶与 CLI 配额可能不同(账号多限额桶, 2026-07-24 实报 bug)
+ expect(compact(source)).toContain(
+ compact('if (isChatgptBridge || (isDeviceLinkRemote && usesCodexQuotaForm)) {'),
+ );
+ expect(compact(source)).toContain(compact('requestCodexAccountRefresh(providerId ?? undefined);'));
+ expect(compact(source)).toContain(compact("requestXaiSubscriptionRefresh(providerId ?? 'xai');"));
+ // 悬念期催刷按会话来源分路:远程订阅会话催被控端(隧道,被控端节流兜底),
+ // 本机订阅会话催本机;不得拿本机通道替远程会话催刷(账号不同)。
expect(compact(source)).toContain(
compact(
- 'if (isChatgptBridge) {\n' +
- ' requestCodexAccountRefresh(providerId ?? undefined);\n' +
- ' } else if (usesXaiQuotaForm) {\n' +
- " requestXaiSubscriptionRefresh(providerId ?? 'xai');\n" +
- ' } else if (isClaudeSubscription && !usesCodexQuotaForm) {\n' +
- " requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');\n" +
- ' }',
+ 'if (isDeviceLinkRemoteClaudeSubscription && deviceLinkDeviceId) {\n' +
+ " requestRemoteClaudeSubscriptionRefresh(deviceLinkDeviceId, providerId ?? 'anthropic');\n" +
+ ' } else if (!isDeviceLinkRemote) {\n' +
+ " requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');\n" +
+ ' }',
),
);
expect(compact(source)).toContain(
diff --git a/apps/desktop/src/renderer/__tests__/useRemoteClaudeSubscriptionUsage.test.ts b/apps/desktop/src/renderer/__tests__/useRemoteClaudeSubscriptionUsage.test.ts
new file mode 100644
index 0000000000..86841442b9
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/useRemoteClaudeSubscriptionUsage.test.ts
@@ -0,0 +1,182 @@
+// @vitest-environment jsdom
+
+/**
+ * useRemoteClaudeSubscriptionUsage 单测。
+ *
+ * reduce 纯函数与本机版同一语义;行为用例覆盖两条 review 修复:
+ * - owner 栅栏:owner A 发起的隧道读在切到 owner B 后才 resolve → 整帧丢弃,
+ * module 缓存不得把 A 的余量顶给 B(缓存跨路由重挂载存活,组件卸载挡不住);
+ * - CHANNEL_NOT_ALLOWED 负缓存带 TTL:TTL 内不重复探测,到期后重新探测
+ * (被控端升级后同 deviceId 重连);收到该设备订阅 push 立即解除负缓存。
+ */
+
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { setDataOwnerGeneration } from '../contexts/dataOwnerGeneration';
+import {
+ reduceRemoteClaudeSubscriptionPush,
+ resetRemoteClaudeSubscriptionUsageCacheForTest,
+ useRemoteClaudeSubscriptionUsage,
+} from '../hooks/useRemoteClaudeSubscriptionUsage';
+
+type PushListener = (
+ push: { deviceId: string; channel: string; payload: unknown },
+ localOwnerStamp?: unknown,
+) => void;
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn<(deviceId: string, channel: string, args: unknown[]) => Promise<unknown>>(),
+ pushListeners: [] as PushListener[],
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (err: unknown) => void;
+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
+ return { promise, resolve, reject };
+}
+
+async function flushMicrotasks(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_788_300_000_000);
+ setDataOwnerGeneration('owner-a');
+ resetRemoteClaudeSubscriptionUsageCacheForTest();
+ mocks.invoke.mockReset();
+ mocks.pushListeners.length = 0;
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ deviceLink: {
+ invoke: mocks.invoke,
+ onRemotePush: (cb: PushListener) => {
+ mocks.pushListeners.push(cb);
+ return () => {
+ const i = mocks.pushListeners.indexOf(cb);
+ if (i >= 0) mocks.pushListeners.splice(i, 1);
+ };
+ },
+ },
+ },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('reduceRemoteClaudeSubscriptionPush', () => {
+ const current = { fiveHour: { utilization: 10 } };
+
+ it('clears on null broadcasts (controlled device logged out / switched account)', () => {
+ expect(reduceRemoteClaudeSubscriptionPush(current, null)).toBeNull();
+ });
+
+ it('replaces with pushed snapshots', () => {
+ const next = { fiveHour: { utilization: 20 } };
+ expect(reduceRemoteClaudeSubscriptionPush(current, next)).toBe(next);
+ });
+
+ it('keeps current value on malformed tunnel payloads', () => {
+ expect(reduceRemoteClaudeSubscriptionPush(current, undefined)).toBe(current);
+ expect(reduceRemoteClaudeSubscriptionPush(current, 'nope')).toBe(current);
+ expect(reduceRemoteClaudeSubscriptionPush(current, [1, 2])).toBe(current);
+ });
+});
+
+describe('owner fence on async backfill', () => {
+ it('discards an in-flight invoke result that resolves after an owner switch', async () => {
+ const read = deferred<unknown>();
+ mocks.invoke.mockReturnValue(read.promise);
+
+ const { result, unmount } = renderHook(() => useRemoteClaudeSubscriptionUsage('device-1'));
+ expect(mocks.invoke).toHaveBeenCalledTimes(1);
+
+ // owner A → owner B(路由树重挂载在真实应用里会发生,module 缓存不受影响)。
+ setDataOwnerGeneration('owner-b');
+ read.resolve({ fiveHour: { utilization: 34 } });
+ await flushMicrotasks();
+
+ // 迟到的 A 账号快照必须整帧丢弃:hook 状态与缓存都不得出现该值。
+ expect(result.current).toBeNull();
+ unmount();
+ const { result: remounted } = renderHook(() => useRemoteClaudeSubscriptionUsage('device-1'));
+ expect(remounted.current).toBeNull();
+ });
+
+ it('drops cached snapshots from a previous owner before seeding a new mount', async () => {
+ mocks.invoke.mockResolvedValue({ fiveHour: { utilization: 12 } });
+ const { result, unmount } = renderHook(() => useRemoteClaudeSubscriptionUsage('device-1'));
+ await flushMicrotasks();
+ expect(result.current).toMatchObject({ fiveHour: { utilization: 12 } });
+ unmount();
+
+ // 换号后重挂载:上一个账号读到的余量不得作为 seed 顶给新账号。
+ setDataOwnerGeneration('owner-b');
+ mocks.invoke.mockReturnValue(deferred<unknown>().promise);
+ const { result: next } = renderHook(() => useRemoteClaudeSubscriptionUsage('device-1'));
+ expect(next.current).toBeNull();
+ });
+});
+
+describe('CHANNEL_NOT_ALLOWED negative cache', () => {
+ const notAllowed = () =>
+ Promise.reject(new Error("[DEVICE_LINK_CHANNEL_NOT_ALLOWED] channel not allowed remotely"));
+
+ it('skips re-probing within the TTL and re-probes after it expires', async () => {
+ mocks.invoke.mockImplementation(notAllowed);
+
+ const first = renderHook(() => useRemoteClaudeSubscriptionUsage('device-old'));
+ await flushMicrotasks();
+ first.unmount();
+ expect(mocks.invoke).toHaveBeenCalledTimes(1);
+
+ // TTL 内重挂载:不再探测(老被控端保持降级占位,不打无谓隧道请求)。
+ const second = renderHook(() => useRemoteClaudeSubscriptionUsage('device-old'));
+ await flushMicrotasks();
+ second.unmount();
+ expect(mocks.invoke).toHaveBeenCalledTimes(1);
+
+ // TTL 过期(被控端可能已升级):重新探测。
+ vi.setSystemTime(1_788_300_000_000 + 16 * 60_000);
+ const third = renderHook(() => useRemoteClaudeSubscriptionUsage('device-old'));
+ await flushMicrotasks();
+ third.unmount();
+ expect(mocks.invoke).toHaveBeenCalledTimes(2);
+ });
+
+ it('clears the negative cache when a subscription push arrives from that device', async () => {
+ mocks.invoke.mockImplementation(notAllowed);
+ const { result, unmount } = renderHook(() => useRemoteClaudeSubscriptionUsage('device-old'));
+ await flushMicrotasks();
+
+ // 被控端升级后推来订阅快照 = 能力已具备:应用快照并解除负缓存。
+ act(() => {
+ for (const cb of [...mocks.pushListeners]) {
+ cb({
+ deviceId: 'device-old',
+ channel: 'usage:claude-subscription-changed',
+ payload: { fiveHour: { utilization: 8 } },
+ });
+ }
+ });
+ expect(result.current).toMatchObject({ fiveHour: { utilization: 8 } });
+ unmount();
+
+ mocks.invoke.mockResolvedValue({ fiveHour: { utilization: 9 } });
+ const { result: remounted } = renderHook(() => useRemoteClaudeSubscriptionUsage('device-old'));
+ await flushMicrotasks();
+ // 负缓存已清 → 重新走隧道读。
+ expect(mocks.invoke).toHaveBeenCalledTimes(2);
+ expect(remounted.current).toMatchObject({ fiveHour: { utilization: 9 } });
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
new file mode 100644
index 0000000000..bc8ada20a6
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
@@ -0,0 +1,293 @@
+// @vitest-environment jsdom
+
+/**
+ * useRemoteDeviceUsage / remoteDeviceUsageMirror / useRemoteClaudeSessionRoute 单测。
+ *
+ * 镜像工厂与 useRemoteClaudeSubscriptionUsage 同语义(owner 栅栏 / CHANNEL_NOT_ALLOWED
+ * TTL 已在该 hook 的测试覆盖同款路径),这里覆盖:
+ * - 工厂 push 整帧替换 / null 清空 / invokeArgs 透传 / push-only 镜像不发 invoke;
+ * - selectRemoteCodexAccountUsage 的选槽 / 选桶口径(与本机 useAccountUsage 一致:
+ * bridge → web 槽;app-server 按模型匹配桶,匹配不到不显示;空桶表回退顶层);
+ * - 路由镜像的观察值应用与 push 更新(按 deviceId+sessionId 过滤)。
+ */
+
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { setDataOwnerGeneration } from '../contexts/dataOwnerGeneration';
+import { createRemoteDeviceUsageMirror } from '../hooks/remoteDeviceUsageMirror';
+import {
+ selectRemoteCodexAccountUsage,
+ useRemoteCodexAccountUsage,
+ useRemoteXaiRateLimit,
+ resetRemoteDeviceUsageMirrorsForTest,
+} from '../hooks/useRemoteDeviceUsage';
+import {
+ resetRemoteClaudeSessionRouteCacheForTest,
+ useRemoteClaudeSessionRoute,
+} from '../hooks/useRemoteClaudeSessionRoute';
+
+type PushListener = (
+ push: { deviceId: string; channel: string; payload: unknown },
+ localOwnerStamp?: unknown,
+) => void;
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn<(deviceId: string, channel: string, args: unknown[]) => Promise<unknown>>(),
+ pushListeners: [] as PushListener[],
+}));
+
+function emitPush(push: { deviceId: string; channel: string; payload: unknown }): void {
+ for (const cb of [...mocks.pushListeners]) cb(push);
+}
+
+async function flushMicrotasks(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_788_300_000_000);
+ setDataOwnerGeneration('owner-a');
+ resetRemoteDeviceUsageMirrorsForTest();
+ resetRemoteClaudeSessionRouteCacheForTest();
+ mocks.invoke.mockReset();
+ mocks.pushListeners.length = 0;
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ deviceLink: {
+ invoke: mocks.invoke,
+ onRemotePush: (cb: PushListener) => {
+ mocks.pushListeners.push(cb);
+ return () => {
+ const i = mocks.pushListeners.indexOf(cb);
+ if (i >= 0) mocks.pushListeners.splice(i, 1);
+ };
+ },
+ },
+ },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('createRemoteDeviceUsageMirror', () => {
+ it('push 整帧替换、null 清空,push-only 镜像不发 invoke', async () => {
+ const pushOnly = createRemoteDeviceUsageMirror<{ v?: number }>({
+ invokeChannel: null,
+ pushChannel: 'test:push-only-changed',
+ });
+ const { result } = renderHook(() => pushOnly.useMirror('device-1'));
+ await flushMicrotasks();
+ expect(mocks.invoke).not.toHaveBeenCalled();
+
+ act(() => emitPush({ deviceId: 'device-1', channel: 'test:push-only-changed', payload: { v: 1 } }));
+ expect(result.current).toEqual({ v: 1 });
+ act(() => emitPush({ deviceId: 'device-1', channel: 'test:push-only-changed', payload: null }));
+ expect(result.current).toBeNull();
+ // 异常形状保留现值。
+ act(() => emitPush({ deviceId: 'device-1', channel: 'test:push-only-changed', payload: { v: 2 } }));
+ act(() => emitPush({ deviceId: 'device-1', channel: 'test:push-only-changed', payload: 'junk' }));
+ expect(result.current).toEqual({ v: 2 });
+ pushOnly.resetForTest();
+ });
+
+ it('useRemoteCodexAccountUsage 经 maker:usage:account 携带 agentKind 参数', async () => {
+ mocks.invoke.mockResolvedValue({ primary: { usedPercent: 3 } });
+ const { result } = renderHook(() => useRemoteCodexAccountUsage('device-1'));
+ await flushMicrotasks();
+ expect(mocks.invoke).toHaveBeenCalledWith('device-1', 'maker:usage:account', ['codex']);
+ expect(result.current).toMatchObject({ primary: { usedPercent: 3 } });
+ });
+});
+
+describe('selectRemoteCodexAccountUsage', () => {
+ const bucketA = {
+ limitId: 'codex',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ };
+ const bucketSpark = {
+ limitId: 'codex_bengalfox',
+ limitName: 'GPT-5.3-Codex-Spark',
+ primary: { usedPercent: 1, windowMinutes: 11_520 },
+ };
+
+ it('bridge 形态取 web 槽', () => {
+ const web = { source: 'openai-web', primary: { usedPercent: 9 } };
+ expect(
+ selectRemoteCodexAccountUsage(
+ { webSnapshot: web, appServerBuckets: { codex: bucketA } },
+ 'openai-web',
+ 'chatgpt/gpt-5.6',
+ ),
+ ).toMatchObject({ primary: { usedPercent: 9 } });
+ });
+
+ it('app-server 形态按模型匹配桶,通用模型不显示模型专属促销桶', () => {
+ const selected = selectRemoteCodexAccountUsage(
+ {
+ ...bucketA,
+ webSnapshot: null,
+ appServerBuckets: { codex: bucketA, codex_bengalfox: bucketSpark },
+ },
+ 'app-server',
+ 'gpt-5.6-sol',
+ );
+ expect(selected?.limitId).toBe('codex');
+ });
+
+ it('桶表为空(旧被控端)回退顶层兼容位;payload 为 null 返回 null', () => {
+ expect(
+ selectRemoteCodexAccountUsage(
+ { ...bucketA, webSnapshot: null, appServerBuckets: null },
+ 'app-server',
+ 'gpt-5.6-sol',
+ )?.primary?.usedPercent,
+ ).toBe(12);
+ expect(selectRemoteCodexAccountUsage(null, 'app-server', 'gpt-5.6-sol')).toBeNull();
+ });
+});
+
+describe('useRemoteClaudeSessionRoute', () => {
+ it('应用被控端观察值,并按 deviceId+sessionId 过滤 push 更新', async () => {
+ mocks.invoke.mockResolvedValue(null);
+ const { result } = renderHook(() => useRemoteClaudeSessionRoute('device-1', 'sess-1'));
+ await flushMicrotasks();
+ expect(mocks.invoke).toHaveBeenCalledWith('device-1', 'maker:claude-session-route:get', ['sess-1']);
+ expect(result.current).toBeNull();
+
+ // 其它会话 / 其它设备的 push 不影响本会话。
+ act(() => emitPush({
+ deviceId: 'device-1',
+ channel: 'maker:claude-session-route-changed',
+ payload: { sessionId: 'sess-other', route: 'gateway' },
+ }));
+ expect(result.current).toBeNull();
+
+ act(() => emitPush({
+ deviceId: 'device-1',
+ channel: 'maker:claude-session-route-changed',
+ payload: { sessionId: 'sess-1', route: 'subscription' },
+ }));
+ expect(result.current).toBe('subscription');
+ });
+
+ it('warm-start 观察值直接生效', async () => {
+ mocks.invoke.mockResolvedValue('gateway');
+ const { result } = renderHook(() => useRemoteClaudeSessionRoute('device-1', 'sess-2'));
+ await flushMicrotasks();
+ expect(result.current).toBe('gateway');
+ });
+
+ // MagicLizi P1 (#3789): a warm-start GET that resolves after a newer push must not win.
+ it.each([null, 'gateway'])('迟到的 warm-start GET(%s)不覆盖在途期间到达的 push', async (late) => {
+ let resolveGet: (v: unknown) => void = () => {};
+ mocks.invoke.mockImplementation(() => new Promise((resolve) => { resolveGet = resolve; }));
+ const { result } = renderHook(() => useRemoteClaudeSessionRoute('device-1', 'sess-3'));
+ await flushMicrotasks();
+ expect(result.current).toBeNull();
+ act(() => emitPush({
+ deviceId: 'device-1',
+ channel: 'maker:claude-session-route-changed',
+ payload: { sessionId: 'sess-3', route: 'subscription' },
+ }));
+ expect(result.current).toBe('subscription');
+ await act(async () => { resolveGet(late); await flushMicrotasks(); });
+ expect(result.current).toBe('subscription');
+ });
+
+ it('无 push 时 warm-start GET 正常生效(revision 未变)', async () => {
+ let resolveGet: (v: unknown) => void = () => {};
+ mocks.invoke.mockImplementation(() => new Promise((resolve) => { resolveGet = resolve; }));
+ const { result } = renderHook(() => useRemoteClaudeSessionRoute('device-1', 'sess-4'));
+ await flushMicrotasks();
+ await act(async () => { resolveGet('gateway'); await flushMicrotasks(); });
+ expect(result.current).toBe('gateway');
+ });
+});
+
+
+describe('remote account parity', () => {
+ it('keeps builtin and named provider reads, pushes and clears separate on one device', async () => {
+ mocks.invoke.mockImplementation(async (_device, _channel, args) => args[1]
+ ? { providerId: args[1], primary: { usedPercent: 70 } }
+ : { primary: { usedPercent: 10 } });
+ const builtin = renderHook(() => useRemoteCodexAccountUsage('device-1'));
+ const named = renderHook(() => useRemoteCodexAccountUsage('device-1', 'account-2'));
+ await flushMicrotasks();
+ expect(mocks.invoke).toHaveBeenCalledWith('device-1', 'maker:usage:account', ['codex', 'account-2']);
+ expect(builtin.result.current?.primary?.usedPercent).toBe(10);
+ expect(named.result.current?.primary?.usedPercent).toBe(70);
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:codex-provider-account-changed',
+ payload: { providerId: 'account-2', snapshot: { primary: { usedPercent: 80 } } } }));
+ expect(named.result.current?.primary?.usedPercent).toBe(80);
+ expect(builtin.result.current?.primary?.usedPercent).toBe(10);
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:codex-account-changed', payload: null }));
+ expect(builtin.result.current).toBeNull();
+ expect(named.result.current?.primary?.usedPercent).toBe(80);
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:codex-provider-account-changed',
+ payload: { providerId: 'account-2', snapshot: null } }));
+ expect(named.result.current).toBeNull();
+ });
+
+ // MagicLizi P1 (#3789): xAI rate-limit mirrors are account-scoped too. An independent
+ // account's record must not land in the builtin mirror and its clear must not empty it.
+ it('keeps builtin and independent xAI rate-limit mirrors separate on one device', () => {
+ const builtin = renderHook(() => useRemoteXaiRateLimit('device-1'));
+ const named = renderHook(() => useRemoteXaiRateLimit('device-1', 'xai-second'));
+ expect(mocks.invoke).not.toHaveBeenCalled();
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:xai-rate-limit-changed',
+ payload: { updatedAt: 1, remainingRequests: 5 } }));
+ expect(builtin.result.current?.remainingRequests).toBe(5);
+ expect(named.result.current).toBeNull();
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:xai-provider-rate-limit-changed',
+ payload: { providerId: 'xai-second', snapshot: { updatedAt: 2, remainingRequests: 9 } } }));
+ expect(named.result.current?.remainingRequests).toBe(9);
+ expect(builtin.result.current?.remainingRequests).toBe(5);
+ // Independent account clear leaves the still-logged-in builtin account untouched.
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:xai-provider-rate-limit-changed',
+ payload: { providerId: 'xai-second', snapshot: null } }));
+ expect(named.result.current).toBeNull();
+ expect(builtin.result.current?.remainingRequests).toBe(5);
+ });
+
+ it('rejects a legacy host builtin response when a named account was requested', async () => {
+ mocks.invoke.mockResolvedValue({ primary: { usedPercent: 10 } });
+ const { result } = renderHook(() => useRemoteCodexAccountUsage('device-1', 'account-2'));
+ await flushMicrotasks();
+ expect(result.current).toBeNull();
+ });
+
+ it('does not let a late initial read overwrite a newer usage push', async () => {
+ let finish!: (value: unknown) => void;
+ mocks.invoke.mockReturnValue(new Promise(resolve => { finish = resolve; }));
+ const { result } = renderHook(() => useRemoteCodexAccountUsage('device-1'));
+ act(() => emitPush({ deviceId: 'device-1', channel: 'usage:codex-account-changed',
+ payload: { primary: { usedPercent: 80 } } }));
+ await act(async () => finish({ primary: { usedPercent: 10 } }));
+ expect(result.current?.primary?.usedPercent).toBe(80);
+ });
+
+ it('does not expose another device snapshot during a device switch', async () => {
+ mocks.invoke.mockResolvedValueOnce({ primary: { usedPercent: 10 } });
+ const seen: unknown[] = [];
+ const { rerender } = renderHook(({ device }) => {
+ const snapshot = useRemoteCodexAccountUsage(device);
+ seen.push(snapshot);
+ return snapshot;
+ }, { initialProps: { device: 'device-1' } });
+ await flushMicrotasks();
+ mocks.invoke.mockReturnValue(new Promise(() => {}));
+ seen.length = 0;
+ rerender({ device: 'device-2' });
+ expect(seen).toEqual([null]);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 3f9ebc08a2..4674b3c9dd 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -1,4 +1,5 @@
import { isOpenAiSubscriptionProvider } from '@cindy/model-providers';
+import { useDeviceProviders } from '@/hooks/useDeviceProviders';
import { useProviders } from '@/hooks/useProviders';
/**
* TodaySpendChip — 右下角用量指示器与所有渠道共用的悬浮卡片入口。
@@ -45,6 +46,20 @@ import {
useClaudeSubscriptionUsage,
type ClaudeSubscriptionUsageSnapshot,
} from '@/hooks/useClaudeSubscriptionUsage';
+import {
+ requestRemoteClaudeSubscriptionRefresh,
+ useRemoteClaudeSubscriptionUsage,
+} from '@/hooks/useRemoteClaudeSubscriptionUsage';
+import { useRemoteClaudeSessionRoute } from '@/hooks/useRemoteClaudeSessionRoute';
+import {
+ requestRemoteCodexAccountRefresh,
+ requestRemoteXaiSubscriptionRefresh,
+ selectRemoteCodexAccountUsage,
+ useRemoteClaudeAccountUsage,
+ useRemoteCodexAccountUsage,
+ useRemoteXaiRateLimit,
+ useRemoteXaiSubscriptionUsage,
+} from '@/hooks/useRemoteDeviceUsage';
import {
isClaudeSubscriptionAlerting,
matchScopedWindowForModel,
@@ -764,21 +779,43 @@ export function TodaySpendChip({
isDefaultRouteClaudeSession &&
observedClaudeRoute == null &&
(gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null));
- const { providers: quotaProviders } = useProviders();
+ const { providers: localQuotaProviders } = useProviders();
+ const { providers: deviceQuotaProviders } = useDeviceProviders(deviceLinkDeviceId ?? 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';
+ 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
+ // 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));
+ const remoteClaudeRoute = useRemoteClaudeSessionRoute(
+ isDeviceLinkRemote && vendorKey === 'cc' && providerId == null && !isDeviceLinkRemoteBridgeModel
+ ? (deviceLinkDeviceId ?? null)
+ : null,
+ sessionId,
+ );
+ const isDeviceLinkRemoteClaudeSubscription =
+ isDeviceLinkRemote &&
+ (vendorKey === 'cc' || vendorKey === 'pi' || vendorKey === 'codex') &&
+ (isClaudeAccount ||
+ (vendorKey === 'cc' &&
+ providerId == null &&
+ !isDeviceLinkRemoteBridgeModel &&
+ remoteClaudeRoute === 'subscription'));
const isClaudeSubscription =
- !isDeviceLinkRemote &&
- ((vendorKey === 'cc' &&
- !isRemoteClaudeSession &&
- (isClaudeAccount ||
- (providerId == null &&
- (observedClaudeRoute != null
- ? observedClaudeRoute === 'subscription'
- : !gatewayKeyReconciling && !hasGatewayKey && claudeOAuthConnected === true)))) ||
- // Pi 的 provider 在创建会话时已经显式固化,不需要再从 CC proxy route 猜。
- ((vendorKey === 'pi' || vendorKey === 'codex') && !remoteHostId && isClaudeAccount));
+ isDeviceLinkRemoteClaudeSubscription ||
+ (!isDeviceLinkRemote &&
+ ((vendorKey === 'cc' &&
+ !isRemoteClaudeSession &&
+ (isClaudeAccount ||
+ (providerId == null &&
+ (observedClaudeRoute != null
+ ? observedClaudeRoute === 'subscription'
+ : !gatewayKeyReconciling && !hasGatewayKey && claudeOAuthConnected === true)))) ||
+ // Pi 的 provider 在创建会话时已经显式固化,不需要再从 CC proxy route 猜。
+ ((vendorKey === 'pi' || vendorKey === 'codex') && !remoteHostId && isClaudeAccount)));
// cc 走「订阅直连 bridge」= model 带 chatgpt/ / xai/ 前缀(经本地 responses-bridge 打用户个人
// 订阅额度,真实计费恒 0,gateway quota 与之无关):
// - chatgpt/ → 与 codex 同一 ChatGPT 账户,复用 codex 订阅 chip 形态(限额窗口 + 价值估算);
@@ -806,10 +843,20 @@ export function TodaySpendChip({
// codex 走订阅价值估算:ChatGPT 订阅需要 oauth-bearer + OpenAI 来源;xAI 由 proxy 注入
// SuperGrok OAuth。显式自定义供应商优先于共享 host 的 authInjection 和模型名前缀。
// 远端 Codex 的事实在远端 daemon 上,本机只记录 token 价值估算,不写本地 gateway cost。
+ // device-link 远程 codex 与 SSH 远程同口径:非 xai / 非折扣模型 / 非显式 XD 即按订阅
+ // 形态处理(本机 runtime route 观察对远程关闭,窗口数据走被控端镜像;被控端若是
+ // API 模式,其账号快照为空,chip 与 SSH 远程一样只显示价值估算)。
+ const isDeviceLinkRemoteCodexOauth =
+ isDeviceLinkRemote &&
+ vendorKey === 'codex' &&
+ !isCodexXaiProvider &&
+ !isCodexGatewayBudgetModel &&
+ (providerId == null || isOpenAiAccount);
const isCodexOauth =
vendorKey === 'codex' &&
!isCodexXaiProvider &&
(isRemoteCodexSession ||
+ isDeviceLinkRemoteCodexOauth ||
(codexAuthInjection === 'oauth-bearer' &&
!isCodexGatewayBudgetModel &&
(providerId == null || isOpenAiAccount)));
@@ -851,6 +898,25 @@ export function TodaySpendChip({
isCodexGatewayBudgetModel ||
(codexAuthInjection === 'provider-oauth' && hasGatewayKey))));
const usesGatewayQuota = isClaudeGateway || isCodexGateway || isPiGateway;
+ // device-link 远程网关形态:显式 XD / codex 折扣模型 / pi 默认(provider 创建时固化,
+ // 空即 XD)直接判;cc 默认路由用被控端路由观察镜像。数据走被控端 LiteLLM 配额镜像,
+ // 本机 quota hook(usesGatewayQuota)对远程保持关闭;credit 三池 handler 绑定主窗口
+ // sender 不镜像 —— 按本机「拿不到就隐藏」的既有降级语义,credit 行远程不显示。
+ const isDeviceLinkRemoteGateway =
+ isDeviceLinkRemote &&
+ ((vendorKey === 'cc' &&
+ !isSubscriptionBridge &&
+ (providerId === 'xd' ||
+ (providerId == null &&
+ !isDeviceLinkRemoteBridgeModel &&
+ remoteClaudeRoute === 'gateway'))) ||
+ (vendorKey === 'codex' &&
+ !isCodexSubscription &&
+ (providerId === 'xd' || isCodexGatewayBudgetModel)) ||
+ (vendorKey === 'pi' &&
+ !isClaudeSubscription &&
+ !isSubscriptionBridge &&
+ (providerId == null || providerId === 'xd')));
const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;
// 会话金额只由已发生的 turn 决定,不由当前选中的 provider/模型决定。实际费用从
// session ledger 读取,订阅价值从消息明细重建,再统一汇总成“本对话”投影。
@@ -869,7 +935,7 @@ export function TodaySpendChip({
// 按会话形态选配额槽: chatgpt/ bridge 消耗 WHAM(openai-web)报告的配额,
// Codex CLI 会话消耗 app-server 报告的配额 —— 不跨槽回退, 绝不显示不是这个
// 会话在消耗的配额(账号多限额桶会互相污染, 见 useAccountUsage 头注释)。
- const accountUsage = useAccountUsage(
+ const localAccountUsage = useAccountUsage(
sessionId,
shouldReadLocalCodexAccountUsage ? 'codex' : undefined,
isChatgptBridge ? 'openai-web' : 'app-server',
@@ -878,26 +944,67 @@ export function TodaySpendChip({
modelId,
providerId ?? 'openai',
);
+ // device-link 远程 codex / chatgpt-bridge:被控端权威组合 payload 镜像,选槽 / 选桶
+ // 与本机同口径在消费点执行(selectRemoteCodexAccountUsage)。
+ const remoteCodexAccountPayload = useRemoteCodexAccountUsage(
+ isDeviceLinkRemote && usesCodexQuotaForm ? (deviceLinkDeviceId ?? null) : null,
+ providerId ?? 'openai',
+ );
+ const accountUsage = isDeviceLinkRemote
+ ? selectRemoteCodexAccountUsage(
+ remoteCodexAccountPayload,
+ isChatgptBridge ? 'openai-web' : 'app-server',
+ modelId,
+ )
+ : localAccountUsage;
const { snapshot: codexRateLimits, refresh: refreshCodexRateLimits } = useCodexRateLimits(
usesCodexQuotaForm && !isAnyRemoteSession,
providerId ?? 'openai',
);
- // xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。
- const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession, providerId ?? 'xai');
- const xaiSubscriptionUsage = useXaiSubscriptionUsage(usesXaiQuotaForm && !isAnyRemoteSession, providerId ?? 'xai');
+ // xAI 限流快照同为本机 main 抓的 —— SSH 远程仍抑制回落价值估算;device-link 远程
+ // 走被控端镜像(订阅周用量 invoke + push,限流头 push-only,与本机同语义降级)。
+ // 本机侧按所选供应商账号取(多账号供应商,#4197 / #4246:限流 hook 同样带 providerId)。
+ const remoteXaiDeviceId =
+ isDeviceLinkRemote && usesXaiQuotaForm ? (deviceLinkDeviceId ?? null) : null;
+ const localXaiRateLimit = useXaiRateLimit(
+ usesXaiQuotaForm && !isAnyRemoteSession,
+ providerId ?? 'xai',
+ );
+ const remoteXaiRateLimit = useRemoteXaiRateLimit(remoteXaiDeviceId, providerId ?? 'xai');
+ const xaiRateLimit = isDeviceLinkRemote ? remoteXaiRateLimit : localXaiRateLimit;
+ const localXaiSubscriptionUsage = useXaiSubscriptionUsage(
+ usesXaiQuotaForm && !isAnyRemoteSession,
+ providerId ?? 'xai',
+ );
+ const remoteXaiSubscriptionUsage = useRemoteXaiSubscriptionUsage(remoteXaiDeviceId, providerId ?? 'xai');
+ const xaiSubscriptionUsage = isDeviceLinkRemote
+ ? remoteXaiSubscriptionUsage
+ : localXaiSubscriptionUsage;
// 只有实际 Gateway 会话读取同一把 XD key 的 LiteLLM quota。订阅与自定义供应商
// 均只展示各自的额度/本地会话统计,不读取 Model Access 账号配额。
- const claudeQuota = useClaudeAccountUsage(usesGatewayQuota);
+ const localClaudeQuota = useClaudeAccountUsage(usesGatewayQuota);
+ const remoteClaudeQuota = useRemoteClaudeAccountUsage(
+ isDeviceLinkRemoteGateway ? (deviceLinkDeviceId ?? null) : null,
+ );
+ const claudeQuota = isDeviceLinkRemote ? remoteClaudeQuota : localClaudeQuota;
// 个人租户的额度事实在 Gateway 三池账本里(推理入口不提供管理面接口), 与上面的
// LiteLLM quota 是两种租户的两种语义, 各自拿不到就各自隐藏 —— 不互相兜底。
const creditUsage = useModelAccessCreditUsage(usesGatewayQuota);
const creditTotals = React.useMemo(() => resolveCreditTotals(creditUsage), [creditUsage]);
// Claude 订阅账号余量 (5h/周/分模型窗口, 端点 + proxy 旁路 headers 双源)。bridge 模型形态
- // 优先(不消耗 Claude 订阅额度),此时不读。
- const claudeSubscriptionUsage = useClaudeSubscriptionUsage(
+ // 优先(不消耗 Claude 订阅额度),此时不读。device-link 远程会话读被控端镜像,
+ // 本机快照与其无关(额度事实在被控端),两个 hook 的 enabled 互斥。
+ const localClaudeSubscriptionUsage = useClaudeSubscriptionUsage(
isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote,
providerId ?? 'anthropic',
);
+ const remoteClaudeSubscriptionUsage = useRemoteClaudeSubscriptionUsage(
+ isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge ? (deviceLinkDeviceId ?? null) : null,
+ providerId ?? 'anthropic',
+ );
+ const claudeSubscriptionUsage = isDeviceLinkRemote
+ ? remoteClaudeSubscriptionUsage
+ : localClaudeSubscriptionUsage;
const latestTurnUsage = useLatestTurnUsageSummary(sessionId);
const quotaCardSessionUsage = toQuotaHoverCardSessionUsage(sessionUsage, sessionTokens);
const quotaCardTurnUsage = toQuotaHoverCardTurnUsage(latestTurnUsage, t);
@@ -1210,20 +1317,38 @@ export function TodaySpendChip({
usesXaiQuotaForm && !isXaiWeeklyUsageCurrent(xaiSubscriptionUsage, windowLabelNowMs);
React.useEffect(() => {
if (!hasPendingResetWindow && !xaiNeedsWeeklyRefresh) return;
- if (isChatgptBridge) {
- requestCodexAccountRefresh(providerId ?? undefined);
+ // 悬念期催刷按会话来源分路:device-link 远程催被控端(经隧道,被控端节流兜底),
+ // 本机催本机(按所选供应商账号,#4197);不得拿本机通道替远程会话催刷(账号不同)。
+ if (isChatgptBridge || (isDeviceLinkRemote && usesCodexQuotaForm)) {
+ if (isDeviceLinkRemote) {
+ if (deviceLinkDeviceId) requestRemoteCodexAccountRefresh(deviceLinkDeviceId, providerId ?? 'openai');
+ } else {
+ requestCodexAccountRefresh(providerId ?? undefined);
+ }
} else if (usesXaiQuotaForm) {
- requestXaiSubscriptionRefresh(providerId ?? 'xai');
+ if (isDeviceLinkRemote) {
+ if (deviceLinkDeviceId) requestRemoteXaiSubscriptionRefresh(deviceLinkDeviceId, providerId ?? 'xai');
+ } else {
+ requestXaiSubscriptionRefresh(providerId ?? 'xai');
+ }
} else if (isClaudeSubscription && !usesCodexQuotaForm) {
- requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');
+ if (isDeviceLinkRemoteClaudeSubscription && deviceLinkDeviceId) {
+ requestRemoteClaudeSubscriptionRefresh(deviceLinkDeviceId, providerId ?? 'anthropic');
+ } else if (!isDeviceLinkRemote) {
+ requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');
+ }
}
}, [
hasPendingResetWindow,
xaiNeedsWeeklyRefresh,
isChatgptBridge,
isClaudeSubscription,
+ isDeviceLinkRemote,
+ isDeviceLinkRemoteClaudeSubscription,
+ deviceLinkDeviceId,
usesCodexQuotaForm,
usesXaiQuotaForm,
+ providerId,
windowLabelNowMs,
]);
@@ -1233,10 +1358,16 @@ export function TodaySpendChip({
void window.electronAPI.openExternal(usageDashboardUrl);
};
+ // device-link 远程形态已解析 = 走与本机一致的对应分支(数据全部来自被控端镜像);
+ // 未解析(默认路由无观察值 / 老被控端)才落占位分支。
+ const deviceLinkRemoteFormResolved =
+ isDeviceLinkRemoteClaudeSubscription ||
+ (isDeviceLinkRemote && (usesCodexQuotaForm || usesXaiQuotaForm || isDeviceLinkRemoteGateway));
let labelNode: React.ReactNode;
let account: UsageCardAccount = { title: t('quotaCard.usageTitle'), windows: [] };
- if (isDeviceLinkRemote) {
+ if (isDeviceLinkRemote && !deviceLinkRemoteFormResolved) {
// device-link 远程会话不读取本机账号形态;金额仍使用同一个会话合计投影。
+ // (形态已解析的远程会话不走这里——落到下方对应形态分支,用被控端镜像渲染。)
const chipSegments = sessionSegment ? [sessionSegment] : [];
labelNode =
chipSegments.length > 0 ? (
@@ -1253,7 +1384,9 @@ export function TodaySpendChip({
) : (
<span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>
);
- if (!isAnyRemoteSession) {
+ // SSH 远程(remoteHostId)没有账号快照镜像,只显示价值估算;device-link 远程的
+ // accountUsage / xai / claude 快照均已在上方切到被控端镜像,与本机同一套卡片渲染。
+ if (!remoteHostId) {
account = usesCodexQuotaForm
? buildCodexUsageCard(accountUsage, codexResetSummary, t, windowLabelNowMs, formatterLocale)
: usesXaiQuotaForm
@@ -1276,8 +1409,9 @@ export function TodaySpendChip({
}),
);
}
- // Account quota is separate from lifetime task cost. API and remote routes never borrow it.
- if (usesGatewayQuota) {
+ // Account quota is separate from lifetime task cost. API and SSH-remote routes never borrow it;
+ // device-link 网关形态用被控端 LiteLLM 配额镜像(claudeQuota 已切换),credit 三池不镜像。
+ if (usesGatewayQuota || isDeviceLinkRemoteGateway) {
account.title = t('quotaCard.gatewayTitle');
if (creditTotals) {
account.windows.push({
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
new file mode 100644
index 0000000000..301dd97e3a
--- /dev/null
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
@@ -0,0 +1,407 @@
+// @vitest-environment jsdom
+
+/**
+ * TodaySpendChip 的 device-link 远程会话形态:
+ * - 显式 anthropic 的远程订阅会话:用被控端镜像快照按本机订阅形态渲染窗口段,
+ * 悬停出同款额度卡(chip 不可点 —— 看板属被控端账号,不跳本机浏览器);
+ * - 被控端镜像不可用(老被控端 / 断链):降级回「仅会话金额 / ¥ 占位」;
+ * - 默认路由(providerId=null)的远程会话:不做本机启发式猜测,维持占位显示。
+ */
+
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ClaudeSubscriptionUsageSnapshot } from '../../../../shared/claudeSubscriptionUsage';
+import type { SessionUsageMoney } from '@/hooks/useSessionUsageMoney';
+
+const mocks = vi.hoisted(() => ({
+ localProviders: [] as Array<{ id: string; auth: { native: string } }>,
+ deviceProviders: [] as Array<{ id: string; auth: { native: string } }>,
+ remoteProviderIds: [] as Array<string | undefined>,
+ localClaudeSnapshot: null as ClaudeSubscriptionUsageSnapshot | null,
+ remoteClaudeSnapshot: null as ClaudeSubscriptionUsageSnapshot | null,
+ remoteHookDeviceIds: [] as Array<string | null>,
+ requestRemoteRefresh: vi.fn(),
+ remoteRoute: null as 'gateway' | 'subscription' | null,
+ remoteRouteDeviceIds: [] as Array<string | null>,
+ remoteCodexPayload: null as Record<string, unknown> | null,
+ remoteCodexDeviceIds: [] as Array<string | null>,
+ remoteClaudeQuota: null as Record<string, unknown> | null,
+ remoteXaiSnapshot: null as Record<string, unknown> | null,
+ sessionUsage: {
+ actualMoney: null,
+ estimatedValueMoney: null,
+ totalMoney: null,
+ } as SessionUsageMoney,
+ displaySnapshot: {
+ messages: [] as Array<Record<string, unknown>>,
+ },
+ openExternal: vi.fn(() => Promise.resolve()),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'zh-CN', resolvedLanguage: 'zh-CN' },
+ t: (key: string, options: Record<string, string | number> = {}) => {
+ const templates: Record<string, string> = {
+ 'todaySpend.claude.weeklyLabel': '周限',
+ 'todaySpend.claude.modelWeeklyLabel': '{{model}} 周限',
+ 'todaySpend.claude.windowSegment': '{{label}} 剩余 {{remaining}}',
+ 'todaySpend.codex.windowSegment': '{{label}} 剩余 {{remaining}}',
+ 'todaySpend.codex.weekWindow': '周限',
+ 'todaySpend.codex.limitWindow': '限额',
+ 'todaySpend.codex.daysWindow': '{{days}}天',
+ 'todaySpend.xai.windowSegment': '{{label}} 剩余 {{remaining}}',
+ 'todaySpend.xai.weekWindow': '周限',
+ 'todaySpend.sessionCostLabel': '本任务 {{cost}}',
+ 'todaySpend.dailyLimitLabel': '今日 {{spend}}/{{limit}}',
+ 'todaySpend.monthlyLimitLabel': '本月 {{spend}}/{{limit}}',
+ 'todaySpend.creditLabel': '额度 {{used}}/{{total}}',
+ 'quotaCard.fiveHourLabel': '5 小时',
+ 'quotaCard.weeklyLabel': '周限',
+ 'quotaCard.modelWeeklyLabel': '{{model}} 周限',
+ 'quotaCard.usedPercent': '已用 {{percent}}%',
+ 'quotaCard.waiting': '等待额度数据',
+ };
+ return (templates[key] ?? key).replace(/{{(\w+)}}/g, (_, name: string) =>
+ String(options[name] ?? ''),
+ );
+ },
+ }),
+}));
+
+vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ providers: mocks.localProviders }) }));
+vi.mock('@/hooks/useDeviceProviders', () => ({ useDeviceProviders: () => ({ providers: mocks.deviceProviders }) }));
+
+vi.mock('@/hooks/useApiKey', () => ({
+ useApiKey: () => ({ hasSavedKey: false, isReconciling: false }),
+}));
+vi.mock('@/hooks/useClaudeOAuthConnected', () => ({
+ useClaudeOAuthConnected: () => null,
+}));
+vi.mock('@/hooks/useClaudeSessionRoute', () => ({
+ useClaudeSessionRoute: () => null,
+}));
+vi.mock('@/hooks/useSessionUsageMoney', () => ({
+ useSessionUsageMoney: () => mocks.sessionUsage,
+}));
+vi.mock('@/hooks/useSessionTokens', () => ({ useSessionTokens: () => null }));
+vi.mock('@/hooks/useAccountUsage', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/hooks/useAccountUsage')>();
+ return {
+ // 选槽 / 选桶纯函数用真实实现(selectRemoteCodexAccountUsage 依赖同一口径)。
+ ...actual,
+ requestCodexAccountRefresh: vi.fn(),
+ useAccountUsage: () => null,
+ };
+});
+vi.mock('@/hooks/useClaudeAccountUsage', () => ({ useClaudeAccountUsage: () => null }));
+vi.mock('@/hooks/useModelAccessCreditUsage', () => ({ useModelAccessCreditUsage: () => null }));
+vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({
+ requestClaudeSubscriptionRefresh: vi.fn(),
+ useClaudeSubscriptionUsage: () => mocks.localClaudeSnapshot,
+}));
+vi.mock('@/hooks/useRemoteClaudeSubscriptionUsage', () => ({
+ requestRemoteClaudeSubscriptionRefresh: mocks.requestRemoteRefresh,
+ useRemoteClaudeSubscriptionUsage: (deviceId: string | null, providerId?: string) => {
+ mocks.remoteProviderIds.push(providerId);
+ mocks.remoteHookDeviceIds.push(deviceId);
+ return deviceId ? mocks.remoteClaudeSnapshot : null;
+ },
+}));
+vi.mock('@/hooks/useRemoteClaudeSessionRoute', () => ({
+ useRemoteClaudeSessionRoute: (deviceId: string | null) => {
+ mocks.remoteRouteDeviceIds.push(deviceId);
+ return deviceId ? mocks.remoteRoute : null;
+ },
+}));
+vi.mock('@/hooks/useRemoteDeviceUsage', async () => {
+ const actual = await vi.importActual<typeof import('@/hooks/useRemoteDeviceUsage')>(
+ '@/hooks/useRemoteDeviceUsage',
+ );
+ return {
+ // selectRemoteCodexAccountUsage 用真实实现(纯函数,选槽口径与本机一致)。
+ selectRemoteCodexAccountUsage: actual.selectRemoteCodexAccountUsage,
+ requestRemoteCodexAccountRefresh: vi.fn(),
+ requestRemoteXaiSubscriptionRefresh: vi.fn(),
+ useRemoteCodexAccountUsage: (deviceId: string | null) => {
+ mocks.remoteCodexDeviceIds.push(deviceId);
+ return deviceId ? mocks.remoteCodexPayload : null;
+ },
+ useRemoteClaudeAccountUsage: (deviceId: string | null) =>
+ deviceId ? mocks.remoteClaudeQuota : null,
+ useRemoteXaiSubscriptionUsage: (deviceId: string | null) =>
+ deviceId ? mocks.remoteXaiSnapshot : null,
+ useRemoteXaiRateLimit: () => null,
+ };
+});
+vi.mock('@/hooks/useCodexRuntimeRoute', () => ({
+ useCodexRuntimeRoute: () => ({ authInjection: null }),
+}));
+vi.mock('@/hooks/useCodexRateLimits', () => ({
+ useCodexRateLimits: () => ({ snapshot: null, refresh: vi.fn() }),
+}));
+vi.mock('@/hooks/useXaiRateLimit', () => ({ useXaiRateLimit: () => null }));
+vi.mock('@/components/chat/ChatDisplaySnapshotContext', () => ({
+ useChatDisplaySnapshot: () => mocks.displaySnapshot,
+}));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ getSnapshot: () => mocks.displaySnapshot,
+ subscribe: () => () => undefined,
+ },
+}));
+
+import { TodaySpendChip } from '../TodaySpendChip';
+
+function renderRemoteChip(providerId: string | null) {
+ return render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId={providerId}
+ modelId="claude-fable-5[1m]"
+ sessionId="session-remote-1"
+ deviceLinkDeviceId="device-abc"
+ />,
+ );
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.localProviders = [];
+ mocks.deviceProviders = [];
+ mocks.remoteProviderIds = [];
+ mocks.localClaudeSnapshot = null;
+ mocks.remoteClaudeSnapshot = null;
+ mocks.remoteHookDeviceIds = [];
+ mocks.remoteRoute = null;
+ mocks.remoteRouteDeviceIds = [];
+ mocks.remoteCodexPayload = null;
+ mocks.remoteCodexDeviceIds = [];
+ mocks.remoteClaudeQuota = null;
+ mocks.remoteXaiSnapshot = null;
+ mocks.sessionUsage = {
+ actualMoney: null,
+ estimatedValueMoney: null,
+ totalMoney: null,
+ };
+ mocks.displaySnapshot.messages = [];
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { openExternal: mocks.openExternal },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+describe('TodaySpendChip device-link remote sessions', () => {
+ it('显式 anthropic 远程会话用被控端镜像快照渲染订阅窗口段(与本机形态一致)', () => {
+ mocks.remoteClaudeSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 12 },
+ sevenDay: { utilization: 25 },
+ scoped: [{ modelDisplayName: 'Fable', utilization: 34 }],
+ };
+
+ const { container } = renderRemoteChip('anthropic');
+
+ expect(container.textContent).toContain('5h 剩余 88%');
+ expect(container.textContent).toContain('Fable 周限 剩余 66%');
+ // 远程订阅会话读的是被控端镜像 hook(deviceId 透传),不读本机快照。
+ expect(mocks.remoteHookDeviceIds).toContain('device-abc');
+ });
+
+ it('远程订阅会话悬停出额度卡,chip 不可点(看板属被控端账号)', () => {
+ mocks.remoteClaudeSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 12 },
+ };
+
+ renderRemoteChip('anthropic');
+
+ // #3972 起 trigger 统一为按钮(打开额度卡);「不可点」= 无看板链接:aria-label 回落
+ // 通用标题、点击不打开外链、卡片里没有看板按钮(看板属被控端账号,不跳本机浏览器)。
+ const trigger = screen.getByRole('button', { name: 'quotaCard.usageTitle' });
+ expect(trigger.textContent).toContain('5h 剩余 88%');
+ fireEvent.click(trigger);
+ expect(mocks.openExternal).not.toHaveBeenCalled();
+
+ fireEvent.mouseEnter(trigger);
+ act(() => vi.advanceTimersByTime(300));
+ const card = screen.getByTestId('quota-hover-card');
+ expect(within(card).queryByRole('button')).toBeNull();
+ // 额度卡用被控端镜像快照渲染同一套窗口进度条。
+ expect(within(card).queryAllByRole('progressbar').length).toBeGreaterThan(0);
+ });
+
+ it('被控端镜像不可用(老被控端 / 断链)时降级回 ¥ 占位', () => {
+ mocks.remoteClaudeSnapshot = null;
+
+ const { container } = renderRemoteChip('anthropic');
+
+ expect(container.textContent).not.toContain('剩余');
+ // 占位货币符号分区域('¥' / '$'),断言形态不锁定具体符号。
+ expect(container.textContent).toMatch(/[¥$]/);
+ });
+
+ it('默认路由(providerId=null)且被控端无路由观察值时维持占位,不做本机启发式猜测', () => {
+ // 即使本机自己连了订阅、有本机快照,也不得替被控端会话渲染本机余量。
+ mocks.localClaudeSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 12 },
+ };
+ mocks.remoteClaudeSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 34 },
+ };
+ mocks.remoteRoute = null;
+
+ const { container } = renderRemoteChip(null);
+
+ expect(container.textContent).not.toContain('剩余');
+ // 无路由观察值 → 订阅镜像 hook 不启用(deviceId 恒为 null),但路由镜像已在探测。
+ expect(mocks.remoteHookDeviceIds.filter(Boolean)).toHaveLength(0);
+ expect(mocks.remoteRouteDeviceIds).toContain('device-abc');
+ });
+
+ it('默认路由远程会话按被控端路由观察值解析形态(subscription → 订阅窗口段)', () => {
+ mocks.remoteRoute = 'subscription';
+ mocks.remoteClaudeSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 12 },
+ };
+
+ const { container } = renderRemoteChip(null);
+
+ expect(container.textContent).toContain('5h 剩余 88%');
+ });
+
+ it('默认路由远程会话路由观察值为 gateway 时按网关形态渲染被控端配额镜像', () => {
+ mocks.remoteRoute = 'gateway';
+ mocks.remoteClaudeQuota = {
+ spend: 120,
+ maxBudget: 3000,
+ currency: 'CNY',
+ todaySpend: 12,
+ };
+
+ const { container } = renderRemoteChip(null);
+
+ // 网关形态主 chip 显示今日额度(月度进 tooltip),数据来自被控端 LiteLLM 镜像。
+ expect(container.textContent).toContain('今日');
+ expect(container.textContent).not.toContain('剩余 ');
+ });
+
+ it('远程 codex 会话按订阅形态渲染被控端账号窗口(组合 payload 选桶)', () => {
+ mocks.remoteCodexPayload = {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ secondary: { usedPercent: 34, windowMinutes: 10_080 },
+ appServerBuckets: {
+ codex: {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ secondary: { usedPercent: 34, windowMinutes: 10_080 },
+ },
+ },
+ webSnapshot: null,
+ };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="codex"
+ providerId="openai"
+ modelId="gpt-5.6-sol"
+ sessionId="session-remote-codex"
+ deviceLinkDeviceId="device-abc"
+ />,
+ );
+
+ expect(container.textContent).toContain('5h 剩余 88%');
+ expect(container.textContent).toContain('7天 剩余 66%');
+ expect(mocks.remoteCodexDeviceIds).toContain('device-abc');
+ });
+
+ it('远程 codex 折扣模型(codex/)按网关形态渲染,不显示订阅窗口', () => {
+ mocks.remoteCodexPayload = {
+ source: 'codex-app-server',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ };
+ mocks.remoteClaudeQuota = {
+ spend: 8,
+ maxBudget: 10_000,
+ currency: 'CNY',
+ todaySpend: 0.5,
+ };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="codex"
+ providerId={null}
+ modelId="codex/gpt-5.5"
+ sessionId="session-remote-codex-budget"
+ deviceLinkDeviceId="device-abc"
+ />,
+ );
+
+ expect(container.textContent).toContain('今日');
+ expect(container.textContent).not.toContain('剩余 88%');
+ });
+
+ it('远程 xai 会话按周用量形态渲染被控端镜像', () => {
+ mocks.remoteXaiSnapshot = {
+ planLabel: 'SuperGrok',
+ creditUsagePercent: 25,
+ resetsAt: null,
+ updatedAt: Date.now(),
+ };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="xai"
+ modelId="grok-4.6"
+ sessionId="session-remote-xai"
+ deviceLinkDeviceId="device-abc"
+ />,
+ );
+
+ expect(container.textContent).toContain('剩余 75%');
+ });
+});
+
+
+describe('existing UI with remote account data', () => {
+ it('renders the same subscription label and classes for identical local and remote data', () => {
+ const snapshot: ClaudeSubscriptionUsageSnapshot = {
+ source: 'oauth-endpoint', fiveHour: { utilization: 12 }, sevenDay: { utilization: 25 },
+ };
+ mocks.localClaudeSnapshot = snapshot;
+ mocks.remoteClaudeSnapshot = snapshot;
+ const local = render(<TodaySpendChip vendorKey="cc" providerId="anthropic" modelId="claude-fable-5[1m]" />);
+ const label = local.container.textContent;
+ const className = local.container.querySelector('button')?.className;
+ local.unmount();
+ const remote = renderRemoteChip('anthropic');
+ expect(remote.container.textContent).toBe(label);
+ expect(remote.container.querySelector('button')?.className).toBe(className);
+ });
+
+ it.each(['cc', 'pi', 'codex'] as const)('reads the selected remote Claude account for %s', vendorKey => {
+ mocks.deviceProviders = [{ id: 'second-account', auth: { native: 'claude' } }];
+ // Same id on the controller belongs to a different vendor and must be ignored.
+ mocks.localProviders = [{ id: 'second-account', auth: { native: 'xai' } }];
+ mocks.remoteClaudeSnapshot = { source: 'oauth-endpoint', fiveHour: { utilization: 12 } };
+ const { container } = render(<TodaySpendChip vendorKey={vendorKey} providerId="second-account"
+ modelId="claude-fable-5[1m]" deviceLinkDeviceId="device-abc" />);
+ expect(container.textContent).toContain('5h 剩余 88%');
+ expect(mocks.remoteProviderIds).toContain('second-account');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
index 87810959bc..feb3423679 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
@@ -126,6 +126,24 @@ vi.mock('@/hooks/useCodexRateLimits', () => ({
refresh: mocks.refreshCodexRateLimits,
}),
}));
+// device-link 远程会话读被控端镜像 hook(#3789);本文件不铺隧道 API,镜像一律返回 null →
+// 远程会话只显示任务用量(与「不混入本机配额」的既有断言同义)。
+vi.mock('@/hooks/useRemoteDeviceUsage', () => ({
+ useRemoteCodexAccountUsage: () => null,
+ requestRemoteCodexAccountRefresh: () => undefined,
+ useRemoteClaudeAccountUsage: () => null,
+ useRemoteXaiSubscriptionUsage: () => null,
+ requestRemoteXaiSubscriptionRefresh: () => undefined,
+ useRemoteXaiRateLimit: () => null,
+ selectRemoteCodexAccountUsage: () => null,
+}));
+vi.mock('@/hooks/useRemoteClaudeSubscriptionUsage', () => ({
+ useRemoteClaudeSubscriptionUsage: () => null,
+ requestRemoteClaudeSubscriptionRefresh: () => undefined,
+}));
+vi.mock('@/hooks/useRemoteClaudeSessionRoute', () => ({
+ useRemoteClaudeSessionRoute: () => null,
+}));
vi.mock('@/hooks/useXaiSubscriptionUsage', () => ({
useXaiSubscriptionUsage: (enabled: boolean) => (enabled ? mocks.xaiSnapshot : null),
requestXaiSubscriptionRefresh: vi.fn(),
diff --git a/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts b/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts
new file mode 100644
index 0000000000..5a45c97ee7
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts
@@ -0,0 +1,149 @@
+/** Remote usage data only; each device/provider consumes the same snapshots as its local UI. */
+import { useEffect, useState } from 'react';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
+import { extractIpcError } from '@/utils/ipcError';
+
+const UNSUPPORTED_RETRY_AFTER_MS = 15 * 60_000;
+function isSnapshotShape(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+}
+
+export interface RemoteDeviceUsageMirror<T> {
+ useMirror(deviceId: string | null, providerId?: string): T | null;
+ request(deviceId: string, providerId?: string): void;
+ resetForTest(): void;
+}
+
+export function createRemoteDeviceUsageMirror<T extends object>(cfg: {
+ invokeChannel: string | null;
+ invokeArgs?: unknown[];
+ pushChannel: string;
+ defaultProviderId?: string;
+ providerPushChannel?: string;
+}): RemoteDeviceUsageMirror<T> {
+ type Entry = {
+ snapshot: T | null;
+ revision: number;
+ unsupportedUntil: number;
+ pending: boolean;
+ owner: ReturnType<typeof getDataOwnerGeneration>;
+ listeners: Set<() => void>;
+ };
+ const entries = new Map<string, Entry>();
+ let cacheOwner = getDataOwnerGeneration();
+ function entryFor(deviceId: string, providerId?: string): Entry {
+ if (!isDataOwnerGenerationCurrent(cacheOwner)) {
+ cacheOwner = getDataOwnerGeneration();
+ entries.clear();
+ }
+ const key = JSON.stringify([deviceId, providerId ?? cfg.defaultProviderId ?? null]);
+ let entry = entries.get(key);
+ if (!entry) {
+ entry = {
+ snapshot: null,
+ revision: 0,
+ unsupportedUntil: 0,
+ pending: false,
+ owner: cacheOwner,
+ listeners: new Set(),
+ };
+ entries.set(key, entry);
+ }
+ return entry;
+ }
+ function apply(entry: Entry, snapshot: T | null): void {
+ entry.snapshot = snapshot;
+ entry.revision++;
+ for (const notify of entry.listeners) notify();
+ }
+ function request(deviceId: string, providerId?: string): void {
+ if (!cfg.invokeChannel) return;
+ const entry = entryFor(deviceId, providerId);
+ if (entry.pending || Date.now() < entry.unsupportedUntil) return;
+ const revision = entry.revision;
+ const args = [...(cfg.invokeArgs ?? [])];
+ // Keep the legacy builtin call shape; scoped reads must explicitly name their provider.
+ if (providerId && providerId !== cfg.defaultProviderId) args.push(providerId);
+ entry.pending = true;
+ void window.electronAPI.deviceLink
+ .invoke(deviceId, cfg.invokeChannel, args)
+ .then((value) => {
+ if (!isDataOwnerGenerationCurrent(entry.owner) || entry.revision !== revision) return;
+ // Older hosts may ignore new optional arguments. Never accept their builtin snapshot
+ // as a named account's usage; scoped handlers echo the provider they actually read.
+ if (
+ providerId &&
+ providerId !== cfg.defaultProviderId &&
+ value !== null &&
+ (!isSnapshotShape(value) || value.providerId !== providerId)
+ )
+ return;
+ if (value === null || isSnapshotShape(value)) apply(entry, value as T | null);
+ })
+ .catch((error: unknown) => {
+ if (!isDataOwnerGenerationCurrent(entry.owner) || entry.revision !== revision) return;
+ if (
+ extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' ||
+ (error instanceof Error && /\[(?:DEVICE_LINK_)?CHANNEL_NOT_ALLOWED\]/.test(error.message))
+ ) {
+ entry.unsupportedUntil = Date.now() + UNSUPPORTED_RETRY_AFTER_MS;
+ }
+ })
+ .finally(() => {
+ entry.pending = false;
+ });
+ }
+ function useMirror(deviceId: string | null, providerId?: string): T | null {
+ const entry = deviceId ? entryFor(deviceId, providerId) : null;
+ const [, rerender] = useState(0);
+ useEffect(() => {
+ if (!deviceId || !entry) return;
+ const notify = () => rerender((value) => value + 1);
+ entry.listeners.add(notify);
+ request(deviceId, providerId);
+ const off = window.electronAPI.deviceLink.onRemotePush((push, ownerStamp) => {
+ if (
+ push.deviceId !== deviceId ||
+ !isDataOwnerGenerationCurrent(entry.owner) ||
+ !isDeviceLinkRemotePushCurrent(push, ownerStamp)
+ )
+ return;
+ const id = providerId ?? cfg.defaultProviderId;
+ let value: unknown;
+ if (
+ push.channel === cfg.pushChannel &&
+ (!cfg.defaultProviderId || id === cfg.defaultProviderId)
+ ) {
+ value = push.payload;
+ } else if (
+ push.channel === cfg.providerPushChannel &&
+ isSnapshotShape(push.payload) &&
+ push.payload.providerId === id
+ ) {
+ value = push.payload.snapshot;
+ } else return;
+ if (value !== null && !isSnapshotShape(value)) return;
+ entry.unsupportedUntil = 0;
+ apply(entry, value as T | null);
+ });
+ return () => {
+ entry.listeners.delete(notify);
+ off();
+ };
+ }, [deviceId, providerId, entry]);
+ // Read the current entry during render: switching devices/accounts must not show the old value.
+ return entry?.snapshot ?? null;
+ }
+ return {
+ useMirror,
+ request,
+ resetForTest: () => {
+ entries.clear();
+ cacheOwner = getDataOwnerGeneration();
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/hooks/useRemoteClaudeSessionRoute.ts b/apps/desktop/src/renderer/hooks/useRemoteClaudeSessionRoute.ts
new file mode 100644
index 0000000000..433cb3013c
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useRemoteClaudeSessionRoute.ts
@@ -0,0 +1,149 @@
+/**
+ * useRemoteClaudeSessionRoute — device-link 远程 cc 默认路由会话的生效计费路由镜像。
+ *
+ * 与 useClaudeSessionRoute(本机)同语义:'gateway' | 'subscription' | null(会话尚未
+ * 发过请求)。路由真值在**被控端** proxy 的按请求观察 registry 里 —— 控制端拿本机
+ * 凭证 / 网关 key 状态替被控端做启发式必然张冠李戴,所以:
+ * - warm-start 隧道读 'maker:claude-session-route:get'(sessionId);
+ * - 变化走 'maker:claude-session-route-changed' push(payload 顶层 sessionId →
+ * session:<id> topic,打开该会话即已订阅;每会话生命周期通常仅一次);
+ * - 观察值为 null(会话没跑过请求)或老被控端 CHANNEL_NOT_ALLOWED → 返回 null,
+ * chip 对该会话维持「仅会话金额」占位(与旧行为一致,不做本机猜测)。
+ *
+ * 缓存按 deviceId+sessionId 存,整体绑定 owner 代次;负缓存(老被控端)按 deviceId
+ * 记且带 TTL,语义与其它远程用量镜像一致。
+ */
+
+import { useEffect, useState } from 'react';
+
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
+import { extractIpcError } from '@/utils/ipcError';
+
+export type RemoteClaudeSessionRoute = 'gateway' | 'subscription';
+
+const ROUTE_GET_CHANNEL = 'maker:claude-session-route:get';
+const ROUTE_CHANGED_CHANNEL = 'maker:claude-session-route-changed';
+const UNSUPPORTED_RETRY_AFTER_MS = 15 * 60_000;
+
+const routeByKey = new Map<string, RemoteClaudeSessionRoute | null>();
+// 与 remoteDeviceUsageMirror 的 entry.revision 同口径:每次 applyRoute 递增;warm-start
+// GET 发起时捕获,返回时 revision 已变(期间来过 push)则丢弃迟到结果,不覆盖更新的值。
+const revisionByKey = new Map<string, number>();
+const unsupportedUntilByDevice = new Map<string, number>();
+const listenersByKey = new Map<string, Set<(r: RemoteClaudeSessionRoute | null) => void>>();
+let cacheOwner = getDataOwnerGeneration();
+
+function cacheKey(deviceId: string, sessionId: string): string {
+ return `${deviceId}\u0000${sessionId}`;
+}
+
+function isRoute(v: unknown): v is RemoteClaudeSessionRoute {
+ return v === 'gateway' || v === 'subscription';
+}
+
+function ensureCacheOwnerCurrent(): void {
+ if (isDataOwnerGenerationCurrent(cacheOwner)) return;
+ cacheOwner = getDataOwnerGeneration();
+ routeByKey.clear();
+ revisionByKey.clear();
+ unsupportedUntilByDevice.clear();
+}
+
+function applyRoute(key: string, next: RemoteClaudeSessionRoute | null): void {
+ revisionByKey.set(key, (revisionByKey.get(key) ?? 0) + 1);
+ routeByKey.set(key, next);
+ const listeners = listenersByKey.get(key);
+ if (!listeners) return;
+ for (const notify of listeners) notify(next);
+}
+
+/** 供单测重置 module 级缓存。 */
+export function resetRemoteClaudeSessionRouteCacheForTest(): void {
+ routeByKey.clear();
+ revisionByKey.clear();
+ unsupportedUntilByDevice.clear();
+ listenersByKey.clear();
+ cacheOwner = getDataOwnerGeneration();
+}
+
+function fetchRoute(deviceId: string, sessionId: string): void {
+ ensureCacheOwnerCurrent();
+ const until = unsupportedUntilByDevice.get(deviceId);
+ if (until !== undefined && Date.now() < until) return;
+ const requestOwner = getDataOwnerGeneration();
+ const key = cacheKey(deviceId, sessionId);
+ const requestRevision = revisionByKey.get(key) ?? 0;
+ void window.electronAPI.deviceLink
+ .invoke(deviceId, ROUTE_GET_CHANNEL, [sessionId])
+ .then((persisted) => {
+ if (!isDataOwnerGenerationCurrent(requestOwner)) return;
+ ensureCacheOwnerCurrent();
+ // A push (or a newer read) landed while this GET was in flight: it is newer than
+ // whatever the GET observed, so the late result must not overwrite it.
+ if ((revisionByKey.get(key) ?? 0) !== requestRevision) return;
+ applyRoute(key, isRoute(persisted) ? persisted : null);
+ })
+ .catch((err: unknown) => {
+ if (!isDataOwnerGenerationCurrent(requestOwner)) return;
+ const unsupported =
+ extractIpcError(err)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED'
+ || (err instanceof Error && /\[(?:DEVICE_LINK_)?CHANNEL_NOT_ALLOWED\]/.test(err.message));
+ if (unsupported) {
+ ensureCacheOwnerCurrent();
+ unsupportedUntilByDevice.set(deviceId, Date.now() + UNSUPPORTED_RETRY_AFTER_MS);
+ }
+ });
+}
+
+export function useRemoteClaudeSessionRoute(
+ deviceId: string | null,
+ sessionId: string | undefined,
+): RemoteClaudeSessionRoute | null {
+ const key = deviceId && sessionId ? cacheKey(deviceId, sessionId) : null;
+ const [route, setRoute] = useState<RemoteClaudeSessionRoute | null>(() => {
+ if (!key) return null;
+ ensureCacheOwnerCurrent();
+ return routeByKey.get(key) ?? null;
+ });
+
+ useEffect(() => {
+ if (!key || !deviceId || !sessionId) {
+ setRoute(null);
+ return;
+ }
+ ensureCacheOwnerCurrent();
+ setRoute(routeByKey.get(key) ?? null);
+ let listeners = listenersByKey.get(key);
+ if (!listeners) {
+ listeners = new Set();
+ listenersByKey.set(key, listeners);
+ }
+ listeners.add(setRoute);
+ fetchRoute(deviceId, sessionId);
+ return () => {
+ listeners.delete(setRoute);
+ if (listeners.size === 0) listenersByKey.delete(key);
+ };
+ }, [key, deviceId, sessionId]);
+
+ useEffect(() => {
+ if (!key || !deviceId || !sessionId) return;
+ const off = window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {
+ if (push.channel !== ROUTE_CHANGED_CHANNEL) return;
+ if (push.deviceId !== deviceId) return;
+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;
+ const payload = push.payload as { sessionId?: unknown; route?: unknown } | null;
+ if (!payload || payload.sessionId !== sessionId) return;
+ ensureCacheOwnerCurrent();
+ unsupportedUntilByDevice.delete(deviceId);
+ applyRoute(key, isRoute(payload.route) ? payload.route : null);
+ });
+ return off;
+ }, [key, deviceId, sessionId]);
+
+ return route;
+}
diff --git a/apps/desktop/src/renderer/hooks/useRemoteClaudeSubscriptionUsage.ts b/apps/desktop/src/renderer/hooks/useRemoteClaudeSubscriptionUsage.ts
new file mode 100644
index 0000000000..cd1828dee3
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useRemoteClaudeSubscriptionUsage.ts
@@ -0,0 +1,23 @@
+/** The remote Claude account uses the same snapshot contract as a local account. */
+import type { ClaudeSubscriptionUsageSnapshot } from '../../shared/claudeSubscriptionUsage';
+import { createRemoteDeviceUsageMirror } from './remoteDeviceUsageMirror';
+
+const mirror = createRemoteDeviceUsageMirror<ClaudeSubscriptionUsageSnapshot>({
+ invokeChannel: 'maker:usage:claude-subscription',
+ pushChannel: 'usage:claude-subscription-changed',
+ defaultProviderId: 'anthropic',
+ providerPushChannel: 'usage:subscription-provider-account-changed',
+});
+export const useRemoteClaudeSubscriptionUsage = mirror.useMirror;
+export const requestRemoteClaudeSubscriptionRefresh = mirror.request;
+export const resetRemoteClaudeSubscriptionUsageCacheForTest = mirror.resetForTest;
+
+export function reduceRemoteClaudeSubscriptionPush(
+ current: ClaudeSubscriptionUsageSnapshot | null,
+ payload: unknown,
+): ClaudeSubscriptionUsageSnapshot | null {
+ if (payload === null) return null;
+ return payload && typeof payload === 'object' && !Array.isArray(payload)
+ ? (payload as ClaudeSubscriptionUsageSnapshot)
+ : current;
+}
diff --git a/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts b/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts
new file mode 100644
index 0000000000..7efb1905cf
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts
@@ -0,0 +1,131 @@
+/**
+ * useRemoteDeviceUsage — device-link 远程会话各计费形态的被控端用量镜像集。
+ *
+ * 与 useRemoteClaudeSubscriptionUsage(Claude 订阅,先落地)并列,覆盖其余形态,
+ * 装配复用 remoteDeviceUsageMirror(invoke warm-start + push 整帧替换 + owner
+ * 栅栏 + CHANNEL_NOT_ALLOWED TTL):
+ * - Codex 账号窗口:invoke 'maker:usage:account'(agentKind='codex')返回权威组合
+ * payload(顶层 app-server 兼容位 + appServerBuckets 桶表 + webSnapshot WHAM 槽),
+ * push 'usage:codex-account-changed' 同形;槽 / 桶选择复用 useAccountUsage 导出的
+ * 纯函数,在消费点按会话形态与模型执行(与本机同口径,绝不显示别的桶)。
+ * - Claude 网关配额(LiteLLM daily/monthly):invoke 同 channel(agentKind=
+ * 'claude-code'),push 'usage:claude-account-changed'。
+ * - xAI 订阅周用量:invoke 'maker:usage:xai-subscription'(被控端 dispatch 拦截
+ * 执行),push 'usage:xai-subscription-changed'。
+ * - xAI 限流头:push-only('usage:xai-rate-limit-changed';独立账号走
+ * 'usage:xai-provider-rate-limit-changed' { providerId, snapshot })—— 被控端无拉取端点,
+ * 本机 renderer 同样只有推送缓存,远程与本机同语义降级。
+ */
+
+import {
+ matchCodexBucketForModel,
+ splitCodexAccountUsagePayload,
+ type CodexQuotaSource,
+ type RateLimitSnapshot,
+} from '@/hooks/useAccountUsage';
+import type { ClaudeAccountUsageSnapshot } from '@/hooks/useClaudeAccountUsage';
+
+import { createRemoteDeviceUsageMirror } from './remoteDeviceUsageMirror';
+
+import type { XaiRateLimitSnapshot } from '../../shared/xaiRateLimit';
+import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage';
+
+/** 被控端 readCodexAccountUsageSnapshot 的组合 payload(与本机 push 同形)。 */
+export type RemoteCodexAccountUsagePayload = RateLimitSnapshot & {
+ webSnapshot?: RateLimitSnapshot | null;
+ appServerBuckets?: Record<string, RateLimitSnapshot> | null;
+};
+
+const codexAccountMirror = createRemoteDeviceUsageMirror<RemoteCodexAccountUsagePayload>({
+ invokeChannel: 'maker:usage:account',
+ invokeArgs: ['codex'],
+ pushChannel: 'usage:codex-account-changed',
+ defaultProviderId: 'openai',
+ providerPushChannel: 'usage:codex-provider-account-changed',
+});
+const claudeAccountMirror = createRemoteDeviceUsageMirror<ClaudeAccountUsageSnapshot>({
+ invokeChannel: 'maker:usage:account',
+ invokeArgs: ['claude-code'],
+ pushChannel: 'usage:claude-account-changed',
+});
+const xaiSubscriptionMirror = createRemoteDeviceUsageMirror<XaiSubscriptionUsageSnapshot>({
+ invokeChannel: 'maker:usage:xai-subscription',
+ pushChannel: 'usage:xai-subscription-changed',
+ defaultProviderId: 'xai',
+ providerPushChannel: 'usage:subscription-provider-account-changed',
+});
+const xaiRateLimitMirror = createRemoteDeviceUsageMirror<XaiRateLimitSnapshot>({
+ invokeChannel: null,
+ pushChannel: 'usage:xai-rate-limit-changed',
+ defaultProviderId: 'xai',
+ providerPushChannel: 'usage:xai-provider-rate-limit-changed',
+});
+
+/** 被控端 Codex 账号组合 payload 镜像(远程 codex / chatgpt-bridge 会话 chip 用)。 */
+export function useRemoteCodexAccountUsage(
+ deviceId: string | null,
+ providerId?: string,
+): RemoteCodexAccountUsagePayload | null {
+ return codexAccountMirror.useMirror(deviceId, providerId);
+}
+
+export function requestRemoteCodexAccountRefresh(deviceId: string, providerId?: string): void {
+ codexAccountMirror.request(deviceId, providerId);
+}
+
+/** 被控端 Claude 网关配额(LiteLLM daily/monthly)镜像(远程网关形态会话 chip 用)。 */
+export function useRemoteClaudeAccountUsage(
+ deviceId: string | null,
+): ClaudeAccountUsageSnapshot | null {
+ return claudeAccountMirror.useMirror(deviceId);
+}
+
+/** 被控端 xAI 订阅周用量镜像(远程 xai 形态会话 chip 用)。 */
+export function useRemoteXaiSubscriptionUsage(
+ deviceId: string | null,
+ providerId?: string,
+): XaiSubscriptionUsageSnapshot | null {
+ return xaiSubscriptionMirror.useMirror(deviceId, providerId);
+}
+
+export function requestRemoteXaiSubscriptionRefresh(deviceId: string, providerId?: string): void {
+ xaiSubscriptionMirror.request(deviceId, providerId);
+}
+
+/** 被控端 xAI 限流头镜像(push-only,tooltip 尽力显示;独立账号订阅各自的 provider 镜像)。 */
+export function useRemoteXaiRateLimit(
+ deviceId: string | null,
+ providerId?: string,
+): XaiRateLimitSnapshot | null {
+ return xaiRateLimitMirror.useMirror(deviceId, providerId);
+}
+
+/**
+ * 远程组合 payload → 会话形态对应的单快照(与本机 useAccountUsage 的选槽同口径):
+ * chatgpt/ bridge 消耗 WHAM(openai-web)槽;Codex CLI 会话消耗 app-server 槽并按
+ * 当前模型匹配限额桶(matchCodexBucketForModel,匹配不到宁可不显示,绝不显示别的
+ * 桶);桶表为空(旧被控端 / 无 app 数据)回退顶层兼容位。split 复用本机同一实现
+ * (含桶表 sanitize —— 远程 payload 一律按数据对待)。
+ */
+export function selectRemoteCodexAccountUsage(
+ payload: RemoteCodexAccountUsagePayload | null,
+ quotaSource: CodexQuotaSource,
+ modelId?: string | null,
+): RateLimitSnapshot | null {
+ if (!payload) return null;
+ const parts = splitCodexAccountUsagePayload(payload);
+ if (quotaSource === 'openai-web') return parts.web ?? null;
+ const buckets = parts.appServerBuckets;
+ if (buckets && Object.keys(buckets).length > 0) {
+ return matchCodexBucketForModel(buckets, modelId);
+ }
+ return parts.appServer ?? null;
+}
+
+/** 供单测重置全部镜像缓存。 */
+export function resetRemoteDeviceUsageMirrorsForTest(): void {
+ codexAccountMirror.resetForTest();
+ claudeAccountMirror.resetForTest();
+ xaiSubscriptionMirror.resetForTest();
+ xaiRateLimitMirror.resetForTest();
+}
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index cdd38dada5..64dd1f3c59 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -173,6 +173,18 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:codex-rate-limit-reset')).toBe(true);
});
+ it('放行 Claude 订阅余量快照只读(远程订阅会话 chip 镜像被控端窗口剩余)', () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:claude-subscription')).toBe(true);
+ });
+
+ it('放行 xAI 订阅周用量只读(被控端 dispatch 拦截执行,不进挂 assert 的 ipcMain)', () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:xai-subscription')).toBe(true);
+ });
+
+ it('放行 cc 默认路由观察值只读(路由真值在被控端 proxy registry,远程形态判定用)', () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:claude-session-route:get')).toBe(true);
+ });
+
it('放行被控端项目顺序读写(显示偏好,真相在被控端)', () => {
expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:get-project-order')).toBe(true);
expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:apply-project-order')).toBe(true);
@@ -378,6 +390,15 @@ describe('PUSH_FORWARD_ALLOWLIST', () => {
'usage:message-turn-cost',
'usage:session-spend-changed',
'usage:session-tokens-changed',
+ 'usage:claude-subscription-changed',
+ 'usage:codex-account-changed',
+ 'usage:codex-provider-account-changed',
+ 'usage:subscription-provider-account-changed',
+ 'usage:claude-account-changed',
+ 'usage:xai-subscription-changed',
+ 'usage:xai-rate-limit-changed',
+ 'usage:xai-provider-rate-limit-changed',
+ 'maker:claude-session-route-changed',
'local-db:messages:created',
'local-db:messages:deleted',
'local-db:session:error-persisted',
diff --git a/packages/device-link/src/__tests__/topics.test.ts b/packages/device-link/src/__tests__/topics.test.ts
index c7e61f3cb5..433de88cb9 100644
--- a/packages/device-link/src/__tests__/topics.test.ts
+++ b/packages/device-link/src/__tests__/topics.test.ts
@@ -55,6 +55,27 @@ describe('topicForPush', () => {
projectOrder: 'custom',
manualProjectOrder: ['local:/a'],
})).toBe('sessions');
+ // Claude 订阅余量快照(账号级,无 sessionId;null = 登出清除)→ 并入 sessions topic。
+ expect(topicForPush('usage:claude-subscription-changed', {
+ fiveHour: { utilization: 4, resetsAt: 1788345000 },
+ })).toBe('sessions');
+ expect(topicForPush('usage:claude-subscription-changed', null)).toBe('sessions');
+ // 其余账号级用量快照同口径。
+ expect(topicForPush('usage:codex-account-changed', {
+ primary: { usedPercent: 3 }, webSnapshot: null,
+ })).toBe('sessions');
+ expect(topicForPush('usage:claude-account-changed', {
+ spend: 0.06, maxBudget: 10000,
+ })).toBe('sessions');
+ expect(topicForPush('usage:xai-subscription-changed', { creditUsagePercent: 2 })).toBe('sessions');
+ expect(topicForPush('usage:xai-rate-limit-changed', null)).toBe('sessions');
+ });
+
+ it('claude-session-route-changed → session:<id>(payload 顶层 sessionId 兜底路由)', () => {
+ expect(topicForPush('maker:claude-session-route-changed', {
+ sessionId: 'sess-1',
+ route: 'subscription',
+ })).toBe('session:sess-1');
});
it('learn:event → sessions(账号级:run 关联触发/蒸馏两个任务,单 sessionId 路由会漏)', () => {
@@ -176,3 +197,11 @@ describe('expandMakerEventBatchPayload', () => {
.toBe('session:s7');
});
});
+
+
+it.each(['usage:codex-provider-account-changed', 'usage:subscription-provider-account-changed', 'usage:xai-provider-rate-limit-changed'])(
+ '%s forwards both scoped usage and account clears on the sessions topic', channel => {
+ expect(topicForPush(channel, { providerId: 'account-2', snapshot: { primary: { usedPercent: 10 } } })).toBe('sessions');
+ expect(topicForPush(channel, { providerId: 'account-2', snapshot: null })).toBe('sessions');
+ },
+);
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 9f58812785..f954e4cd54 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -425,6 +425,25 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// 人工 reset。mutation 不接收 creditId,不能泛化成任意账号/凭证控制入口。
'maker:usage:codex-rate-limits',
'maker:usage:codex-rate-limit-reset',
+ // Claude 订阅账号余量快照(只读,cached-first):控制端远程会话状态栏 chip 显示
+ // 被控端订阅的 5h/周/分模型窗口剩余(数据真相在被控端 —— turn 在被控端消耗其
+ // 订阅额度)。快照只含利用率百分比、reset 时间与账号归属指纹(单向 scrypt 哈希,
+ // 与本机 renderer 收到的广播 payload 同形),不含凭证材料。无 sender 依赖、无副
+ // 作用;老被控端无此 channel → CHANNEL_NOT_ALLOWED → 控制端降级为原「仅会话
+ // 金额」占位显示。
+ 'maker:usage:claude-subscription',
+ // xAI(SuperGrok)订阅周用量快照(只读):与 claude-subscription 同定位。该 channel
+ // 的 ipcMain handler 挂了 assertTrustedSender(合成 event 必然不可信,那道闸不为
+ // 远程放宽)—— 与 device-link:telegram:* 同先例,由被控端 dispatch 在通用 dispatch
+ // 前拦截、直读 usage reader,不进 ipcMain。列入 allowlist 作契约登记 + 老被控端
+ // CHANNEL_NOT_ALLOWED 供控制端探测降级。
+ 'maker:usage:xai-subscription',
+ // cc 默认路由会话的生效计费路由观察值(只读,'gateway' | 'subscription' | null):
+ // 控制端远程会话据此判定订阅 / 网关显示形态 —— 路由真值在被控端 proxy 的按请求
+ // 观察 registry 里,控制端拿本机凭证状态重算必然张冠李戴。入参 sessionId,无
+ // sender 依赖、无副作用;老被控端 CHANNEL_NOT_ALLOWED → 控制端对默认路由远程
+ // 会话维持「仅会话金额」占位(与旧行为一致)。
+ 'maker:claude-session-route:get',
// 模型单价表(只读,main 侧 Model Access model-groups 投影缓存):控制端模型选择器展示
// 被控端视角的单价(与被控端桌面 tooltip 同源)。无 sender 依赖、无副作用;老被控端无此 channel
// → CHANNEL_NOT_ALLOWED → 控制端隐藏价格(与桌面「无价不显示」口径一致)。
@@ -613,6 +632,31 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
// sessions:patched,控制端远程会话底部 $ chip 依赖这两条把累计值镜像成被控端真相。
'usage:session-spend-changed',
'usage:session-tokens-changed',
+ // Claude 订阅账号余量变化(账号级,无 sessionId → topics.ts 归入 sessions topic):
+ // 控制端远程会话 chip 据此实时镜像被控端订阅窗口剩余。推送频率有上限:被控端
+ // headers 观察器按 (5h,7d,status) 签名去抖、端点刷新 180s 节流,只有数值变化才
+ // 广播,不随 turn 内逐请求刷帧。
+ 'usage:claude-subscription-changed',
+ // Codex 账号订阅用量变化(账号级组合 payload:app-server 桶表 + WHAM web 槽):
+ // 控制端远程 codex / chatgpt-bridge 会话 chip 镜像被控端限额窗口。频率上限:
+ // app-server 每 turn 记录一次、WHAM 后台刷新 10s 节流。
+ 'usage:codex-account-changed',
+ // Same provider-scoped payloads consumed by the local usage hooks.
+ 'usage:codex-provider-account-changed',
+ 'usage:subscription-provider-account-changed',
+ // Claude 网关配额变化(LiteLLM 月度/今日,账号级):控制端远程网关形态会话 chip
+ // 镜像被控端 daily/monthly。被控端刷新自带 10s 节流 + turn-done 触发。
+ 'usage:claude-account-changed',
+ // xAI 订阅周用量变化(账号级):同上定位;被控端周用量刷新低频。
+ 'usage:xai-subscription-changed',
+ // xAI 限流头快照(账号级,纯内存瞬时值):tooltip 尽力显示;bridge 每成功请求
+ // 至多一帧,xai/ 会话低频。
+ 'usage:xai-rate-limit-changed',
+ // 独立 xAI 账号的限流头({ providerId, snapshot }):与 codex-provider 同口径按账号分路。
+ 'usage:xai-provider-rate-limit-changed',
+ // cc 默认路由会话路由观察值变化(payload 顶层 sessionId → session:<id> topic,
+ // 打开该会话的控制端可见;每会话生命周期通常仅一次)。
+ 'maker:claude-session-route-changed',
// local-db 推送(读模型增量)
'local-db:sessions:created',
'local-db:sessions:patched',
diff --git a/packages/device-link/src/topics.ts b/packages/device-link/src/topics.ts
index 497f0a3de9..18d593fe60 100644
--- a/packages/device-link/src/topics.ts
+++ b/packages/device-link/src/topics.ts
@@ -182,6 +182,21 @@ const ACCOUNT_CHANNELS: ReadonlySet<string> = new Set([
'learn:event',
// 被控端项目手动顺序变化:无 sessionId,并入 sessions topic 随设备列表订阅到达。
'sidebar-settings:project-order-changed',
+ // Claude 订阅账号余量快照(账号级,无 sessionId):控制端打开远程订阅会话时 chip
+ // 据此实时刷新;并入 sessions topic 随设备列表订阅到达,低频(签名去抖 + 节流)。
+ 'usage:claude-subscription-changed',
+ // Codex 账号订阅用量 / Claude 网关配额 / xAI 订阅与限流头:同上定位,账号级
+ // 无 sessionId,并入 sessions topic。频率上限见 allowlist.ts 对应条目注释。
+ // (maker:claude-session-route-changed 不在此表 —— payload 带 sessionId,走
+ // topicForPush 的 session-scoped 兜底路由到 session:<id>。)
+ 'usage:codex-account-changed',
+ // Same provider-scoped payloads consumed by the local usage hooks.
+ 'usage:codex-provider-account-changed',
+ 'usage:subscription-provider-account-changed',
+ 'usage:claude-account-changed',
+ 'usage:xai-subscription-changed',
+ 'usage:xai-rate-limit-changed',
+ 'usage:xai-provider-rate-limit-changed',
]);
/** 从 unknown payload 安全读一个字符串字段。 */