Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): 保留限额重试并在重启后按准确时间续跑
Dash09f664d189db
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex 8d7a927851..6ed0f3e0bd 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -3031,6 +3031,8 @@ describe('remote subscription data reads', () => {ok: true, result: { providerId: 'account-2', fiveHour: { utilization: 12 } },});expect(reader).toHaveBeenCalledWith('account-2');+ await runInvoke('ctrl', { channel, args: ['account-2', true] });+ expect(reader).toHaveBeenLastCalledWith('account-2', { fresh: true });expect(ipcHandler).not.toHaveBeenCalled();reader.mockClear();await expect(runInvoke('ctrl', { channel, args: [42] })).resolves.toMatchObject({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('[INVALID_PARAMS]') } });diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 0fe0c2eacb..3fb364efa2 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -767,6 +767,10 @@ import {allowBotWorkbenchPendingPermission,applyCodexSpawnConfigChangeWithRestart,clearDeferredCodexRestartForOwnerBoundary,+ restoreUsageLimitWaits,+ suspendUsageLimitWaits,+ flushUsageLimitWaits,+ reconcileScheduledUsageLimitWaits,scheduleDeferredCodexRestart,clearWorkingDirectoryRecoveryForOwnerBoundary,collectAgentInputQueueScanTexts,@@ -1286,6 +1290,8 @@ async function attemptStartSchedulerOnce(): Promise<void> {}const automationGitBaselineHooks = createAutomationUserTurnGitBaselineHooks();try {+ await restoreUsageLimitWaits();+ if (getGoalTeardownGeneration() !== goalGenBefore) return;const scheduler = await startScheduler({maker,getDb: () => getDbClient().drizzle,@@ -1311,6 +1317,10 @@ async function attemptStartSchedulerOnce(): Promise<void> {// 内通过 registerScheduleHandlers() 提前挂好,handler 内部 awaitReady 等本行// setSchedulerReady 调用。if (!_scheduleIpcRegistered.has(scheduler)) {+ scheduler.on('changed', event => {+ void reconcileScheduledUsageLimitWaits(event.scheduleId).catch(error =>+ console.warn('[usage-limit] schedule reconciliation failed', error));+ });attachSchedulerEventListeners(scheduler, getScheduleStorage());registerProjectAutomationIpc(getProjectAutomationLoader());_scheduleIpcRegistered.add(scheduler);@@ -1913,7 +1923,9 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {// 等 relogin 后的 setSchedulerReady 喂入**新实例**(与 worker bug #1 的 relogin// 路径同构,这里关掉 teardown 路径的对偶窗口)。// 不 reject _pending — 让在途请求继续等下次 setSchedulerReady,30s 超时兜底。+ suspendUsageLimitWaits();resetSchedulerReady();+ await flushUsageLimitWaits();agentIslandService = getAgentIslandService();agentIslandService?.resetRuntimeState();// ② 再停旧 scheduler。scheduler 持有旧 user 的 storage drizzle 引用,必须在@@ -9933,10 +9945,12 @@ onQuit(onQuit('session-active-turn-freeze',() => {+ suspendUsageLimitWaits();freezeSessionActiveTurnMarkers();},'sync',);+onQuit('usage-limit-waits-flush', flushUsageLimitWaits, 'async');onQuit('reap-claude-children',() => {diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex d64fc037c2..21de9804af 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -496,7 +496,7 @@ export function setRemoteTurnChangeAction(handler: RemoteTurnChangeAction): void* 模块图保持纯净(usage 面会拖进 runtime-configs 等 app 依赖,纯 dispatch 单测只* mock 极小 Electron 面)。*/-type RemoteSubscriptionUsageReader = (providerId?: string) => Promise<unknown | null>;+type RemoteSubscriptionUsageReader = (providerId?: string, options?: { fresh?: boolean }) => Promise<unknown | null>;let remoteXaiSubscriptionUsageReader: RemoteSubscriptionUsageReader | null = null;let remoteClaudeSubscriptionUsageReader: RemoteSubscriptionUsageReader | null = null;export function setRemoteClaudeSubscriptionUsageReader(reader: RemoteSubscriptionUsageReader | null): void {@@ -4661,7 +4661,9 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefinreturn { ok: false, error: { code: 'IPC_ERROR', message: 'subscription usage reader not ready' } };}try {- const snapshot = await reader(providerId as string | undefined);+ const snapshot = (payload.args ?? [])[1] === true+ ? await reader(providerId as string | undefined, { fresh: true })+ : await reader(providerId as string | undefined);const result = snapshot && providerId ? { ...snapshot as object, providerId } : snapshot;return { ok: true, result };} catch (err) {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.tsindex 8a1b8f161c..0ff0332147 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@@ -14241,7 +14241,63 @@ describe('AgentInputCoordinator 中断自动续跑', () => {});describe('usage-limit wait (ordinary tasks)', () => {+ it('restores a scheduled quota failure after restart without replaying the dead run context', async () => {+ const original = createHarness(); const sid = 'restarted-quota';+ original.coordinator.enqueue(sid, makeItem('input', 'work', {+ origin: { kind: 'scheduler', scheduleId: 'sch', scheduleName: 'Check', runId: 'old-run' },+ }));+ await flush(); original.setRunning(false);+ original.coordinator.onTurnEvent(sid, 'error', 'weekly limit', LIMIT_SIGNALS);+ const token = original.onUsageLimitedTurnError.mock.calls.at(-1)?.[3] as number;+ const snapshot = original.coordinator.snapshotUsageLimitRecovery(sid, token)!;+ const restarted = createHarness();+ restarted.setHasAssistantProgressAfter(async () => true);+ const restored = restarted.coordinator.restoreUsageLimitRecovery(sid, snapshot, restarted.coordinator.getGeneration(sid))!;+ expect(restarted.coordinator.getProjection(sid).error).toBe('weekly limit');+ expect(restarted.coordinator.armUsageLimitWait(sid, restored, 9_000_000)).toBe(true);+ await restarted.coordinator.continueAfterUsageLimitReset(sid, restored, INFO); await flush();+ expect(restarted.sendToAgent).toHaveBeenCalledOnce();+ expect(restarted.sendToAgent.mock.calls[0][1]).toMatchObject({ content: CONTINUE_AFTER_ERROR_PROMPT });+ expect(restarted.sendToAgent.mock.calls[0][3].origin).toBeUndefined();+ expect(await restarted.coordinator.continueAfterUsageLimitReset(sid, restored, INFO)).toBe('superseded');+ });++ it('does not restore across clear, and unloads runtime waiting for a later owner activation', async () => {+ const h = createHarness(); const sid = 'unloaded-quota';+ const snapshot = { kind: 'active-turn' as const, item: makeItem('input', 'work'), error: 'weekly limit' };+ const generation = h.coordinator.getGeneration(sid);+ h.coordinator.clearSession(sid);+ expect(h.coordinator.restoreUsageLimitRecovery(sid, snapshot, generation)).toBeNull();+ const token = h.coordinator.restoreUsageLimitRecovery(sid, snapshot, h.coordinator.getGeneration(sid))!;+ h.coordinator.unloadUsageLimitRecovery(sid, token);+ expect(h.coordinator.getProjection(sid).recovery).toBeNull();+ expect(h.coordinator.restoreUsageLimitRecovery(sid, snapshot, h.coordinator.getGeneration(sid))).not.toBeNull();+ });+const LIMIT_SIGNALS = { sdkError: 'rate_limit', usageResetAt: 5_000_000 };+ // Regression: scheduled quota failures used to discard recovery before the+ // reset-time resolver could run. A real run keeps Retry and the same origin.+ it.each([true, false])('keeps scheduled quota recovery and resumes once; progress=%s', async (progress) => {+ const h = createHarness();+ const sid = 'scheduled-quota';+ const origin = { kind: 'scheduler', scheduleId: 'sch-1', scheduleName: 'Check', runId: 'run-1' } as const;+ h.setHasAssistantProgressAfter(async () => progress);+ h.coordinator.enqueue(sid, makeItem('quota-original', 'original work', { origin }));+ await flush();+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'error', 'weekly limit', LIMIT_SIGNALS);+ const token = h.onUsageLimitedTurnError.mock.calls.at(-1)?.[3] as number;+ expect(h.coordinator.getProjection(sid).recovery?.kind).toBe('active-turn');+ expect(h.coordinator.armUsageLimitWait(sid, token, 9_000_000)).toBe(true);+ h.coordinator.onTurnEvent(sid, 'done');+ expect(h.coordinator.getProjection(sid).usageLimitWait).toEqual({ resumeAt: 9_000_000 });+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, token, INFO)).toBe('resumed');+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, token, INFO)).toBe('superseded');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1][1]).toMatchObject({ content: progress ? CONTINUE_AFTER_ERROR_PROMPT : 'original work' });+ expect(h.sendToAgent.mock.calls[1][3].origin).toEqual(origin);+ });const INFO = {reason: USAGE_LIMIT_RESET_AUTO_RESUME_REASON,attempt: 1,@@ -14249,6 +14305,91 @@ describe('usage-limit wait (ordinary tasks)', () => {sessionTotal: 0,};+ it('keeps scheduled quota recovery when the terminal arrives before persistence completes', async () => {+ const h = createHarness();+ const sid = 'scheduled-quota-persisting';+ const origin = { kind: 'scheduler', scheduleId: 'sch', scheduleName: 'Check', runId: 'run' } as const;+ const persisted = deferred<Record<string, never>>();+ mocks.createMessage.mockImplementationOnce(() => persisted.promise);+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {+ await persistQueuedUserMessage(sessionId, sendOpts);+ return sendSuccess();+ });+ h.coordinator.enqueue(sid, makeItem('original', 'work', { origin }));+ await flush();+ h.coordinator.onTurnEvent(sid, 'error', 'weekly limit', LIMIT_SIGNALS);+ persisted.resolve({});+ await flush();+ expect(h.coordinator.getProjection(sid).recovery?.kind).toBe('active-turn');+ expect(h.onUsageLimitedTurnError).toHaveBeenCalledOnce();+ });++ it.each(['manual', 'cancel'] as const)('hands scheduled quota recovery to the user on %s', async (action) => {+ const h = createHarness();+ const sid = 'scheduled-quota-takeover';+ h.setHasAssistantProgressAfter(async () => false);+ h.coordinator.enqueue(sid, makeItem('original', 'work', {+ origin: { kind: 'scheduler', scheduleId: 'sch', scheduleName: 'Check', runId: 'run' },+ }));+ await flush();+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'error', 'weekly limit', LIMIT_SIGNALS);+ const token = h.onUsageLimitedTurnError.mock.calls.at(-1)?.[3] as number;+ h.coordinator.armUsageLimitWait(sid, token, 9_000_000);+ if (action === 'cancel') {+ h.coordinator.releaseScheduledUsageLimitRecovery(sid, 'run');+ expect(h.coordinator.getProjection(sid).error).toBe('weekly limit');+ expect(h.coordinator.getProjection(sid).recovery?.kind).toBe('active-turn');+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, token, INFO)).toBe('superseded');+ }+ await h.coordinator.retryLastError(sid);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1][3].origin).toBeUndefined();+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, token, INFO)).toBe('superseded');+ });++ it('preserves a quota wait across provider cleanup but cancels it on explicit task close', async () => {+ const sid = 'quota-runtime-close';+ const { h, candidate } = await failWithLimit(sid, false);+ expect(h.coordinator.hasUsageLimitRecovery(sid, candidate)).toBe(true);+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });+ expect(h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000)).toBe(true);+ h.coordinator.onSessionClosed(sid);+ expect(h.coordinator.hasUsageLimitRecovery(sid)).toBe(false);+ expect(await h.coordinator.continueAfterUsageLimitReset(sid, candidate, INFO)).toBe('superseded');+ expect(h.coordinator.getProjection(sid).recovery?.kind).toBe('active-turn');+ });++ it('cancels a scheduled quota continuation during preparation and retains manual retry', async () => {+ const h = createHarness();+ const sid = 'quota-cancel-preparing';+ h.setHasAssistantProgressAfter(async () => false);+ h.coordinator.enqueue(sid, makeItem('original', 'work', {+ origin: { kind: 'scheduler', scheduleId: 'sch', scheduleName: 'Check', runId: 'run' },+ }));+ await flush();+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'error', 'weekly limit', LIMIT_SIGNALS);+ const token = h.onUsageLimitedTurnError.mock.calls.at(-1)?.[3] as number;+ h.coordinator.armUsageLimitWait(sid, token, 9_000_000);+ const preparation = deferred<{ action: 'allow' }>();+ h.setScreenUserMessage(() => preparation.promise);+ await h.coordinator.continueAfterUsageLimitReset(sid, token, INFO);+ await flush();+ const clientId = h.onUiRetry.mock.calls.at(-1)?.[1] as string;+ h.coordinator.releaseScheduledUsageLimitRecovery(sid, 'other-run', clientId);+ h.coordinator.releaseScheduledUsageLimitRecovery(sid, 'run', clientId);+ preparation.resolve({ action: 'allow' });+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledOnce();+ expect(h.coordinator.getProjection(sid).error).toBe('weekly limit');+ expect(h.coordinator.getProjection(sid).recovery?.kind).toBe('active-turn');+ await h.coordinator.retryLastError(sid);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ });+// Unit regression (#6611): direct send rejections missed the transaction's bootstrap// wrappers. Drive the real transaction + coordinator for lazy creation and rehydrate;// a verified quota error must keep its reset metadata and original queued input.diff --git a/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.tsindex 51b54f3d8a..af8dba61d5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/usageLimitAutoResume.test.ts@@ -73,6 +73,66 @@ describe('isAccountUsageLimitError', () => {});describe('UsageLimitAutoResume', () => {+ it('restores the saved deadline and attempt budget; overdue startup waits buffer once', async () => {+ const h = harness();+ expect(h.guard.restore('restarted', 42, RESET_AT, 2)).toBe(true);+ expect(h.timers.at(-1)?.delayMs).toBe(RESET_AT - NOW);+ await h.fireLast();+ expect(h.deps.continueSession).toHaveBeenCalledWith('restarted', 42, expect.objectContaining({ attempt: 3 }));+ expect(h.guard.restore('overdue', 43, NOW - 1, 0)).toBe(true);+ expect(h.timers.at(-1)?.delayMs).toBe(USAGE_LIMIT_RESUME_BUFFER_MS);+ h.guard.suspend();+ expect(h.timers.at(-1)?.cleared).toBe(true);+ expect(h.guard.restore('capped', 44, RESET_AT, 3)).toBe(false);+ });++ it('does not arm a timer when persistence fails or cancellation wins the save', async () => {+ const failed = harness({ saveWait: async () => { throw new Error('disk full'); } });+ await failed.guard.onTurnError('s1', LIMIT);+ expect(failed.timers).toHaveLength(0);+ expect(failed.deps.cancel).toHaveBeenCalledWith('s1', 1);+ let release!: (saved: boolean) => void;+ const h = harness({ saveWait: () => new Promise(resolve => { release = resolve; }) });+ const scheduling = h.guard.onTurnError('s1', LIMIT);+ await h.flush();+ h.current.clear(); h.guard.noteUserAction('s1'); release(true);+ await scheduling;+ expect(h.timers).toHaveLength(0);+ });++ it('waits for scheduler capacity without consuming quota retries or spinning on restored quota', async () => {+ let available = false;+ const h = harness({ continueSession: vi.fn(async () => available ? 'resumed' : 'capacity-wait') });+ h.guard.onTurnError('scheduled', LIMIT);+ await h.flush();+ await h.guard.resumeRestored(async () => true);+ expect(h.deps.continueSession).toHaveBeenCalledOnce();+ expect(h.timers.at(-1)?.delayMs).toBe(USAGE_LIMIT_RESUME_BUFFER_MS);+ for (let index = 0; index < USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES; index++) await h.fireLast();+ available = true;+ await h.fireLast();+ expect(h.deps.continueSession).toHaveBeenLastCalledWith('scheduled', 1, expect.objectContaining({ attempt: 1 }));+ expect(h.deps.cancel).not.toHaveBeenCalled();+ });++ it('reports unarmed waits so their scheduler run can settle', async () => {+ const h = harness({ resolveResetAt: async () => null });+ await expect(UsageLimitAutoResume.prototype.onTurnError.call(h.guard, 'scheduled', LIMIT, 42)).resolves.toBe(false);+ expect(h.deps.cancel).toHaveBeenCalledWith('scheduled', 42);+ expect(h.timers).toHaveLength(0);+ });++ // Unit regression: a failed disk write while capacity is full must not leave a dead countdown.+ it('cancels the wait if persisting a capacity deferral fails', async () => {+ const saveWait = vi.fn(async () => true);+ const h = harness({ saveWait, continueSession: vi.fn(async () => 'capacity-wait' as const) });+ await h.guard.onTurnError('scheduled', LIMIT);+ saveWait.mockRejectedValueOnce(new Error('disk full'));+ await h.fireLast();+ expect(h.deps.cancel).toHaveBeenCalledWith('scheduled', 1);+ expect(h.timers).toHaveLength(1);+ expect(h.current.size).toBe(0);+ });// Unit regression: a pending group switch can still have the previous local route saved.// Resetting that local account must not wake the group's wait or consume its retry budget.it('keeps a group quota wait until its timer even when the old account resets', async () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/usageLimitRecoveryStore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/usageLimitRecoveryStore.test.tsnew file mode 100644index 0000000000..b0223a2c19--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/usageLimitRecoveryStore.test.ts@@ -0,0 +1,54 @@+// Standard tier: real atomic files, restart and competing consumers. No user profile is touched.+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { createUsageLimitRecoveryStore, type SavedUsageLimitWait } from '../usageLimitRecoveryStore.js';++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+function fixture() {+ const root = mkdtempSync(join(tmpdir(), 'cindy-usage-wait-')); dirs.push(root);+ let owner = 'a';+ const create = () => createUsageLimitRecoveryStore({+ filePath: () => join(root, `${owner}.json`), scopeKey: () => owner,+ log: { info() {}, warn() {} },+ });+ const record: SavedUsageLimitWait = {+ id: 'wait-1', sessionId: 'session-1', resumeAt: 9_000_000, attempts: 1, savedAt: 1_000,+ route: 'route', kind: 'active-turn', error: 'weekly limit',+ item: { clientId: 'input-1', text: 'work', persistedContent: 'work', model: 'model',+ effort: 'medium', permissionMode: 'default', workingDir: '/test',+ chatMessage: { role: 'user', content: 'work', clientId: 'input-1' },+ createOpts: { agentKind: 'claude-code', model: 'model', workingDir: '/test' } },+ };+ return { create, record, setOwner: (next: string) => { owner = next; } };+}++describe('durable quota waiting', () => {+ it('restores deadline/input after restart and only one instance can take it', async () => {+ const h = fixture();+ await h.create().save(h.record);+ const restarted = h.create();+ expect(restarted.readAll()).toEqual([h.record]);+ const results = await Promise.all([restarted.take('session-1', 'wait-1'), h.create().take('session-1', 'wait-1')]);+ expect(results.sort()).toEqual([false, true]);+ expect(h.create().readAll()).toEqual([]);+ });++ it('persists cancellation without deleting a newer wait or crossing accounts', async () => {+ const h = fixture(); const store = h.create();+ await store.save(h.record);+ await store.save({ ...h.record, id: 'wait-2' });+ // A stale save that waited for the file lock cannot overwrite the current generation.+ expect(await store.save(h.record, () => false)).toBe(false);+ expect(await store.take('session-1', 'wait-1')).toBe(false);+ h.setOwner('b');+ expect(store.readAll()).toEqual([]);+ expect(await store.take('session-1', 'wait-2')).toBe(false);+ h.setOwner('a');+ expect(store.readAll()[0].id).toBe('wait-2');+ expect(await store.take('session-1', 'wait-2')).toBe(true);+ expect(h.create().readAll()).toEqual([]);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex e89373a69d..adae734915 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -36,6 +36,8 @@ import { MCP_APP_MESSAGE_GUARD, isUnrestorableMcpAppMessage, queuedAppMessageGuaimport { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { isUnsupportedResponsesImageErrorPayload } from '@cindy/responses-chat-bridge';import { isPiImageInputUnsupportedError } from '../../shared/inputError.js';+import { isAccountUsageLimitError } from './usageLimitAutoResume.js';+import type { UsageLimitRecoverySnapshot } from './usageLimitRecoveryStore.js';import { createLogger } from '../logger.js';import { AUTO_REVIEW_DELEGATED_CONTINUATION, readAutoReviewUserText } from './autoReviewUserIntent.js';import { createMessage as createDbMessage } from '../localDb/ipc/messages.js';@@ -429,7 +431,7 @@ export interface AgentInputCoordinatorDeps {* 一条留下 active-turn recovery、且没有被自愈接管的 terminal error 已经呈现。host 据此* 判断是不是账号限额、解析重置时刻,确定后调 `armUsageLimitWait` 挂上等待计划* (见 maker-ipc/usageLimitAutoResume.ts)。fire-and-forget,不影响错误呈现。- * Schedule 输入与用户已接手的候选不会回调。+ * 带 runId 的 Schedule 限额失败也使用本入口;Hook 与用户已接手的候选不回调。*/onUsageLimitedTurnError?: (sessionId: string,@@ -775,6 +777,7 @@ interface SessionInputState {resumeAt: number | null;token: number;recovery: NonNullable<AgentInputRecovery>;+ accountLimit?: boolean;} | null;/*** 供应商组正在为这次错误换电脑(docs/product-rules/provider-groups.md §6.1):错误仍是当前状态,@@ -1147,7 +1150,7 @@ function isActiveTurnDispatched(active: ActiveTurn): boolean {* 这条消息是自动任务(scheduler)投进来的吗。** Scheduler prompt 属于某一轮 run。它可以复用自动续跑,但不能被当作真人介入或- * UI Continue;确定性错误也不能留下脱离 FireContext 的人工 Retry。+ * UI Continue;限额失败可保留 Retry,人工接手时必须脱离旧 FireContext。** 判据抽成函数是因为它必须覆盖**所有**终态路径:派发失败、turn 终态 error、* 派发前会话关闭。前两轮只改了派发失败那一条,漏掉的两条照样造出重试入口@@ -1157,6 +1160,16 @@ function isSchedulerOriginItem(item: AgentInputQueuedMessage | null | undefined)return item?.origin?.kind === 'scheduler';}+/** Hooks reuse scheduler origin but have no live schedule run to resume. */+function isScheduledQuotaRecovery(+ item: AgentInputQueuedMessage | null | undefined,+ message?: string,+ signals?: Omit<InterruptedTurnErrorSignals, 'message'>,+): boolean {+ return item?.origin?.kind === 'scheduler' && Boolean(item.origin.runId) &&+ isAccountUsageLimitError({ ...signals, message });+}+/** Scheduler / Orca / tool-sent session inputs are automation, not a fresh human intervention. */function isAutomaticOriginItem(item: AgentInputQueuedMessage | null | undefined): boolean {return isAutomaticInputOriginKind(item?.origin?.kind);@@ -1241,6 +1254,7 @@ export class AgentInputCoordinator {* emit 会因"未恢复"跳过持久化,旧快照删不掉,下次打开会话又诈尸。*/private readonly restoredQueueSessions = new Set<string>();+ private readonly restoredUsageLimitRecoveries = new WeakSet<object>();private readonly restoredQueueItems = new WeakSet<AgentInputQueuedMessage>();private readonly restoreAttempted = new Set<string>();private readonly queueRestorePromises = new Map<string, Promise<void>>();@@ -3378,6 +3392,9 @@ export class AgentInputCoordinator {attemptToken,});}+ // Manual retry is a user takeover. The old scheduler waiter settles as+ // failed; its FireContext must not be inherited by the user's new turn.+ if ((!automatic || this.restoredUsageLimitRecoveries.has(recovery)) && isSchedulerOriginItem(item)) item.origin = undefined;state.pendingQueue.unshift(item);this.prependPendingCompactWaitClientId(state, item.clientId);// 「用户显式重试」信号 —— **只在 active-turn recovery 上发**。这一支重试的是@@ -3951,8 +3968,9 @@ export class AgentInputCoordinator {state.stickyError = null;const schedulerItem = active.item && isSchedulerOriginItem(active.item);const resumableCandidate = this.isResumableTurnErrorCandidate(sessionId, message, signals, active.item);+ const scheduledQuota = isScheduledQuotaRecovery(active.item, message, signals);const outcome = this.setActiveTurnRecovery(state, active.item, {- allowSchedulerAutoResume: Boolean(schedulerItem && resumableCandidate),+ allowSchedulerAutoResume: Boolean(schedulerItem && resumableCandidate) || scheduledQuota,});if (outcome === 'dropped-scheduler') {state.error = message ?? state.error;@@ -3987,9 +4005,8 @@ export class AgentInputCoordinator {} else {state.error = message ?? state.error;setErrorProjectionSignals(state, signals);- // Schedule 的确定性错误或额度耗尽仍由 runner 收口,不留下脱离 run 记账的- // 人工 Retry。只有真正被普通自动续跑接管的窗口才保留 recovery。- if (schedulerItem) {+ // 限额失败保留 Retry 与等待;其它确定性错误仍交给 runner 收口。+ if (schedulerItem && !scheduledQuota) {state.recovery = null;this.markPendingExternalTerminalDone(sessionId, state);this.emit(sessionId);@@ -6460,8 +6477,8 @@ export class AgentInputCoordinator {* **唯一的 active-turn recovery 出口。**任何终态路径想留「重试上一轮」入口都必须经这里,* 不要再直接写 `state.recovery = { kind: 'active-turn', ... }`。*- * Schedule 的确定性失败仍不留人工 Retry(runner 已记账);只有候选瞬时错误允许- * 暂时保留 recovery,交给与普通聊天相同的自动续跑路径。+ * Schedule 的瞬时错误与账号限额可保留 recovery,复用普通聊天的恢复路径;+ * 其余失败由 runner 收口。** @returns `kept` = 留下了;`dropped-scheduler` = 因 scheduler 来源被摘掉,此时队列少了* 「用户点 clearError / Retry」这个唤醒源,调用方通常要补一次 scheduleDrain(Stop 那条@@ -6676,12 +6693,12 @@ export class AgentInputCoordinator {item: AgentInputQueuedMessage,beforeDispatch = false,): boolean {- // scheduler origin(含复用它的 Slack / X / Telegram Hook 消息)终态失败时本就不留- // recovery、由各自 runner 收尾,没有可续的入口。共享任务访客的回合也不自动续:+ // 真实 Schedule 由 runId 绑定 runner;复用 scheduler origin 的 Hook 仍由渠道收尾。+ // 共享任务访客的回合也不自动续:// 授权可能在等待期间被撤销,数小时后替访客重发原指令不安全,交给房主手动处理。return Boolean(this.deps.onUsageLimitedTurnError &&- !isSchedulerOriginItem(item) &&+ (!isSchedulerOriginItem(item) || Boolean(item.origin?.kind === 'scheduler' && item.origin.runId)) &&!item.sharedTaskAuthor &&(state.recovery?.kind === 'active-turn' || (beforeDispatch && state.recovery?.kind === 'queue-head')) &&state.error !== null,@@ -6697,7 +6714,10 @@ export class AgentInputCoordinator {const state = this.states.get(sessionId);if (!state || !this.willNotifyUsageLimitedTurnError(state, item, signals?.providerGroupUsageLimit !== undefined)) return;const token = ++this.usageLimitWaitSeq;- state.usageLimitWait = { resumeAt: null, token, recovery: state.recovery! };+ state.usageLimitWait = {+ resumeAt: null, token, recovery: state.recovery!,+ accountLimit: isAccountUsageLimitError({ ...signals, message }),+ };try {this.deps.onUsageLimitedTurnError!(sessionId, { ...(signals ?? {}), message }, item, token);} catch (err) {@@ -6719,6 +6739,9 @@ export class AgentInputCoordinator {signals?: Omit<InterruptedTurnErrorSignals, 'message'>,): void {state.providerGroupSwitchHold = null;+ // Scheduled quota waits belong to the runner; do not hide their error behind+ // a provider-group takeover that this scheduled path does not start.+ if (isSchedulerOriginItem(item)) return;const candidate = this.deps.providerGroupSwitchCandidate;if (!candidate || !this.willNotifyUsageLimitedTurnError(state, item)) return;let cause: AutoResumeAgentSwitchCause | null = null;@@ -6858,6 +6881,49 @@ export class AgentInputCoordinator {return state ? isUsageLimitWaitLive(state, token) : false;}+ /** Includes reset-time resolution: a provider self-close must not cancel the logical wait. */+ hasUsageLimitRecovery(sessionId: string, token?: number): boolean {+ const state = this.states.get(sessionId);+ return Boolean(state?.usageLimitWait?.accountLimit && isUsageLimitCandidateCurrent(state, token));+ }++ snapshotUsageLimitRecovery(sessionId: string, token: number): UsageLimitRecoverySnapshot | null {+ const state = this.states.get(sessionId);+ if (!state || !isUsageLimitCandidateCurrent(state, token) || !state.error || !state.recovery) return null;+ const recovery = state.recovery;+ const item = recovery.kind === 'active-turn' ? recovery.item+ : state.pendingQueue.find(item => item.clientId === recovery.clientId);+ return item && !item.sharedTaskAuthor+ ? { kind: state.recovery.kind, item: sanitizeQueuedMessageForPersistence(item), error: state.error } : null;+ }++ /** Rehydrate only an untouched task. The expired scheduler FireContext is never replayed. */+ restoreUsageLimitRecovery(sessionId: string, snapshot: UsageLimitRecoverySnapshot, generation: number): number | null {+ const state = this.getState(sessionId);+ if (state.generation !== generation || state.activeTurn || state.recovery || state.error || this.isExecutionPaused(sessionId) ||+ state.pendingQueue.some(item => item.clientId !== snapshot.item.clientId)) return null;+ const item = sanitizeQueuedMessageForPersistence(snapshot.item);+ if (snapshot.kind === 'queue-head') {+ if (!state.pendingQueue.some(queued => queued.clientId === item.clientId)) state.pendingQueue.unshift(item);+ state.recovery = { kind: 'queue-head', clientId: item.clientId };+ } else state.recovery = { kind: 'active-turn', item };+ state.error = snapshot.error;+ const token = ++this.usageLimitWaitSeq;+ state.usageLimitWait = { token, resumeAt: null, recovery: state.recovery, accountLimit: true };+ this.restoredUsageLimitRecoveries.add(state.recovery);+ this.emit(sessionId);+ return token;+ }++ unloadUsageLimitRecovery(sessionId: string, token: number): void {+ const state = this.states.get(sessionId);+ if (!state || !isUsageLimitCandidateCurrent(state, token)) return;+ state.usageLimitWait = null;+ state.recovery = null;+ state.error = null;+ this.emit(sessionId);+ }+/*** 撤销自动继续:只撤等待,错误与手动重试入口保留。用户取消时不带令牌;host 到点放弃时* 带令牌,只撤自己那一次,不误撤之后新挂上的等待。@@ -6866,11 +6932,34 @@ export class AgentInputCoordinator {const state = this.getState(sessionId);if (state.usageLimitWait && (token === undefined || state.usageLimitWait.token === token)) {state.usageLimitWait = null;+ if (state.recovery?.kind === 'active-turn' && this.restoredUsageLimitRecoveries.has(state.recovery)) {+ state.recovery = { ...state.recovery, item: { ...state.recovery.item, origin: undefined } };+ }this.emit(sessionId);}return this.getProjection(sessionId);}+ /** End a scheduled quota claim while preserving an ordinary manual Retry. */+ releaseScheduledUsageLimitRecovery(sessionId: string, runId: string, retryClientId?: string): void {+ const state = this.getState(sessionId);+ if (retryClientId) {+ const pending = this.pendingAutoResumeRecoveries.get(retryClientId);+ if (pending?.recovery.kind === 'active-turn' && pending.recovery.item.origin?.kind === 'scheduler' &&+ pending.recovery.item.origin.runId === runId) {+ this.restoreAutoResumeRecovery(sessionId, retryClientId, null);+ }+ }+ const recovery = state.recovery;+ if (recovery?.kind !== 'active-turn' || recovery.item.origin?.kind !== 'scheduler' ||+ recovery.item.origin.runId !== runId) return;+ this.cancelPreparedAutoResume(sessionId, state);+ if (state.recovery !== recovery) return;+ state.usageLimitWait = null;+ state.recovery = { ...recovery, item: { ...recovery.item, origin: undefined } };+ this.emit(sessionId);+ }+/*** 额度重置后自动继续:与人工「继续」同一条已验证路径(有产出发续跑指令、零产出重发原文),* 但按自动动作落库(隐藏气泡、显示「额度已恢复,已自动继续」活动行、不算用户发送)。@@ -7194,15 +7283,16 @@ export class AgentInputCoordinator {state.stickyError = null;if (terminalEvent.type === 'error') {// 第五条终态路径:终态 error 在持久化还在进行时到达 → 被暂存,落库完成后才在这里- // 结算。Schedule 只在候选瞬时错误上短暂保留 recovery,复用普通自动续跑;- // 确定性错误仍由 runner 收口,不留下脱离 run 记账的人工 Retry。+ // 结算。Schedule 的候选瞬时错误和账号限额保留 recovery,复用普通恢复路径;+ // 其它确定性错误仍由 runner 收口,不留下脱离 run 记账的人工 Retry。// 被按住的 error 最终没能接管(recovery 没留住 / host 拒绝接管)时,统一在本方法里// 通知 host 补落 error 行 —— 出口有三个(dropped-scheduler、非 kept、拒绝接管),// 集中在这里判比让 host 在每个 null 返回点各自记得补落更难漏(不变量 I2)。const deferredPersistSuppressed = terminalEvent.resumableCandidate === true;const schedulerItem = active.item && isSchedulerOriginItem(active.item);+ const scheduledQuota = isScheduledQuotaRecovery(active.item, terminalEvent.message, terminalEvent.signals);const outcome = this.setActiveTurnRecovery(state, active.item, {- allowSchedulerAutoResume: Boolean(schedulerItem && deferredPersistSuppressed),+ allowSchedulerAutoResume: Boolean(schedulerItem && deferredPersistSuppressed) || scheduledQuota,});if (outcome === 'dropped-scheduler') {state.error = terminalEvent.message ?? state.error;@@ -7254,7 +7344,7 @@ export class AgentInputCoordinator {owner: { generation: active.generation, clientId: active.item!.clientId },});}- if (schedulerItem) {+ if (schedulerItem && !scheduledQuota) {state.recovery = null;this.markPendingExternalTerminalDone(sessionId, state);this.emit(sessionId);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 785f39bcf5..ab73308d3f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -533,6 +533,7 @@ import {orcaWorkers,orcaWorkerCreationReservations,sessions,+ schedules,} from '../localDb/schema.js';import { nextBotModelRoute, normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';import { createBotModelRouteReconciler } from './botModelRouteReconciler.js';@@ -1095,10 +1096,14 @@ import { peekGoalInactiveNote } from '../goal-host/inactiveNote.js';import { readTurnUsageResetAt } from '../goal-host/usageLimit.js';import {readAccountUsageLimit,+ readRemoteAccountUsageLimit,+ claudeAccountUsageLimit,+ codexAccountUsageLimit,sessionUsesOtherMachineAccount,subscriptionFamilyOf,} from '../usage/accountUsageLimit.js';import { UsageLimitAutoResume } from './usageLimitAutoResume.js';+import { createUsageLimitRecoveryStore, type SavedUsageLimitWait } from './usageLimitRecoveryStore.js';import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';import { persistAndHydrateSessionProvider } from './sessionProviderBootstrap.js';import { registerMakerSessionSendHandler } from './sessionSendHandler.js';@@ -1568,7 +1573,7 @@ export function resolveSessionRuntimeRoute(}/**- * 会话所用账号的重置时刻:错误自带 → 报错原文 → 订阅用量快照(须显示已用满)。+ * 会话所用账号的重置时刻:结构化错误 → 实际账号的用量窗口 → 报错原文。* 只服务订阅账号:API key / Coding Plan / 网关等来源的普通 429 即使带 Retry-After,也不是* 周期额度耗尽,按产品规则只报错不等待。*/@@ -1583,21 +1588,131 @@ async function resolveSessionUsageResetAt(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;+ let family = subscriptionFamilyOf(agentKind, providerId);+ if (!family && row.agentDeviceId && !row.remoteHostId && providerId) {+ const views = await readDeviceProviderViews(remoteBackgroundInvoke, row.agentDeviceId);+ family = views.find(view => view.id === providerId)?.auth.native ?? null;+ }+ if (!family) return null;// SSH 远程会话 / 远程 Agent 的报错用那台机器的本地时间:不带时区的钟点不按本机时区理解。const otherMachineAccount = sessionUsesOtherMachineAccount(row);const fromError = readTurnUsageResetAt(signals, Date.now(), {localTimeZoneTrusted: !otherMachineAccount,});- if (fromError !== null) return fromError;- // SSH 远端主机 / 远程 Agent 所在电脑用自己的登录,本机快照属于另一个账号,不能拿来推算。- if (otherMachineAccount) return null;- const limit = await readAccountUsageLimit(agentKind, providerId, modelId);- return limit?.limited ? limit.resetAtMs : null;+ if (fromError !== null && signals.usageResetAt !== undefined) return fromError;+ // Ask the actual account for its dated windows before relying on a text-only clock.+ // SSH has no account-usage RPC; never substitute a local account there.+ try {+ const scope = activeOwnerScopeKey();+ const limit = row.remoteHostId ? null : row.agentDeviceId && providerId+ ? await readRemoteAccountUsageLimit({ deviceId: row.agentDeviceId, providerId, family, agentKind, modelId },+ (deviceId, channel, args) => remoteBackgroundInvoke(deviceId, channel, args, {+ preSend: () => { if (scope !== activeOwnerScopeKey()) throw new Error('Account changed'); },+ }))+ : family === 'claude'+ ? claudeAccountUsageLimit(await readClaudeSubscriptionUsageSnapshotForDeviceLink(providerId ?? undefined, { fresh: true }), modelId)+ : family === 'codex'+ ? codexAccountUsageLimit(await readCodexAccountUsageSnapshotWithWebRefresh(providerId ?? undefined, { fresh: true }), { agentKind, modelId })+ : await readAccountUsageLimit(agentKind, providerId, modelId);+ if (scope !== activeOwnerScopeKey()) return null;+ if (limit?.limited && limit.resetAtMs !== null) return limit.resetAtMs;+ } catch (error) {+ log.info('usage reset lookup unavailable; retaining provider error hint', { sessionId, error: String(error) });+ }+ return fromError;}-// 普通任务撞上账号限额:照常报错,同时等额度重置后自动继续(仅本次运行内有效)。+// 普通任务撞上账号限额:照常报错,保存等待并在额度重置后自动继续。// coordinator 是可变绑定,必须懒读。+const usageLimitRecoveryStore = createUsageLimitRecoveryStore({+ filePath: () => ownerScopedUserDataPath('usage-limit-waits.json'),+ scopeKey: activeOwnerScopeKey,+ log,+});+const savedUsageLimitWaits = new Map<string, { token: number; record: SavedUsageLimitWait }>();+let usageLimitRecoverySuspended = false;++function usageLimitSavedRoute(row: Awaited<ReturnType<typeof getSessionRowSnapshot>>): string {+ return JSON.stringify([row?.agentKind, row?.providerId, row?.model, row?.agentDeviceId, row?.remoteHostId]);+}++async function isSavedUsageLimitWaitValid(record: SavedUsageLimitWait): Promise<boolean> {+ const row = await getSessionRowSnapshot(record.sessionId);+ if (!row || row.status !== 'active' || (row.clearedAt ?? 0) >= record.savedAt ||+ (row.userSendAt ?? 0) > record.savedAt || usageLimitSavedRoute(row) !== record.route) return false;+ const origin = record.item.origin;+ if (origin?.kind === 'scheduler') {+ const [schedule] = await getDbClient().drizzle.select({ status: schedules.status })+ .from(schedules).where(eq(schedules.id, origin.scheduleId)).limit(1);+ if (!schedule || schedule.status !== 'active') return false;+ }+ return true;+}++function forgetSavedUsageLimitWait(sessionId: string): void {+ if (usageLimitRecoverySuspended) return;+ const pending = savedUsageLimitWaits.get(sessionId);+ if (!pending) return;+ savedUsageLimitWaits.delete(sessionId);+ void usageLimitRecoveryStore.take(sessionId, pending.record.id).catch(error =>+ log.warn('could not cancel saved usage-limit wait', { sessionId, error: String(error) }));+}++/** Called before scheduler/Maker teardown; shutdown is not a user's cancellation. */+export function suspendUsageLimitWaits(): void {+ usageLimitRecoverySuspended = true;+ usageLimitAutoResume.suspend();+ for (const [sessionId, pending] of savedUsageLimitWaits) agentInputCoordinatorHolder?.unloadUsageLimitRecovery(sessionId, pending.token);+ savedUsageLimitWaits.clear();+}++export async function flushUsageLimitWaits(): Promise<void> { await usageLimitRecoveryStore.flush(); }++export async function reconcileScheduledUsageLimitWaits(scheduleId: string): Promise<void> {+ const scope = activeOwnerScopeKey();+ for (const [sessionId, pending] of savedUsageLimitWaits) {+ if (pending.record.item.origin?.kind !== 'scheduler' || pending.record.item.origin.scheduleId !== scheduleId) continue;+ const valid = await isSavedUsageLimitWaitValid(pending.record);+ if (usageLimitRecoverySuspended || scope !== activeOwnerScopeKey()) return;+ if (!valid && savedUsageLimitWaits.get(sessionId) === pending) {+ agentInputCoordinatorHolder?.cancelUsageLimitWait(sessionId, pending.token);+ }+ }+}++async function restoreSavedUsageLimitWait(sessionId: string): Promise<void> {+ const coordinator = agentInputCoordinatorHolder;+ if (!coordinator || usageLimitRecoverySuspended || savedUsageLimitWaits.has(sessionId) ||+ (!app.isPackaged && process.env.XDT_SCHEDULER_PASSIVE === '1')) return;+ const record = usageLimitRecoveryStore.readAll().find(wait => wait.sessionId === sessionId);+ if (!record) return;+ const scope = activeOwnerScopeKey();+ const generation = coordinator.getGeneration(sessionId);+ const valid = await isSavedUsageLimitWaitValid(record) && await isUsageLimitAutoResumeEligible(sessionId);+ if (scope !== activeOwnerScopeKey() || usageLimitRecoverySuspended) return;+ if (!valid) { await usageLimitRecoveryStore.take(sessionId, record.id); return; }+ const pending = { token: 0, record };+ savedUsageLimitWaits.set(sessionId, pending);+ const token = coordinator.restoreUsageLimitRecovery(sessionId, record, generation);+ if (token === null) { forgetSavedUsageLimitWait(sessionId); return; }+ pending.token = token;+ if (!usageLimitAutoResume.restore(sessionId, token, record.resumeAt, record.attempts, record.groupQuota === true)) {+ coordinator.cancelUsageLimitWait(sessionId, token);+ }+}++/** Run after account/DB readiness, before scheduler ticks. Passive instances only display state. */+export async function restoreUsageLimitWaits(): Promise<void> {+ if (!agentInputCoordinatorHolder || (!app.isPackaged && process.env.XDT_SCHEDULER_PASSIVE === '1')) return;+ usageLimitRecoverySuspended = false;+ const scope = activeOwnerScopeKey();+ for (const record of usageLimitRecoveryStore.readAll()) {+ if (scope !== activeOwnerScopeKey() || usageLimitRecoverySuspended) return;+ await agentInputCoordinatorHolder.ensureQueueRestored(record.sessionId);+ await restoreSavedUsageLimitWait(record.sessionId);+ }+}+const usageLimitAutoResume = new UsageLimitAutoResume({now: () => Date.now(),random: () => Math.random(),@@ -1612,14 +1727,50 @@ const usageLimitAutoResume = new UsageLimitAutoResume({arm: (sessionId, token, resumeAt) =>agentInputCoordinatorHolder?.armUsageLimitWait(sessionId, token, resumeAt) ?? false,isCurrent: (sessionId, token) =>- agentInputCoordinatorHolder?.isUsageLimitWaitCurrent(sessionId, token) ?? false,+ !usageLimitRecoverySuspended && (agentInputCoordinatorHolder?.isUsageLimitWaitCurrent(sessionId, token) ?? false),+ saveWait: async (sessionId, token, resumeAt, attempts, groupQuota) => {+ const scope = activeOwnerScopeKey();+ const snapshot = agentInputCoordinatorHolder?.snapshotUsageLimitRecovery(sessionId, token);+ if (!snapshot || usageLimitRecoverySuspended) return false;+ const row = await getSessionRowSnapshot(sessionId);+ if (!row || scope !== activeOwnerScopeKey() || usageLimitRecoverySuspended ||+ !agentInputCoordinatorHolder?.isUsageLimitWaitCurrent(sessionId, token)) return false;+ const prior = savedUsageLimitWaits.get(sessionId);+ const record: SavedUsageLimitWait = { ...snapshot, sessionId, resumeAt, attempts, groupQuota,+ id: prior?.token === token ? prior.record.id : randomUUID(),+ savedAt: prior?.token === token ? prior.record.savedAt : Date.now(), route: usageLimitSavedRoute(row) };+ savedUsageLimitWaits.set(sessionId, { token, record });+ if (!await usageLimitRecoveryStore.save(record, () => scope === activeOwnerScopeKey() &&+ !usageLimitRecoverySuspended && agentInputCoordinatorHolder?.isUsageLimitWaitCurrent(sessionId, token) === true)) return false;+ if (scope !== activeOwnerScopeKey() || usageLimitRecoverySuspended) return false;+ if (!agentInputCoordinatorHolder?.isUsageLimitWaitCurrent(sessionId, token)) {+ await usageLimitRecoveryStore.take(sessionId, record.id);+ return false;+ }+ return true;+ },cancel: (sessionId, token) => {agentInputCoordinatorHolder?.cancelUsageLimitWait(sessionId, token);},- continueSession: async (sessionId, token, info) =>- agentInputCoordinatorHolder+ continueSession: async (sessionId, token, info) => {+ const scope = activeOwnerScopeKey();+ const saved = savedUsageLimitWaits.get(sessionId);+ if (saved?.token !== token || !await isSavedUsageLimitWaitValid(saved.record) ||+ scope !== activeOwnerScopeKey() || usageLimitRecoverySuspended) return 'superseded';+ const pending = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (pending?.usageLimitToken === token) {+ const listeners = schedulerAutoResumeFailureListeners.get(schedulerAutoResumeRunKey(sessionId, pending.runId));+ for (const listener of listeners ?? []) {+ if (listener.quotaWait?.resume() === false) return 'capacity-wait';+ }+ }+ if (!await usageLimitRecoveryStore.take(sessionId, saved.record.id)) return 'superseded';+ if (scope !== activeOwnerScopeKey() || usageLimitRecoverySuspended) return 'superseded';+ savedUsageLimitWaits.delete(sessionId);+ return agentInputCoordinatorHolder? agentInputCoordinatorHolder.continueAfterUsageLimitReset(sessionId, token, info)- : 'superseded',+ : 'superseded';+ },log: (message, fields) => log.info(message, fields),});@@ -1642,9 +1793,13 @@ onCodexAutoResetRestored(providerId => usageLimitAutoResume.resumeRestored(id =>// 和「最终仍失败」桥给 runner,让同一个 run 继续等待或正确失败。const pendingSchedulerAutoResumeRunBySession = new Map<string,- { runId: string; attemptToken: number }+ { runId: string; attemptToken: number; usageLimitToken?: number; retryClientId?: string }>();-const schedulerAutoResumeFailureListeners = new Map<string, Set<() => void>>();+interface SchedulerRecoveryListener {+ failed(): void;+ quotaWait?: { start(): void; resume(): boolean };+}+const schedulerAutoResumeFailureListeners = new Map<string, Set<SchedulerRecoveryListener>>();function schedulerAutoResumeRunKey(sessionId: string, runId: string): string {return JSON.stringify([sessionId, runId]);@@ -1687,7 +1842,7 @@ function notifySchedulerAutoResumeFailed(if (!listeners) return;for (const listener of listeners) {try {- listener();+ listener.failed();} catch {// Runner listener failures must not break chat recovery cleanup.}@@ -1700,6 +1855,15 @@ function failPendingSchedulerAutoResume(sessionId: string, attemptToken?: numbernotifySchedulerAutoResumeFailed(sessionId, current.runId, attemptToken);}+/** Quota waits use the same run waiter; no second scheduler timer or replay queue. */+function finishSchedulerUsageLimitWait(sessionId: string, token: number): void {+ const pending = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (pending?.usageLimitToken !== token) return;+ notifySchedulerAutoResumeFailed(sessionId, pending.runId, pending.attemptToken);+ usageLimitAutoResume.clear(sessionId);+ agentInputCoordinatorHolder?.releaseScheduledUsageLimitRecovery(sessionId, pending.runId, pending.retryClientId);+}+export function isSchedulerAutoResumePending(sessionId: string, runId: string): boolean {return pendingSchedulerAutoResumeRunBySession.get(sessionId)?.runId === runId;}@@ -1708,6 +1872,7 @@ export function onSchedulerAutoResumeFailed(sessionId: string,runId: string,listener: () => void,+ quotaWait?: SchedulerRecoveryListener['quotaWait'],): () => void {const key = schedulerAutoResumeRunKey(sessionId, runId);let listeners = schedulerAutoResumeFailureListeners.get(key);@@ -1715,9 +1880,10 @@ export function onSchedulerAutoResumeFailed(listeners = new Set();schedulerAutoResumeFailureListeners.set(key, listeners);}- listeners.add(listener);+ const entry = { failed: listener, quotaWait };+ listeners.add(entry);return () => {- listeners!.delete(listener);+ listeners!.delete(entry);if (listeners!.size === 0) schedulerAutoResumeFailureListeners.delete(key);};}@@ -1725,6 +1891,11 @@ export function onSchedulerAutoResumeFailed(/** Schedule pause/delete:只撤销仍属于该 run 的普通聊天自动续跑。 */export function cancelSchedulerAutoResume(sessionId: string, runId: string): boolean {if (!isSchedulerAutoResumePending(sessionId, runId)) return false;+ const pending = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (pending?.usageLimitToken !== undefined) {+ finishSchedulerUsageLimitWait(sessionId, pending.usageLimitToken);+ return true;+ }// teardown 是既有唯一生命周期出口:撤退避、清 coordinator 接管与隐藏续跑、// 结算活动行并通知 runner。runId 校验防止迟到的旧 abort 误杀新 run。autoResumeBookkeeping.teardown(sessionId);@@ -1935,6 +2106,10 @@ function settleUndispatchedInterruptedAutoResume(// 额度重置后的自动继续不走中断自愈记账(sessionTotal 刻意为 0),只需恢复原错误与手动重试入口。if (item.autoResume === true && item.autoResumeInfo?.reason === USAGE_LIMIT_RESET_AUTO_RESUME_REASON) {agentInputCoordinatorHolder?.restoreAutoResumeRecovery(sessionId, item.clientId, null);+ const pending = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (pending?.usageLimitToken !== undefined && pending.retryClientId === item.clientId) {+ finishSchedulerUsageLimitWait(sessionId, pending.usageLimitToken);+ }// 供应商组换电脑后的续跑没派出去:协同 Worker 的这次异常终止回报给 Lead。settleProviderGroupContinuation(sessionId, false);return false;@@ -5579,7 +5754,9 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSessionconst closedDirectAbortBoundary = getDirectAbortBoundaryForClosingSession(session.id, session);const preserveAutoResumeIntent =shouldPreserveContinuationOnlyAutoResume(session, closeReason) ||- shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason);+ shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason) ||+ (closeReason === 'unexpected' && session.wasClosedByRuntime() &&+ agentInputCoordinatorHolder?.hasUsageLimitRecovery(session.id) === true);pendingContinuationOnlyAutoResumeRebuilds.delete(session);return { closeReason, closedDirectAbortBoundary, preserveAutoResumeIntent };},@@ -18572,7 +18749,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerGroupService?.mayHandleTurnError(sessionId, signals)? providerGroupSwitchCause(signals, 'run'): null,- onUsageLimitedTurnError: (sessionId, signals, _item, candidateToken) => {+ onUsageLimitedTurnError: (sessionId, signals, item, candidateToken) => {+ if (item.origin?.kind === 'scheduler' && item.origin.runId) {+ // Claim synchronously, before the runner consumes this error. Reset-time+ // lookup is async; unknown/unsafe resets release the run but keep Retry.+ pendingSchedulerAutoResumeRunBySession.set(sessionId, {+ runId: item.origin.runId, attemptToken: 0, usageLimitToken: candidateToken,+ });+ for (const listener of schedulerAutoResumeFailureListeners.get(schedulerAutoResumeRunKey(sessionId, item.origin.runId)) ?? []) {+ listener.quotaWait?.start();+ }+ void usageLimitAutoResume.onTurnError(sessionId, signals, candidateToken).then(armed => {+ if (!armed) finishSchedulerUsageLimitWait(sessionId, candidateToken);+ });+ return;+ }// 供应商组分配的任务先试自动换电脑,不换时由它交回额度重置后自动继续。if (!providerGroupService || signals.providerGroupUsageLimit) {usageLimitAutoResume.onTurnError(sessionId, signals, candidateToken);@@ -18941,6 +19132,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)botDelegationServiceHolder?.confirmQueuedSessionInputDispatched(sessionId, item.clientId);welcomeDispatchReceipts.settle(sessionId, item.clientId, true);const attemptToken = autoResumeAttemptToken(item);+ const quotaClaim = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (quotaClaim?.usageLimitToken !== undefined && quotaClaim.retryClientId === item.clientId) {+ clearSchedulerAutoResumePending(sessionId, quotaClaim.runId, quotaClaim.attemptToken);+ }if (attemptToken !== null &&autoResumeBookkeeping.discardSuppressedError(sessionId, attemptToken)@@ -18985,6 +19180,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 失败 turn 重试 → hook 侧把这一轮接回渠道那条已收口的消息。source 区分// 人工与自动续跑:只有真人接手才作废 scheduler waiter,自动路径不能取消自己。onUiRetry: (sessionId, clientId, source, attemptToken) => {+ const quotaClaim = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (source === 'auto' && quotaClaim?.usageLimitToken !== undefined) {+ quotaClaim.retryClientId = clientId;+ }autoResumeBookkeeping.claimSuppressedErrorForRetry(sessionId, clientId, source);if (source === 'auto' && attemptToken !== undefined) {autoResumeBookkeeping.bindSuppressedErrorToClient(sessionId, attemptToken, clientId);@@ -19063,6 +19262,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions));},onUnconfirmedAutoResumeTurn: (sessionId, item) => {+ const pending = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (pending?.usageLimitToken !== undefined && pending.retryClientId === item.clientId) {+ // Outcome is uncertain: settle the waiter without restoring/replaying input.+ notifySchedulerAutoResumeFailed(sessionId, pending.runId, pending.attemptToken);+ }const attemptToken = autoResumeAttemptToken(item);if (attemptToken === null) return;autoResumeBookkeeping.abandonUnconfirmedPersistedResume(@@ -19129,6 +19333,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)gatewayCodexRestartHolder?.isSessionRestarting(sessionId) === true,}),emitProjection: (projection) => {+ const savedWait = savedUsageLimitWaits.get(projection.sessionId);+ if (savedWait && savedWait.token > 0 &&+ !inputCoordinator.leaseUsageLimitRecovery(projection.sessionId, savedWait.token)) {+ forgetSavedUsageLimitWait(projection.sessionId);+ }+ const quotaClaim = pendingSchedulerAutoResumeRunBySession.get(projection.sessionId);+ if (quotaClaim?.usageLimitToken !== undefined && !quotaClaim.retryClientId &&+ !inputCoordinator.hasUsageLimitRecovery(projection.sessionId, quotaClaim.usageLimitToken)) {+ finishSchedulerUsageLimitWait(projection.sessionId, quotaClaim.usageLimitToken);+ }broadcastToAllWindows(MAKER_PUSH.INPUT_PROJECTION, projection);// 伙伴自主跟进:出错 / 用量上限等待旁路进状态表(只读投影,不影响原广播)。try { noteBotAutonomyInputProjection(projection); } catch { /* 观察层异常不影响输入协调 */ }@@ -19204,6 +19418,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)loadQueueSnapshot: async (sessionId) => {// Rehydrate durable task holds before any entry point can drain restored/new input.await botDelegationServiceHolder?.restorePauseForSession(sessionId);+ await restoreSavedUsageLimitWait(sessionId);return loadAgentInputQueueSnapshot(sessionId);},getPersistedClientIds: getPersistedInputClientIds,diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.tsindex ee93fc68ca..7810f3b0c5 100644--- a/apps/desktop/src/main/maker-ipc/usage.ts+++ b/apps/desktop/src/main/maker-ipc/usage.ts@@ -196,8 +196,8 @@ export async function readXaiSubscriptionUsageSnapshotForDeviceLink(providerId?:return await readSubscriptionAccountUsage(providerId) as XaiSubscriptionUsageSnapshot | null;}-export async function readClaudeSubscriptionUsageSnapshotForDeviceLink(providerId?: string): Promise<import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot | null> {- if (!providerId || providerId === 'anthropic') return claudeSubscriptionUsageReader.read();+export async function readClaudeSubscriptionUsageSnapshotForDeviceLink(providerId?: string, options?: { fresh?: boolean }): Promise<import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot | null> {+ if (!providerId || providerId === 'anthropic') return claudeSubscriptionUsageReader.read(options);if (subscriptionAccountKind(providerId) !== 'claude') return null;return await readSubscriptionAccountUsage(providerId) as import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot | null;}diff --git a/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.ts b/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.tsindex 5a7e141397..9f6487b189 100644--- a/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.ts+++ b/apps/desktop/src/main/maker-ipc/usageLimitAutoResume.ts@@ -8,8 +8,8 @@* - 本模块只做判定、求重置时刻和定时;所有用户动作(发消息、重试、收下错误、取消、清空)* 都由 coordinator 自然作废等待,这里到点复核即可,不需要逐个入口撤销。*- * 产品约束(2026-10-07):- * - 只在本次运行内有效,不落盘;重启后停在报错,交给用户。+ * 产品约束(2026-10-22):+ * - Host 保存等待与恢复项,重启后以新的内存令牌恢复;派发前原子消费保存项。* - 拿不到可靠重置时刻(Coding Plan、API key、网关个人额度等)就不等,也不定时试探。* - 同一任务连续自动继续而没有任何实质产出达到上限后停下,防止重置时刻算早时反复撞限额。*/@@ -28,7 +28,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 type UsageLimitContinueOutcome = 'resumed' | 'superseded' | 'no-progress' | 'capacity-wait';export interface UsageLimitAutoResumeDeps {now(): number;@@ -37,11 +37,12 @@ export interface UsageLimitAutoResumeDeps {clearTimer(handle: unknown): void;/** 该会话是否交给本机制(排除目标模式、Orca worker、伙伴等由别的机制负责的会话)。 */isEligible(sessionId: string): Promise<boolean>;- /** 会话所用账号的重置时刻(unix ms):错误自带 → 报错原文 → 订阅快照;拿不到为 null。 */+ /** 会话所用账号的重置时刻(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;+ saveWait?(sessionId: string, token: number, resumeAt: number, attempts: number, groupQuota: boolean): Promise<boolean>;/** 放弃这一次等待(到点时已不归本机制管),撤掉横幅上的自动继续提示。 */cancel(sessionId: string, token: number): void;continueSession(@@ -66,24 +67,31 @@ export class UsageLimitAutoResume {constructor(private readonly deps: UsageLimitAutoResumeDeps) {}- onTurnError(+ async onTurnError(sessionId: string,signals: InterruptedTurnErrorSignals,candidateToken: number,- ): void {- if (this.disposed || !isAccountUsageLimitError(signals)) return;+ ): Promise<boolean> {+ if (this.disposed || !isAccountUsageLimitError(signals)) return false;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;+ this.deps.cancel(sessionId, candidateToken);+ return false;}const generation = this.bumpGeneration(sessionId);- void this.schedule(sessionId, signals, candidateToken, generation).catch((err) => {+ try {+ const armed = await this.schedule(sessionId, signals, candidateToken, generation);+ if (!armed) this.deps.cancel(sessionId, candidateToken);+ return armed;+ } catch (err) {this.deps.log('usage-limit auto-resume scheduling failed', {sessionId,error: err instanceof Error ? err.message : String(err),});- });+ this.deps.cancel(sessionId, candidateToken);+ return false;+ }}private bumpGeneration(sessionId: string): number {@@ -97,35 +105,40 @@ export class UsageLimitAutoResume {signals: InterruptedTurnErrorSignals,token: number,generation: number,- ): Promise<void> {- if (!(await this.deps.isEligible(sessionId))) return;+ ): Promise<boolean> {+ if (!(await this.deps.isEligible(sessionId))) return false;const resetAt = await this.deps.resolveResetAt(sessionId, signals);- if (this.disposed || this.generations.get(sessionId) !== generation) return;+ if (this.disposed || this.generations.get(sessionId) !== generation) return false;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;+ return false;}// 已过点(错误到达时额度刚好重置)也按最短缓冲继续。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;+ if (!this.deps.arm(sessionId, token, resumeAt)) return false;+ if (this.deps.saveWait && !await this.deps.saveWait(sessionId, token, resumeAt, this.consecutive.get(sessionId) ?? 0, signals.providerGroupUsageLimit !== undefined)) return false;+ if (this.disposed || this.generations.get(sessionId) !== generation || !this.deps.isCurrent(sessionId, token)) return false;this.clear(sessionId);const handle = this.deps.setTimer(() => {void this.fire(sessionId, token);}, resumeAt - now);this.timers.set(sessionId, { token, handle, groupQuota: signals.providerGroupUsageLimit !== undefined });this.deps.log('usage-limit auto-resume scheduled', { sessionId, resumeAt });+ return true;}private async fire(sessionId: string, token: number): Promise<void> {const pending = this.timers.get(sessionId);- if (pending?.token === token) this.timers.delete(sessionId);+ if (pending?.token !== token) return;+ const generation = this.generations.get(sessionId);+ this.timers.delete(sessionId);if (this.disposed || !this.deps.isCurrent(sessionId, token)) return;// 等待期间可能开了目标模式、暂停了执行等:到点再判一次归属。放弃时撤掉提示,// 不留下一个过了点却不会执行的「将于 X 自动继续」。@@ -133,6 +146,7 @@ export class UsageLimitAutoResume {this.deps.cancel(sessionId, token);return;}+ if (this.disposed || this.generations.get(sessionId) !== generation || !this.deps.isCurrent(sessionId, token)) return;const attempt = (this.consecutive.get(sessionId) ?? 0) + 1;this.consecutive.set(sessionId, attempt);let outcome: UsageLimitContinueOutcome;@@ -153,14 +167,59 @@ export class UsageLimitAutoResume {this.deps.cancel(sessionId, token);return;}+ if (outcome === 'capacity-wait') {+ // The scheduler has not dispatched anything. Keep the same wait/run and+ // reuse this timer while its existing concurrency gate is full.+ if (this.disposed || !this.deps.isCurrent(sessionId, token)) return;+ this.consecutive.set(sessionId, attempt - 1);+ const resumeAt = this.deps.now() + USAGE_LIMIT_RESUME_BUFFER_MS;+ if (!this.deps.arm(sessionId, token, resumeAt)) return;+ try {+ if (this.deps.saveWait && !await this.deps.saveWait(sessionId, token, resumeAt, attempt - 1, pending.groupQuota)) {+ this.deps.cancel(sessionId, token);+ return;+ }+ } catch (err) {+ this.deps.log('usage-limit capacity wait save failed', {+ sessionId, error: err instanceof Error ? err.message : String(err),+ });+ this.deps.cancel(sessionId, token);+ return;+ }+ if (this.disposed || !this.deps.isCurrent(sessionId, token)) return;+ const handle = this.deps.setTimer(() => { void this.fire(sessionId, token); }, USAGE_LIMIT_RESUME_BUFFER_MS);+ this.timers.set(sessionId, { token, handle, groupQuota: pending?.groupQuota ?? false });+ return;+ }// 没真正续上(如判断不了有无产出):撤掉已过点的提示,保留原错误与手动重试,不再自动等待。if (outcome !== 'resumed') this.deps.cancel(sessionId, token);this.deps.log('usage-limit auto-resume fired', { sessionId, outcome, attempt });}+ /** Keep the original deadline across restart; overdue waits get a short startup buffer. */+ restore(sessionId: string, token: number, resumeAt: number, attempts: number, groupQuota = false): boolean {+ if (this.disposed || attempts >= USAGE_LIMIT_MAX_CONSECUTIVE_RESUMES) return false;+ const due = Math.max(resumeAt, this.deps.now() + USAGE_LIMIT_RESUME_BUFFER_MS);+ if (!this.deps.arm(sessionId, token, due)) return false;+ this.bumpGeneration(sessionId);+ this.clear(sessionId);+ this.consecutive.set(sessionId, attempts);+ const handle = this.deps.setTimer(() => { void this.fire(sessionId, token); }, due - this.deps.now());+ this.timers.set(sessionId, { token, handle, groupQuota });+ return true;+ }++ /** App/owner teardown keeps durable waits but invalidates all in-flight lookups. */+ suspend(): void {+ for (const id of this.generations.keys()) this.bumpGeneration(id);+ for (const { handle } of this.timers.values()) this.deps.clearTimer(handle);+ this.timers.clear();+ this.consecutive.clear();+ }+/** A verified quota refresh may satisfy existing waits before their natural reset time. */async resumeRestored(matches: (sessionId: string) => Promise<boolean>): Promise<void> {- for (const [sessionId, pending] of this.timers) {+ for (const [sessionId, pending] of [...this.timers]) {// A pending group switch still has the previous route saved. A local reset event// says nothing about the group's quota; only its own reset timer may resume it.if (pending.groupQuota) continue;diff --git a/apps/desktop/src/main/maker-ipc/usageLimitRecoveryStore.ts b/apps/desktop/src/main/maker-ipc/usageLimitRecoveryStore.tsnew file mode 100644index 0000000000..5a4176b975--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/usageLimitRecoveryStore.ts@@ -0,0 +1,85 @@+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';+import { sanitizeQueuedMessageForPersistence } from '../../shared/agentInputQueue.js';+import { isRestorableQueuedMessage } from '../localDb/agentInputQueueSnapshots.js';+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';++export interface UsageLimitRecoverySnapshot {+ kind: 'active-turn' | 'queue-head';+ item: AgentInputQueuedMessage;+ error: string;+}++export interface SavedUsageLimitWait extends UsageLimitRecoverySnapshot {+ id: string;+ sessionId: string;+ resumeAt: number;+ attempts: number;+ groupQuota?: boolean;+ savedAt: number;+ route: string;+}++/** Reuse the owner-scoped atomic file store, including its cross-process lock. */+export function createUsageLimitRecoveryStore(options: {+ filePath(): string;+ scopeKey(): string;+ log: { info(message: string, meta?: Record<string, unknown>): void; warn(message: string, meta?: Record<string, unknown>): void };+}) {+ const writes = new Set<Promise<unknown>>();+ function track<T>(write: Promise<T>): Promise<T> {+ writes.add(write);+ void write.then(() => writes.delete(write), () => writes.delete(write));+ return write;+ }+ const file = createOverrideSettingsFile<{ waits: Record<string, SavedUsageLimitWait> }>({+ ...options,+ label: 'usage-limit-recovery',+ defaults: { waits: {} },+ maxBytes: 16 * 1024 * 1024,+ preserveUnreadableFile: true,+ logLoadedValue: false,+ logReadErrorDetails: false,+ normalize(raw) {+ const source = (raw as { waits?: unknown } | null)?.waits;+ const waits: Record<string, SavedUsageLimitWait> = {};+ if (source && typeof source === 'object' && !Array.isArray(source)) {+ for (const [sid, value] of Object.entries(source)) {+ const v = value as SavedUsageLimitWait | null;+ if (!v || v.sessionId !== sid || typeof v.id !== 'string' || !v.id ||+ !['active-turn', 'queue-head'].includes(v.kind) || typeof v.error !== 'string' ||+ typeof v.route !== 'string' || !Number.isFinite(v.resumeAt) || v.resumeAt <= 0 ||+ !Number.isFinite(v.savedAt) || !Number.isInteger(v.attempts) || v.attempts < 0 ||+ !isRestorableQueuedMessage(v.item) || v.item.sharedTaskAuthor) continue;+ Object.defineProperty(waits, sid, { enumerable: true, configurable: true, writable: true,+ value: { ...v, item: sanitizeQueuedMessageForPersistence(v.item) } });+ }+ }+ return { waits };+ },+ });+ return {+ async flush() { await Promise.all([...writes]); },+ readAll() { file.invalidateIfChanged(); return Object.values(file.read().waits); },+ async save(value: SavedUsageLimitWait, isCurrent = () => true): Promise<boolean> {+ let saved = false;+ await track(file.updateAtomic(current => {+ if (!isCurrent()) return { waits: current.value.waits };+ saved = true;+ return { waits: { ...current.value.waits,+ [value.sessionId]: { ...value, item: sanitizeQueuedMessageForPersistence(value.item) },+ } };+ }));+ return saved;+ },+ /** Delete before dispatch: a second instance or restart cannot replay a claimed turn. */+ async take(sessionId: string, id: string): Promise<boolean> {+ let taken = false;+ await track(file.updateAtomic(current => {+ const waits = { ...current.value.waits };+ if (waits[sessionId]?.id === id) { delete waits[sessionId]; taken = true; }+ return { waits };+ }));+ return taken;+ },+ };+}diff --git a/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts b/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.tsindex 52f8b5a363..0b6226b954 100644--- a/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts@@ -25,7 +25,7 @@ function setup(virtual: string) {const workspace = new ExecutorWorkspace({ workingDir: real, aliases: [{ from: virtual, to: real }] });workspace.setVirtualRoot(virtual);const controller = createRemoteAgentHandle({- client: {} as RemoteAgentRunClient,+ client: { callWithId: async () => undefined } as unknown as RemoteAgentRunClient,started: { id: 'sdk-1', agentKind: 'claude-code', model: 'm', shadowDir: virtual, virtualWorkspace: true, methods: [], state: {} },workspace, mapEvent: mapClaudeHostedEvent, recordApproval: () => {}, newId: () => 'request-id', dispose: async () => {},});@@ -42,6 +42,44 @@ async function eventsFrom(controller: ReturnType<typeof setup>['controller'], inreturn output;}+// Unit regression: a quota terminal followed by a missing remote run must keep+// the actionable error (and its reset time), rather than replacing it with EXPIRED.+describe('remote terminal error ownership', () => {+ it.each([true, false])('preserves a terminal error across remote close; paired done=%s', async (done) => {+ const { controller } = setup('/remote/workspace');+ const error: AgentEvent = { type: 'error', source: 'claude-code', data: {+ message: "You've hit your weekly limit · resets 9am (Pacific/Auckland)",+ sdkError: 'rate_limit', usageResetAt: 1792612800000,+ } };+ controller.onEvent(error);+ if (done) controller.onEvent({ type: 'done', source: 'claude-code', data: {} });+ controller.onClosed('missing', '[REMOTE_AGENT_EXPIRED] The task is no longer running on the other computer.');+ const events: AgentEvent[] = [];+ for await (const event of controller.handle.events()) events.push(event);+ expect(events.filter(event => event.type === 'error')).toEqual([error]);+ });++ it('still reports remote loss after a nonterminal warning', async () => {+ const { controller } = setup('/remote/workspace');+ controller.onEvent({ type: 'error', source: 'claude-code', data: { message: 'retrying', isTerminal: false } });+ controller.onClosed('missing', '[REMOTE_AGENT_EXPIRED] missing');+ const events: AgentEvent[] = [];+ for await (const event of controller.handle.events()) events.push(event);+ expect(events.at(-1)?.data).toMatchObject({ reason: 'remote_agent_closed' });+ });++ it('does not carry the previous failure into a newly sent turn', async () => {+ const { controller } = setup('/remote/workspace');+ controller.onEvent({ type: 'error', source: 'claude-code', data: { message: 'weekly limit', sdkError: 'rate_limit' } });+ controller.onEvent({ type: 'done', source: 'claude-code', data: {} });+ await controller.handle.send({ type: 'user', content: 'try again' });+ controller.onClosed('missing', '[REMOTE_AGENT_EXPIRED] missing');+ const events: AgentEvent[] = [];+ for await (const event of controller.handle.events()) events.push(event);+ expect(events.at(-1)?.data).toMatchObject({ reason: 'remote_agent_closed' });+ });+});+function text(event: AgentEvent): string { return (event.data as { text: string }).text; }/** 正文里还原的路径沿用 Agent 写的分隔符(Markdown 会把 `\.git` 这类反斜杠当转义);结构化路径字段仍用本机写法。 */diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.tsindex 2c59b4b35a..59cdad96d1 100644--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts@@ -10,6 +10,7 @@* 调用先连回同一个会话;只改设置的调用(换模型、权限档、计划模式、目录等)只记在本机,连回来时带上。*/import fsp from 'node:fs/promises';+import { isTerminalAgentErrorEvent } from '@cindy/maker-core';import type { RemoteAgentMethod, RemoteAgentReply, RemoteAgentReverseRequest, RemoteAgentTeardownReason } from '@cindy/device-link';import type {@@ -283,6 +284,9 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandlet carriedUsage: unknown;/** 回到某条消息后、下一轮跑完前(Claude Code 要到下一次发送才在对方截断):不能让出名额。 */let rewindPending = false;+ // The provider terminal owns this turn's failure, including its quota reset.+ // A later transport teardown must close the handle without replacing that error.+ let terminalErrorDelivered = false;const dispose = async () => {if (disposed) return;@@ -343,6 +347,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand// 连回之后才转换路径:让出期间改过的目录要等连回补发后才有虚拟路径。projectMessage(wireMessage);if (encoded.wire.cindy?.autoReviewSourceContent) projectMessage(encoded.wire.cindy.autoReviewSourceContent);+ if (method === 'send') terminalErrorDelivered = false;await client.callWithId(callId, method, [wireMessage, encoded.wire]);}@@ -535,6 +540,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandonEvent(event) {if (!event || typeof event !== 'object' || typeof (event as AgentEvent).type !== 'string') return;let typed = event as AgentEvent;+ if (isTerminalAgentErrorEvent(typed) && typed.turnScope !== 'background') terminalErrorDelivered = true;if (typed.type === 'image' && typed.source === 'codex'&& (typed.data as { kind?: unknown } | null)?.kind === 'generation') {typed = { ...typed, data: { ...(typed.data as object), pathOrigin: 'remote-agent' } };@@ -613,7 +619,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandonClosed(reason, message) {for (const projected of projection.flush()) queue.push(projected);// 'superseded':同一任务被重新打开、旧实例让位给新实例,不是错误,静默收起。- if (reason !== 'closed' && reason !== 'detached' && reason !== 'ended' && reason !== 'superseded') {+ if (!terminalErrorDelivered && reason !== 'closed' && reason !== 'detached' && reason !== 'ended' && reason !== 'superseded') {queue.push({type: 'error',data: {diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex 2395feacbd..d9f321daa8 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -308,6 +308,8 @@ interface QueueHarness {discard(): void;/** 模拟普通自动续跑最终仍失败。 */failAutoResume(): void;+ startQuotaWait(): void;+ resumeQuotaWait(): boolean;}function createQueueHarness(opts: {@@ -333,6 +335,7 @@ function createQueueHarness(opts: {const removeCalls: QueueHarness['removeCalls'] = [];const cancelAutoResumeCalls: QueueHarness['cancelAutoResumeCalls'] = [];const autoResumeFailureListeners = new Set<() => void>();+ let quotaWait: { start(): void; resume(): boolean } | undefined;return {enqueueCalls,removeCalls,@@ -361,7 +364,8 @@ function createQueueHarness(opts: {},isPromptTracked: () => (opts.tracked ? opts.tracked() : true),isAutoResumePending: () => opts.autoResumePending?.() ?? false,- onAutoResumeFailed: (_sessionId, _runId, listener) => {+ onAutoResumeFailed: (_sessionId, _runId, listener, wait) => {+ quotaWait = wait;autoResumeFailureListeners.add(listener);return () => autoResumeFailureListeners.delete(listener);},@@ -381,6 +385,8 @@ function createQueueHarness(opts: {failAutoResume() {for (const listener of [...autoResumeFailureListeners]) listener();},+ startQuotaWait() { quotaWait?.start(); },+ resumeQuotaWait() { return quotaWait?.resume() ?? false; },};}@@ -984,6 +990,53 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {expect(harness.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();});+ // Quota waits may last days: use the engine's existing queue-wait contract,+ // which releases capacity and excludes the run from the no-progress watchdog.+ it.each(['resume', 'cancel', 'no-slot'] as const)('settles a scheduled quota wait on %s', async (outcome) => {+ let pending = true;+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true, autoResumePending: () => pending });+ const { runner } = createRunnerHarness(harness.session, queue.deps);+ const ctx = { ...createFireContext(), onQueueWaitStart: vi.fn(), endQueueWait: vi.fn(() => true) };+ const fire = runner.fire(heartbeatSchedule(), ctx);+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();+ ctx.onQueueWaitStart.mockClear();+ ctx.endQueueWait.mockClear();+ queue.startQuotaWait();+ queue.startQuotaWait();+ harness.emit({ type: 'error', source: 'claude-code', data: { message: 'weekly limit', sdkError: 'rate_limit' } });+ harness.emit({ type: 'done', source: 'claude-code', data: {} });+ await Promise.resolve();+ expect(ctx.onQueueWaitStart).toHaveBeenCalledOnce();+ expect(ctx.endQueueWait).not.toHaveBeenCalled();+ if (outcome === 'cancel') {+ pending = false;+ queue.failAutoResume();+ await expect(fire).rejects.toThrow('scheduled task auto-resume failed');+ expect(ctx.endQueueWait).toHaveBeenCalledExactlyOnceWith(false);+ } else if (outcome === 'no-slot') {+ ctx.endQueueWait.mockReturnValue(false);+ expect(queue.resumeQuotaWait()).toBe(false);+ expect(ctx.endQueueWait).toHaveBeenCalledExactlyOnceWith(true);+ // The same run remains queued until capacity is actually available.+ ctx.endQueueWait.mockReturnValue(true);+ expect(queue.resumeQuotaWait()).toBe(true);+ pending = false;+ harness.emit({ type: 'text', source: 'claude-code', data: { text: 'continued', isFinal: true } });+ harness.emit({ type: 'done', source: 'claude-code', data: {} });+ await expect(fire).resolves.toMatchObject({ resultText: 'continued' });+ expect(ctx.endQueueWait.mock.calls).toEqual([[true], [true]]);+ } else {+ expect(queue.resumeQuotaWait()).toBe(true);+ pending = false;+ harness.emit({ type: 'text', source: 'claude-code', data: { text: 'continued', isFinal: true } });+ harness.emit({ type: 'done', source: 'claude-code', data: {} });+ await expect(fire).resolves.toMatchObject({ resultText: 'continued' });+ expect(ctx.endQueueWait).toHaveBeenCalledExactlyOnceWith(true);+ }+ });+it("rebinds the same run to Maker's replacement Session while auto-resume still owns it", async () => {vi.useFakeTimers();try {diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex 9e9e17761f..af12890a27 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -259,7 +259,10 @@ export interface SchedulerQueueDeps {/** 普通聊天自动续跑是否已接管当前 scheduler run。 */isAutoResumePending?: (sessionId: string, runId: string) => boolean;/** 已接管的续跑最终仍失败(含补发未 dispatch / Stop / clear)。 */- onAutoResumeFailed?: (sessionId: string, runId: string, listener: () => void) => () => void;+ onAutoResumeFailed?: (+ sessionId: string, runId: string, listener: () => void,+ quotaWait?: { start(): void; resume(): boolean },+ ) => () => void;/** Schedule pause/delete:撤销仍属于该 run 的退避或派发前隐藏续跑。 */cancelAutoResume?: (sessionId: string, runId: string) => void;}@@ -430,6 +433,8 @@ interface TurnCompletionWaiter {interface TurnCompletionWaiterOptions {onProgress?: () => void;+ onQueueWaitStart?: FireContext['onQueueWaitStart'];+ endQueueWait?: FireContext['endQueueWait'];origin: { kind: 'scheduler'; scheduleId: string; scheduleName: string; runId: string };/** Coordinator queue path has authoritative per-turn origins; direct fallback keeps legacy compatibility. */requireTurnOrigin?: boolean;@@ -1833,7 +1838,9 @@ export class MakerScheduleRunner implements ScheduleRunner {scheduleName: schedule.name,runId: ctx.runId,} as const;- const waiter = this.createTurnCompletionWaiter(session, { onProgress: ctx.onProgress, origin });+ const waiter = this.createTurnCompletionWaiter(session, {+ onProgress: ctx.onProgress, onQueueWaitStart: ctx.onQueueWaitStart, endQueueWait: ctx.endQueueWait, origin,+ });const turnFinished = waiter.turnFinished;// 6. send 并在 onAccepted 中落库 user prompt(不要 close session)。@@ -2620,6 +2627,8 @@ export class MakerScheduleRunner implements ScheduleRunner {if (live) {waiterSlot.current = this.createTurnCompletionWaiter(live, {onProgress: ctx.onProgress,+ onQueueWaitStart: ctx.onQueueWaitStart,+ endQueueWait: ctx.endQueueWait,origin,requireTurnOrigin: true,});@@ -3391,6 +3400,7 @@ export class MakerScheduleRunner implements ScheduleRunner {let offStatus: () => void = () => undefined;let currentSession: Session | null = null;let settled = false;+ let quotaWaiting = false;const clearInterruptedDoneTimer = (): void => {if (interruptedDoneTimer) {clearTimeout(interruptedDoneTimer);@@ -3409,6 +3419,10 @@ export class MakerScheduleRunner implements ScheduleRunner {currentSession = null;};const cleanup = (): void => {+ if (quotaWaiting) {+ quotaWaiting = false;+ options.endQueueWait?.(false);+ }clearInterruptedDoneTimer();pendingSettleUnsub?.();pendingSettleUnsub = undefined;@@ -3631,6 +3645,20 @@ export class MakerScheduleRunner implements ScheduleRunner {sessionId,options.origin.runId,() => fail(new Error('scheduled task auto-resume failed')),+ {+ start: () => {+ if (settled || quotaWaiting) return;+ quotaWaiting = true;+ options.onQueueWaitStart?.();+ },+ resume: () => {+ if (settled) return false;+ if (!quotaWaiting) return true;+ if (options.endQueueWait?.(true) === false) return false;+ quotaWaiting = false;+ return true;+ },+ },);stopListeningTurn = (): void => {cleanup();diff --git a/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.ts b/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.tsindex 7e372c4d15..ecc3af5bcd 100644--- a/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.ts+++ b/apps/desktop/src/main/usage/__tests__/accountUsageLimit.test.ts@@ -26,6 +26,7 @@ import {claudeAccountUsageLimit,codexAccountUsageLimit,readAccountUsageLimit,+ readRemoteAccountUsageLimit,sessionUsesOtherMachineAccount,subscriptionFamilyOf,xaiAccountUsageLimit,@@ -38,6 +39,19 @@ import type { CodexAccountUsagePayload } from '../../usageBroadcaster';// 远程 Agent 的任务撞上限额时,本机订阅快照属于另一个账号(2026-10-09:与 SSH 同一边界)。describe('sessionUsesOtherMachineAccount', () => {+ it('reads the executing computer and rejects an unverified named-account reply', async () => {+ const reset = Date.now() / 1000 + 86400;+ const invoke = vi.fn(async () => ({ ok: true, result: {+ fiveHour: { utilization: 100, resetsAt: reset - 3600 },+ sevenDay: { utilization: 100, resetsAt: reset }, scoped: [],+ } }));+ const route = { deviceId: 'remote', providerId: 'anthropic', family: 'claude' as const, agentKind: 'claude-code' };+ expect(await readRemoteAccountUsageLimit(route, invoke)).toEqual({ limited: true, resetAtMs: reset * 1000 });+ expect(invoke).toHaveBeenCalledWith('remote', 'maker:usage:claude-subscription', ['anthropic', true]);+ expect(await readRemoteAccountUsageLimit({ ...route, providerId: 'named' }, invoke)).toBeNull();+ expect(mocks.claude).not.toHaveBeenCalled();+ });+it('SSH 远程工作区与远程 Agent(含分享来的供应商)都用另一台机器的账号', () => {expect(sessionUsesOtherMachineAccount({ remoteHostId: 'host-1' })).toBe(true);expect(sessionUsesOtherMachineAccount({ agentDeviceId: 'device-agent' })).toBe(true);diff --git a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.tsindex cafdf74435..61c84bda65 100644--- a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts+++ b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts@@ -44,6 +44,19 @@ function setup(options: { account?: string | null; cached?: ClaudeSubscriptionUsconst flush = () => new Promise((resolve) => setImmediate(resolve));describe('createClaudeSubscriptionUsageReader', () => {+ it('awaits a fresh exact reset snapshot for recovery while sharing the existing refresh', async () => {+ const { deps, reader, state } = setup();+ let finish!: (value: ClaudeSubscriptionUsageSnapshot) => void;+ deps.fetchSnapshot.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const waiting = reader.read({ fresh: true });+ await flush();+ expect(state.cached).toBeNull();+ finish({ ...SNAPSHOT, sevenDay: { utilization: 100, resetsAt: 9_000_000 } });+ expect(await waiting).toMatchObject({ sevenDay: { utilization: 100, resetsAt: 9_000_000 } });+ await reader.read({ fresh: true });+ expect(deps.fetchSnapshot).toHaveBeenCalledOnce();+ });+it('cached-first:读立即返回缓存,后台拉取并附上账号指纹', async () => {const { deps, reader, state } = setup({ cached: { ...SNAPSHOT, source: 'unified-headers' } });await expect(reader.read()).resolves.toMatchObject({ source: 'unified-headers' });diff --git a/apps/desktop/src/main/usage/accountUsageLimit.ts b/apps/desktop/src/main/usage/accountUsageLimit.tsindex 7e8001a843..2b3cb1bafe 100644--- a/apps/desktop/src/main/usage/accountUsageLimit.ts+++ b/apps/desktop/src/main/usage/accountUsageLimit.ts@@ -142,3 +142,22 @@ export async function readAccountUsageLimit(return undefined;}}++/** Query the actual execution computer; never substitute this computer's account. */+export async function readRemoteAccountUsageLimit(+ route: { deviceId: string; providerId: string; family: NativeSubscriptionAuth; agentKind: string; modelId?: string | null },+ invoke: (deviceId: string, channel: string, args: unknown[]) => Promise<{ ok: boolean; result?: unknown }>,+): Promise<AccountUsageLimit | null> {+ const channel = route.family === 'claude' ? 'maker:usage:claude-subscription'+ : route.family === 'codex' ? 'maker:usage:account' : 'maker:usage:xai-subscription';+ const reply = await invoke(route.deviceId, channel,+ route.family === 'codex' ? ['codex', route.providerId] : [route.providerId, true]);+ if (!reply.ok || !reply.result || typeof reply.result !== 'object') return null;+ const data = reply.result as { providerId?: unknown };+ const defaultId = NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS[route.family];+ // Old hosts may ignore named-account arguments. Accept an omitted echo only for defaults.+ if (data.providerId !== undefined ? data.providerId !== route.providerId : route.providerId !== defaultId) return null;+ if (route.family === 'claude') return claudeAccountUsageLimit(data as import('../../shared/claudeSubscriptionUsage.js').ClaudeSubscriptionUsageSnapshot, route.modelId);+ if (route.family === 'codex') return codexAccountUsageLimit(data as CodexAccountUsagePayload, route);+ return xaiAccountUsageLimit(data as XaiSubscriptionUsageSnapshot);+}diff --git a/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts b/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.tsindex e765be67a1..109da29a3d 100644--- a/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts+++ b/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts@@ -41,7 +41,7 @@ const DEFAULT_BACKOFF_MAX_MS = 30 * 60_000;export interface ClaudeSubscriptionUsageReader {/** cached-first 读(IPC handler 用):立即返回缓存快照,后台按节流刷新。 */- read(): Promise<ClaudeSubscriptionUsageSnapshot | null>;+ read(options?: { fresh?: boolean }): Promise<ClaudeSubscriptionUsageSnapshot | null>;/** 显式触发一次后台刷新(turn-done 钩子用),同样吃节流 / 退避。 */triggerRefresh(): void;/**@@ -148,7 +148,7 @@ export function createClaudeSubscriptionUsageReader(}return {- async read(): Promise<ClaudeSubscriptionUsageSnapshot | null> {+ async read(options): Promise<ClaudeSubscriptionUsageSnapshot | null> {const account = readAccountSafe();if (account === null) return null;const cached = await deps.readCachedSnapshot();@@ -160,6 +160,10 @@ export function createClaudeSubscriptionUsageReader(void refreshFor(account);return null;}+ if (options?.fresh) {+ await refreshFor(account);+ return readAccountSafe() === account ? deps.readCachedSnapshot() : null;+ }void refreshFor(account);return cached;},diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex cb1442eb7b..8c459e202d 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,12 @@# 跨端协议兼容+## 限额恢复时间查询++既有 `maker:usage:claude-subscription` 请求可选在 providerId 后追加 `true`,表示等待同一余量+reader 的刷新完成(仍遵守节流/退避),不改变返回结构、授权门或凭证归属。旧控制端省略参数时+仍使用缓存优先读取;旧被控端忽略新增参数,返回其已有快照。自动续跑只使用实际受限窗口的可信+重置时刻,不把请求成功当成已恢复,也不将远程快照替换为本机账号。无需服务端或 Mobile 原生更新。+## 远程链路流量治理:交互优先名额与 Subagent 变更推送交互类 invoke(`maker:send`、`maker:abort-session`、`maker:input:enqueue` / `steer` / `stop` /diff --git a/docs/product-rules/usage-limit-auto-continue.md b/docs/product-rules/usage-limit-auto-continue.mdindex 6c597dcdf5..208d2e2f0c 100644--- a/docs/product-rules/usage-limit-auto-continue.md+++ b/docs/product-rules/usage-limit-auto-continue.md@@ -9,6 +9,11 @@这个任务。有产出的 turn 发续跑指令,零产出的 turn 重发原文,与人工「重试」同一条路径。- **目标模式**:沿用 `usageLimited` 状态到点自动续跑(见 `goal-host`),与普通任务共用同一套「按会话所用账号求重置时刻」的逻辑,两者不会重复续跑。+- **定时任务**(2026-10-22):真实 Schedule run 的账号限额失败同样保留手动重试并等待重置。+ 本次运行内自动继续沿用同一个 run;等待期间复用调度器的纯等待状态,不占执行名额,也不按无进展判卡死。+ 到点重新检查执行名额,暂时无空位时复用限额等待计时器每分钟再检查,不请求模型、不消耗续跑次数。+ 用户手动重试或取消等待时结束原 run 的等待,保留普通任务的手动恢复入口;手动续跑不继承已结束+ run 的执行上下文。暂停/删除定时任务也撤销其等待和尚未派发的自动续跑。- 自动继续按自动动作呈现:隐藏续跑指令气泡,消息流里显示「用量已恢复,已自动继续」活动行,不计为用户发送。@@ -17,12 +22,15 @@按顺序取第一个可用的:1. 限额错误自带的结构化时刻(Claude 订阅:SDK `rate_limit_event`)。-2. 报错原文里写明的时刻(ChatGPT 订阅 `resets_at` / `try again at 3:05 PM` / Pi 的+2. 会话实际使用的订阅账号用量窗口,且窗口已用满。本机按既有 reader 刷新;远程 Agent+ 经已有 device-link 余量通道读执行电脑,独立账号必须核对回包的 providerId。+ Claude 查询等待既有 CLI `get_usage` 刷新完成,保留节流和失败退避,不新增登录或凭证读取。+ 多个相关窗口同时受限时,等它们全部恢复;不拿其它模型或本机另一个账号的额度推断。+3. 报错原文里写明的时刻(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 上无关)。+ 订阅家族由 provider 的 `auth.native` 决定,与跑在哪个 Harness 上无关。-前两步也只对订阅账号生效:Coding Plan、Copilot、API key、Cindy 网关个人额度等即使报错原文带了+以上来源也只对订阅账号生效:Coding Plan、Copilot、API key、Cindy 网关个人额度等即使报错原文带了重试时刻也不等(那多半是按分钟的请求速率限制),**不等待、也不定时试探**,只报错交给用户。快照只看会话模型实际受限的那一格:Codex 按模型取对应的用量桶(如 Spark 单独计),Claude 订阅@@ -30,21 +38,28 @@另一台电脑、含分享来的供应商,2026-10-09 起)都用那台机器的登录,不读本机快照(目标模式同样只用远端报错里的时刻),且不采用远端报错里不带时区的钟点(如 Codex `try again at 3:05 PM` 用的是那台机器的本地时间);相对时长与带时区的时刻照常。判定见`apps/desktop/src/main/usage/accountUsageLimit.ts` 的 `sessionUsesOtherMachineAccount`。-已知限制:订阅家族按本机供应商目录认,远程 Agent 用的是那台电脑独有的独立账号(本机目录里没有)时认不出是订阅,-按非订阅处理,只报错不等待;内置默认账号(Claude / ChatGPT / SuperGrok)不受影响。+普通任务在本机目录认不出远程独立账号时读取执行电脑的目录。SSH 没有余量查询通道,仍只采信+远端报错中的可靠时刻;目标模式的远端查询边界沿用既有行为。快照不可靠时同样不等:用满的窗口没有重置时刻(不拿别的窗口的时刻顶替)、窗口已过重置点(快照在翻篇前取的)、SuperGrok 缓存快照超过有效期。目标模式同样只对订阅账号采信报错原文里的时刻,快照也须显示已用满才采纳其时刻。只认具体窗口显示用满,不认快照级「已触顶」标记(说不清来源,且混有需要充值的余额耗尽)。## 边界-- 普通任务的等待只在本次运行内有效,不落盘;应用或电脑重启后停在报错,由用户手动继续。- 目标模式例外:沿用既有的 `usageLimited` 持久状态,重启后按保存的重置时刻继续排期。+- 普通任务与定时任务的等待按 Cindy 账号保存到本机 `usage-limit-waits.json`,复用原子文件存储。+ 保存原错误、恢复项、模型路线、截止时刻及次数;重启登录后自动恢复,已过点的留一分钟启动缓冲。+ 取消、手动接手、清空、改路线、归档/删除会使保存项失效;换账号只停内存计时,原账号下次激活再恢复。+ 正常退出先冻结等待再停 scheduler/Maker,等待写入完成。派发前原子消费保存项,多个实例只能一个续跑;+ 消费后发生崩溃不重放结果未知的发送,保留既有中断后的手动恢复流程。+ 重启后旧 schedule run 按既有规则收口,恢复的是该任务的续跑,不复活旧 FireContext;等待时仍阻止+ 同 schedule 再排一份输入,并核对 schedule 未暂停/删除。目标模式沿用已有的持久状态。+- 已收到上游终态错误后,远程运行消失等收尾错误不得覆盖原始原因和重置时刻;下一次发送仍独立报告+ 新错误。额度等待期间 Agent 自行退出只清运行时,保留任务的恢复意图;用户明确关闭任务仍撤销等待。- 普通任务里用户动手换模型或来源即视为接手,开始切换时就撤销等待(新选择可能有额度;切换失败时错误与手动重试仍在,不恢复等待)。目标模式的`usageLimited` 排期沿用既有行为,由目标自身的暂停 / 恢复控制,不在本规则内。- 重置后再等约 1 分钟并错开几十秒,避免同账号多个任务同时涌入。- 同一任务两次实质产出之间最多自动继续 3 次,防止重置时刻算早时反复撞上限。-- 不覆盖:Schedule 运行与复用其来源的 Slack / X / Telegram Hook 消息(失败时本就不留重试入口,由各自 runner 收尾)、Orca worker(失败已交给 Lead;归在供应商组里的 Worker 仍会先自动换电脑接着跑,见 [供应商组](provider-groups.md) §6.1)、伙伴会话(走候选链)、+- 不覆盖:复用 scheduler 来源、但没有真实 runId 的 Slack / X / Telegram Hook 消息(由各自 runner 收尾)、Orca worker(失败已交给 Lead;归在供应商组里的 Worker 仍会先自动换电脑接着跑,见 [供应商组](provider-groups.md) §6.1)、伙伴会话(走候选链)、目标模式在管的任务、执行已暂停的任务、共享任务访客发起或插话的回合(授权可能在等待期间被撤销,由房主手动处理)。- **共享中的任务撞上限额不自动等待**(Dash 2026-10-08):普通任务与目标模式都一样——报错照常,