Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(mobile): 在任务菜单展示配额与用量摘要 (#3979)

Dasha5e724daa00f
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 8f33a3d720..da301e5302 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1609,8 +1609,6 @@ export default function SessionScreen() {
setLoading(false);
rewindRequestSeqRef.current += 1;
}
- const [contextLoading, setContextLoading] = useState(false);
- const [contextUsage, setContextUsage] = useState<unknown>(null);
// 账号级限额快照(`maker:usage:account` 原始返回):账号级数据本身跨会话共享,但
// 会话 agentKind 不同时语义不同(只对 codex 会话拉取/展示),随 sessionId 一起清。
const [accountUsage, setAccountUsage] = useState<unknown>(null);
@@ -1620,14 +1618,11 @@ export default function SessionScreen() {
const [codexResetBusy, setCodexResetBusy] = useState(false);
// consume 回包丢失时保留本次 UUID;即使面板重新拉取额度,重试也不能换 key。
const [codexResetRetryKey, setCodexResetRetryKey] = useState<string | null>(null);
- // contextUsage 的归属会话号:同屏 sessionId 变化(深链 setParams 等原地切换路径)时
- // 清空缓存并作废在途请求,防止上一会话的用量数据在新会话的「会话信息」里串档。
+ // 账号控制快照的归属会话号;上下文详情缓存由菜单自身管理。
const contextUsageSessionRef = useRef(sessionId);
useEffect(() => {
if (contextUsageSessionRef.current === sessionId) return;
contextUsageSessionRef.current = sessionId;
- setContextUsage(null);
- setContextLoading(false);
setAccountUsage(null);
setCodexRateLimits(null);
setCodexResetBusy(false);
@@ -6211,13 +6206,11 @@ export default function SessionScreen() {
if (localSystemCommand) {
let data: Record<string, unknown>;
if (localSystemCommand === 'context') {
- setContextLoading(true);
try {
const usage = await maker.getContextUsage(
sessionId,
buildContextUsageCreateOpts(sessionAtSend),
);
- setContextUsage(usage);
data = buildMobileSystemCardData(localSystemCommand, {
contextUsage: usage,
projection: inputProjection,
@@ -6231,8 +6224,6 @@ export default function SessionScreen() {
remoteCommands: commandsAtSend,
session: sessionAtSend,
});
- } finally {
- setContextLoading(false);
}
} else {
data = buildMobileSystemCardData(localSystemCommand, {
@@ -7890,25 +7881,6 @@ export default function SessionScreen() {
setModelSheetOpen(true);
}, [agentSwitchIntent, canUseRemoteSessionControls, modelSheetOpen, sessionAgentKind]);
- const refreshContextUsage = useCallback(async () => {
- if (!currentSession || contextLoading) return;
- setContextLoading(true);
- setError(null);
- try {
- const usage = await maker.getContextUsage(
- sessionId,
- buildContextUsageCreateOpts(currentSession),
- );
- // 会话已原地切换 → 丢弃迟到结果,归属校验见 contextUsageSessionRef 注释。
- if (contextUsageSessionRef.current !== sessionId) return;
- setContextUsage(usage);
- } catch (err) {
- if (contextUsageSessionRef.current === sessionId) setError(formatRemoteError(err));
- } finally {
- if (contextUsageSessionRef.current === sessionId) setContextLoading(false);
- }
- }, [contextLoading, currentSession, maker, sessionId]);
-
// 账号限额按需拉取(会话信息面板打开时):优先走 Codex app-server 权威控制面,
// 同时拿窗口和 reset credits。老被控端没有新通道时回退既有只读 usage channel;
// 两条都失败则静默保留当前快照——限额是补充信息,不打断会话操作。
@@ -7921,7 +7893,7 @@ export default function SessionScreen() {
}
try {
const snapshot = await maker.getCodexRateLimits();
- // 迟到结果归属校验,同 contextUsage(见 contextUsageSessionRef 注释)。
+ // 迟到结果仍按账号控制快照的会话归属校验。
if (contextUsageSessionRef.current !== sessionId) return;
setCodexRateLimits(snapshot);
setAccountUsage(snapshot.rateLimits);
@@ -8719,12 +8691,12 @@ export default function SessionScreen() {
</View>
{currentSession ? (
<SessionMenuSheet
+ usageReader={maker}
accountUsage={localCodexRateLimitControl ? accountUsage : null}
busy={controlBusy}
codexRateLimits={localCodexRateLimitControl ? codexRateLimits : null}
codexResetBusy={codexResetBusy}
- contextLoading={contextLoading}
- contextUsage={contextUsage}
+ onContextError={setError}
extraDirBrowser={extraDirBrowser}
initialView={menuInitialView}
keyboardAvoidingBehavior={nativeShellLayout.keyboardAvoidingBehavior}
@@ -8734,7 +8706,6 @@ export default function SessionScreen() {
onDelete={() => patchSessionMeta({ status: 'deleted' })}
onLoadExtraDirPath={(path) => void loadExtraDirBrowsePath(path)}
onRefreshAccountUsage={() => void refreshAccountUsage()}
- onRefreshContextUsage={() => void refreshContextUsage()}
onResetCodexRateLimits={() => void resetCodexRateLimits()}
onOpenWorkspace={() => {
if (!currentSession.workingDir) return;
diff --git a/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx b/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx
new file mode 100644
index 0000000000..c2bceebfea
--- /dev/null
+++ b/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx
@@ -0,0 +1,136 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vitest";
+import {
+ SessionMenuSheet,
+ type SessionMenuSheetProps,
+} from "@/session/SessionMenuSheet";
+import { i18n } from "@/i18n";
+
+vi.mock("react-native", async () => {
+ const { createElement } = await import("react");
+ const view = ({
+ children,
+ onPress,
+ testID,
+ }: {
+ children?: ReactNode;
+ onPress?: () => void;
+ testID?: string;
+ }) =>
+ createElement("div", { onClick: onPress, "data-testid": testID }, children);
+ return {
+ View: view,
+ Pressable: view,
+ Text: view,
+ TextInput: view,
+ ActivityIndicator: () => null,
+ Alert: { alert: vi.fn() },
+ Animated: {
+ Value: class {
+ setValue() {}
+ },
+ View: view,
+ timing: () => ({ start: (done?: () => void) => done?.() }),
+ },
+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },
+ useWindowDimensions: () => ({ height: 800, width: 400 }),
+ };
+});
+vi.mock("@/components/AppText", async () => {
+ const rn = await import("react-native");
+ return { Text: rn.Text, TextInput: rn.TextInput };
+});
+vi.mock("lucide-react-native", () =>
+ Object.fromEntries(
+ [
+ "Archive",
+ "ArchiveRestore",
+ "ChevronRight",
+ "Copy",
+ "GitBranch",
+ "Link2",
+ "Pencil",
+ "Pin",
+ "PinOff",
+ "RefreshCw",
+ "Sparkles",
+ "Trash2",
+ ].map((name) => [name, () => null]),
+ ),
+);
+vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }),
+}));
+vi.mock("@/theme", async () => {
+ const tokens = await import("@/theme/tokens");
+ return {
+ ...tokens,
+ monoFont: "monospace",
+ useTheme: () => ({ colors: tokens.lightColors }),
+ useThemedStyles: (make: (colors: typeof tokens.lightColors) => unknown) =>
+ make(tokens.lightColors),
+ };
+});
+vi.mock("@/components/MobilePrimitives", () => ({
+ MainWindowActionGroup: () => null,
+}));
+vi.mock("@/session/SheetModal", () => ({
+ SheetModal: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@/session/SheetSurface", () => ({
+ SheetSurface: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@/session/messageActions", () => ({ writeClipboardText: vi.fn() }));
+
+it("reopening the primary menu after info does not initialize an engine, but entering info does", async () => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ await i18n.changeLanguage("zh-CN");
+ const reader = {
+ getContextUsage: vi.fn(async () => ({
+ totalTokens: 20,
+ rawMaxTokens: 100,
+ })),
+ getCodexRateLimits: vi.fn(),
+ getAccountUsage: vi.fn(),
+ getSessionEstimatedValue: vi.fn(async () => ({})),
+ };
+ const props = {
+ usageReader: reader,
+ onContextError: vi.fn(),
+ onRefreshAccountUsage: vi.fn(),
+ session: {
+ id: "a",
+ model: "custom",
+ providerId: "custom",
+ agentKind: "pi",
+ title: "Task",
+ contextTokens: 20,
+ contextWindow: 0,
+ },
+ initialView: "info",
+ visible: true,
+ busy: false,
+ } as unknown as SessionMenuSheetProps;
+ const host = document.createElement("div");
+ const root = createRoot(host);
+ try {
+ await act(async () => root.render(<SessionMenuSheet {...props} />));
+ expect(reader.getContextUsage).toHaveBeenCalledOnce();
+ await act(async () =>
+ root.render(<SessionMenuSheet {...props} visible={false} />),
+ );
+ await act(async () =>
+ root.render(<SessionMenuSheet {...props} initialView="menu" />),
+ );
+ expect(reader.getContextUsage).toHaveBeenCalledOnce();
+ // Both surfaces stay mounted. The primary card is the first summary entry.
+ const summary = host.querySelector('[data-testid="session.menuUsageRow"]');
+ expect(summary).not.toBeNull();
+ await act(async () => (summary as HTMLElement).click());
+ expect(reader.getContextUsage).toHaveBeenCalledTimes(2);
+ } finally {
+ act(() => root.unmount());
+ }
+});
diff --git a/apps/mobile/src/__tests__/SessionUsageSummary.test.tsx b/apps/mobile/src/__tests__/SessionUsageSummary.test.tsx
new file mode 100644
index 0000000000..f693f6847d
--- /dev/null
+++ b/apps/mobile/src/__tests__/SessionUsageSummary.test.tsx
@@ -0,0 +1,264 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SessionUsageSummary } from "@/session/SessionUsageSummary";
+import { i18n } from "@/i18n";
+import type { RemoteSession } from "@/session/types";
+import type { useSessionMenuUsage } from "@/session/useSessionMenuUsage";
+
+const theme = vi.hoisted(() => ({ mode: "light" }));
+vi.mock("react-native", async () => {
+ const { createElement } = await import("react");
+ const view =
+ (tag: string) =>
+ ({
+ children,
+ onPress,
+ accessibilityLabel,
+ }: {
+ children?: ReactNode;
+ onPress?: () => void;
+ accessibilityLabel?: string;
+ }) =>
+ createElement(
+ tag,
+ { onClick: onPress, "aria-label": accessibilityLabel },
+ children,
+ );
+ return {
+ View: view("div"),
+ Pressable: view("button"),
+ Text: view("span"),
+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },
+ };
+});
+vi.mock("@/components/AppText", async () => ({
+ Text: (await import("react-native")).Text,
+}));
+vi.mock("lucide-react-native", () => ({ ChevronRight: () => null }));
+vi.mock("@/theme", async () => {
+ const tokens = await import("@/theme/tokens");
+ const colors = () =>
+ theme.mode === "light" ? tokens.lightColors : tokens.darkColors;
+ return {
+ iconSize: tokens.iconSize,
+ iconStroke: tokens.iconStroke,
+ useTheme: () => ({ colors: colors() }),
+ useThemedStyles: (make: (value: typeof tokens.lightColors) => unknown) =>
+ make(colors()),
+ };
+});
+let root: Root;
+let host: HTMLDivElement;
+beforeEach(async () => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ await i18n.changeLanguage("zh-CN");
+ host = document.createElement("div");
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+});
+const session = {
+ model: "gpt-5",
+ agentKind: "codex",
+ providerId: "openai",
+ totalCostUsd: 0,
+ contextTokens: 45,
+ contextWindow: 100,
+} as RemoteSession;
+const usage: ReturnType<typeof useSessionMenuUsage> = {
+ account: {
+ source: "chatgpt",
+ plan: "pro",
+ updatedAt: Date.now(),
+ amounts: [],
+ windows: [
+ {
+ id: "primary",
+ minutes: 300,
+ remainingPercent: 72,
+ resetsAt: Date.now() / 1000 + 3600,
+ },
+ ],
+ },
+ estimate: {
+ amount: 12.3,
+ currency: "USD",
+ approximate: true,
+ kind: "value-estimate",
+ },
+ loading: false,
+ accountFailed: false,
+ estimateFailed: false,
+ refresh: () => {},
+};
+describe("task menu usage summary", () => {
+ it.each(["light", "dark"])(
+ "shows quota, value and context in the first-level entry with %s tokens",
+ (mode) => {
+ theme.mode = mode;
+ const onPress = vi.fn();
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={session}
+ usage={usage}
+ contextUsage={null}
+ onPress={onPress}
+ />,
+ ),
+ );
+ expect(host.textContent).toContain("剩余 72%");
+ expect(host.textContent).toContain("本任务价值");
+ expect(host.textContent).toContain("≈ $12.30");
+ expect(host.textContent).toContain("45%");
+ act(() => host.querySelector("button")!.click());
+ expect(onPress).toHaveBeenCalledOnce();
+ },
+ );
+ it("labels legacy quota as account-only without attributing its plan to the task", () => {
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={session}
+ usage={{
+ ...usage,
+ estimate: null,
+ account: { ...usage.account!, accountOnly: true },
+ }}
+ contextUsage={null}
+ />,
+ ),
+ );
+ expect(host.textContent).toContain("gpt-5 · openai");
+ expect(host.textContent).toContain(
+ "ChatGPT 账号配额,未确认本任务使用此套餐",
+ );
+ expect(host.textContent).toContain("本任务用量");
+ expect(host.textContent).not.toContain("本任务价值");
+ });
+ it("shows a mixed task breakdown without presenting estimated value as a charge", () => {
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={{ ...session, totalCostUsd: 2 }}
+ usage={usage}
+ contextUsage={null}
+ detail
+ />,
+ ),
+ );
+ expect(host.textContent).toContain("实际费用$2.00");
+ expect(host.textContent).toContain("估算价值≈ $12.30");
+ expect(host.textContent).toContain("不代表实际扣款");
+ });
+ it("prefers live context counters over a previous detail query", () => {
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={session}
+ usage={usage}
+ contextUsage={{ totalTokens: 90, rawMaxTokens: 100 }}
+ />,
+ ),
+ );
+ expect(host.textContent).toContain("45%");
+ expect(host.textContent).not.toContain("90%");
+ });
+ it.each([0, -1, NaN, Infinity, undefined])(
+ "falls back from an uninitialized window (%s), then accepts live counters including zero",
+ (contextWindow) => {
+ const render = (task: RemoteSession, contextUsage: unknown) =>
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={task}
+ usage={usage}
+ contextUsage={contextUsage}
+ />,
+ ),
+ );
+ const task = { ...session, contextWindow };
+ render(task, null);
+ expect(host.textContent).toContain("暂未获取");
+ render(task, { totalTokens: 90, rawMaxTokens: 0, maxTokens: 100 });
+ expect(host.textContent).toContain("45%");
+ for (const field of [
+ "rawMaxTokens",
+ "maxContextTokens",
+ "contextWindow",
+ ]) {
+ render(task, { totalTokens: 90, [field]: 100 });
+ expect(host.textContent).toContain("45%");
+ }
+ render(
+ { ...task, contextTokens: 0, contextWindow: 200 },
+ { totalTokens: 90, rawMaxTokens: 100 },
+ );
+ expect(host.textContent).toContain("上下文0%");
+ expect(host.textContent).not.toContain("90%");
+ },
+ );
+ it("keeps the overall exhausted weekly limit visible beside the model-specific limit", () => {
+ const account = {
+ ...usage.account!,
+ source: "claude" as const,
+ windows: [
+ { id: "weekly", minutes: 10080, remainingPercent: 0, resetsAt: null },
+ {
+ id: "model-weekly",
+ modelLabel: "Opus",
+ minutes: 10080,
+ remainingPercent: 80,
+ resetsAt: null,
+ },
+ ],
+ };
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={session}
+ usage={{ ...usage, account }}
+ contextUsage={null}
+ />,
+ ),
+ );
+ expect(host.textContent).toContain("剩余 0%");
+ expect(host.textContent).toContain("剩余 80%");
+ });
+ it("keeps last-known quota visible with its observation time when offline", () => {
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={session}
+ usage={{ ...usage, accountFailed: true }}
+ contextUsage={null}
+ />,
+ ),
+ );
+ expect(host.textContent).toContain("剩余 72%");
+ expect(host.textContent).toContain("上次更新");
+ });
+ it("hides quota for custom API routes and does not display missing data as zero", () => {
+ const unavailable = {
+ ...usage,
+ account: { ...usage.account!, source: "api" as const, windows: [] },
+ estimate: null,
+ estimateFailed: true,
+ };
+ act(() =>
+ root.render(
+ <SessionUsageSummary
+ session={session}
+ usage={unavailable}
+ contextUsage={null}
+ />,
+ ),
+ );
+ expect(host.textContent).not.toContain("账号配额");
+ expect(host.textContent).not.toContain("$0.00");
+ expect(host.textContent).toContain("暂未获取");
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 9f1b2f5de4..c8a67d396e 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -54,6 +54,7 @@ describe('mobile maker transport', () => {
'maker:get-new-maker-worktree-branch-pref',
'maker:apply-new-maker-worktree-branch-pref',
'maker:usage:model-pricing',
+ 'local-db:messages:estimatedSessionValue',
'maker:usage:codex-rate-limits',
'maker:usage:codex-rate-limit-reset',
'maker:api-key:present',
diff --git a/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts b/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts
new file mode 100644
index 0000000000..1335d661d6
--- /dev/null
+++ b/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts
@@ -0,0 +1,357 @@
+import { describe, expect, it, vi } from "vitest";
+import type { MobileCodexRateLimitsResult } from "@cindy/maker-shared/device-link-contract";
+import { readSessionMenuAccountUsage } from "@/session/readSessionMenuAccountUsage";
+import type { RemoteSession } from "@/session/types";
+
+const session = {
+ id: "s1",
+ agentKind: "codex",
+ providerId: "openai",
+ model: "gpt-6-astra",
+} as RemoteSession;
+const quota = (): MobileCodexRateLimitsResult => ({
+ account: {
+ email: "[email protected]",
+ accountId: "private-id",
+ planType: "pro",
+ },
+ rateLimits: { primary: { usedPercent: 25, windowMinutes: 300 } },
+ rateLimitsByLimitId: null,
+ rateLimitResetCredits: null,
+ resetOffer: null,
+});
+const reader = () => ({
+ getCodexRateLimits: vi.fn(async () => quota()),
+ getAccountUsage: vi.fn<() => Promise<unknown>>().mockResolvedValue({
+ primary: { usedPercent: 40, windowMinutes: 300 },
+ updatedAt: 1000,
+ }),
+});
+
+describe("existing remote quota compatibility", () => {
+ it("reads Codex quota using only the existing transport methods", async () => {
+ const r = reader();
+ const result = await readSessionMenuAccountUsage(session, r);
+ expect(result).toMatchObject({
+ source: "chatgpt",
+ accountOnly: true,
+ plan: "pro",
+ windows: [{ remainingPercent: 75, minutes: 300 }],
+ });
+ expect(r.getCodexRateLimits).toHaveBeenCalledOnce();
+ expect(r.getAccountUsage).not.toHaveBeenCalled();
+ expect(JSON.stringify(result)).not.toContain("private");
+ });
+
+ it("uses the existing account snapshot on desktops without the official control channel", async () => {
+ const r = reader();
+ r.getCodexRateLimits.mockRejectedValue({ code: "CHANNEL_NOT_ALLOWED" });
+ const result = await readSessionMenuAccountUsage(session, r);
+ expect(r.getAccountUsage).toHaveBeenCalledWith("codex");
+ expect(result).toMatchObject({
+ updatedAt: 1000,
+ windows: [{ remainingPercent: 60 }],
+ });
+ expect(result.accountOnly).toBe(true);
+ });
+
+ it("does not fall back to an old account after the desktop reports an identity change", async () => {
+ const r = reader();
+ const error = { code: "PRECONDITION_FAILED", message: "ACCOUNT_CHANGED" };
+ r.getCodexRateLimits.mockRejectedValue(error);
+ await expect(readSessionMenuAccountUsage(session, r)).rejects.toBe(error);
+ expect(r.getAccountUsage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { providerId: "custom" },
+ { remoteHostId: "ssh" },
+ { agentKind: "cc" as const },
+ ])(
+ "does not substitute Codex account usage for another task route: %o",
+ async (patch) => {
+ const r = reader();
+ const result = await readSessionMenuAccountUsage(
+ { ...session, ...patch },
+ r,
+ );
+ expect(result.windows).toEqual([]);
+ expect(result.amounts).toEqual([]);
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ expect(r.getAccountUsage).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([null, undefined, "", " ", "anthropic", "custom"])(
+ "does not attribute Gateway usage to a Pi task without a confirmed Gateway source: %s",
+ async (providerId) => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue({
+ spend: 12,
+ maxBudget: 100,
+ currency: "CNY",
+ });
+ for (const agentKind of ["pi", "cc"] as const) {
+ for (const model of ["claude-sonnet-4-6", "chatgpt/gpt-5"]) {
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind, providerId, model },
+ r,
+ );
+ expect(result.source).toBe(
+ providerId === "custom" ? "api" : "unavailable",
+ );
+ expect(result.windows).toEqual([]);
+ expect(result.amounts).toEqual([]);
+ }
+ }
+ expect(r.getAccountUsage).not.toHaveBeenCalled();
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ { agentKind: "codex", providerId: "xd", model: "gpt-6-astra" },
+ { agentKind: "pi", providerId: "xd", model: "claude-sonnet-4-6" },
+ { agentKind: "cc", providerId: "xd", model: "claude-sonnet-4-6" },
+ { agentKind: "codex", providerId: null, model: "codex/gpt-6-astra" },
+ ] as const)(
+ "uses existing Gateway cycle usage for a confirmed Gateway route and preserves currency: %o",
+ async (route) => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue({
+ spend: 12,
+ maxBudget: 100,
+ todaySpend: 0,
+ currency: "CNY",
+ fetchedAt: 1000,
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, ...route },
+ r,
+ );
+ expect(result).toMatchObject({
+ source: "gateway",
+ updatedAt: 1000,
+ amounts: [
+ { id: "cycle", amount: 12, limit: 100, currency: "CNY" },
+ { id: "today", amount: 0, currency: "CNY" },
+ ],
+ });
+ expect(r.getAccountUsage).toHaveBeenCalledWith("claude-code");
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ null,
+ { spend: 12, maxBudget: 100, todaySpend: 0 },
+ { spend: NaN, maxBudget: 100, todaySpend: null, currency: "USD" },
+ ])(
+ "does not invent money from incomplete Gateway data: %o",
+ async (payload) => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue(payload);
+ const result = await readSessionMenuAccountUsage(
+ { ...session, providerId: "xd" },
+ r,
+ );
+ expect(result.amounts).toEqual([]);
+ },
+ );
+
+ it("does not infer the default Codex task route from account login", async () => {
+ const result = await readSessionMenuAccountUsage(
+ { ...session, providerId: null },
+ reader(),
+ );
+ expect(result.accountOnly).toBe(true);
+ });
+
+ it("keeps ChatGPT bridge usage separate from Codex app-server usage", async () => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue({
+ primary: { usedPercent: 90 },
+ webSnapshot: {
+ primary: { usedPercent: 20 },
+ planType: "plus",
+ updatedAt: 1000,
+ },
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "pi", model: "chatgpt/gpt-5" },
+ r,
+ );
+ expect(result).toMatchObject({
+ plan: "plus",
+ accountOnly: false,
+ windows: [{ remainingPercent: 80 }],
+ });
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ });
+
+ it("does not substitute CLI usage when the ChatGPT web slot is missing", async () => {
+ const r = reader();
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "pi", model: "chatgpt/gpt-5" },
+ r,
+ );
+ expect(result.windows).toEqual([]);
+ });
+
+ it.each(["official", "legacy"])(
+ "keeps exhausted overall quota alongside the current model quota via %s",
+ async (source) => {
+ const r = reader();
+ const buckets = {
+ codex: {
+ limitId: "codex",
+ secondary: { usedPercent: 100, windowMinutes: 10080 },
+ },
+ spark: {
+ limitId: "spark",
+ limitName: "GPT-5.3-Codex-Spark",
+ primary: { usedPercent: 20, windowMinutes: 300 },
+ },
+ other: {
+ limitId: "other",
+ limitName: "Another Model",
+ primary: { usedPercent: 40 },
+ },
+ };
+ if (source === "official") {
+ r.getCodexRateLimits.mockResolvedValue({
+ ...quota(),
+ rateLimitsByLimitId: buckets,
+ });
+ } else {
+ r.getCodexRateLimits.mockRejectedValue({ code: "CHANNEL_NOT_ALLOWED" });
+ r.getAccountUsage.mockResolvedValue({ appServerBuckets: buckets });
+ }
+ const result = await readSessionMenuAccountUsage(
+ { ...session, model: "gpt-5.3-codex-spark" },
+ r,
+ );
+ expect(result.windows).toEqual([
+ {
+ id: "secondary",
+ remainingPercent: 0,
+ minutes: 10080,
+ resetsAt: null,
+ },
+ {
+ id: "model:primary",
+ modelLabel: "GPT-5.3-Codex-Spark",
+ remainingPercent: 80,
+ minutes: 300,
+ resetsAt: null,
+ },
+ ]);
+ },
+ );
+
+ it("does not duplicate the generic bucket when no model bucket matches", async () => {
+ const r = reader();
+ r.getCodexRateLimits.mockResolvedValue({
+ ...quota(),
+ rateLimitsByLimitId: {
+ __default__: { primary: { usedPercent: 10 } },
+ codex: { limitId: "codex", primary: { usedPercent: 80 } },
+ other: {
+ limitId: "other",
+ limitName: "Another Model",
+ primary: { usedPercent: 40 },
+ },
+ },
+ });
+ const result = await readSessionMenuAccountUsage(session, r);
+ expect(result.windows).toEqual([
+ { id: "primary", remainingPercent: 20, minutes: null, resetsAt: null },
+ ]);
+ });
+
+ it.each(["gpt-5.3-codex-spark", "another-model"])(
+ "only shows a matching model bucket when overall quota is absent: %s",
+ async (model) => {
+ const r = reader();
+ r.getCodexRateLimits.mockResolvedValue({
+ ...quota(),
+ rateLimitsByLimitId: {
+ spark: {
+ limitId: "spark",
+ limitName: "GPT-5.3-Codex-Spark",
+ primary: { usedPercent: 20 },
+ },
+ },
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, model },
+ r,
+ );
+ expect(result.windows).toEqual(
+ model === "another-model"
+ ? []
+ : [
+ {
+ id: "model:primary",
+ modelLabel: "GPT-5.3-Codex-Spark",
+ remainingPercent: 80,
+ minutes: null,
+ resetsAt: null,
+ },
+ ],
+ );
+ },
+ );
+
+ it("retains the oldest bucket timestamp when combining legacy observations", async () => {
+ const r = reader();
+ r.getCodexRateLimits.mockRejectedValue({ code: "CHANNEL_NOT_ALLOWED" });
+ r.getAccountUsage.mockResolvedValue({
+ updatedAt: 3000,
+ appServerBuckets: {
+ codex: { updatedAt: 1000, primary: { usedPercent: 100 } },
+ spark: {
+ limitName: "GPT-5.3-Codex-Spark",
+ updatedAt: 2000,
+ primary: { usedPercent: 20 },
+ },
+ },
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, model: "gpt-5.3-codex-spark" },
+ r,
+ );
+ expect(result.updatedAt).toBe(1000);
+ expect(result.windows).toHaveLength(2);
+ });
+
+ it("keeps both buckets while omitting expired observations", async () => {
+ const r = reader();
+ r.getCodexRateLimits.mockResolvedValue({
+ ...quota(),
+ rateLimitsByLimitId: {
+ codex: { limitId: "codex", primary: { usedPercent: 90 } },
+ spark: {
+ limitId: "spark",
+ limitName: "GPT-5.3-Codex-Spark",
+ primary: { usedPercent: 10 },
+ secondary: { usedPercent: 50, resetsAt: 1 },
+ },
+ },
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, model: "gpt-5.3-codex-spark" },
+ r,
+ );
+ expect(result.windows).toEqual([
+ { id: "primary", remainingPercent: 10, minutes: null, resetsAt: null },
+ {
+ id: "model:primary",
+ modelLabel: "GPT-5.3-Codex-Spark",
+ remainingPercent: 90,
+ minutes: null,
+ resetsAt: null,
+ },
+ ]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
new file mode 100644
index 0000000000..e3548c94a3
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
@@ -0,0 +1,87 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import { i18n } from "@/i18n";
+import {
+ accountUsageRows,
+ formatSessionUsageMoney,
+ sessionUsageAmounts,
+} from "@/session/sessionUsagePresentation";
+import type { SessionMenuAccountUsage } from "@/session/readSessionMenuAccountUsage";
+import type { RemoteMoney } from "@/session/remoteMoney";
+
+beforeAll(async () => {
+ await i18n.changeLanguage("zh-CN");
+});
+const money = (
+ amount: number,
+ currency: "USD" | "CNY" = "USD",
+ estimate = false,
+): RemoteMoney => ({
+ amount,
+ currency,
+ approximate: estimate,
+ kind: estimate ? "value-estimate" : "actual-cost",
+});
+describe("task menu usage presentation", () => {
+ it("includes the full persisted subscription estimate in mixed task usage", () => {
+ const result = sessionUsageAmounts(
+ { totalMoney: money(2) },
+ money(12, "USD", true),
+ );
+ expect(result.total).toEqual(money(14, "USD", true));
+ expect(result.actual).toEqual(money(2));
+ expect(result.estimate).toEqual(money(12, "USD", true));
+ });
+ it("does not combine currencies or label a value estimate as actual cost", () => {
+ const result = sessionUsageAmounts(
+ { totalMoney: money(2, "CNY") },
+ money(12, "USD", true),
+ );
+ expect(result.total).toBeNull();
+ expect(result.mixed).toBe(true);
+ expect(formatSessionUsageMoney(result.estimate!)).toBe("≈ $12.00");
+ });
+ it("prefers structured money over legacy USD and preserves small nonzero values", () => {
+ expect(
+ sessionUsageAmounts(
+ { totalMoney: money(3, "CNY"), totalCostUsd: 10 },
+ null,
+ ).total,
+ ).toEqual(money(3, "CNY"));
+ expect(formatSessionUsageMoney(money(0.001))).toBe("<$0.01");
+ expect(sessionUsageAmounts({ totalCostUsd: NaN }, null).total).toBeNull();
+ });
+ it("shows missing usage separately from zero balance", () => {
+ expect(sessionUsageAmounts({}, null).total).toBeNull();
+ expect(accountUsageRows(null, i18n.t, "zh-CN")).toEqual([]);
+ const account: SessionMenuAccountUsage = {
+ source: "gateway",
+ plan: null,
+ updatedAt: 1,
+ windows: [],
+ amounts: [{ id: "balance", amount: 0, currency: "CNY" }],
+ };
+ expect(accountUsageRows(account, i18n.t, "zh-CN")[0]).toMatchObject({
+ value: "¥0.00",
+ warning: true,
+ });
+ });
+ it("uses real window periods, warns at low remaining, and marks expired observations", () => {
+ const account: SessionMenuAccountUsage = {
+ source: "chatgpt",
+ plan: "pro",
+ updatedAt: 1000,
+ amounts: [],
+ windows: [
+ { id: "a", minutes: 180, remainingPercent: 8, resetsAt: 2000 },
+ { id: "b", minutes: 10080, remainingPercent: 0, resetsAt: 1 },
+ ],
+ };
+ const rows = accountUsageRows(account, i18n.t, "zh-CN", 1_000_000);
+ expect(rows[0]).toMatchObject({
+ label: "3 小时",
+ value: "剩余 8%",
+ warning: true,
+ });
+ expect(rows[1]).toMatchObject({ value: "等待刷新", warning: false });
+ });
+});
diff --git a/apps/mobile/src/__tests__/useSessionMenuContextUsage.test.tsx b/apps/mobile/src/__tests__/useSessionMenuContextUsage.test.tsx
new file mode 100644
index 0000000000..8c25d433e6
--- /dev/null
+++ b/apps/mobile/src/__tests__/useSessionMenuContextUsage.test.tsx
@@ -0,0 +1,155 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useSessionMenuContextUsage } from "@/session/useSessionMenuContextUsage";
+import type { RemoteSession } from "@/session/types";
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+});
+const task = {
+ id: "a",
+ deviceLinkDeviceId: "host",
+ model: "gpt-5",
+ providerId: "openai",
+ agentKind: "codex",
+ contextTokens: 20,
+ contextWindow: 0,
+} as RemoteSession;
+function deferred() {
+ let resolve!: (value: unknown) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<unknown>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+function harness() {
+ const reader = {
+ getContextUsage:
+ vi.fn<(id: string, opts?: Record<string, unknown>) => Promise<unknown>>(),
+ };
+ const onError = vi.fn();
+ let value!: ReturnType<typeof useSessionMenuContextUsage>;
+ function Probe({
+ session,
+ inspecting,
+ }: {
+ session: RemoteSession;
+ inspecting: boolean;
+ }) {
+ value = useSessionMenuContextUsage(session, reader, inspecting, onError);
+ return null;
+ }
+ root = createRoot(document.createElement("div"));
+ return {
+ reader,
+ onError,
+ get value() {
+ return value;
+ },
+ async render(session = task, inspecting = true) {
+ await act(async () =>
+ root!.render(createElement(Probe, { session, inspecting })),
+ );
+ },
+ };
+}
+
+describe("menu context snapshot ownership", () => {
+ it.each([
+ { model: "gpt-other" },
+ { providerId: "custom" },
+ { agentKind: "pi" },
+ { id: "b" },
+ { deviceLinkDeviceId: "other-host" },
+ { remoteHostId: "ssh" },
+ { clearedAt: 1 },
+ { runtimeGeneration: 2 },
+ ] as Partial<RemoteSession>[])(
+ "invalidates the window and reads again for %o while inspecting",
+ async (change) => {
+ const h = harness();
+ h.reader.getContextUsage.mockResolvedValueOnce({ rawMaxTokens: 100 });
+ await h.render();
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 100 });
+ const next = deferred();
+ h.reader.getContextUsage.mockReturnValueOnce(next.promise);
+ await h.render({ ...task, ...change });
+ expect(h.value.contextUsage).toBeNull();
+ expect(h.value.contextLoading).toBe(true);
+ expect(h.reader.getContextUsage).toHaveBeenCalledTimes(2);
+ await act(async () => next.resolve({ rawMaxTokens: 200 }));
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 200 });
+ },
+ );
+
+ it("does not inspect the primary menu or restart on live counter pushes", async () => {
+ const h = harness();
+ await h.render(task, false);
+ expect(h.reader.getContextUsage).not.toHaveBeenCalled();
+ h.reader.getContextUsage.mockResolvedValue({ rawMaxTokens: 100 });
+ await h.render();
+ await h.render({ ...task, contextTokens: 40 });
+ expect(h.reader.getContextUsage).toHaveBeenCalledOnce();
+ await h.render(task, false);
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 100 });
+ await h.render({ ...task, model: "other" }, false);
+ await h.render(task, false);
+ expect(h.value.contextUsage).toBeNull();
+ expect(h.reader.getContextUsage).toHaveBeenCalledOnce();
+ });
+
+ it("rejects A-B-A late successes and failures without ending the current loading state", async () => {
+ const h = harness();
+ const oldA = deferred(),
+ oldB = deferred(),
+ newA = deferred();
+ h.reader.getContextUsage
+ .mockReturnValueOnce(oldA.promise)
+ .mockReturnValueOnce(oldB.promise)
+ .mockReturnValueOnce(newA.promise);
+ await h.render();
+ await h.render({ ...task, model: "other" });
+ await h.render();
+ await act(async () => {
+ oldA.resolve({ rawMaxTokens: 100 });
+ oldB.reject(new Error("old failure"));
+ });
+ expect(h.value.contextUsage).toBeNull();
+ expect(h.value.contextLoading).toBe(true);
+ expect(h.onError.mock.calls.every(([error]) => error === null)).toBe(true);
+ await act(async () => newA.resolve({ rawMaxTokens: 200 }));
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 200 });
+ expect(h.value.contextLoading).toBe(false);
+ });
+
+ it("retains current data on refresh failure without retry loops and cancels reads when info closes", async () => {
+ const h = harness();
+ h.reader.getContextUsage.mockResolvedValueOnce({ rawMaxTokens: 100 });
+ await h.render();
+ h.reader.getContextUsage.mockRejectedValueOnce(new Error("offline"));
+ await act(async () => h.value.refresh());
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 100 });
+ expect(h.value.contextLoading).toBe(false);
+ expect(h.onError).toHaveBeenLastCalledWith(
+ expect.stringContaining("offline"),
+ );
+ expect(h.reader.getContextUsage).toHaveBeenCalledTimes(2);
+ const pending = deferred();
+ h.reader.getContextUsage.mockReturnValueOnce(pending.promise);
+ await act(async () => h.value.refresh());
+ await h.render(task, false);
+ await act(async () => pending.resolve({ rawMaxTokens: 300 }));
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 100 });
+ expect(h.value.contextLoading).toBe(false);
+ h.reader.getContextUsage.mockResolvedValueOnce({ rawMaxTokens: 400 });
+ await h.render();
+ expect(h.value.contextUsage).toEqual({ rawMaxTokens: 400 });
+ });
+});
diff --git a/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx b/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
new file mode 100644
index 0000000000..ae9bc7acaf
--- /dev/null
+++ b/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
@@ -0,0 +1,243 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ useSessionMenuUsage,
+ type SessionMenuUsageReader,
+} from "@/session/useSessionMenuUsage";
+import type { RemoteSession } from "@/session/types";
+import type { MobileCodexRateLimitsResult } from "@cindy/maker-shared/device-link-contract";
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ vi.useRealTimers();
+});
+const account: MobileCodexRateLimitsResult = {
+ account: { email: null, accountId: null, planType: "pro" },
+ rateLimits: { primary: { usedPercent: 25, windowMinutes: 300 } },
+ rateLimitsByLimitId: null,
+ rateLimitResetCredits: null,
+ resetOffer: null,
+};
+const session = (id: string): RemoteSession =>
+ ({
+ id,
+ model: "gpt-5",
+ providerId: "openai",
+ agentKind: "codex",
+ deviceLinkDeviceId: "host",
+ }) as RemoteSession;
+function reader(): SessionMenuUsageReader {
+ return {
+ getCodexRateLimits: vi.fn(async () => account),
+ getAccountUsage: vi.fn(async () => {
+ throw new Error("unavailable");
+ }),
+ getSessionEstimatedValue: vi.fn(async () => ({
+ totalValueMoney: {
+ amount: 12,
+ currency: "USD",
+ approximate: true,
+ kind: "value-estimate",
+ },
+ })),
+ };
+}
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { resolve, promise };
+}
+function harness(r: SessionMenuUsageReader) {
+ let value!: ReturnType<typeof useSessionMenuUsage>;
+ function Probe({
+ task,
+ visible,
+ snapshot,
+ }: {
+ task: RemoteSession;
+ visible: boolean;
+ snapshot: MobileCodexRateLimitsResult | null;
+ }) {
+ value = useSessionMenuUsage(task, r, visible, snapshot);
+ return null;
+ }
+ root = createRoot(document.createElement("div"));
+ return {
+ get value() {
+ return value;
+ },
+ render: async (
+ task = session("a"),
+ visible = true,
+ snapshot: MobileCodexRateLimitsResult | null = null,
+ ) => {
+ await act(async () =>
+ root!.render(createElement(Probe, { task, visible, snapshot })),
+ );
+ },
+ };
+}
+
+describe("menu usage refresh lifecycle", () => {
+ it("reads on opening the primary sheet, polls only while visible, and retains values on reopening", async () => {
+ vi.useFakeTimers();
+ const r = reader();
+ const h = harness(r);
+ await h.render(session("a"), false);
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ await h.render();
+ expect(h.value.estimate?.amount).toBe(12);
+ expect(r.getCodexRateLimits).toHaveBeenCalledOnce();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+ expect(r.getCodexRateLimits).toHaveBeenCalledTimes(2);
+ await h.render(session("a"), false);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(r.getCodexRateLimits).toHaveBeenCalledTimes(2);
+ await h.render();
+ expect(h.value.account?.plan).toBe("pro");
+ });
+ it("refreshes on the reset snapshot and rejects a late pre-reset response", async () => {
+ const r = reader();
+ const h = harness(r);
+ const exhausted = {
+ ...account,
+ rateLimits: { primary: { usedPercent: 100 } },
+ };
+ const reset = { ...account, rateLimits: { primary: { usedPercent: 0 } } };
+ vi.mocked(r.getCodexRateLimits).mockResolvedValue(exhausted);
+ await h.render(session("a"), true, exhausted);
+ expect(h.value.account?.windows[0].remainingPercent).toBe(0);
+ const pending = deferred<MobileCodexRateLimitsResult>();
+ vi.mocked(r.getCodexRateLimits).mockReturnValueOnce(pending.promise);
+ await act(async () => h.value.refresh());
+ vi.mocked(r.getCodexRateLimits).mockResolvedValue(reset);
+ await h.render(session("a"), true, reset);
+ expect(h.value.account?.windows[0].remainingPercent).toBe(100);
+ await act(async () => pending.resolve(exhausted));
+ expect(h.value.account?.windows[0].remainingPercent).toBe(100);
+ await h.render(session("a"), true, reset);
+ expect(r.getCodexRateLimits).toHaveBeenCalledTimes(3);
+ });
+ it("defers control snapshot refresh while hidden and discards results after closing", async () => {
+ const r = reader();
+ const h = harness(r);
+ await h.render(session("a"), false, account);
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ const pending = deferred<MobileCodexRateLimitsResult>();
+ vi.mocked(r.getCodexRateLimits).mockReturnValueOnce(pending.promise);
+ await h.render(session("a"), true, account);
+ await h.render(session("a"), false, { ...account });
+ await act(async () => pending.resolve(account));
+ expect(h.value.account).toBeNull();
+ expect(r.getCodexRateLimits).toHaveBeenCalledTimes(1);
+ await h.render(session("a"), true, account);
+ expect(h.value.account?.plan).toBe("pro");
+ expect(r.getCodexRateLimits).toHaveBeenCalledTimes(2);
+ });
+ it("drops late responses from the previous task and does not show its values in the next task", async () => {
+ const pending = deferred<MobileCodexRateLimitsResult>();
+ const r = reader();
+ vi.mocked(r.getCodexRateLimits).mockImplementationOnce(
+ () => pending.promise,
+ );
+ const h = harness(r);
+ await h.render();
+ await h.render(session("b"));
+ await act(async () =>
+ pending.resolve({
+ ...account,
+ account: { ...account.account, planType: "old-account" },
+ }),
+ );
+ expect(h.value.account?.plan).toBe("pro");
+ });
+ it("clears account data when the same task switches provider and rejects its old in-flight result", async () => {
+ const pending = deferred<MobileCodexRateLimitsResult>();
+ const r = reader();
+ const h = harness(r);
+ await h.render();
+ vi.mocked(r.getCodexRateLimits).mockReturnValueOnce(pending.promise);
+ await act(async () => h.value.refresh());
+ await h.render({ ...session("a"), providerId: "custom" });
+ expect(h.value.account?.source).toBe("api");
+ await h.render({ ...session("a"), providerId: "xai" });
+ await act(async () =>
+ pending.resolve({
+ ...account,
+ account: { ...account.account, planType: "wrong-provider" },
+ }),
+ );
+ expect(h.value.account?.source).toBe("unavailable");
+ expect(h.value.account?.windows).toEqual([]);
+ });
+ it("does not reuse web quota across an unresolved source and a Gateway switch", async () => {
+ const r = reader();
+ const pending = deferred<unknown>();
+ vi.mocked(r.getAccountUsage).mockReturnValueOnce(pending.promise);
+ const h = harness(r);
+ const task = {
+ ...session("a"),
+ agentKind: "pi" as const,
+ model: "chatgpt/gpt-5",
+ };
+ await h.render(task);
+ await h.render({ ...task, providerId: null });
+ expect(h.value.account?.source).toBe("unavailable");
+ expect(r.getAccountUsage).toHaveBeenCalledTimes(1);
+ vi.mocked(r.getAccountUsage).mockResolvedValue({
+ spend: 12,
+ maxBudget: 100,
+ currency: "CNY",
+ });
+ await h.render({ ...task, providerId: "xd" });
+ await act(async () =>
+ pending.resolve({ webSnapshot: { primary: { usedPercent: 20 } } }),
+ );
+ expect(h.value.account?.source).toBe("gateway");
+ expect(h.value.account?.windows).toEqual([]);
+ await h.render({ ...task, providerId: null });
+ expect(h.value.account?.source).toBe("unavailable");
+ expect(h.value.account?.amounts).toEqual([]);
+ expect(r.getAccountUsage).toHaveBeenCalledTimes(2);
+ });
+ it("preserves the last successful values with failure metadata when disconnected", async () => {
+ const r = reader();
+ const h = harness(r);
+ await h.render();
+ vi.mocked(r.getCodexRateLimits).mockRejectedValue(
+ new Error("DEVICE_OFFLINE"),
+ );
+ vi.mocked(r.getSessionEstimatedValue).mockRejectedValue(
+ new Error("DEVICE_OFFLINE"),
+ );
+ await act(async () => h.value.refresh());
+ expect(h.value.account?.plan).toBe("pro");
+ expect(h.value.estimate?.amount).toBe(12);
+ expect(h.value.accountFailed).toBe(true);
+ expect(h.value.estimateFailed).toBe(true);
+ expect(h.value.loading).toBe(false);
+ });
+ it("allows task value to load even when both existing quota reads fail", async () => {
+ const r = reader();
+ vi.mocked(r.getCodexRateLimits).mockRejectedValue(
+ new Error("CHANNEL_NOT_ALLOWED"),
+ );
+ const h = harness(r);
+ await h.render();
+ expect(h.value.account).toBeNull();
+ expect(h.value.accountFailed).toBe(true);
+ expect(h.value.estimate?.amount).toBe(12);
+ expect(h.value.loading).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 559e0af62c..67447f47e2 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -460,6 +460,7 @@ export interface MobileMakerTransport {
* 网关配额。老被控端 CHANNEL_NOT_ALLOWED → 调用方隐藏限额区块。
*/
getAccountUsage(agentKind: MobileAgentKind): Promise<unknown>;
+ getSessionEstimatedValue(sessionId: string): Promise<{ totalValueMoney?: unknown; totalValueUsd?: number }>;
/** Codex app-server authoritative windows plus banked reset credits and a bound reset offer. */
getCodexRateLimits(): Promise<MobileCodexRateLimitsResult>;
/** Consume the desktop-issued offer; retries must pass the same idempotency key. */
@@ -736,6 +737,7 @@ export function createMobileMakerTransport({
setExtraDirs: (sessionId, dirs) => call('maker:set-extra-dirs', [sessionId, dirs]),
getModelPricing: () => call('maker:usage:model-pricing'),
getAccountUsage: (agentKind) => call('maker:usage:account', [agentKind]),
+ getSessionEstimatedValue: (sessionId) => call('local-db:messages:estimatedSessionValue', [sessionId]),
getCodexRateLimits: () => call('maker:usage:codex-rate-limits'),
resetCodexRateLimits: (idempotencyKey) => (
call('maker:usage:codex-rate-limit-reset', [idempotencyKey])
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index da5e721e80..c484dd4370 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -394,6 +394,37 @@
"system": "System"
},
"usageSection": "Usage",
+ "usage": {
+ "quota": "Quota",
+ "week": "This week",
+ "hours": "{{count}} hours",
+ "minutes": "{{count}} minutes",
+ "remaining": "{{percent}}% remaining",
+ "resets": "Resets {{time}}",
+ "awaitingRefresh": "Awaiting refresh",
+ "balance": "Available balance",
+ "cycle": "Used this cycle",
+ "today": "Used today",
+ "unavailable": "Unavailable",
+ "quotaUnavailable": "Account quota unavailable",
+ "accountOnly": "ChatGPT account quota; this task's use of this plan is unconfirmed",
+ "lastUpdated": "Last updated {{time}}",
+ "taskUsage": "Task usage",
+ "taskValue": "Task value",
+ "taskCost": "Task cost",
+ "actualCost": "Actual cost",
+ "estimatedValue": "Estimated value",
+ "totalTokens": "Total tokens",
+ "seeDetails": "View breakdown",
+ "valueUnavailable": "Some task value is unavailable",
+ "valueExplanation": "Value is estimated from usage and reference prices. It is not an actual charge.",
+ "source": {
+ "chatgpt": "ChatGPT subscription",
+ "claude": "Claude subscription",
+ "xai": "SuperGrok subscription",
+ "gateway": "Cindy AI"
+ }
+ },
"refreshContextUsage": "Refresh context usage",
"currentSessionSpend": "This session",
"noSessionSpend": "No session usage yet",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index dd47a0dedd..fa14b799fe 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -394,6 +394,37 @@
"system": "システム"
},
"usageSection": "使用量",
+ "usage": {
+ "quota": "クォータ",
+ "week": "今週",
+ "hours": "{{count}} 時間",
+ "minutes": "{{count}} 分",
+ "remaining": "残り {{percent}}%",
+ "resets": "{{time}} にリセット",
+ "awaitingRefresh": "更新待ち",
+ "balance": "利用可能残高",
+ "cycle": "今サイクルの使用額",
+ "today": "今日の使用額",
+ "unavailable": "未取得",
+ "quotaUnavailable": "アカウントのクォータを取得できません",
+ "accountOnly": "ChatGPT アカウントのクォータ。このタスクがこのプランを使うかは未確認です",
+ "lastUpdated": "最終更新 {{time}}",
+ "taskUsage": "タスクの使用量",
+ "taskValue": "タスクの価値",
+ "taskCost": "タスクの費用",
+ "actualCost": "実際の費用",
+ "estimatedValue": "推定価値",
+ "totalTokens": "累計トークン",
+ "seeDetails": "内訳を見る",
+ "valueUnavailable": "一部のタスク価値を取得できません",
+ "valueExplanation": "価値は使用量と参考単価による推定であり、実際の請求額ではありません。",
+ "source": {
+ "chatgpt": "ChatGPT サブスクリプション",
+ "claude": "Claude サブスクリプション",
+ "xai": "SuperGrok サブスクリプション",
+ "gateway": "Cindy AI"
+ }
+ },
"refreshContextUsage": "コンテキスト使用量を更新",
"currentSessionSpend": "今回のセッション",
"noSessionSpend": "セッションの使用量はまだありません",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index d1493becbc..29e1299cc8 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -394,6 +394,37 @@
"system": "시스템"
},
"usageSection": "사용량",
+ "usage": {
+ "quota": "할당량",
+ "week": "이번 주",
+ "hours": "{{count}}시간",
+ "minutes": "{{count}}분",
+ "remaining": "{{percent}}% 남음",
+ "resets": "{{time}}에 초기화",
+ "awaitingRefresh": "새로고침 대기 중",
+ "balance": "사용 가능한 잔액",
+ "cycle": "이번 주기 사용액",
+ "today": "오늘 사용액",
+ "unavailable": "가져오지 못함",
+ "quotaUnavailable": "계정 할당량을 가져오지 못했습니다",
+ "accountOnly": "ChatGPT 계정 할당량이며, 이 작업이 해당 요금제를 사용하는지는 확인되지 않았습니다",
+ "lastUpdated": "마지막 업데이트 {{time}}",
+ "taskUsage": "작업 사용량",
+ "taskValue": "작업 가치",
+ "taskCost": "작업 비용",
+ "actualCost": "실제 비용",
+ "estimatedValue": "추정 가치",
+ "totalTokens": "누적 토큰",
+ "seeDetails": "내역 보기",
+ "valueUnavailable": "일부 작업 가치를 가져오지 못했습니다",
+ "valueExplanation": "가치는 사용량과 참고 단가로 추정하며 실제 청구액이 아닙니다.",
+ "source": {
+ "chatgpt": "ChatGPT 구독",
+ "claude": "Claude 구독",
+ "xai": "SuperGrok 구독",
+ "gateway": "Cindy AI"
+ }
+ },
"refreshContextUsage": "컨텍스트 사용량 새로 고침",
"currentSessionSpend": "이번 세션",
"noSessionSpend": "아직 세션 사용량이 없습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index f51575c720..76c0575c1d 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -394,6 +394,37 @@
"system": "系统"
},
"usageSection": "用量",
+ "usage": {
+ "quota": "配额",
+ "week": "本周",
+ "hours": "{{count}} 小时",
+ "minutes": "{{count}} 分钟",
+ "remaining": "剩余 {{percent}}%",
+ "resets": "{{time}} 重置",
+ "awaitingRefresh": "等待刷新",
+ "balance": "可用余额",
+ "cycle": "本周期已用",
+ "today": "今日已用",
+ "unavailable": "暂未获取",
+ "quotaUnavailable": "暂未获取账号配额",
+ "accountOnly": "ChatGPT 账号配额,未确认本任务使用此套餐",
+ "lastUpdated": "上次更新 {{time}}",
+ "taskUsage": "本任务用量",
+ "taskValue": "本任务价值",
+ "taskCost": "本任务费用",
+ "actualCost": "实际费用",
+ "estimatedValue": "估算价值",
+ "totalTokens": "累计 Token",
+ "seeDetails": "查看拆分",
+ "valueUnavailable": "部分任务价值暂未获取",
+ "valueExplanation": "价值按用量和参考单价估算,不代表实际扣款。",
+ "source": {
+ "chatgpt": "ChatGPT 订阅",
+ "claude": "Claude 订阅",
+ "xai": "SuperGrok 订阅",
+ "gateway": "Cindy AI"
+ }
+ },
"refreshContextUsage": "刷新上下文用量",
"currentSessionSpend": "本次任务",
"noSessionSpend": "暂无任务用量",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index 56a73144aa..ee95e7c28e 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -394,6 +394,37 @@
"system": "系統"
},
"usageSection": "用量",
+ "usage": {
+ "quota": "配額",
+ "week": "本週",
+ "hours": "{{count}} 小時",
+ "minutes": "{{count}} 分鐘",
+ "remaining": "剩餘 {{percent}}%",
+ "resets": "{{time}} 重設",
+ "awaitingRefresh": "等待重新整理",
+ "balance": "可用餘額",
+ "cycle": "本週期已用",
+ "today": "今日已用",
+ "unavailable": "暫未取得",
+ "quotaUnavailable": "暫未取得帳號配額",
+ "accountOnly": "ChatGPT 帳號配額,尚未確認本任務使用此方案",
+ "lastUpdated": "上次更新 {{time}}",
+ "taskUsage": "本任務用量",
+ "taskValue": "本任務價值",
+ "taskCost": "本任務費用",
+ "actualCost": "實際費用",
+ "estimatedValue": "估算價值",
+ "totalTokens": "累計 Token",
+ "seeDetails": "查看明細",
+ "valueUnavailable": "部分任務價值暫未取得",
+ "valueExplanation": "價值依用量和參考單價估算,不代表實際扣款。",
+ "source": {
+ "chatgpt": "ChatGPT 訂閱",
+ "claude": "Claude 訂閱",
+ "xai": "SuperGrok 訂閱",
+ "gateway": "Cindy AI"
+ }
+ },
"refreshContextUsage": "重新整理上下文用量",
"currentSessionSpend": "本次任務",
"noSessionSpend": "暫無任務用量",
diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsx
index b39feb3c8e..422dc29e7c 100644
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@ -4,8 +4,8 @@
* 形态对齐「+ 号」Context 面板 / 模型浮窗:SheetModal 外壳(背板淡入淡出 + 面板滑入
* 滑出)+ SheetSurface(把手
* half/full/下拉 dismiss),**单 Modal 双 Surface 叠层**:一级 = 详情头部(状态 chip /
- * 元信息 / 用量摘要)+ 操作列表(重命名 / 复制链接 / 置顶 / 归档 / 删除)+「会话信息」入口;
- * 二级 = 会话信息(用量 / 工作目录 / 附加引用目录),translateY 滑入,返回键 /
+ * 元信息)+ 任务信息摘要卡入口 + 操作列表(重命名 / 复制链接 / 置顶 / 归档 / 删除);
+ * 二级 = 任务信息(用量 / 工作目录 / 附加引用目录),translateY 滑入,返回键 /
* backdrop 先回一级再关浮窗(settleSessionMenuBack)。刻意不用嵌套 Modal,原因同
* ModelPickerSheet 头注释(iOS 同级双 Modal 不显示、Android 返回键派发不可控)。
*
@@ -21,7 +21,6 @@ import {
ChevronRight,
Copy,
GitBranch,
- Info,
Link2,
Pencil,
Pin,
@@ -44,7 +43,7 @@ import { useTranslation } from 'react-i18next';
import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';
import { Text, TextInput } from '@/components/AppText';
import { MainWindowActionGroup } from '@/components/MobilePrimitives';
-import type { RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';
+import type { MobileMakerTransport, RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
@@ -59,8 +58,10 @@ import {
summarizeAccountRateLimits,
summarizeCodexRateLimitReset,
summarizeContextUsage,
- summarizeSessionSpend,
} from '@/session/sessionControls';
+import { useSessionMenuUsage, type SessionMenuUsageReader } from '@/session/useSessionMenuUsage';
+import { useSessionMenuContextUsage } from '@/session/useSessionMenuContextUsage';
+import { SessionUsageSummary } from '@/session/SessionUsageSummary';
import {
addSessionExtraDir,
aiRenameFailureText,
@@ -95,15 +96,14 @@ export interface SessionExtraDirBrowserState {
}
export interface SessionMenuSheetProps {
+ usageReader: SessionMenuUsageReader & Pick<MobileMakerTransport, 'getContextUsage'>;
visible: boolean;
/** 打开时落在哪个视图(header 用量入口可直达 info)。 */
initialView: SessionMenuView;
session: RemoteSession;
busy: boolean;
readOnlyReason?: string | null;
- contextUsage: unknown;
- contextLoading: boolean;
- onRefreshContextUsage(): void;
+ onContextError(error: string | null): void;
/**
* 账号级限额快照(被控端 `maker:usage:account` 原始返回,unknown 防御解析)。
* 父级只对 Codex 会话传数据;null = 不显示「账号限额」区(通道不支持 / 拉取失败 /
@@ -136,14 +136,13 @@ export interface SessionMenuSheetProps {
}
export function SessionMenuSheet({
+ usageReader,
visible,
initialView,
session,
busy,
readOnlyReason,
- contextUsage,
- contextLoading,
- onRefreshContextUsage,
+ onContextError,
accountUsage,
codexRateLimits,
codexResetBusy,
@@ -168,10 +167,20 @@ export function SessionMenuSheet({
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
+ const menuUsage = useSessionMenuUsage(session, usageReader, visible, codexRateLimits);
const { height: windowHeight } = useWindowDimensions();
const insets = useSafeAreaInsets();
- const [view, setView] = useState<SessionMenuView>('menu');
+ const [view, setView] = useState<SessionMenuView>(initialView);
+ const [opening, setOpening] = useState({ visible, initialView });
+ // Reset before effects: reopening the primary menu must not inspect the old info view.
+ if (opening.visible !== visible || opening.initialView !== initialView) {
+ setOpening({ visible, initialView });
+ if (visible) setView(initialView);
+ }
+ const { contextUsage, contextLoading, refresh: onRefreshContextUsage } = useSessionMenuContextUsage(
+ session, usageReader, visible && view === 'info', onContextError,
+ );
const [primarySnap, setPrimarySnap] = useState<ContextSheetSnap>('half');
const [secondarySnap, setSecondarySnap] = useState<ContextSheetSnap>('half');
const [renaming, setRenaming] = useState(false);
@@ -212,7 +221,6 @@ export function SessionMenuSheet({
// 不触发重置,见上方 windowHeightRef 注释。
useEffect(() => {
if (!visible) return;
- setView(initialView);
setPrimarySnap('half');
setSecondarySnap('half');
renameSeqRef.current += 1;
@@ -238,14 +246,6 @@ export function SessionMenuSheet({
if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
}, []);
- // 进入 info 视图且还没有上下文数据时自动拉一次(免去手点「刷新」的空态)。
- // 依赖刻意只挂 visible/view:contextUsage 到货或 loading 翻转不应重复触发拉取。
- useEffect(() => {
- if (!visible || view !== 'info') return;
- if (contextUsage || contextLoading) return;
- onRefreshContextUsage();
- }, [visible, view]); // eslint-disable-line react-hooks/exhaustive-deps
-
// 账号限额拉取:每次进入 info 视图都拉(被控端通道 cached-first,重复拉便宜且
// 能带回后台刷新的新快照,不做「有数据就短路」——否则打开期间数据永不更新);
// session.id 进依赖:面板开着原地切会话时父组件会清空快照,必须跟着重新拉取
@@ -427,7 +427,6 @@ export function SessionMenuSheet({
onSetExtraDirs(removeSessionExtraDir(session.extraDirs, path));
}, [onSetExtraDirs, session.extraDirs]);
- const spend = summarizeSessionSpend(session, mobilePresentationLocalizer);
const usage = summarizeContextUsage(contextUsage, mobilePresentationLocalizer);
// 账号限额行:窗口构成完全跟随被控端上游接口返回(不假设 5h/周),解析不出内容 → null 不渲染。
// 陈旧判定依赖当前时间: 重开面板要重算, 面板长开跨过失效时刻也要重算
@@ -558,20 +557,10 @@ export function SessionMenuSheet({
{readOnlyReason}
</Text>
) : null}
- {header.usageSummary ? (
- <Pressable
- accessibilityLabel={t('session.menu.viewUsageDetail')}
- accessibilityRole="button"
- onPress={openInfo}
- style={({ pressed }) => [styles.usageRow, pressed && styles.pressed]}
- testID="session.menuUsageRow"
- >
- <Text numberOfLines={1} style={styles.usageText}>{header.usageSummary}</Text>
- <ChevronRight color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- </Pressable>
- ) : null}
</View>
+ <SessionUsageSummary session={session} usage={menuUsage} contextUsage={contextUsage} onPress={openInfo} />
+
<View style={styles.actionGroup}>
{mainActions.map((action) => (
<MenuActionRow
@@ -587,8 +576,8 @@ export function SessionMenuSheet({
))}
</View>
- <View style={styles.actionGroup}>
- {session.agentKind === 'pi' && onOpenSessionTree ? (
+ {session.agentKind === 'pi' && onOpenSessionTree ? (
+ <View style={styles.actionGroup}>
<MenuActionRow
icon={GitBranch}
label={t('session.menu.branches')}
@@ -596,15 +585,8 @@ export function SessionMenuSheet({
testID="session.branchesButton"
trailing={<ChevronRight color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
/>
- ) : null}
- <MenuActionRow
- icon={Info}
- label={t('session.menu.sessionInfo')}
- onPress={openInfo}
- testID="session.infoButton"
- trailing={<ChevronRight color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
- />
- </View>
+ </View>
+ ) : null}
{deleteAction ? (
<View style={styles.actionGroup}>
@@ -625,6 +607,7 @@ export function SessionMenuSheet({
const infoContent = (
<View style={styles.infoBody} testID="session.infoSheetBody">
+ <SessionUsageSummary session={session} usage={menuUsage} contextUsage={contextUsage} detail />
<View style={styles.infoSection}>
<View style={styles.infoSectionHeader}>
<Text style={styles.infoSectionTitle}>{t('session.menu.usageSection')}</Text>
@@ -632,7 +615,7 @@ export function SessionMenuSheet({
accessibilityLabel={t('session.menu.refreshContextUsage')}
accessibilityRole="button"
disabled={contextLoading}
- onPress={onRefreshContextUsage}
+ onPress={() => { onRefreshContextUsage(); menuUsage.refresh(); onRefreshAccountUsage(); }}
style={({ pressed }) => [styles.refreshButton, pressed && styles.pressed]}
testID="session.contextRefreshButton"
>
@@ -643,7 +626,6 @@ export function SessionMenuSheet({
)}
</Pressable>
</View>
- <InfoRow label={t('session.menu.currentSessionSpend')} value={spend.available ? spend.detail : t('session.menu.noSessionSpend')} />
<InfoRow label={t('session.menu.contextLabel')} value={usage.detail} />
{usage.rows.length > 0 ? (
<View style={styles.usageRows} testID="session.contextRows">
@@ -654,10 +636,10 @@ export function SessionMenuSheet({
) : null}
</View>
- {accountLimits || resetSummary ? (
+ {(!menuUsage.account && accountLimits) || resetSummary ? (
<View style={styles.infoSection} testID="session.accountLimitsSection">
<Text style={styles.infoSectionTitle}>{t('session.menu.accountLimits')}</Text>
- {accountLimits?.rows.map((row, index) => (
+ {!menuUsage.account && accountLimits?.rows.map((row, index) => (
// 两个窗口都缺时长数据时 label 会同为「限额」,key 需带 index 去重。
<InfoRow key={`${row.label}:${index}`} label={row.label} value={row.value} />
))}
@@ -1032,19 +1014,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
fontSize: typeScale.caption,
lineHeight: lineHeight.caption,
},
- usageRow: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: spacing.xs,
- justifyContent: 'space-between',
- minHeight: 32,
- },
- usageText: {
- color: colors.textSecondary,
- flex: 1,
- fontSize: typeScale.caption,
- minWidth: 0,
- },
actionGroup: {
backgroundColor: colors.sheetActionSurface,
borderColor: colors.sheetActionBorder,
diff --git a/apps/mobile/src/session/SessionUsageSummary.tsx b/apps/mobile/src/session/SessionUsageSummary.tsx
new file mode 100644
index 0000000000..4cb8ae8b9c
--- /dev/null
+++ b/apps/mobile/src/session/SessionUsageSummary.tsx
@@ -0,0 +1,288 @@
+import { Pressable, StyleSheet, View } from "react-native";
+import { ChevronRight } from "lucide-react-native";
+import { useTranslation } from "react-i18next";
+import { Text } from "@/components/AppText";
+import {
+ iconSize,
+ iconStroke,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+import {
+ fontWeight,
+ lineHeight,
+ radius,
+ spacing,
+ typeScale,
+} from "@/theme/tokens";
+import type { RemoteSession } from "./types";
+import type { useSessionMenuUsage } from "./useSessionMenuUsage";
+import {
+ accountUsageRows,
+ formatSessionUsageMoney,
+ sessionUsageAmounts,
+} from "./sessionUsagePresentation";
+
+export function SessionUsageSummary({
+ session,
+ usage,
+ contextUsage,
+ onPress,
+ detail = false,
+}: {
+ session: RemoteSession;
+ usage: ReturnType<typeof useSessionMenuUsage>;
+ contextUsage: unknown;
+ onPress?: () => void;
+ detail?: boolean;
+}) {
+ const { t, i18n } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const amounts = sessionUsageAmounts(session, usage.estimate);
+ const account = usage.account;
+ const source = account?.source;
+ const sourceLabel =
+ !account?.accountOnly &&
+ source &&
+ source !== "api" &&
+ source !== "unavailable"
+ ? t(`session.menu.usage.source.${source}`)
+ : (session.providerId ??
+ { cc: "Claude Code", codex: "Codex", pi: "Pi" }[session.agentKind]);
+ // Overall and model-specific limits both constrain the task; never hide an exhausted one.
+ const rows = accountUsageRows(account, t, i18n.language);
+ const rawContext =
+ contextUsage && typeof contextUsage === "object"
+ ? (contextUsage as Record<string, unknown>)
+ : {};
+ // Session counters are live pushes; an earlier detail read must not freeze this summary.
+ const contextTokens = [
+ session.contextTokens,
+ rawContext.totalTokens,
+ rawContext.contextTokens,
+ ].find(
+ (value): value is number =>
+ typeof value === "number" && Number.isFinite(value) && value >= 0,
+ );
+ const contextWindow = [
+ session.contextWindow,
+ rawContext.rawMaxTokens,
+ rawContext.maxTokens,
+ rawContext.maxContextTokens,
+ rawContext.contextWindow,
+ ].find(
+ (value): value is number =>
+ typeof value === "number" && Number.isFinite(value) && value > 0,
+ );
+ const context =
+ typeof contextTokens === "number" && typeof contextWindow === "number"
+ ? `${Math.round(Math.min(100, Math.max(0, (contextTokens / contextWindow) * 100)))}%`
+ : t("session.menu.usage.unavailable");
+ const amountText = amounts.total
+ ? formatSessionUsageMoney(amounts.total)
+ : amounts.mixed
+ ? t("session.menu.usage.seeDetails")
+ : usage.loading
+ ? t("session.menu.reading")
+ : usage.estimateFailed
+ ? t("session.menu.usage.unavailable")
+ : t("session.menu.noSessionSpend");
+ const caption =
+ amounts.mixed || (!amounts.total && account?.accountOnly)
+ ? t("session.menu.usage.taskUsage")
+ : amounts.total?.kind === "value-estimate" ||
+ (!amounts.total &&
+ (source === "chatgpt" || source === "claude" || source === "xai"))
+ ? t("session.menu.usage.taskValue")
+ : t("session.menu.usage.taskCost");
+ const stale =
+ usage.accountFailed ||
+ (account?.updatedAt != null && Date.now() - account.updatedAt > 5 * 60_000);
+ const content = (
+ <>
+ <View style={styles.heading}>
+ <Text style={styles.source} numberOfLines={2}>
+ {session.model} · {sourceLabel}
+ {account?.plan && !account.accountOnly ? ` · ${account.plan}` : ""}
+ </Text>
+ </View>
+ {account?.accountOnly && rows.length > 0 ? (
+ <Text style={styles.note}>
+ {t("session.menu.usage.accountOnly")}
+ {account.plan ? ` · ${account.plan}` : ""}
+ </Text>
+ ) : null}
+ {rows.map((row, index) => (
+ <View key={index} style={styles.quotaRow}>
+ <View style={styles.row}>
+ <Text style={styles.label}>{row.label}</Text>
+ <Text style={[styles.value, row.warning && styles.warning]}>
+ {row.value}
+ </Text>
+ </View>
+ {row.detail ? <Text style={styles.note}>{row.detail}</Text> : null}
+ </View>
+ ))}
+ {rows.length === 0 && source !== "api" ? (
+ <Text style={styles.note}>
+ {usage.loading && !usage.accountFailed
+ ? t("session.menu.reading")
+ : t("session.menu.usage.quotaUnavailable")}
+ </Text>
+ ) : null}
+ {account?.updatedAt != null && stale ? (
+ <Text style={styles.note}>
+ {t("session.menu.usage.lastUpdated", {
+ time: new Date(account.updatedAt).toLocaleString(i18n.language, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ }),
+ })}
+ </Text>
+ ) : null}
+ <View style={styles.metrics}>
+ <View style={styles.metric}>
+ <Text style={styles.label}>{caption}</Text>
+ <Text style={styles.value}>{amountText}</Text>
+ </View>
+ {!detail ? (
+ <View style={styles.metric}>
+ <Text style={styles.label}>{t("session.menu.contextLabel")}</Text>
+ <Text style={styles.value}>{context}</Text>
+ </View>
+ ) : null}
+ </View>
+ {usage.estimateFailed && amounts.total ? (
+ <Text style={styles.note}>
+ {t("session.menu.usage.valueUnavailable")}
+ </Text>
+ ) : null}
+ {detail ? (
+ <>
+ {amounts.actual && amounts.actual.amount > 0 ? (
+ <View style={styles.row}>
+ <Text style={styles.label}>
+ {t("session.menu.usage.actualCost")}
+ </Text>
+ <Text style={styles.value}>
+ {formatSessionUsageMoney(amounts.actual)}
+ </Text>
+ </View>
+ ) : null}
+ {amounts.estimate && amounts.estimate.amount > 0 ? (
+ <View style={styles.row}>
+ <Text style={styles.label}>
+ {t("session.menu.usage.estimatedValue")}
+ </Text>
+ <Text style={styles.value}>
+ {formatSessionUsageMoney(amounts.estimate)}
+ </Text>
+ </View>
+ ) : null}
+ {amounts.estimate && amounts.estimate.amount > 0 ? (
+ <Text style={styles.note}>
+ {t("session.menu.usage.valueExplanation")}
+ </Text>
+ ) : null}
+ {typeof session.totalTokenUsage === "number" ? (
+ <View style={styles.row}>
+ <Text style={styles.label}>
+ {t("session.menu.usage.totalTokens")}
+ </Text>
+ <Text style={styles.value}>
+ {session.totalTokenUsage.toLocaleString(i18n.language)}
+ </Text>
+ </View>
+ ) : null}
+ </>
+ ) : null}
+ </>
+ );
+ return onPress ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t("session.menu.sessionInfo")}
+ onPress={onPress}
+ style={({ pressed }) => [
+ styles.container,
+ styles.entry,
+ pressed && styles.pressed,
+ ]}
+ testID="session.menuUsageRow"
+ >
+ <View style={styles.entryContent}>{content}</View>
+ <ChevronRight
+ accessible={false}
+ color={colors.textTertiary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ ) : (
+ <View style={styles.container} testID="session.usageDetails">
+ {content}
+ </View>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ container: {
+ gap: spacing.sm,
+ padding: spacing.md,
+ borderRadius: radius.container,
+ backgroundColor: colors.sheetActionSurface,
+ borderColor: colors.sheetActionBorder,
+ borderWidth: StyleSheet.hairlineWidth,
+ minHeight: 44,
+ },
+ entry: { flexDirection: "row", alignItems: "center" },
+ entryContent: { flex: 1, minWidth: 0, gap: spacing.sm },
+ heading: { flexDirection: "row", alignItems: "center", gap: spacing.sm },
+ source: {
+ flex: 1,
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ },
+ quotaRow: { gap: spacing.xs },
+ row: {
+ flexDirection: "row",
+ flexWrap: "wrap",
+ justifyContent: "space-between",
+ alignItems: "center",
+ gap: spacing.xs,
+ },
+ label: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ },
+ value: {
+ color: colors.textPrimary,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ fontWeight: fontWeight.medium,
+ flexShrink: 1,
+ },
+ note: {
+ color: colors.textTertiary,
+ fontSize: typeScale.micro,
+ lineHeight: lineHeight.caption,
+ },
+ metrics: {
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: colors.border,
+ paddingTop: spacing.sm,
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: spacing.md,
+ },
+ metric: { flexGrow: 1, flexBasis: 0, minWidth: 100, gap: spacing.xs },
+ warning: { color: colors.errorText },
+ pressed: { opacity: 0.72 },
+ });
diff --git a/apps/mobile/src/session/readSessionMenuAccountUsage.ts b/apps/mobile/src/session/readSessionMenuAccountUsage.ts
new file mode 100644
index 0000000000..aff096b818
--- /dev/null
+++ b/apps/mobile/src/session/readSessionMenuAccountUsage.ts
@@ -0,0 +1,215 @@
+import { selectCodexUsageForModel } from "@cindy/maker-shared/codex-usage-buckets";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+import type { RemoteSession } from "./types";
+import {
+ canUseLocalCodexRateLimitControl,
+ shouldFallbackToLegacyCodexUsage,
+} from "./sessionControls";
+
+type Reader = Pick<
+ MobileMakerTransport,
+ "getCodexRateLimits" | "getAccountUsage"
+>;
+/** Mobile presentation only; this shape is never sent through device-link. */
+export interface SessionMenuAccountUsage {
+ source: "chatgpt" | "claude" | "xai" | "gateway" | "api" | "unavailable";
+ plan: string | null;
+ updatedAt: number | null;
+ windows: Array<{
+ id: string;
+ minutes: number | null;
+ modelLabel?: string;
+ remainingPercent: number;
+ resetsAt: number | null;
+ }>;
+ amounts: Array<{
+ id: "balance" | "cycle" | "today";
+ amount: number;
+ currency: "CNY" | "USD";
+ limit?: number;
+ }>;
+ /** The account read cannot prove this task's frozen auth route. */
+ accountOnly?: boolean;
+}
+const empty = (
+ source: SessionMenuAccountUsage["source"],
+): SessionMenuAccountUsage => ({
+ source,
+ plan: null,
+ updatedAt: null,
+ windows: [],
+ amounts: [],
+});
+const finite = (value: unknown): value is number =>
+ typeof value === "number" && Number.isFinite(value);
+const record = (value: unknown): Record<string, unknown> =>
+ value !== null && typeof value === "object"
+ ? (value as Record<string, unknown>)
+ : {};
+
+/** Reuse the existing remote Codex read, including its account-change fallback guard. */
+export async function readSessionMenuAccountUsage(
+ session: RemoteSession,
+ reader: Reader,
+): Promise<SessionMenuAccountUsage> {
+ if (session.remoteHostId?.trim()) return empty("unavailable");
+ // The host projects runtime-effective selection onto providerId. Missing
+ // selection alone proves neither a Gateway nor an OpenAI web account route.
+ const provider = session.providerId?.trim() || null;
+ const model = session.model.trim();
+ if (canUseLocalCodexRateLimitControl(session))
+ return readCodexAccount(session, reader);
+ if (
+ session.agentKind !== "codex" &&
+ provider === "openai" &&
+ model.startsWith("chatgpt/")
+ ) {
+ const payload = record(await reader.getAccountUsage("codex"));
+ // The ChatGPT bridge uses the web slot, not the CLI's app-server bucket.
+ const web =
+ payload.webSnapshot ?? (payload.source === "openai-web" ? payload : null);
+ return projectCodexAccount(
+ web,
+ session.model,
+ undefined,
+ null,
+ null,
+ false,
+ );
+ }
+ const gateway =
+ provider === "xd" ||
+ (provider === null &&
+ session.agentKind === "codex" &&
+ model.startsWith("codex/"));
+ if (gateway) {
+ const payload = record(await reader.getAccountUsage("claude-code"));
+ const result = empty("gateway");
+ result.updatedAt = finite(payload.fetchedAt) ? payload.fetchedAt : null;
+ const currency = payload.currency;
+ // Preserve the host's currency; an old/malformed payload is not evidence of USD.
+ if (currency !== "CNY" && currency !== "USD") return result;
+ if (
+ finite(payload.spend) &&
+ payload.spend >= 0 &&
+ finite(payload.maxBudget) &&
+ payload.maxBudget > 0
+ ) {
+ result.amounts.push({
+ id: "cycle",
+ amount: payload.spend,
+ limit: payload.maxBudget,
+ currency,
+ });
+ }
+ if (finite(payload.todaySpend) && payload.todaySpend >= 0) {
+ result.amounts.push({
+ id: "today",
+ amount: payload.todaySpend,
+ currency,
+ });
+ }
+ return result;
+ }
+ // Claude/xAI subscription and personal balance reads are not exposed by existing remote APIs.
+ return empty(
+ provider && !["anthropic", "xai", "openai"].includes(provider)
+ ? "api"
+ : "unavailable",
+ );
+}
+
+async function readCodexAccount(
+ session: RemoteSession,
+ reader: Reader,
+): Promise<SessionMenuAccountUsage> {
+ let raw: unknown;
+ let byLimitId: unknown;
+ let observedAt: number | null = null;
+ let plan: string | null = null;
+ try {
+ const result = await reader.getCodexRateLimits();
+ raw = result.rateLimits;
+ byLimitId = result.rateLimitsByLimitId;
+ plan = result.account.planType;
+ observedAt = Date.now();
+ } catch (error) {
+ if (!shouldFallbackToLegacyCodexUsage(error)) throw error;
+ raw = await reader.getAccountUsage("codex");
+ }
+ return projectCodexAccount(
+ raw,
+ session.model,
+ byLimitId,
+ observedAt,
+ plan,
+ true,
+ );
+}
+
+function projectCodexAccount(
+ raw: unknown,
+ modelId: string,
+ byLimitId: unknown,
+ observedAt: number | null,
+ plan: string | null,
+ accountOnly: boolean,
+): SessionMenuAccountUsage {
+ const payload = record(raw);
+ const now = Date.now();
+ const input = {
+ fallback: raw,
+ byLimitId,
+ appServerBuckets: payload.appServerBuckets,
+ nowMs: now,
+ };
+ // Generic and model-specific limits both apply. Reuse the shared selector's
+ // source precedence, generic aliases and stale-bucket rules for both reads.
+ const generic = selectCodexUsageForModel(input);
+ const selected = selectCodexUsageForModel({ ...input, modelId });
+ const selectedPlan = record(selected).planType;
+ const snapshots = [...new Set([generic, selected])]
+ .filter(Boolean)
+ .map(record);
+ const timestamps = snapshots
+ .map((snapshot) => snapshot.updatedAt ?? payload.updatedAt ?? observedAt)
+ .filter(finite);
+ const windows: SessionMenuAccountUsage["windows"] = [];
+ for (const snapshot of snapshots) {
+ const modelLabel =
+ snapshot !== generic
+ ? typeof snapshot.limitName === "string"
+ ? snapshot.limitName
+ : modelId
+ : undefined;
+ for (const id of ["primary", "secondary"] as const) {
+ const window = record(snapshot[id]);
+ const used = window.usedPercent;
+ if (typeof used !== "number" || !Number.isFinite(used)) continue;
+ const resetsAt =
+ typeof window.resetsAt === "number" && Number.isFinite(window.resetsAt)
+ ? window.resetsAt
+ : null;
+ if (resetsAt !== null && resetsAt * 1000 <= now) continue;
+ windows.push({
+ id: modelLabel ? `model:${id}` : id,
+ ...(modelLabel ? { modelLabel } : {}),
+ minutes:
+ typeof window.windowMinutes === "number" &&
+ Number.isFinite(window.windowMinutes)
+ ? window.windowMinutes
+ : null,
+ remainingPercent: Math.max(0, Math.min(100, 100 - used)),
+ resetsAt,
+ });
+ }
+ }
+ return {
+ source: "chatgpt",
+ accountOnly,
+ plan: typeof selectedPlan === "string" ? selectedPlan : plan,
+ updatedAt: timestamps.length > 0 ? Math.min(...timestamps) : observedAt,
+ windows,
+ amounts: [],
+ };
+}
diff --git a/apps/mobile/src/session/sessionUsagePresentation.ts b/apps/mobile/src/session/sessionUsagePresentation.ts
new file mode 100644
index 0000000000..0da7c3b5b7
--- /dev/null
+++ b/apps/mobile/src/session/sessionUsagePresentation.ts
@@ -0,0 +1,121 @@
+import type { TFunction } from "i18next";
+import type { SessionMenuAccountUsage } from "./readSessionMenuAccountUsage";
+import {
+ normalizeRemoteMoney,
+ remoteMoneySymbol,
+ type RemoteMoney,
+} from "./remoteMoney";
+import type { RemoteSession } from "./types";
+
+export function formatSessionUsageMoney(money: RemoteMoney): string {
+ const symbol = remoteMoneySymbol(money.currency);
+ const amount =
+ money.amount > 0 && money.amount < 0.01
+ ? `<${symbol}0.01`
+ : `${symbol}${money.amount.toFixed(2)}`;
+ return `${money.approximate || money.kind === "value-estimate" ? "≈ " : ""}${amount}`;
+}
+
+export function sessionUsageAmounts(
+ session: Pick<RemoteSession, "totalMoney" | "totalCostUsd">,
+ estimate: RemoteMoney | null,
+) {
+ const actual =
+ normalizeRemoteMoney(session.totalMoney) ??
+ (typeof session.totalCostUsd === "number" &&
+ Number.isFinite(session.totalCostUsd) &&
+ session.totalCostUsd >= 0
+ ? {
+ amount: session.totalCostUsd,
+ currency: "USD" as const,
+ approximate: false,
+ kind: "actual-cost" as const,
+ }
+ : null);
+ // Do not combine incompatible currencies or relabel a value estimate as a bill.
+ const values = [actual, estimate].filter(
+ (value): value is RemoteMoney => value !== null && value.amount > 0,
+ );
+ const total =
+ values.length === 0
+ ? null
+ : values.every((value) => value.currency === values[0].currency)
+ ? {
+ ...values[0],
+ amount: values.reduce((sum, value) => sum + value.amount, 0),
+ approximate: values.some(
+ (value) => value.approximate || value.kind === "value-estimate",
+ ),
+ kind: values.some((value) => value.kind === "value-estimate")
+ ? ("value-estimate" as const)
+ : ("actual-cost" as const),
+ }
+ : null;
+ return { actual, estimate, total, mixed: values.length > 1 };
+}
+
+export interface AccountUsageRow {
+ label: string;
+ value: string;
+ detail?: string;
+ warning?: boolean;
+}
+
+export function accountUsageRows(
+ account: SessionMenuAccountUsage | null,
+ t: TFunction,
+ locale: string,
+ now = Date.now(),
+): AccountUsageRow[] {
+ if (!account) return [];
+ const rows: AccountUsageRow[] = [];
+ for (const window of account.windows) {
+ const label =
+ window.minutes === 10080
+ ? t("session.menu.usage.week")
+ : window.minutes && window.minutes % 60 === 0
+ ? t("session.menu.usage.hours", { count: window.minutes / 60 })
+ : window.minutes
+ ? t("session.menu.usage.minutes", { count: window.minutes })
+ : t("session.menu.usage.quota");
+ const expired = window.resetsAt !== null && window.resetsAt * 1000 <= now;
+ rows.push({
+ label: window.modelLabel ? `${window.modelLabel} · ${label}` : label,
+ value: expired
+ ? t("session.menu.usage.awaitingRefresh")
+ : t("session.menu.usage.remaining", {
+ percent: Math.round(window.remainingPercent),
+ }),
+ warning: !expired && window.remainingPercent <= 10,
+ ...(window.resetsAt !== null
+ ? {
+ detail: t("session.menu.usage.resets", {
+ time: new Date(window.resetsAt * 1000).toLocaleString(locale, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ }),
+ }),
+ }
+ : {}),
+ });
+ }
+ for (const amount of account.amounts) {
+ const money: RemoteMoney = {
+ amount: amount.amount,
+ currency: amount.currency,
+ approximate: false,
+ kind: "actual-cost",
+ };
+ rows.push({
+ label: t(`session.menu.usage.${amount.id}`),
+ value: `${formatSessionUsageMoney(money)}${amount.limit === undefined ? "" : ` / ${formatSessionUsageMoney({ ...money, amount: amount.limit })}`}`,
+ warning:
+ amount.id === "balance"
+ ? amount.amount <= 0
+ : amount.limit !== undefined && amount.amount >= amount.limit,
+ });
+ }
+ return rows;
+}
diff --git a/apps/mobile/src/session/useSessionMenuContextUsage.ts b/apps/mobile/src/session/useSessionMenuContextUsage.ts
new file mode 100644
index 0000000000..c842cae66b
--- /dev/null
+++ b/apps/mobile/src/session/useSessionMenuContextUsage.ts
@@ -0,0 +1,63 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+import { formatRemoteError } from "@/device-link/remoteStatus";
+import type { RemoteSession } from "./types";
+import { buildContextUsageCreateOpts } from "./sessionControls";
+import { sessionMenuUsageScope } from "./useSessionMenuUsage";
+
+/** The info view alone owns its context snapshot; primary menus never bootstrap an engine. */
+export function useSessionMenuContextUsage(
+ session: RemoteSession,
+ reader: Pick<MobileMakerTransport, "getContextUsage">,
+ inspecting: boolean,
+ onError: (error: string | null) => void,
+) {
+ const key = sessionMenuUsageScope(session);
+ // Object identity also distinguishes A -> B -> A, including while the menu is closed.
+ const owner = useMemo(() => ({ key, reader }), [key, reader]);
+ const [stored, setStored] = useState<{
+ owner: typeof owner;
+ usage: unknown;
+ loading: boolean;
+ } | null>(null);
+ const [refreshKey, setRefreshKey] = useState(0);
+ const refresh = useCallback(() => setRefreshKey((key) => key + 1), []);
+
+ useEffect(() => {
+ if (!inspecting) return;
+ let cancelled = false;
+ setStored((previous) => ({
+ owner,
+ usage: previous?.owner === owner ? previous.usage : null,
+ loading: true,
+ }));
+ onError(null);
+ void reader
+ .getContextUsage(session.id, buildContextUsageCreateOpts(session))
+ .then(
+ (usage) => {
+ if (!cancelled) setStored({ owner, usage, loading: false });
+ },
+ (error) => {
+ if (cancelled) return;
+ setStored((previous) =>
+ previous?.owner === owner
+ ? { ...previous, loading: false }
+ : previous,
+ );
+ onError(formatRemoteError(error));
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ // Counter pushes must not restart inspection; owner captures the running configuration.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [owner, inspecting, refreshKey, onError]);
+
+ return {
+ contextUsage: stored?.owner === owner ? stored.usage : null,
+ contextLoading: inspecting && (stored?.owner !== owner || stored.loading),
+ refresh,
+ };
+}
diff --git a/apps/mobile/src/session/useSessionMenuUsage.ts b/apps/mobile/src/session/useSessionMenuUsage.ts
new file mode 100644
index 0000000000..d143d5c955
--- /dev/null
+++ b/apps/mobile/src/session/useSessionMenuUsage.ts
@@ -0,0 +1,158 @@
+import { useCallback, useEffect, useState } from "react";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+import { normalizeRemoteMoney, type RemoteMoney } from "@/session/remoteMoney";
+import type { RemoteSession } from "@/session/types";
+import {
+ readSessionMenuAccountUsage,
+ type SessionMenuAccountUsage,
+} from "./readSessionMenuAccountUsage";
+import {
+ isPreconditionFailedRemoteError,
+ type MobileCodexRateLimitsResult,
+} from "@cindy/maker-shared/device-link-contract";
+
+export type SessionMenuUsageReader = Pick<
+ MobileMakerTransport,
+ "getSessionEstimatedValue" | "getCodexRateLimits" | "getAccountUsage"
+>;
+
+interface UsageState {
+ account: SessionMenuAccountUsage | null;
+ estimate: RemoteMoney | null;
+ accountFailed: boolean;
+ estimateFailed: boolean;
+ loading: boolean;
+}
+const EMPTY: UsageState = {
+ account: null,
+ estimate: null,
+ accountFailed: false,
+ estimateFailed: false,
+ loading: true,
+};
+
+/** Identity shared by menu snapshots; live counters do not change their owner. */
+export function sessionMenuUsageScope(session: RemoteSession): string {
+ return [
+ session.deviceLinkDeviceId,
+ session.id,
+ session.model,
+ session.providerId,
+ session.agentKind,
+ session.remoteHostId,
+ session.clearedAt,
+ session.runtimeGeneration,
+ ].join("\0");
+}
+
+/** Only fetch while the sheet is visible. An effect owns both requests and their late results. */
+export function useSessionMenuUsage(
+ session: RemoteSession,
+ reader: SessionMenuUsageReader,
+ visible: boolean,
+ codexRateLimits: MobileCodexRateLimitsResult | null = null,
+) {
+ const taskScope = [
+ session.deviceLinkDeviceId,
+ session.id,
+ session.clearedAt,
+ ].join("\0");
+ const scope = sessionMenuUsageScope(session);
+ const [stored, setStored] = useState<{
+ scope: string;
+ taskScope: string;
+ value: UsageState;
+ } | null>(null);
+ const [refreshKey, setRefreshKey] = useState(0);
+ const refresh = useCallback(() => setRefreshKey((key) => key + 1), []);
+ // Parent control reads/resets replace codexRateLimits. Effect cleanup discards
+ // pre-reset reads and refreshes immediately instead of waiting for polling.
+ useEffect(() => {
+ if (!visible) return;
+ let cancelled = false;
+ let inFlight = false;
+ const update = (patch: Partial<UsageState>) => {
+ if (cancelled) return;
+ setStored((previous) => ({
+ scope,
+ taskScope,
+ value: {
+ ...(previous?.scope === scope
+ ? previous.value
+ : {
+ ...EMPTY,
+ estimate:
+ previous?.taskScope === taskScope
+ ? previous.value.estimate
+ : null,
+ }),
+ ...patch,
+ },
+ }));
+ };
+ const read = async () => {
+ if (inFlight) return;
+ inFlight = true;
+ update({ loading: true });
+ await Promise.allSettled([
+ readSessionMenuAccountUsage(session, reader).then(
+ (account) => update({ account, accountFailed: false }),
+ (error) =>
+ update({
+ accountFailed: true,
+ ...(isPreconditionFailedRemoteError(error)
+ ? { account: null }
+ : {}),
+ }),
+ ),
+ reader.getSessionEstimatedValue(session.id).then(
+ (snapshot) =>
+ update({
+ estimate:
+ normalizeRemoteMoney(snapshot.totalValueMoney) ??
+ (typeof snapshot.totalValueUsd === "number" &&
+ Number.isFinite(snapshot.totalValueUsd) &&
+ snapshot.totalValueUsd >= 0
+ ? {
+ amount: snapshot.totalValueUsd,
+ currency: "USD",
+ approximate: true,
+ kind: "value-estimate",
+ }
+ : null),
+ estimateFailed: false,
+ }),
+ () => update({ estimateFailed: true }),
+ ),
+ ]);
+ update({ loading: false });
+ inFlight = false;
+ };
+ void read();
+ // Existing host readers refresh cached snapshots in the background. Re-read while visible
+ // so their first cold response does not leave the sheet empty until it is reopened.
+ const timer = setInterval(() => void read(), 30_000);
+ return () => {
+ cancelled = true;
+ clearInterval(timer);
+ };
+ }, [
+ scope,
+ taskScope,
+ reader,
+ visible,
+ refreshKey,
+ session.id,
+ codexRateLimits,
+ ]);
+ return {
+ ...(stored?.scope === scope
+ ? stored.value
+ : {
+ ...EMPTY,
+ estimate:
+ stored?.taskScope === taskScope ? stored.value.estimate : null,
+ }),
+ refresh,
+ };
+}
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index be4b9e7272..3865bee700 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -307,6 +307,7 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [
'maker:apply-new-maker-worktree-branch-pref',
// 模型选择列表元信息:被控端视角的模型单价表(只读;拉不到 → 隐藏价格)。
'maker:usage:model-pricing',
+ 'local-db:messages:estimatedSessionValue',
// Codex app-server 官方控制面:只读额度/reset 次数 + 人工确认后的单次 reset。
// reset 使用 desktop 预签发、账号绑定的幂等 offer,手机不能自行指定 creditId。
'maker:usage:codex-rate-limits',