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(topic): clear the rate-limit error card when a scheduled continuation dispatches (#17208)

Arvin Xu269e8afc7e90
diff --git a/apps/server/src/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts b/apps/server/src/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts
index 697b0bb73d3..009e13e5435 100644
--- a/apps/server/src/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts
+++ b/apps/server/src/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts
@@ -6,10 +6,13 @@ import { scheduledTopicDispatch } from '../scheduledTopicDispatch';
const mocks = vi.hoisted(() => ({
claimScheduledTopic: vi.fn(),
clearScheduledRun: vi.fn(),
+ deleteMessage: vi.fn(),
execAgent: vi.fn(),
findById: vi.fn(),
getDueScheduledTopics: vi.fn(),
getServerDB: vi.fn(),
+ repointScheduledRunFailedMessage: vi.fn(),
+ updateMessage: vi.fn(),
}));
vi.mock('@/database/server', () => ({ getServerDB: mocks.getServerDB }));
@@ -19,12 +22,15 @@ vi.mock('@/database/models/topic', () => ({
claimScheduledTopic: mocks.claimScheduledTopic,
clearScheduledRun: mocks.clearScheduledRun,
getDueScheduledTopics: mocks.getDueScheduledTopics,
+ repointScheduledRunFailedMessage: mocks.repointScheduledRunFailedMessage,
},
}));
vi.mock('@/database/models/message', () => ({
MessageModel: class {
findById = mocks.findById;
+ update = mocks.updateMessage;
+ deleteMessage = mocks.deleteMessage;
},
}));
@@ -147,6 +153,95 @@ describe('scheduledTopicDispatch', () => {
);
});
+ it('clears the rate-limit error card before dispatch, keeping preserved work', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(resumeAfterRateLimit)]);
+ // The failed step streamed content before dying β†’ keep it, only drop the error.
+ mocks.findById.mockResolvedValue({
+ content: 'partial answer',
+ error: { body: { code: 'rate_limit' } },
+ id: 'assistant-failed',
+ });
+
+ await dispatch();
+
+ expect(mocks.updateMessage).toHaveBeenCalledWith('assistant-failed', { error: null });
+ expect(mocks.deleteMessage).not.toHaveBeenCalled();
+ // Cleanup runs first β€” the continuation must never stream in above a stale card.
+ expect(mocks.updateMessage.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.execAgent.mock.invocationCallOrder[0],
+ );
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ parentMessageId: 'assistant-failed' }),
+ );
+ });
+
+ it('deletes an error-only failed step and anchors the continuation on its parent', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(resumeAfterRateLimit)]);
+ // Nothing but the error (content is the loading placeholder, no tools).
+ mocks.findById.mockResolvedValue({
+ content: '...',
+ error: { body: { code: 'rate_limit' } },
+ id: 'assistant-failed',
+ parentId: 'user-message',
+ });
+
+ await dispatch();
+
+ expect(mocks.deleteMessage).toHaveBeenCalledWith('assistant-failed');
+ expect(mocks.updateMessage).not.toHaveBeenCalled();
+ expect(mocks.deleteMessage.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.execAgent.mock.invocationCallOrder[0],
+ );
+ // The deleted step can't anchor anything β€” chain onto its parent.
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ parentMessageId: 'user-message', resume: true }),
+ );
+ });
+
+ it('re-points the schedule at the dispatch-failure bubble so the retry cleans it too', async () => {
+ // A failed dispatch leaves a `ServerAgentRuntimeError` bubble on the
+ // placeholder execAgent created (finalizeHeteroDispatchError). Without
+ // re-pointing, the next successful retry would strand that bubble forever β€”
+ // the same stale-card bug this handler's cleanup exists to prevent.
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(resumeAfterRateLimit)]);
+ mocks.execAgent.mockResolvedValue({
+ assistantMessageId: 'assistant-dispatch-failed',
+ error: 'device offline',
+ success: false,
+ });
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ dispatched: 0 });
+ // Fenced on the dispatcher's claim lease β€” a stale attempt must not
+ // re-point a newer scheduled run.
+ expect(mocks.repointScheduledRunFailedMessage).toHaveBeenCalledWith(
+ {},
+ 'topic-1',
+ 'assistant-dispatch-failed',
+ mocks.claimScheduledTopic.mock.calls[0][2].id,
+ );
+ // The topic itself stays scheduled β€” the next tick retries.
+ expect(mocks.clearScheduledRun).not.toHaveBeenCalled();
+ });
+
+ it('retries from the user turn when the failed message is already gone', async () => {
+ // A prior tick cleaned the error-only step but its dispatch failed (device
+ // offline). The retry must not error out β€” it falls back to the user turn
+ // recorded in the payload.
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(resumeAfterRateLimit)]);
+ mocks.findById.mockResolvedValue(undefined);
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ dispatched: 1 });
+ expect(mocks.updateMessage).not.toHaveBeenCalled();
+ expect(mocks.deleteMessage).not.toHaveBeenCalled();
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ parentMessageId: 'user-message', resume: true }),
+ );
+ });
+
it('leaves the topic scheduled when dispatch fails, so the next tick retries', async () => {
mocks.getDueScheduledTopics.mockResolvedValue([topic(delayedStart)]);
mocks.execAgent.mockResolvedValue({ error: 'device offline', success: false });
@@ -155,6 +250,8 @@ describe('scheduledTopicDispatch', () => {
await expect(response.json()).resolves.toMatchObject({ claimed: 1, dispatched: 0 });
expect(mocks.clearScheduledRun).not.toHaveBeenCalled();
+ // Only the resume kind has a cleanup phase to hand the bubble to.
+ expect(mocks.repointScheduledRunFailedMessage).not.toHaveBeenCalled();
});
it('dispatches a continuation parked by the pre-`kind` version, rather than discarding it', async () => {
diff --git a/apps/server/src/workflows-hono/task/handlers/scheduledRunKinds.ts b/apps/server/src/workflows-hono/task/handlers/scheduledRunKinds.ts
index 77864466722..afe3ffb28ee 100644
--- a/apps/server/src/workflows-hono/task/handlers/scheduledRunKinds.ts
+++ b/apps/server/src/workflows-hono/task/handlers/scheduledRunKinds.ts
@@ -1,13 +1,16 @@
-import { HETERO_CONTINUE_PROMPT } from '@lobechat/const';
+import { HETERO_CONTINUE_PROMPT, LOADING_FLAT } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
import type { ExecAgentResult, TopicScheduledRun, TopicScheduledRunKind } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
import type { TopicItem } from '@/database/schemas/topic';
import { AiAgentService } from '@/server/services/aiAgent';
export interface ScheduledRunContext {
+ /** The dispatcher's claim lease id β€” fences post-dispatch writes against stale attempts. */
+ claimId: string;
db: LobeChatDatabase;
topic: TopicItem;
workspaceId?: string;
@@ -23,27 +26,67 @@ type ScheduledRunHandlers = {
/**
* Resume a heterogeneous turn that was parked when the provider rate-limited it.
*
- * Mirrors `continueHeteroAfterError`: resume the surviving CLI session from the
- * assistant-chain tail with the shared continuation instruction. The failed turn
- * is deliberately NOT deleted before dispatch β€” a dispatch failure must leave the
- * user's error card and retry entry intact.
+ * Mirrors `continueHeteroAfterError` β€” including its ordering: the stale
+ * rate-limit card is cleared BEFORE dispatch. A step that preserved work
+ * (streamed content / tool calls) keeps its body and only drops the error; an
+ * error-only step would render as an empty block, so it is deleted and the
+ * continuation anchors on its parent instead. Then the surviving CLI session is
+ * resumed from that anchor with the shared continuation instruction.
+ *
+ * If dispatch fails (e.g. device offline) the topic stays `scheduled` and the
+ * next tick retries; by then the failed message may already be cleaned or gone,
+ * so a missing message is not an error β€” the retry falls back to anchoring on
+ * the user turn recorded in the payload.
*/
const runResumeAfterRateLimit: ScheduledRunHandlers['resume_after_rate_limit'] = async (
run,
- { db, topic, workspaceId },
+ { claimId, db, topic, workspaceId },
) => {
const messageModel = new MessageModel(db, topic.userId, workspaceId);
const failedMessage = await messageModel.findById(run.failedAssistantMessageId);
- if (!failedMessage) throw new Error('Scheduled continuation message no longer exists');
- return new AiAgentService(db, topic.userId, { workspaceId }).execAgent({
+ let parentMessageId = run.userMessageId;
+ if (failedMessage) {
+ const hasSalvageableWork =
+ (Array.isArray(failedMessage.tools) && failedMessage.tools.length > 0) ||
+ (!!failedMessage.content && failedMessage.content !== LOADING_FLAT);
+
+ if (hasSalvageableWork) {
+ await messageModel.update(failedMessage.id, { error: null });
+ parentMessageId = failedMessage.id;
+ } else {
+ await messageModel.deleteMessage(failedMessage.id);
+ parentMessageId = failedMessage.parentId ?? run.userMessageId;
+ }
+ }
+
+ const result = await new AiAgentService(db, topic.userId, { workspaceId }).execAgent({
agentId: topic.agentId ?? undefined,
appContext: { topicId: topic.id },
- parentMessageId: failedMessage.id,
+ parentMessageId,
prompt: HETERO_CONTINUE_PROMPT,
resume: true,
trigger: RequestTrigger.Cron,
});
+
+ // A dispatch that fails inside execAgent (device offline, access denied, …)
+ // leaves its own error bubble on the placeholder it created
+ // (`finalizeHeteroDispatchError`) β€” the user still sees why the continuation
+ // didn't fire. Track that bubble as the run's failed message so the next
+ // tick's pre-dispatch cleanup clears it exactly like the original card;
+ // otherwise every failed attempt would strand one more stale error card.
+ // Fenced on our claim lease: an attempt that outlived it (or whose schedule
+ // was cancelled and re-armed) must not re-point a newer run.
+ if (!result.success && result.assistantMessageId) {
+ await TopicModel.repointScheduledRunFailedMessage(
+ db,
+ topic.id,
+ result.assistantMessageId,
+ claimId,
+ );
+ }
+
+ return result;
};
/**
diff --git a/apps/server/src/workflows-hono/task/handlers/scheduledTopicDispatch.ts b/apps/server/src/workflows-hono/task/handlers/scheduledTopicDispatch.ts
index 3249ad209c5..763c3eb6e41 100644
--- a/apps/server/src/workflows-hono/task/handlers/scheduledTopicDispatch.ts
+++ b/apps/server/src/workflows-hono/task/handlers/scheduledTopicDispatch.ts
@@ -94,7 +94,12 @@ export async function scheduledTopicDispatch(c: Context) {
const workspaceId = topic.workspaceId ?? undefined;
try {
- const result = await dispatchScheduledRun(run, { db, topic, workspaceId });
+ const result = await dispatchScheduledRun(run, {
+ claimId: claim.id,
+ db,
+ topic,
+ workspaceId,
+ });
if (!result.success) {
throw new Error(result.error || result.message || 'Scheduled run dispatch failed');
}
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index c66626af369..76b9b2ec5bf 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -908,5 +908,89 @@ describe('TopicModel', () => {
expect(cleared.status).toBe('running');
expect(cleared.metadata?.scheduledRun).toBeNull();
});
+
+ it('re-points a pending run at a new failed message, preserving the claim and payload', async () => {
+ await serverDB.insert(topics).values({
+ id: 'scheduled-repoint',
+ metadata: {
+ scheduledRun: { ...scheduledRun, claim: { claimedAt: '', expiresAt: '', id: 'claim-1' } },
+ },
+ status: 'scheduled',
+ title: 'repoint',
+ userId,
+ });
+
+ await TopicModel.repointScheduledRunFailedMessage(
+ serverDB,
+ 'scheduled-repoint',
+ 'assistant-retry-1',
+ 'claim-1',
+ );
+
+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, 'scheduled-repoint'));
+ // Only the failed-message pointer moves β€” the lease and the rest of the
+ // payload must survive the merge.
+ expect(row.metadata?.scheduledRun).toMatchObject({
+ claim: { id: 'claim-1' },
+ failedAssistantMessageId: 'assistant-retry-1',
+ kind: 'resume_after_rate_limit',
+ runAt: scheduledRun.runAt,
+ userMessageId: 'user-message',
+ });
+ });
+
+ it('does not let a stale dispatch attempt re-point a re-armed schedule', async () => {
+ // The failed attempt's claim lease expired and the user (or a newer tick)
+ // re-armed / re-claimed the schedule β€” the old writer must lose.
+ await serverDB.insert(topics).values({
+ id: 'scheduled-reclaimed',
+ metadata: {
+ scheduledRun: { ...scheduledRun, claim: { claimedAt: '', expiresAt: '', id: 'new' } },
+ },
+ status: 'scheduled',
+ title: 'reclaimed',
+ userId,
+ });
+
+ await TopicModel.repointScheduledRunFailedMessage(
+ serverDB,
+ 'scheduled-reclaimed',
+ 'assistant-stale-attempt',
+ 'old',
+ );
+
+ const [row] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, 'scheduled-reclaimed'));
+ expect(row.metadata?.scheduledRun).toMatchObject({
+ claim: { id: 'new' },
+ failedAssistantMessageId: 'assistant-failed',
+ });
+ });
+
+ it('does not resurrect a cancelled schedule when re-pointing', async () => {
+ await serverDB.insert(topics).values({
+ id: 'scheduled-cancelled',
+ metadata: { scheduledRun: null },
+ status: 'active',
+ title: 'cancelled',
+ userId,
+ });
+
+ await TopicModel.repointScheduledRunFailedMessage(
+ serverDB,
+ 'scheduled-cancelled',
+ 'assistant-retry-2',
+ 'claim-1',
+ );
+
+ const [row] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, 'scheduled-cancelled'));
+ expect(row.metadata?.scheduledRun).toBeNull();
+ expect(row.status).toBe('active');
+ });
});
});
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 5da2c39424d..27d0a76e218 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1538,4 +1538,53 @@ export class TopicModel {
.where(eq(topics.id, id));
});
}
+
+ /**
+ * Re-point a still-pending scheduled run at a new failed-attempt message. A
+ * dispatch that fails inside execAgent leaves its own error bubble on the
+ * placeholder it created; tracking that bubble as the run's
+ * `failedAssistantMessageId` lets the next tick's pre-dispatch cleanup clear
+ * it the same way it clears the original card, so retries don't strand one
+ * stale error bubble per failed attempt.
+ *
+ * `expectedClaimId` fences stale writers the same way it does in
+ * {@link TopicModel.clearScheduledRun}: a dispatch attempt that outlived its
+ * claim lease β€” or one whose schedule the user cancelled and re-armed β€” must
+ * not overwrite the pointer of a NEWER scheduled run, or the next cleanup
+ * would delete / anchor against an unrelated message. No-ops when the
+ * schedule was cleared or the claim no longer matches.
+ */
+ static async repointScheduledRunFailedMessage(
+ db: LobeChatDatabase,
+ id: string,
+ failedAssistantMessageId: string,
+ expectedClaimId: string,
+ ): Promise<void> {
+ await db.transaction(async (tx) => {
+ const [row] = await tx
+ .select({ metadata: topics.metadata, status: topics.status })
+ .from(topics)
+ .where(eq(topics.id, id))
+ .for('update');
+ if (!row || row.status !== 'scheduled') return;
+
+ const scheduledRun = row.metadata?.scheduledRun;
+ if (!scheduledRun) return;
+ if (scheduledRun.claim?.id !== expectedClaimId) return;
+
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...row.metadata,
+ scheduledRun: {
+ ...scheduledRun,
+ failedAssistantMessageId,
+ updatedAt: new Date().toISOString(),
+ },
+ } as ChatTopicMetadata,
+ })
+ .where(eq(topics.id, id));
+ });
+ }
}