π€― 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): do not abandon an operation that already settled (#20282)
Arvin Xu3ecdafcc3e71
diff --git a/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts b/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.tsindex aa3c3357a2b..51f826853f5 100644--- a/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts+++ b/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts@@ -41,6 +41,11 @@ export async function finalizeAbandoned(c: Context): Promise<Response> {// as handled while it stays parked forever.if (result.subAgentResume) {await resumeAbandonedParent(serverDB, operationId, result.subAgentResume);+ // Only now is the abandonment actually complete: until the hand-off lands+ // the durable mark stays `handoff_pending`, so a retry replays the parent+ // resume instead of reading the child as finalized and stranding the+ // parent in `waiting_for_async_tool`.+ await service.completeAbandonmentHandoff(operationId);}const executionTime = Date.now() - startTime;diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex e485ef985fd..884df86f922 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -2,10 +2,11 @@ import type { ISnapshotStore } from '@lobechat/agent-tracing';import { LOADING_FLAT } from '@lobechat/const';import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';import type { ChatMessageError } from '@lobechat/types';-import { AgentRuntimeErrorType } from '@lobechat/types';+import { AgentRuntimeErrorType, isAgentOperationSettled } from '@lobechat/types';import debug from 'debug';import { and, desc, eq, gt, gte, isNull, lte, ne, or, sql } from 'drizzle-orm';+import type { AgentAbandonmentMark } from '@/database/models/agentOperation';import { AgentOperationModel } from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';@@ -102,8 +103,39 @@ export interface FinalizeAbandonedResult {** Idempotent: calling twice is a no-op the second time because `finalize()`* removes the partial, so `loadAgentState` may return null or finalize will- * skip due to missing partial.+ * skip due to missing partial. An operation whose durable row is already+ * settled is skipped outright, before any of that β see the guard in+ * `finalizeAbandoned`.*/+/** Terminal status an abandonment wrote when it claimed the durable row. */+type ClaimedStatus = 'abandoned' | 'error';++/**+ * Read back the parent-resume linkage persisted with a `handoff_pending` mark.+ *+ * Validated field by field because it round-trips through jsonb: a truncated or+ * hand-edited mark must degrade to "nothing to resume" rather than construct a+ * bridge with `undefined` ids.+ */+const readAbandonmentHandoff = (+ mark: AgentAbandonmentMark | undefined,+): AbandonedSubAgentResume | undefined => {+ const resume = mark?.handoff?.resume;+ if (!resume || typeof resume !== 'object') return undefined;++ const candidate = resume as Partial<AbandonedSubAgentResume>;+ if (+ !candidate.parentOperationId ||+ !candidate.threadId ||+ !candidate.toolMessageId ||+ !candidate.userId+ ) {+ return undefined;+ }++ return candidate as AbandonedSubAgentResume;+};+export class AbandonOperationService {private readonly coordinator: AgentRuntimeCoordinator;private readonly snapshotStore: ISnapshotStore | null;@@ -136,15 +168,93 @@ export class AbandonOperationService {found: false,};+ // A caller that already CAS'd the row to a terminal status owns the+ // abandonment: its claim is the decision, and this call only runs the side+ // effects. `StaleOperationReaper` and the orphaned-run settle in `runStep`+ // both arrive this way.+ const callerClaimed = options?.settledAsAbandoned === true;++ // The durable row is the authority on whether anything is left to abandon.+ // The inactivity watchdog fires on *silence*, and a run that finished+ // normally is silent too once its terminal event fails to reach the gateway+ // β so this call can arrive for an operation that already settled. The+ // snapshot side cannot tell the two apart: a completed run can still leave a+ // partial behind, which is exactly the `found && finalized` shape the+ // gateway has to read as a real death. Trusting the row instead keeps a+ // phantom timeout from stamping a failure on a conversation that already+ // delivered its answer, and reports it as a phantom so the gateway can+ // reconcile rather than record one.+ const row = await this.findOperationRow(operationId);+ // A claim that never finished is not a settled run. `claimForAbandonment`+ // retires the row *before* the side effects that the conversation depends+ // on, so a host recycled in that window leaves a terminal row with nothing+ // written: no error bubble, no topic cleanup, no hooks, no parent resume β+ // and `StaleOperationReaper` only scans live rows, so nothing ever picks it+ // back up. The `claimed` mark is the difference between "someone else+ // settled this" and "we started and got cut off", so re-enter instead of+ // reporting a phantom.+ const abandonmentMark = (row?.metadata as { abandonment?: AgentAbandonmentMark } | undefined)+ ?.abandonment;+ const resumableClaim = abandonmentMark?.phase === 'claimed';+ // Every side effect already landed in the invocation that wrote+ // `handoff_pending`; the only thing still owed is the caller's parent-resume+ // hand-off. Replaying the full finalisation would fire the same+ // `onComplete` / `onError` hooks a second time, so hand back the persisted+ // linkage and let the caller retry just that step.+ if (row && !callerClaimed && abandonmentMark?.phase === 'handoff_pending') {+ result.abandoned = true;+ result.finalized = true;+ result.found = true;+ result.subAgentResume = readAbandonmentHandoff(abandonmentMark);+ log('[%s] abandonment hand-off replayed: parent resume still owed', operationId);+ return result;+ }+ if (row && !callerClaimed && !resumableClaim && isAgentOperationSettled(row.status)) {+ log('[%s] abandon skipped: operation already %s', operationId, row.status);+ result.abandoned = false;+ return result;+ }++ // That read is a fast path only β the run can still settle between it and+ // the side effects below (the executor commits `done` while the watchdog is+ // deciding), and the error written then is invisible to the `settleLive`+ // safety net at the end of this method, because that CAS runs after the+ // damage. So claim the live row first and let the claim be the decision: it+ // fails exactly when the run settled under us, and once it wins, this call+ // owns the transition under the same contract as a caller-claimed row.+ //+ // Which terminal status the claim wrote matters downstream: the lifecycle+ // persists onto it, and `recordCompletion` refuses to move a row from one+ // terminal status to another. A caller's `settleStaleRunning` wrote+ // `abandoned`; this local claim writes `error`, so the hooks must persist+ // `error` β reporting it as `abandoned` would be refused and silently drop+ // `onComplete` / `onError` for every real watchdog abandonment.+ let claimedStatus: ClaimedStatus | undefined = callerClaimed+ ? 'abandoned'+ : resumableClaim+ ? ((row?.status === 'abandoned' ? 'abandoned' : 'error') as ClaimedStatus)+ : undefined;+ if (row && !claimedStatus) {+ const claimed = await new AgentOperationModel(+ this.db,+ row.userId,+ row.workspaceId ?? undefined,+ ).claimForAbandonment(operationId, reason);+ if (!claimed) {+ log('[%s] abandon skipped: operation settled before it could be claimed', operationId);+ result.abandoned = false;+ return result;+ }+ claimedStatus = 'error';+ }+const state = await this.coordinator.loadAgentState(operationId);if (!state) {log('[%s] no agent state in coordinator β already cleaned up', operationId);- await this.finalizeRunningOperationWithoutState(- operationId,- reason,- result,- options?.settledAsAbandoned,- );+ await this.finalizeRunningOperationWithoutState(operationId, reason, result, claimedStatus);+ // Only once the no-state side effects have landed: the mark is what a+ // retry reads to decide whether it still owes this run any work.+ await this.markAbandonmentFinalized(operationId, row, callerClaimed);return result;}result.found = true;@@ -269,7 +379,7 @@ export class AbandonOperationService {await new CompletionLifecycle(this.db, origin.userId, origin.workspaceId, {includeShareVisitor,}).dispatchHooks(operationId, finalState, 'error', {- settledAsAbandoned: options?.settledAsAbandoned,+ settledAsAbandoned: claimedStatus === 'abandoned',skipErrorMessageWrite: result.assistantMessageUpdated,});} catch (e) {@@ -389,22 +499,105 @@ export class AbandonOperationService {}}+ // Close the claim only after every side effect above has run β hooks last,+ // so an interruption before this point still looks resumable, and one after+ // it can never fire them twice (nor re-resume the same parent).+ //+ // A pending parent resume is the exception: it happens in the *caller*,+ // after this method returns, and the process can die in that gap. Keeping+ // the mark resumable and carrying the linkage lets the retry replay the+ // hand-off; the caller retires the mark once the resume actually landed+ // (`completeAbandonmentHandoff`).+ if (result.subAgentResume) {+ await this.markAbandonmentHandoffPending(operationId, row, result.subAgentResume);+ } else {+ await this.markAbandonmentFinalized(operationId, row, callerClaimed);+ }+log('[%s] abandoned op finalized (reason=%s): %O', operationId, reason, result);return result;}+ /**+ * Retire the `claimed` mark written by {@link AgentOperationModel.claimForAbandonment}.+ *+ * Skipped for caller-claimed rows: those were retired by another writer+ * (`settleStaleRunning`), never carried this mark, and are not re-enterable+ * anyway. A failure here is logged, not thrown β the abandonment itself+ * already landed, and the worst case is one redundant re-entry later.+ */+ private async markAbandonmentFinalized(+ operationId: string,+ row: { userId?: string | null; workspaceId?: string | null } | null | undefined,+ callerClaimed: boolean,+ ): Promise<void> {+ if (callerClaimed || !row?.userId) return;+ try {+ await new AgentOperationModel(+ this.db,+ row.userId,+ row.workspaceId ?? undefined,+ ).markAbandonmentFinalized(operationId);+ } catch (e) {+ log('[%s] abandonment finalize mark failed (non-fatal): %O', operationId, e);+ }+ }++ /**+ * Persist the parent-resume linkage and keep the claim resumable.+ *+ * Skipped for caller-claimed rows for the same reason as+ * {@link markAbandonmentFinalized}. A failure here is logged, not thrown: it+ * only costs a redundant replay, never the abandonment itself.+ */+ private async markAbandonmentHandoffPending(+ operationId: string,+ row: { userId?: string | null; workspaceId?: string | null } | null | undefined,+ resume: AbandonedSubAgentResume,+ ): Promise<void> {+ if (!row?.userId) return;+ try {+ await new AgentOperationModel(+ this.db,+ row.userId,+ row.workspaceId ?? undefined,+ ).markAbandonmentHandoffPending(operationId, { resume });+ } catch (e) {+ log('[%s] abandonment hand-off mark failed (non-fatal): %O', operationId, e);+ }+ }++ /**+ * Retire the abandonment claim once the caller's parent-resume hand-off has+ * landed, so a later invocation neither replays the hand-off nor re-fires the+ * hooks.+ *+ * Called by the endpoint right after `resumeAbandonedParent` returns. A+ * failure is swallowed: the mark stays `handoff_pending`, which is the safe+ * direction (one redundant replay) rather than the unsafe one (a stranded+ * parent).+ */+ async completeAbandonmentHandoff(operationId: string): Promise<void> {+ const row = await this.findOperationRow(operationId);+ await this.markAbandonmentFinalized(operationId, row, false);+ }+private async finalizeRunningOperationWithoutState(operationId: string,reason: string,result: FinalizeAbandonedResult,- settledAsAbandoned?: boolean,+ claimedStatus?: ClaimedStatus,): Promise<void> {const op = await this.findOperationRow(operationId);- // A caller that already claimed the row (`settleStaleRunning`) has moved it- // to `abandoned`, so that status still needs the topic / placeholder /- // hook side effects below β otherwise the row retires while the turn keeps- // loading.- const preClaimed = settledAsAbandoned === true && op?.status === 'abandoned';+ // A row this abandonment already claimed (`settleStaleRunning` writes+ // `abandoned`, the live-row claim above writes `error`) is terminal on+ // purpose, so it still needs the topic / placeholder / hook side effects+ // below β otherwise the row retires while the turn keeps loading.+ const preClaimed = claimedStatus !== undefined && op?.status === claimedStatus;+ // Only an `abandoned` pre-claim has to be persisted onto as-is: the local+ // `error` claim matches the status the terminal write below records anyway,+ // which `recordCompletion` accepts, so that write still fills in the error.+ const preClaimedAbandoned = preClaimed && claimedStatus === 'abandoned';if (!op ||(!preClaimed &&@@ -424,8 +617,8 @@ export class AbandonOperationService {type: AgentRuntimeErrorType.AgentRuntimeError,};- // The pre-claim already wrote the terminal row; do not overwrite it.- if (!preClaimed) {+ // The `abandoned` pre-claim already wrote the terminal row; do not overwrite it.+ if (!preClaimedAbandoned) {try {await new AgentOperationModel(this.db,@@ -435,12 +628,17 @@ export class AbandonOperationService {completedAt: new Date(),completionReason: 'error',error: { message, type: String(error.type) },- llmCalls: 0,+ // A resumed claim may already carry the real counters β+ // `CompletionLifecycle` persists usage before the finalise mark+ // lands β so writing zeros here would erase the run's statistics.+ // On a fresh claim these are the row's current values (usually 0),+ // which is exactly what "no state was recorded" should look like.+ llmCalls: op.llmCalls ?? 0,processingTimeMs: op.startedAt ? Date.now() - new Date(op.startedAt).getTime() : null,status: 'error',- stepCount: 0,- toolCalls: 0,- totalTokens: 0,+ stepCount: op.stepCount ?? 0,+ toolCalls: op.toolCalls ?? 0,+ totalTokens: op.totalTokens ?? 0,});} catch (e) {reportSettleFailure(@@ -509,7 +707,7 @@ export class AbandonOperationService {'error',// Persist onto the pre-claimed `abandoned` row instead of being refused// as a conflicting terminal owner, which would skip the hooks.- preClaimed+ preClaimedAbandoned? { settledAsAbandoned: true, skipErrorMessageWrite: true }: { skipErrorMessageWrite: true },);diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex c10e093f735..73cb46bbe63 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -45,10 +45,16 @@ vi.mock('@/database/models/message', () => ({const findOperationMock = vi.fn().mockResolvedValue(null);const recordCompletionMock = vi.fn().mockResolvedValue(undefined);const settleLiveMock = vi.fn().mockResolvedValue(true);+const claimForAbandonmentMock = vi.fn().mockResolvedValue(true);+const markAbandonmentFinalizedMock = vi.fn().mockResolvedValue(undefined);+const markAbandonmentHandoffPendingMock = vi.fn().mockResolvedValue(undefined);vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(function () {return {+ claimForAbandonment: claimForAbandonmentMock,findById: findOperationMock,+ markAbandonmentFinalized: markAbandonmentFinalizedMock,+ markAbandonmentHandoffPending: markAbandonmentHandoffPendingMock,recordCompletion: recordCompletionMock,settleLive: settleLiveMock,};@@ -127,6 +133,9 @@ describe('AbandonOperationService', () => {recordCompletionMock.mockClear();findThreadMock.mockReset().mockResolvedValue(null);settleLiveMock.mockReset().mockResolvedValue(true);+ claimForAbandonmentMock.mockReset().mockResolvedValue(true);+ markAbandonmentFinalizedMock.mockReset().mockResolvedValue(undefined);+ markAbandonmentHandoffPendingMock.mockReset().mockResolvedValue(undefined);latestSpineMessageIdMock.mockReset().mockResolvedValue(undefined);messageCreateMock.mockReset().mockResolvedValue({ id: 'msg_new_failure' });topicSettleRunningOperationMock@@ -205,6 +214,55 @@ describe('AbandonOperationService', () => {});});+ it('preserves the counters a resumed claim already recorded', async () => {+ // Regression: `CompletionLifecycle` persists the run's usage before the+ // finalise mark lands, so a retry that entered the no-state branch used to+ // rewrite `llmCalls` / `stepCount` / `toolCalls` / `totalTokens` with zeros+ // and silently erase the run's statistics.+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });+ const db = buildDb({+ operationRow: {+ agentId: 'agt_x',+ id: 'op_x',+ llmCalls: 7,+ metadata: {+ abandonment: {+ at: '2026-11-03T00:00:00.000Z',+ phase: 'claimed',+ reason: 'inactivity_watchdog',+ },+ },+ startedAt: new Date('2026-06-30T11:51:14.745Z'),+ status: 'error',+ stepCount: 3,+ toolCalls: 2,+ topicId: 'tpc_x',+ totalTokens: 900,+ userId: 'user_x',+ workspaceId: 'ws_x',+ },+ });++ const svc = new AbandonOperationService(db, {+ coordinator: coord as any,+ snapshotStore: buildStore() as any,+ });++ await svc.finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(recordCompletionMock).toHaveBeenCalledWith(+ 'op_x',+ expect.objectContaining({+ completionReason: 'error',+ llmCalls: 7,+ status: 'error',+ stepCount: 3,+ toolCalls: 2,+ totalTokens: 900,+ }),+ );+ });+describe('no-state lifecycle hooks', () => {const configureEnvironmentHooks = (events: string) => {vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');@@ -394,7 +452,9 @@ describe('AbandonOperationService', () => {it('leaves an abandoned row alone without the pre-claim flag', async () => {const result = await abandon();- expect(result.abandoned).toBeUndefined();+ // A settled row is not a real abandonment, and the explicit `false` is+ // what lets the gateway reconcile its silence as a phantom timeout.+ expect(result.abandoned).toBe(false);expect(topicSettleRunningOperationMock).not.toHaveBeenCalled();expect(messageUpdateMock).not.toHaveBeenCalled();});@@ -418,11 +478,362 @@ describe('AbandonOperationService', () => {const result = await svc.finalizeAbandoned('op_done', 'inactivity_watchdog');- expect(result.abandoned).toBeUndefined();+ // The row guard now settles this even earlier than the no-state path did:+ // `abandoned: false` is what tells the gateway watchdog to reconcile the+ // silence as a phantom instead of recording an error.+ expect(result.abandoned).toBe(false);expect(recordCompletionMock).not.toHaveBeenCalled();expect(messageUpdateMock).not.toHaveBeenCalled();});+ describe('row guard for an operation that already settled', () => {+ // Regression: the inactivity watchdog fires on stream *silence*, and a run+ // that finished normally is silent too once its terminal event never+ // reached the gateway. The real case this covers had 21 completed steps and+ // a `done` row, yet the abandon still created an error bubble on the+ // conversation and reported a real death to the gateway β the partial the+ // finished run left behind made `found && finalized` look exactly like one.+ const settledRow = (status: string) => ({+ agentId: 'agt_x',+ id: 'op_x',+ startedAt: new Date('2026-10-01T15:32:22.480Z'),+ status,+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: null,+ });++ const abandonWithRow = async (status: string, options?: { settledAsAbandoned?: boolean }) => {+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });+ const store = buildStore();+ // A partial left behind by a finished run is precisely what used to make+ // this read as a genuine mid-flight death.+ store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }] });++ const result = await new AbandonOperationService(+ buildDb({ operationRow: settledRow(status) }),+ {+ coordinator: coord as any,+ snapshotStore: store as any,+ },+ ).finalizeAbandoned('op_x', 'inactivity_watchdog', options);++ return { coord, result, store };+ };++ it.each(['done', 'error', 'interrupted', 'abandoned'])(+ 'leaves a %s operation and its conversation alone',+ async (status) => {+ const { coord, result, store } = await abandonWithRow(status);++ expect(result).toEqual({+ abandoned: false,+ assistantMessageUpdated: false,+ finalized: false,+ found: false,+ });+ // No Redis read, no snapshot finalise, nothing the user can see β and+ // `abandoned: false` is what lets the gateway reconcile the silence as a+ // phantom timeout instead of recording an error.+ expect(coord.loadAgentState).not.toHaveBeenCalled();+ expect(store.save).not.toHaveBeenCalled();+ expect(store.removePartial).not.toHaveBeenCalled();+ expect(dispatchHooksMock).not.toHaveBeenCalled();+ expect(messageUpdateMock).not.toHaveBeenCalled();+ expect(messageCreateMock).not.toHaveBeenCalled();+ },+ );++ it('still runs the side effects for a row the caller already claimed', async () => {+ // StaleOperationReaper CASes the row to `abandoned` before calling in, so+ // that status is its own claim and must not read as a settled run.+ const { coord, result } = await abandonWithRow('abandoned', { settledAsAbandoned: true });++ expect(coord.loadAgentState).toHaveBeenCalled();+ expect(result.assistantMessageUpdated).toBe(true);+ expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', {+ error: expect.objectContaining({+ message: expect.stringContaining('inactivity_watchdog'),+ }),+ });+ });++ it('still abandons a live operation', async () => {+ const { coord, result } = await abandonWithRow('running');++ expect(coord.loadAgentState).toHaveBeenCalled();+ expect(result.found).toBe(true);+ expect(messageUpdateMock).toHaveBeenCalled();+ // The claim is what decides, so it has to land before the irreversible+ // write rather than after it: the trailing `settleLive` cannot undo a+ // message error.+ expect(claimForAbandonmentMock).toHaveBeenCalledWith('op_x', 'inactivity_watchdog');+ expect(claimForAbandonmentMock.mock.invocationCallOrder[0]).toBeLessThan(+ messageUpdateMock.mock.invocationCallOrder[0],+ );+ });++ it('resumes a claim whose finalisation was cut off', async () => {+ // Regression: the claim retires the row *before* the side effects the+ // conversation needs. A host recycled in that window β or a throwing+ // `loadAgentState` β left a terminal row with no error bubble, no topic+ // cleanup, no hooks and no parent resume. The second invocation read that+ // row as "already settled" and reported a phantom, and+ // `StaleOperationReaper` only scans live rows, so nothing else would ever+ // finish the job.+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }] });++ const result = await new AbandonOperationService(+ buildDb({+ operationRow: {+ ...settledRow('error'),+ metadata: {+ abandonment: {+ at: '2026-11-03T00:00:00.000Z',+ phase: 'claimed',+ reason: 'inactivity_watchdog',+ },+ },+ },+ }),+ { coordinator: coord as any, snapshotStore: store as any },+ ).finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(result.found).toBe(true);+ expect(result.assistantMessageUpdated).toBe(true);+ expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', {+ error: expect.objectContaining({+ message: expect.stringContaining('inactivity_watchdog'),+ }),+ });+ // The mark already says this run is ours, so no second claim is attemptedβ¦+ expect(claimForAbandonmentMock).not.toHaveBeenCalled();+ // β¦and the hooks still persist onto the `error` status the claim wrote.+ expect(dispatchHooksMock).toHaveBeenCalledWith(+ 'op_x',+ expect.anything(),+ 'error',+ expect.objectContaining({ settledAsAbandoned: false }),+ );+ // Only once everything landed does the claim stop being resumable.+ expect(markAbandonmentFinalizedMock).toHaveBeenCalledWith('op_x');+ });++ it('replays only the parent-resume hand-off when the finalisation already landed', async () => {+ // Regression: the finalized mark used to be written before the caller+ // handed the parent over to a resume. A host recycled in that gap left a+ // child that read as finalized, so no later invocation returned the+ // linkage and the parent stayed parked in `waiting_for_async_tool`.+ // `handoff_pending` keeps exactly that step replayable β and only it.+ const coord = buildCoordinator({ loadAgentState: vi.fn() });++ const result = await new AbandonOperationService(+ buildDb({+ operationRow: {+ ...settledRow('error'),+ metadata: {+ abandonment: {+ at: '2026-11-03T00:00:00.000Z',+ handoff: {+ resume: {+ errorMessage: 'Operation abandoned: inactivity_watchdog',+ parentOperationId: 'op_parent',+ threadId: 'thread_1',+ toolMessageId: 'msg_tool',+ userId: 'user_x',+ },+ },+ phase: 'handoff_pending',+ },+ },+ },+ }),+ { coordinator: coord as any, snapshotStore: buildStore() as any },+ ).finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(result).toEqual({+ abandoned: true,+ assistantMessageUpdated: false,+ finalized: true,+ found: true,+ subAgentResume: {+ errorMessage: 'Operation abandoned: inactivity_watchdog',+ parentOperationId: 'op_parent',+ threadId: 'thread_1',+ toolMessageId: 'msg_tool',+ userId: 'user_x',+ },+ });+ // Nothing is redone: no second claim, no second Redis read, no duplicate+ // error bubble and no duplicate hooks.+ expect(coord.loadAgentState).not.toHaveBeenCalled();+ expect(claimForAbandonmentMock).not.toHaveBeenCalled();+ expect(messageUpdateMock).not.toHaveBeenCalled();+ expect(dispatchHooksMock).not.toHaveBeenCalled();+ expect(markAbandonmentFinalizedMock).not.toHaveBeenCalled();+ });++ it('keeps the claim resumable until the parent hand-off is delivered', async () => {+ // The sub-agent's parent is resumed by the *caller*, after this method+ // returns. Retiring the mark here would make a crash in that window+ // unrecoverable.+ findOperationMock.mockResolvedValue({+ parentOperationId: 'op_parent',+ threadId: 'thread_1',+ userId: 'user_x',+ workspaceId: null,+ });+ findThreadMock.mockResolvedValue({ sourceMessageId: 'msg_tool' });++ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: { assistantMessageId: 'msg_assist_1' },+ origin: {+ threadId: 'thread_1',+ userId: 'user_x',+ lineage: { isSubAgent: true },+ },+ }),+ ),+ });++ const svc = new AbandonOperationService(+ buildDb({+ operationRow: {+ agentId: 'agt_x',+ id: 'op_child',+ startedAt: new Date('2026-10-01T15:32:22.480Z'),+ status: 'running',+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: null,+ },+ }),+ {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ },+ );++ const result = await svc.finalizeAbandoned('op_child', 'inactivity_watchdog');++ expect(result.subAgentResume).toBeDefined();+ expect(markAbandonmentHandoffPendingMock).toHaveBeenCalledWith('op_child', {+ resume: expect.objectContaining({ parentOperationId: 'op_parent' }),+ });+ expect(markAbandonmentFinalizedMock).not.toHaveBeenCalled();++ // Once the caller confirms the resume landed, the claim is retired.+ await svc.completeAbandonmentHandoff('op_child');+ expect(markAbandonmentFinalizedMock).toHaveBeenCalledWith('op_child');+ });++ it('leaves a finalised abandonment alone', async () => {+ // The other half of the mark: a retry after a *completed* finalisation+ // must not re-fire hooks or re-resume the same parent.+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });++ const result = await new AbandonOperationService(+ buildDb({+ operationRow: {+ ...settledRow('error'),+ metadata: { abandonment: { phase: 'finalized' } },+ },+ }),+ { coordinator: coord as any, snapshotStore: buildStore() as any },+ ).finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(result).toEqual({+ abandoned: false,+ assistantMessageUpdated: false,+ finalized: false,+ found: false,+ });+ expect(coord.loadAgentState).not.toHaveBeenCalled();+ expect(dispatchHooksMock).not.toHaveBeenCalled();+ expect(markAbandonmentFinalizedMock).not.toHaveBeenCalled();+ });++ it('fires the hooks onto the error status its own claim wrote', async () => {+ // Regression: the local claim moves the row to `error`, but the hooks+ // were told the row had been settled as `abandoned`. `recordCompletion`+ // refuses to move one terminal status to another, so the persist was+ // rejected and `onComplete` / `onError` (task / bot hooks) never fired.+ await abandonWithRow('running');++ expect(dispatchHooksMock).toHaveBeenCalledWith(+ 'op_x',+ expect.anything(),+ 'error',+ expect.objectContaining({ settledAsAbandoned: false }),+ );+ });++ it('fires the no-state hooks onto the error status its own claim wrote', async () => {+ // Same mismatch on the no-state path (hetero / device runs): the row now+ // reads `error` after the claim, and the lifecycle must persist `error`.+ const hooks = [{ id: 'h1', type: 'onComplete', webhook: { url: '/hook' } }];+ const row = { ...settledRow('running'), metadata: { _hooks: hooks } };+ const findFirst = vi+ .fn()+ .mockResolvedValueOnce(row)+ .mockResolvedValue({ ...row, status: 'error' });+ topicSettleRunningOperationMock.mockResolvedValue({+ assistantMessageId: 'msg_assist_1',+ status: 'settled',+ });++ const result = await new AbandonOperationService(+ { query: { agentOperations: { findFirst }, messages: { findFirst: vi.fn() } } } as any,+ {+ coordinator: buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) }) as any,+ snapshotStore: buildStore() as any,+ },+ ).finalizeAbandoned('op_x', 'inactivity_watchdog');++ expect(result.abandoned).toBe(true);+ // The error detail still lands on the row: `error` β `error` is accepted.+ expect(recordCompletionMock).toHaveBeenCalledWith(+ 'op_x',+ expect.objectContaining({ status: 'error' }),+ );+ expect(completeOperationMock).toHaveBeenCalledWith(expect.anything(), 'error', {+ skipErrorMessageWrite: true,+ });+ });++ it('leaves the turn alone when the run settles before the claim lands', async () => {+ // Interleaving: the read still saw `running`, but the executor committed+ // `done` before the CAS β so not one abandonment side effect may run.+ claimForAbandonmentMock.mockResolvedValueOnce(false);++ const { coord, result, store } = await abandonWithRow('running');++ expect(claimForAbandonmentMock).toHaveBeenCalledWith('op_x', 'inactivity_watchdog');+ expect(result).toEqual({+ abandoned: false,+ assistantMessageUpdated: false,+ finalized: false,+ found: false,+ });+ expect(coord.loadAgentState).not.toHaveBeenCalled();+ expect(dispatchHooksMock).not.toHaveBeenCalled();+ expect(messageUpdateMock).not.toHaveBeenCalled();+ expect(messageCreateMock).not.toHaveBeenCalled();+ expect(store.save).not.toHaveBeenCalled();+ expect(store.removePartial).not.toHaveBeenCalled();+ });+ });+it('does not touch a newer runningOperation when abandoning an old no-state op', async () => {const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });const store = buildStore();@@ -567,7 +978,9 @@ describe('AbandonOperationService', () => {status: 'error',}),'error',- { skipErrorMessageWrite: true },+ // No operation row was readable here, so nothing was claimed and the+ // lifecycle decides for itself.+ { settledAsAbandoned: false, skipErrorMessageWrite: true },);// Coordinator state cleaneddiff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex 25d8148c73c..8386cfd3929 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -691,6 +691,66 @@ describe('AgentOperationModel', () => {});});+ describe('claimForAbandonment', () => {+ const park = async (+ model: AgentOperationModel,+ operationId: string,+ status: 'waiting_for_async_tool' | 'waiting_for_client' | 'waiting_for_human',+ ) => {+ await model.recordStart({ operationId });+ await model.recordCompletion(operationId, { completionReason: status, status });+ };++ it('claims every live status, including a client wait', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'op-claim-running' });+ await park(model, 'op-claim-human', 'waiting_for_human');+ await park(model, 'op-claim-async', 'waiting_for_async_tool');+ await park(model, 'op-claim-client', 'waiting_for_client');++ for (const id of ['op-claim-running', 'op-claim-human', 'op-claim-async', 'op-claim-client']) {+ expect(await model.claimForAbandonment(id, 'inactivity_watchdog')).toBe(true);+ expect(await model.findById(id)).toMatchObject({+ completionReason: 'error',+ status: 'error',+ });+ }+ });++ it('stamps the claim provenance so a retry can tell it apart', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await park(model, 'op-claim-mark', 'waiting_for_client');++ await model.claimForAbandonment('op-claim-mark', 'inactivity_watchdog');++ expect((await model.findById('op-claim-mark'))?.metadata).toMatchObject({+ abandonment: { phase: 'claimed', reason: 'inactivity_watchdog' },+ });+ });++ it('never re-claims a row that already settled on its own', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'op-claim-done' });+ await model.settleRunning('op-claim-done', 'done');++ expect(await model.claimForAbandonment('op-claim-done', 'inactivity_watchdog')).toBe(false);+ expect(await model.findById('op-claim-done')).toMatchObject({ status: 'done' });+ });++ it("does not claim another user's parked client wait", async () => {+ const owner = new AgentOperationModel(serverDB, userId);+ await park(owner, 'op-claim-foreign', 'waiting_for_client');++ expect(+ await new AgentOperationModel(serverDB, otherUserId).claimForAbandonment(+ 'op-claim-foreign',+ 'inactivity_watchdog',+ ),+ ).toBe(false);+ expect((await owner.findById('op-claim-foreign'))?.status).toBe('waiting_for_client');+ });+ });+describe('client wait resume claim', () => {const park = async (model: AgentOperationModel, operationId: string) => {await model.recordStart({ operationId });diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 59fda41bf79..4e8f8a04aca 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -28,6 +28,30 @@ import { findLiveTopicOperations, findScopedOperation } from './agentOperationQu*/export type VerifyStatus = VerifyRunStatus;+/**+ * Provenance of an abandonment claim, persisted under `metadata.abandonment`.+ *+ * Three phases rather than a boolean because the windows that matter are the+ * ones *between* them: `claimed` means a watchdog retired the row and still+ * owes the conversation its side effects, so a retry must finish the job;+ * `handoff_pending` means those side effects landed but the caller still has to+ * hand the sub-agent's parent over to a resume, so a retry replays only that+ * step; `finalized` means everything landed and a retry must leave the row+ * alone.+ */+export interface AgentAbandonmentMark {+ /** ISO timestamp of the claim; absent on the `finalized` rewrite. */+ at?: string;+ /**+ * Linkage for the parent-resume hand-off this abandonment still owes. Kept+ * durable so a retry can replay the hand-off after the finalising host dies,+ * instead of stranding the parent in `waiting_for_async_tool`.+ */+ handoff?: Record<string, unknown>;+ phase: 'claimed' | 'finalized' | 'handoff_pending';+ reason?: string;+}+export interface RecordOperationStartParams {agentId?: string | null;appContext?: AgentOperationAppContext;@@ -408,6 +432,91 @@ export class AgentOperationModel {]);}+ /**+ * Claim a live row for an abandonment, atomically recording that the claim+ * exists.+ *+ * `settleLive` alone cannot say *who* retired the row, so a finalisation that+ * dies after the claim but before its side effects leaves a row that looks+ * exactly like a run which failed on its own β and the second invocation then+ * reads it as "already settled" and gives up. Stamping `metadata.abandonment`+ * in the same UPDATE keeps the claim and its provenance inseparable: a retry+ * can tell a half-finished abandonment (`phase: 'claimed'`) from a foreign or+ * completed terminal row, and pick the finalisation back up.+ */+ async claimForAbandonment(operationId: string, reason: string): Promise<boolean> {+ const mark: AgentAbandonmentMark = {+ at: new Date().toISOString(),+ phase: 'claimed',+ reason,+ };+ const [row] = await this.db+ .update(agentOperations)+ .set({+ completedAt: new Date(),+ completionReason: 'error',+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ abandonment: mark })}::jsonb`,+ status: 'error',+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ inArray(agentOperations.status, [+ 'running',+ 'waiting_for_human',+ 'waiting_for_async_tool',+ 'waiting_for_client',+ ]),+ this.ownership(),+ ),+ )+ .returning({ id: agentOperations.id });+ return Boolean(row);+ }++ /**+ * Retire the `claimed` mark once every abandonment side effect has landed, so+ * a later invocation cannot re-run hooks (or re-resume a parent) for a run+ * that was already finalised.+ */+ async markAbandonmentFinalized(operationId: string): Promise<void> {+ const mark: AgentAbandonmentMark = { phase: 'finalized' };+ await this.db+ .update(agentOperations)+ .set({+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ abandonment: mark })}::jsonb`,+ })+ .where(and(eq(agentOperations.id, operationId), this.ownership()));+ }++ /**+ * Keep the claim resumable while the parent-resume hand-off is still owed.+ *+ * The conversation side effects have landed by this point, but a sub-agent's+ * parent is only resumed by the *caller*, after `finalizeAbandoned` returns.+ * Retiring the mark here would make a crash in that window permanent: the+ * child reads as finalised, so no later invocation returns the linkage the+ * parent needs, and the parent stays parked in `waiting_for_async_tool`.+ * Persisting the linkage in the same UPDATE makes the hand-off itself+ * durable, so a retry replays exactly that step β and nothing else.+ */+ async markAbandonmentHandoffPending(+ operationId: string,+ handoff: Record<string, unknown>,+ ): Promise<void> {+ const mark: AgentAbandonmentMark = {+ at: new Date().toISOString(),+ handoff,+ phase: 'handoff_pending',+ };+ await this.db+ .update(agentOperations)+ .set({+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ abandonment: mark })}::jsonb`,+ })+ .where(and(eq(agentOperations.id, operationId), this.ownership()));+ }+private async settleFrom(operationId: string,status: 'done' | 'error' | 'interrupted',diff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.tsindex 2fcd5689824..69fe631c857 100644--- a/packages/types/src/agentOperation.ts+++ b/packages/types/src/agentOperation.ts@@ -27,6 +27,24 @@ const IN_FLIGHT_OPERATION_STATUSES = new Set<AgentOperationStatus>(IN_FLIGHT_OPEexport const isAgentOperationInFlight = (status: AgentOperationStatus): boolean =>IN_FLIGHT_OPERATION_STATUSES.has(status);+/**+ * The complement of {@link isAgentOperationInFlight}: the run reached a+ * terminal state and nothing will write to its topic again. Kept as an explicit+ * set rather than `!isAgentOperationInFlight(status)` so an unknown or absent+ * status (a partial row, a value from a newer build) is NOT mistaken for a+ * settled one β callers use this to decide whether there is still work to+ * retire, where a wrong "yes" silently skips a live run.+ */+const SETTLED_OPERATION_STATUSES = new Set<AgentOperationStatus>([+ 'abandoned',+ 'done',+ 'error',+ 'interrupted',+]);++export const isAgentOperationSettled = (status: AgentOperationStatus | null | undefined): boolean =>+ status != null && SETTLED_OPERATION_STATUSES.has(status);+export type AgentOperationCompletionReason =| 'cost_limit'| 'done'