From 0d7e345d3d35f92595ffc60b430c299eef9d28b4 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 16 Oct 2026 13:09:03 +0900 Subject: [PATCH] fix: check every scheduled Claude attempt for the usage limit The alignment-hold check in runTask only looked at the first attempt's streamed trigger. A limit that came back only as the final error (no streamed output) or on the retry after an auth refresh extended nothing. holdAlignmentAfterClaudeTaskLimit now runs inside runTaskAttempt for every Claude attempt and reads the streamed trigger, the final error and the attempt error (classifyClaudeTrigger), then calls the shared holdUntilSlotAfterLimitReset. Co-Authored-By: Claude Opus 5.5 --- src/task-scheduler.test.ts | 99 ++++++++++++++++++++++++++++++++++++++ src/task-scheduler.ts | 73 ++++++++++++++++++---------- 2 files changed, 146 insertions(+), 26 deletions(-) diff --git a/src/task-scheduler.test.ts b/src/task-scheduler.test.ts index d720d6e..65b3815 100644 --- a/src/task-scheduler.test.ts +++ b/src/task-scheduler.test.ts @@ -925,6 +925,105 @@ Check the run. ); }); + function startOffSlotLimitTask(id: string): void { + vi.setSystemTime(new Date('2026-10-16T08:30:00+09:00')); + const dueAt = new Date(Date.now() - 60_000).toISOString(); + createTask({ + id, + group_folder: 'shared-group', + chat_jid: 'shared@g.us', + agent_type: 'claude-code', + prompt: 'claude task', + schedule_type: 'once', + schedule_value: dueAt, + context_mode: 'isolated', + next_run: dueAt, + status: 'active', + created_at: '2026-02-22T00:00:00.000Z', + }); + startSchedulerLoop({ + serviceAgentType: 'claude-code', + roomBindings: () => ({ + 'shared@g.us': { + name: 'Shared', + folder: 'shared-group', + trigger: '@Claude', + added_at: '2026-02-22T00:00:00.000Z', + agentType: 'claude-code', + }, + }), + getSessions: () => ({}), + queue: { + enqueueTask: vi.fn( + (_groupJid: string, _taskId: string, fn: () => Promise) => { + void fn(); + }, + ), + } as any, + onProcess: () => {}, + sendMessage: vi.fn(async () => {}), + }); + } + + it('holds until the next slot when a scheduled Claude task ends with a 429 error and no streamed output', async () => { + (runAgentProcessMock as any).mockImplementationOnce(async () => ({ + status: 'error', + result: null, + error: + "API Error: 429 You've hit your limit · resets 9:20am (Asia/Seoul)", + })); + + startOffSlotLimitTask('task-final-429'); + await vi.advanceTimersByTimeAsync(10); + + expect(runAgentProcessMock).toHaveBeenCalledTimes(1); + expect(getRouterState(USAGE_ALIGNMENT_HOLD_UNTIL_KEY)).toBe( + '2026-10-16T04:00:00.000Z', + ); + }); + + it('holds until the next slot when the retry after an auth refresh hits the limit', async () => { + vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValueOnce( + 'refreshed-token', + ); + const authBanner = + 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}'; + (runAgentProcessMock as any) + .mockImplementationOnce( + async ( + _group: unknown, + _input: unknown, + _onProcess: unknown, + onOutput?: (output: Record) => Promise, + ) => { + await onOutput?.({ status: 'success', result: authBanner }); + return { status: 'success', result: null }; + }, + ) + .mockImplementationOnce( + async ( + _group: unknown, + _input: unknown, + _onProcess: unknown, + onOutput?: (output: Record) => Promise, + ) => { + await onOutput?.({ + status: 'success', + result: "You're out of extra usage · resets 9:20am (Asia/Seoul)", + }); + return { status: 'success', result: null }; + }, + ); + + startOffSlotLimitTask('task-retry-limit'); + await vi.advanceTimersByTimeAsync(10); + + expect(runAgentProcessMock).toHaveBeenCalledTimes(2); + expect(getRouterState(USAGE_ALIGNMENT_HOLD_UNTIL_KEY)).toBe( + '2026-10-16T04:00:00.000Z', + ); + }); + it('suppresses Claude OAuth expiry banners for scheduled tasks and retries after a token refresh', async () => { const dueAt = new Date(Date.now() - 60_000).toISOString(); createTask({ diff --git a/src/task-scheduler.ts b/src/task-scheduler.ts index bbb1512..82201d7 100644 --- a/src/task-scheduler.ts +++ b/src/task-scheduler.ts @@ -23,7 +23,10 @@ import { } from './db.js'; import { createScopedLogger, logger } from './logger.js'; import { createTaskStatusTracker } from './task-status-tracker.js'; -import type { AgentTriggerReason } from './agent-error-detection.js'; +import { + classifyClaudeTrigger, + type AgentTriggerReason, +} from './agent-error-detection.js'; import { getCurrentClaudeToken } from './claude-oauth-token.js'; import { evaluateTaskSuspension, @@ -132,6 +135,40 @@ function writeCurrentTaskSnapshot( ); } +/** + * Same as a room turn: when a scheduled Claude attempt hit the usage limit + * and the limit resets off the slot grid, hold until the next slot so the + * first request after the reset does not open an off-slot window. Checks the + * streamed trigger and the final/attempt error, on every attempt (including + * the retry after an auth refresh). + */ +function holdAlignmentAfterClaudeTaskLimit(args: { + streamedTrigger?: { reason: AgentTriggerReason; message?: string }; + finalError?: string; + attemptError: string | null; + attemptResult: string | null; + log: { warn: (obj: Record, msg: string) => void }; +}): void { + const errorText = args.finalError ?? args.attemptError ?? undefined; + const reason = + args.streamedTrigger?.reason ?? classifyClaudeTrigger(errorText).reason; + if (!reason || !isClaudeUsageLimitReason(reason)) return; + const resume = resolveClaudeUsageResume( + args.streamedTrigger?.message ?? errorText ?? args.attemptResult, + ); + const slot = resume.resetKnown + ? holdUntilSlotAfterLimitReset(resume.resumeAt) + : null; + args.log.warn( + { + reason, + resetAt: resume.resetKnown ? resume.resumeAt.toISOString() : null, + alignmentHoldUntil: slot?.toISOString() ?? null, + }, + 'Scheduled Claude task hit the usage limit', + ); +} + async function runTask( task: ScheduledTask, deps: SchedulerDependencies, @@ -311,6 +348,15 @@ async function runTask( } const streamedState = streamedOutputHandler.getState(); + if (provider === 'claude') { + holdAlignmentAfterClaudeTaskLimit({ + streamedTrigger: streamedState.streamedTriggerReason, + finalError: output.status === 'error' ? output.error : undefined, + attemptError, + attemptResult, + log, + }); + } return { output, sawOutput: streamedState.sawOutput, @@ -362,31 +408,6 @@ async function runTask( if (retryAction.kind === 'none' && attempt.output.status === 'error') { error = attempt.attemptError || 'Unknown error'; } - - // Same as a room turn: a limit that resets off the slot grid must not - // let the first request after the reset open an off-slot window. - const trigger = attempt.streamedTriggerReason?.reason; - if ( - provider === 'claude' && - trigger && - isClaudeUsageLimitReason(trigger) - ) { - const resume = resolveClaudeUsageResume( - attempt.streamedTriggerReason?.message ?? - attempt.attemptError ?? - attempt.attemptResult, - ); - const slot = resume.resetKnown - ? holdUntilSlotAfterLimitReset(resume.resumeAt) - : null; - log.warn( - { - resetAt: resume.resetKnown ? resume.resumeAt.toISOString() : null, - alignmentHoldUntil: slot?.toISOString() ?? null, - }, - 'Scheduled Claude task hit the usage limit', - ); - } } // end else (non-exhausted path) log.info(