fix: alignment hold also covers scheduled-task limits and the primer
- A scheduled Claude task that hits the usage limit now extends the alignment hold to the next slot when the reset is off the grid, like a room turn (it called runAgentProcess directly and skipped that path). - The Claude primer is skipped while a hold outlasts its slot (e.g. the 08:00 primer during a realignment hold until 13:00). A hold ending at the slot itself does not count: the slot timer fired at 07:59:59.999 for 08:00 on 2026-10-16. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,12 +22,11 @@ import {
|
||||
} from './claude-usage-pause.js';
|
||||
import { getPairedTaskById } from './db.js';
|
||||
import {
|
||||
extendUsageAlignmentHold,
|
||||
formatUsageAlignmentHoldMessage,
|
||||
formatUsageLimitAlignedPauseMessage,
|
||||
getUsageAlignmentHold,
|
||||
holdUntilSlotAfterLimitReset,
|
||||
isUsageAlignmentBypassed,
|
||||
nextWindowStartAfterOffSlotReset,
|
||||
} from './usage-alignment-hold.js';
|
||||
import { completePairedTaskWithReason } from './paired-task-status.js';
|
||||
import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js';
|
||||
@@ -126,10 +125,7 @@ async function pauseRunForClaudeUsage(args: {
|
||||
} else {
|
||||
// A limit that resets off the slot grid would open an off-slot window
|
||||
// on the first request after the reset; hold until the next slot.
|
||||
if (pause.resetKnown) {
|
||||
const slot = nextWindowStartAfterOffSlotReset(pause.until);
|
||||
if (slot) extendUsageAlignmentHold(slot);
|
||||
}
|
||||
if (pause.resetKnown) holdUntilSlotAfterLimitReset(pause.until);
|
||||
const holdAtReset = pause.resetKnown
|
||||
? getUsageAlignmentHold(pause.until.getTime())
|
||||
: null;
|
||||
|
||||
@@ -124,6 +124,7 @@ import {
|
||||
_initTestDatabase,
|
||||
createPairedTask,
|
||||
createTask,
|
||||
getRouterState,
|
||||
getTaskById,
|
||||
setRouterState,
|
||||
} from './db.js';
|
||||
@@ -136,6 +137,7 @@ import {
|
||||
} from './claude-usage-pause.js';
|
||||
import { TIMEZONE } from './config.js';
|
||||
import * as usageAlignmentHold from './usage-alignment-hold.js';
|
||||
import { USAGE_ALIGNMENT_HOLD_UNTIL_KEY } from './usage-alignment-hold.js';
|
||||
import * as serviceRouting from './service-routing.js';
|
||||
import * as tokenRefresh from './token-refresh.js';
|
||||
import { createTaskStatusTracker } from './task-status-tracker.js';
|
||||
@@ -862,6 +864,67 @@ Check the run.
|
||||
);
|
||||
});
|
||||
|
||||
it('holds until the next slot when a scheduled Claude task hits a limit that resets off the grid', async () => {
|
||||
vi.setSystemTime(new Date('2026-10-16T08:30:00+09:00'));
|
||||
const dueAt = new Date(Date.now() - 60_000).toISOString();
|
||||
createTask({
|
||||
id: 'task-off-slot-limit',
|
||||
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',
|
||||
});
|
||||
(runAgentProcessMock as any).mockImplementationOnce(
|
||||
async (
|
||||
_group: unknown,
|
||||
_input: unknown,
|
||||
_onProcess: unknown,
|
||||
onOutput?: (output: Record<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
await onOutput?.({
|
||||
status: 'success',
|
||||
result: "You're out of extra usage · resets 9:20am (Asia/Seoul)",
|
||||
});
|
||||
return { status: 'success', result: null };
|
||||
},
|
||||
);
|
||||
const enqueueTask = vi.fn(
|
||||
(_groupJid: string, _taskId: string, fn: () => Promise<void>) => {
|
||||
void fn();
|
||||
},
|
||||
);
|
||||
|
||||
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 } as any,
|
||||
onProcess: () => {},
|
||||
sendMessage: vi.fn(async () => {}),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
|
||||
expect(runAgentProcessMock).toHaveBeenCalledTimes(1);
|
||||
// 09:20 KST reset -> no Claude until the 13:00 KST slot.
|
||||
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({
|
||||
|
||||
@@ -48,8 +48,13 @@ import {
|
||||
import { runGithubCiTask } from './task-scheduler-github.js';
|
||||
import {
|
||||
getUsageAlignmentHold,
|
||||
holdUntilSlotAfterLimitReset,
|
||||
isUsageAlignmentBypassed,
|
||||
} from './usage-alignment-hold.js';
|
||||
import {
|
||||
isClaudeUsageLimitReason,
|
||||
resolveClaudeUsageResume,
|
||||
} from './claude-usage-limit.js';
|
||||
import type {
|
||||
SchedulerDependencies,
|
||||
TaskExecutionContext,
|
||||
@@ -193,6 +198,7 @@ async function runTask(
|
||||
streamedTriggerReason?: {
|
||||
reason: AgentTriggerReason;
|
||||
retryAfterMs?: number;
|
||||
message?: string;
|
||||
};
|
||||
attemptResult: string | null;
|
||||
attemptError: string | null;
|
||||
@@ -356,6 +362,31 @@ 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(
|
||||
|
||||
@@ -111,6 +111,16 @@ export function extendUsageAlignmentHold(until: Date): void {
|
||||
setRouterState(USAGE_ALIGNMENT_HOLD_UNTIL_KEY, until.toISOString());
|
||||
}
|
||||
|
||||
/**
|
||||
* After a usage limit that resets at `resetAt`: when that is off the slot
|
||||
* grid, hold until the next slot. Returns that slot, or null.
|
||||
*/
|
||||
export function holdUntilSlotAfterLimitReset(resetAt: Date): Date | null {
|
||||
const slot = nextWindowStartAfterOffSlotReset(resetAt);
|
||||
if (slot) extendUsageAlignmentHold(slot);
|
||||
return slot;
|
||||
}
|
||||
|
||||
const MENTION_PATTERN = /<@!?\d+>|(^|\s)@\S/;
|
||||
|
||||
/** True when a human message @-mentions someone (urgent bypass). */
|
||||
|
||||
@@ -38,6 +38,11 @@ vi.mock('./claude-oauth-token.js', () => ({
|
||||
getCurrentClaudeToken: vi.fn(() => undefined),
|
||||
}));
|
||||
|
||||
vi.mock('./db.js', () => ({
|
||||
getRouterState: vi.fn(() => undefined),
|
||||
setRouterState: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./claude-usage.js', () => ({
|
||||
getCachedClaudeFiveHourResetAt: vi.fn(() => null),
|
||||
}));
|
||||
@@ -83,4 +88,20 @@ describe('usage-primer', () => {
|
||||
expect(claudePrimerDelayMs(slot, null)).toBe(0);
|
||||
expect(claudePrimerDelayMs(slot, new Date(slot + 20 * 60_000))).toBe(0);
|
||||
});
|
||||
|
||||
it('skips the Claude primer only for a hold that outlasts the slot', async () => {
|
||||
const { claudePrimerHeldUntil } = await import('./usage-primer.js');
|
||||
const slot = Date.parse('2026-10-16T08:00:00+09:00');
|
||||
const at = (iso: string) => ({ until: new Date(iso) });
|
||||
|
||||
// The timer fired 1 ms early; the daily gap ends at this very slot.
|
||||
expect(
|
||||
claudePrimerHeldUntil(slot - 1, at('2026-10-16T08:00:00+09:00')),
|
||||
).toBeNull();
|
||||
expect(claudePrimerHeldUntil(slot, null)).toBeNull();
|
||||
// One-off realignment hold until 13:00: no Claude call at 08:00.
|
||||
expect(
|
||||
claudePrimerHeldUntil(slot, at('2026-10-16T13:00:00+09:00')),
|
||||
).toEqual(new Date('2026-10-16T13:00:00+09:00'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import { runCodexWarmupCycle } from './codex-warmup.js';
|
||||
import { logger } from './logger.js';
|
||||
import { getCurrentClaudeToken } from './claude-oauth-token.js';
|
||||
import { getCachedClaudeFiveHourResetAt } from './claude-usage.js';
|
||||
import { getUsageAlignmentHold } from './usage-alignment-hold.js';
|
||||
|
||||
/**
|
||||
* Usage-window warm-up primer.
|
||||
@@ -126,6 +127,8 @@ function runClaudePrimerOnce(
|
||||
|
||||
/** Wait for a window that ends at most this long after the slot. */
|
||||
const CLAUDE_PRIMER_MAX_RESET_WAIT_MS = 10 * 60_000;
|
||||
/** A hold ending within this long of the slot is the slot's own hold. */
|
||||
const PRIMER_HOLD_END_GRACE_MS = 60_000;
|
||||
/** Fire this long after the window's reset, never just before it. */
|
||||
const CLAUDE_PRIMER_RESET_MARGIN_MS = 5_000;
|
||||
|
||||
@@ -148,12 +151,37 @@ export function claudePrimerDelayMs(
|
||||
return untilReset + CLAUDE_PRIMER_RESET_MARGIN_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* End of a hold that outlasts this slot (one-off realignment, or the hold
|
||||
* after an off-slot limit reset), or null. While it lasts nothing may call
|
||||
* Claude; the primer at the hold's end opens the window. The slot timer can
|
||||
* fire a millisecond early (07:59:59.999 for 08:00), so a hold ending at the
|
||||
* slot itself does not count.
|
||||
*/
|
||||
export function claudePrimerHeldUntil(
|
||||
nowMs: number,
|
||||
hold: { until: Date } | null,
|
||||
): Date | null {
|
||||
if (!hold || hold.until.getTime() - nowMs <= PRIMER_HOLD_END_GRACE_MS) {
|
||||
return null;
|
||||
}
|
||||
return hold.until;
|
||||
}
|
||||
|
||||
async function runClaudePrimerCycle(): Promise<void> {
|
||||
const token = getCurrentClaudeToken();
|
||||
if (!token) {
|
||||
logger.info('Claude primer skipped: no Claude OAuth token configured');
|
||||
return;
|
||||
}
|
||||
const heldUntil = claudePrimerHeldUntil(Date.now(), getUsageAlignmentHold());
|
||||
if (heldUntil) {
|
||||
logger.info(
|
||||
{ until: heldUntil.toISOString() },
|
||||
'Claude primer skipped: usage alignment hold in effect',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const windowResetAt = getCachedClaudeFiveHourResetAt();
|
||||
const delayMs = claudePrimerDelayMs(Date.now(), windowResetAt);
|
||||
if (delayMs > 0) {
|
||||
|
||||
Reference in New Issue
Block a user