π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-runtime): auto-recover operations whose host died mid-step (#19160)
Arvin Xub8ef62da87ad
diff --git a/apps/server/src/router-hono/agent/handlers/reapOperations.ts b/apps/server/src/router-hono/agent/handlers/reapOperations.tsnew file mode 100644index 00000000000..bf10cd049b2--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/reapOperations.ts@@ -0,0 +1,59 @@+import debug from 'debug';+import type { Context } from 'hono';++import { getServerDB } from '@/database/core/db-adaptor';+import { StaleOperationReaper } from '@/server/services/agentRuntime';++const log = debug('lobe-server:agent:reap-operations');++/**+ * Vercel cron entry point for recovering operations whose executing host died+ * mid-step β see {@link StaleOperationReaper}.+ *+ * Auth: `bearerSecretAuth(CRON_SECRET)` on the route, matching the existing+ * `/api/agent/gateway` cron.+ *+ * Query params (all optional, mainly for manual runs and incident response):+ * - `staleAfterMs` β override the lease window+ * - `limit` β cap the operations examined in this tick+ * - `maxRedriveAttempts` β override the per-operation redrive budget+ */+export async function reapOperations(c: Context): Promise<Response> {+ const startedAt = Date.now();++ const num = (name: string): number | undefined => {+ const raw = c.req.query(name);+ if (raw === undefined) return undefined;+ const parsed = Number(raw);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;+ };++ try {+ const serverDB = await getServerDB();+ const result = await new StaleOperationReaper(serverDB).sweep({+ limit: num('limit'),+ maxRedriveAttempts: num('maxRedriveAttempts'),+ staleAfterMs: num('staleAfterMs'),+ });++ log('sweep completed in %dms: %O', Date.now() - startedAt, result);++ // A tick where every candidate failed is an outage (Redis, database or+ // queue down), not a quiet sweep: answer 5xx so cron monitoring alerts while+ // the operations stay stuck. A partial failure is one poisoned row among+ // healthy recoveries, so it stays 2xx but still reports `success: false`.+ const allFailed = result.examined > 0 && result.failed === result.examined;+ if (result.failed > 0)+ console.error('[reap-operations] %d candidate(s) failed: %O', result.failed, result);++ return c.json(+ { ...result, executionTime: Date.now() - startedAt, success: result.failed === 0 },+ allFailed ? 500 : 200,+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : 'unknown error';+ console.error('[reap-operations] %O', error);++ return c.json({ error: message, executionTime: Date.now() - startedAt, success: false }, 500);+ }+}diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.tsindex 802a08f0812..101a0a0f819 100644--- a/apps/server/src/router-hono/agent/index.ts+++ b/apps/server/src/router-hono/agent/index.ts@@ -13,6 +13,7 @@ import { messengerInstall } from './handlers/messengerInstall';import { messengerOAuthCallback } from './handlers/messengerOAuthCallback';import { messengerWebhook } from './handlers/messengerWebhook';import { platformWebhook } from './handlers/platformWebhook';+import { reapOperations } from './handlers/reapOperations';import { runStep, runStepHealth } from './handlers/runStep';import { subAgentCallback } from './handlers/subAgentCallback';import { toolResult } from './handlers/toolResult';@@ -58,6 +59,13 @@ app.get(gatewayCron,);+// GET /api/agent/reap-operations β Vercel cron entry point (Bearer CRON_SECRET)+app.get(+ '/reap-operations',+ bearerSecretAuth(() => process.env.CRON_SECRET),+ reapOperations,+);+// POST /api/agent/gateway/start β non-Vercel ensureRunning (Bearer KEY_VAULTS_SECRET)app.post('/gateway/start',diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex 9adc2531c67..de949759d64 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -4,7 +4,7 @@ import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';import type { ChatMessageError } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';import debug from 'debug';-import { and, desc, eq, gte, lte, or } from 'drizzle-orm';+import { and, desc, eq, gt, gte, isNull, lte, ne, or, sql } from 'drizzle-orm';import { AgentOperationModel } from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';@@ -104,7 +104,17 @@ export class AbandonOperationService {this.traceRecorder = new OperationTraceRecorder(this.snapshotStore);}- async finalizeAbandoned(operationId: string, reason: string): Promise<FinalizeAbandonedResult> {+ /**+ * @param options.settledAsAbandoned Set when the caller already retired the+ * durable row with its own compare-and-set (`settleStaleRunning`) and only+ * wants the side effects. The lifecycle then persists onto that status rather+ * than racing it, so `onComplete` / `onError` still fire.+ */+ async finalizeAbandoned(+ operationId: string,+ reason: string,+ options?: { settledAsAbandoned?: boolean },+ ): Promise<FinalizeAbandonedResult> {const result: FinalizeAbandonedResult = {assistantMessageUpdated: false,finalized: false,@@ -169,19 +179,53 @@ export class AbandonOperationService {// path must opt in when this flag is present.const includeShareVisitor = Boolean(metadata.streamOwnerUserId);- if (origin.userId && metadata.assistantMessageId) {+ if (origin.userId) {+ const messageModel = new MessageModel(this.db, origin.userId, origin.workspaceId, undefined, {+ includeShareVisitor,+ });+try {- const messageModel = new MessageModel(- this.db,- origin.userId,- origin.workspaceId,- undefined,- { includeShareVisitor },- );- await messageModel.update(metadata.assistantMessageId, { error });- result.assistantMessageUpdated = true;+ if (metadata.assistantMessageId) {+ // The dying step got as far as creating its placeholder, so the+ // failure belongs on exactly that row.+ await messageModel.update(metadata.assistantMessageId, { error });+ result.assistantMessageUpdated = true;+ } else if (origin.topicId && !(await this.topicMovedOn(operationId, origin))) {+ // No placeholder: the step was killed before its first token, which+ // is the usual shape when the host is recycled mid-LLM-call. The+ // turn would otherwise carry no error anywhere, and the client keys+ // its failure banner and retry action off `message.error` β that+ // silence is exactly why an abandoned turn renders as frozen rather+ // than failed.+ //+ // A fresh assistant row rather than marking the conversation tail:+ // the tail here is either the user's own turn, whose renderer reads+ // `error` for nothing but the double-click-to-edit guard and so+ // would show the user nothing at all, or a *previous* assistant turn+ // that genuinely succeeded and must not be relabelled as failed.+ await messageModel.create({+ agentId: origin.agentId,+ content: '',+ error,+ parentId: await this.resolveTailMessageId(+ {+ threadId: origin.threadId,+ topicId: origin.topicId,+ userId: origin.userId,+ workspaceId: origin.workspaceId,+ },+ includeShareVisitor,+ ),+ model: state.modelRuntimeConfig?.model,+ provider: state.modelRuntimeConfig?.provider,+ role: 'assistant',+ threadId: origin.threadId ?? null,+ topicId: origin.topicId,+ });+ result.assistantMessageUpdated = true;+ }} catch (e) {- log('[%s] assistant message update failed (non-fatal): %O', operationId, e);+ log('[%s] assistant failure row write failed (non-fatal): %O', operationId, e);}}@@ -201,6 +245,7 @@ export class AbandonOperationService {await new CompletionLifecycle(this.db, origin.userId, origin.workspaceId, {includeShareVisitor,}).dispatchHooks(operationId, finalState, 'error', {+ settledAsAbandoned: options?.settledAsAbandoned,skipErrorMessageWrite: result.assistantMessageUpdated,});} catch (e) {@@ -208,6 +253,32 @@ export class AbandonOperationService {}}+ // Safety net for the durable row. `dispatchHooks` owns the rich terminal+ // write (step count, usage, cost, traceS3Key) via `persistCompletion`, but+ // it only runs behind the guard above: a sub-agent, a missing+ // `origin.userId`, or a state whose `status` is not one of+ // running/waiting_* (e.g. a step boundary persisted as `idle`) all skip it+ // silently, and a throw inside it is swallowed as non-fatal. Any of those+ // used to leave the operation `running` forever β nothing else retires a+ // non-Goal op, so it stayed live on the dashboard and blocked its own+ // recovery. `settleRunning` is idempotent and only matches rows still in+ // `running`, so it cannot overwrite the richer outcome when the dispatch+ // did happen.+ if (origin.userId) {+ try {+ const settled = await new AgentOperationModel(+ this.db,+ origin.userId,+ origin.workspaceId,+ ).settleRunning(operationId, 'error');+ if (settled) {+ log('[%s] durable row settled by abandon safety net', operationId);+ }+ } catch (e) {+ log('[%s] abandon safety-net settle failed (non-fatal): %O', operationId, e);+ }+ }+// Resolve sub-agent β parent linkage. The watchdog killed this op without// firing its onComplete bridge, so a parent parked on `callSubAgent` would// otherwise wait on this slot forever. We surface the ids the caller needs@@ -389,6 +460,83 @@ export class AbandonOperationService {}}+ /**+ * Anchor for an abandonment error when the dying step never created its own+ * assistant placeholder: the latest main-chain message of the run.+ *+ * Reuses the same spine query the runtime itself uses to pick a turn's+ * continuation point, so the error lands on the node the client is actually+ * rendering as the tail rather than on a tool child or a stale fork.+ */+ private async resolveTailMessageId(+ params: { threadId?: string | null; topicId: string; userId: string; workspaceId?: string },+ includeShareVisitor: boolean,+ ): Promise<string | undefined> {+ try {+ const messageModel = new MessageModel(this.db, params.userId, params.workspaceId, undefined, {+ includeShareVisitor,+ });+ return await messageModel.getLatestSpineMessageId({+ threadId: params.threadId ?? null,+ topicId: params.topicId,+ });+ } catch (e) {+ log('[%s] tail message lookup failed (non-fatal): %O', params.topicId, e);+ return undefined;+ }+ }++ /**+ * Whether a newer run has started on this conversation since the abandoned+ * one, which means the spine tail now belongs to that run, not to this one.+ *+ * The fallback failure row is anchored to the tail, so writing it after the+ * user has moved on would graft this run's error under the newer turn β and+ * an interactive start overwrites `runningOperation` rather than waiting, so+ * the topic marker alone cannot tell (a newer run that already finished has+ * cleared it too). The durable operation rows can: any top-level operation+ * on the same topic/thread created after this one. The abandoned run's own+ * sub-agent children are excluded, since they extend its turn.+ *+ * Fails closed: on a lookup error the row is not written, because a missing+ * error bubble is recoverable (the durable row still settles) and a failure+ * grafted onto the active branch is not.+ */+ private async topicMovedOn(+ operationId: string,+ origin: { threadId?: string; topicId?: string; userId?: string },+ ): Promise<boolean> {+ if (!origin.topicId || !origin.userId) return true;+ try {+ const newer = await (this.db as any).query?.agentOperations?.findFirst({+ columns: { id: true },+ where: and(+ eq(agentOperations.topicId, origin.topicId),+ eq(agentOperations.userId, origin.userId),+ origin.threadId+ ? eq(agentOperations.threadId, origin.threadId)+ : isNull(agentOperations.threadId),+ ne(agentOperations.id, operationId),+ or(+ isNull(agentOperations.parentOperationId),+ ne(agentOperations.parentOperationId, operationId),+ ),+ // Own alias on purpose: the relational query aliases the outer table,+ // and interpolated columns in the subquery would resolve against that+ // alias and compare each row with itself.+ gt(+ agentOperations.createdAt,+ sql`(select self.created_at from agent_operations self where self.id = ${operationId})`,+ ),+ ),+ });+ return Boolean(newer);+ } catch (e) {+ log('[%s] newer-run lookup failed, not writing a fallback row: %O', operationId, e);+ return true;+ }+ }+private async findOperationRow(operationId: string) {try {return await (this.db as any).query?.agentOperations?.findFirst({diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 24a517a45ef..9c3b54a2c2d 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -156,6 +156,14 @@ export interface OperationCompletionInput {/** Options shared by {@link CompletionLifecycle.completeOperation} / `dispatchHooks`. */export interface CompleteOperationOptions {+ /**+ * The durable row was already retired to `abandoned` / `lease_expired` by the+ * caller's own compare-and-set (`settleStaleRunning`). Persist the terminal+ * stats onto that status instead of `error`: `recordCompletion` refuses to+ * move a row out of one terminal status into another, so writing `error`+ * would be rejected and the hooks below would never fire.+ */+ settledAsAbandoned?: boolean;/*** Skip writing the terminal error onto the assistant message row. Set by callers* that already wrote a bespoke error bubble before delegating (e.g. the hetero@@ -352,13 +360,15 @@ export class CompletionLifecycle {operationId: string,state: any,reason: string,+ settledAsAbandoned?: boolean,): Promise<boolean> {- const completionReason: any =- reason === 'max_steps' ||- reason === 'cost_limit' ||- reason === 'tool_call_repeat_limit' ||- reason === 'waiting_for_human' ||- reason === 'waiting_for_async_tool'+ const completionReason: any = settledAsAbandoned+ ? 'lease_expired'+ : reason === 'max_steps' ||+ reason === 'cost_limit' ||+ reason === 'tool_call_repeat_limit' ||+ reason === 'waiting_for_human' ||+ reason === 'waiting_for_async_tool'? reason: this.statusForReason(reason);@@ -372,11 +382,12 @@ export class CompletionLifecycle {? Date.now() - new Date(state.createdAt).getTime(): null;- const status = this.statusForReason(reason);+ const runtimeStatus = this.statusForReason(reason);+ const status = settledAsAbandoned ? ('abandoned' as const) : runtimeStatus;// Parked statuses are pauses, not true terminal states β leave completedAt// null so analytics doesn't read a paused op as completed. The next// dispatchHooks call (when the op resumes and truly ends) overwrites both.- const completedAt = isParkedStatus(status) ? undefined : new Date();+ const completedAt = isParkedStatus(runtimeStatus) ? undefined : new Date();// Fold every child operation's spend (callSubAgent children, isolated group// members) into the parent's totals, so an op's row accounts for the whole@@ -928,7 +939,12 @@ export class CompletionLifecycle {// Finalize the agent_operations row before user hooks fire so// downstream consumers see the row in its terminal shape.- const completionAccepted = await this.persistCompletion(operationId, state, reason);+ const completionAccepted = await this.persistCompletion(+ operationId,+ state,+ reason,+ options?.settledAsAbandoned,+ );if (completionAccepted === false) {log('[%s] Skipping hooks for an operation with a conflicting terminal owner', operationId);return;diff --git a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts b/apps/server/src/services/agentRuntime/StaleOperationReaper.tsnew file mode 100644index 00000000000..53e7142abff--- /dev/null+++ b/apps/server/src/services/agentRuntime/StaleOperationReaper.ts@@ -0,0 +1,394 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';+import { and, asc, eq, isNull, lt, or } from 'drizzle-orm';+import urlJoin from 'url-join';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { agentOperations } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';+import { QueueService } from '@/server/services/queue';++import { AbandonOperationService } from './AbandonOperationService';++const log = debug('lobe-server:stale-operation-reaper');++/**+ * How long an operation may go without refreshing its durable liveness lease+ * before this sweep treats it as dead.+ *+ * `AgentRuntimeService.startStepLockHeartbeat` touches the row every+ * `STEP_LOCK_HEARTBEAT_MS * DURABLE_LEASE_HEARTBEAT_EVERY_TICKS` = 90s while a+ * step holds the step lock, so five minutes is three missed beats: comfortably+ * past jitter, and far tighter than the 30-minute in-flight window the gateway+ * watchdog has to use (it can only reason about stream events, which stop for+ * legitimately slow first-token latency too).+ */+const DEFAULT_STALE_AFTER_MS = 5 * 60_000;++/**+ * Redriving costs a real LLM call, so a step that dies deterministically+ * (poison payload, an input that reliably OOMs the host) must not be retried+ * forever. Past this budget the operation is abandoned with a user-visible+ * error instead.+ */+const DEFAULT_MAX_REDRIVE_ATTEMPTS = 3;++/** Bound the work of a single cron tick so one sweep cannot run long. */+const DEFAULT_LIMIT = 50;++export interface ReapStaleOperationsParams {+ limit?: number;+ maxRedriveAttempts?: number;+ staleAfterMs?: number;+}++export interface ReapStaleOperationsResult {+ /** Operations retired with a user-visible error (budget spent, or no context). */+ abandoned: number;+ /** Candidates whose lease was refreshed between select and claim. */+ alive: number;+ examined: number;+ /**+ * Candidates whose recovery threw (Redis, database or queue failure). Reported+ * so a sweep that recovered nothing is visible to whatever polls the endpoint,+ * rather than looking identical to a quiet tick.+ */+ failed: number;+ /** Operations whose next step was re-queued. */+ redriven: number;+ /** Candidates this sweep has no authority over β see `recover`. */+ skipped: number;+}++/**+ * Periodic recovery for operations whose executing host died mid-step.+ *+ * A serverless instance can be recycled while it owns a step. When that+ * happens nothing else notices: QStash already ACKed the delivery that started+ * the step (so it never redelivers), the step lock simply expires, and only+ * `services/goal` ever calls `settleStaleRunning` β a chat/bot/task operation+ * has no reaper at all. The row stays `running` forever and the conversation+ * freezes with no error and no way to resume.+ *+ * This sweep closes that hole from the durable side, and prefers *resuming*+ * over reporting: the runtime keeps its resumable state in Redis, so as long+ * as that state is still alive the correct recovery is to re-queue the next+ * step and let the run continue where it stopped. Only when the state is gone+ * (or the redrive budget is spent) does it fall back to abandoning the+ * operation with a visible error the user can retry from.+ *+ * Safety comes from three existing mechanisms rather than new bookkeeping:+ * - `claimStaleRedrive` consumes the candidate in the same UPDATE that selects+ * it, so overlapping ticks cannot both re-queue one step.+ * - `tryClaimStep` arbitrates against a host that turns out to be alive after+ * all: the redelivered step loses the lock race and returns without running.+ * - `executeStep` ACKs deliveries for operations already in a terminal state,+ * so a redrive that races a completion is a no-op.+ */+export class StaleOperationReaper {+ private readonly coordinator: AgentRuntimeCoordinator;+ private readonly queueService: QueueService | null;++ constructor(+ private readonly db: LobeChatDatabase,+ options?: { coordinator?: AgentRuntimeCoordinator; queueService?: QueueService | null },+ ) {+ this.coordinator = options?.coordinator ?? new AgentRuntimeCoordinator();+ this.queueService =+ options?.queueService === null ? null : (options?.queueService ?? new QueueService());+ }++ private get baseURL() {+ const baseUrl = process.env.AGENT_RUNTIME_BASE_URL || process.env.APP_URL;++ return urlJoin(baseUrl || 'http://localhost:3010', '/api/agent');+ }++ async sweep(params?: ReapStaleOperationsParams): Promise<ReapStaleOperationsResult> {+ const staleAfterMs = params?.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;+ const maxRedriveAttempts = params?.maxRedriveAttempts ?? DEFAULT_MAX_REDRIVE_ATTEMPTS;+ const limit = params?.limit ?? DEFAULT_LIMIT;+ const staleBefore = new Date(Date.now() - staleAfterMs);++ const candidates = await this.listStaleRunning(staleBefore, limit);+ const result: ReapStaleOperationsResult = {+ abandoned: 0,+ alive: 0,+ examined: candidates.length,+ failed: 0,+ redriven: 0,+ skipped: 0,+ };++ for (const candidate of candidates) {+ try {+ const outcome = await this.recover(candidate, staleBefore, maxRedriveAttempts);+ result[outcome] += 1;+ } catch (e) {+ // One poisoned row must not abort the rest of the sweep.+ result.failed += 1;+ log('[%s] recovery failed: %O', candidate.id, e);+ }+ }++ log('sweep done: %O', result);+ return result;+ }++ /**+ * Stale candidates across all tenants. Queried directly rather than through+ * `AgentOperationModel`, which is user-scoped by construction β this is a+ * system-level sweep, and the per-operation mutations below re-enter the+ * model with the row's own owner so ownership is still enforced where it+ * matters.+ */+ private async listStaleRunning(staleBefore: Date, limit: number) {+ return (+ this.db+ // Only what recovery needs: everything else about the run is read from+ // the coordinator state, and the abandon path re-reads the row itself.+ .select({+ id: agentOperations.id,+ userId: agentOperations.userId,+ workspaceId: agentOperations.workspaceId,+ })+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.status, 'running'),+ lt(agentOperations.updatedAt, staleBefore),+ // A never-heartbeated row is only meaningful once it is older than+ // the window too; `startedAt` is the lease's initial value.+ or(isNull(agentOperations.startedAt), lt(agentOperations.startedAt, staleBefore)),+ ),+ )+ // Oldest first: a backlog should drain in the order it accumulated, and+ // it keeps the tick deterministic when `limit` truncates.+ .orderBy(asc(agentOperations.updatedAt))+ .limit(limit)+ );+ }++ private async recover(+ candidate: { id: string; userId: string; workspaceId: string | null },+ staleBefore: Date,+ maxRedriveAttempts: number,+ ): Promise<'abandoned' | 'alive' | 'redriven' | 'skipped'> {+ const operationId = candidate.id;+ const operationModel = new AgentOperationModel(+ this.db,+ candidate.userId,+ candidate.workspaceId ?? undefined,+ );++ // Everything that decides *whether* to act is read before the claim, so a+ // candidate this sweep cannot help never consumes an attempt.+ const state = await this.coordinator.loadAgentState(operationId).catch((e) => {+ log('[%s] state load failed, treating as unresumable: %O', operationId, e);+ return null;+ });++ // No coordinator state means this sweep has no authority over the run.+ // Crucially that is the shape of a *healthy* heterogeneous operation: a+ // Claude Code / Codex run is driven by an external CLI, never creates+ // coordinator state, and only refreshes its lease when `heteroIngest`+ // batches arrive β so a single long tool call reads as "stale" here.+ // Retiring one would be actively destructive rather than merely useless:+ // `heteroIngest` bails out on `touchRunning` returning false, so every+ // subsequent batch of a live session would be dropped before persistence.+ //+ // Stateless-but-genuinely-dead operations are the inactivity watchdog's+ // job (it reaches them through `finalize-abandoned`), and it has the+ // gateway-side evidence to tell the two apart. This sweep deliberately+ // limits itself to runs it can actually resume.+ if (!state || !this.queueService) return 'skipped';++ // Parked operations have their own resume paths; a plain step would run+ // past whatever they are waiting on.+ if (!this.canRedrive(state)) return 'skipped';++ // `stepCount` is the number of completed steps, so it is also the index of+ // the step that never finished.+ const stepIndex = state.stepCount;++ // The context is NOT optional in practice. `runtime.step` falls back to+ // `createInitialContext(state)` when it gets none, which re-enters the run+ // at `user_input` β so a step that owed a `tool_result` / graph+ // continuation would instead start a fresh LLM turn and silently drop the+ // pending work. Recover the real one, and refuse to redrive without it:+ // abandoning with a visible error is recoverable, corrupting the run is+ // not.+ const context = await this.resolveRedriveContext(operationId, state, stepIndex);+ if (!context) {+ // Skipped rather than abandoned, because "no context" is not a reliable+ // signal: `AgentStateManager.getExecutionHistory` swallows a failed+ // LRANGE or a JSON parse error and returns an empty array, so a+ // transient Redis blip is indistinguishable here from a genuinely+ // missing entry. Retiring an operation is irreversible and user-visible,+ // and this one is otherwise resumable β a later tick may well recover it+ // once the read succeeds, and the inactivity watchdog still declares it+ // dead if it never does.+ log('[%s][%d] no persisted context to resume from', operationId, stepIndex);+ return 'skipped';+ }++ const attempt = await operationModel.claimStaleRedrive(+ operationId,+ staleBefore,+ maxRedriveAttempts,+ );++ if (attempt === null) {+ // Either a heartbeat landed while we were reading state (the step is+ // alive and owns itself again) or the redrive budget is spent. The CAS+ // below distinguishes them without a separate read: only a row that is+ // still both running and past its lease can be retired.+ return this.abandonIfStillStale(+ operationModel,+ operationId,+ staleBefore,+ 'redrive_exhausted',+ );+ }++ try {+ await this.queueService.scheduleMessage({+ context,+ // Distinct per attempt: a shared key would let the provider dedupe a+ // genuinely needed second redrive away and strand the operation again.+ deduplicationId: `stale-redrive:${operationId}:${stepIndex}:${attempt}`,+ endpoint: urlJoin(this.baseURL, '/run'),+ operationId,+ priority: 'normal',+ retryDelay:+ typeof state.metadata?.queueRetryDelay === 'string'+ ? state.metadata.queueRetryDelay+ : undefined,+ retries:+ typeof state.metadata?.queueRetries === 'number'+ ? state.metadata.queueRetries+ : undefined,+ stepIndex,+ });+ } catch (e) {+ // The attempt was claimed before publishing, because the claim is also+ // the mutual exclusion between overlapping sweeps. Publishing is what it+ // was claimed *for*, so a failure has to give it back β the budget+ // bounds LLM spend, and nothing was spent. Without this, a brief queue+ // outage walks a healthy operation to its limit and retires it having+ // never attempted a single recovery.+ await operationModel.releaseStaleRedrive(operationId, attempt).catch((releaseError) => {+ log('[%s] failed to release redrive attempt %d: %O', operationId, attempt, releaseError);+ });+ throw e;+ }++ log('[%s][%d] redriven (attempt %d/%d)', operationId, stepIndex, attempt, maxRedriveAttempts);+ return 'redriven';+ }++ /**+ * The context the interrupted step should have received.+ *+ * Step 0 carries the context the operation was created with, which the+ * runtime persists onto the state β the same field the intervention+ * continuation re-publishes from. Every later step is driven by the+ * `nextContext` its predecessor produced, which `saveStepResult` stores+ * alongside the step in the execution history under the *producing* step's+ * index (so step N's entry holds the context for step N+1).+ *+ * Returns undefined rather than a synthesized fallback: the caller must be+ * able to tell "resume correctly" from "cannot resume".+ */+ private async resolveRedriveContext(+ operationId: string,+ state: AgentState,+ stepIndex: number,+ ): Promise<AgentRuntimeContext | undefined> {+ if (stepIndex === 0) {+ return (state as AgentState & { initialContext?: AgentRuntimeContext }).initialContext;+ }++ try {+ const history = await this.coordinator.getExecutionHistory(operationId);+ const producer = history.find(+ (entry: { context?: AgentRuntimeContext; stepIndex?: number }) =>+ entry?.stepIndex === stepIndex - 1,+ );++ return producer?.context;+ } catch (e) {+ log('[%s][%d] execution history lookup failed: %O', operationId, stepIndex, e);+ return undefined;+ }+ }++ /**+ * Whether the runtime state can still carry a resumed step.+ *+ * `idle` counts alongside `running`: it is the status a state carries+ * between its creation and the first step, which is exactly the shape of an+ * operation whose step-0 delivery never executed (the row is `running` with+ * no steps, no snapshot and no messages beyond the user turn). Those are+ * resumable for the same reason a mid-run death is β the state describes a+ * step that still needs to happen.+ *+ * Parked operations are excluded on purpose: `waiting_for_human` and+ * `waiting_for_async_tool` are deliberate pauses with their own resume+ * paths, and re-queueing a plain step would run past the thing they wait on.+ * Terminal statuses are excluded because there is nothing left to run.+ */+ private canRedrive(state: AgentState | null): state is AgentState {+ return (+ !!state &&+ (state.status === 'running' || state.status === 'idle') &&+ typeof state.stepCount === 'number' &&+ state.stepCount >= 0+ );+ }++ /**+ * Retire an operation, but only if it is *still* past its lease at this+ * instant.+ *+ * Abandonment is irreversible and user-visible β it settles the durable row,+ * errors the conversation tail and clears the topic's running pointer β so it+ * must never act on a stale read. Minutes can pass between+ * `listStaleRunning` selecting a candidate and this line running (the sweep+ * walks candidates serially, and reading state plus execution history costs+ * two Redis round trips each), which is ample room for the worker to resume+ * and heartbeat. A transiently empty history read reaches here the same way.+ *+ * `settleStaleRunning` is the compare-and-set that closes it: its WHERE+ * clause re-checks `status = 'running' AND updatedAt < staleBefore` inside+ * the UPDATE, so a heartbeat that landed in the meantime wins and this+ * returns `alive` untouched. Only once the row is claimed do the+ * irreversible side effects run.+ */+ private async abandonIfStillStale(+ operationModel: AgentOperationModel,+ operationId: string,+ staleBefore: Date,+ reason: string,+ ): Promise<'abandoned' | 'alive'> {+ const claimed = await operationModel.settleStaleRunning(operationId, staleBefore);+ if (!claimed) {+ log('[%s] lease was refreshed before abandon could claim it', operationId);+ return 'alive';+ }++ // The claim above already moved the row to `abandoned`; tell the lifecycle+ // so it persists onto that status instead of being refused as a conflicting+ // terminal owner β which would skip `onComplete` / `onError` and leave+ // hook consumers (tasks, bots, parent runs) waiting on a retired operation.+ await new AbandonOperationService(this.db).finalizeAbandoned(+ operationId,+ `stale_lease_${reason}`,+ { settledAsAbandoned: true },+ );+ log('[%s] abandoned (reason=%s)', operationId, reason);++ return 'abandoned';+ }+}diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex 67d955388ae..84246bbce2f 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -30,19 +30,27 @@ const buildCoordinator = (});const messageUpdateMock = vi.fn().mockResolvedValue({ success: true });+const messageCreateMock = vi.fn().mockResolvedValue({ id: 'msg_new_failure' });+const latestSpineMessageIdMock = vi.fn().mockResolvedValue(undefined);vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(function () {- return { update: messageUpdateMock };+ return {+ create: messageCreateMock,+ getLatestSpineMessageId: latestSpineMessageIdMock,+ update: messageUpdateMock,+ };}),}));const findOperationMock = vi.fn().mockResolvedValue(null);const recordCompletionMock = vi.fn().mockResolvedValue(undefined);+const settleRunningMock = vi.fn().mockResolvedValue(true);vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(function () {return {findById: findOperationMock,recordCompletion: recordCompletionMock,+ settleRunning: settleRunningMock,};}),}));@@ -104,6 +112,12 @@ const buildDb = (overrides: { assistantRow?: any; operationRow?: any } = {}) =>},}) as any;+const buildPartiallessStore = () => {+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);+ return store;+};+describe('AbandonOperationService', () => {beforeEach(() => {messageUpdateMock.mockClear();@@ -112,6 +126,9 @@ describe('AbandonOperationService', () => {findOperationMock.mockReset().mockResolvedValue(null);recordCompletionMock.mockClear();findThreadMock.mockReset().mockResolvedValue(null);+ settleRunningMock.mockReset().mockResolvedValue(true);+ latestSpineMessageIdMock.mockReset().mockResolvedValue(undefined);+ messageCreateMock.mockReset().mockResolvedValue({ id: 'msg_new_failure' });topicSettleRunningOperationMock.mockReset().mockResolvedValue({ assistantMessageId: undefined, status: 'missing' });@@ -450,6 +467,24 @@ describe('AbandonOperationService', () => {expect(coord.deleteAgentOperation).toHaveBeenCalledWith('op_x');});+ it('tells the lifecycle when the caller already retired the durable row', async () => {+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });++ await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ }).finalizeAbandoned('op_x', 'stale_lease_redrive_exhausted', { settledAsAbandoned: true });++ expect(dispatchHooksMock).toHaveBeenCalledWith(+ 'op_x',+ expect.anything(),+ 'error',+ expect.objectContaining({ settledAsAbandoned: true }),+ );+ });+it.each(['done', 'error', 'interrupted'])('skips abandoned lifecycle dispatch for terminal coordinator state %s',async (status) => {@@ -797,6 +832,148 @@ describe('AbandonOperationService', () => {});});+ it('settles the durable row from the with-state branch too', async () => {+ // Regression: only the no-state branch used to touch `agent_operations`,+ // so an op whose Redis state was still inside its TTL when the watchdog+ // fired stayed `running` forever β nothing else retires a non-Goal op.+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [{ stepIndex: 0 }] });++ await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: store as any,+ }).finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(settleRunningMock).toHaveBeenCalledWith('op_x', 'error');+ });++ it('still settles the durable row when the lifecycle dispatch is skipped', async () => {+ // `dispatchHooks` β which owns the rich terminal write β is gated on the+ // state being running/waiting_*. An `idle` step boundary skips it, and+ // that used to mean nothing settled the row at all.+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith({ status: 'idle' })),+ });++ await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ }).finalizeAbandoned('op_idle', 'stale_lease');++ expect(dispatchHooksMock).not.toHaveBeenCalled();+ expect(settleRunningMock).toHaveBeenCalledWith('op_idle', 'error');+ });++ it('creates an assistant failure row when the dying step never made a placeholder', async () => {+ // A host recycled mid-LLM-call leaves no assistant placeholder, so there+ // was nothing carrying `error` β and the client keys its retry affordance+ // off `message.error`, which is why the turn rendered as frozen.+ latestSpineMessageIdMock.mockResolvedValue('msg_tail');+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: {},+ origin: { agentId: 'agt_x', topicId: 'tpc_x', userId: 'user_x' },+ }),+ ),+ });++ const result = await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ }).finalizeAbandoned('op_no_placeholder', 'stale_lease');++ // Anchored to the tail, but written as a NEW assistant row: the tail is+ // either the user's own turn β whose renderer never passes `error` to+ // ChatItem, so the user would see nothing β or an earlier assistant turn+ // that actually succeeded and must not be relabelled as failed.+ expect(latestSpineMessageIdMock).toHaveBeenCalledWith({+ threadId: null,+ topicId: 'tpc_x',+ });+ expect(messageUpdateMock).not.toHaveBeenCalled();+ expect(messageCreateMock).toHaveBeenCalledWith(+ expect.objectContaining({+ content: '',+ error: expect.objectContaining({ message: expect.any(String) }),+ parentId: 'msg_tail',+ role: 'assistant',+ topicId: 'tpc_x',+ }),+ );+ expect(result.assistantMessageUpdated).toBe(true);+ });++ it('writes no fallback row once a newer run has taken over the conversation', async () => {+ // The tail now belongs to the newer turn; grafting this run's error under+ // it would corrupt the branch the user is working on.+ latestSpineMessageIdMock.mockResolvedValue('msg_newer_turn');+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: {},+ origin: { agentId: 'agt_x', topicId: 'tpc_x', userId: 'user_x' },+ }),+ ),+ });++ const result = await new AbandonOperationService(+ buildDb({ operationRow: { id: 'op_newer' } }),+ { coordinator: coord as any, snapshotStore: buildPartiallessStore() as any },+ ).finalizeAbandoned('op_no_placeholder', 'stale_lease');++ expect(messageCreateMock).not.toHaveBeenCalled();+ expect(result.assistantMessageUpdated).toBe(false);+ // The durable row still settles, so the run is not left running.+ expect(settleRunningMock).toHaveBeenCalledWith('op_no_placeholder', 'error');+ });++ it('marks the existing placeholder rather than creating a row when the step made one', async () => {+ latestSpineMessageIdMock.mockResolvedValue('msg_tail');+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });++ await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ }).finalizeAbandoned('op_x', 'stale_lease');++ expect(latestSpineMessageIdMock).not.toHaveBeenCalled();+ expect(messageCreateMock).not.toHaveBeenCalled();+ expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', expect.anything());+ });++ it('scopes the tail lookup to the operation thread when it has one', async () => {+ latestSpineMessageIdMock.mockResolvedValue('msg_thread_tail');+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: {},+ origin: {+ agentId: 'agt_x',+ threadId: 'thr_x',+ topicId: 'tpc_x',+ userId: 'user_x',+ },+ }),+ ),+ });++ await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ }).finalizeAbandoned('op_thread', 'stale_lease');++ expect(latestSpineMessageIdMock).toHaveBeenCalledWith({+ threadId: 'thr_x',+ topicId: 'tpc_x',+ });+ });+it('omits subAgentResume for a non-sub-agent abandoned op', async () => {const coord = buildCoordinator({loadAgentState: vi.fn().mockResolvedValue(stateWith()),diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.topicMovedOn.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.topicMovedOn.test.tsnew file mode 100644index 00000000000..548328cfe6a--- /dev/null+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.topicMovedOn.test.ts@@ -0,0 +1,99 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import { agentOperations, threads, topics, users } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { AbandonOperationService } from '../AbandonOperationService';++/**+ * The fallback failure row is anchored to the conversation tail, so it must+ * only be written while the tail still belongs to the abandoned run. These run+ * against a real database because the check is a single query whose subquery,+ * thread scoping and child exclusion are the whole point.+ */+describe('AbandonOperationService.topicMovedOn', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;+ let topicId: string;++ const at = (iso: string) => new Date(iso);++ const seedOp = async (+ id: string,+ createdAt: string,+ extra: Partial<typeof agentOperations.$inferInsert> = {},+ ) =>+ serverDB.insert(agentOperations).values({+ createdAt: at(createdAt),+ id,+ status: 'running',+ topicId,+ userId,+ ...extra,+ });++ const movedOn = (operationId: string, origin: { threadId?: string } = {}) =>+ (+ new AbandonOperationService(serverDB, {+ coordinator: {} as any,+ snapshotStore: null,+ }) as any+ ).topicMovedOn(operationId, { topicId, userId, ...origin });++ beforeEach(async () => {+ serverDB = await getTestDB();+ userId = randomUUID();+ topicId = `tpc_${randomUUID()}`;+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(topics).values({ id: topicId, title: 't', userId });+ });++ afterEach(async () => {+ await serverDB.delete(agentOperations).where(eq(agentOperations.userId, userId));+ await serverDB.delete(users).where(eq(users.id, userId));+ });++ it('is false while the abandoned run is still the latest on the topic', async () => {+ await seedOp('op_old_first', '2026-09-01T00:00:00Z');+ await seedOp('op_stale', '2026-09-02T00:00:00Z');++ expect(await movedOn('op_stale')).toBe(false);+ });++ it('is true once a newer run started on the topic, even if it already finished', async () => {+ await seedOp('op_stale', '2026-09-02T00:00:00Z');+ await seedOp('op_newer', '2026-09-03T00:00:00Z', { status: 'done' });++ expect(await movedOn('op_stale')).toBe(true);+ });++ it("does not count the abandoned run's own sub-agent children", async () => {+ await seedOp('op_stale', '2026-09-02T00:00:00Z');+ await seedOp('op_child', '2026-09-02T00:01:00Z', { parentOperationId: 'op_stale' });++ expect(await movedOn('op_stale')).toBe(false);+ });++ it('scopes the check to the conversation the run belongs to', async () => {+ const threadId = `thd_${randomUUID()}`;+ await serverDB.insert(threads).values({+ id: threadId,+ sourceMessageId: 'm',+ title: 't',+ topicId,+ type: 'continuation',+ userId,+ });+ await seedOp('op_stale', '2026-09-02T00:00:00Z');+ // A newer run inside a thread does not own the main spine's tail.+ await seedOp('op_in_thread', '2026-09-03T00:00:00Z', { threadId });++ expect(await movedOn('op_stale')).toBe(false);+ await seedOp('op_stale_thread', '2026-09-01T00:00:00Z', { threadId });+ expect(await movedOn('op_stale_thread', { threadId })).toBe(true);+ });+});diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 57191b68002..aad4669ad0e 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -721,6 +721,50 @@ describe('CompletionLifecycle.dispatchHooks β error persistence', () => {expect(dispatch).not.toHaveBeenCalled();});++ describe('a row the caller already retired as abandoned', () => {+ // Mirrors `recordCompletion`'s guard: a row the stale-lease CAS moved to+ // `abandoned` only accepts a write that keeps that status.+ const retiredRowModel = () => ({+ findById: vi.fn(async () => ({ id: 'op-stale', status: 'abandoned' })),+ recordCompletion: vi.fn(async (_id: string, params: { status: string }) => {+ return params.status === 'abandoned';+ }),+ sumChildUsage: vi.fn(async () => undefined),+ });++ it('persists onto the abandoned status and still fires the hooks', async () => {+ const lifecycle = buildLifecycle();+ const model = retiredRowModel();+ (lifecycle as any).agentOperationModel = model;+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});++ await lifecycle.dispatchHooks('op-stale', { host: { hooks: [] }, status: 'error' }, 'error', {+ settledAsAbandoned: true,+ skipErrorMessageWrite: true,+ });++ expect(model.recordCompletion).toHaveBeenCalledWith(+ 'op-stale',+ expect.objectContaining({ completionReason: 'lease_expired', status: 'abandoned' }),+ );+ expect(dispatch).toHaveBeenCalled();+ });++ it('is refused as a conflicting owner without the flag, so no hooks fire', async () => {+ const lifecycle = buildLifecycle();+ (lifecycle as any).agentOperationModel = retiredRowModel();+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});++ await lifecycle.dispatchHooks('op-stale', { host: { hooks: [] }, status: 'error' }, 'error', {+ skipErrorMessageWrite: true,+ });++ expect(dispatch).not.toHaveBeenCalled();+ });+ });});describe('CompletionLifecycle.dispatchHooks β verify plan race', () => {@@ -800,7 +844,12 @@ describe('CompletionLifecycle.dispatchHooks β async-tool park', () => {await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_async_tool');- expect(persistSpy).toHaveBeenCalledWith('op-1', parkedState, 'waiting_for_async_tool');+ expect(persistSpy).toHaveBeenCalledWith(+ 'op-1',+ parkedState,+ 'waiting_for_async_tool',+ undefined,+ );expect(dispatchSpy).not.toHaveBeenCalled();expect(unregisterSpy).not.toHaveBeenCalled();});diff --git a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.tsnew file mode 100644index 00000000000..b5bb7352da0--- /dev/null+++ b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts@@ -0,0 +1,267 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { StaleOperationReaper } from '../StaleOperationReaper';++const claimStaleRedriveMock = vi.fn();+const settleStaleRunningMock = vi.fn();+const releaseStaleRedriveMock = vi.fn();+vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return {+ claimStaleRedrive: claimStaleRedriveMock,+ releaseStaleRedrive: releaseStaleRedriveMock,+ settleStaleRunning: settleStaleRunningMock,+ };+ }),+}));++const finalizeAbandonedMock = vi.fn().mockResolvedValue({});+vi.mock('../AbandonOperationService', () => ({+ AbandonOperationService: vi.fn().mockImplementation(function () {+ return { finalizeAbandoned: finalizeAbandonedMock };+ }),+}));++/** Minimal drizzle select chain returning `rows`. */+const buildDb = (rows: any[]) =>+ ({+ select: () => ({+ from: () => ({+ where: () => ({+ orderBy: () => ({ limit: vi.fn().mockResolvedValue(rows) }),+ }),+ }),+ }),+ }) as any;++const candidate = (id = 'op_x') => ({+ id,+ threadId: null,+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: null,+});++const buildCoordinator = (state: any, history: any[] = []) => ({+ getExecutionHistory: vi.fn().mockResolvedValue(history),+ loadAgentState: vi.fn().mockResolvedValue(state),+});+const buildQueue = () => ({ scheduleMessage: vi.fn().mockResolvedValue('msg_1') });++const runningState = (overrides: Record<string, any> = {}) => ({+ metadata: {},+ status: 'running',+ stepCount: 7,+ ...overrides,+});++/** `saveStepResult` files the context for step N+1 under producing step N. */+const historyFor = (stepIndex: number, context: any = { phase: 'tool_result' }) => [+ { context: { phase: 'llm_result' }, stepIndex: stepIndex - 1 },+ { context, stepIndex },+];++const buildReaper = (+ rows: any[],+ state: any,+ queue: any = buildQueue(),+ history: any[] = historyFor(6),+) =>+ new StaleOperationReaper(buildDb(rows), {+ coordinator: buildCoordinator(state, history) as any,+ queueService: queue as any,+ });++describe('StaleOperationReaper', () => {+ beforeEach(() => {+ claimStaleRedriveMock.mockReset().mockResolvedValue(1);+ settleStaleRunningMock.mockReset().mockResolvedValue(true);+ releaseStaleRedriveMock.mockReset().mockResolvedValue(true);+ finalizeAbandonedMock.mockClear();+ process.env.APP_URL = 'https://app.lobehub.test';+ });++ it('re-queues the unfinished step of a resumable operation', async () => {+ const queue = buildQueue();+ const result = await buildReaper([candidate()], runningState(), queue).sweep();++ expect(queue.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ // The context step 6 produced for step 7 β without it `runtime.step`+ // would synthesize a `user_input` context and drop the pending work.+ context: { phase: 'tool_result' },+ // stepCount is the count of COMPLETED steps, so it is also the index+ // of the one that never finished.+ endpoint: 'https://app.lobehub.test/api/agent/run',+ operationId: 'op_x',+ stepIndex: 7,+ }),+ );+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, examined: 1, redriven: 1 });+ });++ it('keys deduplication per attempt so a later redrive is not deduped away', async () => {+ const queue = buildQueue();+ claimStaleRedriveMock.mockResolvedValue(2);++ await buildReaper([candidate()], runningState(), queue).sweep();++ expect(queue.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({ deduplicationId: 'stale-redrive:op_x:7:2' }),+ );+ });++ it('redrives step 0 with the context the operation was created with', async () => {+ // Born-dead shape: state exists but is still `idle` at step 0. There is no+ // producing step, so the context comes off the state β the same field the+ // intervention continuation re-publishes from.+ const queue = buildQueue();+ await buildReaper(+ [candidate()],+ runningState({ initialContext: { phase: 'user_input' }, status: 'idle', stepCount: 0 }),+ queue,+ [],+ ).sweep();++ expect(queue.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({ context: { phase: 'user_input' }, stepIndex: 0 }),+ );+ });++ it('skips rather than abandons when the step context cannot be recovered', async () => {+ // `getExecutionHistory` swallows a failed LRANGE and returns [], so an+ // empty result cannot be told apart from a transient Redis failure.+ // Retiring is irreversible, and this operation is otherwise resumable.+ const queue = buildQueue();+ const result = await buildReaper([candidate()], runningState(), queue, []).sweep();++ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(claimStaleRedriveMock).not.toHaveBeenCalled();+ expect(settleStaleRunningMock).not.toHaveBeenCalled();+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, redriven: 0, skipped: 1 });+ });++ it('never touches an operation with no coordinator state', async () => {+ // This is the shape of a HEALTHY heterogeneous run: an external Claude+ // Code / Codex CLI drives it, it never creates coordinator state, and it+ // only refreshes its lease on `heteroIngest` batches β so one long tool+ // call reads as stale here. Retiring it would make `heteroIngest` drop+ // every subsequent batch of a live session.+ const queue = buildQueue();+ const result = await buildReaper([candidate()], null, queue).sweep();++ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(claimStaleRedriveMock).not.toHaveBeenCalled();+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, redriven: 0, skipped: 1 });+ });++ it.each(['waiting_for_human', 'waiting_for_async_tool'])(+ 'never redrives a deliberately parked operation (%s)',+ async (status) => {+ const queue = buildQueue();+ const result = await buildReaper([candidate()], runningState({ status }), queue).sweep();++ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ skipped: 1 });+ },+ );++ it('leaves an operation alone when a heartbeat wins the claim race', async () => {+ const queue = buildQueue();+ claimStaleRedriveMock.mockResolvedValue(null);+ // The stale CAS finds the row refreshed β the step is alive and owns itself+ // again, so nothing irreversible may happen to it.+ settleStaleRunningMock.mockResolvedValue(false);++ const result = await buildReaper([candidate()], runningState(), queue).sweep();++ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ alive: 1, redriven: 0 });+ });++ it('abandons once the redrive budget is spent', async () => {+ const queue = buildQueue();+ claimStaleRedriveMock.mockResolvedValue(null);+ // CAS still matches β the claim failed on the attempt budget, not a heartbeat.+ settleStaleRunningMock.mockResolvedValue(true);++ const result = await buildReaper([candidate()], runningState(), queue).sweep();++ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(settleStaleRunningMock).toHaveBeenCalledWith('op_x', expect.any(Date));+ // The claim already retired the row, so the lifecycle must be told β+ // otherwise its own completion write is refused and no hooks fire.+ expect(finalizeAbandonedMock).toHaveBeenCalledWith('op_x', 'stale_lease_redrive_exhausted', {+ settledAsAbandoned: true,+ });+ expect(result).toMatchObject({ abandoned: 1 });+ });++ it('refuses to abandon a run that heartbeated after the candidate was selected', async () => {+ // `listStaleRunning` selected this row, then the worker resumed while the+ // sweep was doing its Redis reads. Abandoning is irreversible and+ // user-visible, so it must re-check the lease atomically rather than+ // trust the stale select.+ const queue = buildQueue();+ claimStaleRedriveMock.mockResolvedValue(null);+ settleStaleRunningMock.mockResolvedValue(false);++ const result = await buildReaper([candidate()], runningState(), queue).sweep();++ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, alive: 1 });+ });++ it('gives the attempt back when the redrive fails to publish', async () => {+ // The budget bounds LLM spend; a delivery that never went out spent+ // nothing. Without the release, a brief queue outage walks a healthy+ // operation to its attempt limit and retires it having never recovered.+ const queue = buildQueue();+ queue.scheduleMessage.mockRejectedValue(new Error('qstash down'));+ claimStaleRedriveMock.mockResolvedValue(2);++ const result = await buildReaper([candidate()], runningState(), queue).sweep();++ expect(releaseStaleRedriveMock).toHaveBeenCalledWith('op_x', 2);+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, failed: 1, redriven: 0 });+ });++ it('keeps the attempt when the redrive publishes successfully', async () => {+ const result = await buildReaper([candidate()], runningState()).sweep();++ expect(releaseStaleRedriveMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ redriven: 1 });+ });++ it('keeps sweeping after one operation throws', async () => {+ const queue = buildQueue();+ queue.scheduleMessage+ .mockRejectedValueOnce(new Error('queue down'))+ .mockResolvedValueOnce('msg_2');++ const result = await buildReaper(+ [candidate('op_a'), candidate('op_b')],+ runningState(),+ queue,+ ).sweep();++ expect(result).toMatchObject({ examined: 2, failed: 1, redriven: 1 });+ });++ it('passes the caller stall window through to the claim', async () => {+ const before = Date.now();+ await buildReaper([candidate()], runningState()).sweep({ staleAfterMs: 60_000 });++ const [, staleBefore, maxAttempts] = claimStaleRedriveMock.mock.calls[0];+ expect(maxAttempts).toBe(3);+ expect(staleBefore.getTime()).toBeLessThanOrEqual(before - 60_000 + 5);+ });+});diff --git a/apps/server/src/services/agentRuntime/index.ts b/apps/server/src/services/agentRuntime/index.tsindex 17158473a78..2c4ab9009b8 100644--- a/apps/server/src/services/agentRuntime/index.ts+++ b/apps/server/src/services/agentRuntime/index.ts@@ -1,3 +1,4 @@export * from './AbandonOperationService';export * from './AgentRuntimeService';+export * from './StaleOperationReaper';export * from './types';diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex 739b8b33ccc..927b763a767 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -520,6 +520,39 @@ describe('AgentOperationModel', () => {status: 'abandoned',});});++ it('lets the retiring caller persist terminal stats onto the abandoned row', async () => {+ // The stale-operation reaper claims with settleStaleRunning, then runs the+ // completion lifecycle, whose write must land (so hooks fire) without+ // moving the row out of `abandoned`.+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-stale-retired-stats';+ await model.recordStart({ operationId });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, operationId));++ expect(await model.settleStaleRunning(operationId, new Date(Date.now() - 60_000))).toBe(true);+ expect(+ await model.recordCompletion(operationId, {+ completionReason: 'error',+ status: 'error',+ }),+ ).toBe(false);+ expect(+ await model.recordCompletion(operationId, {+ completionReason: 'lease_expired',+ status: 'abandoned',+ stepCount: 4,+ }),+ ).toBe(true);+ expect(await model.findById(operationId)).toMatchObject({+ completionReason: 'lease_expired',+ status: 'abandoned',+ stepCount: 4,+ });+ });});describe('hetero ingest rejection marker', () => {@@ -577,6 +610,130 @@ describe('AgentOperationModel', () => {});});+ describe('claimStaleRedrive', () => {+ const makeStale = async (operationId: string) =>+ serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, operationId));++ const staleBefore = () => new Date(Date.now() - 60_000);++ it('hands out increasing attempts and stops at the budget', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-budget';+ await model.recordStart({ operationId });++ await makeStale(operationId);+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 2)).toBe(1);+ await makeStale(operationId);+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 2)).toBe(2);+ await makeStale(operationId);+ // Budget spent β the caller falls back to abandoning the operation.+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 2)).toBeNull();+ });++ it('re-arms the lease so the next sweep skips a recovering operation', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-rearm';+ await model.recordStart({ operationId });+ await makeStale(operationId);++ expect(await model.claimStaleRedrive(operationId, staleBefore(), 3)).toBe(1);+ // The claim itself bumped updatedAt, so the row is no longer a candidate.+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 3)).toBeNull();+ });++ it('loses to a heartbeat that landed after the candidate was selected', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-heartbeat-race';+ await model.recordStart({ operationId });+ await makeStale(operationId);++ const selectedAt = staleBefore();+ await model.touchRunning(operationId);++ expect(await model.claimStaleRedrive(operationId, selectedAt, 3)).toBeNull();+ expect((await model.findById(operationId))?.status).toBe('running');+ });++ it('never claims an operation that already reached a terminal state', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-terminal';+ await model.recordStart({ operationId });+ await model.recordCompletion(operationId, { completionReason: 'done', status: 'done' });+ await makeStale(operationId);++ expect(await model.claimStaleRedrive(operationId, staleBefore(), 3)).toBeNull();+ });++ it('preserves unrelated metadata keys', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-metadata';+ await model.recordStart({ operationId, metadata: { keepMe: 'yes' } });+ await makeStale(operationId);++ await model.claimStaleRedrive(operationId, staleBefore(), 3);++ const row = await model.findById(operationId);+ expect(row?.metadata).toMatchObject({+ keepMe: 'yes',+ staleRedrive: { attempts: 1 },+ });+ });++ it('gives an attempt back so a failed publish costs no budget', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-release';+ await model.recordStart({ operationId });++ await makeStale(operationId);+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 2)).toBe(1);+ expect(await model.releaseStaleRedrive(operationId, 1)).toBe(true);++ // Budget restored: the next claim hands out attempt 1 again.+ await makeStale(operationId);+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 2)).toBe(1);+ });++ it('only ever undoes its own increment', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-redrive-release-race';+ await model.recordStart({ operationId });++ await makeStale(operationId);+ await model.claimStaleRedrive(operationId, staleBefore(), 3);+ await makeStale(operationId);+ expect(await model.claimStaleRedrive(operationId, staleBefore(), 3)).toBe(2);++ // A late release for attempt 1 must not walk the counter backwards past+ // the attempt another sweep has since claimed.+ expect(await model.releaseStaleRedrive(operationId, 1)).toBe(false);+ const row = await model.findById(operationId);+ expect(row?.metadata).toMatchObject({ staleRedrive: { attempts: 2 } });+ });++ it('scopes the release to the owning user', async () => {+ const operationId = 'op-redrive-release-ownership';+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId });+ await makeStale(operationId);+ await model.claimStaleRedrive(operationId, staleBefore(), 3);++ const intruder = new AgentOperationModel(serverDB, otherUserId);+ expect(await intruder.releaseStaleRedrive(operationId, 1)).toBe(false);+ });++ it('is scoped to the owning user', async () => {+ const operationId = 'op-redrive-ownership';+ await new AgentOperationModel(serverDB, userId).recordStart({ operationId });+ await makeStale(operationId);++ const intruder = new AgentOperationModel(serverDB, otherUserId);+ expect(await intruder.claimStaleRedrive(operationId, staleBefore(), 3)).toBeNull();+ });+ });+describe('sumChildUsage', () => {const seedChild = async (model: AgentOperationModel,diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 40f56cc2879..18f252d885e 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -479,6 +479,96 @@ export class AgentOperationModel {return Boolean(row);}+ /**+ * Atomically claim the next redrive attempt for an operation whose liveness+ * lease has expired, so a stale step can be re-queued instead of stranding.+ *+ * The claim is the concurrency control for the whole reaper: the same+ * predicate that selects a candidate also consumes it, so two overlapping+ * sweeps (or two instances of one sweep) can never both re-queue the same+ * step. Three guards ride in the WHERE clause rather than in the caller:+ * - `status = 'running'` β a terminal op is nobody's business anymore.+ * - `updatedAt < staleBefore` β a heartbeat that landed between the SELECT+ * and this UPDATE means the step is alive after all, and wins the race.+ * - attempt budget β a step that dies deterministically (poison payload,+ * OOM) must stop costing LLM calls; when this predicate fails the caller+ * falls back to abandoning the op with a user-visible error.+ *+ * Writing `metadata` also bumps `updatedAt` via `$onUpdate`, which re-arms+ * the lease: the redriven step gets a fresh stall window before the next+ * sweep can look at it again, and no extra bookkeeping is needed to keep+ * ticks from piling redrives onto an operation that is busy recovering.+ *+ * @returns the 1-based attempt number just claimed, or `null` when this+ * operation is not (or no longer) eligible.+ */+ async claimStaleRedrive(+ operationId: string,+ staleBefore: Date,+ maxAttempts: number,+ ): Promise<number | null> {+ // `jsonb_build_object` and the bare comparison below both take `any`, so+ // every parameter feeding them needs an explicit cast β Postgres cannot+ // infer a placeholder's type from an `any` argument (42P18).+ const attempts = sql`coalesce((${agentOperations.metadata} #>> '{staleRedrive,attempts}')::int, 0)`;++ const [row] = await this.db+ .update(agentOperations)+ .set({+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || jsonb_build_object('staleRedrive', jsonb_build_object('attempts', ${attempts} + 1, 'lastAttemptAt', ${new Date().toISOString()}::text))`,+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ eq(agentOperations.status, 'running'),+ sql`${agentOperations.updatedAt} < ${staleBefore}`,+ sql`${attempts} < ${maxAttempts}::int`,+ this.ownership(),+ ),+ )+ .returning({ metadata: agentOperations.metadata });++ if (!row) return null;++ const claimed = (row.metadata as { staleRedrive?: { attempts?: number } } | null)?.staleRedrive+ ?.attempts;++ return typeof claimed === 'number' ? claimed : null;+ }++ /**+ * Give back an attempt claimed by {@link claimStaleRedrive} when the redrive+ * it was claimed for never actually went out.+ *+ * The budget exists to bound LLM spend on a step that dies deterministically,+ * so a delivery that failed to publish must not consume it β otherwise a+ * brief queue outage walks an otherwise healthy operation to its attempt+ * limit and retires it without a single recovery ever having been attempted.+ *+ * The claimed attempt number is checked in SQL so this can only ever undo+ * *its own* increment: a concurrent sweep that claimed the next attempt in+ * between moves the counter past `attempt` and this becomes a no-op.+ * `updatedAt` is deliberately left where the claim moved it, so the release+ * shortens no stall window β the next sweep still waits out a full lease.+ */+ async releaseStaleRedrive(operationId: string, attempt: number): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({+ metadata: sql`jsonb_set(coalesce(${agentOperations.metadata}, '{}'::jsonb), '{staleRedrive,attempts}', to_jsonb(${attempt - 1}::int))`,+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ sql`(${agentOperations.metadata} #>> '{staleRedrive,attempts}')::int = ${attempt}::int`,+ this.ownership(),+ ),+ )+ .returning({ id: agentOperations.id });++ return Boolean(row);+ }+/*** Sum the terminal usage of every child operation forked from `parentOperationId`* (`callSubAgent` children, isolated group members).