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(usage-limit): 账号用量上限重置后自动继续,覆盖更多订阅套餐 (#5540)

Dash48bfca40dfaa
diff --git a/AGENTS.md b/AGENTS.md
index 60f0bcc385..d1b376f9c9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -57,6 +57,8 @@
- 修改 IM 工具授权、来源消息、多端确认或暂停期间的确认回执,或新增 IM 渠道前,
必须先读 `docs/product-rules/im-permission-confirmation.md`;Desktop、Mobile 与共享
packages 共用同一最终决定,渠道收到回答不代表执行已恢复。
+- 修改账号用量上限的判定、重置时刻来源,或普通任务/目标模式撞上限额后的等待与自动继续前,
+ 必须先读 `docs/product-rules/usage-limit-auto-continue.md`。
- 新增或修改自动发送/远程发送消息的路径、消息来源标签,或发给模型的来源说明前,必须先读
`docs/product-rules/message-source.md`:界面标签与模型说明同源,两侧一起改。
- 修改伙伴(Bot)的身份、Session 生命周期、模型 fallback、工作目录、Skill / MCP 装配、
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 0b3809e9a4..935996005c 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -751,6 +751,7 @@ import {
setGoalClearObserver,
setGoalDeferredResumeCancelObserver,
setGoalIdleObserver,
+ setGoalOwnsUsageLimitProbe,
setGoalStopObserver,
setGoalAskAnswerObserver,
withSendToSessionLock,
@@ -6164,6 +6165,11 @@ const registerIpcHandlers = () => {
setGoalDeferredResumeCancelObserver((sid) => {
getGoalController()?.cancelDeferredManualResume(sid, { restoreUsageResume: true });
});
+ // 目标在管的任务由 goal-host 自己等额度重置,普通任务的限额自动继续让路。
+ setGoalOwnsUsageLimitProbe(async (sid) => {
+ const goal = await getGoalController()?.getStatus(sid);
+ return goal?.status === 'active' || goal?.status === 'usageLimited';
+ });
// 用户 Stop 当前 turn → 暂停 active 目标。返回 Promise 让 ABORT_SESSION 在 abort 前 await,
// 确保目标先 paused + detach 监听,abort 终止事件不再触发续跑判定。
setGoalStopObserver((sid) => getGoalController()?.pauseGoal(sid, 'paused: stopped by user'));
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index 75ea66ea01..df966bd63f 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -14,6 +14,16 @@ let readInteractionSession: ((requestId: string) => SharedTaskInteractionCapture
export function setSharedTaskQueueReader(value: typeof readQueueItem): void { readQueueItem = value; }
export function setSharedTaskInteractionReader(value: typeof readInteractionSession): void { readInteractionSession = value; }
export function setSharedTaskDispatchHost(value: SharedTaskHost | null): void { host = value; }
+/** 本机当前是否在共享这个任务(共享未关闭)。宿主不可用时访客本就无法操作,按未共享处理。 */
+export function isSessionSharedTaskActive(sessionId: string): boolean {
+ const current = host;
+ if (!current) return false;
+ try {
+ return current.activeSharedTaskIds().some((id) => current.detail(id)?.sessionId === sessionId);
+ } catch {
+ return false;
+ }
+}
export function captureSharedTaskPeer(source: string): SharedTaskPeerCapture | null {
return host?.capturePeer(source) ?? null;
}
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
index f99009595c..a38ea672c7 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -4076,6 +4076,89 @@ describe('GoalController', () => {
expect(h.session.sends).toHaveLength(1);
});
+ it('reads the account limit of the goal session so the subscription provider is respected', async () => {
+ const getAccountLimit = vi.fn(async () => ({ limited: true, resetAtMs: 3_601_000 }));
+ const local = makeController({ getAccountLimit });
+ try {
+ await startGoal(local);
+ local.session.emitErrorTurn({ sdkError: 'rate_limit', message: 'rate limit reached' });
+ await tick();
+ expect(getAccountLimit).toHaveBeenCalledWith(
+ expect.any(String),
+ 's1',
+ expect.objectContaining({ sdkError: 'rate_limit' }),
+ );
+ expect((await local.storage.get('s1'))?.usageResetAt).toBe(3_601_000);
+ } finally {
+ await local.controller.dispose();
+ }
+ });
+
+ it('reactive: ignores the snapshot reset time when the snapshot does not show the limit', async () => {
+ // 未用满窗口的重置时刻与这次限流无关:不排期,留待手动 resume。
+ h.setAccountLimit({ limited: false, resetAtMs: 3_601_000 });
+ await startGoal(h);
+ h.session.emitErrorTurn({ errorStatus: 429, message: 'Too many requests' });
+ await tick();
+ const st = await h.storage.get('s1');
+ expect(st?.status).toBe('usageLimited');
+ expect(st?.usageResetAt).toBeNull();
+ });
+
+ it('leaves the reset time written in the error text to the host (only trusted for subscriptions)', async () => {
+ // 报错原文里的时刻要由注入端按会话订阅家族判定;非订阅来源的 Retry-After 不能直接排期。
+ const getAccountLimit = vi.fn(async () => null);
+ const local = makeController({ getAccountLimit });
+ try {
+ await startGoal(local);
+ const error = { errorStatus: 429, message: 'Too many requests. Try again in ~2 min.' };
+ local.session.emitErrorTurn(error);
+ await tick();
+ expect(getAccountLimit).toHaveBeenCalledWith(expect.any(String), 's1', expect.objectContaining(error));
+ const st = await local.storage.get('s1');
+ expect(st?.status).toBe('usageLimited');
+ expect(st?.usageResetAt).toBeNull();
+ } finally {
+ await local.controller.dispose();
+ }
+ });
+
+ it('shared task: a usage limit stays usageLimited without scheduling an auto resume', async () => {
+ const local = makeController({ isSessionShared: () => true });
+ try {
+ local.setAccountLimit({ limited: true, resetAtMs: 1000 });
+ await startGoal(local);
+ local.session.emitErrorTurn({ sdkError: 'rate_limit', usageResetAt: 1000 });
+ await tick();
+ await tick();
+ const st = await local.storage.get('s1');
+ expect(st?.status).toBe('usageLimited');
+ expect(st?.usageResetAt).toBeNull();
+ expect(local.notices).toEqual([]);
+ expect(local.session.sends).toHaveLength(1);
+ } finally {
+ await local.controller.dispose();
+ }
+ });
+
+ it('shared task: a wait that becomes shared does not auto resume at the reset time', async () => {
+ // 报错时尚未共享(排了恢复),到点时已在共享。
+ const isSessionShared = vi.fn(() => isSessionShared.mock.calls.length > 1);
+ const local = makeController({ isSessionShared });
+ try {
+ local.setAccountLimit({ limited: true, resetAtMs: 1000 });
+ await startGoal(local);
+ local.session.emitErrorTurn({ sdkError: 'rate_limit' });
+ await vi.waitFor(() => expect(isSessionShared).toHaveBeenCalledTimes(2));
+ await tick();
+ expect(local.notices).toEqual([]);
+ expect(await local.storage.get('s1')).toMatchObject({ status: 'usageLimited', usageResetAt: 1000 });
+ expect(local.session.sends).toHaveLength(1);
+ } finally {
+ await local.controller.dispose();
+ }
+ });
+
it('proactive: a would-be-continue turn flips to usageLimited when the account is limited', async () => {
h.setAccountLimit({ limited: true, resetAtMs: 3_601_000 });
await startGoal(h);
diff --git a/apps/desktop/src/main/goal-host/__tests__/usageLimit.test.ts b/apps/desktop/src/main/goal-host/__tests__/usageLimit.test.ts
index 889df0ae5e..fed34be380 100644
--- a/apps/desktop/src/main/goal-host/__tests__/usageLimit.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/usageLimit.test.ts
@@ -5,6 +5,7 @@ import {
OVERLOAD_RESUME_DELAY_MS,
classifyTurnOverload,
classifyTurnUsageLimit,
+ readStructuredUsageResetAt,
readTurnUsageResetAt,
} from '../usageLimit';
@@ -125,7 +126,31 @@ describe('classifyTurnOverload', () => {
});
});
+describe('classifyTurnUsageLimit (billing depletion)', () => {
+ it('never treats billing depletion as a periodic limit, even with quota wording', () => {
+ expect(classifyTurnUsageLimit({ sdkError: 'billing_error', message: 'quota exceeded' })).toBe(false);
+ expect(classifyTurnUsageLimit({ errorStatus: 429, message: 'insufficient_quota: quota exceeded' })).toBe(false);
+ expect(classifyTurnUsageLimit({ message: 'Credit balance too low; usage limit reached' })).toBe(false);
+ });
+});
+
+describe('classifyTurnUsageLimit (Codex structured tag)', () => {
+ it('matches codexErrorInfo usageLimitExceeded even without limit wording', () => {
+ expect(classifyTurnUsageLimit({ codexErrorInfo: 'usageLimitExceeded', message: 'Upgrade to Pro' })).toBe(true);
+ });
+});
+
describe('readTurnUsageResetAt', () => {
+ it('falls back to the reset time written in the error text', () => {
+ const now = Date.parse('2026-01-24T10:00:00.000Z');
+ expect(
+ readTurnUsageResetAt(
+ { message: 'You have hit your ChatGPT usage limit (plus plan). Try again in ~12 min.' },
+ now,
+ ),
+ ).toBe(now + 12 * 60_000);
+ });
+
it('reads the reset time carried by the error', () => {
expect(readTurnUsageResetAt({ sdkError: 'rate_limit', usageResetAt: 1_791_202_800_000 })).toBe(1_791_202_800_000);
});
@@ -137,3 +162,10 @@ describe('readTurnUsageResetAt', () => {
expect(readTurnUsageResetAt(null)).toBeNull();
});
});
+
+describe('readStructuredUsageResetAt', () => {
+ it('only reads the structured field, never the error text', () => {
+ expect(readStructuredUsageResetAt({ usageResetAt: 1_791_202_800_000 })).toBe(1_791_202_800_000);
+ expect(readStructuredUsageResetAt({ errorStatus: 429, message: 'Try again in ~2 min.' })).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index f00e18ca20..fb906d9b0d 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -27,7 +27,7 @@ import {
OVERLOAD_RESUME_DELAY_MS,
classifyTurnOverload,
classifyTurnUsageLimit,
- readTurnUsageResetAt,
+ readStructuredUsageResetAt,
} from './usageLimit';
import { parseVerdict, type GoalVerdict } from './verdict';
import {
@@ -1971,7 +1971,7 @@ export class GoalController {
let shouldFire = decision.shouldFire;
let usageResetAt: number | null = null;
const reportedResetAt =
- outcome.errorKind === 'usage_limit' ? readTurnUsageResetAt(event.data) : null;
+ outcome.errorKind === 'usage_limit' ? readStructuredUsageResetAt(event.data) : null;
// 过载改判:上游没容量与账号限流是两种恢复时机。这里用固定短窗口,不去查
// getAccountLimit——账号并没有被限流,那个接口不会给出可用的 resetAt,查了只会
// 让目标停在 usageLimited 等人手动 resume。
@@ -1984,11 +1984,20 @@ export class GoalController {
shouldFire = false;
} else if (status === 'usageLimited' || shouldFire) {
const limit = this.deps.getAccountLimit
- ? await this.deps.getAccountLimit(state.agentKind).catch(() => null)
+ ? await this.deps
+ .getAccountLimit(
+ state.agentKind,
+ sessionId,
+ // 报错原文里的时刻要先确认会话属于订阅账号才可信,交给注入端判定。
+ status === 'usageLimited' && outcome.errorKind === 'usage_limit' ? event.data : undefined,
+ )
+ .catch(() => null)
: null;
if (!isCurrentTurn()) return;
if (status === 'usageLimited') {
- usageResetAt = limit?.resetAtMs ?? null; // 被动:补 resetAt(可能拿不到→null,留待手动 resume)
+ // 被动:补 resetAt。只采纳确认已用满的时刻——未用满窗口的重置时刻与这次限流无关;
+ // 拿不到就 null,留待手动 resume。
+ usageResetAt = limit?.limited ? limit.resetAtMs : null;
shouldFire = false;
} else if (limit?.limited) {
status = 'usageLimited';
@@ -1998,6 +2007,16 @@ export class GoalController {
}
}
+ // 共享中的任务撞上账号限额不自动恢复(Dash 2026-10-08):停在 usageLimited 由房主手动恢复。
+ if (
+ status === 'usageLimited' &&
+ outcome.errorKind !== 'overload' &&
+ usageResetAt !== null &&
+ this.deps.isSessionShared?.(sessionId)
+ ) {
+ usageResetAt = null;
+ }
+
// 目标改写(Option 1):模型澄清含糊目标后,经 refined_objective 报回更具体的目标。
// 仅在目标继续推进(shouldFire)且新目标非空、与当前不同时确定性改写 storage.objective,
// 让 chip 更新、后续续轮按新目标跑。终止/暂停态不改写(避免停掉的目标文案被无意义重写)。
@@ -2239,6 +2258,11 @@ export class GoalController {
const state = await this.deps.storage.get(sessionId).catch(() => null);
if (!isCurrent()) return;
if (!state || state.status !== 'usageLimited') return; // 用户可能已 clear / 手动 resume
+ // 等待期间开始共享:到点不自动恢复账号限额(过载短窗口照常),留给房主手动恢复。
+ if (state.lastReason !== OVERLOAD_LAST_REASON && this.deps.isSessionShared?.(sessionId)) {
+ this.deps.logger.info('[goal] skipped usage auto resume — task is shared', { sessionId });
+ return;
+ }
// 预算已经用尽时一条都不该说:下面的 resumeGoal → fireTurn 有 preflight 预算守卫,
// 会立刻把目标转成 budgetLimited、一轮都不发,而这张卡片已经落库,会在会话里永久
// 留下一句「正在重试目标 / 用量已恢复」——那次重试根本没发生(review #844 codex P1)。
diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts
index a7003b5293..07c36bfa90 100644
--- a/apps/desktop/src/main/goal-host/index.ts
+++ b/apps/desktop/src/main/goal-host/index.ts
@@ -14,13 +14,17 @@ import { createLogger } from '../logger.js';
import {
acquirePendingAgentSwitchForDirectSend,
isSessionInTurn,
+ resolveSessionRuntimeRoute,
stopActiveGoalTurnForClear,
} from '../maker-ipc/register.js';
+import { isSessionSharedTaskActive } from '../device-link/sharedTaskDispatch.js';
import { createMessage } from '../localDb/ipc/messages.js';
import { readGoalSettings, writeGoalSettings } from '../maker-host/goal-settings-store.js';
+import { getSessionRowSnapshot } from '../localDb/ipc/sessions.js';
+import { readAccountUsageLimit, subscriptionFamilyOf } from '../usage/accountUsageLimit.js';
import { readClaudeAccountUsageSnapshot } from '../usage/claudeAccountUsage.js';
-import { readCodexAccountUsageSnapshot } from '../usageBroadcaster.js';
import { GoalController } from './controller';
+import { readTurnUsageResetAt } from './usageLimit.js';
import { restoreSessionForGoal } from './sessionRestore.js';
import { GoalStorage, type GoalDrizzleDb } from './storage';
import type { GoalStatusUpdate, SessionLike } from './types';
@@ -89,26 +93,28 @@ export function startGoalController(deps: StartGoalControllerDeps): GoalControll
agentMeta: { goalCompletion: summary },
});
},
- // 主动配额检测:读对应 agent 的账号用量快照(codex 走 account_usage 事件落库的
- // snapshot、claude 走 LiteLLM 轮询),判 limited + 取 resetAt(unix ms)。
- getAccountLimit: async (agentKind) => {
- if (agentKind === 'codex') {
- const snap = await readCodexAccountUsageSnapshot().catch(() => null);
- if (!snap) return null;
- // 取"已用满(>=100%)窗口里最晚的"重置;都没满则取两窗口里最晚的(宁晚勿早)。
- // 不能一律取 primary —— 当限流来自周 / 次要窗口时 primary 重置更早,会让目标早醒、
- // 反复撞同一限额,直到次要窗口真正恢复(reviewer #354)。
- const windows = [snap.primary, snap.secondary].filter(
- (w): w is NonNullable<typeof w> => !!w && typeof w.resetsAt === 'number',
- );
- const exhausted = windows.filter((w) => w.usedPercent >= 100);
- const pool = exhausted.length > 0 ? exhausted : windows;
- const resetsAtSec = pool.length > 0 ? Math.max(...pool.map((w) => w.resetsAt as number)) : null;
- return {
- limited: snap.rateLimitReachedType != null,
- resetAtMs: resetsAtSec != null ? resetsAtSec * 1000 : null,
- };
+ // 主动配额检测:按会话所用订阅账号读用量快照(ChatGPT 订阅无论跑在 Codex、Claude Code
+ // bridge 还是 Pi 上都读同一份额度),判 limited + 取 resetAt(unix ms)。
+ getAccountLimit: async (agentKind, sessionId, turnError) => {
+ const row = await getSessionRowSnapshot(sessionId);
+ const { providerId, modelId } = resolveSessionRuntimeRoute(sessionId, agentKind, row);
+ if (subscriptionFamilyOf(agentKind, providerId)) {
+ // 报错原文写明的重置时刻只对订阅账号可信(非订阅来源的是分钟级请求限流)。
+ if (turnError !== undefined) {
+ // SSH 远程会话的报错用远端主机的本地时间:不带时区的钟点不按本机时区理解。
+ const fromError = readTurnUsageResetAt(turnError, Date.now(), {
+ localTimeZoneTrusted: !row?.remoteHostId,
+ });
+ if (fromError !== null) return { limited: true, resetAtMs: fromError };
+ }
+ // SSH 远程会话用远端主机自己的登录,本机订阅快照属于另一个账号(与普通任务同一边界)。
+ if (row?.remoteHostId) return null;
}
+ const subscription = await readAccountUsageLimit(agentKind, providerId, modelId).catch(
+ () => null,
+ );
+ if (subscription !== undefined) return subscription;
+ // 非订阅的 Claude Code 会话(Cindy 网关):读 LiteLLM 预算周期。
if (agentKind === 'claude-code') {
const snap = readClaudeAccountUsageSnapshot();
if (!snap) return null;
@@ -121,6 +127,7 @@ export function startGoalController(deps: StartGoalControllerDeps): GoalControll
return null;
},
// usageLimited 到点自动续跑时,落一条"用量已恢复,继续目标"提示(渲染成 system card)。
+ isSessionShared: (sessionId) => isSessionSharedTaskActive(sessionId),
persistGoalNotice: async (sessionId, kind) => {
await createMessage(sessionId, {
clientId: randomUUID(),
diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts
index 8605b6d3c5..492c0f64f6 100644
--- a/apps/desktop/src/main/goal-host/types.ts
+++ b/apps/desktop/src/main/goal-host/types.ts
@@ -227,12 +227,22 @@ export interface GoalControllerDeps {
*/
persistGoalCompletion?: (sessionId: string, summary: GoalCompletionSummary) => Promise<void>;
/**
- * 读某 agent 当前账号用量是否受限 + 何时重置(主动检测)。注入端读对应配额快照:
- * codex → readCodexAccountUsageSnapshot(rateLimitReachedType / resetsAt);
- * claude → readClaudeAccountUsageSnapshot(spend>=maxBudget / budgetResetAt)。
+ * 该任务当前是否在共享中。共享中的目标撞上账号限额不排自动恢复(访客可能已影响本目标,
+ * 等待期间撤权后到点续跑不安全),停在 usageLimited 由房主手动恢复;过载短窗口不受影响。
+ */
+ isSessionShared?: (sessionId: string) => boolean;
+ /**
+ * 读该会话所用账号当前是否受限 + 何时重置(主动检测)。注入端按会话 provider 所属的订阅
+ * 家族读对应快照(ChatGPT / Claude / SuperGrok,见 usage/accountUsageLimit.ts);非订阅的
+ * Claude Code 会话退回 Cindy 网关预算快照。`turnError` 为本轮限额报错(被动检测时传入):
+ * 会话属于订阅账号时优先用报错原文里写明的重置时刻。
* 返回 null = 拿不到快照(按"未受限"处理)。
*/
- getAccountLimit?: (agentKind: AgentKind) => Promise<AccountLimitInfo | null>;
+ getAccountLimit?: (
+ agentKind: AgentKind,
+ sessionId: string,
+ turnError?: unknown,
+ ) => Promise<AccountLimitInfo | null>;
/**
* 持久化一条 goal 提示记录(注入 createMessage,role:'assistant' + agentMeta.goalNotice)。
* 目前用于 usageLimited 到点自动续跑时落一条"用量已恢复,继续目标"。
diff --git a/apps/desktop/src/main/goal-host/usageLimit.ts b/apps/desktop/src/main/goal-host/usageLimit.ts
index 354b2f257e..011122126d 100644
--- a/apps/desktop/src/main/goal-host/usageLimit.ts
+++ b/apps/desktop/src/main/goal-host/usageLimit.ts
@@ -1,5 +1,5 @@
/**
- * 账号用量受限识别 —— 纯函数,零依赖,可独立单测。
+ * 账号用量受限识别 —— 纯函数,可独立单测。普通任务的限额自动续跑复用同一套判定。
*
* 被动检测:goal turn 以 error 收尾时,判断该错误是不是"账号/套餐限流"(rate limit /
* quota),从而把状态置 `usageLimited`(可恢复、到点自动续)而非 `blocked`(真出错)。
@@ -8,9 +8,15 @@
* - Claude Code:error 事件带结构化 `data.sdkError`,限流时 = `'rate_limit'`。
* 注意 `billing_error`(余额耗尽、无周期重置)**不算** usage limit —— 那是"去充值",
* 保持 blocked 更合适。
- * - Codex:error 事件只有 `data.message` 文本,限流靠文本匹配(无结构化 tag)。
+ * - Codex:error 事件带 `codexErrorInfo: 'usageLimitExceeded'`,另有 `data.message` 文本兜底。
*/
+import {
+ extractUsageLimitRecoveryHint,
+ isBillingDepletionError,
+ type UsageLimitRecoveryParseOptions,
+} from '../../shared/usageLimitRecovery.js';
+
/** turn error 的 data 是否表示"账号用量/限流"。 */
export function classifyTurnUsageLimit(data: unknown): boolean {
if (!data || typeof data !== 'object') return false;
@@ -19,9 +25,13 @@ export function classifyTurnUsageLimit(data: unknown): boolean {
message?: unknown;
errorStatus?: unknown;
usageLimit?: unknown;
+ codexErrorInfo?: unknown;
};
- // Claude:结构化 tag(权威)。
+ // 余额 / 计费耗尽要充值、不会周期重置,文案里带 quota 也不算(保持 blocked)。
+ if (isBillingDepletionError(data)) return false;
+ // 结构化 tag(权威)。
if (d.sdkError === 'rate_limit') return true;
+ if (d.codexErrorInfo === 'usageLimitExceeded') return true;
if (d.usageLimit === true) return true;
if (d.errorStatus === 429 || d.errorStatus === 529) return true;
// Codex / 兜底:文本匹配。
@@ -30,16 +40,35 @@ export function classifyTurnUsageLimit(data: unknown): boolean {
}
/**
- * turn error 自带的限额重置时刻(unix ms)。Claude 订阅会话由 translator 从 SDK
- * `rate_limit_event` 带上 —— 账号快照(getAccountLimit)读不到订阅的 5h / 周窗口,
- * 没有它目标会停在 usageLimited 等人手动恢复。
+ * turn error 自带的结构化重置时刻(unix ms)。只有 Claude 订阅会话由 translator 从 SDK
+ * `rate_limit_event` 带上,天然属于订阅账号,可直接使用。
*/
-export function readTurnUsageResetAt(data: unknown): number | null {
+export function readStructuredUsageResetAt(data: unknown): number | null {
if (!data || typeof data !== 'object') return null;
const v = (data as { usageResetAt?: unknown }).usageResetAt;
return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null;
}
+/**
+ * turn error 给出的限额重置时刻(unix ms):先取结构化 `usageResetAt`,再从报错原文解析
+ * (ChatGPT 订阅的 `resets_at` / `try again at 3:05 PM` / Pi 的 `Try again in ~N min` 等)。
+ * 都没有时返回 null,调用方再退回账号快照。
+ *
+ * 只对订阅账号的会话调用:API key / Coding Plan / 网关等来源报错里的重试时刻是分钟级请求
+ * 限流,不是周期额度重置。
+ */
+export function readTurnUsageResetAt(
+ data: unknown,
+ nowMs = Date.now(),
+ opts?: UsageLimitRecoveryParseOptions,
+): number | null {
+ return (
+ readStructuredUsageResetAt(data) ??
+ extractUsageLimitRecoveryHint(data, nowMs, opts)?.resetAtMs ??
+ null
+ );
+}
+
/**
* turn error 的 data 是否表示"上游模型服务没有可用容量"(Codex 的
* `Selected model is at capacity` / Anthropic 的 529 overloaded)。
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 392d5ba165..4c3356a420 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -833,6 +833,10 @@ export interface SessionRowSnapshot {
orcaRole?: 'lead' | 'worker' | null;
/** Collab policy gate: remote session 的 codex / claude-code 均放行。 */
agentKind?: string | null;
+ /** 会话来源(`bot` = 伙伴会话);限额自动继续据此排除伙伴。 */
+ source?: string | null;
+ /** 会话当前模型;限额判定据此只看该模型的额度窗口。 */
+ model?: string | null;
/** Authoritative `/clear` visibility boundary (unix ms). */
clearedAt?: number | null;
}
@@ -855,6 +859,8 @@ async function selectSessionRowSnapshot(id: string): Promise<SessionRowSnapshot
remoteHostId: sessions.remoteHostId,
orcaRole: sessions.orcaRole,
agentKind: sessions.agentKind,
+ source: sessions.source,
+ model: sessions.model,
})
.from(sessions)
.where(eq(sessions.id, id))
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index f4ace75658..22da21b745 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -32,6 +32,7 @@ import type {
AgentInputProjection,
AgentInputQueuedMessage,
} from '../../../shared/agentInputQueue.js';
+import { USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../../shared/agentInputQueue.js';
import {
CONTINUE_AFTER_APP_EXIT_PROMPT,
CONTINUE_AFTER_ERROR_PROMPT,
@@ -934,6 +935,9 @@ function createHarness(opts?: {
const onResumableTurnErrorDiscarded = vi.fn<
NonNullable<AgentInputCoordinatorDeps['onResumableTurnErrorDiscarded']>
>(() => {});
+ const onUsageLimitedTurnError = vi.fn<
+ NonNullable<AgentInputCoordinatorDeps['onUsageLimitedTurnError']>
+ >(() => {});
const noteSessionClearBoundary =
vi.fn<NonNullable<AgentInputCoordinatorDeps['noteSessionClearBoundary']>>();
const resolveSessionReferences = vi.fn<
@@ -1040,6 +1044,7 @@ function createHarness(opts?: {
onResumableTurnError,
isResumableTurnErrorCandidate,
onResumableTurnErrorDiscarded,
+ onUsageLimitedTurnError,
noteSessionClearBoundary,
resolveSessionReferences,
refreshAgentReferencesBeforeDispatch,
@@ -1082,6 +1087,7 @@ function createHarness(opts?: {
onResumableTurnError,
isResumableTurnErrorCandidate,
onResumableTurnErrorDiscarded,
+ onUsageLimitedTurnError,
noteSessionClearBoundary,
resolveSessionReferences,
refreshAgentReferencesBeforeDispatch,
@@ -13288,3 +13294,260 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
expect(h.onResumableTurnError, '落库失败就没有可续跑的目标,不该消耗额度').not.toHaveBeenCalled();
});
});
+
+describe('usage-limit wait (ordinary tasks)', () => {
+ const LIMIT_SIGNALS = { sdkError: 'rate_limit', usageResetAt: 5_000_000 };
+ const INFO = {
+ reason: USAGE_LIMIT_RESET_AUTO_RESUME_REASON,
+ attempt: 1,
+ maxAttempts: 3,
+ sessionTotal: 0,
+ };
+
+ async function failWithLimit(sid: string, progress: boolean) {
+ const h = createHarness();
+ h.setHasAssistantProgressAfter(async () => progress);
+ h.coordinator.enqueue(sid, makeItem('q-first', 'original long task'));
+ await flush();
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', "You've hit your session limit", LIMIT_SIGNALS);
+ await flush();
+ const candidate = h.onUsageLimitedTurnError.mock.calls.at(-1)?.[3] as number;
+ return { h, candidate };
+ }
+
+ it('reports the limit error with a candidate token and keeps the normal error banner', async () => {
+ const sid = 'usage-wait-notify';
+ const { h, candidate } = await failWithLimit(sid, true);
+ expect(h.onUsageLimitedTurnError).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ message: "You've hit your session limit", ...LIMIT_SIGNALS }),
+ expect.objectContaining({ clientId: 'q-first' }),
+ expect.any(Number),
+ );
+ expect(typeof candidate).toBe('number');
+ const projection = latestProjection(h.projections);
+ expect(projection.error).toBe("You've hit your session limit");
+ // 候选还没排期,不显示等待。
+ expect(projection.usageLimitWait).toBeNull();
+ });
+
+ it('projects the wait alongside the error and continues with the hidden prompt when it fires', async () => {
+ const sid = 'usage-wait-continue';
+ const { h, candidate } = await failWithLimit(sid, true);
+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(true);
+ const projection = latestProjection(h.projections);
+ expect(projection.error).not.toBeNull();
+ expect(projection.usageLimitWait).toEqual({ resumeAt: 9_000_000 });
+
+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, candidate, INFO)).toBe('resumed');
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ const persist = h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage;
+ expect(persist?.autoResume).toBe(true);
+ expect(persist?.autoResumeInfo).toMatchObject({
+ ...INFO,
+ error: "You've hit your session limit",
+ });
+ // 自动动作不冒充用户点击。
+ expect(h.onUiRetry).toHaveBeenLastCalledWith(sid, expect.any(String), 'auto', undefined);
+ expect(latestProjection(h.projections).usageLimitWait).toBeNull();
+ });
+
+ it('restores the error and manual retry if the continuation is dropped before dispatch', async () => {
+ const sid = 'usage-wait-dropped';
+ const { h, candidate } = await failWithLimit(sid, true);
+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(true);
+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, candidate, INFO)).toBe('resumed');
+ const clientId = h.onUiRetry.mock.calls.at(-1)?.[1] as string;
+ // 中断自愈的令牌对不上额度续跑项。
+ expect(h.coordinator.restoreAutoResumeRecovery(sid, clientId, 7)).toBe(false);
+ expect(h.coordinator.restoreAutoResumeRecovery(sid, clientId, null)).toBe(true);
+ const projection = h.coordinator.getProjection(sid);
+ expect(projection.error).toBe("You've hit your session limit");
+ expect(projection.recovery?.kind).toBe('active-turn');
+
+ // 已交给 vendor 的续跑不再回滚。
+ const sent = await failWithLimit('usage-wait-dispatched', true);
+ expect(sent.h.coordinator.armUsageLimitWait('usage-wait-dispatched', sent.candidate, 9_000_000)).toBe(true);
+ await sent.h.coordinator.continueAfterUsageLimitReset('usage-wait-dispatched', sent.candidate, INFO);
+ await flush();
+ const sentClientId = sent.h.onUiRetry.mock.calls.at(-1)?.[1] as string;
+ expect(sent.h.coordinator.restoreAutoResumeRecovery('usage-wait-dispatched', sentClientId, null)).toBe(false);
+ });
+
+ it('does not offer a retry when the continuation may already have reached the vendor', async () => {
+ const sid = 'usage-wait-unconfirmed';
+ const { h, candidate } = await failWithLimit(sid, true);
+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(true);
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ throw turnDispatchUnconfirmedError(`Session ${sessionId} terminated before provider acceptance`);
+ });
+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, candidate, INFO)).toBe('resumed');
+ await flush();
+ const clientId = h.onUiRetry.mock.calls.at(-1)?.[1] as string;
+ // 可能已被 vendor 接住:按已派发提交,不回滚成可重试错误。
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.onUnconfirmedAutoResumeTurn).toHaveBeenCalledTimes(1);
+ expect(h.coordinator.restoreAutoResumeRecovery(sid, clientId, null)).toBe(false);
+ const projection = h.coordinator.getProjection(sid);
+ expect(projection.error).toContain('terminated before provider acceptance');
+ expect(projection.recovery).toBeNull();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ });
+
+ it('re-sends the original input when the failed turn made no progress', async () => {
+ const sid = 'usage-wait-clone';
+ const { h, candidate } = await failWithLimit(sid, false);
+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(true);
+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, candidate, INFO)).toBe('resumed');
+ await flush();
+ expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.autoResume).toBe(true);
+ expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.content).toBe('original long task');
+ });
+
+ it('is invalidated by user actions, an explicit cancel and closing the task', async () => {
+ const cleared = await failWithLimit('usage-wait-clear', true);
+ expect(cleared.h.coordinator.armUsageLimitWait('usage-wait-clear', cleared.candidate, 9_000_000)).toBe(true);
+ cleared.h.coordinator.clearError('usage-wait-clear');
+ expect(latestProjection(cleared.h.projections).usageLimitWait).toBeNull();
+ expect(cleared.h.coordinator.isUsageLimitWaitCurrent('usage-wait-clear', cleared.candidate)).toBe(false);
+ expect(
+ await cleared.h.coordinator.continueAfterUsageLimitReset('usage-wait-clear', cleared.candidate, INFO),
+ ).toBe('superseded');
+
+ const sent = await failWithLimit('usage-wait-user-send', true);
+ expect(sent.h.coordinator.armUsageLimitWait('usage-wait-user-send', sent.candidate, 9_000_000)).toBe(true);
+ sent.h.coordinator.enqueue('usage-wait-user-send', makeItem('q-second', 'do something else'));
+ await flush();
+ expect(sent.h.coordinator.isUsageLimitWaitCurrent('usage-wait-user-send', sent.candidate)).toBe(false);
+
+ const cancelled = await failWithLimit('usage-wait-cancel', true);
+ expect(cancelled.h.coordinator.armUsageLimitWait('usage-wait-cancel', cancelled.candidate, 9_000_000)).toBe(true);
+ const projection = cancelled.h.coordinator.cancelUsageLimitWait('usage-wait-cancel');
+ expect(projection.usageLimitWait).toBeNull();
+ // 错误与手动重试入口保留。
+ expect(projection.error).not.toBeNull();
+ expect(projection.recovery?.kind).toBe('active-turn');
+ expect(
+ await cancelled.h.coordinator.continueAfterUsageLimitReset('usage-wait-cancel', cancelled.candidate, INFO),
+ ).toBe('superseded');
+ expect(cancelled.h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ const closed = await failWithLimit('usage-wait-closed', true);
+ expect(closed.h.coordinator.armUsageLimitWait('usage-wait-closed', closed.candidate, 9_000_000)).toBe(true);
+ closed.h.coordinator.onSessionClosed('usage-wait-closed');
+ expect(closed.h.coordinator.getProjection('usage-wait-closed').usageLimitWait).toBeNull();
+ expect(
+ await closed.h.coordinator.continueAfterUsageLimitReset('usage-wait-closed', closed.candidate, INFO),
+ ).toBe('superseded');
+ });
+
+ it('does not offer a wait for a shared-task guest turn', async () => {
+ const h = createHarness();
+ const sid = 'usage-wait-guest';
+ h.coordinator.enqueue(sid, {
+ ...makeItem('q-guest', 'guest instruction'),
+ sharedTaskAuthor: {
+ sharedTaskId: 'st-1',
+ sessionId: sid,
+ memberId: 'm-1',
+ accountId: 'a-1',
+ displayName: 'Guest',
+ },
+ });
+ await flush();
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', "You've hit your session limit", LIMIT_SIGNALS);
+ await flush();
+ // 授权可能在等待期间被撤销:不自动续,错误与房主手动处理保留。
+ expect(h.onUsageLimitedTurnError).not.toHaveBeenCalled();
+ expect(latestProjection(h.projections).error).toBe("You've hit your session limit");
+ });
+
+ // 访客 steer 的两种时序都不得挂等待:ACK 先到时本轮归属换成访客 steer 项(被访客判据挡住);
+ // 终态先到时 steer 仍在途、不形成可续的 recovery,也就不会报告候选。
+ it('does not offer a wait once a guest steer joined the turn, even before its ack', async () => {
+ const guest = (sid: string, clientId: string) => ({
+ ...makeItem(clientId, 'guest steer'),
+ sharedTaskAuthor: {
+ sharedTaskId: 'st-1',
+ sessionId: sid,
+ memberId: 'm-1',
+ accountId: 'a-1',
+ displayName: 'Guest',
+ },
+ });
+ for (const ackBeforeError of [true, false]) {
+ const h = createHarness();
+ const sid = `usage-wait-guest-steer-${ackBeforeError}`;
+ h.sendToAgent.mockImplementationOnce(async () => {
+ h.setRunning(true);
+ return sendSuccess();
+ });
+ h.coordinator.enqueue(sid, makeItem('owner', 'owner task'));
+ await flush();
+ let ack!: () => void;
+ h.steerToAgent.mockImplementationOnce(() => new Promise<void>((resolve) => { ack = resolve; }));
+ const steering = h.coordinator.steer(sid, guest(sid, 'guest-steer'));
+ await flush();
+ if (ackBeforeError) {
+ ack();
+ await steering;
+ }
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', "You've hit your session limit", LIMIT_SIGNALS);
+ await flush();
+ if (!ackBeforeError) {
+ ack();
+ await steering;
+ await flush();
+ }
+ expect(h.onUsageLimitedTurnError).not.toHaveBeenCalled();
+ }
+
+ // 房主自己的 steer 不影响。
+ const owner = createHarness();
+ const ownerSid = 'usage-wait-owner-steer';
+ owner.sendToAgent.mockImplementationOnce(async () => {
+ owner.setRunning(true);
+ return sendSuccess();
+ });
+ owner.coordinator.enqueue(ownerSid, makeItem('owner', 'owner task'));
+ await flush();
+ await owner.coordinator.steer(ownerSid, makeItem('owner-steer', 'more detail'));
+ await flush();
+ owner.setRunning(false);
+ owner.coordinator.onTurnEvent(ownerSid, 'error', "You've hit your session limit", LIMIT_SIGNALS);
+ await flush();
+ expect(owner.onUsageLimitedTurnError).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects an arm for a superseded candidate even if a newer error is showing', async () => {
+ const sid = 'usage-wait-stale';
+ const { h, candidate } = await failWithLimit(sid, true);
+ // 用户手动重试,随后新的一轮以非限额错误结束。
+ await h.coordinator.retryLastError(sid);
+ await flush();
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', 'some other failure');
+ await flush();
+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(false);
+ expect(latestProjection(h.projections).usageLimitWait).toBeNull();
+ });
+
+ it('only cancels the matching wait when a token is given', async () => {
+ const sid = 'usage-wait-token-cancel';
+ const { h, candidate } = await failWithLimit(sid, true);
+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(true);
+ expect(h.coordinator.cancelUsageLimitWait(sid, candidate + 1000).usageLimitWait).toEqual({
+ resumeAt: 9_000_000,
+ });
+ expect(h.coordinator.cancelUsageLimitWait(sid, candidate).usageLimitWait).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
index 22489c47dc..b22e7229e2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
@@ -37,6 +37,13 @@ describe('isInterruptedTurnError', () => {
},
);
+ it('leaves account usage limits to the reset-time wait instead of a quick reconnect', () => {
+ expect(isInterruptedTurnError({ message: availabilityError, errorStatus: 503, usageLimit: true })).toBe(false);
+ expect(
+ isInterruptedTurnError({ message: availabilityError, codexErrorInfo: 'usageLimitExceeded' }),
+ ).toBe(false);
+ });
+
it.each([502, 503, 504, 529])('still recovers HTTP %s without a rejection category', (errorStatus) => {
expect(isInterruptedTurnError({ message: 'opaque', sdkError: 'server_error', errorStatus })).toBe(true);
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.ts
new file mode 100644
index 0000000000..704a000db4
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.ts
@@ -0,0 +1,210 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES,
+ USAGE_LIMIT_RESUME_BUFFER_MS,
+ UsageLimitAutoResume,
+ isAccountUsageLimitError,
+ type UsageLimitAutoResumeDeps,
+} from '../usageLimitAutoResume';
+import { USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../../shared/agentInputQueue';
+
+const NOW = 1_000_000;
+const RESET_AT = NOW + 60 * 60 * 1000;
+const LIMIT = { sdkError: 'rate_limit', message: "You've hit your session limit" };
+
+function harness(overrides: Partial<UsageLimitAutoResumeDeps> = {}) {
+ const timers: Array<{ fn: () => void; delayMs: number; cleared: boolean }> = [];
+ let tokenSeq = 0;
+ const current = new Set<number>();
+ // coordinator 在终态错误时下发候选令牌;测试里每次 onTurnError 用新令牌。
+ const nextCandidate = () => ++tokenSeq;
+ const deps: UsageLimitAutoResumeDeps = {
+ now: () => NOW,
+ random: () => 0,
+ setTimer: (fn, delayMs) => {
+ const timer = { fn, delayMs, cleared: false };
+ timers.push(timer);
+ return timer;
+ },
+ clearTimer: (handle) => {
+ (handle as { cleared: boolean }).cleared = true;
+ },
+ isEligible: vi.fn(async () => true),
+ resolveResetAt: vi.fn(async () => RESET_AT),
+ arm: vi.fn((_sessionId: string, token: number) => {
+ current.add(token);
+ return true;
+ }),
+ isCurrent: (_sessionId, token) => current.has(token),
+ cancel: vi.fn((_sessionId: string, token: number) => {
+ current.delete(token);
+ }),
+ continueSession: vi.fn(async () => 'resumed' as const),
+ log: () => {},
+ ...overrides,
+ };
+ const raw = new UsageLimitAutoResume(deps);
+ // 测试里省掉候选令牌参数:每次报错自动取一个新令牌。
+ const guard = Object.assign(raw, {
+ onTurnError: (sessionId: string, signals: Parameters<UsageLimitAutoResume['onTurnError']>[1]) =>
+ UsageLimitAutoResume.prototype.onTurnError.call(raw, sessionId, signals, nextCandidate()),
+ });
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+ const fireLast = async () => {
+ const timer = timers.at(-1)!;
+ expect(timer.cleared).toBe(false);
+ timer.fn();
+ await flush();
+ };
+ return { guard, deps, timers, current, flush, fireLast };
+}
+
+describe('isAccountUsageLimitError', () => {
+ it('accepts account limits and rejects overload or unrelated errors', () => {
+ expect(isAccountUsageLimitError(LIMIT)).toBe(true);
+ expect(isAccountUsageLimitError({ codexErrorInfo: 'usageLimitExceeded', message: 'x' })).toBe(true);
+ expect(isAccountUsageLimitError({ errorStatus: 529, message: 'overloaded_error' })).toBe(false);
+ expect(isAccountUsageLimitError({ sdkError: 'billing_error', message: 'credit balance too low' })).toBe(false);
+ expect(isAccountUsageLimitError({ sdkError: 'billing_error', message: 'quota exceeded' })).toBe(false);
+ expect(isAccountUsageLimitError({ errorStatus: 429, message: 'insufficient_quota' })).toBe(false);
+ expect(isAccountUsageLimitError({ message: 'Connection closed mid-response' })).toBe(false);
+ });
+});
+
+describe('UsageLimitAutoResume', () => {
+ it('arms a wait after the reset plus buffer and continues the session when it fires', async () => {
+ const h = harness();
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+
+ expect(h.deps.arm).toHaveBeenCalledWith('s1', 1, RESET_AT + USAGE_LIMIT_RESUME_BUFFER_MS);
+ expect(h.timers).toHaveLength(1);
+ expect(h.timers[0].delayMs).toBe(RESET_AT + USAGE_LIMIT_RESUME_BUFFER_MS - NOW);
+
+ await h.fireLast();
+ expect(h.deps.continueSession).toHaveBeenCalledWith('s1', 1, {
+ reason: USAGE_LIMIT_RESET_AUTO_RESUME_REASON,
+ attempt: 1,
+ maxAttempts: USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES,
+ sessionTotal: 0,
+ });
+ });
+
+ it('does not wait without a usable reset time or for an ineligible session', async () => {
+ const noReset = harness({ resolveResetAt: vi.fn(async () => null) });
+ noReset.guard.onTurnError('s1', LIMIT);
+ await noReset.flush();
+ expect(noReset.deps.arm).not.toHaveBeenCalled();
+
+ const tooFar = harness({ resolveResetAt: vi.fn(async () => NOW + 30 * 24 * 60 * 60 * 1000) });
+ tooFar.guard.onTurnError('s1', LIMIT);
+ await tooFar.flush();
+ expect(tooFar.deps.arm).not.toHaveBeenCalled();
+
+ const goal = harness({ isEligible: vi.fn(async () => false) });
+ goal.guard.onTurnError('s1', LIMIT);
+ await goal.flush();
+ expect(goal.deps.resolveResetAt).not.toHaveBeenCalled();
+ expect(goal.deps.arm).not.toHaveBeenCalled();
+
+ const other = harness();
+ other.guard.onTurnError('s1', { message: 'Connection closed mid-response' });
+ await other.flush();
+ expect(other.deps.isEligible).not.toHaveBeenCalled();
+ });
+
+ it('skips the continuation when the user already took over', async () => {
+ const h = harness();
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ h.current.clear(); // coordinator 侧 recovery 已被用户动作替换
+ await h.fireLast();
+ expect(h.deps.continueSession).not.toHaveBeenCalled();
+ });
+
+ it('re-checks eligibility when the timer fires (e.g. Goal started meanwhile)', async () => {
+ const isEligible = vi.fn(async () => true);
+ const h = harness({ isEligible });
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ isEligible.mockResolvedValue(false);
+ await h.fireLast();
+ expect(h.deps.continueSession).not.toHaveBeenCalled();
+ // 放弃时撤掉横幅上的自动继续提示。
+ expect(h.deps.cancel).toHaveBeenCalledWith('s1', 1);
+ });
+
+ it('withdraws the wait when the continuation does not start', async () => {
+ for (const continueSession of [
+ vi.fn(async () => 'no-progress' as const),
+ vi.fn(async () => {
+ throw new Error('db read failed');
+ }),
+ ]) {
+ const h = harness({ continueSession });
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ await h.fireLast();
+ expect(h.deps.cancel).toHaveBeenCalledWith('s1', 1);
+ }
+ const ok = harness();
+ ok.guard.onTurnError('s1', LIMIT);
+ await ok.flush();
+ await ok.fireLast();
+ expect(ok.deps.cancel).not.toHaveBeenCalled();
+ });
+
+ it('stops after the consecutive cap until progress or a human action resets it', async () => {
+ const h = harness();
+ for (let i = 0; i < USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES; i += 1) {
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ await h.fireLast();
+ }
+ expect(h.deps.continueSession).toHaveBeenCalledTimes(USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES);
+
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ expect(h.deps.arm).toHaveBeenCalledTimes(USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES);
+
+ h.guard.noteProgress('s1');
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ expect(h.deps.arm).toHaveBeenCalledTimes(USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES + 1);
+ });
+
+ it('drops a stale resolution when a newer error arrives, and clears timers on user action', async () => {
+ let release!: (value: number) => void;
+ const first = new Promise<number>((resolve) => { release = resolve; });
+ const resolveResetAt = vi
+ .fn<UsageLimitAutoResumeDeps['resolveResetAt']>()
+ .mockReturnValueOnce(first)
+ .mockResolvedValue(RESET_AT);
+ const h = harness({ resolveResetAt });
+ h.guard.onTurnError('s1', LIMIT);
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ release(RESET_AT + 999);
+ await h.flush();
+ expect(h.deps.arm).toHaveBeenCalledTimes(1);
+ expect(h.deps.arm).toHaveBeenCalledWith('s1', 2, RESET_AT + USAGE_LIMIT_RESUME_BUFFER_MS);
+
+ h.guard.noteUserAction('s1');
+ expect(h.timers.at(-1)!.cleared).toBe(true);
+ });
+
+ it('drops an in-flight resolution once the user takes over or the task closes', async () => {
+ for (const interrupt of ['noteUserAction', 'noteSessionClosed'] as const) {
+ let release!: (value: number) => void;
+ const pending = new Promise<number>((resolve) => { release = resolve; });
+ const h = harness({ resolveResetAt: vi.fn(() => pending) });
+ h.guard.onTurnError('s1', LIMIT);
+ await h.flush();
+ h.guard[interrupt]('s1');
+ release(RESET_AT);
+ await h.flush();
+ expect(h.deps.arm).not.toHaveBeenCalled();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index e9022051ca..ba06764131 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -73,6 +73,7 @@ import {
sanitizeQueuedMessageForPersistence,
updateQueuedMessageContent,
updateQueuedMessageText,
+ USAGE_LIMIT_RESET_AUTO_RESUME_REASON,
} from '../../shared/agentInputQueue.js';
import { CONTINUE_AFTER_ERROR_PROMPT, syntheticTriggerKind } from '../../shared/interruptedTurn.js';
import { isSyntheticTriggerText } from '@cindy/maker-shared/synthetic-trigger';
@@ -411,6 +412,19 @@ export interface AgentInputCoordinatorDeps {
signals: InterruptedTurnErrorSignals,
item: AgentInputQueuedMessage,
) => AutoResumeInfo | null;
+ /**
+ * 一条留下 active-turn recovery、且没有被自愈接管的 terminal error 已经呈现。host 据此
+ * 判断是不是账号限额、解析重置时刻,确定后调 `armUsageLimitWait` 挂上等待计划
+ * (见 maker-ipc/usageLimitAutoResume.ts)。fire-and-forget,不影响错误呈现。
+ * Schedule 输入与用户已接手的候选不会回调。
+ */
+ onUsageLimitedTurnError?: (
+ sessionId: string,
+ signals: InterruptedTurnErrorSignals,
+ item: AgentInputQueuedMessage,
+ /** 绑定本次错误 recovery 的令牌;`armUsageLimitWait` 只认这个令牌。 */
+ candidateToken: number,
+ ) => void;
/**
* **纯判定**:这条 terminal error 有没有可能被自愈接管(`isInterruptedTurnError`)。
* 不消耗额度、不排期、无副作用。
@@ -717,6 +731,17 @@ interface SessionInputState {
autoResumePending: AutoResumeInfo | null;
/** 最新自动接管 attempt;展示态落库后仍保留到 vendor accepted 或明确失败。 */
autoResumeAttemptToken: number | null;
+ /**
+ * 账号限额等待计划。终态错误那一刻登记候选(`resumeAt: null`,绑定当时的 recovery),
+ * host 求出重置时刻后用同一令牌 `armUsageLimitWait` 才生效。只在那个 recovery 仍在、
+ * 错误仍在时有效:用户发新消息 / 重试 / 收下错误 / 清空任务都会换掉 recovery,等待随之
+ * 失效,不需要在每个用户入口单独撤销;迟到的旧查询也挂不到新错误上。
+ */
+ usageLimitWait: {
+ resumeAt: number | null;
+ token: number;
+ recovery: NonNullable<AgentInputRecovery>;
+ } | null;
recovery: AgentInputRecovery;
drainScheduled: boolean;
drainWakeupGeneration: number;
@@ -790,7 +815,8 @@ interface PendingAutoResumeRecovery {
toolLoop: AgentInputToolLoopDetails | null;
stickyError: string | null;
autoResumeInfo: AutoResumeInfo | null;
- attemptToken: number;
+ /** 中断自愈的 attempt 令牌;额度重置后的自动继续不走那套记账,为 null。 */
+ attemptToken: number | null;
}
function createInitialInputState(
@@ -818,6 +844,7 @@ function createInitialInputState(
stickyError: null,
autoResumePending: null,
autoResumeAttemptToken: null,
+ usageLimitWait: null,
recovery: null,
drainScheduled: false,
drainWakeupGeneration: 0,
@@ -842,6 +869,23 @@ function createInitialInputState(
};
}
+/** 候选仍代表用户所见:登记时的 recovery 未被替换、错误仍在、没有别的自愈接管。 */
+function isUsageLimitCandidateCurrent(state: SessionInputState, token?: number): boolean {
+ const wait = state.usageLimitWait;
+ return (
+ wait !== null &&
+ (token === undefined || wait.token === token) &&
+ wait.recovery === state.recovery &&
+ state.error !== null &&
+ state.autoResumePending === null
+ );
+}
+
+/** 已排期(有自动继续时刻)且仍有效的等待。 */
+function isUsageLimitWaitLive(state: SessionInputState, token?: number): boolean {
+ return state.usageLimitWait?.resumeAt != null && isUsageLimitCandidateCurrent(state, token);
+}
+
function readSessionInstanceId(identity: object | null | undefined): string | null {
if (!identity || typeof identity !== 'object') return null;
const id = (identity as { instanceId?: unknown }).instanceId;
@@ -1091,6 +1135,8 @@ function isHostGeneratedSteerItem(item: AgentInputQueuedMessage): boolean {
export class AgentInputCoordinator {
private readonly states = new Map<string, SessionInputState>();
+ /** 账号限额等待计划的单调令牌(跨会话唯一,迟到的 host 定时器据此失效)。 */
+ private usageLimitWaitSeq = 0;
private readonly steerAbortControllers = new Map<string, Map<string, AbortController>>();
/**
* Stop clears visible steer markers before the provider promise necessarily settles. Retain
@@ -2914,11 +2960,25 @@ export class AgentInputCoordinator {
*/
private async performRetryLastError(
sessionId: string,
- opts?: { auto?: boolean; attemptToken?: number },
+ opts?: {
+ auto?: boolean;
+ attemptToken?: number;
+ /** 额度重置后自动继续(`continueAfterUsageLimitReset`),以等待令牌复核用户未接手。 */
+ usageLimitWait?: { token: number; info: AutoResumeInfo };
+ },
): Promise<{ projection: AgentInputProjection; outcome: AutoRetryOutcome }> {
const state = this.getState(sessionId);
const recovery = state.recovery;
if (!recovery) return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ const usageWait = opts?.usageLimitWait;
+ // 等待计划在每个 await 之后都要复核:用户可能在读库期间发了消息 / 收下错误 / 取消等待。
+ const usageWaitSuperseded = (): boolean =>
+ usageWait !== undefined && !isUsageLimitWaitLive(this.getState(sessionId), usageWait.token);
+ if (usageWaitSuperseded()) {
+ return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ }
+ // 自动动作(中断自愈 / 额度重置后继续):隐藏气泡、不算用户发送、保留原 Plan/权限选项。
+ const automatic = Boolean(opts?.auto || usageWait);
// auto 路径的第二道守卫:接管态必须**仍然**成立。
//
// 只看 recovery 不够 —— 用户在退避窗口里自己发了消息时 `enqueue` 清的是接管态,
@@ -2942,6 +3002,12 @@ export class AgentInputCoordinator {
let continueItem: AgentInputQueuedMessage | null = null;
let progressKnown = false;
const previousAutoResumeInfo = opts?.auto ? state.autoResumePending : null;
+ // 额度重置后的续跑记录带上当初的限额原文,作为活动行展开详情里的原因。
+ const automaticResumeInfo = opts?.auto
+ ? previousAutoResumeInfo
+ : usageWait
+ ? { ...usageWait.info, ...(state.error ? { error: state.error } : {}) }
+ : null;
const attemptToken = opts?.auto ? (opts.attemptToken ?? null) : null;
const continuationOnly = Boolean(
opts?.auto && isAcceptedTurnContinuationOnlyReason(previousAutoResumeInfo?.reason),
@@ -2974,6 +3040,9 @@ export class AgentInputCoordinator {
) {
return { projection: this.getProjection(sessionId), outcome: 'superseded' };
}
+ if (usageWaitSuperseded()) {
+ return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ }
} else if (continuationOnly) {
progressKnown = true;
}
@@ -2997,12 +3066,15 @@ export class AgentInputCoordinator {
) {
return { projection: this.getProjection(sessionId), outcome: 'superseded' };
}
+ if (usageWaitSuperseded()) {
+ return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ }
recoveryCheckpoint = buildRecoveryCheckpoint(
- opts?.auto ? 'automatic' : 'manual',
+ automatic ? 'automatic' : 'manual',
recovery.item.clientId,
recovery.item.recoveryCheckpoint,
snapshot,
- opts?.auto ? previousAutoResumeInfo?.attempt : undefined,
+ automatic ? automaticResumeInfo?.attempt : undefined,
);
continueText = appendRecoveryCheckpointPrompt(continueText, recoveryCheckpoint);
} catch (err) {
@@ -3026,6 +3098,9 @@ export class AgentInputCoordinator {
) {
return { projection: this.getProjection(sessionId), outcome: 'superseded' };
}
+ if (usageWaitSuperseded()) {
+ return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ }
}
}
const clientId = crypto.randomUUID();
@@ -3035,11 +3110,11 @@ export class AgentInputCoordinator {
text: continueText,
originalSyntheticTrigger: 'continue',
persistedContent: continueText,
- autoResume: opts?.auto ? true : undefined,
+ autoResume: automatic ? true : undefined,
recoveryCheckpoint,
// 人工 Retry 是新的真人介入周期,不能继承上一轮隐藏自动消息的标记;自动路径
// 则把展示信息随消息落库,成为「已重新连接」活动行的 param 位与展开详情。
- autoResumeInfo: opts?.auto ? (previousAutoResumeInfo ?? undefined) : undefined,
+ autoResumeInfo: automatic ? (automaticResumeInfo ?? undefined) : undefined,
// 附件 / mention 属于原始消息,已在失败 turn 里送达过模型,续跑指令不重带。
files: undefined,
mentions: undefined,
@@ -3050,7 +3125,7 @@ export class AgentInputCoordinator {
supersedesUserClientId: undefined,
// 自动恢复不是计划批准:保留原 Plan/权限选项,不能因隐藏 CONTINUE
// 降到 Full access。人工 Retry 仍沿用既有合成 UI 动作策略。
- createOpts: opts?.auto
+ createOpts: automatic
? { ...recovery.item.createOpts }
: { ...recovery.item.createOpts, planMode: false },
chatMessage: {
@@ -3065,7 +3140,7 @@ export class AgentInputCoordinator {
// queue-head recovery 表示消息从未跨过 accepted 边界,自动重发仍然可能重复一条
// 尚未确认是否落库的输入;这条路径继续交给用户。active-turn recovery 则已经落库,
// 零产出克隆重发是安全的,连续失败次数由 host 守卫负责止损。
- if (opts?.auto && (recovery.kind !== 'active-turn' || (!continueItem && !progressKnown))) {
+ if (automatic && (recovery.kind !== 'active-turn' || (!continueItem && !progressKnown))) {
log.debug('auto retry skipped — progress state is not safe to resend', {
sessionId,
recoveryKind: recovery.kind,
@@ -3098,6 +3173,7 @@ export class AgentInputCoordinator {
// autoResume 行(渲染成「已重新连接」活动行,详情同样可展开)。
state.autoResumePending = null;
if (!opts?.auto) state.autoResumeAttemptToken = null;
+ state.usageLimitWait = null;
state.recovery = null;
if (recovery.kind === 'active-turn') {
let item = continueItem;
@@ -3106,12 +3182,12 @@ export class AgentInputCoordinator {
item = {
...(retryItem ?? recovery.item),
clientId,
- autoResume: opts?.auto ? true : undefined,
- autoResumeInfo: opts?.auto ? (previousAutoResumeInfo ?? undefined) : undefined,
+ autoResume: automatic ? true : undefined,
+ autoResumeInfo: automatic ? (automaticResumeInfo ?? undefined) : undefined,
// 自动 clone 自身会被 renderer 隐藏,不能再软删原始可见 user 行;人工 Retry
// 才用可见克隆取代旧行。显式覆盖也避免继承上一轮的隐藏标记。
retrySourceClientId: recovery.item.retrySourceClientId ?? recovery.item.supersedesUserClientId ?? recovery.item.clientId,
- supersedesUserClientId: opts?.auto ? undefined : recovery.item.clientId,
+ supersedesUserClientId: automatic ? undefined : recovery.item.clientId,
chatMessage: {
...(retryItem ?? recovery.item).chatMessage,
clientId,
@@ -3119,7 +3195,7 @@ export class AgentInputCoordinator {
},
};
}
- if (opts?.auto && attemptToken !== null) {
+ if ((opts?.auto && attemptToken !== null) || usageWait) {
this.pendingAutoResumeRecoveries.set(item.clientId, {
sessionId,
stateRef: state,
@@ -3146,11 +3222,11 @@ export class AgentInputCoordinator {
this.deps.onUiRetry?.(
sessionId,
item.clientId,
- opts?.auto ? 'auto' : 'manual',
+ automatic ? 'auto' : 'manual',
attemptToken ?? undefined,
);
}
- if (!opts?.auto) this.touchUserSend(sessionId);
+ if (!automatic) this.touchUserSend(sessionId);
this.emit(sessionId);
this.scheduleDrain(sessionId, 'retry');
this.scheduleExternalTurnRetryIfNeeded(sessionId, state, 'retry');
@@ -3755,6 +3831,9 @@ export class AgentInputCoordinator {
}
}
this.emit(sessionId);
+ if (!takeover && outcome === 'kept' && active.item) {
+ this.notifyUsageLimitedTurnError(sessionId, active.item, message, signals);
+ }
return;
}
if (active?.persisting) {
@@ -3965,6 +4044,8 @@ export class AgentInputCoordinator {
state.suppressedTerminalError = null;
if (!opts?.preserveAutoResumeIntent) {
this.supersedePendingAutoResumeRecoveries(sessionId);
+ // 任务被关闭:限额等待也一并撤销,到点不能把已关闭的任务重新拉起来。
+ state.usageLimitWait = null;
}
const releasedAbortLock = state.queueAbortPending;
this.cancelScheduledDrain(state);
@@ -4173,6 +4254,9 @@ export class AgentInputCoordinator {
...(state.error && state.toolLoop ? { toolLoop: state.toolLoop } : {}),
recovery,
...(autoResumePending ? { autoResumePending } : {}),
+ usageLimitWait: isUsageLimitWaitLive(state)
+ ? { resumeAt: state.usageLimitWait!.resumeAt! }
+ : null,
errorRetryText: projectionRetryText(state.pendingQueue, state.recovery),
credentialSwitchWait: state.credentialSwitchWait
? {
@@ -5493,6 +5577,11 @@ export class AgentInputCoordinator {
state: SessionInputState,
item: AgentInputQueuedMessage,
): boolean {
+ // 额度重置后的续跑没有中断自愈令牌(sessionTotal 刻意为 0):以派发前回滚记录仍在为准,
+ // 用户接手 / 清空会话都会撤掉它。
+ if (item.autoResumeInfo?.reason === USAGE_LIMIT_RESET_AUTO_RESUME_REASON) {
+ return this.pendingAutoResumeRecoveries.get(item.clientId)?.stateRef === state;
+ }
const attemptToken = item.autoResumeInfo?.sessionTotal;
return typeof attemptToken === 'number' && state.autoResumeAttemptToken === attemptToken;
}
@@ -5660,7 +5749,11 @@ export class AgentInputCoordinator {
* 自动续跑项在 pre-vendor 边界被丢弃时恢复原错误入口。
* 返回 false 表示它已经被用户动作取代、会话已清空,或已跨过 dispatch 边界。
*/
- restoreAutoResumeRecovery(sessionId: string, clientId: string, attemptToken: number): boolean {
+ restoreAutoResumeRecovery(
+ sessionId: string,
+ clientId: string,
+ attemptToken: number | null,
+ ): boolean {
const pending = this.pendingAutoResumeRecoveries.get(clientId);
if (!pending) return false;
const state = this.states.get(sessionId);
@@ -5668,7 +5761,7 @@ export class AgentInputCoordinator {
pending.sessionId !== sessionId ||
pending.attemptToken !== attemptToken ||
state !== pending.stateRef ||
- state.autoResumeAttemptToken !== attemptToken
+ (attemptToken !== null && state.autoResumeAttemptToken !== attemptToken)
) {
return false;
}
@@ -6330,6 +6423,82 @@ export class AgentInputCoordinator {
}
}
+ private notifyUsageLimitedTurnError(
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ message?: string,
+ signals?: Omit<InterruptedTurnErrorSignals, 'message'>,
+ ): void {
+ // scheduler origin(含复用它的 Slack / X / Telegram Hook 消息)终态失败时本就不留
+ // recovery、由各自 runner 收尾,没有可续的入口。共享任务访客的回合也不自动续:
+ // 授权可能在等待期间被撤销,数小时后替访客重发原指令不安全,交给房主手动处理。
+ if (
+ !this.deps.onUsageLimitedTurnError ||
+ isSchedulerOriginItem(item) ||
+ item.sharedTaskAuthor
+ ) {
+ return;
+ }
+ const state = this.states.get(sessionId);
+ if (!state || state.recovery?.kind !== 'active-turn' || state.error === null) return;
+ const token = ++this.usageLimitWaitSeq;
+ state.usageLimitWait = { resumeAt: null, token, recovery: state.recovery };
+ try {
+ this.deps.onUsageLimitedTurnError(sessionId, { ...(signals ?? {}), message }, item, token);
+ } catch (err) {
+ log.warn('onUsageLimitedTurnError failed', { sessionId, error: errorMessage(err) });
+ }
+ }
+
+ /**
+ * 普通任务撞上账号限额后挂等待计划:错误与手动重试照常保留,到 `resumeAt` 仍无人处理时
+ * host 调 `continueAfterUsageLimitReset`。只认终态错误时下发的候选令牌、且那次错误的
+ * recovery 仍在;返回 false 表示目标已不在(用户已接手、任务已关闭等)。
+ */
+ armUsageLimitWait(sessionId: string, token: number, resumeAt: number): boolean {
+ const state = this.states.get(sessionId);
+ if (!state || state.activeTurn !== null || !isUsageLimitCandidateCurrent(state, token)) {
+ return false;
+ }
+ state.usageLimitWait = { ...state.usageLimitWait!, resumeAt };
+ this.emit(sessionId);
+ return true;
+ }
+
+ /** 等待计划是否仍有效(host 到点前复核用)。 */
+ isUsageLimitWaitCurrent(sessionId: string, token: number): boolean {
+ const state = this.states.get(sessionId);
+ return state ? isUsageLimitWaitLive(state, token) : false;
+ }
+
+ /**
+ * 撤销自动继续:只撤等待,错误与手动重试入口保留。用户取消时不带令牌;host 到点放弃时
+ * 带令牌,只撤自己那一次,不误撤之后新挂上的等待。
+ */
+ cancelUsageLimitWait(sessionId: string, token?: number): AgentInputProjection {
+ const state = this.getState(sessionId);
+ if (state.usageLimitWait && (token === undefined || state.usageLimitWait.token === token)) {
+ state.usageLimitWait = null;
+ this.emit(sessionId);
+ }
+ return this.getProjection(sessionId);
+ }
+
+ /**
+ * 额度重置后自动继续:与人工「继续」同一条已验证路径(有产出发续跑指令、零产出重发原文),
+ * 但按自动动作落库(隐藏气泡、显示「额度已恢复,已自动继续」活动行、不算用户发送)。
+ */
+ async continueAfterUsageLimitReset(
+ sessionId: string,
+ token: number,
+ info: AutoResumeInfo,
+ ): Promise<AutoRetryOutcome> {
+ const { outcome } = await this.performRetryLastError(sessionId, {
+ usageLimitWait: { token, info },
+ });
+ return outcome;
+ }
+
abandonAutoResume(sessionId: string, message?: string, attemptToken?: number): void {
const state = this.getState(sessionId);
if (attemptToken !== undefined && state.autoResumeAttemptToken !== attemptToken) {
@@ -6691,6 +6860,19 @@ export class AgentInputCoordinator {
}
}
this.emit(sessionId);
+ if (
+ !deferredTakeover &&
+ outcome === 'kept' &&
+ active.item &&
+ terminalEvent.supersededByUser !== true
+ ) {
+ this.notifyUsageLimitedTurnError(
+ sessionId,
+ active.item,
+ terminalEvent.message,
+ terminalEvent.signals,
+ );
+ }
return;
}
state.error = null;
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 3df3a8b28a..b61d52af5f 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -45,6 +45,8 @@ export const MAKER_INVOKE = {
INPUT_RESUME: 'maker:input:resume',
INPUT_RETRY_LAST_ERROR: 'maker:input:retry-last-error',
INPUT_CLEAR_ERROR: 'maker:input:clear-error',
+ /** 取消账号限额重置后的自动继续(只撤等待,错误与手动重试保留)。 */
+ INPUT_CANCEL_USAGE_LIMIT_WAIT: 'maker:input:cancel-usage-limit-wait',
/**
* Renderer 侧 auth-retry 放弃(catch 或 guard fall-through)时调用,告知 main 补落持久化。
* main 侧在相同 isRemoteAuthRetry 条件下跳过了 onTurnErrorEvent;此 IPC 覆盖"未重试/重试失败"两路。
diff --git a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts
index cfba40d1ed..58e38c743e 100644
--- a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts
+++ b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts
@@ -45,6 +45,12 @@ export interface InterruptedTurnErrorSignals {
errorStatus?: number;
/** Bounded details for the live error projection; never contains raw provider data. */
toolLoop?: AgentInputToolLoopDetails;
+ /** translator 判定的账号用量 / 限流错误。 */
+ usageLimit?: boolean;
+ /** 上游给出的限额重置时刻(unix ms)。 */
+ usageResetAt?: number;
+ /** Codex app-server 的结构化错误 tag(如 `usageLimitExceeded`)。 */
+ codexErrorInfo?: string;
}
/**
@@ -203,6 +209,8 @@ export function isInterruptedTurnError(signals: InterruptedTurnErrorSignals): bo
// Prefer provider status/tags to text compatibility. In particular, an auth,
// quota or invalid-request rejection must not become retryable just because
// its explanation mentions temporary unavailability or also carries a 5xx.
+ // 账号限额要等周期重置,秒级重连只会再撞一次(由 usageLimitAutoResume 等到重置后续跑)。
+ if (signals.usageLimit === true || signals.codexErrorInfo === 'usageLimitExceeded') return false;
const status = signals.errorStatus;
if (status !== undefined && status >= 400 && status < 500) return false;
if ([
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 363252ea33..a8d0386184 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -145,6 +145,7 @@ import {
isAutomaticInputOriginKind,
normalizeAgentInputClearBoundaryMs,
serializeSessionReferencePayload,
+ USAGE_LIMIT_RESET_AUTO_RESUME_REASON,
type AgentInputClearBoundaryOpts,
type AgentInputCreateOpts,
type AgentInputQueuedMessage,
@@ -910,6 +911,9 @@ import {
import { clearSealedCodexPlanState, readCodexPlanState } from '../localDb/codexPlanState.js';
import { buildCompletedPlanGuardNote, buildPlanReconcileNote } from './planReconcile.js';
import { peekGoalInactiveNote } from '../goal-host/inactiveNote.js';
+import { readTurnUsageResetAt } from '../goal-host/usageLimit.js';
+import { readAccountUsageLimit, subscriptionFamilyOf } from '../usage/accountUsageLimit.js';
+import { UsageLimitAutoResume } from './usageLimitAutoResume.js';
import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';
import { persistAndHydrateSessionProvider } from './sessionProviderBootstrap.js';
import { registerMakerSessionSendHandler } from './sessionSendHandler.js';
@@ -1150,7 +1154,7 @@ import {
import { stampSharedTaskInput } from './sharedTaskInput.js';
import { createSharedTaskContextUsageGuard } from './sharedTaskContextUsage.js';
import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
-import { assertSharedTaskInteractionResolveCurrent, setSharedTaskInteractionReader, setSharedTaskQueueReader } from '../device-link/sharedTaskDispatch.js';
+import { assertSharedTaskInteractionResolveCurrent, isSessionSharedTaskActive, setSharedTaskInteractionReader, setSharedTaskQueueReader } from '../device-link/sharedTaskDispatch.js';
function captureSharedTaskSettingGuard(sessionId: string) {
const context = getDeviceLinkInvokeContext();
@@ -1311,6 +1315,99 @@ const interruptedTurnAutoResumeGuard = new InterruptedTurnAutoResumeGuard({
let settlePendingSessionRuntimeControlHolder: ((sessionId: string, reason: string) => void) | null =
null;
+/**
+ * 目标模式是否在管这个会话(active / usageLimited 时由 goal-host 自己等额度重置)。
+ * setter 注入避免 register↔goal-host 环;bootstrap 接上 GoalController。
+ */
+let goalOwnsUsageLimitProbe: ((sessionId: string) => Promise<boolean>) | null = null;
+export function setGoalOwnsUsageLimitProbe(
+ probe: ((sessionId: string) => Promise<boolean>) | null,
+): void {
+ goalOwnsUsageLimitProbe = probe;
+}
+
+async function isUsageLimitAutoResumeEligible(sessionId: string): Promise<boolean> {
+ if (agentInputCoordinatorHolder?.isExecutionPaused(sessionId)) return false;
+ const row = await getSessionRowSnapshot(sessionId);
+ // Orca worker 的失败已桥给 Lead 重新安排;伙伴有自己的候选链与群聊编排,都不在这里续跑。
+ if (!row || row.orcaRole === 'worker' || row.source === 'bot') return false;
+ // 共享中的任务撞上限额不自动等待(Dash 2026-10-08):访客可能已影响本任务,等待期间撤权后
+ // 到点续跑不安全,交给房主手动处理。报错时与到点时都复核。
+ if (isSessionSharedTaskActive(sessionId)) return false;
+ return !(await goalOwnsUsageLimitProbe?.(sessionId).catch(() => false));
+}
+
+/**
+ * 会话当前实际在跑的来源与模型:临时切换(set_session_runtime)或自动降级的运行时覆盖优先,
+ * 否则用会话保存的选择。分模型额度必须按实际运行的模型匹配。
+ */
+export function resolveSessionRuntimeRoute(
+ sessionId: string,
+ agentKind: string,
+ saved: { providerId?: string | null; model?: string | null } | null,
+): { providerId: string | null; modelId: string | null } {
+ const override = getSessionRuntimeControlSnapshot(sessionId).effectiveOverride;
+ if (override && override.agentKind === agentKind) {
+ return { providerId: override.providerId ?? null, modelId: override.model ?? null };
+ }
+ return {
+ providerId: getSessionProvider(sessionId) ?? saved?.providerId ?? null,
+ modelId: saved?.model ?? null,
+ };
+}
+
+/**
+ * 会话所用账号的重置时刻:错误自带 → 报错原文 → 订阅用量快照(须显示已用满)。
+ * 只服务订阅账号:API key / Coding Plan / 网关等来源的普通 429 即使带 Retry-After,也不是
+ * 周期额度耗尽,按产品规则只报错不等待。
+ */
+async function resolveSessionUsageResetAt(
+ sessionId: string,
+ signals: InterruptedTurnErrorSignals,
+): Promise<number | null> {
+ const row = await getSessionRowSnapshot(sessionId);
+ const agentKind = row?.agentKind ? dbToMakerAgentKind(row.agentKind) : null;
+ if (!row || !agentKind) return null;
+ const { providerId, modelId } = resolveSessionRuntimeRoute(sessionId, agentKind, row);
+ if (!subscriptionFamilyOf(agentKind, providerId)) return null;
+ // SSH 远程会话的报错用远端主机的本地时间:不带时区的钟点不按本机时区理解。
+ const fromError = readTurnUsageResetAt(signals, Date.now(), {
+ localTimeZoneTrusted: !row.remoteHostId,
+ });
+ if (fromError !== null) return fromError;
+ // SSH 远程会话用远端主机自己的登录,本机快照属于另一个账号,不能拿来推算。
+ if (row.remoteHostId) return null;
+ const limit = await readAccountUsageLimit(agentKind, providerId, modelId);
+ return limit?.limited ? limit.resetAtMs : null;
+}
+
+// 普通任务撞上账号限额:照常报错,同时等额度重置后自动继续(仅本次运行内有效)。
+// coordinator 是可变绑定,必须懒读。
+const usageLimitAutoResume = new UsageLimitAutoResume({
+ now: () => Date.now(),
+ random: () => Math.random(),
+ setTimer: (fn, delayMs) => {
+ const timer = setTimeout(fn, delayMs);
+ timer.unref?.();
+ return timer;
+ },
+ clearTimer: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
+ isEligible: isUsageLimitAutoResumeEligible,
+ resolveResetAt: resolveSessionUsageResetAt,
+ arm: (sessionId, token, resumeAt) =>
+ agentInputCoordinatorHolder?.armUsageLimitWait(sessionId, token, resumeAt) ?? false,
+ isCurrent: (sessionId, token) =>
+ agentInputCoordinatorHolder?.isUsageLimitWaitCurrent(sessionId, token) ?? false,
+ cancel: (sessionId, token) => {
+ agentInputCoordinatorHolder?.cancelUsageLimitWait(sessionId, token);
+ },
+ continueSession: async (sessionId, token, info) =>
+ agentInputCoordinatorHolder
+ ? agentInputCoordinatorHolder.continueAfterUsageLimitReset(sessionId, token, info)
+ : 'superseded',
+ log: (message, fields) => log.info(message, fields),
+});
+
// Schedule 不另建重试状态机:真正的恢复仍由 AgentInputCoordinator +
// AutoResumeBookkeeping 独占。这里仅把「这一轮 scheduler run 已被普通自动续跑接管」
// 和「最终仍失败」桥给 runner,让同一个 run 继续等待或正确失败。
@@ -1491,6 +1588,8 @@ function resetAutomaticRecoveryForExplicitStop(sessionId: string): void {
}
function autoResumeAttemptToken(item: AgentInputQueuedMessage): number | null {
+ // 额度重置后的续跑不走中断自愈记账,它的 sessionTotal(0)不是令牌。
+ if (item.autoResumeInfo?.reason === USAGE_LIMIT_RESET_AUTO_RESUME_REASON) return null;
const value = item.autoResumeInfo?.sessionTotal;
return item.autoResume === true && typeof value === 'number' ? value : null;
}
@@ -1528,6 +1627,11 @@ function settleUndispatchedInterruptedAutoResume(
sessionId: string,
item: AgentInputQueuedMessage,
): boolean {
+ // 额度重置后的自动继续不走中断自愈记账(sessionTotal 刻意为 0),只需恢复原错误与手动重试入口。
+ if (item.autoResume === true && item.autoResumeInfo?.reason === USAGE_LIMIT_RESET_AUTO_RESUME_REASON) {
+ agentInputCoordinatorHolder?.restoreAutoResumeRecovery(sessionId, item.clientId, null);
+ return false;
+ }
const attemptToken = autoResumeAttemptToken(item);
if (attemptToken === null) return false;
const ownsAttempt = autoResumeBookkeeping.hasPendingLifecycleForClient(
@@ -4774,6 +4878,7 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSession
// from being resurrected or attaching recovery to a replacement runtime.
interruptedTurnAutoResumeGuard.noteSessionReset(session.id);
autoResumeBookkeeping.teardown(session.id);
+ usageLimitAutoResume.noteSessionClosed(session.id);
},
// Read at the coordinator boundary, as before: only a close/rebuild window
// preserves the signal currently driving that rebuild, not the old queue.
@@ -4915,6 +5020,9 @@ const sessionEventDependencies: SessionEventDependencies = {
get log() {
return log;
},
+ get usageLimitAutoResume() {
+ return usageLimitAutoResume;
+ },
get interruptedTurnAutoResumeGuard() {
return interruptedTurnAutoResumeGuard;
},
@@ -14156,7 +14264,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// hard upper bound.
const isAutomaticPrompt = isAutomaticInputOriginKind(originKind);
silentStopAutoResumeGuard.noteUserSend(sessionId);
- if (!isAutomaticPrompt) interruptedTurnAutoResumeGuard.noteUserSend(sessionId);
+ if (!isAutomaticPrompt) {
+ interruptedTurnAutoResumeGuard.noteUserSend(sessionId);
+ usageLimitAutoResume.noteUserAction(sessionId);
+ }
}
// 落库失败 → 撤掉刚才那条待确认登记:那条消息压根不存在,留着会让后续事件去 patch
// 一个不存在的 clientId,map 也一直脏着(copilot review)。登记刻意放在写之前(不能
@@ -15680,6 +15791,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 两处必须同判据 —— 否则会出现"按住了却永远不接管"或"没按住却接管"的错配。
isResumableTurnErrorCandidate: canRecoverTurn,
// 被按住的 error 最终没接管 → 只补落 error 行(横幅 coordinator 自己设)。
+ onUsageLimitedTurnError: (sessionId, signals, _item, candidateToken) => {
+ usageLimitAutoResume.onTurnError(sessionId, signals, candidateToken);
+ },
onResumableTurnErrorDiscarded: (
sessionId: string,
options: { surfaceError: boolean; owner: SuppressedTurnErrorOwner },
@@ -16032,6 +16146,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// persistence/vendor await, so a failed manual retry still starts a fresh episode.
silentStopAutoResumeGuard.noteUserSend(sessionId);
interruptedTurnAutoResumeGuard.noteUserSend(sessionId);
+ usageLimitAutoResume.noteUserAction(sessionId);
}
publishUiContinuation(sessionId, clientId);
},
@@ -17531,6 +17646,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return inputCoordinator.clearError(sid);
});
+ ipcMain.handle(
+ MAKER_INVOKE.INPUT_CANCEL_USAGE_LIMIT_WAIT,
+ async (event, sessionId: unknown, opts?: unknown) => {
+ const remote = isDeviceLinkInvoke();
+ // 本机调用必须来自 Cindy 自己的 renderer;device-link 调用由隧道上下文与输入控制边界把关。
+ if (!remote) assertTrustedAppRendererEvent(event);
+ const sid = requireSessionId(sessionId);
+ await assertRemoteInputControlBoundary(sid, remote, opts);
+ usageLimitAutoResume.clear(sid);
+ return inputCoordinator.cancelUsageLimitWait(sid);
+ },
+ );
+
// renderer auth-retry 放弃时(catch / guard fall-through)调回 main 补落持久化。
// main 侧在 isRemoteAuthRetry 条件下跳过了 onTurnErrorEvent;此处覆盖"重试失败/不能重试"两路。
// agentMetaRaw:renderer 传来的 event.agentMeta(可选),用于 flushAssistantBlock 边界 meta 兜底
@@ -19702,8 +19830,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertTrustedSender: (event) => assertTrustedAppRendererEvent(
event as Parameters<typeof assertTrustedAppRendererEvent>[0],
),
- apply: (sessionId, model, providerId, revision, selection) =>
- handleSetModel(sessionId, model, providerId, revision, selection, { source: 'user' }),
+ apply: (sessionId, model, providerId, revision, selection) => {
+ // 用户动手换模型或来源即视为接手:在进入切换(含等锁、重建会话)之前就撤销额度等待,
+ // 不让到点的续跑抢在切换期间派发。切换失败时错误与手动重试仍在,不恢复等待。
+ if (typeof sessionId === 'string') {
+ usageLimitAutoResume.noteUserAction(sessionId);
+ agentInputCoordinatorHolder?.cancelUsageLimitWait(sessionId);
+ }
+ return handleSetModel(sessionId, model, providerId, revision, selection, { source: 'user' });
+ },
});
const recoverRemoteRuntimeAxisPersistence = async (
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
index a39e9ac181..1efa14f2d5 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
@@ -47,6 +47,7 @@ import {
InterruptedTurnAutoResumeGuard,
isSubstantiveProgressEvent,
} from './interruptedTurnAutoResume.js';
+import type { UsageLimitAutoResume } from './usageLimitAutoResume.js';
import { isBotGroupClientId } from '../../shared/botGroupChat.js';
/** Bot DMs and group-lane turns answer an internal channel, not the user watching this Session. */
@@ -69,6 +70,8 @@ export interface PrepareSessionEventDeps {
InterruptedTurnAutoResumeGuard,
'noteAttemptEvent' | 'noteTurnStarted' | 'noteAttemptSettled' | 'noteProgress'
>;
+ /** 限额自动继续:有实质产出时重算连续自动继续次数。 */
+ readonly usageLimitAutoResume?: Pick<UsageLimitAutoResume, 'noteProgress'>;
readonly redactEventForRenderer: (event: AgentEvent) => AgentEvent;
readonly handleAgentIslandInteractionDismissed: (sessionId: string, requestId: string) => void;
readonly clearPendingInteraction: (requestId: string) => DismissedInteraction | null;
@@ -468,6 +471,9 @@ export function prepareSessionEvent(
sdkError?: unknown;
errorStatus?: unknown;
toolLoop?: unknown;
+ usageLimit?: unknown;
+ usageResetAt?: unknown;
+ codexErrorInfo?: unknown;
}
| undefined)
: undefined;
@@ -511,6 +517,14 @@ export function prepareSessionEvent(
...(typeof errData?.reason === 'string' ? { reason: errData.reason } : {}),
...(typeof errData?.errorStatus === 'number' ? { errorStatus: errData.errorStatus } : {}),
...(toolLoop ? { toolLoop } : {}),
+ // 账号限额信号:普通任务据此等额度重置后自动继续(见 usageLimitAutoResume.ts)。
+ ...(errData?.usageLimit === true ? { usageLimit: true } : {}),
+ ...(typeof errData?.usageResetAt === 'number' && Number.isFinite(errData.usageResetAt)
+ ? { usageResetAt: errData.usageResetAt }
+ : {}),
+ ...(typeof errData?.codexErrorInfo === 'string'
+ ? { codexErrorInfo: errData.codexErrorInfo }
+ : {}),
},
{
sessionTurnGeneration: event.sessionTurnGeneration,
@@ -548,6 +562,7 @@ export function prepareSessionEvent(
if (accepted && typeof progressAttemptToken === 'number') {
deps.autoResumeBookkeeping.settleOutcome(session.id, progressAttemptToken, 'succeeded');
}
+ deps.usageLimitAutoResume?.noteProgress(session.id);
}
return {
event,
diff --git a/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.ts b/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.ts
new file mode 100644
index 0000000000..833f55853d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.ts
@@ -0,0 +1,191 @@
+/**
+ * 普通任务的账号限额自动继续 —— 撞上 5 小时 / 周限额后照常报错,同时等额度重置;
+ * 到点用户仍没处理,就自动继续这个任务。
+ *
+ * 分工:
+ * - coordinator 持有用户可见状态(错误 + `usageLimitWait`),并以「同一个 recovery 仍在」
+ * 作为「用户没接手」的唯一判据(`armUsageLimitWait` / `continueAfterUsageLimitReset`)。
+ * - 本模块只做判定、求重置时刻和定时;所有用户动作(发消息、重试、收下错误、取消、清空)
+ * 都由 coordinator 自然作废等待,这里到点复核即可,不需要逐个入口撤销。
+ *
+ * 产品约束(2026-10-07):
+ * - 只在本次运行内有效,不落盘;重启后停在报错,交给用户。
+ * - 拿不到可靠重置时刻(Coding Plan、API key、网关个人额度等)就不等,也不定时试探。
+ * - 同一任务连续自动继续而没有任何实质产出达到上限后停下,防止重置时刻算早时反复撞限额。
+ */
+
+import type { AutoResumeInfo } from '../../shared/agentInputQueue.js';
+import { USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../shared/agentInputQueue.js';
+import { classifyTurnOverload, classifyTurnUsageLimit } from '../goal-host/usageLimit.js';
+import type { InterruptedTurnErrorSignals } from './interruptedTurnAutoResume.js';
+
+/** 重置后再等一会儿:上游各窗口的重置有秒级偏差,过早会再撞一次。 */
+export const USAGE_LIMIT_RESUME_BUFFER_MS = 60_000;
+/** 同一账号的多个任务会在同一刻醒来,错开一点避免同时涌入。 */
+export const USAGE_LIMIT_RESUME_JITTER_MS = 30_000;
+/** 超过这个等待时长不排(周限额最长 7 天;更远的时刻多半是解析错误)。 */
+export const USAGE_LIMIT_MAX_WAIT_MS = 8 * 24 * 60 * 60 * 1000;
+/** 两次实质产出之间最多自动继续几次。 */
+export const USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES = 3;
+
+export type UsageLimitContinueOutcome = 'resumed' | 'superseded' | 'no-progress';
+
+export interface UsageLimitAutoResumeDeps {
+ now(): number;
+ random(): number;
+ setTimer(fn: () => void, delayMs: number): unknown;
+ clearTimer(handle: unknown): void;
+ /** 该会话是否交给本机制(排除目标模式、Orca worker、伙伴等由别的机制负责的会话)。 */
+ isEligible(sessionId: string): Promise<boolean>;
+ /** 会话所用账号的重置时刻(unix ms):错误自带 → 报错原文 → 订阅快照;拿不到为 null。 */
+ resolveResetAt(sessionId: string, signals: InterruptedTurnErrorSignals): Promise<number | null>;
+ /** 用终态错误时 coordinator 下发的候选令牌挂上等待;false = 那次错误已不是当前状态。 */
+ arm(sessionId: string, token: number, resumeAt: number): boolean;
+ isCurrent(sessionId: string, token: number): boolean;
+ /** 放弃这一次等待(到点时已不归本机制管),撤掉横幅上的自动继续提示。 */
+ cancel(sessionId: string, token: number): void;
+ continueSession(
+ sessionId: string,
+ token: number,
+ info: AutoResumeInfo,
+ ): Promise<UsageLimitContinueOutcome>;
+ log(message: string, fields?: Record<string, unknown>): void;
+}
+
+/** 是否为账号额度用尽(不含上游容量过载:那由中断自愈按秒级退避处理)。 */
+export function isAccountUsageLimitError(signals: InterruptedTurnErrorSignals): boolean {
+ return classifyTurnUsageLimit(signals) && !classifyTurnOverload(signals);
+}
+
+export class UsageLimitAutoResume {
+ private readonly timers = new Map<string, { token: number; handle: unknown }>();
+ private readonly consecutive = new Map<string, number>();
+ /** 每次新错误 / 用户接手 / 任务关闭都递增;迟到的异步解析结果据此丢弃。 */
+ private readonly generations = new Map<string, number>();
+ private disposed = false;
+
+ constructor(private readonly deps: UsageLimitAutoResumeDeps) {}
+
+ onTurnError(
+ sessionId: string,
+ signals: InterruptedTurnErrorSignals,
+ candidateToken: number,
+ ): void {
+ if (this.disposed || !isAccountUsageLimitError(signals)) return;
+ const used = this.consecutive.get(sessionId) ?? 0;
+ if (used >= USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES) {
+ this.deps.log('usage-limit auto-resume exhausted', { sessionId, used });
+ return;
+ }
+ const generation = this.bumpGeneration(sessionId);
+ void this.schedule(sessionId, signals, candidateToken, generation).catch((err) => {
+ this.deps.log('usage-limit auto-resume scheduling failed', {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
+ }
+
+ private bumpGeneration(sessionId: string): number {
+ const generation = (this.generations.get(sessionId) ?? 0) + 1;
+ this.generations.set(sessionId, generation);
+ return generation;
+ }
+
+ private async schedule(
+ sessionId: string,
+ signals: InterruptedTurnErrorSignals,
+ token: number,
+ generation: number,
+ ): Promise<void> {
+ if (!(await this.deps.isEligible(sessionId))) return;
+ const resetAt = await this.deps.resolveResetAt(sessionId, signals);
+ if (this.disposed || this.generations.get(sessionId) !== generation) return;
+ const now = this.deps.now();
+ if (resetAt === null || resetAt - now > USAGE_LIMIT_MAX_WAIT_MS) {
+ this.deps.log('usage-limit auto-resume skipped: no usable reset time', {
+ sessionId,
+ hasResetAt: resetAt !== null,
+ });
+ return;
+ }
+ // 已过点(错误到达时额度刚好重置)也按最短缓冲继续。
+ const resumeAt =
+ Math.max(resetAt, now) +
+ USAGE_LIMIT_RESUME_BUFFER_MS +
+ Math.floor(this.deps.random() * USAGE_LIMIT_RESUME_JITTER_MS);
+ if (!this.deps.arm(sessionId, token, resumeAt)) return;
+ this.clear(sessionId);
+ const handle = this.deps.setTimer(() => {
+ void this.fire(sessionId, token);
+ }, resumeAt - now);
+ this.timers.set(sessionId, { token, handle });
+ this.deps.log('usage-limit auto-resume scheduled', { sessionId, resumeAt });
+ }
+
+ private async fire(sessionId: string, token: number): Promise<void> {
+ const pending = this.timers.get(sessionId);
+ if (pending?.token === token) this.timers.delete(sessionId);
+ if (this.disposed || !this.deps.isCurrent(sessionId, token)) return;
+ // 等待期间可能开了目标模式、暂停了执行等:到点再判一次归属。放弃时撤掉提示,
+ // 不留下一个过了点却不会执行的「将于 X 自动继续」。
+ if (!(await this.deps.isEligible(sessionId))) {
+ this.deps.cancel(sessionId, token);
+ return;
+ }
+ const attempt = (this.consecutive.get(sessionId) ?? 0) + 1;
+ this.consecutive.set(sessionId, attempt);
+ let outcome: UsageLimitContinueOutcome;
+ try {
+ outcome = await this.deps.continueSession(sessionId, token, {
+ reason: USAGE_LIMIT_RESET_AUTO_RESUME_REASON,
+ attempt,
+ maxAttempts: USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES,
+ // sessionTotal 兼作中断自愈的 attempt 令牌(见 register 的 autoResumeAttemptTokenFromAgentMeta);
+ // 0 永远不是有效令牌,避免与进行中的重连记账串号。本行也不展示累计次数。
+ sessionTotal: 0,
+ });
+ } catch (err) {
+ this.deps.log('usage-limit auto-resume failed', {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ this.deps.cancel(sessionId, token);
+ return;
+ }
+ // 没真正续上(如判断不了有无产出):撤掉已过点的提示,保留原错误与手动重试,不再自动等待。
+ if (outcome !== 'resumed') this.deps.cancel(sessionId, token);
+ this.deps.log('usage-limit auto-resume fired', { sessionId, outcome, attempt });
+ }
+
+ /** 任务有了实质产出:重新计算连续自动继续次数。 */
+ noteProgress(sessionId: string): void {
+ this.consecutive.delete(sessionId);
+ }
+
+ /** 用户亲自接手(发消息 / 手动重试):作废在途查询、撤掉定时器并重置次数。 */
+ noteUserAction(sessionId: string): void {
+ this.consecutive.delete(sessionId);
+ this.bumpGeneration(sessionId);
+ this.clear(sessionId);
+ }
+
+ /** 任务被关闭:作废在途查询与定时器(coordinator 侧等待同时撤销)。 */
+ noteSessionClosed(sessionId: string): void {
+ this.bumpGeneration(sessionId);
+ this.clear(sessionId);
+ }
+
+ clear(sessionId: string): void {
+ const pending = this.timers.get(sessionId);
+ if (!pending) return;
+ this.deps.clearTimer(pending.handle);
+ this.timers.delete(sessionId);
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ for (const { handle } of this.timers.values()) this.deps.clearTimer(handle);
+ this.timers.clear();
+ }
+}
diff --git a/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.ts b/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.ts
new file mode 100644
index 0000000000..32d84c8e6d
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.ts
@@ -0,0 +1,223 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ providers: [] as Array<{ id: string; auth: { native?: string } }>,
+ codex: vi.fn(),
+ claude: vi.fn(),
+ xai: vi.fn(),
+ accountUsage: vi.fn(),
+}));
+
+vi.mock('../../maker-host/active-catalog.js', () => ({
+ getActiveCatalog: () => ({ providers: mocks.providers }),
+}));
+vi.mock('../../usageBroadcaster.js', () => ({
+ readCodexAccountUsageSnapshot: mocks.codex,
+ readClaudeSubscriptionUsageSnapshot: mocks.claude,
+ readXaiSubscriptionUsageSnapshot: mocks.xai,
+}));
+vi.mock('../subscriptionAccountUsage.js', () => ({
+ readSubscriptionAccountUsage: mocks.accountUsage,
+}));
+
+import {
+ claudeAccountUsageLimit,
+ codexAccountUsageLimit,
+ readAccountUsageLimit,
+ subscriptionFamilyOf,
+ xaiAccountUsageLimit,
+} from '../accountUsageLimit';
+
+// 必须在未来:过期窗口的 app-server 桶会被选桶逻辑当作陈旧桶跳过。
+const NOW_SEC = Math.floor(Date.now() / 1000);
+const RESET_5H = NOW_SEC + 3 * 60 * 60;
+const RESET_WEEK = NOW_SEC + 5 * 24 * 60 * 60;
+
+beforeEach(() => {
+ mocks.providers = [];
+ mocks.codex.mockReset();
+ mocks.claude.mockReset();
+ mocks.xai.mockReset();
+ mocks.accountUsage.mockReset();
+});
+
+describe('codexAccountUsageLimit', () => {
+ const buckets = {
+ codex: { limitId: 'codex', primary: { usedPercent: 40, resetsAt: RESET_5H } },
+ spark: {
+ limitId: 'spark',
+ limitName: 'GPT-5.3-Codex-Spark',
+ primary: { usedPercent: 100, resetsAt: RESET_WEEK },
+ },
+ };
+
+ it('only looks at the bucket matching the Codex session model', () => {
+ expect(
+ codexAccountUsageLimit(
+ { appServerBuckets: buckets },
+ { agentKind: 'codex', modelId: 'gpt-5.5' },
+ ),
+ ).toEqual({ limited: false, resetAtMs: null });
+ expect(
+ codexAccountUsageLimit(
+ { appServerBuckets: buckets },
+ { agentKind: 'codex', modelId: 'gpt-5.3-codex-spark' },
+ ),
+ ).toEqual({ limited: true, resetAtMs: RESET_WEEK * 1000 });
+ });
+
+ it('reads the ChatGPT web slot for bridge / Pi sessions', () => {
+ expect(
+ codexAccountUsageLimit(
+ {
+ appServerBuckets: buckets,
+ webSnapshot: { secondary: { usedPercent: 100, resetsAt: RESET_WEEK } },
+ },
+ { agentKind: 'claude-code', modelId: 'gpt-5.5' },
+ ),
+ ).toEqual({ limited: true, resetAtMs: RESET_WEEK * 1000 });
+ expect(codexAccountUsageLimit({ appServerBuckets: buckets }, { agentKind: 'pi' })).toBeNull();
+ });
+
+ it('ignores snapshot-level reached flags (stale or credits depleted) without an exhausted window', () => {
+ for (const rateLimitReachedType of ['primary', 'credits_depleted']) {
+ expect(
+ codexAccountUsageLimit(
+ {
+ rateLimitReachedType,
+ primary: { usedPercent: 100, resetsAt: NOW_SEC - 60 },
+ secondary: { usedPercent: 40, resetsAt: RESET_WEEK },
+ },
+ { agentKind: 'codex' },
+ ),
+ ).toEqual({ limited: false, resetAtMs: null });
+ }
+ });
+
+ it('falls back to the top-level snapshot without a bucket table', () => {
+ expect(
+ codexAccountUsageLimit(
+ { primary: { usedPercent: 100, resetsAt: RESET_5H } },
+ { agentKind: 'codex' },
+ ),
+ ).toEqual({ limited: true, resetAtMs: RESET_5H * 1000 });
+ });
+});
+
+describe('claudeAccountUsageLimit', () => {
+ it('treats the rejected headers window as exhausted', () => {
+ expect(
+ claudeAccountUsageLimit({
+ fiveHour: { utilization: 92, resetsAt: RESET_5H },
+ sevenDay: { utilization: 40, resetsAt: RESET_WEEK },
+ rateLimitStatus: 'rejected',
+ representativeClaim: 'five_hour',
+ }),
+ ).toEqual({ limited: true, resetAtMs: RESET_5H * 1000 });
+ });
+
+ it('only counts the model-scoped window of the session model', () => {
+ const snapshot = {
+ fiveHour: { utilization: 10, resetsAt: RESET_5H },
+ scoped: [{ utilization: 100, resetsAt: RESET_WEEK, modelDisplayName: 'Opus' }],
+ };
+ expect(claudeAccountUsageLimit(snapshot, 'claude-opus-5-5')).toEqual({
+ limited: true,
+ resetAtMs: RESET_WEEK * 1000,
+ });
+ expect(claudeAccountUsageLimit(snapshot, 'claude-sonnet-5')?.limited).toBe(false);
+ });
+
+ it('gives no reset time when an exhausted window lacks one instead of borrowing another window', () => {
+ expect(
+ claudeAccountUsageLimit({
+ fiveHour: { utilization: 20, resetsAt: RESET_5H },
+ sevenDay: { utilization: 100, resetsAt: null },
+ }),
+ ).toEqual({ limited: true, resetAtMs: null });
+ });
+
+ it('ignores windows whose reset already passed (the snapshot predates the rollover)', () => {
+ expect(
+ claudeAccountUsageLimit({
+ fiveHour: { utilization: 100, resetsAt: NOW_SEC - 60 },
+ sevenDay: { utilization: 40, resetsAt: RESET_WEEK },
+ }),
+ ).toEqual({ limited: false, resetAtMs: null });
+ });
+});
+
+describe('xaiAccountUsageLimit', () => {
+ it('reads the weekly window', () => {
+ expect(
+ xaiAccountUsageLimit({
+ creditUsagePercent: 100,
+ resetsAt: RESET_WEEK,
+ updatedAt: Date.now(),
+ }),
+ ).toEqual({ limited: true, resetAtMs: RESET_WEEK * 1000 });
+ expect(xaiAccountUsageLimit({ planLabel: 'SuperGrok' })).toBeNull();
+ });
+
+ it('ignores a cached snapshot past its freshness window', () => {
+ expect(
+ xaiAccountUsageLimit({
+ creditUsagePercent: 100,
+ resetsAt: RESET_WEEK,
+ updatedAt: Date.now() - 2 * 60 * 60 * 1000,
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('subscriptionFamilyOf / readAccountUsageLimit', () => {
+ it('maps a provider to its subscription family, independent of the agent', () => {
+ // 内置默认账号目录里不带 auth.native。
+ mocks.providers = [
+ { id: 'openai', auth: {} },
+ { id: 'anthropic', auth: {} },
+ { id: 'xai', auth: {} },
+ { id: 'codex-work', auth: { native: 'codex' } },
+ { id: 'kimi-coding', auth: {} },
+ ];
+ expect(subscriptionFamilyOf('claude-code', 'openai')).toBe('codex');
+ expect(subscriptionFamilyOf('pi', 'openai')).toBe('codex');
+ expect(subscriptionFamilyOf('claude-code', 'anthropic')).toBe('claude');
+ expect(subscriptionFamilyOf('pi', 'xai')).toBe('xai');
+ expect(subscriptionFamilyOf('codex', 'codex-work')).toBe('codex');
+ expect(subscriptionFamilyOf('claude-code', 'kimi-coding')).toBeNull();
+ // 旧会话缺省 provider:只有 Codex 能确定是 ChatGPT 默认账号。
+ expect(subscriptionFamilyOf('codex', null)).toBe('codex');
+ expect(subscriptionFamilyOf('claude-code', null)).toBeNull();
+ });
+
+ it('returns undefined for non-subscription providers so callers can use another source', async () => {
+ mocks.providers = [{ id: 'kimi-coding', auth: {} }];
+ await expect(readAccountUsageLimit('claude-code', 'kimi-coding')).resolves.toBeUndefined();
+ expect(mocks.codex).not.toHaveBeenCalled();
+ });
+
+ it('reads the ChatGPT snapshot of the session provider', async () => {
+ mocks.providers = [{ id: 'codex-work', auth: { native: 'codex' } }];
+ mocks.codex.mockResolvedValue({ primary: { usedPercent: 100, resetsAt: RESET_5H } });
+ await expect(readAccountUsageLimit('codex', 'codex-work', 'gpt-5.5')).resolves.toEqual({
+ limited: true,
+ resetAtMs: RESET_5H * 1000,
+ });
+ expect(mocks.codex).toHaveBeenCalledWith('codex-work');
+ });
+
+ it('reads independent SuperGrok accounts through the account reader', async () => {
+ mocks.providers = [{ id: 'xai-2', auth: { native: 'xai' } }];
+ mocks.accountUsage.mockResolvedValue({
+ creditUsagePercent: 100,
+ resetsAt: RESET_WEEK,
+ updatedAt: Date.now(),
+ });
+ await expect(readAccountUsageLimit('pi', 'xai-2')).resolves.toEqual({
+ limited: true,
+ resetAtMs: RESET_WEEK * 1000,
+ });
+ expect(mocks.xai).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/usage/accountUsageLimit.ts b/apps/desktop/src/main/usage/accountUsageLimit.ts
new file mode 100644
index 0000000000..096c689e77
--- /dev/null
+++ b/apps/desktop/src/main/usage/accountUsageLimit.ts
@@ -0,0 +1,189 @@
+/**
+ * 按会话所用订阅账号读「是否已用满 / 何时重置」—— 目标模式与普通任务的限额自动续跑共用。
+ *
+ * 订阅家族由会话 provider 的 `auth.native` 决定(ChatGPT 订阅不论跑在 Codex、Claude Code
+ * bridge 还是 Pi 上都读同一份 ChatGPT 额度)。不是订阅家族的 provider(API key、Coding Plan、
+ * Cindy 网关等)返回 `undefined`,由调用方决定是否另有来源;本模块不猜。
+ *
+ * 快照只是兜底:限额错误自带或文案里写明的重置时刻更准,调用方应优先用那个。
+ */
+
+import { matchCodexBucketForModel } from '@cindy/maker-shared/codex-usage-buckets';
+import {
+ isXaiWeeklyUsageCurrent,
+ matchScopedWindowForModel,
+} from '@cindy/maker-shared/subscription-usage';
+import {
+ NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS,
+ type NativeSubscriptionAuth,
+} from '@cindy/model-providers';
+import type { ClaudeSubscriptionUsageSnapshot } from '../../shared/claudeSubscriptionUsage.js';
+import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage.js';
+import { getActiveCatalog } from '../maker-host/active-catalog.js';
+import {
+ readClaudeSubscriptionUsageSnapshot,
+ readCodexAccountUsageSnapshot,
+ readXaiSubscriptionUsageSnapshot,
+ type CodexAccountUsagePayload,
+ type RateLimitSnapshot,
+} from '../usageBroadcaster.js';
+import { readSubscriptionAccountUsage } from './subscriptionAccountUsage.js';
+
+export interface AccountUsageLimit {
+ /** 快照里有仍在有效期内的窗口显示已用满。 */
+ limited: boolean;
+ /**
+ * 受限时的重置时刻(unix ms):用满窗口里最晚的(宁晚勿早);任一用满窗口缺重置时刻
+ * 则为 null(拿别的窗口顶替会提前醒来)。未受限时恒为 null——未用满窗口的重置与限流无关。
+ */
+ resetAtMs: number | null;
+}
+
+interface UsageWindow {
+ usedPercent: number;
+ resetsAtSec: number | null | undefined;
+}
+
+function hasReset(w: UsageWindow): w is UsageWindow & { resetsAtSec: number } {
+ return typeof w.resetsAtSec === 'number' && Number.isFinite(w.resetsAtSec) && w.resetsAtSec > 0;
+}
+
+/**
+ * 只认具体窗口显示用满,不认快照级「已触顶」标记(Codex `rateLimitReachedType` 等):
+ * 标记说不清由哪个窗口触发,还混有余额耗尽(`credits_depleted`,要充值、不会重置)。
+ */
+function fromWindows(windows: readonly UsageWindow[], nowMs: number): AccountUsageLimit {
+ // 已过重置点的窗口在快照之后已经翻篇,快照里的用量不再成立。
+ const live = windows.filter((w) => !hasReset(w) || w.resetsAtSec * 1000 > nowMs);
+ const exhausted = live.filter((w) => w.usedPercent >= 100);
+ if (exhausted.length === 0) return { limited: false, resetAtMs: null };
+ if (exhausted.some((w) => !hasReset(w))) return { limited: true, resetAtMs: null };
+ return { limited: true, resetAtMs: Math.max(...exhausted.map((w) => w.resetsAtSec as number)) * 1000 };
+}
+
+function codexWindows(snapshot: RateLimitSnapshot | null | undefined): UsageWindow[] {
+ if (!snapshot) return [];
+ return [snapshot.primary, snapshot.secondary]
+ .filter((w): w is NonNullable<typeof w> => !!w && typeof w.usedPercent === 'number')
+ .map((w) => ({ usedPercent: w.usedPercent, resetsAtSec: w.resetsAt }));
+}
+
+/**
+ * ChatGPT 订阅:只看当前会话实际消耗的那一份额度,别的模型桶用满不影响本会话。
+ * - Codex 原生会话:按模型匹配 app-server 桶(没有桶表时退回顶层兼容位);
+ * - Claude Code bridge / Pi:走 ChatGPT web 额度(WHAM 槽)。
+ */
+export function codexAccountUsageLimit(
+ payload: CodexAccountUsagePayload | null,
+ session: { agentKind: string; modelId?: string | null },
+ nowMs = Date.now(),
+): AccountUsageLimit | null {
+ if (!payload) return null;
+ let snapshot: RateLimitSnapshot | null;
+ if (session.agentKind === 'codex') {
+ const buckets = payload.appServerBuckets;
+ snapshot =
+ buckets && Object.keys(buckets).length > 0
+ ? matchCodexBucketForModel(buckets, session.modelId, nowMs)
+ : payload;
+ } else {
+ snapshot = payload.webSnapshot ?? null;
+ }
+ const windows = codexWindows(snapshot);
+ if (!snapshot || windows.length === 0) return null;
+ return fromWindows(windows, nowMs);
+}
+
+const CLAUDE_REJECTED_CLAIM_TO_WINDOW = {
+ five_hour: 'fiveHour',
+ seven_day: 'sevenDay',
+} as const;
+
+/** Claude 订阅:总窗口 + 仅当前模型的专属周窗口(别的模型的专属窗口用满不影响本会话)。 */
+export function claudeAccountUsageLimit(
+ snapshot: ClaudeSubscriptionUsageSnapshot | null,
+ modelId?: string | null,
+ nowMs = Date.now(),
+): AccountUsageLimit | null {
+ if (!snapshot) return null;
+ const scoped = matchScopedWindowForModel(snapshot.scoped, modelId);
+ const windows: UsageWindow[] = [snapshot.fiveHour, snapshot.sevenDay, scoped]
+ .filter((w): w is NonNullable<typeof w> => !!w && typeof w.utilization === 'number')
+ .map((w) => ({ usedPercent: w.utilization, resetsAtSec: w.resetsAt }));
+ // headers 源被拒时只报状态和「最紧窗口」名,不带用量;把那个窗口视为已用满。
+ const rejectedKey =
+ snapshot.rateLimitStatus === 'rejected' && snapshot.representativeClaim
+ ? CLAUDE_REJECTED_CLAIM_TO_WINDOW[
+ snapshot.representativeClaim as keyof typeof CLAUDE_REJECTED_CLAIM_TO_WINDOW
+ ]
+ : undefined;
+ const rejectedWindow = rejectedKey ? snapshot[rejectedKey] : null;
+ if (rejectedWindow) windows.push({ usedPercent: 100, resetsAtSec: rejectedWindow.resetsAt });
+ if (windows.length === 0) return null;
+ return fromWindows(windows, nowMs);
+}
+
+/**
+ * SuperGrok 只有周窗口。快照是 cached-first、后台刷新,超过有效期(或已过重置点)的不用,
+ * 与用量面板同一判定。
+ */
+export function xaiAccountUsageLimit(
+ snapshot: XaiSubscriptionUsageSnapshot | null,
+ nowMs = Date.now(),
+): AccountUsageLimit | null {
+ if (!snapshot || !isXaiWeeklyUsageCurrent(snapshot, nowMs)) return null;
+ return fromWindows(
+ [{ usedPercent: snapshot.creditUsagePercent as number, resetsAtSec: snapshot.resetsAt }],
+ nowMs,
+ );
+}
+
+/**
+ * 会话所用 provider 属于哪个订阅家族。providerId 缺省(旧会话的隐式默认来源)时只有
+ * Codex 能确定是 ChatGPT 默认账号;其它 agent 的默认来源可能是 Cindy 网关,不猜。
+ */
+export function subscriptionFamilyOf(
+ agentKind: string,
+ providerId: string | null | undefined,
+): NativeSubscriptionAuth | null {
+ if (!providerId) return agentKind === 'codex' ? 'codex' : null;
+ // 内置默认账号(openai / anthropic / xai)不带 auth.native,按固定 id 识别;独立账号才带。
+ for (const [family, id] of Object.entries(NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS)) {
+ if (id === providerId) return family as NativeSubscriptionAuth;
+ }
+ const provider = getActiveCatalog().providers.find((p) => p.id === providerId);
+ return provider?.auth.native ?? null;
+}
+
+/**
+ * @returns `undefined` = 不是订阅家族(调用方另找来源);`null` = 是订阅家族但暂无可用快照。
+ */
+export async function readAccountUsageLimit(
+ agentKind: string,
+ providerId: string | null | undefined,
+ modelId?: string | null,
+): Promise<AccountUsageLimit | null | undefined> {
+ const family = subscriptionFamilyOf(agentKind, providerId);
+ switch (family) {
+ case 'codex':
+ return codexAccountUsageLimit(await readCodexAccountUsageSnapshot(providerId ?? undefined), {
+ agentKind,
+ modelId,
+ });
+ case 'claude':
+ // 独立 Claude 账号已停用,只有内置默认账号有快照。
+ return providerId === 'anthropic' || !providerId
+ ? claudeAccountUsageLimit(await readClaudeSubscriptionUsageSnapshot(), modelId)
+ : null;
+ case 'xai':
+ return xaiAccountUsageLimit(
+ !providerId || providerId === 'xai'
+ ? await readXaiSubscriptionUsageSnapshot()
+ : ((await readSubscriptionAccountUsage(
+ providerId,
+ )) as XaiSubscriptionUsageSnapshot | null),
+ );
+ default:
+ return undefined;
+ }
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 1335e23fa2..5c7fa3e38a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -7435,6 +7435,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
opts?: { expectedClearBoundaryMs?: number | null },
): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>
ipcRenderer.invoke('maker:input:clear-error', sessionId, opts),
+ cancelUsageLimitWait: (
+ sessionId: string,
+ opts?: { expectedClearBoundaryMs?: number | null },
+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>
+ ipcRenderer.invoke('maker:input:cancel-usage-limit-wait', sessionId, opts),
persistTurnErrorDeferred: (
sessionId: string,
errData: Record<string, unknown> | null,
diff --git a/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts b/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts
index edcf9ebe82..edc08adb04 100644
--- a/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts
+++ b/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts
@@ -100,3 +100,19 @@ describe('composer reconnect presentation', () => {
expect(active?.maxAttempts).toBeUndefined();
});
});
+
+describe('usage-limit reset continuation', () => {
+ it('is not reported as a reconnect in the composer', () => {
+ expect(
+ findActiveReconnect({
+ ...base,
+ messages: [
+ row({
+ systemCardData: { reason: 'usage-limit-reset', attempt: 1, maxAttempts: 3, sessionTotal: 1 },
+ }),
+ ],
+ }),
+ ).toBeNull();
+ });
+});
+
diff --git a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
index db6b72bbcd..f25d60386a 100644
--- a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
@@ -79,6 +79,7 @@ const state = (overrides: Partial<SessionChatState> = {}): SessionChatState => (
errorPersistId: null,
disposedErrorPersistId: null,
credentialSwitchWait: null,
+ usageLimitWait: null,
continuationInFlightClientId: null,
continuationTurnClientId: null,
continuationInFlightProjectionCapability: 'unknown',
diff --git a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts
index d503dc60e0..fbc8de679f 100644
--- a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts
@@ -9,11 +9,6 @@ import type { SessionReference } from '../../shared/sessionReference';
import { SchedulerPage } from '@/features/scheduler/SchedulerPage';
import { ScheduleFormDialog } from '@/features/scheduler/components/ScheduleFormDialog';
-import {
- oneTimeCronAfterUsageReset,
- systemTimeZone,
- usageLimitScheduleNavigationState,
-} from '@/features/scheduler/lib/usageLimitScheduleCreateIntent';
import { pluginScheduleNavigationState } from '@/features/scheduler/lib/pluginScheduleCreateIntent';
const createSchedule = vi.fn();
@@ -288,53 +283,6 @@ describe('Scheduler template entry', () => {
);
});
- it('opens a usage-limit recovery Automation for confirmation without creating it', async () => {
- const resetAtMs = Date.parse('2027-01-24T10:30:00.000Z');
- routerMocks.location.state = usageLimitScheduleNavigationState({
- kind: 'usage-limit-recovery',
- requestId: 'request-1',
- sessionId: 'session-1',
- agentKind: 'codex',
- resetAtMs,
- });
-
- render(createElement(SchedulerPage));
-
- await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());
- expect(
- screen.getByDisplayValue('scheduler.usageLimitRecovery.name'),
- ).toBeTruthy();
- expect(
- screen.getByDisplayValue('scheduler.usageLimitRecovery.prompt'),
- ).toBeTruthy();
- expect(screen.getByTestId('cron-expr').textContent).toBe(
- oneTimeCronAfterUsageReset(resetAtMs, systemTimeZone()),
- );
- expect(screen.getByTestId('agent-kind').textContent).toBe('codex');
- expect(createSchedule).not.toHaveBeenCalled();
- expect(routerMocks.navigate).toHaveBeenCalledWith('/cc-agent/scheduled', {
- replace: true,
- state: null,
- });
- });
-
- it('opens the same confirmation form with a blank schedule when reset time is unknown', async () => {
- routerMocks.location.state = usageLimitScheduleNavigationState({
- kind: 'usage-limit-recovery',
- requestId: 'request-unknown-time',
- sessionId: 'session-2',
- agentKind: 'claude-code',
- resetAtMs: null,
- });
-
- render(createElement(SchedulerPage));
-
- await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());
- expect(screen.getByTestId('cron-expr').textContent).toBe('');
- expect(screen.getByTestId('agent-kind').textContent).toBe('claude-code');
- expect(createSchedule).not.toHaveBeenCalled();
- });
-
it('插件请求打开预填的创建表单,但不创建任务', async () => {
routerMocks.location.state = pluginScheduleNavigationState({
kind: 'plugin-schedule-draft',
diff --git a/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.ts b/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.ts
index f907164400..e34f134a02 100644
--- a/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.ts
+++ b/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.ts
@@ -34,6 +34,66 @@ describe('usage limit recovery detection', () => {
).toEqual({ resetAtMs: NOW + 75 * 60_000, isAccountUsageLimit: true });
});
+ it('parses the Codex app-server "try again at" wording in local time', () => {
+ const sameDay = new Date(NOW);
+ sameDay.setHours(23, 30, 0, 0);
+ if (sameDay.getTime() <= NOW) sameDay.setDate(sameDay.getDate() + 1);
+ expect(
+ extractUsageLimitRecoveryHint(
+ {
+ codexErrorInfo: 'usageLimitExceeded',
+ message: "You've hit your usage limit. Upgrade to Pro, or try again at 11:30 PM.",
+ },
+ NOW,
+ )?.resetAtMs,
+ ).toBe(sameDay.getTime());
+
+ expect(
+ extractUsageLimitRecoveryHint(
+ {
+ codexErrorInfo: 'usageLimitExceeded',
+ message: "You've hit your usage limit. Try again at Jan 27, 2026 3:05 PM.",
+ },
+ NOW,
+ )?.resetAtMs,
+ ).toBe(new Date(2026, 0, 27, 15, 5).getTime());
+ });
+
+ it('drops zone-less clock times when the local time zone is not trusted (SSH sessions)', () => {
+ const remote = { localTimeZoneTrusted: false };
+ expect(
+ extractUsageLimitRecoveryHint(
+ { codexErrorInfo: 'usageLimitExceeded', message: 'Try again at Jan 27, 2026 3:05 PM.' },
+ NOW,
+ remote,
+ )?.resetAtMs,
+ ).toBeNull();
+ // 带时区的钟点与相对时长不受影响。
+ expect(
+ extractUsageLimitRecoveryHint(
+ { sdkError: 'rate_limit', message: "You've hit your limit · resets 11pm (UTC)" },
+ NOW,
+ remote,
+ )?.resetAtMs,
+ ).toBe(Date.parse('2026-01-24T23:00:00.000Z'));
+ expect(
+ extractUsageLimitRecoveryHint(
+ { codexErrorInfo: 'usageLimitExceeded', message: 'Try again in 1h 15m.' },
+ NOW,
+ remote,
+ )?.resetAtMs,
+ ).toBe(NOW + 75 * 60_000);
+ });
+
+ it("parses Pi's approximate ChatGPT relative reset", () => {
+ expect(
+ extractUsageLimitRecoveryHint(
+ { message: 'You have hit your ChatGPT usage limit (plus plan). Try again in ~12 min.' },
+ NOW,
+ )?.resetAtMs,
+ ).toBe(NOW + 12 * 60_000);
+ });
+
it('extracts the organization plan and reset time from the Codex 429 payload', () => {
expect(
extractUsageLimitRecoveryHint(
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 61f8c0e2aa..ec2557016a 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -73,8 +73,10 @@ interface ErrorBannerProps {
onCancel?: () => void;
/** silent-stop 耗尽横幅「继续」:清横幅 + 发隐藏续跑指令(见 makerChatStore)。 */
onSilentStopContinue?: () => void;
- /** 账号用量限制:打开预填好的一次性 Automation,由用户确认后创建。 */
- onContinueAfterUsageReset?: () => void;
+ /** 账号限额等待中:额度重置后到这个时刻(unix ms)若无人处理,被控端自动继续任务。 */
+ usageLimitWait?: { resumeAt: number } | null;
+ /** 取消自动继续(错误与重试保留)。 */
+ onCancelUsageLimitWait?: () => void;
/** 已识别的账号用量限制及恢复时间;用于替换上游 429 JSON 为可读提示。 */
usageLimitRecovery?: UsageLimitRecoveryHint | null;
/** 当前 session 的 agent kind。codex 的 401 / Missing bearer 必须 hide Retry,
@@ -129,7 +131,8 @@ export function ErrorBanner({
onRetry,
onCancel,
onSilentStopContinue,
- onContinueAfterUsageReset,
+ usageLimitWait,
+ onCancelUsageLimitWait,
usageLimitRecovery,
agentKind,
remoteHostId,
@@ -324,8 +327,15 @@ export function ErrorBanner({
const isOrganizationCodexPlan = ['business', 'enterprise', 'team'].includes(
usageLimitRecovery?.planType?.toLowerCase() ?? '',
);
- const canContinueAfterUsageReset =
- Boolean(onContinueAfterUsageReset) && (agentKind !== 'codex' || isCodexUsageLimitError);
+ const usageLimitResumeAt = (() => {
+ if (!usageLimitWait || !Number.isFinite(usageLimitWait.resumeAt)) return null;
+ const resumeDate = new Date(usageLimitWait.resumeAt);
+ const sameDay = resumeDate.toDateString() === new Date().toDateString();
+ return new Intl.DateTimeFormat(
+ i18n?.resolvedLanguage ?? i18n?.language,
+ sameDay ? { timeStyle: 'short' } : { dateStyle: 'medium', timeStyle: 'short' },
+ ).format(resumeDate);
+ })();
// Retry 的显示条件与网络错误文案必须共用同一个判定。外部发起的 turn(例如
// scheduler / goal)失败时没有安全的 recovery target,errorRetryText 会是 null;
// 此时不能一边隐藏按钮,一边仍提示用户“点击重试”。
@@ -754,20 +764,28 @@ export function ErrorBanner({
{t('chat.errorBanner.silentStopContinue')}
</button>
)}
- {canContinueAfterUsageReset && onContinueAfterUsageReset && (
+ {usageLimitResumeAt && (
+ // 额度重置后自动继续:只是告知,不是按钮;用户仍可重试、换模型或发新消息接手。
+ <span
+ className="shrink-0 flex select-none items-center gap-1 text-xs text-[var(--error-fg)]"
+ title={t('chat.errorBanner.usageLimitAutoContinueTitle')}
+ >
+ <Timer size={12} />
+ {t('chat.errorBanner.usageLimitAutoContinueAt', { time: usageLimitResumeAt })}
+ </span>
+ )}
+ {usageLimitResumeAt && onCancelUsageLimitWait && (
<button
type="button"
- data-split-pane-route-action=""
- onClick={onContinueAfterUsageReset}
+ onClick={onCancelUsageLimitWait}
className={cn(
'shrink-0 flex items-center gap-1 text-xs font-medium',
'text-[var(--error-fg)]',
'hover:opacity-70 transition-opacity',
)}
- title={t('chat.errorBanner.continueAfterResetTitle')}
+ title={t('chat.errorBanner.usageLimitAutoContinueCancelTitle')}
>
- <Timer size={12} />
- {t('chat.errorBanner.continueAfterReset')}
+ {t('chat.errorBanner.usageLimitAutoContinueCancel')}
</button>
)}
{safeRetryText && (
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index 0908cd61fb..7ea6b9476f 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -944,7 +944,11 @@ function AutoResumeActionRow({
}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
- const hasProgress = info.attempt !== undefined && info.maxAttempts !== undefined;
+ // 用量上限重置后的自动继续不是重连:不展示「第几次重试 / 累计重连」。
+ const usageLimitReset = info.usageLimitReset === true;
+ const hasProgress =
+ !usageLimitReset && info.attempt !== undefined && info.maxAttempts !== undefined;
+ const showSessionTotal = !usageLimitReset && info.sessionTotal !== undefined;
// **转圈的判据是"此刻真的有 turn 在跑",不是"是不是 ephemeral 行"。**
//
// 一次中断的进行中状态跨两种载体:退避那 3–20 秒是 ephemeral 行(state='live'),续跑
@@ -959,7 +963,9 @@ function AutoResumeActionRow({
// - 已回填 → ✓ / ✗ 定格,`inFlight` 不参与(终态优先)
const live = state === 'live' || (inFlight === true && info.outcome === undefined);
const outcome = live ? undefined : info.outcome;
- const label = live
+ const label = usageLimitReset
+ ? t('chat.systemCard.autoResume.labelUsageReset')
+ : live
? hasProgress
? t('chat.systemCard.autoResumePending.labelWithProgress', {
attempt: info.attempt,
@@ -972,7 +978,7 @@ function AutoResumeActionRow({
? t('chat.systemCard.autoResume.labelFailed')
: t('chat.systemCard.autoResume.labelNeutral');
const summary = summarizeInterruption(info.error);
- const canExpand = Boolean(info.error) || hasProgress || info.sessionTotal !== undefined;
+ const canExpand = Boolean(info.error) || hasProgress || showSessionTotal;
return (
<div className="flex flex-col">
<button
@@ -1050,7 +1056,7 @@ function AutoResumeActionRow({
</pre>
</>
)}
- {(hasProgress || info.sessionTotal !== undefined) && (
+ {(hasProgress || showSessionTotal) && (
<div className={cn('flex flex-wrap gap-x-4 gap-y-[2px] text-12', info.error && 'mt-2')}>
{hasProgress && (
<span>
@@ -1060,7 +1066,7 @@ function AutoResumeActionRow({
})}
</span>
)}
- {info.sessionTotal !== undefined && (
+ {showSessionTotal && (
<span>
{t('chat.systemCard.autoResume.detail.sessionTotal', {
count: info.sessionTotal,
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index 843600b52d..83eb8fb514 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -939,33 +939,42 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(screen.queryByText('logic.errors.toolUseLoopDetectedWithCount')).toBeNull();
});
- it('exposes the explicit Continue After Reset action only when provided', () => {
- const onContinueAfterUsageReset = vi.fn();
+ it('shows the automatic continuation time and a cancel action only while waiting', () => {
+ const onCancelUsageLimitWait = vi.fn();
const { rerender } = render(
<ErrorBanner
error="usageLimitExceeded"
retryText="retry this turn"
onRetry={vi.fn()}
agentKind="codex"
- onContinueAfterUsageReset={onContinueAfterUsageReset}
+ usageLimitWait={{ resumeAt: Date.now() + 60 * 60 * 1000 }}
+ onCancelUsageLimitWait={onCancelUsageLimitWait}
usageLimitRecovery={{ resetAtMs: null, isAccountUsageLimit: true }}
/>,
);
expect(screen.getByText('chat.errorBanner.codexUsageLimit')).toBeTruthy();
- expect(screen.queryByText('usageLimitExceeded')).toBeNull();
- const continueButton = screen.getByRole('button', {
- name: 'chat.errorBanner.continueAfterReset',
- });
- expect(continueButton.getAttribute('data-split-pane-route-action')).toBe('');
- fireEvent.click(continueButton);
- expect(onContinueAfterUsageReset).toHaveBeenCalledOnce();
+ expect(screen.getByText('chat.errorBanner.usageLimitAutoContinueAt')).toBeTruthy();
+ // 等待期间手动重试仍可用。
+ expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
+ fireEvent.click(
+ screen.getByRole('button', { name: 'chat.errorBanner.usageLimitAutoContinueCancel' }),
+ );
+ expect(onCancelUsageLimitWait).toHaveBeenCalledOnce();
rerender(
- <ErrorBanner error="A normal failure" retryText="retry this turn" onRetry={vi.fn()} />,
+ <ErrorBanner
+ error="usageLimitExceeded"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ usageLimitWait={null}
+ onCancelUsageLimitWait={onCancelUsageLimitWait}
+ />,
);
+ expect(screen.queryByText('chat.errorBanner.usageLimitAutoContinueAt')).toBeNull();
expect(
- screen.queryByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),
+ screen.queryByRole('button', { name: 'chat.errorBanner.usageLimitAutoContinueCancel' }),
).toBeNull();
});
@@ -1020,7 +1029,6 @@ describe('ErrorBanner OpenAI connection recovery', () => {
retryText="retry this turn"
onRetry={vi.fn()}
agentKind="codex"
- onContinueAfterUsageReset={vi.fn()}
usageLimitRecovery={{ resetAtMs: null }}
/>,
);
@@ -1030,9 +1038,6 @@ describe('ErrorBanner OpenAI connection recovery', () => {
fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
expect(screen.getByText(rawError)).toBeTruthy();
expect(screen.queryByText('chat.errorBanner.codexUsageLimit')).toBeNull();
- expect(
- screen.queryByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),
- ).toBeNull();
});
it('rebuilds the organization usage-limit hint for a persisted error tail', () => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 32fce95901..917ca0beda 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -335,7 +335,6 @@ import {
shouldRevealOrcaWorkersBeforeFirstPaint,
} from './lib/orcaPassiveReveal';
import { didOpenOrcaWorkersTab, revealOrcaWorkersWithRetry } from './lib/orcaWorkersRevealRetry';
-import { usageLimitScheduleNavigationState } from '@/features/scheduler/lib/usageLimitScheduleCreateIntent';
import {
closeOrcaWorkersTabAfterTeamEnd,
ensureOrcaWorkersTab,
@@ -1771,6 +1770,8 @@ export function CCAgentSessionView({
updateSystemCardData,
error,
usageLimitRecovery,
+ usageLimitWait,
+ cancelUsageLimitWait,
errorIsRecoverable,
errorRetryText,
disposedErrorPersistId,
@@ -4231,26 +4232,6 @@ export function CCAgentSessionView({
continueAfterSilentStop();
}, [continueAfterSilentStop]);
- const handleContinueAfterUsageReset = useCallback(() => {
- if (!sessionId || !usageLimitRecovery || remoteDeviceId) return;
- const requestId =
- typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
- ? crypto.randomUUID()
- : `${sessionId}:${Date.now()}`;
- navigate('/cc-agent/scheduled', {
- state: usageLimitScheduleNavigationState({
- kind: 'usage-limit-recovery',
- requestId,
- sessionId,
- agentKind:
- session?.agentKind === 'codex' || session?.agentKind === 'pi'
- ? session.agentKind
- : 'claude-code',
- resetAtMs: usageLimitRecovery.resetAtMs,
- }),
- });
- }, [navigate, remoteDeviceId, session?.agentKind, sessionId, usageLimitRecovery]);
-
// 点击 Cancel 关闭报错 banner 同样是处置(用户选择不管它了)。
const handleDismissError = useCallback(() => {
if (sessionId) ackErrorAlertHandled(sessionId);
@@ -5299,9 +5280,8 @@ export function CCAgentSessionView({
retryText={errorRetryText}
onRetry={handleRetry}
onSilentStopContinue={handleSilentStopContinue}
- onContinueAfterUsageReset={
- usageLimitRecovery && !remoteDeviceId ? handleContinueAfterUsageReset : undefined
- }
+ usageLimitWait={usageLimitWait}
+ onCancelUsageLimitWait={cancelUsageLimitWait}
usageLimitRecovery={usageLimitRecovery}
onCancel={handleDismissError}
agentKind={session?.agentKind}
diff --git a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx
index 555f05bbef..8adedc8706 100644
--- a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx
@@ -62,10 +62,6 @@ import {
scheduleToProjectConfig,
} from './lib/projectAutomationConfig';
import type { ScheduleFormState } from './lib/scheduleFormLogic';
-import {
- buildUsageLimitScheduleFormOverrides,
- readUsageLimitScheduleCreateIntent,
-} from './lib/usageLimitScheduleCreateIntent';
import {
buildPluginScheduleFormOverrides,
readPluginScheduleCreateIntent,
@@ -207,29 +203,8 @@ export function SchedulerPage() {
setFormOpen(true);
}, [editToken, focusId, schedules]);
- useEffect(() => {
- const intent = readUsageLimitScheduleCreateIntent(location.state);
- if (!intent || handledScheduleCreateRequestRef.current === intent.requestId) return;
- handledScheduleCreateRequestRef.current = intent.requestId;
- setCreatePrefillWorkingDir(null);
- setCreateInitialTemplate(null);
- setEditing(null);
- setCreateInitialValues(
- buildUsageLimitScheduleFormOverrides(intent, {
- name: t('scheduler.usageLimitRecovery.name'),
- prompt: t('scheduler.usageLimitRecovery.prompt'),
- }),
- );
- setFormOpen(true);
- // Consume the one-shot navigation intent so revisiting Automations does not
- // reopen the modal. Creation still happens only after the user submits.
- const path = `${location.pathname || '/cc-agent/scheduled'}${location.search}`;
- navigate(path, { replace: true, state: null });
- }, [location.pathname, location.search, location.state, navigate, t]);
-
- // 插件请求新建自动化(agent 槽 schedule 加档):形态与上面 usage-limit 那条
- // 完全一致 —— 一次性导航意图 → 预填打开面板 → 用完立刻清掉 state。
- // 与它共用 handledScheduleCreateRequestRef:两种意图不该叠开两个面板。
+ // 插件请求新建自动化(agent 槽 schedule 加档):一次性导航意图 → 预填打开面板 →
+ // 用完立刻清掉 state。handledScheduleCreateRequestRef 防同一意图重复开面板。
// ⚠️ 这里只 setCreateInitialValues + 打开面板,**不创建任务**。落库仍然只发生在
// 用户点保存后走 handleSubmit —— 插件全程没有直接建任务的通道。
useEffect(() => {
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/usageLimitScheduleCreateIntent.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/usageLimitScheduleCreateIntent.test.ts
deleted file mode 100644
index 884c0016f0..0000000000
--- a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/usageLimitScheduleCreateIntent.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import {
- buildUsageLimitScheduleFormOverrides,
- oneTimeCronAfterUsageReset,
- readUsageLimitScheduleCreateIntent,
- usageLimitScheduleNavigationState,
- type UsageLimitScheduleCreateIntent,
-} from '../usageLimitScheduleCreateIntent';
-
-const intent: UsageLimitScheduleCreateIntent = {
- kind: 'usage-limit-recovery',
- requestId: 'request-1',
- sessionId: 'session-1',
- agentKind: 'codex',
- resetAtMs: Date.parse('2026-01-24T10:30:00.000Z'),
-};
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe('usage-limit Automation create intent', () => {
- it('formats reset plus one minute as a one-shot cron expression', () => {
- expect(
- oneTimeCronAfterUsageReset(
- Date.parse('2026-01-24T10:30:00.000Z'),
- 'UTC',
- Date.parse('2026-01-24T10:00:00.000Z'),
- ),
- ).toBe('31 10 24 1 *');
- });
-
- it('normalizes Intl midnight hour 24 before building the cron expression', () => {
- const originalFormatToParts = Intl.DateTimeFormat.prototype.formatToParts;
- vi.spyOn(Intl.DateTimeFormat.prototype, 'formatToParts').mockImplementation(function (
- this: Intl.DateTimeFormat,
- date,
- ) {
- return originalFormatToParts
- .call(this, date)
- .map((part) =>
- part.type === 'hour' && part.value === '00' ? { ...part, value: '24' } : part,
- );
- });
-
- expect(
- oneTimeCronAfterUsageReset(
- Date.parse('2026-01-24T23:59:00.000Z'),
- 'UTC',
- Date.parse('2026-01-24T23:00:00.000Z'),
- ),
- ).toBe('0 0 25 1 *');
- });
-
- it('leaves the schedule blank when no reset time can be identified', () => {
- expect(oneTimeCronAfterUsageReset(null, 'UTC')).toBe('');
- const form = buildUsageLimitScheduleFormOverrides(
- { ...intent, resetAtMs: null },
- { name: 'Continue later', prompt: 'Continue the task.' },
- );
- expect(form).toMatchObject({
- name: 'Continue later',
- prompt: 'Continue the task.',
- cronExpr: '',
- recurring: false,
- targetSessionId: 'session-1',
- agentKind: 'codex',
- });
- });
-
- it('round-trips a valid navigation intent and rejects malformed state', () => {
- expect(readUsageLimitScheduleCreateIntent(usageLimitScheduleNavigationState(intent))).toEqual(
- intent,
- );
- expect(
- readUsageLimitScheduleCreateIntent({
- scheduleCreateIntent: { ...intent, sessionId: '', resetAtMs: 'tomorrow' },
- }),
- ).toBeNull();
- expect(readUsageLimitScheduleCreateIntent(null)).toBeNull();
- });
-});
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts b/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts
index 438a091142..7369e62883 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts
@@ -5,8 +5,7 @@
* scheduleSlot(资格审/净化/钳制/限速)→ 广播 → 订阅点导航到自动化页并带上本
* intent → SchedulerPage 读出来转成表单预填 → 面板打开,用户选模型后**亲手保存**。
*
- * 形态与 usageLimitScheduleCreateIntent 逐条同构(同一套 navigation state 通道 +
- * Partial<ScheduleFormState> 预填),不另发明一条路。
+ * 走 navigation state 通道 + Partial<ScheduleFormState> 预填,不另发明一条路。
*
* 落成的任务是一条**普通 agent 自动化**:执行者是 AI 会话,插件只是这条任务到点
* 去调用的目标(靠已有的 tool 槽 + ghost_call)。所以这里不碰 executionMode,也
@@ -75,7 +74,7 @@ export function readPluginScheduleCreateIntent(
return value as PluginScheduleCreateIntent;
}
-/** 本机时区(与 usageLimit 那条同实现,失败兜底 UTC)。 */
+/** 本机时区,失败兜底 UTC。 */
function systemTimeZone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
@@ -104,7 +103,7 @@ function systemTimeZone(): string {
* 只是占位(见 Schedule.intervalMs 注释);没给建议频率时就用面板默认。
*
* `workspaceKind: 'dialogue'` —— 这类任务是"去查点东西再更新插件",不属于任何
- * 项目目录,落 app 管理的对话工作区(与 usageLimit 那条同口径)。
+ * 项目目录,落 app 管理的对话工作区。
*/
export function buildPluginScheduleFormOverrides(
intent: PluginScheduleCreateIntent,
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts b/apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts
deleted file mode 100644
index d586d888ec..0000000000
--- a/apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import type { ScheduleFormState } from './scheduleFormLogic';
-
-export interface UsageLimitScheduleCreateIntent {
- kind: 'usage-limit-recovery';
- requestId: string;
- sessionId: string;
- agentKind: 'claude-code' | 'codex' | 'pi';
- resetAtMs: number | null;
-}
-
-export interface UsageLimitScheduleLabels {
- name: string;
- prompt: string;
-}
-
-export function usageLimitScheduleNavigationState(intent: UsageLimitScheduleCreateIntent): {
- scheduleCreateIntent: UsageLimitScheduleCreateIntent;
-} {
- return { scheduleCreateIntent: intent };
-}
-
-export function readUsageLimitScheduleCreateIntent(
- state: unknown,
-): UsageLimitScheduleCreateIntent | null {
- if (!state || typeof state !== 'object') return null;
- const candidate = (state as { scheduleCreateIntent?: unknown }).scheduleCreateIntent;
- if (!candidate || typeof candidate !== 'object') return null;
- const value = candidate as Partial<UsageLimitScheduleCreateIntent>;
- if (
- value.kind !== 'usage-limit-recovery' ||
- typeof value.requestId !== 'string' ||
- !value.requestId ||
- typeof value.sessionId !== 'string' ||
- !value.sessionId ||
- (value.agentKind !== 'claude-code' && value.agentKind !== 'codex' && value.agentKind !== 'pi') ||
- (value.resetAtMs !== null &&
- (typeof value.resetAtMs !== 'number' || !Number.isFinite(value.resetAtMs)))
- ) {
- return null;
- }
- return value as UsageLimitScheduleCreateIntent;
-}
-
-export function systemTimeZone(): string {
- try {
- return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
- } catch {
- return 'UTC';
- }
-}
-
-function timePartsAt(
- timestamp: number,
- timeZone: string,
-): { month: number; day: number; hour: number; minute: number } | null {
- try {
- const formatter = new Intl.DateTimeFormat('en-US', {
- timeZone,
- month: 'numeric',
- day: 'numeric',
- hour: 'numeric',
- minute: 'numeric',
- hourCycle: 'h23',
- });
- const parts: Partial<Record<'month' | 'day' | 'hour' | 'minute', number>> = {};
- for (const part of formatter.formatToParts(new Date(timestamp))) {
- if (
- part.type === 'month' ||
- part.type === 'day' ||
- part.type === 'hour' ||
- part.type === 'minute'
- ) {
- const value = Number(part.value);
- if (!Number.isFinite(value)) continue;
- // Keep parity with maker-scheduler's wallClock(): some Intl
- // implementations report midnight as 24 even with hourCycle=h23.
- parts[part.type] = part.type === 'hour' && value === 24 ? 0 : value;
- }
- }
- if (
- parts.month === undefined ||
- parts.day === undefined ||
- parts.hour === undefined ||
- parts.minute === undefined
- ) {
- return null;
- }
- return parts as { month: number; day: number; hour: number; minute: number };
- } catch {
- return null;
- }
-}
-
-/** Convert reset + one minute into the existing scheduler's one-shot cron shape. */
-export function oneTimeCronAfterUsageReset(
- resetAtMs: number | null,
- timeZone: string,
- nowMs = Date.now(),
-): string {
- if (resetAtMs === null || !Number.isFinite(resetAtMs)) return '';
- const runAtMs = resetAtMs + 60_000;
- if (runAtMs <= nowMs) return '';
- const parts = timePartsAt(runAtMs, timeZone);
- if (!parts) return '';
- return `${parts.minute} ${parts.hour} ${parts.day} ${parts.month} *`;
-}
-
-export function buildUsageLimitScheduleFormOverrides(
- intent: UsageLimitScheduleCreateIntent,
- labels: UsageLimitScheduleLabels,
- nowMs = Date.now(),
-): Partial<ScheduleFormState> {
- const timezone = systemTimeZone();
- return {
- name: labels.name,
- prompt: labels.prompt,
- executionMode: 'agent',
- cronExpr: oneTimeCronAfterUsageReset(intent.resetAtMs, timezone, nowMs),
- intervalMs: undefined,
- timezone,
- recurring: false,
- manual: false,
- agentKind: intent.agentKind,
- model: '',
- providerId: '',
- effort: '',
- fastMode: false,
- workspaceKind: 'dialogue',
- workingDir: '',
- useWorktree: false,
- targetSessionId: intent.sessionId,
- persistentSession: false,
- };
-}
diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
index 0e3441c862..26342e2e19 100644
--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
@@ -170,6 +170,8 @@ interface UseCCAgentChatReturn {
clearSession: () => void;
/** Dismiss the error banner without retrying. */
clearError: () => void;
+ /** 取消账号限额重置后的自动继续(错误与重试保留)。 */
+ cancelUsageLimitWait: () => void;
/** Retry the main-owned typed recovery target. */
retryLastError: () => Promise<void>;
/** silent-stop 耗尽横幅「继续」:清横幅并发隐藏续跑指令(充值守卫额度)。 */
@@ -202,6 +204,8 @@ interface UseCCAgentChatReturn {
disposedErrorPersistId: string | null;
/** 凭证切换等待态(main 透传):挡路会话结束后自动重发,渲染等待横幅。 */
credentialSwitchWait: { clientId?: string; blockedBySessionIds: string[] } | null;
+ /** 账号限额等待:错误横幅附「将于 X 自动继续 · 取消」。 */
+ usageLimitWait: { resumeAt: number } | null;
/** 已离队、正在 coordinator dispatch/turn 边界内的 Continue clientId。 */
continuationInFlightClientId: string | null;
/** 当前 vendor turn 的续跑发起项 clientId,steer 后及 Renderer 重载仍保持。 */
@@ -531,6 +535,11 @@ export function useCCAgentChat(
makerChatStore.clearError(sessionId);
}, [sessionId]);
+ const cancelUsageLimitWait = useCallback(() => {
+ if (!sessionId) return;
+ makerChatStore.cancelUsageLimitWait(sessionId);
+ }, [sessionId]);
+
const continueAfterSilentStop = useCallback(() => {
if (!sessionId) return;
makerChatStore.continueAfterSilentStop(sessionId);
@@ -857,6 +866,7 @@ export function useCCAgentChat(
stopSession,
clearSession,
clearError,
+ cancelUsageLimitWait,
retryLastError,
continueAfterSilentStop,
insertSystemCard,
@@ -882,6 +892,7 @@ export function useCCAgentChat(
errorPersistId: lightState.errorPersistId,
disposedErrorPersistId: lightState.disposedErrorPersistId,
credentialSwitchWait: lightState.credentialSwitchWait,
+ usageLimitWait: lightState.error ? (lightState.usageLimitWait ?? null) : null,
continuationInFlightClientId: lightState.continuationInFlightClientId,
continuationTurnClientId: lightState.continuationTurnClientId,
continuationInFlightProjectionCapability: lightState.continuationInFlightProjectionCapability,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4d60c7d070..ba7b04365a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9724,8 +9724,10 @@
"retryTitle": "Resend the last message",
"cancelTitle": "Dismiss error",
"retry": "Retry",
- "continueAfterReset": "Continue After Reset",
- "continueAfterResetTitle": "Create a one-time Automation to continue this task after usage resets",
+ "usageLimitAutoContinueAt": "Continues automatically at {{time}}",
+ "usageLimitAutoContinueTitle": "If you haven't acted by the time the usage limit resets, this task continues automatically",
+ "usageLimitAutoContinueCancel": "Cancel",
+ "usageLimitAutoContinueCancelTitle": "Cancel automatic continuation. The error and Retry stay available.",
"codexOrganizationUsageLimitWithReset": "The connected Codex account is managed by your organization and has reached its usage limit. Usage is expected to reset at {{resetAt}}.",
"codexOrganizationUsageLimit": "The connected Codex account is managed by your organization and has reached its usage limit. Wait for the limit to reset, or switch to another available account before retrying.",
"codexUsageLimitWithReset": "The connected Codex account has reached its usage limit. Usage is expected to reset at {{resetAt}}.",
@@ -10156,6 +10158,7 @@
"label": "Reconnected",
"labelFailed": "Reconnect failed",
"labelNeutral": "Reconnect",
+ "labelUsageReset": "Usage reset, continued automatically",
"detail": {
"reason": "Interruption reason",
"attempt": "Attempt {{attempt}}/{{total}}",
@@ -11512,10 +11515,6 @@
"promptHeading": "No Automations yet",
"promptDescription": "Create a cron Automation to run your prompt on a schedule."
},
- "usageLimitRecovery": {
- "name": "Continue Task After Usage Resets",
- "prompt": "Continue the current task from where it stopped."
- },
"template": {
"useTemplate": "Getting Started",
"blank": "Blank",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index ce4e4db6b7..64b1495d1c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9707,8 +9707,10 @@
"retryTitle": "最後のメッセージを再送信",
"cancelTitle": "エラーを閉じる",
"retry": "再試行",
- "continueAfterReset": "リセット後に続行",
- "continueAfterResetTitle": "利用上限のリセット後にこのタスクを続行する一回限りの自動化を作成",
+ "usageLimitAutoContinueAt": "{{time}} に自動で続行",
+ "usageLimitAutoContinueTitle": "使用量の上限がリセットされるまでに操作がなければ、このタスクを自動で続行します",
+ "usageLimitAutoContinueCancel": "キャンセル",
+ "usageLimitAutoContinueCancelTitle": "自動続行をキャンセル(エラーと再試行は残ります)",
"codexOrganizationUsageLimitWithReset": "接続中の Codex アカウントは組織によって管理されており、利用上限に達しました。{{resetAt}} にリセットされる見込みです。",
"codexOrganizationUsageLimit": "接続中の Codex アカウントは組織によって管理されており、利用上限に達しました。上限のリセットを待つか、別の利用可能なアカウントに切り替えてから再試行してください。",
"codexUsageLimitWithReset": "接続中の Codex アカウントは利用上限に達しました。{{resetAt}} にリセットされる見込みです。",
@@ -10139,6 +10141,7 @@
"label": "再接続しました",
"labelFailed": "再接続できませんでした",
"labelNeutral": "再接続",
+ "labelUsageReset": "使用量が回復したため自動で続行しました",
"detail": {
"reason": "中断の理由",
"attempt": "今回の再試行 {{attempt}}/{{total}}",
@@ -11486,10 +11489,6 @@
"promptHeading": "自動化がまだありません",
"promptDescription": "cron 自動化を作成して、プロンプトをスケジュール実行させましょう。"
},
- "usageLimitRecovery": {
- "name": "利用上限リセット後にタスクを続行",
- "prompt": "中断したところから現在のタスクを続行してください。"
- },
"template": {
"useTemplate": "初心者ヘルプ",
"blank": "空白",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 55289112e2..02ac825961 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9707,8 +9707,10 @@
"retryTitle": "마지막 메시지 다시 보내기",
"cancelTitle": "오류 알림 닫기",
"retry": "다시 시도",
- "continueAfterReset": "재설정 후 계속",
- "continueAfterResetTitle": "사용량 제한 재설정 후 현재 작업을 계속할 일회성 자동화 만들기",
+ "usageLimitAutoContinueAt": "{{time}}에 자동으로 계속",
+ "usageLimitAutoContinueTitle": "사용량 한도가 재설정될 때까지 별도 조치가 없으면 이 작업을 자동으로 계속합니다",
+ "usageLimitAutoContinueCancel": "취소",
+ "usageLimitAutoContinueCancelTitle": "자동 계속 취소(오류와 다시 시도는 유지됩니다)",
"codexOrganizationUsageLimitWithReset": "현재 연결된 Codex 계정은 조직에서 관리하며 사용량 한도에 도달했습니다. {{resetAt}}에 한도가 재설정될 예정입니다.",
"codexOrganizationUsageLimit": "현재 연결된 Codex 계정은 조직에서 관리하며 사용량 한도에 도달했습니다. 한도 재설정을 기다리거나 사용 가능한 다른 계정으로 전환한 후 다시 시도하세요.",
"codexUsageLimitWithReset": "현재 연결된 Codex 계정이 사용량 한도에 도달했습니다. {{resetAt}}에 한도가 재설정될 예정입니다.",
@@ -10139,6 +10141,7 @@
"label": "다시 연결되었습니다",
"labelFailed": "다시 연결하지 못했습니다",
"labelNeutral": "다시 연결",
+ "labelUsageReset": "사용량이 복구되어 자동으로 계속했습니다",
"detail": {
"reason": "중단 원인",
"attempt": "이번 재시도 {{attempt}}/{{total}}",
@@ -11486,10 +11489,6 @@
"promptHeading": "자동화가 아직 없습니다",
"promptDescription": "cron 자동화를 만들어 프롬프트를 일정에 따라 실행하세요."
},
- "usageLimitRecovery": {
- "name": "사용량 제한 재설정 후 작업 계속",
- "prompt": "중단된 지점부터 현재 작업을 계속하세요."
- },
"template": {
"useTemplate": "초보자 도움말",
"blank": "빈 항목",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 6a3b0ef1a0..7e04a2fe23 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9707,8 +9707,10 @@
"retryTitle": "重新发送最后一条消息",
"cancelTitle": "关闭错误提示",
"retry": "重试",
- "continueAfterReset": "恢复后继续",
- "continueAfterResetTitle": "创建一次性自动化,在用量恢复后继续当前任务",
+ "usageLimitAutoContinueAt": "将于 {{time}} 自动继续",
+ "usageLimitAutoContinueTitle": "用量上限重置后,如果你还没处理,这个任务会自动继续",
+ "usageLimitAutoContinueCancel": "取消",
+ "usageLimitAutoContinueCancelTitle": "取消自动继续,错误与重试仍保留",
"codexOrganizationUsageLimitWithReset": "当前连接的是企业 Codex 账号,已达到用量上限,预计于 {{resetAt}} 恢复。",
"codexOrganizationUsageLimit": "当前连接的是企业 Codex 账号,已达到用量上限。请等待用量上限重置,或切换其他可用账号后再重试。",
"codexUsageLimitWithReset": "当前连接的 Codex 账号已达到用量上限,预计于 {{resetAt}} 恢复。",
@@ -10139,6 +10141,7 @@
"label": "已重新连接",
"labelFailed": "重新连接未成功",
"labelNeutral": "重新连接",
+ "labelUsageReset": "用量已恢复,已自动继续",
"detail": {
"reason": "中断原因",
"attempt": "本次重试 {{attempt}}/{{total}}",
@@ -11486,10 +11489,6 @@
"promptHeading": "暂无自动化",
"promptDescription": "创建一个 cron 自动化,按计划执行你的 Prompt。"
},
- "usageLimitRecovery": {
- "name": "用量恢复后继续任务",
- "prompt": "从中断的位置继续完成当前任务。"
- },
"template": {
"useTemplate": "新手帮助",
"blank": "空白",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d86c2fb1a2..3ad2118eef 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9706,8 +9706,10 @@
"retryTitle": "重新傳送最後一條訊息",
"cancelTitle": "關閉錯誤提示",
"retry": "重試",
- "continueAfterReset": "恢復後繼續",
- "continueAfterResetTitle": "建立一次性自動化,在用量恢復後繼續當前任務",
+ "usageLimitAutoContinueAt": "將於 {{time}} 自動繼續",
+ "usageLimitAutoContinueTitle": "用量上限重置後,如果你還沒處理,這個任務會自動繼續",
+ "usageLimitAutoContinueCancel": "取消",
+ "usageLimitAutoContinueCancelTitle": "取消自動繼續,錯誤與重試仍保留",
"codexOrganizationUsageLimitWithReset": "目前連線的是企業 Codex 帳號,已達到用量上限,預計於 {{resetAt}} 恢復。",
"codexOrganizationUsageLimit": "目前連線的是企業 Codex 帳號,已達到用量上限。請等待用量上限重置,或切換其他可用帳號後再重試。",
"codexUsageLimitWithReset": "目前連線的 Codex 帳號已達到用量上限,預計於 {{resetAt}} 恢復。",
@@ -10138,6 +10140,7 @@
"label": "已重新連線",
"labelFailed": "重新連線未成功",
"labelNeutral": "重新連線",
+ "labelUsageReset": "用量已恢復,已自動繼續",
"detail": {
"reason": "中斷原因",
"attempt": "本次重試 {{attempt}}/{{total}}",
@@ -11486,10 +11489,6 @@
"promptHeading": "暫無自動化",
"promptDescription": "建立一個 cron 自動化,按計劃執行你的 Prompt。"
},
- "usageLimitRecovery": {
- "name": "用量恢復後繼續任務",
- "prompt": "從中斷的位置繼續完成當前任務。"
- },
"template": {
"useTemplate": "新手幫助",
"blank": "空白",
diff --git a/apps/desktop/src/renderer/lib/autoResumePresentation.ts b/apps/desktop/src/renderer/lib/autoResumePresentation.ts
index dd44de2dcb..c5b3958134 100644
--- a/apps/desktop/src/renderer/lib/autoResumePresentation.ts
+++ b/apps/desktop/src/renderer/lib/autoResumePresentation.ts
@@ -1,6 +1,9 @@
+import { USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../shared/agentInputQueue';
import type { ChatMessage, ContinuationInFlightProjectionCapability } from './makerChatStore';
export interface AutoResumeCardInfo {
+ /** 账号用量上限重置后自动继续(不是重连:不展示重试次数)。 */
+ usageLimitReset?: boolean;
error?: string;
attempt?: number;
maxAttempts?: number;
@@ -11,6 +14,7 @@ export interface AutoResumeCardInfo {
/** Silent-stop continuations have no interruption context and are not reconnects. */
export function hasInterruptionContext(info: AutoResumeCardInfo): boolean {
return (
+ info.usageLimitReset === true ||
info.error !== undefined ||
info.attempt !== undefined ||
info.maxAttempts !== undefined ||
@@ -23,6 +27,7 @@ export function readAutoResumeInfo(data?: Record<string, unknown>): AutoResumeCa
const num = (value: unknown) =>
typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
return {
+ ...(data?.reason === USAGE_LIMIT_RESET_AUTO_RESUME_REASON ? { usageLimitReset: true } : {}),
...(typeof data?.error === 'string' && data.error.length > 0 ? { error: data.error } : {}),
...(num(data?.attempt) !== undefined ? { attempt: num(data?.attempt) } : {}),
...(num(data?.maxAttempts) !== undefined ? { maxAttempts: num(data?.maxAttempts) } : {}),
@@ -78,6 +83,8 @@ export function findActiveReconnect(args: {
if (message.role !== 'user' || message.systemCardType !== 'auto-resume') continue;
const info = readAutoResumeInfo(message.systemCardData);
if (
+ // 用量上限重置后的自动继续不是重连:输入框不显示「重新连接中」。
+ !info.usageLimitReset &&
hasInterruptionContext(info) &&
info.outcome === undefined &&
isAutoResumeRowInFlight({
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index b2cf1498ce..bba1e34d66 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -2577,6 +2577,11 @@ export interface SessionChatState {
* 会话挡住;队首保留、结束后 main 自动重发。渲染为等待横幅(非错误)。
*/
credentialSwitchWait: { clientId?: string; blockedBySessionIds: string[] } | null;
+ /**
+ * 账号限额等待(main projection 透传):错误照常显示,横幅附「将于 X 自动继续 · 取消」。
+ * 只在 error 仍在时有值;老被控端缺省 = null。
+ */
+ usageLimitWait: { resumeAt: number } | null;
/**
* Main coordinator 中已经离开 pendingQueue、但仍占有 dispatch/turn 边界的
* Continue clientId。用于让中断横幅在「离队 → running/session patch」窗口
@@ -2866,6 +2871,7 @@ export type SessionChatLightState = Pick<
| 'errorPersistId'
| 'disposedErrorPersistId'
| 'credentialSwitchWait'
+ | 'usageLimitWait'
| 'continuationInFlightClientId'
| 'continuationTurnClientId'
| 'continuationInFlightProjectionCapability'
@@ -2935,6 +2941,7 @@ function createInitialState(): SessionChatState {
errorPersistId: null,
disposedErrorPersistId: null,
credentialSwitchWait: null,
+ usageLimitWait: null,
continuationInFlightClientId: null,
continuationTurnClientId: null,
continuationInFlightProjectionCapability: 'unknown',
@@ -3016,6 +3023,7 @@ export const EMPTY_SESSION_STATE: SessionChatState = Object.freeze({
errorPersistId: null,
disposedErrorPersistId: null,
credentialSwitchWait: null,
+ usageLimitWait: null,
continuationInFlightClientId: null,
continuationTurnClientId: null,
continuationInFlightProjectionCapability: 'unknown',
@@ -4830,6 +4838,12 @@ function applyInputProjection(
errorRetryText: projection.errorRetryText,
errorPersistId: projection.error ? s.errorPersistId : null,
credentialSwitchWait: projection.credentialSwitchWait ?? null,
+ usageLimitWait:
+ projection.error && projection.usageLimitWait
+ ? s.usageLimitWait?.resumeAt === projection.usageLimitWait.resumeAt
+ ? s.usageLimitWait
+ : { resumeAt: projection.usageLimitWait.resumeAt }
+ : null,
continuationInFlightClientId: projection.continuationInFlightClientId ?? null,
continuationTurnClientId: projectedContinuationTurnClientId,
continuationInFlightProjectionCapability,
@@ -9613,6 +9627,7 @@ function selectLightState(state: SessionChatState): SessionChatLightState {
errorPersistId: state.errorPersistId,
disposedErrorPersistId: state.disposedErrorPersistId,
credentialSwitchWait: state.credentialSwitchWait,
+ usageLimitWait: state.usageLimitWait,
continuationInFlightClientId: state.continuationInFlightClientId,
continuationTurnClientId: state.continuationTurnClientId,
continuationInFlightProjectionCapability: state.continuationInFlightProjectionCapability,
@@ -9663,6 +9678,7 @@ function lightStateEquals(a: SessionChatLightState, b: SessionChatLightState): b
a.errorPersistId === b.errorPersistId &&
a.disposedErrorPersistId === b.disposedErrorPersistId &&
a.credentialSwitchWait === b.credentialSwitchWait &&
+ a.usageLimitWait === b.usageLimitWait &&
a.continuationInFlightClientId === b.continuationInFlightClientId &&
a.continuationTurnClientId === b.continuationTurnClientId &&
a.continuationInFlightProjectionCapability === b.continuationInFlightProjectionCapability &&
@@ -15580,6 +15596,18 @@ function disposeLiveErrorPersist(sessionId: string): void {
});
}
+/** 取消账号限额重置后的自动继续:错误与手动重试保留,只撤等待。 */
+function cancelUsageLimitWait(sessionId: string): void {
+ if (!sessionId) return;
+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);
+ runInputProjectionOperation(sessionId, (input) =>
+ boundaryOpts
+ ? input.cancelUsageLimitWait(sessionId, boundaryOpts)
+ : input.cancelUsageLimitWait(sessionId),
+ ).catch((err) => log.warn('cancelUsageLimitWait failed:', err));
+ // 不乐观清除:以主进程返回的投影为准。取消失败时等待仍会到点执行,提示必须留着。
+}
+
/**
* Dismiss the error banner without retrying. Also disposes the bound persist row
* so the same error does not reappear as a tail banner in this view.
@@ -17499,6 +17527,7 @@ export const makerChatStore = {
clearSession,
/** Dismiss the error banner without retrying. */
clearError,
+ cancelUsageLimitWait,
/** Bind live error to persist row as already handled (retry/close). */
disposeLiveErrorPersist,
/** Retry the typed recovery target owned by main coordinator. */
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index 49ef07c096..cecc2bfe3f 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -151,6 +151,7 @@ export interface RoutableMaker {
| 'updateText'
| 'updateContent'
| 'clearError'
+ | 'cancelUsageLimitWait'
| 'retryLastError'
| 'clearSession'
| 'persistTurnErrorDeferred'
@@ -265,6 +266,7 @@ function remoteMakerApi(deviceId: string): RoutableMaker {
updateText: t('maker:input:update-text') as FullMaker['input']['updateText'],
updateContent: t('maker:input:update-content') as FullMaker['input']['updateContent'],
clearError: t('maker:input:clear-error') as FullMaker['input']['clearError'],
+ cancelUsageLimitWait: t('maker:input:cancel-usage-limit-wait') as FullMaker['input']['cancelUsageLimitWait'],
retryLastError: t('maker:input:retry-last-error') as FullMaker['input']['retryLastError'],
clearSession: t('maker:input:clear-session') as FullMaker['input']['clearSession'],
// device-link:auth error 重试失败/放弃时在被控端落库,经隧道路由到被控端 main。
diff --git a/apps/desktop/src/renderer/lib/usageLimitRecovery.ts b/apps/desktop/src/renderer/lib/usageLimitRecovery.ts
index f836a8806a..412e0c465d 100644
--- a/apps/desktop/src/renderer/lib/usageLimitRecovery.ts
+++ b/apps/desktop/src/renderer/lib/usageLimitRecovery.ts
@@ -1,315 +1,2 @@
-/**
- * Renderer-side usage-limit detection.
- *
- * The live maker event is the most precise signal available to the chat UI:
- * Claude normally supplies sdkError='rate_limit', while Codex may only supply
- * an HTTP status / codexErrorInfo / human-readable message. Keep this
- * deliberately conservative because this result exposes an Automation action.
- */
-
-export interface UsageLimitRecoveryHint {
- resetAtMs: number | null;
- /** True only when upstream explicitly identifies account-cycle exhaustion, not a generic 429. */
- isAccountUsageLimit?: boolean;
- /** Upstream subscription plan when the provider exposes it (for example `business`). */
- planType?: string;
-}
-
-type UnknownRecord = Record<string, unknown>;
-
-const ABSOLUTE_RESET_KEYS = new Set([
- 'resetat',
- 'resetatms',
- 'reset_at',
- 'resetsat',
- 'resets_at',
- 'usageresetat',
- 'usageresetatms',
- 'usage_reset_at',
-]);
-
-const RETRY_AFTER_MS_KEYS = new Set(['retryafterms', 'retry_after_ms']);
-const RETRY_AFTER_SECONDS_KEYS = new Set([
- 'retryafter',
- 'retryafterseconds',
- 'retry_after',
- 'retry_after_seconds',
-]);
-const PLAN_TYPE_KEYS = new Set(['plantype', 'plan_type']);
-const EXPLICIT_ACCOUNT_USAGE_LIMIT_PATTERN = /\busage_limit_reached\b|\busageLimitExceeded\b/;
-
-function asRecord(value: unknown): UnknownRecord | null {
- return value !== null && typeof value === 'object' && !Array.isArray(value)
- ? (value as UnknownRecord)
- : null;
-}
-
-function collectRecords(root: UnknownRecord): UnknownRecord[] {
- const records: UnknownRecord[] = [];
- const queue: Array<{ record: UnknownRecord; depth: number }> = [{ record: root, depth: 0 }];
- const seen = new Set<UnknownRecord>();
- while (queue.length > 0) {
- const current = queue.shift();
- if (!current || seen.has(current.record)) continue;
- seen.add(current.record);
- records.push(current.record);
- if (current.depth >= 2) continue;
- for (const value of Object.values(current.record)) {
- const nested = asRecord(value);
- if (nested) queue.push({ record: nested, depth: current.depth + 1 });
- }
- }
- return records;
-}
-
-function collectText(records: readonly UnknownRecord[]): string {
- const parts: string[] = [];
- for (const record of records) {
- for (const value of Object.values(record)) {
- if (typeof value === 'string') parts.push(value);
- }
- }
- return parts.join('\n');
-}
-
-function finiteNumber(value: unknown): number | null {
- if (typeof value === 'number' && Number.isFinite(value)) return value;
- if (typeof value === 'string' && value.trim()) {
- const parsed = Number(value.trim());
- if (Number.isFinite(parsed)) return parsed;
- }
- return null;
-}
-
-function normalizeAbsoluteTimestamp(value: unknown, nowMs: number): number | null {
- const numeric = finiteNumber(value);
- if (numeric !== null) {
- // Epoch seconds are currently around 1e9; epoch milliseconds around 1e12.
- const timestamp = numeric >= 100_000_000_000 ? numeric : numeric * 1000;
- return timestamp > nowMs ? timestamp : null;
- }
- if (typeof value !== 'string') return null;
- const parsed = Date.parse(value);
- return Number.isFinite(parsed) && parsed > nowMs ? parsed : null;
-}
-
-function parseStructuredResetAt(records: readonly UnknownRecord[], nowMs: number): number | null {
- for (const record of records) {
- for (const [rawKey, value] of Object.entries(record)) {
- const key = rawKey.toLowerCase();
- if (ABSOLUTE_RESET_KEYS.has(key)) {
- const parsed = normalizeAbsoluteTimestamp(value, nowMs);
- if (parsed !== null) return parsed;
- }
- if (RETRY_AFTER_MS_KEYS.has(key)) {
- const delay = finiteNumber(value);
- if (delay !== null && delay > 0) return nowMs + delay;
- }
- if (RETRY_AFTER_SECONDS_KEYS.has(key)) {
- const delay = finiteNumber(value);
- if (delay !== null && delay > 0) return nowMs + delay * 1000;
- }
- }
- }
- return null;
-}
-
-function normalizePlanType(value: unknown): string | null {
- if (typeof value !== 'string') return null;
- const normalized = value.trim().toLowerCase();
- return normalized && normalized.length <= 64 ? normalized : null;
-}
-
-function parsePlanType(records: readonly UnknownRecord[], text: string): string | null {
- for (const record of records) {
- for (const [rawKey, value] of Object.entries(record)) {
- if (!PLAN_TYPE_KEYS.has(rawKey.toLowerCase())) continue;
- const normalized = normalizePlanType(value);
- if (normalized) return normalized;
- }
- }
-
- const textMatch = text.match(/["']?plan[_-]?type["']?\s*[:=]\s*["']?([a-z0-9_-]+)["']?/i);
- return normalizePlanType(textMatch?.[1]);
-}
-
-function parseRelativeResetAt(text: string, nowMs: number): number | null {
- const relative = text.match(
- /(?:resets?|retry(?:\s+after)?|try\s+again)\s+(?:in\s+)?(?:(\d+)\s*d(?:ays?)?\s*)?(?:(\d+)\s*h(?:ours?)?\s*)?(?:(\d+)\s*m(?:in(?:ute)?s?)?\s*)?(?:(\d+)\s*s(?:ec(?:ond)?s?)?)?/i,
- );
- if (!relative) return null;
- const days = Number(relative[1] ?? 0);
- const hours = Number(relative[2] ?? 0);
- const minutes = Number(relative[3] ?? 0);
- const seconds = Number(relative[4] ?? 0);
- const delayMs = (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
- return delayMs > 0 ? nowMs + delayMs : null;
-}
-
-function partsInTimeZone(timestamp: number, timeZone: string): Record<string, number> | null {
- try {
- const formatter = new Intl.DateTimeFormat('en-US', {
- timeZone,
- year: 'numeric',
- month: 'numeric',
- day: 'numeric',
- hour: 'numeric',
- minute: 'numeric',
- second: 'numeric',
- hourCycle: 'h23',
- });
- const parts: Record<string, number> = {};
- for (const part of formatter.formatToParts(new Date(timestamp))) {
- if (
- part.type !== 'year' &&
- part.type !== 'month' &&
- part.type !== 'day' &&
- part.type !== 'hour' &&
- part.type !== 'minute' &&
- part.type !== 'second'
- ) {
- continue;
- }
- const value = Number(part.value);
- if (!Number.isFinite(value)) continue;
- // Keep parity with maker-scheduler's wallClock(): some Intl
- // implementations report midnight as 24 even with hourCycle=h23.
- parts[part.type] = part.type === 'hour' && value === 24 ? 0 : value;
- }
- return parts;
- } catch {
- return null;
- }
-}
-
-function zonedDateTimeToMs(
- input: { year: number; month: number; day: number; hour: number; minute: number },
- timeZone: string,
-): number | null {
- const targetAsUtc = Date.UTC(input.year, input.month - 1, input.day, input.hour, input.minute, 0);
- let guess = targetAsUtc;
- for (let i = 0; i < 3; i += 1) {
- const actual = partsInTimeZone(guess, timeZone);
- if (!actual) return null;
- const actualAsUtc = Date.UTC(
- actual.year,
- actual.month - 1,
- actual.day,
- actual.hour,
- actual.minute,
- actual.second,
- );
- guess += targetAsUtc - actualAsUtc;
- }
- const verified = partsInTimeZone(guess, timeZone);
- if (
- !verified ||
- verified.year !== input.year ||
- verified.month !== input.month ||
- verified.day !== input.day ||
- verified.hour !== input.hour ||
- verified.minute !== input.minute
- ) {
- return null;
- }
- return guess;
-}
-
-function parseTimeOfDayResetAt(text: string, nowMs: number): number | null {
- const match = text.match(
- /\bresets?(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i,
- );
- if (!match) return null;
- let hour = Number(match[1]);
- const minute = Number(match[2] ?? 0);
- if (hour < 1 || hour > 12 || minute > 59) return null;
- const meridiem = match[3].toLowerCase();
- if (hour === 12) hour = 0;
- if (meridiem === 'pm') hour += 12;
- const fallbackTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
- const timeZone = match[4]?.trim() || fallbackTimeZone;
- const current = partsInTimeZone(nowMs, timeZone);
- if (!current) return null;
-
- for (let dayOffset = 0; dayOffset <= 1; dayOffset += 1) {
- const date = new Date(Date.UTC(current.year, current.month - 1, current.day + dayOffset));
- const candidate = zonedDateTimeToMs(
- {
- year: date.getUTCFullYear(),
- month: date.getUTCMonth() + 1,
- day: date.getUTCDate(),
- hour,
- minute,
- },
- timeZone,
- );
- if (candidate !== null && candidate > nowMs) return candidate;
- }
- return null;
-}
-
-function parseTextResetAt(text: string, nowMs: number): number | null {
- const isoMatches = text.match(
- /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})\b/g,
- );
- for (const value of isoMatches ?? []) {
- const parsed = Date.parse(value);
- if (Number.isFinite(parsed) && parsed > nowMs) return parsed;
- }
-
- const labeledEpoch = text.match(/(?:reset(?:s|_at|At)?|retry[_\s-]*after)\D{0,12}(\d{10,13})\b/i);
- if (labeledEpoch) {
- const parsed = normalizeAbsoluteTimestamp(labeledEpoch[1], nowMs);
- if (parsed !== null) return parsed;
- }
-
- return parseRelativeResetAt(text, nowMs) ?? parseTimeOfDayResetAt(text, nowMs);
-}
-
-/**
- * Returns a hint only for a restorable account usage/rate limit. Billing
- * depletion and temporary upstream overload are intentionally excluded.
- */
-export function extractUsageLimitRecoveryHint(
- data: unknown,
- nowMs = Date.now(),
-): UsageLimitRecoveryHint | null {
- const root = asRecord(data);
- if (!root) return null;
- const records = collectRecords(root);
- const text = collectText(records);
-
- const sdkError = typeof root.sdkError === 'string' ? root.sdkError : '';
- const codexErrorInfo = typeof root.codexErrorInfo === 'string' ? root.codexErrorInfo : '';
- const status = finiteNumber(root.errorStatus ?? root.status);
-
- if (
- sdkError === 'billing_error' ||
- codexErrorInfo === 'serverOverloaded' ||
- status === 529 ||
- /\b(?:insufficient_quota|billing_error|credit(?:s| balance)?\s+(?:depleted|exhausted|too low)|at capacity|overloaded_error)\b/i.test(
- text,
- )
- ) {
- return null;
- }
-
- const isAccountUsageLimit = EXPLICIT_ACCOUNT_USAGE_LIMIT_PATTERN.test(text);
- const isUsageLimit =
- sdkError === 'rate_limit' ||
- codexErrorInfo === 'usageLimitExceeded' ||
- isAccountUsageLimit ||
- root.usageLimit === true ||
- status === 429 ||
- /\b(?:rate.?limit|usage.?limit|too\s+many\s+requests|quota\s+(?:exceeded|exhausted)|you(?:'|’)ve\s+hit\s+your\s+(?:(?:session|weekly)\s+)?limit)\b/i.test(
- text,
- );
- if (!isUsageLimit) return null;
-
- const planType = parsePlanType(records, text);
- return {
- resetAtMs: parseStructuredResetAt(records, nowMs) ?? parseTextResetAt(text, nowMs),
- ...(isAccountUsageLimit ? { isAccountUsageLimit: true } : {}),
- ...(planType ? { planType } : {}),
- };
-}
+// 解析器在 shared:main 侧的限额自动续跑与 renderer 横幅共用同一份判定。
+export * from '../../shared/usageLimitRecovery';
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 687dc1dc74..6fda8e8951 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6125,6 +6125,11 @@ interface ElectronAPI {
sessionId: string,
opts?: { expectedClearBoundaryMs?: number | null },
) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;
+ /** 取消账号限额重置后的自动继续(错误与重试保留)。 */
+ cancelUsageLimitWait: (
+ sessionId: string,
+ opts?: { expectedClearBoundaryMs?: number | null },
+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;
persistTurnErrorDeferred: (
sessionId: string,
errData: Record<string, unknown> | null,
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index b1fb9be927..471246b84f 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -205,6 +205,18 @@ export interface AutoResumeInfo {
sessionTotal: number;
}
+/** 账号额度重置后自动继续时 `AutoResumeInfo.reason` 的取值(活动行据此换文案)。 */
+export const USAGE_LIMIT_RESET_AUTO_RESUME_REASON = 'usage-limit-reset';
+
+/**
+ * 普通任务撞上账号 5 小时 / 周限额后的等待计划:错误照常呈现,用户可随时自己处理;
+ * 到 `resumeAt` 仍无人处理时被控端自动继续该任务。仅在本次运行内有效(不落盘)。
+ */
+export interface AgentInputUsageLimitWait {
+ /** 预计自动继续的时刻(unix ms,已含重置后的缓冲)。 */
+ resumeAt: number;
+}
+
/**
* Durable recovery context for a retry/continue action.
*
@@ -485,6 +497,11 @@ export interface AgentInputProjection {
* 老被控端可能缺省该字段,消费方按 falsy 处理即可(退化成"没有自愈提示")。
*/
autoResumePending?: AutoResumeInfo;
+ /**
+ * 账号限额等待中(与 `error` 同时存在:错误照常显示,横幅附「将于 X 自动继续 · 取消」)。
+ * 老被控端缺省该字段,消费方按 null 处理(退化成只有错误、没有自动继续)。
+ */
+ usageLimitWait?: AgentInputUsageLimitWait | null;
}
export type AgentInputMakerMessage =
diff --git a/apps/desktop/src/shared/usageLimitRecovery.ts b/apps/desktop/src/shared/usageLimitRecovery.ts
new file mode 100644
index 0000000000..a93393f9c6
--- /dev/null
+++ b/apps/desktop/src/shared/usageLimitRecovery.ts
@@ -0,0 +1,365 @@
+/**
+ * Usage-limit detection shared by the renderer banner and the main-process
+ * usage-limit auto-resume.
+ *
+ * The terminal error event is the most precise signal available: Claude normally
+ * supplies sdkError='rate_limit', while Codex may only supply an HTTP status /
+ * codexErrorInfo / human-readable message. Keep this deliberately conservative
+ * because a reset time here schedules an automatic continuation.
+ */
+
+export interface UsageLimitRecoveryHint {
+ resetAtMs: number | null;
+ /** True only when upstream explicitly identifies account-cycle exhaustion, not a generic 429. */
+ isAccountUsageLimit?: boolean;
+ /** Upstream subscription plan when the provider exposes it (for example `business`). */
+ planType?: string;
+}
+
+type UnknownRecord = Record<string, unknown>;
+
+const ABSOLUTE_RESET_KEYS = new Set([
+ 'resetat',
+ 'resetatms',
+ 'reset_at',
+ 'resetsat',
+ 'resets_at',
+ 'usageresetat',
+ 'usageresetatms',
+ 'usage_reset_at',
+]);
+
+const RETRY_AFTER_MS_KEYS = new Set(['retryafterms', 'retry_after_ms']);
+const RETRY_AFTER_SECONDS_KEYS = new Set([
+ 'retryafter',
+ 'retryafterseconds',
+ 'retry_after',
+ 'retry_after_seconds',
+]);
+const PLAN_TYPE_KEYS = new Set(['plantype', 'plan_type']);
+const EXPLICIT_ACCOUNT_USAGE_LIMIT_PATTERN = /\busage_limit_reached\b|\busageLimitExceeded\b/;
+
+function asRecord(value: unknown): UnknownRecord | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as UnknownRecord)
+ : null;
+}
+
+function collectRecords(root: UnknownRecord): UnknownRecord[] {
+ const records: UnknownRecord[] = [];
+ const queue: Array<{ record: UnknownRecord; depth: number }> = [{ record: root, depth: 0 }];
+ const seen = new Set<UnknownRecord>();
+ while (queue.length > 0) {
+ const current = queue.shift();
+ if (!current || seen.has(current.record)) continue;
+ seen.add(current.record);
+ records.push(current.record);
+ if (current.depth >= 2) continue;
+ for (const value of Object.values(current.record)) {
+ const nested = asRecord(value);
+ if (nested) queue.push({ record: nested, depth: current.depth + 1 });
+ }
+ }
+ return records;
+}
+
+function collectText(records: readonly UnknownRecord[]): string {
+ const parts: string[] = [];
+ for (const record of records) {
+ for (const value of Object.values(record)) {
+ if (typeof value === 'string') parts.push(value);
+ }
+ }
+ return parts.join('\n');
+}
+
+function finiteNumber(value: unknown): number | null {
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+ if (typeof value === 'string' && value.trim()) {
+ const parsed = Number(value.trim());
+ if (Number.isFinite(parsed)) return parsed;
+ }
+ return null;
+}
+
+function normalizeAbsoluteTimestamp(value: unknown, nowMs: number): number | null {
+ const numeric = finiteNumber(value);
+ if (numeric !== null) {
+ // Epoch seconds are currently around 1e9; epoch milliseconds around 1e12.
+ const timestamp = numeric >= 100_000_000_000 ? numeric : numeric * 1000;
+ return timestamp > nowMs ? timestamp : null;
+ }
+ if (typeof value !== 'string') return null;
+ const parsed = Date.parse(value);
+ return Number.isFinite(parsed) && parsed > nowMs ? parsed : null;
+}
+
+function parseStructuredResetAt(records: readonly UnknownRecord[], nowMs: number): number | null {
+ for (const record of records) {
+ for (const [rawKey, value] of Object.entries(record)) {
+ const key = rawKey.toLowerCase();
+ if (ABSOLUTE_RESET_KEYS.has(key)) {
+ const parsed = normalizeAbsoluteTimestamp(value, nowMs);
+ if (parsed !== null) return parsed;
+ }
+ if (RETRY_AFTER_MS_KEYS.has(key)) {
+ const delay = finiteNumber(value);
+ if (delay !== null && delay > 0) return nowMs + delay;
+ }
+ if (RETRY_AFTER_SECONDS_KEYS.has(key)) {
+ const delay = finiteNumber(value);
+ if (delay !== null && delay > 0) return nowMs + delay * 1000;
+ }
+ }
+ }
+ return null;
+}
+
+function normalizePlanType(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const normalized = value.trim().toLowerCase();
+ return normalized && normalized.length <= 64 ? normalized : null;
+}
+
+function parsePlanType(records: readonly UnknownRecord[], text: string): string | null {
+ for (const record of records) {
+ for (const [rawKey, value] of Object.entries(record)) {
+ if (!PLAN_TYPE_KEYS.has(rawKey.toLowerCase())) continue;
+ const normalized = normalizePlanType(value);
+ if (normalized) return normalized;
+ }
+ }
+
+ const textMatch = text.match(/["']?plan[_-]?type["']?\s*[:=]\s*["']?([a-z0-9_-]+)["']?/i);
+ return normalizePlanType(textMatch?.[1]);
+}
+
+function parseRelativeResetAt(text: string, nowMs: number): number | null {
+ // `~` / `about`: Pi rewrites ChatGPT's resets_at into "Try again in ~N min".
+ const relative = text.match(
+ /(?:resets?|retry(?:\s+after)?|try\s+again)\s+(?:in\s+)?(?:~\s*|about\s+)?(?:(\d+)\s*d(?:ays?)?\s*)?(?:(\d+)\s*h(?:ours?)?\s*)?(?:(\d+)\s*m(?:in(?:ute)?s?)?\s*)?(?:(\d+)\s*s(?:ec(?:ond)?s?)?)?/i,
+ );
+ if (!relative) return null;
+ const days = Number(relative[1] ?? 0);
+ const hours = Number(relative[2] ?? 0);
+ const minutes = Number(relative[3] ?? 0);
+ const seconds = Number(relative[4] ?? 0);
+ const delayMs = (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
+ return delayMs > 0 ? nowMs + delayMs : null;
+}
+
+function partsInTimeZone(timestamp: number, timeZone: string): Record<string, number> | null {
+ try {
+ const formatter = new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ year: 'numeric',
+ month: 'numeric',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: 'numeric',
+ second: 'numeric',
+ hourCycle: 'h23',
+ });
+ const parts: Record<string, number> = {};
+ for (const part of formatter.formatToParts(new Date(timestamp))) {
+ if (
+ part.type !== 'year' &&
+ part.type !== 'month' &&
+ part.type !== 'day' &&
+ part.type !== 'hour' &&
+ part.type !== 'minute' &&
+ part.type !== 'second'
+ ) {
+ continue;
+ }
+ const value = Number(part.value);
+ if (!Number.isFinite(value)) continue;
+ // Keep parity with maker-scheduler's wallClock(): some Intl
+ // implementations report midnight as 24 even with hourCycle=h23.
+ parts[part.type] = part.type === 'hour' && value === 24 ? 0 : value;
+ }
+ return parts;
+ } catch {
+ return null;
+ }
+}
+
+function zonedDateTimeToMs(
+ input: { year: number; month: number; day: number; hour: number; minute: number },
+ timeZone: string,
+): number | null {
+ const targetAsUtc = Date.UTC(input.year, input.month - 1, input.day, input.hour, input.minute, 0);
+ let guess = targetAsUtc;
+ for (let i = 0; i < 3; i += 1) {
+ const actual = partsInTimeZone(guess, timeZone);
+ if (!actual) return null;
+ const actualAsUtc = Date.UTC(
+ actual.year,
+ actual.month - 1,
+ actual.day,
+ actual.hour,
+ actual.minute,
+ actual.second,
+ );
+ guess += targetAsUtc - actualAsUtc;
+ }
+ const verified = partsInTimeZone(guess, timeZone);
+ if (
+ !verified ||
+ verified.year !== input.year ||
+ verified.month !== input.month ||
+ verified.day !== input.day ||
+ verified.hour !== input.hour ||
+ verified.minute !== input.minute
+ ) {
+ return null;
+ }
+ return guess;
+}
+
+const MONTH_INDEX: Record<string, number> = {
+ jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6,
+ jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12,
+};
+
+export interface UsageLimitRecoveryParseOptions {
+ /**
+ * 不带时区的绝对钟点(Codex `try again at 3:05 PM`)是否可按本机时区理解。SSH 远程会话的
+ * 报错用的是远端主机的本地时间,传 false 时这类钟点不解析;相对时长与带时区的时刻不受影响。
+ */
+ localTimeZoneTrusted?: boolean;
+}
+
+function parseTimeOfDayResetAt(
+ text: string,
+ nowMs: number,
+ opts?: UsageLimitRecoveryParseOptions,
+): number | null {
+ // Claude: "resets 1:20am (Pacific/Auckland)".
+ // Codex: "try again at 3:05 PM." / "try again at Oct 8, 2026 3:05 PM." (local time).
+ const match = text.match(
+ /\b(?:resets?(?:\s+at)?|try\s+again\s+at)\s+(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2}),\s*(\d{4})\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i,
+ );
+ if (!match) return null;
+ let hour = Number(match[4]);
+ const minute = Number(match[5] ?? 0);
+ if (hour < 1 || hour > 12 || minute > 59) return null;
+ const meridiem = match[6].toLowerCase();
+ if (hour === 12) hour = 0;
+ if (meridiem === 'pm') hour += 12;
+ const explicitTimeZone = match[7]?.trim();
+ if (!explicitTimeZone && opts?.localTimeZoneTrusted === false) return null;
+ const timeZone =
+ explicitTimeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+
+ if (match[1]) {
+ const month = MONTH_INDEX[match[1].toLowerCase()];
+ const day = Number(match[2]);
+ const year = Number(match[3]);
+ if (!month || day < 1 || day > 31) return null;
+ const candidate = zonedDateTimeToMs({ year, month, day, hour, minute }, timeZone);
+ return candidate !== null && candidate > nowMs ? candidate : null;
+ }
+
+ const current = partsInTimeZone(nowMs, timeZone);
+ if (!current) return null;
+
+ for (let dayOffset = 0; dayOffset <= 1; dayOffset += 1) {
+ const date = new Date(Date.UTC(current.year, current.month - 1, current.day + dayOffset));
+ const candidate = zonedDateTimeToMs(
+ {
+ year: date.getUTCFullYear(),
+ month: date.getUTCMonth() + 1,
+ day: date.getUTCDate(),
+ hour,
+ minute,
+ },
+ timeZone,
+ );
+ if (candidate !== null && candidate > nowMs) return candidate;
+ }
+ return null;
+}
+
+function parseTextResetAt(
+ text: string,
+ nowMs: number,
+ opts?: UsageLimitRecoveryParseOptions,
+): number | null {
+ const isoMatches = text.match(
+ /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})\b/g,
+ );
+ for (const value of isoMatches ?? []) {
+ const parsed = Date.parse(value);
+ if (Number.isFinite(parsed) && parsed > nowMs) return parsed;
+ }
+
+ const labeledEpoch = text.match(/(?:reset(?:s|_at|At)?|retry[_\s-]*after)\D{0,12}(\d{10,13})\b/i);
+ if (labeledEpoch) {
+ const parsed = normalizeAbsoluteTimestamp(labeledEpoch[1], nowMs);
+ if (parsed !== null) return parsed;
+ }
+
+ return parseRelativeResetAt(text, nowMs) ?? parseTimeOfDayResetAt(text, nowMs, opts);
+}
+
+/**
+ * Returns a hint only for a restorable account usage/rate limit. Billing
+ * depletion and temporary upstream overload are intentionally excluded.
+ */
+const BILLING_DEPLETION_PATTERN =
+ /\b(?:insufficient_quota|billing_error|credit(?:s| balance)?\s+(?:depleted|exhausted|too low))\b/i;
+
+/**
+ * 余额 / 计费耗尽(要充值,不会到点恢复)。即使文案里也出现 quota / limit,也不是周期额度上限,
+ * 所有「等额度重置」的判定都必须先排除它。
+ */
+export function isBillingDepletionError(data: unknown): boolean {
+ const root = asRecord(data);
+ if (!root) return false;
+ if (root.sdkError === 'billing_error') return true;
+ return BILLING_DEPLETION_PATTERN.test(collectText(collectRecords(root)));
+}
+
+export function extractUsageLimitRecoveryHint(
+ data: unknown,
+ nowMs = Date.now(),
+ opts?: UsageLimitRecoveryParseOptions,
+): UsageLimitRecoveryHint | null {
+ const root = asRecord(data);
+ if (!root) return null;
+ const records = collectRecords(root);
+ const text = collectText(records);
+
+ const sdkError = typeof root.sdkError === 'string' ? root.sdkError : '';
+ const codexErrorInfo = typeof root.codexErrorInfo === 'string' ? root.codexErrorInfo : '';
+ const status = finiteNumber(root.errorStatus ?? root.status);
+
+ if (
+ isBillingDepletionError(root) ||
+ codexErrorInfo === 'serverOverloaded' ||
+ status === 529 ||
+ /\b(?:at capacity|overloaded_error)\b/i.test(text)
+ ) {
+ return null;
+ }
+
+ const isAccountUsageLimit = EXPLICIT_ACCOUNT_USAGE_LIMIT_PATTERN.test(text);
+ const isUsageLimit =
+ sdkError === 'rate_limit' ||
+ codexErrorInfo === 'usageLimitExceeded' ||
+ isAccountUsageLimit ||
+ root.usageLimit === true ||
+ status === 429 ||
+ /\b(?:rate.?limit|usage.?limit|too\s+many\s+requests|quota\s+(?:exceeded|exhausted)|you(?:'|’)ve\s+hit\s+your\s+(?:(?:session|weekly)\s+)?limit)\b/i.test(
+ text,
+ );
+ if (!isUsageLimit) return null;
+
+ const planType = parsePlanType(records, text);
+ return {
+ resetAtMs: parseStructuredResetAt(records, nowMs) ?? parseTextResetAt(text, nowMs, opts),
+ ...(isAccountUsageLimit ? { isAccountUsageLimit: true } : {}),
+ ...(planType ? { planType } : {}),
+ };
+}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 0c03a897d2..9ff412f23b 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -7529,6 +7529,11 @@ export default function SessionScreen() {
void runQueueAction(() => maker.input.clearError(sessionId));
};
+ const cancelUsageLimitWait = () => {
+ if (queueAvailabilityReason) return;
+ void runQueueAction(() => maker.input.cancelUsageLimitWait(sessionId));
+ };
+
// --- session-tail-banner:error-tail / interrupted 收尾提示(对齐桌面两套 banner)---
// dismissedTailErrorClientIds 声明在上方 renderItems 区(errorTailClientId 过滤要用);
// acked = interrupted 已操作或本窗口内会话跑起来过(对齐桌面「跑起来即熄灭」锁存)。
@@ -9856,6 +9861,7 @@ export default function SessionScreen() {
busy={queueBusy}
sessionSource={currentSession?.source}
onClearError={clearQueueError}
+ onCancelUsageLimitWait={cancelUsageLimitWait}
onResume={resumeQueue}
onRetryError={retryQueueError}
projection={inputProjection}
diff --git a/apps/mobile/scripts/mock-device-link-host.mjs b/apps/mobile/scripts/mock-device-link-host.mjs
index dba86efc1b..09cce82080 100644
--- a/apps/mobile/scripts/mock-device-link-host.mjs
+++ b/apps/mobile/scripts/mock-device-link-host.mjs
@@ -282,6 +282,8 @@ async function handleInvoke(controllerId, channel, args) {
case 'maker:input:retry-last-error':
case 'maker:input:clear-error':
return updateProjection(String(args[0] ?? sessionId), { error: null, errorRetryText: null, recovery: null });
+ case 'maker:input:cancel-usage-limit-wait':
+ return updateProjection(String(args[0] ?? sessionId), { usageLimitWait: null });
case 'maker:input:remove':
return removeQueued(String(args[0] ?? sessionId), String(args[1] ?? ''));
case 'maker:input:update-text':
diff --git a/apps/mobile/src/__tests__/autoResumePresentation.test.ts b/apps/mobile/src/__tests__/autoResumePresentation.test.ts
index ca720594fe..19a29adfe4 100644
--- a/apps/mobile/src/__tests__/autoResumePresentation.test.ts
+++ b/apps/mobile/src/__tests__/autoResumePresentation.test.ts
@@ -56,3 +56,21 @@ describe('autoResumePresentation', () => {
expect(toggleMobileAutoResumeExpanded(true, false)).toBe(false);
});
});
+
+describe('usage-limit reset continuation', () => {
+ it('is its own row without reconnect attempt details', () => {
+ const presentation = getMobileAutoResumePresentation({
+ reason: 'usage-limit-reset',
+ error: "You've hit your session limit",
+ attempt: 1,
+ maxAttempts: 3,
+ sessionTotal: 1,
+ });
+ expect(presentation.info.usageLimitReset).toBe(true);
+ expect(presentation.state).toBe('neutral');
+ expect(presentation.hasProgress).toBe(false);
+ expect(presentation.info.sessionTotal).toBeUndefined();
+ expect(presentation.canExpand).toBe(true);
+ });
+});
+
diff --git a/apps/mobile/src/__tests__/inputProjection.test.ts b/apps/mobile/src/__tests__/inputProjection.test.ts
index aeea655abc..565eb21a60 100644
--- a/apps/mobile/src/__tests__/inputProjection.test.ts
+++ b/apps/mobile/src/__tests__/inputProjection.test.ts
@@ -647,3 +647,14 @@ describe('normalizeInputProjection — credentialSwitchWait', () => {
).toBeNull();
});
});
+
+describe('normalizeInputProjection usageLimitWait', () => {
+ it('reads the wait and treats legacy or malformed values as no wait', () => {
+ expect(normalizeInputProjection({ sessionId: 's1', usageLimitWait: { resumeAt: 123 } }).usageLimitWait)
+ .toEqual({ resumeAt: 123 });
+ expect(normalizeInputProjection({ sessionId: 's1' }).usageLimitWait).toBeNull();
+ expect(normalizeInputProjection({ sessionId: 's1', usageLimitWait: { resumeAt: 'soon' } }).usageLimitWait)
+ .toBeNull();
+ });
+});
+
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 9d276269ca..0e2164ff64 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -393,6 +393,7 @@ describe("mobile maker transport", () => {
"maker:input:resume",
"maker:input:retry-last-error",
"maker:input:clear-error",
+ "maker:input:cancel-usage-limit-wait",
"maker:input:remove",
"maker:input:update-text",
"maker:input:update-content",
@@ -768,6 +769,7 @@ describe("mobile maker transport", () => {
await maker.compactSession("s1", "focus on API design");
await maker.input.retryLastError("s1");
await maker.input.clearError("s1");
+ await maker.input.cancelUsageLimitWait("s1");
await maker.input.updateText("s1", "queued-1", "updated");
await maker.input.updateContent("s1", "queued-1", {
clientId: "queued-1",
@@ -845,6 +847,7 @@ describe("mobile maker transport", () => {
["maker:compact-session", ["s1", "focus on API design"]],
["maker:input:retry-last-error", ["s1"]],
["maker:input:clear-error", ["s1"]],
+ ["maker:input:cancel-usage-limit-wait", ["s1"]],
["maker:input:update-text", ["s1", "queued-1", "updated"]],
[
"maker:input:update-content",
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index fcacb65812..601da37594 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -839,6 +839,8 @@ export interface MobileMakerTransport {
resume(sessionId: string): Promise<InputProjection>;
retryLastError(sessionId: string): Promise<InputProjection>;
clearError(sessionId: string): Promise<InputProjection>;
+ /** 取消账号限额重置后的自动继续;老被控端没有该通道时会被拒(调用方只在投影带等待时显示入口)。 */
+ cancelUsageLimitWait(sessionId: string): Promise<InputProjection>;
remove(sessionId: string, clientId: string): Promise<InputProjection>;
updateText(
sessionId: string,
@@ -1392,6 +1394,8 @@ export function createMobileMakerTransport({
retryLastError: (sessionId) =>
call("maker:input:retry-last-error", [sessionId]),
clearError: (sessionId) => call("maker:input:clear-error", [sessionId]),
+ cancelUsageLimitWait: (sessionId) =>
+ call("maker:input:cancel-usage-limit-wait", [sessionId]),
remove: (sessionId, clientId) =>
call("maker:input:remove", [sessionId, clientId]),
updateText: (
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 860d8f4661..b70a112ef8 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -204,6 +204,8 @@
"withSource": "{{source}}: {{message}}",
"retrySend": "Retry Send",
"clearError": "Clear Error",
+ "usageLimitAutoContinueAt": "Continues automatically at {{time}}",
+ "usageLimitAutoContinueCancel": "Cancel Auto-Continue",
"noRetryContent": "No content is available to resend. Clear the error and enter your input again.",
"piImageInputUnsupported": "Image input is not enabled for the current Pi model. Switch to a model that supports images. For a custom model, enable “Supports image input” in provider settings, then start a new Pi task.",
"codexResumeNotReady": "Codex can't resume this task right now. Try again in a little while.",
@@ -252,6 +254,7 @@
"succeeded": "Reconnected",
"failed": "Reconnect failed",
"neutral": "Reconnect",
+ "usageReset": "Usage reset, continued automatically",
"pending": "Reconnecting…",
"pendingWithProgress": "Reconnecting {{attempt}}/{{total}}…",
"details": "Attempt {{attempt}}/{{total}} · {{count}} reconnects in this session",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 9039728b39..a901f7114f 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -204,6 +204,8 @@
"withSource": "{{source}}:{{message}}",
"retrySend": "送信を再試行",
"clearError": "エラーをクリア",
+ "usageLimitAutoContinueAt": "{{time}} に自動で続行",
+ "usageLimitAutoContinueCancel": "自動続行をキャンセル",
"noRetryContent": "再送信できる内容がありません。エラーをクリアして、もう一度入力してください。",
"piImageInputUnsupported": "現在の Pi モデルでは画像入力が有効になっていません。画像に対応するモデルへ切り替えてください。カスタムモデルの場合は、プロバイダー設定で「画像入力に対応」を有効にしてから、新しい Pi タスクを開始してください。",
"codexResumeNotReady": "Codex は現在このタスクを再開できません。しばらくしてからもう一度お試しください。",
@@ -252,6 +254,7 @@
"succeeded": "再接続しました",
"failed": "再接続できませんでした",
"neutral": "再接続",
+ "usageReset": "使用量が回復したため自動で続行しました",
"pending": "再接続中…",
"pendingWithProgress": "再接続中 {{attempt}}/{{total}}…",
"details": "今回の再試行 {{attempt}}/{{total}} · このセッションでの再接続 {{count}} 回",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 95ba7661fe..2ccbd7f258 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -204,6 +204,8 @@
"withSource": "{{source}}: {{message}}",
"retrySend": "전송 재시도",
"clearError": "오류 지우기",
+ "usageLimitAutoContinueAt": "{{time}}에 자동으로 계속",
+ "usageLimitAutoContinueCancel": "자동 계속 취소",
"noRetryContent": "다시 보낼 내용이 없습니다. 오류를 지운 후 다시 입력해 주세요.",
"piImageInputUnsupported": "현재 Pi 모델에는 이미지 입력이 활성화되어 있지 않습니다. 이미지를 지원하는 모델로 전환하세요. 사용자 지정 모델이라면 제공자 설정에서 ‘이미지 입력 지원’을 켠 다음 새 Pi 작업을 시작하세요.",
"codexResumeNotReady": "Codex에서 현재 이 작업을 재개할 수 없습니다. 잠시 후 다시 시도해 주세요.",
@@ -252,6 +254,7 @@
"succeeded": "다시 연결되었습니다",
"failed": "다시 연결하지 못했습니다",
"neutral": "다시 연결",
+ "usageReset": "사용량이 복구되어 자동으로 계속했습니다",
"pending": "다시 연결하는 중…",
"pendingWithProgress": "다시 연결하는 중 {{attempt}}/{{total}}…",
"details": "이번 재시도 {{attempt}}/{{total}} · 이 세션에서 재연결 {{count}}회",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index 0ccb440cd9..8f9a5e39b8 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -204,6 +204,8 @@
"withSource": "{{source}}:{{message}}",
"retrySend": "重试发送",
"clearError": "清除错误",
+ "usageLimitAutoContinueAt": "将于 {{time}} 自动继续",
+ "usageLimitAutoContinueCancel": "取消自动继续",
"noRetryContent": "没有可重发的内容,请清除错误后重新输入。",
"piImageInputUnsupported": "当前 Pi 模型未启用图片输入。请切换到支持图片的模型;如果这是自定义模型,请在供应商设置中开启“支持图片输入”,然后新建 Pi 任务。",
"codexResumeNotReady": "Codex 暂时无法恢复这个任务,请稍后重试",
@@ -252,6 +254,7 @@
"succeeded": "已重新连接",
"failed": "重新连接未成功",
"neutral": "重新连接",
+ "usageReset": "用量已恢复,已自动继续",
"pending": "重新连接中…",
"pendingWithProgress": "重新连接中 {{attempt}}/{{total}}…",
"details": "本次重试 {{attempt}}/{{total}} · 本任务累计重连 {{count}} 次",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index 76e3bdaf3b..dabbcb0f62 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -204,6 +204,8 @@
"withSource": "{{source}}:{{message}}",
"retrySend": "重試傳送",
"clearError": "清除錯誤",
+ "usageLimitAutoContinueAt": "將於 {{time}} 自動繼續",
+ "usageLimitAutoContinueCancel": "取消自動繼續",
"noRetryContent": "沒有可重新傳送的內容,請清除錯誤後重新輸入。",
"piImageInputUnsupported": "當前 Pi 模型未啟用圖片輸入。請切換到支援圖片的模型;如果這是自定義模型,請在供應商設定中開啟“支援圖片輸入”,然後新建 Pi 任務。",
"codexResumeNotReady": "Codex 暫時無法恢復這個任務,請稍後重試",
@@ -252,6 +254,7 @@
"succeeded": "已重新連線",
"failed": "重新連線未成功",
"neutral": "重新連線",
+ "usageReset": "用量已恢復,已自動繼續",
"pending": "重新連線中…",
"pendingWithProgress": "重新連線中 {{attempt}}/{{total}}…",
"details": "本次重試 {{attempt}}/{{total}} · 本任務累計重連 {{count}} 次",
diff --git a/apps/mobile/src/session/InlineQueueSection.tsx b/apps/mobile/src/session/InlineQueueSection.tsx
index c1bfdbd4ee..8b0e5bc8ca 100644
--- a/apps/mobile/src/session/InlineQueueSection.tsx
+++ b/apps/mobile/src/session/InlineQueueSection.tsx
@@ -46,6 +46,8 @@ export interface InlineQueueSectionProps {
onResume(): void;
onRetryError(): void;
onClearError(): void;
+ /** 取消账号限额重置后的自动继续(只在投影带 usageLimitWait 时出现)。 */
+ onCancelUsageLimitWait?(): void;
}
export function InlineQueueSection({
@@ -56,10 +58,11 @@ export function InlineQueueSection({
onResume,
onRetryError,
onClearError,
+ onCancelUsageLimitWait,
}: InlineQueueSectionProps) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const hasBanner = !!projection.error
|| !!projection.credentialSwitchWait
@@ -87,6 +90,10 @@ export function InlineQueueSection({
: (describeAgentAuthError(projection.error) ?? localizeUnclassifiedAgentError(projection.error, sessionSource)))
: null;
+ const usageLimitResumeAt = projection.error && projection.usageLimitWait
+ ? formatUsageLimitResumeAt(projection.usageLimitWait.resumeAt, i18n.resolvedLanguage || i18n.language)
+ : null;
+
return (
<View style={styles.container} testID="queue.inline.section">
{projection.error ? (
@@ -117,6 +124,24 @@ export function InlineQueueSection({
{retryDisabledReason}
</Text>
) : null}
+ {usageLimitResumeAt ? (
+ // 额度重置后自动继续(桌面端执行);等待期间重试 / 清除照常可用。
+ <View style={styles.errorActions} testID="queue.inline.usageLimitWait">
+ <Text style={styles.disabledHint}>
+ {t('message.queue.usageLimitAutoContinueAt', { time: usageLimitResumeAt })}
+ </Text>
+ {onCancelUsageLimitWait ? (
+ <ActionPill
+ busy={busy}
+ disabled={!!errorDisabledReason}
+ disabledReason={errorDisabledReason}
+ label={t('message.queue.usageLimitAutoContinueCancel')}
+ onPress={onCancelUsageLimitWait}
+ testID="queue.inline.cancelUsageLimitWaitButton"
+ />
+ ) : null}
+ </View>
+ ) : null}
</View>
) : null}
@@ -154,6 +179,19 @@ export function InlineQueueSection({
);
}
+/** 同一天只显示时刻,跨天带日期(与桌面横幅同口径)。 */
+function formatUsageLimitResumeAt(resumeAt: number, language: string): string | null {
+ if (!Number.isFinite(resumeAt)) return null;
+ const date = new Date(resumeAt);
+ const sameDay = date.toDateString() === new Date().toDateString();
+ return new Intl.DateTimeFormat(
+ language,
+ sameDay
+ ? { hour: '2-digit', minute: '2-digit' }
+ : { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' },
+ ).format(date);
+}
+
function ActionPill({
busy,
disabled,
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index d8a4d8ca0b..f3a848e0f8 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -5325,7 +5325,9 @@ function MobileAutoResumeActionRow({
);
}
- const label = state === 'live'
+ const label = info.usageLimitReset
+ ? t('message.systemCard.autoResume.usageReset')
+ : state === 'live'
? hasProgress
? t('message.systemCard.autoResume.pendingWithProgress', {
attempt: info.attempt,
diff --git a/apps/mobile/src/session/autoResumePresentation.ts b/apps/mobile/src/session/autoResumePresentation.ts
index 3154fa0b1a..cbb9fa08c6 100644
--- a/apps/mobile/src/session/autoResumePresentation.ts
+++ b/apps/mobile/src/session/autoResumePresentation.ts
@@ -1,6 +1,11 @@
import type { ContinuationInFlightProjectionCapability } from '@/session/types';
+/** 对齐桌面 USAGE_LIMIT_RESET_AUTO_RESUME_REASON(apps/desktop/src/shared/agentInputQueue.ts)。 */
+const USAGE_LIMIT_RESET_REASON = 'usage-limit-reset';
+
export interface MobileAutoResumeInfo {
+ /** 账号用量上限重置后自动继续(不是重连:不展示重试次数)。 */
+ usageLimitReset?: boolean;
error?: string;
attempt?: number;
maxAttempts?: number;
@@ -21,10 +26,12 @@ export interface MobileAutoResumePresentation {
export function readMobileAutoResumeInfo(data?: Record<string, unknown>): MobileAutoResumeInfo {
const number = (value: unknown) =>
typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
- const attempt = number(data?.attempt);
- const maxAttempts = number(data?.maxAttempts);
- const sessionTotal = number(data?.sessionTotal);
+ const usageLimitReset = data?.reason === USAGE_LIMIT_RESET_REASON;
+ const attempt = usageLimitReset ? undefined : number(data?.attempt);
+ const maxAttempts = usageLimitReset ? undefined : number(data?.maxAttempts);
+ const sessionTotal = usageLimitReset ? undefined : number(data?.sessionTotal);
return {
+ ...(usageLimitReset ? { usageLimitReset: true } : {}),
...(typeof data?.error === 'string' && data.error.trim() ? { error: data.error } : {}),
...(attempt !== undefined ? { attempt } : {}),
...(maxAttempts !== undefined ? { maxAttempts } : {}),
@@ -58,6 +65,7 @@ export function getMobileAutoResumePresentation(
const info = readMobileAutoResumeInfo(data);
const hasProgress = info.attempt !== undefined && info.maxAttempts !== undefined;
const hasInterruptionContext =
+ info.usageLimitReset === true ||
data?.live === true ||
info.error !== undefined ||
hasProgress ||
diff --git a/apps/mobile/src/session/inputProjection.ts b/apps/mobile/src/session/inputProjection.ts
index 7f8eaed5c8..fcd569b844 100644
--- a/apps/mobile/src/session/inputProjection.ts
+++ b/apps/mobile/src/session/inputProjection.ts
@@ -105,9 +105,17 @@ export function normalizeInputProjection(value: unknown, fallbackSessionId = '')
continuationTurnClientId: readString(record?.continuationTurnClientId),
continuationInFlightProjectionCapability,
credentialSwitchWait: readCredentialSwitchWait(record?.credentialSwitchWait),
+ usageLimitWait: readUsageLimitWait(record?.usageLimitWait),
};
}
+function readUsageLimitWait(value: unknown): InputProjection['usageLimitWait'] {
+ const resumeAt = readRecord(value)?.resumeAt;
+ return typeof resumeAt === 'number' && Number.isFinite(resumeAt) && resumeAt > 0
+ ? { resumeAt }
+ : null;
+}
+
/** 宽松解析凭证切换等待态:非对象/blockedBySessionIds 缺失或为空一律视作无等待。 */
function readCredentialSwitchWait(
value: unknown,
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index bd2dba7f81..50dbd0ba87 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -290,6 +290,11 @@ export interface InputProjection {
* 却无任何解释(2026-07 排查发现)。
*/
credentialSwitchWait: { clientId?: string; blockedBySessionIds: string[] } | null;
+ /**
+ * 账号限额等待(对齐桌面 AgentInputProjection.usageLimitWait):错误照常显示,到 `resumeAt`
+ * 无人处理时桌面端自动继续。老被控端缺省 = 无等待。
+ */
+ usageLimitWait?: { resumeAt: number } | null;
}
export interface PendingInteraction {
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index f6b0f83f1f..4a69ec50f3 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -22,7 +22,7 @@
| `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 17 | 7 | 45 |
| `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 3 |
| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 252 | 38 | 337 |
-| `desktop.chat.scheduled` | desktop | 调度任务列表 | hash `/cc-agent/scheduled`(SchedulerPage) | SchedulerPage | apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx, apps/desktop/src/renderer/features/scheduler/components/AgentMark.tsx, apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx, apps/desktop/src/renderer/features/scheduler/components/ProjectAutomationNotifyBridge.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleSessionIndexOwner.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleStatusChip.tsx, apps/desktop/src/renderer/features/scheduler/components/ScriptCapabilityMultiSelect.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListFilterPopover.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateCard.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateGallery.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateParamForm.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts, apps/desktop/src/renderer/features/scheduler/hooks/useTemplates.ts, apps/desktop/src/renderer/features/scheduler/index.ts, apps/desktop/src/renderer/features/scheduler/lib/cronCodexPreset.ts, apps/desktop/src/renderer/features/scheduler/lib/cronToHuman.ts, apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts, apps/desktop/src/renderer/features/scheduler/lib/formatters.ts, apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts, apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts, apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/runHistoryGrouping.ts, apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSessionBinding.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts, apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilter.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilterStorage.ts, apps/desktop/src/renderer/features/scheduler/lib/templateLocalization.ts, apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts | 34 | 0 | 90 |
+| `desktop.chat.scheduled` | desktop | 调度任务列表 | hash `/cc-agent/scheduled`(SchedulerPage) | SchedulerPage | apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx, apps/desktop/src/renderer/features/scheduler/components/AgentMark.tsx, apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx, apps/desktop/src/renderer/features/scheduler/components/ProjectAutomationNotifyBridge.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleSessionIndexOwner.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleStatusChip.tsx, apps/desktop/src/renderer/features/scheduler/components/ScriptCapabilityMultiSelect.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListFilterPopover.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateCard.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateGallery.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateParamForm.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts, apps/desktop/src/renderer/features/scheduler/hooks/useTemplates.ts, apps/desktop/src/renderer/features/scheduler/index.ts, apps/desktop/src/renderer/features/scheduler/lib/cronCodexPreset.ts, apps/desktop/src/renderer/features/scheduler/lib/cronToHuman.ts, apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts, apps/desktop/src/renderer/features/scheduler/lib/formatters.ts, apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts, apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts, apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/runHistoryGrouping.ts, apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSessionBinding.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts, apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilter.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilterStorage.ts, apps/desktop/src/renderer/features/scheduler/lib/templateLocalization.ts | 34 | 0 | 90 |
| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 252 | 38 | 336 |
| `desktop.dev.maker-experimental` | desktop | Maker 实验诊断页 | hash `/maker-experimental`(MakerExperimentalView;EXPERIMENTAL_FEATURES 现为空,仍是生产路由) | MakerExperimentalView | apps/desktop/src/renderer/features/maker-experimental/MakerExperimentalView.tsx | 9 | 0 | 7 |
| `desktop.issues.guide` | desktop | Issue 引导页 | hash `/issues`(IssueTrackerFeatureLayout,已迁 GitHub 后的引导页) | IssueTrackerFeatureLayout | apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx, apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx, apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts, apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts, apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts | 0 | 0 | 7 |
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 9f2614bc5d..eb31d3b937 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,17 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## 账号用量上限的自动继续
+
+输入投影 `AgentInputProjection` 新增可选字段 `usageLimitWait: { resumeAt } | null`,与 `error`
+同时出现,表示被控端会在 `resumeAt` 自动继续该任务;旧被控端缺省,控制端按无等待处理。
+新增 invoke `maker:input:cancel-usage-limit-wait(sessionId, opts?)`(Desktop preload、Mobile
+transport 与 device-link 的 core / review-input / mobile allowlist 均已登记),只撤等待、保留错误
+与 typed recovery,返回最新投影;控制端只在投影带等待时显示取消入口,因此不会对旧被控端发起
+该调用。自动继续复用既有 `CONTINUE_AFTER_ERROR_PROMPT` 与 `agentMeta.autoResume`,
+`autoResumeInfo.reason` 新值 `usage-limit-reset`,旧客户端按普通自动续跑行显示。
+Claude Code 终态 error 事件可带 `usageResetAt`(unix ms)。服务端无需改动。
+
## Agent 跨设备历史发现与搜索
`cindy_helper` 的 `list_history_devices` 使用现有同账号设备目录;`list_sessions` 和
diff --git a/docs/product-rules/session-runtime-control.md b/docs/product-rules/session-runtime-control.md
index 96e95c406d..d6ead21e58 100644
--- a/docs/product-rules/session-runtime-control.md
+++ b/docs/product-rules/session-runtime-control.md
@@ -47,6 +47,9 @@ Cindy 允许 Agent 通过统一会话控制面查询和临时调整当前任务
2. 切换到同一模型的其他已连接、未停用来源。
3. 若仍失败,只尝试目录通过 `newSessionDefault` 为当前 Harness 明确声明的模型。
+账号 5 小时 / 周用量上限不在此白名单内:那类失败等额度重置后自动继续,见
+[usage-limit-auto-continue.md](usage-limit-auto-continue.md)。
+
自动降级不采用“可用列表第一个”之类的隐式兜底,不跨 Harness;每个任务最多换路两次,
记录已访问的 `(来源, 模型)`,禁止 `A → B → A` 回环。用户修改运行时选择后立即清空本轮降级轨迹。
diff --git a/docs/product-rules/usage-limit-auto-continue.md b/docs/product-rules/usage-limit-auto-continue.md
new file mode 100644
index 0000000000..8b54ddd4a4
--- /dev/null
+++ b/docs/product-rules/usage-limit-auto-continue.md
@@ -0,0 +1,51 @@
+# 账号用量上限:等重置后自动继续
+
+2026-10-07 裁决。订阅账号撞上 5 小时 / 周用量上限时,任务不该需要用户守着手动续跑。
+
+## 行为
+
+- **普通任务**:照常报错暂停,用户可以随时自己处理(重试、换模型或来源、发新消息、收下错误)。
+ 同时默认等待额度重置:错误横幅显示「将于 X 自动继续 · 取消」,到点时用户仍未处理就自动继续
+ 这个任务。有产出的 turn 发续跑指令,零产出的 turn 重发原文,与人工「重试」同一条路径。
+- **目标模式**:沿用 `usageLimited` 状态到点自动续跑(见 `goal-host`),与普通任务共用同一套
+ 「按会话所用账号求重置时刻」的逻辑,两者不会重复续跑。
+- 自动继续按自动动作呈现:隐藏续跑指令气泡,消息流里显示「用量已恢复,已自动继续」活动行,
+ 不计为用户发送。
+
+## 重置时刻从哪来
+
+按顺序取第一个可用的:
+
+1. 限额错误自带的结构化时刻(Claude 订阅:SDK `rate_limit_event`)。
+2. 报错原文里写明的时刻(ChatGPT 订阅 `resets_at` / `try again at 3:05 PM` / Pi 的
+ `Try again in ~N min`,Claude 的 `resets 1:20am (TZ)`)。
+3. 会话所用订阅账号的用量快照,且快照显示已用满(ChatGPT / Claude / SuperGrok;订阅家族由
+ provider 的 `auth.native` 决定,与跑在哪个 Harness 上无关)。
+
+前两步也只对订阅账号生效:Coding Plan、Copilot、API key、Cindy 网关个人额度等即使报错原文带了
+重试时刻也不等(那多半是按分钟的请求速率限制),**不等待、也不定时试探**,只报错交给用户。
+
+快照只看会话模型实际受限的那一格:Codex 按模型取对应的用量桶(如 Spark 单独计),Claude 订阅
+除 5 小时 / 周窗口外只计该模型的分模型窗口,其它模型用满不影响本会话。SSH 远程会话不读本机快照(目标模式同样只用远端报错里的时刻),且不采用远端报错里不带时区的钟点
+(如 Codex `try again at 3:05 PM` 用的是远端主机本地时间);相对时长与带时区的时刻照常。
+快照不可靠时同样不等:用满的窗口没有重置时刻(不拿别的窗口的时刻顶替)、窗口已过重置点(快照
+在翻篇前取的)、SuperGrok 缓存快照超过有效期。目标模式同样只对订阅账号采信报错原文里的时刻,快照也须显示已用满才采纳其时刻。只认具体窗口显示用满,不认快照级「已触顶」标记(说不清来源,且混有需要充值的余额耗尽)。
+
+## 边界
+
+- 普通任务的等待只在本次运行内有效,不落盘;应用或电脑重启后停在报错,由用户手动继续。
+ 目标模式例外:沿用既有的 `usageLimited` 持久状态,重启后按保存的重置时刻继续排期。
+- 普通任务里用户动手换模型或来源即视为接手,开始切换时就撤销等待(新选择可能有额度;切换失败时错误
+ 与手动重试仍在,不恢复等待)。目标模式的
+ `usageLimited` 排期沿用既有行为,由目标自身的暂停 / 恢复控制,不在本规则内。
+- 重置后再等约 1 分钟并错开几十秒,避免同账号多个任务同时涌入。
+- 同一任务两次实质产出之间最多自动继续 3 次,防止重置时刻算早时反复撞上限。
+- 不覆盖:Schedule 运行与复用其来源的 Slack / X / Telegram Hook 消息(失败时本就不留重试入口,由各自 runner 收尾)、Orca worker(失败已交给 Lead)、伙伴会话(走候选链)、
+ 目标模式在管的任务、执行已暂停的任务、共享任务访客发起或插话的回合(授权可能在等待期间被撤销,
+ 由房主手动处理)。
+- **共享中的任务撞上限额不自动等待**(Dash 2026-10-08):普通任务与目标模式都一样——报错照常,
+ 不排自动继续 / 自动恢复,由房主手动处理;等待期间开始共享的,到点也不自动继续。判断的是此刻
+ 任务是否处于共享中,访客可能已影响过本任务,撤权后到点替其续跑不安全。目标模式过载的短窗口
+ 重试不受影响。
+- 自动继续在真正发给模型前被丢弃(任务关闭、准备失败等)时,恢复原错误与手动重试入口,不再自动等待。
+- 等待由被控电脑持有;手机与另一台电脑只显示等待并可取消。
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index b8a3242e90..8bbc372f2e 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -183,6 +183,7 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
'maker:input:resume',
'maker:input:retry-last-error',
'maker:input:clear-error',
+ 'maker:input:cancel-usage-limit-wait',
'maker:input:remove',
'maker:input:update-text',
// 整条内容替换(文本+附件),手机端排队消息复用 composer 编辑;老被控端无 handler →
@@ -622,6 +623,7 @@ export const REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS: ReadonlySet<string> = new Se
'maker:input:resume',
'maker:input:retry-last-error',
'maker:input:clear-error',
+ 'maker:input:cancel-usage-limit-wait',
'maker:input:remove',
'maker:input:update-text',
'maker:input:update-content',
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index b85a1bd52e..ea4f4a0ed2 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -394,6 +394,7 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [
'maker:input:resume',
'maker:input:retry-last-error',
'maker:input:clear-error',
+ 'maker:input:cancel-usage-limit-wait',
'maker:input:remove',
'maker:input:update-text',
'maker:input:update-content',