Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(goal): hold a task until its usage limit resets when the owner chose to wait (#22609)

Arvin Xu9d09f91f70e5
diff --git a/apps/server/src/services/goal/GoalService/__tests__/device.test.ts b/apps/server/src/services/goal/GoalService/__tests__/device.test.ts
index f690c82688f..0e11f3e209c 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/device.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/device.test.ts
@@ -10,6 +10,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '@/database/core/getTestDB';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
+import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { goals, tasks, taskTopics, topics } from '@/database/schemas';
@@ -604,6 +605,72 @@ describe('GoalService machine failures', () => {
vi.useRealTimers();
});
+ describe('answering a usage-limit gate', () => {
+ const WEEKLY_LIMIT = "You've hit your weekly limit · resets Oct 9, 5pm (America/New_York)";
+ const WEEKLY_RESET = new Date('2026-10-09T21:00:00.000Z');
+
+ const gated = async (title: string) => {
+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });
+ vi.setSystemTime(new Date(FAILED_AT.getTime() + MINUTE));
+ const context = await setup(title);
+ await failRun(context.created.taskId!, QUOTA_LIMITED_RUN_STATUS, WEEKLY_LIMIT, FAILED_AT);
+ await context.service.tick(context.graph.goal.id);
+ const [decision] = (await context.service.graph(context.graph.goal.id)).decisions;
+ await new GoalGraphModel(serverDB, userId).updatePendingDecisionOptions(
+ context.graph.goal.id,
+ decision.id,
+ [
+ { effect: 'retry', id: 'switch_account', label: 'Switch account, run now' },
+ { effect: 'retry_after_reset', id: 'wait_reset', label: 'Wait for the reset' },
+ ],
+ );
+ return { ...context, decision, goalId: context.graph.goal.id };
+ };
+
+ // Regression: an option promising to wait could only say "retry", so the
+ // answer started a run straight into the same limit.
+ it('holds the Task until the reset when the owner chose to wait', async () => {
+ const { created, decision, goalId, runSpy, service, taskModel } = await gated('Wait');
+
+ await service.decide(goalId, decision.id, 'wait_reset');
+ const held = await service.tick(goalId);
+
+ expect(held.outcome).toBe('waiting_external');
+ expect(runSpy).not.toHaveBeenCalled();
+ expect(await taskModel.findById(created.taskId!)).toMatchObject({
+ error: WEEKLY_LIMIT,
+ status: 'paused',
+ });
+ expect((await service.graph(goalId)).decisions.filter((d) => d.status === 'pending')).toEqual(
+ [],
+ );
+
+ vi.setSystemTime(new Date(WEEKLY_RESET.getTime() + QUOTA_RESET_MARGIN_MS + MINUTE));
+ await service.tick(goalId);
+
+ expect(runSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs at once when the limit is already gone by the time the owner chose to wait', async () => {
+ const { created, decision, goalId, runSpy, service, taskModel } = await gated('Gone');
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Some other failure' });
+
+ await service.decide(goalId, decision.id, 'wait_reset');
+ await service.tick(goalId);
+
+ expect(runSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('still runs at once when the owner answered with a plain retry', async () => {
+ const { decision, goalId, runSpy, service } = await gated('Switch');
+
+ await service.decide(goalId, decision.id, 'switch_account');
+ await service.tick(goalId);
+
+ expect(runSpy).toHaveBeenCalledTimes(1);
+ });
+ });
+
it('waits for a usage limit to reset, then retries without charging the attempt', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });
vi.setSystemTime(new Date(FAILED_AT.getTime() + MINUTE));
diff --git a/apps/server/src/services/goal/GoalService/decisions.ts b/apps/server/src/services/goal/GoalService/decisions.ts
index 6ce549c203a..ead6aed0936 100644
--- a/apps/server/src/services/goal/GoalService/decisions.ts
+++ b/apps/server/src/services/goal/GoalService/decisions.ts
@@ -22,6 +22,7 @@ import { TaskArchiveModel } from '@/database/models/taskArchive';
import { GoalRepository } from '@/database/repositories/goal';
import { collectStrandedDependents, GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';
+import { classifyGoalFailure } from '../failureClass';
import { answeredProblem, GoalManagerService, problemKey } from '../manager';
import { GoalSupervisorService } from '../supervisor';
import type { GoalServiceContext } from './types';
@@ -39,7 +40,7 @@ const REOPENABLE_GOAL_STATUSES = new Set(['achieved', 'running']);
const decisionOptionEffect = (
option: GoalDecisionOption | undefined,
sourceTitle?: string,
-): 'fail' | 'retire' | 'retry' | undefined => {
+): 'fail' | 'retire' | 'retry' | 'retry_after_reset' | undefined => {
if (!option) return undefined;
if (option.effect) return option.effect;
if (option.id === 'retry' || option.id === 'retire') return option.id;
@@ -220,8 +221,16 @@ export const decide = async (
true,
);
const effect = decisionOptionEffect(chosen, source.title);
- if (effect === 'retry' && source.taskId) {
- await ctx.taskModel.updateStatus(source.taskId, 'backlog', { error: null });
+ if ((effect === 'retry' || effect === 'retry_after_reset') && source.taskId) {
+ // Answered to wait: the Task stays paused on its limit, which is what the
+ // tick reads to hold it until the reset and then rerun it. With the limit
+ // already gone there is nothing to wait for, so it is an ordinary retry.
+ const sourceTask =
+ effect === 'retry_after_reset' ? await ctx.taskModel.findById(source.taskId) : undefined;
+ const heldForReset =
+ sourceTask?.status === 'paused' && classifyGoalFailure(sourceTask.error).class === 'quota';
+ if (!heldForReset)
+ await ctx.taskModel.updateStatus(source.taskId, 'backlog', { error: null });
await ctx.graphModel.updateNodeStatus(goalId, source.id, 'active', resolution);
// The note is guidance for the next attempt, so it goes where that
// attempt reads: the Task's comments are part of every run prompt.
diff --git a/apps/server/src/services/goal/GoalService/recovery.ts b/apps/server/src/services/goal/GoalService/recovery.ts
index 146fc1bdee8..aa8f154f450 100644
--- a/apps/server/src/services/goal/GoalService/recovery.ts
+++ b/apps/server/src/services/goal/GoalService/recovery.ts
@@ -20,7 +20,11 @@ import { LEASE_EXPIRED_ERROR } from '../decideNextMove';
import { isDeliverySettling } from '../deliverySettle';
import { readDeviceDispatchStreak } from '../deviceDispatchStreak';
import { classifyGoalFailure } from '../failureClass';
-import { lastAnsweredGateAt, planMachineRecovery } from '../machineRecovery';
+import {
+ lastAnsweredGateAt,
+ lastGateAnsweredToWait,
+ planMachineRecovery,
+} from '../machineRecovery';
import {
classifyRunFailure,
countConsecutiveDeviceOfflineRuns,
@@ -265,10 +269,19 @@ export const planMachineRecoveryFor = async (
) => {
// A person's Retry restarts the schedule they overrode.
const answeredAt = lastAnsweredGateAt(graph, nodeId);
- const runs = (await ctx.taskTopicModel.findByTaskId(task.id)).filter(
- (run) => !answeredAt || new Date(run.updatedAt) > answeredAt,
- );
- return planMachineRecovery({ error: task.error, now, runs, taskUpdatedAt: task.updatedAt });
+ const allRuns = await ctx.taskTopicModel.findByTaskId(task.id);
+ const runs = allRuns.filter((run) => !answeredAt || new Date(run.updatedAt) > answeredAt);
+ // "Wait for the reset" keeps the schedule running on the limited run it was
+ // answered about. It covers that one wait: a run refused again after it goes
+ // back to the ordinary bound, so a person hears about a limit that outlived it.
+ const holdUntilReset = runs.length === 0 && lastGateAnsweredToWait(graph, nodeId);
+ return planMachineRecovery({
+ error: task.error,
+ holdUntilReset,
+ now,
+ runs: holdUntilReset ? allRuns : runs,
+ taskUpdatedAt: task.updatedAt,
+ });
};
/**
diff --git a/apps/server/src/services/goal/machineRecovery.test.ts b/apps/server/src/services/goal/machineRecovery.test.ts
index fdf4aca2585..479bb5b1861 100644
--- a/apps/server/src/services/goal/machineRecovery.test.ts
+++ b/apps/server/src/services/goal/machineRecovery.test.ts
@@ -1,7 +1,7 @@
import { QUOTA_LIMITED_RUN_STATUS, TRANSIENT_FAILED_RUN_STATUS } from '@lobechat/const/goal';
import { describe, expect, it } from 'vitest';
-import { lastAnsweredGateAt, planMachineRecovery } from './machineRecovery';
+import { lastAnsweredGateAt, lastGateAnsweredToWait, planMachineRecovery } from './machineRecovery';
import { QUOTA_RESET_MARGIN_MS } from './recoveryPolicy';
const MINUTE = 60 * 1000;
@@ -75,6 +75,49 @@ describe('planMachineRecovery', () => {
expect(plan.action === 'gate' && plan.reason).toContain('Retried 6 time(s) over 18h');
});
+ it('holds past the one-day bound when a person chose to wait for the reset', () => {
+ const plan = planMachineRecovery({
+ error: "You've hit your weekly limit · resets Oct 9, 5pm (America/New_York)",
+ holdUntilReset: true,
+ now: new Date(FAILED_AT.getTime() + MINUTE),
+ runs: [run(QUOTA_LIMITED_RUN_STATUS, FAILED_AT)],
+ taskUpdatedAt: FAILED_AT,
+ });
+ expect(plan.action).toBe('wait');
+ });
+
+ it('keeps holding when the retries were spent before a person chose to wait', () => {
+ // Six retries were spent on the streak a person then answered with "wait
+ // for the reset". That bound belongs to the automatic loop they overrode,
+ // so the wait has to survive it instead of reopening the gate at once.
+ const runs = Array.from({ length: 7 }, (_, i) =>
+ run(QUOTA_LIMITED_RUN_STATUS, new Date(FAILED_AT.getTime() - i * 3 * HOUR)),
+ );
+ const plan = planMachineRecovery({
+ error: SESSION_LIMIT,
+ holdUntilReset: true,
+ now: new Date(FAILED_AT.getTime() + MINUTE),
+ runs,
+ taskUpdatedAt: FAILED_AT,
+ });
+ expect(plan).toMatchObject({ action: 'wait', failedAt: FAILED_AT, failureClass: 'quota' });
+ });
+
+ it('restarts the authorized wait once its reset has passed', () => {
+ const runs = Array.from({ length: 7 }, (_, i) =>
+ run(QUOTA_LIMITED_RUN_STATUS, new Date(FAILED_AT.getTime() - i * 3 * HOUR)),
+ );
+ expect(
+ planMachineRecovery({
+ error: SESSION_LIMIT,
+ holdUntilReset: true,
+ now: new Date(RESET_AT.getTime() + 3 * MINUTE),
+ runs,
+ taskUpdatedAt: FAILED_AT,
+ }),
+ ).toEqual({ action: 'retry', failureClass: 'quota' });
+ });
+
it('asks at once when the limit resets more than a day away', () => {
const plan = planMachineRecovery({
error: "You've hit your weekly limit · resets Oct 9, 5pm (America/New_York)",
@@ -176,3 +219,28 @@ describe('lastAnsweredGateAt', () => {
expect(lastAnsweredGateAt(graph, 'none')).toBeUndefined();
});
});
+
+describe('lastGateAnsweredToWait', () => {
+ const graph = (resolvedOptionId: string) =>
+ ({
+ decisions: [
+ {
+ nodeId: 'gate',
+ options: [
+ { effect: 'retry', id: 'switch', label: 'Switch account' },
+ { effect: 'retry_after_reset', id: 'wait', label: 'Wait' },
+ ],
+ resolvedAt: new Date('2026-10-03T00:00:00Z'),
+ resolvedOptionId,
+ status: 'resolved',
+ },
+ ],
+ edges: [{ kind: 'leads_to', sourceNodeId: 'task', targetNodeId: 'gate' }],
+ }) as any;
+
+ it('reads the effect of the option the person chose', () => {
+ expect(lastGateAnsweredToWait(graph('wait'), 'task')).toBe(true);
+ expect(lastGateAnsweredToWait(graph('switch'), 'task')).toBe(false);
+ expect(lastGateAnsweredToWait(graph('wait'), 'none')).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/goal/machineRecovery.ts b/apps/server/src/services/goal/machineRecovery.ts
index 38e39a4f391..fb8db66b4f3 100644
--- a/apps/server/src/services/goal/machineRecovery.ts
+++ b/apps/server/src/services/goal/machineRecovery.ts
@@ -111,6 +111,8 @@ const nextQuotaRetryAt = (
*/
export const planMachineRecovery = (params: {
error: string | null | undefined;
+ /** A person chose to wait this limit out, however far off its reset is. */
+ holdUntilReset?: boolean;
now: Date;
runs: readonly RunLike[];
taskUpdatedAt: Date | string;
@@ -135,7 +137,10 @@ export const planMachineRecovery = (params: {
// A wall-clock reset ("resets 4:30am") is the next one after the failure.
const failure = classifyGoalFailure(error, lastFailureAt);
const retryAt = nextQuotaRetryAt(failure, failures, lastFailureAt);
- if (retryAt.getTime() - firstFailureAt.getTime() > QUOTA_MAX_HOLD_MS) {
+ if (
+ !params.holdUntilReset &&
+ retryAt.getTime() - firstFailureAt.getTime() > QUOTA_MAX_HOLD_MS
+ ) {
return {
action: 'gate',
reason:
@@ -144,7 +149,10 @@ export const planMachineRecovery = (params: {
: `Usage limit: ${trimError(error)}. Retried ${retries} time(s) over ${spentFor} and the limit still applies. Check the plan or switch the agent to another account or provider`,
};
}
- if (retries >= MAX_QUOTA_RETRIES) {
+ // The bound stops an automatic retry loop, not the wait a person asked for:
+ // the streak it counts predates their answer, so applying it here would
+ // reopen the decision they just made instead of holding for the reset.
+ if (!params.holdUntilReset && retries >= MAX_QUOTA_RETRIES) {
return {
action: 'gate',
reason: `Usage limit: ${trimError(error)}. Retried ${retries} time(s) over ${spentFor} and the limit still applies. Check the plan or switch the agent to another account or provider`,
@@ -186,17 +194,36 @@ export const lastAnsweredGateAt = (
graph: Pick<GoalGraphSnapshot, 'decisions' | 'edges'>,
nodeId: string,
): Date | undefined => {
+ const decision = lastAnsweredGate(graph, nodeId);
+ return decision ? new Date(decision.resolvedAt!) : undefined;
+};
+
+/** Whether a person's last answer on this Task node was to wait for its limit to reset. */
+export const lastGateAnsweredToWait = (
+ graph: Pick<GoalGraphSnapshot, 'decisions' | 'edges'>,
+ nodeId: string,
+): boolean => {
+ const decision = lastAnsweredGate(graph, nodeId);
+ return (
+ decision?.options?.find((option) => option.id === decision.resolvedOptionId)?.effect ===
+ 'retry_after_reset'
+ );
+};
+
+const lastAnsweredGate = (
+ graph: Pick<GoalGraphSnapshot, 'decisions' | 'edges'>,
+ nodeId: string,
+) => {
const gates = new Set(
graph.edges
.filter((edge) => edge.sourceNodeId === nodeId && edge.kind === 'leads_to')
.map((edge) => edge.targetNodeId),
);
- let latest: Date | undefined;
+ let latest: GoalGraphSnapshot['decisions'][number] | undefined;
for (const decision of graph.decisions) {
if (!gates.has(decision.nodeId) || decision.status !== 'resolved' || !decision.resolvedAt)
continue;
- const at = new Date(decision.resolvedAt);
- if (!latest || at > latest) latest = at;
+ if (!latest || new Date(decision.resolvedAt) > new Date(latest.resolvedAt!)) latest = decision;
}
return latest;
};
diff --git a/apps/server/src/services/goal/manager/planSchema.ts b/apps/server/src/services/goal/manager/planSchema.ts
index 137dd208bc8..6e9606533b6 100644
--- a/apps/server/src/services/goal/manager/planSchema.ts
+++ b/apps/server/src/services/goal/manager/planSchema.ts
@@ -38,7 +38,7 @@ const goalAskSchema = z
.regex(/^[\w-]{1,40}$/),
label: z.string().trim().min(1).max(120),
description: z.string().trim().max(600).optional(),
- effect: z.enum(['retry', 'retire']).optional(),
+ effect: z.enum(['retry', 'retire', 'retry_after_reset']).optional(),
})
.strict(),
)
diff --git a/apps/server/src/services/goal/manager/submit.ts b/apps/server/src/services/goal/manager/submit.ts
index 8bfbd93e732..bcf62e8f331 100644
--- a/apps/server/src/services/goal/manager/submit.ts
+++ b/apps/server/src/services/goal/manager/submit.ts
@@ -311,7 +311,7 @@ export const submitPlan = async (
throw new TRPCError({
code: 'BAD_REQUEST',
message:
- 'Every option of a takeover question needs an effect (retry or retire) for the blocked Task',
+ 'Every option of a takeover question needs an effect (retry, retry_after_reset or retire) for the blocked Task',
});
} else if (plan.action === 'escalate' && !state.problem && plan.ask) {
// A question with answers is asked, not parked: it opens a gate the
diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.ts
index b79aa02c4f5..1fb28e8ca33 100644
--- a/packages/prompts/src/chains/goalManager.test.ts
+++ b/packages/prompts/src/chains/goalManager.test.ts
@@ -28,7 +28,7 @@ describe('buildGoalManagerPrompt', () => {
'keeps supervision language tied to the goal rather than the English control prompt: %s',
(requirement) => {
const prompt = buildGoalManagerPrompt({ ...base, requirement });
- expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v14');
+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v15');
expect(cdataOf(prompt, 'requirement')).toBe(requirement);
expect(prompt).toContain('Use the language of the Goal requirement');
expect(prompt).toContain(
@@ -166,7 +166,7 @@ describe('buildGoalManagerPrompt', () => {
});
expect(prompt.split('\n')[0]).toBe(
- '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v14">',
+ '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v15">',
);
expect(prompt.endsWith('</goalTurn>')).toBe(true);
// CommonMark ends an HTML block at a blank line; the client needs one block.
diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.ts
index 56424629f21..682c4641a4d 100644
--- a/packages/prompts/src/chains/goalManager.ts
+++ b/packages/prompts/src/chains/goalManager.ts
@@ -27,8 +27,10 @@ import { GOAL_TURN_TAG } from '@lobechat/const';
* v14 lets that distill turn send probes back: a probe whose delivery falls
* short of the distilled plan is named in `rerun` and runs again on it before
* the gate judges the round.
+ * v15 adds the retry_after_reset effect, for an answer that
+ * promises to wait out a usage limit.
*/
-export const GOAL_MANAGER_PROMPT_VERSION = 'v14';
+export const GOAL_MANAGER_PROMPT_VERSION = 'v15';
export interface GoalManagerFeedbackNote {
/** `user`, or `agent <id>` for an agent-written comment. */
@@ -218,7 +220,7 @@ const contract = (input: GoalManagerPromptInput) =>
'{"action":"verify","reason":"why the existing evidence warrants independent Goal verification"}',
'{"action":"retry","taskId":"failed Task ID","failedOperationId":"latest confirmed failure ID","reason":"diagnosis and checkpoint-aware recovery instruction"}',
'{"action":"escalate","reason":"what you found and why only the owner can unblock it","ask":{"question":"the one decision the owner has to make, in the Goal language","options":[{"id":"waive","label":"short answer","description":"what happens if they choose it","effect":"retry"},{"id":"keep","label":"short answer","description":"what happens if they choose it","effect":"retire"}],"recommendedOptionId":"waive"}}',
- 'When you escalate, ask the actual decision with 2-4 concrete answers in "ask" instead of burying it in reason: the owner sees the question with your answers as buttons, your reason as the evidence, and your recommendation marked. When you are taking over a blocked Task, every option needs an effect: "retry" sends the Task back with the chosen answer as guidance, "retire" drops it. On an ordinary planning turn options need no effect; the owner\'s answer appears as a resolved decision in lh goal show on your next turn, and you plan from it. Name each option id after the answer itself (e.g. "waive"); retry, retire, fail, assume and answer are reserved for the coordinator and will be refused.',
+ 'When you escalate, ask the actual decision with 2-4 concrete answers in "ask" instead of burying it in reason: the owner sees the question with your answers as buttons, your reason as the evidence, and your recommendation marked. When you are taking over a blocked Task, every option needs an effect: "retry" sends the Task back now with the chosen answer as guidance, "retry_after_reset" keeps a Task stopped by a usage limit held and reruns it once the limit resets (use it for any answer that promises to wait, since "retry" starts a run immediately), "retire" drops it. On an ordinary planning turn options need no effect; the owner\'s answer appears as a resolved decision in lh goal show on your next turn, and you plan from it. Name each option id after the answer itself (e.g. "waive"); retry, retire, fail, assume and answer are reserved for the coordinator and will be refused.',
].join('\n');
export const buildGoalManagerPrompt = (input: GoalManagerPromptInput) => {
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 6f069e6ee9c..e8518bf491b 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -619,8 +619,10 @@ export type GoalDecisionStatus = 'pending' | 'resolved' | 'canceled';
* Coordinator options carry it implicitly through their fixed ids
* (`retry` / `retire` / `fail`); options the main Agent writes for its own
* question name it, so its wording never has to match a reserved id.
+ * `retry_after_reset` leaves a Task stopped by a usage limit held until the
+ * limit resets; `retry` sends it back now.
*/
-export type GoalDecisionOptionEffect = 'retry' | 'retire';
+export type GoalDecisionOptionEffect = 'retry' | 'retire' | 'retry_after_reset';
export interface GoalDecisionOption {
/**
diff --git a/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts b/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts
index 9dcc03a527d..e5e4934ac12 100644
--- a/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts
+++ b/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts
@@ -39,8 +39,14 @@ const COORDINATOR_EFFECTS = new Set<string>(['fail', 'retire', 'retry']);
export const effectOfOption = (
option: Pick<GoalDecisionOption, 'effect' | 'id'>,
-): DecisionEffect | undefined =>
- option.effect ?? (COORDINATOR_EFFECTS.has(option.id) ? (option.id as DecisionEffect) : undefined);
+): DecisionEffect | undefined => {
+ // Waiting for a reset still ends in a retry; the option's own words say when.
+ if (option.effect === 'retry_after_reset') return 'retry';
+ return (
+ option.effect ??
+ (COORDINATOR_EFFECTS.has(option.id) ? (option.id as DecisionEffect) : undefined)
+ );
+};
/**
* `labels` are the options as the reader should see them (already localized,