Skip to content

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

♻️ refactor(server): split the 1763-line CompletionLifecycle into cohesive modules (#21157)

Arvin Xubbeefe6a57ab
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index 797f6b153b0..c4902fb7377 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -60,7 +60,7 @@ execAgent({ hooks })
| `apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts` | Tool notifications and execution results |
| `apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts` | Tool, compression and human-intervention execution |
| `apps/server/src/services/agentRuntime/AgentRuntimeService/` (`executeStep/`, `intervention.ts`) | Step events and human-intervention continuation |
-| `apps/server/src/services/agentRuntime/CompletionLifecycle.ts` | Terminal events |
+| `apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts` | Terminal events |
| `apps/server/src/services/aiAgent/subAgentRuns.ts` | Sub-agent events |
## Registration
diff --git a/.agents/skills/source-layout/SKILL.md b/.agents/skills/source-layout/SKILL.md
index 8fb0b91399f..bfabd72e395 100644
--- a/.agents/skills/source-layout/SKILL.md
+++ b/.agents/skills/source-layout/SKILL.md
@@ -10,15 +10,15 @@ Top-level ownership (`src/features`, `src/routes`, `apps/server/src`, `packages`
## 1. Names
-| What | Form | Example |
-| ---------------------------------------------------- | --------------------- | ---------------------------------------------- |
-| React component file / component directory | PascalCase | `PlanCard.tsx`, `ChatInput/ControlBar/` |
-| Hook | `useXxx.ts(x)` | `ChatInputNotice/useChatInputNotice.ts` |
-| Other module | camelCase or one word | `originLink.ts`, `recentDirs.ts` |
-| Server class module | the class name | `services/agentRuntime/CompletionLifecycle.ts` |
-| Service, router, store, and other non-component dirs | camelCase | `services/aiAgent/`, `store/chat/slices/` |
-| Package directory | kebab-case | `packages/agent-runtime/` |
-| Files inside a package | camelCase | `packages/database/src/models/` |
+| What | Form | Example |
+| ---------------------------------------------------- | --------------------- | ----------------------------------------------- |
+| React component file / component directory | PascalCase | `PlanCard.tsx`, `ChatInput/ControlBar/` |
+| Hook | `useXxx.ts(x)` | `ChatInputNotice/useChatInputNotice.ts` |
+| Other module | camelCase or one word | `originLink.ts`, `recentDirs.ts` |
+| Server class module | the class name | `services/agentRuntime/StaleOperationReaper.ts` |
+| Service, router, store, and other non-component dirs | camelCase | `services/aiAgent/`, `store/chat/slices/` |
+| Package directory | kebab-case | `packages/agent-runtime/` |
+| Files inside a package | camelCase | `packages/database/src/models/` |
A package whose files are already kebab-case (`alint`, `openapi`, `builtin-skills`) keeps kebab-case internally. Shared per-directory modules are `constants.ts`, `types.ts`, `style.ts`, and `utils.ts`, not `const.ts`, `type.ts`, `styles.ts`, or `helpers.ts`. Create one only when two or more modules in that directory use it; a constant or type used by one module stays in that module.
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
deleted file mode 100644
index fa0e90a7b71..00000000000
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ /dev/null
@@ -1,1763 +0,0 @@
-import { isParkedStatus } from '@lobechat/agent-runtime';
-import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';
-import {
- type AgentOperationStatus,
- isAgentOperationInFlight,
- RequestTrigger,
-} from '@lobechat/types';
-import { deserializeParts } from '@lobechat/utils';
-import { isRecord } from '@lobechat/utils/object';
-import debug from 'debug';
-
-import { notifyAgentInterventionRequired } from '@/business/server/agent-run/agentInterventionReview';
-import { notifyAgentRunCompleted } from '@/business/server/agent-run/notifyAgentRunCompleted';
-import {
- AgentOperationModel,
- type ChildUsageRollup,
- type RecordOperationStartParams,
-} from '@/database/models/agentOperation';
-import { MessageModel } from '@/database/models/message';
-import { TopicModel } from '@/database/models/topic';
-import { recomputeTopicUsage } from '@/database/models/topicUsage';
-import { VerifyRunModel } from '@/database/models/verifyRun';
-import { WorkModel } from '@/database/models/work';
-import { type LobeChatDatabase } from '@/database/type';
-import {
- formatErrorForState,
- readErrorBudgetContext,
-} from '@/server/modules/AgentRuntime/formatErrorForState';
-import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';
-import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
-import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
-import { parseAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';
-import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
-import {
- instantiateVerifyPlanOnStart,
- runVerifyOnCompletion,
- settleFailedRepair,
-} from '@/server/services/verify';
-import {
- registerWorksForOperation,
- resolveRunWorkAccessScope,
-} from '@/server/services/workRegistration';
-import { after } from '@/server/utils/scheduleAfterResponse';
-
-import { buildRuntimeInterventionNotification } from './agentInterventionNotification';
-import { extractFinalReplyImageUrls } from './finalReplyImages';
-import { CriticalHookDeliveryError, hookDispatcher, type SerializedHook } from './hooks';
-
-const log = debug('lobe-server:completion-lifecycle');
-
-/**
- * Terminal reasons this lifecycle treats as a successful completion: the run
- * produced a deliverable, even when it was stopped by a step/cost cap rather
- * than finishing naturally. `persistCompletion` stores all three with
- * status='done', and success-side effects (assistant-content recovery,
- * file-Work registration) must cover the capped reasons too β€” gating them on
- * `reason === 'done'` alone silently drops capped runs' artifacts.
- */
-export const isSuccessLikeCompletionReason = (reason: string): boolean =>
- reason === 'done' ||
- reason === 'max_steps' ||
- reason === 'cost_limit' ||
- reason === 'tool_call_repeat_limit';
-
-/**
- * The topic status a finished run leaves behind, mirroring what the client
- * writes for the same outcome (`executeGatewayAgent`'s `onSessionComplete`) and
- * what `agentNotify` does for the remote path: only a clean finish is something
- * the user may not have watched (`unread`); every other ending is an
- * interruption they already saw (`active`).
- *
- * Agrees with the one existing server-side settle, too:
- * `ServerOperationStore.clearRunningMark` hardcodes `unread`, and it only ever
- * runs from the `finish` executor β€” the success path, where this helper returns
- * `unread` as well.
- */
-const topicStatusForTerminalRun = (status: string): 'active' | 'unread' =>
- status === 'done' ? 'unread' : 'active';
-
-/**
- * Triggers whose completion recalls the user with a push notification. Beyond
- * plain chat: `Scheduled` is a user-deferred chat turn ("send this in 3
- * hours"), and `Cron` is today stamped only by the rate-limit auto-resume of a
- * user's own chat turn (see scheduledRunKinds) β€” both are exactly the "user
- * walked away mid-conversation" case the recall exists for. Everything else
- * (task runner, bots, evals, API, agent-signal self-iterations, …) is
- * background work and stays silent.
- */
-const USER_RECALLABLE_TRIGGERS = new Set<string>([
- RequestTrigger.Chat,
- RequestTrigger.Cron,
- RequestTrigger.Scheduled,
-]);
-
-/**
- * A parked human-approval run is not safely published until its generic Review
- * batch is durable. Unlike ordinary notification fanout, this error must reach
- * the queue/request boundary so the idempotent lifecycle delivery can retry.
- */
-export class CriticalAgentInterventionPersistenceError extends Error {
- constructor(operationId: string, cause: unknown) {
- super(`Failed to persist intervention Review for parked operation ${operationId}`, { cause });
- this.name = 'CriticalAgentInterventionPersistenceError';
- }
-}
-
-type SignalEvent = { [key: string]: unknown; type: string };
-
-/**
- * Whether a lifecycle event's `metadata` belongs to an Agent Share visitor
- * run. `principal.actor.shareVisitor.visitorUserId` is stamped once at operation
- * creation (`AgentRuntimeService.createOperation`'s `initialState.metadata`)
- * and rides the state through to the terminal event β€” mirrors
- * `GatewayStreamNotifier`'s share-visitor check, the sibling chokepoint that
- * scrubs the creator's `AgentState` off the visitor's WS channel.
- *
- * Exported so every OTHER chokepoint that emits a `userId`-scoped Agent
- * Signal source event on the runtime's `state`/operation metadata (the
- * `runtime.before_step` / `runtime.after_step` emissions in
- * `AgentRuntimeService`) can reuse the exact same check instead of
- * hand-rolling their own.
- */
-export const isAgentShareRun = (
- state:
- { principal?: { actor?: { shareVisitor?: { visitorUserId?: string } } } } | undefined | null,
-): boolean => Boolean(state?.principal?.actor?.shareVisitor?.visitorUserId);
-
-/**
- * Normalized terminal-completion input for {@link CompletionLifecycle.completeOperation}.
- *
- * This is the single typed shape every NON-in-process terminal path passes in β€”
- * heterogeneous CLI exit (`heteroFinish`), remote-agent done signal
- * (`agentNotify`), and synchronous dispatch failure
- * (`finalizeHeteroDispatchError`). `completeOperation` expands it into the
- * runtime `state` shape `dispatchHooks` consumes via one builder, so there is
- * exactly ONE place that mirrors the runtime state β€” no per-caller hand-rolled
- * synthetic state to drift.
- *
- * The in-process runtime keeps calling `dispatchHooks` with its real, rich
- * `state` directly (full message array, interruption, …) β€” it needs no synthesis.
- */
-export interface OperationCompletionInput {
- /** Owning agent id β€” trace snapshot key + the lifecycle event's `agentId`. */
- agentId?: string;
- /** Final assistant message row id β€” anchors the verify card / error bubble. */
- assistantMessageId?: string;
- cost?: { total?: number | null } | null;
- /** Final assistant deliverable text β€” the verify gate's input + bot rendering. */
- deliverable?: string;
- /** Terminal error payload (error path only). */
- error?: unknown;
- /**
- * The user goal (first user turn) β€” the verify gate judges against it. Typed
- * `unknown` because message content is polymorphic (string or multimodal part
- * array); `dispatchHooks` normalizes it to text the same way it does the
- * in-process path's user turn.
- */
- goal?: unknown;
- /** Executed model β€” the verify gate keys off `op.model`, so hetero backfills it. */
- model?: string | null;
- operationId: string;
- /** Group orchestration role; members must not trigger user-facing completion recalls. */
- orchestrationRole?: 'member' | 'supervisor';
- /** Executed provider β€” see {@link OperationCompletionInput.model}. */
- provider?: string | null;
- /** Serialized webhook hooks (queue mode); ignored in local in-memory mode. */
- serializedHooks?: SerializedHook[];
- /** When the run started, so the terminal row keeps its processing time. */
- startedAt?: Date | string;
- stepCount?: number | null;
- topicId?: string;
- /** Trace / usage aggregates (llm calls, tokens, tool calls). */
- usage?: unknown;
- userId?: string;
-}
-
-/** 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
- * dispatch-failure path, which surfaces a device-specific `detail`).
- */
- skipErrorMessageWrite?: boolean;
-}
-
-const toAgentSignalSnapshotEvents = (
- emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,
-): SignalEvent[] => {
- if (!emission || emission.deduped) return [];
- return toAgentSignalTraceEvents({
- actions: emission.orchestration.actions,
- results: emission.orchestration.results,
- signals: emission.orchestration.emittedSignals,
- source: emission.source,
- });
-};
-
-/**
- * Owns everything that happens once an operation reaches a terminal state:
- * building the lifecycle event payload, emitting completion AgentSignal source
- * events, dispatching `onComplete`/`onError` hooks, and writing the final
- * error back onto the assistant message row.
- *
- * Ordinary side-effect errors are logged and remain non-fatal. Critical
- * no-fallback webhook failures are rethrown after terminal persistence so a
- * queue execution can retry the control-flow handoff.
- */
-export class CompletionLifecycle {
- private readonly messageModel: MessageModel;
- private readonly agentOperationModel: AgentOperationModel;
- private readonly workspaceId?: string;
- /**
- * In-flight verify-plan instantiations started in {@link recordStart}, keyed by
- * operationId. `dispatchHooks` awaits the matching one before running the
- * completion gate so a very short / no-op task run can't race past its own plan
- * (instantiation is fire-and-forget at start and may not have settled yet).
- */
- private readonly verifyPlanInstantiations = new Map<string, Promise<void>>();
-
- constructor(
- private readonly serverDB: LobeChatDatabase,
- private readonly userId: string,
- workspaceId?: string,
- options?: {
- /**
- * Opt IN to agent-share visitor rows on this service's `messageModel`.
- * Reserved for share-runtime callers driving a visitor turn under the
- * creator's identity.
- */
- includeShareVisitor?: boolean;
- },
- ) {
- this.workspaceId = workspaceId;
- this.includeShareVisitor = options?.includeShareVisitor ?? false;
- this.messageModel = new MessageModel(serverDB, userId, workspaceId, undefined, {
- includeShareVisitor: this.includeShareVisitor,
- });
- this.agentOperationModel = new AgentOperationModel(serverDB, userId, workspaceId);
- }
-
- private readonly includeShareVisitor: boolean;
-
- /**
- * Persist the initial `agent_operations` row when an operation is created.
- * Returns whether the row write succeeded so security-sensitive callers can
- * require durable state before dispatch. Other runtime paths may preserve
- * the historical non-blocking behavior by ignoring the result.
- */
- async recordStart(params: RecordOperationStartParams): Promise<boolean> {
- let persisted = true;
- try {
- await this.agentOperationModel.recordStart(params);
- } catch (error) {
- persisted = false;
- // Hook configuration may contain inline authorization headers. Never log
- // a database error that could repeat its bound metadata parameters.
- const hooks = params.metadata?._hooks;
- if (hooks && (!Array.isArray(hooks) || hooks.length > 0))
- log('[%s] Failed to record operation start (non-fatal)', params.operationId);
- else log('[%s] Failed to record operation start (non-fatal): %O', params.operationId, error);
- }
-
- // Auto-instantiate the task's verify plan at run start so the completion gate
- // fires. Only for a top-level task operation β€” repair / verifier sub-agents
- // (which carry a parentOperationId) get their plan from the repair path, not
- // here. Fire-and-forget; never blocks startup. We keep the promise (instead of
- // void-ing it) so `dispatchHooks` can await it before the completion gate runs
- // β€” a fast run can otherwise complete first and the gate would no-op on a plan
- // that lands moments later. (instantiateVerifyPlanOnStart never rejects.)
- if (params.taskId && !params.parentOperationId) {
- this.verifyPlanInstantiations.set(
- params.operationId,
- instantiateVerifyPlanOnStart(
- this.serverDB,
- this.userId,
- { operationId: params.operationId, taskId: params.taskId },
- this.workspaceId,
- ),
- );
- }
-
- return persisted;
- }
-
- /**
- * Publish a provider-neutral Review snapshot only after every referenced tool
- * row can be read back as a member of this exact sealed parked batch. The
- * business slot is idempotent by batch id; repeated lifecycle delivery is
- * therefore safe, while a partial/mismatched write fails closed.
- */
- private async notifyPendingAgentIntervention(operationId: string, state: any): Promise<void> {
- try {
- const notification = await buildRuntimeInterventionNotification({
- operationId,
- state,
- userId: state?.origin?.userId || this.userId,
- workspaceId: this.workspaceId,
- });
- if (!notification) return;
-
- const persistedRows = await Promise.all(
- notification.items.map(async (item, itemIndex) => {
- if (item.sourceRef.type !== 'runtime') return;
- const [message, plugin] = await Promise.all([
- this.messageModel.findById(item.sourceRef.toolMessageId),
- this.messageModel.findMessagePlugin(item.sourceRef.toolMessageId),
- ]);
- if (
- !message ||
- message.role !== 'tool' ||
- message.parentId !== notification.context.assistantMessageId ||
- message.topicId !== notification.context.topicId ||
- !plugin ||
- plugin.toolCallId !== item.sourceRef.toolCallId ||
- plugin.intervention?.status !== 'pending' ||
- plugin.intervention.operationId !== operationId ||
- plugin.intervention.batchId !== notification.batch.id ||
- plugin.intervention.stepIndex !== notification.batch.stepIndex ||
- plugin.intervention.itemIndex !== itemIndex
- ) {
- return;
- }
- return true;
- }),
- );
-
- if (persistedRows.some((persisted) => persisted !== true)) {
- throw new Error(
- 'Cannot create intervention Review because the sealed pending batch is not durable',
- );
- }
-
- // Contract boundary: Cloud resolves only after the generic batch is
- // durable. Push/Live Activity fanout failures are handled inside the
- // Cloud override and must not reject this call after persistence.
- await notifyAgentInterventionRequired(notification);
- } catch (error) {
- if (error instanceof CriticalAgentInterventionPersistenceError) throw error;
- throw new CriticalAgentInterventionPersistenceError(operationId, error);
- }
- }
-
- /**
- * Map a completion reason to the terminal `agent_operations.status` value.
- * `waiting_for_human` / `waiting_for_async_tool` keep their own status so
- * analytics can distinguish paused ops from terminal ones.
- */
- private statusForReason(
- reason: string,
- ):
- | 'done'
- | 'error'
- | 'interrupted'
- | 'waiting_for_human'
- | 'waiting_for_async_tool'
- | 'waiting_for_client' {
- switch (reason) {
- case 'error': {
- return 'error';
- }
- case 'interrupted': {
- return 'interrupted';
- }
- case 'waiting_for_human': {
- return 'waiting_for_human';
- }
- case 'waiting_for_async_tool': {
- return 'waiting_for_async_tool';
- }
- case 'waiting_for_client': {
- return 'waiting_for_client';
- }
- default: {
- return 'done';
- }
- }
- }
-
- /**
- * Persist terminal state to `agent_operations`. Fire-and-forget: a DB
- * outage must never block hook dispatch or the executor's terminal
- * cleanup path.
- */
- private async persistCompletion(
- operationId: string,
- state: any,
- reason: string,
- settledAsAbandoned?: boolean,
- ): Promise<boolean> {
- 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 === 'waiting_for_client'
- ? reason
- : this.statusForReason(reason);
-
- const runOrigin = state?.origin ?? {};
- const agentId = runOrigin.agentId;
- const topicId = runOrigin.topicId;
- const traceS3Key =
- agentId && topicId ? buildFinalSnapshotKey(agentId, topicId, operationId) : null;
-
- const processingTimeMs = state?.createdAt
- ? Date.now() - new Date(state.createdAt).getTime()
- : null;
-
- 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(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
- // tree it forked rather than only the tokens its own turns burned.
- //
- // Re-derived from the child rows on every write instead of accumulated onto
- // this one: `recordCompletion` is a wholesale SET, and this method runs again
- // each time the op parks and resumes β€” an additive rollup would multiply. The
- // SUM is exact however often it re-runs.
- //
- // Skipped for sub-agents and group members themselves: nested sub-agents are
- // rejected up front, so a child never has children of its own and the query
- // would always return zero.
- const rollup =
- runOrigin.lineage?.isSubAgent === true ? undefined : await this.sumChildUsage(operationId);
-
- const add = (own: number | null | undefined, child: number): number | null => {
- if (!child) return own ?? null;
- return (own ?? 0) + child;
- };
-
- let completionDurable = false;
- let conflictingTerminalOwner = false;
- // The status the durable row actually carries. Usually this callback's own,
- // but NOT when a terminal owner got there first with a different one β€” see
- // the fallback below.
- let durableStatus: AgentOperationStatus = status;
- try {
- const accepted = await this.agentOperationModel.recordCompletion(operationId, {
- completedAt,
- completionReason,
- cost: state?.cost ?? null,
- error: state?.error ?? null,
- interruption: state?.interruption ?? null,
- llmCalls: add(state?.usage?.llm?.apiCalls, rollup?.llmCalls ?? 0),
- // Backfill the executed model/provider when the terminal state carries
- // them. The in-process runtime sets neither on `state` (the op already
- // holds them from recordStart) so these stay undefined and recordCompletion
- // skips them β€” a no-op. A heterogeneous run, which only learns its real
- // model from the CLI stream, feeds them in via the synthetic state built in
- // heteroFinish; the verify gate keys off op.model/provider, so dropping this
- // backfill would leave op.model null and silently skip verify.
- model: state?.model,
- processingTimeMs,
- provider: state?.provider,
- status,
- stepCount: state?.stepCount ?? null,
- toolCalls: add(state?.usage?.tools?.totalCalls, rollup?.toolCalls ?? 0),
- totalCost: add(state?.cost?.total, rollup?.totalCost ?? 0),
- totalInputTokens: add(state?.usage?.llm?.tokens?.input, rollup?.totalInputTokens ?? 0),
- totalOutputTokens: add(state?.usage?.llm?.tokens?.output, rollup?.totalOutputTokens ?? 0),
- totalTokens: add(state?.usage?.llm?.tokens?.total, rollup?.totalTokens ?? 0),
- traceS3Key,
- // The `usage` / `cost` blobs stay the op's OWN accumulator, un-rolled-up:
- // they are the runtime's counter, and the executor reads them back as state
- // (the cost-limit gate compares `state.cost.total` against the budget). Only
- // the scalar columns β€” the reporting surface β€” carry the whole tree.
- usage: state?.usage ?? null,
- });
- if (accepted) {
- completionDurable = true;
- } else {
- const operation = await this.agentOperationModel.findById(operationId);
- // Preserve the historical best-effort behavior when no durable start
- // row exists, but never let a conflicting terminal owner be replaced.
- conflictingTerminalOwner = !!operation;
- // Someone else wrote a terminal row: the run is over even though this
- // call is not the one that recorded it.
- completionDurable = conflictingTerminalOwner;
- // `recordCompletion` only refuses a row that is ALREADY terminal with a
- // different status than this callback carries (its `where` matches every
- // in-flight status, plus an equal one). So the row it refused is the
- // authoritative outcome, and the topic must be settled for what landed β€”
- // not for what this late callback is carrying. Two racing terminal
- // callbacks (`done` vs `error`/`interrupted`) would otherwise write
- // whichever one arrived second, `unread` and `active` included.
- if (operation) durableStatus = operation.status;
- }
- } catch (error) {
- log('[%s] Failed to persist operation completion (non-fatal): %O', operationId, error);
- }
-
- // The run is over durably β€” converge the topic's running mark, or it outlives
- // the run (see `settleTopicRunningMark`). Deliberately not attempted when the
- // completion above did not land: a DB error or a missing start row leaves the
- // operation's own end unproven, and a mark cleared on an unproven ending
- // reads as settled while `agent_operations` still says `running`.
- if (completionDurable) {
- await this.settleTopicRunningMark({ operationId, status: durableStatus, topicId });
- }
-
- if (conflictingTerminalOwner) return false;
-
- // The topic rollup's tool / human-interaction stats derive from the
- // operation rows written above (`recomputeTopicUsage` reads their usage/cost
- // blobs), but its usual trigger is the assistant message's usage write,
- // which can land BEFORE this terminal persist. Refresh here so this op's
- // tool spend shows up without waiting for the next message mutation.
- // Idempotent (pure derived projection) and non-fatal.
- if (topicId) {
- try {
- await this.serverDB.transaction((trx) =>
- recomputeTopicUsage(trx, this.userId, topicId, this.workspaceId),
- );
- } catch (error) {
- log('[%s] Failed to recompute topic usage rollup (non-fatal): %O', operationId, error);
- }
- }
-
- return true;
- }
-
- /**
- * Drop the topic's `runningOperation` mark when a run reaches its terminal row.
- *
- * The ONLY server-side settle used to be `ServerOperationStore.clearRunningMark`,
- * and it runs from a single place: the `finish` executor. Every ending that
- * never emits a `finish` instruction therefore wrote a terminal
- * `agent_operations` row and left the topic exactly as the run's start had left
- * it β€” `status = 'running'` with `metadata.runningOperation` naming an operation
- * that had already finished:
- *
- * - a Stop is persisted at the step boundary (`AgentRuntimeService.executeStep`
- * sets the state to `interrupted` once the in-flight step returns), and the
- * following delivery usually finds the operation already terminal;
- * - `interruptOperation` settles a client-parked run itself, and
- * `buildShareAbortResult` settles a revoked share visitor run;
- * - a loop stopped by `max_steps` / `cost_limit` ends without the agent asking
- * to finish.
- *
- * Nothing then revisited the row: the client's own settle is a single attempt
- * that a transient server refusal discards, and the client watchdog only runs
- * with that user's sidebar open. Observed 2026-10-13 on a self-hosted
- * deployment as a topic shown "running" for 45 minutes whose operation row had
- * been `interrupted` since 03:33:58Z with `topics.updated_at` frozen at the
- * run's start β€” `settleRunningOperation` always bumps `updated_at`, so that
- * timestamp is proof no settle ever reached the row. 16 rows of the same shape,
- * the oldest two months old.
- *
- * Persisting the terminal row is the moment the run is over, so converging
- * here covers every ending above (and any future one) instead of adding a call
- * to each caller. Compare-and-clear, exactly as the executor's adapter does:
- * only the operation the mark names β€” or one of its children β€” may drop it, so
- * a newer run that claimed the topic meanwhile is left alone and answers
- * `conflict`. Best-effort: a topic that cannot be reached must not fail the
- * completion it already persisted.
- */
- private async settleTopicRunningMark(params: {
- operationId: string;
- status: AgentOperationStatus;
- topicId?: string;
- }): Promise<void> {
- const { operationId, status, topicId } = params;
-
- // No topic to settle (a sub-agent run, a bot thread, a verify pass).
- if (!topicId) return;
- // Only an ending may drop the mark. Not merely the parked three: the fallback
- // above settles for the status read back from the row rather than one this
- // callback authored, and `idle` / `running` are no more of an ending than a
- // pause is. `isAgentOperationInFlight` is the shared authority for both.
- if (isAgentOperationInFlight(status)) return;
- // A lease-expired abandon settles the topic on its own path with its own
- // status (`AbandonOperationService`); leave that one to it.
- if (status === 'abandoned') return;
-
- try {
- const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId, undefined, {
- includeShareVisitor: this.includeShareVisitor,
- });
-
- const settled = await topicModel.settleRunningOperation(
- topicId,
- operationId,
- topicStatusForTerminalRun(status),
- );
-
- // `missing` (another writer already cleared it) and `conflict` (a newer run
- // owns the mark) are both correct no-ops, not failures.
- if (settled.status !== 'settled') {
- log('[%s] Topic running mark left alone: %s', operationId, settled.status);
- }
- } catch (error) {
- log('[%s] Failed to settle the topic running mark (non-fatal): %O', operationId, error);
- }
- }
-
- /** Best-effort child-usage rollup β€” a DB hiccup must not fail the completion write. */
- private async sumChildUsage(operationId: string): Promise<ChildUsageRollup | undefined> {
- try {
- return await this.agentOperationModel.sumChildUsage(operationId);
- } catch (error) {
- log('[%s] Failed to sum child operation usage (non-fatal): %O', operationId, error);
- return undefined;
- }
- }
-
- /**
- * Extract a human-readable error message from the agent state error object.
- * Handles both raw `ChatCompletionErrorPayload` (from runtime.step catch) and
- * formatted `ChatMessageError` (from executeStep catch).
- *
- * Public so callers can use the same formatting when surfacing errors
- * outside the hook dispatch path (e.g. trace snapshot finalize).
- */
- extractErrorMessage(error: any): string | undefined {
- if (!error) return undefined;
-
- // Path B: formatted ChatMessageError β€” { body, message, type }
- if (error.body) {
- const body = error.body;
- // OpenAI-style: body.error.message
- if (body.error?.message) return body.error.message;
- if (body.message) return body.message;
- }
-
- // Path A: raw ChatCompletionErrorPayload β€” { errorType, error: {...}, provider }
- if (error.error) {
- const inner = error.error;
- if (inner.error?.message) return inner.error.message;
- if (inner.message) return inner.message;
- }
-
- if (error.message && error.message !== 'error') return error.message;
- if (error.type || error.errorType) return String(error.type || error.errorType);
-
- return undefined;
- }
-
- /**
- * Emit completion AgentSignal source events and return compact snapshot
- * events for attachment to the trace step. Fire-and-forget.
- */
- async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {
- try {
- const {
- assistantMessageId,
- metadata,
- origin: runOrigin,
- } = this.buildLifecycleEvent(operationId, state, reason);
-
- // Agent Share visitor runs execute AS the creator (`runOrigin.userId` is
- // the creator's id β€” see `isAgentShareRun`'s JSDoc), so every completion
- // signal below (`agent.execution.completed` / `.failed`) would otherwise
- // run synchronous policy processing and record creator-scoped windows /
- // telemetry for a run an anonymous link visitor triggered. Suppress the
- // whole emission rather than merely re-scoping it: a share visitor has no
- // Agent Signal identity of its own to attribute this to.
- if (isAgentShareRun(state)) {
- log(
- '[completion-lifecycle] skip agent signal emission for share visitor run op=%s reason=%s',
- operationId,
- reason,
- );
- return [];
- }
-
- let selfIteration =
- reason === 'error' ? undefined : extractSelfIterationCompletionPayload(state);
- if (reason !== 'error' && !selfIteration) {
- try {
- const operation = await this.agentOperationModel.findById(operationId);
- const operationMetadata = operation?.metadata;
- if (operationMetadata?.agentSignal) {
- selfIteration = extractSelfIterationCompletionPayload({
- ...state,
- origin: {
- ...runOrigin,
- signal: parseAgentSignalMarker(operationMetadata.agentSignal),
- userId: runOrigin.userId || this.userId,
- },
- });
- }
- } catch (error) {
- log(
- '[completion-lifecycle] failed to hydrate Agent Signal marker op=%s: %O',
- operationId,
- error,
- );
- }
- }
- // A memory-writer run's terminal state may not carry the tool calls that
- // name the written memory (messages live in the DB). When the receipt would
- // fall back to a generic "Memory saved" with no id, re-read the run's own
- // thread so it can name the memory and offer undo.
- const memoryTargetUnresolved = selfIteration?.mutations.some((mutation) => {
- const target = isRecord(mutation.data) ? mutation.data.target : undefined;
- return !isRecord(target) || !target.id;
- });
- if (selfIteration?.marker.kind === 'memory' && memoryTargetUnresolved && runOrigin.threadId) {
- try {
- const messages = await this.messageModel.query(
- {
- agentId: runOrigin.agentId,
- threadId: runOrigin.threadId,
- topicId: runOrigin.topicId,
- },
- { allowShareVisitor: true },
- );
- selfIteration =
- extractSelfIterationCompletionPayload({
- ...state,
- messages,
- origin: { ...runOrigin, signal: selfIteration.marker, userId: selfIteration.userId },
- }) ?? selfIteration;
- } catch (error) {
- log(
- '[completion-lifecycle] failed to load memory-writer messages op=%s: %O',
- operationId,
- error,
- );
- }
- }
- if (reason !== 'error') {
- log(
- '[completion-lifecycle] emit agent.execution.completed op=%s userId=%s assistant=%s metaAssistant=%s selfIteration=%s',
- operationId,
- runOrigin.userId || this.userId,
- assistantMessageId ?? 'undefined',
- metadata?.assistantMessageId ?? 'undefined',
- selfIteration
- ? `kind=${selfIteration.marker?.kind} mutations=${selfIteration.mutations?.length}`
- : 'ABSENT',
- );
- }
- const completionSignalEmission =
- reason === 'error'
- ? await emitAgentSignalSourceEvent(
- {
- payload: {
- agentId: runOrigin.agentId,
- errorMessage: this.extractErrorMessage(state?.error),
- operationId,
- reason,
- serializedContext: undefined,
- topicId: runOrigin.topicId,
- turnCount: state?.stepCount || 0,
- },
- sourceId: `${operationId}:complete:${reason}`,
- sourceType: 'agent.execution.failed',
- },
- {
- agentId: runOrigin.agentId,
- db: this.serverDB,
- userId: runOrigin.userId || this.userId,
- workspaceId: this.workspaceId,
- },
- { ignoreError: true },
- )
- : await emitAgentSignalSourceEvent(
- {
- payload: {
- agentId: runOrigin.agentId,
- // Anchor the deferred skill synthesis to the completed assistant
- // turn: the completion-stage skill handler walks this id back
- // to the user message to read the parked candidate and seeds
- // the skill under the assistant group β€” instead of synthesizing
- // from the user prompt alone at inbound time. Resolved from
- // the final assistant message row when operation metadata omits
- // it (the server execAgent path).
- anchorMessageId: assistantMessageId,
- assistantMessageId,
- operationId,
- // Carry the completion reason so completion-stage consumers can
- // tell a finished turn from a non-terminal pause
- // (waiting_for_async_tool / waiting_for_human), which reuse this
- // same source.
- reason,
- // Self-iteration runs carry their finalState tool outcomes here
- // (the one point finalState is in hand) so the completion policy
- // can project receipts. Undefined for every other agent.
- selfIteration,
- serializedContext: undefined,
- steps: state?.stepCount || 0,
- topicId: runOrigin.topicId,
- turnCount: state?.stepCount || 0,
- },
- sourceId: `${operationId}:complete:${reason}`,
- sourceType: 'agent.execution.completed',
- },
- {
- agentId: runOrigin.agentId,
- db: this.serverDB,
- userId: runOrigin.userId || this.userId,
- workspaceId: this.workspaceId,
- },
- { ignoreError: true },
- );
-
- log(
- '[completion-lifecycle] emission done op=%s reason=%s deduped=%s',
- operationId,
- reason,
- (completionSignalEmission as { deduped?: boolean } | undefined)?.deduped ?? 'n/a',
- );
-
- return toAgentSignalSnapshotEvents(completionSignalEmission);
- } catch (error) {
- log('[%s] Completion signal emission error (non-fatal): %O', operationId, error);
- return [];
- }
- }
-
- /**
- * Insert a `role='verify'` message that renders the Agent Run delivery-checker
- * card (plan + results, read off `metadata.verifyOperationId`). Only created
- * when the run actually has a verify plan. Self-guarded β€” failures never affect
- * the run; the card is purely additive UI.
- */
- private async createVerifyMessage(
- operationId: string,
- assistantMessageId: string | undefined,
- userId: string,
- ): Promise<void> {
- try {
- const run = await new VerifyRunModel(this.serverDB, userId).findByOperation(operationId);
- if (!run?.plan?.length) return;
-
- const op = await new AgentOperationModel(this.serverDB, userId).findById(operationId);
- if (!op?.topicId) return;
-
- const messageModel = new MessageModel(this.serverDB, userId, undefined, undefined, {
- includeShareVisitor: this.includeShareVisitor,
- });
- await messageModel.create({
- agentId: op.agentId ?? undefined,
- content: '',
- groupId: op.chatGroupId ?? undefined,
- metadata: { verifyOperationId: operationId },
- parentId: assistantMessageId,
- role: 'verify',
- threadId: op.threadId ?? undefined,
- topicId: op.topicId,
- });
- } catch (error) {
- log('createVerifyMessage failed for op %s (non-fatal): %O', operationId, error);
- }
- }
-
- /**
- * Expand a normalized {@link OperationCompletionInput} into the runtime `state`
- * shape `dispatchHooks` consumes. The SINGLE place that mirrors the runtime
- * state for non-in-process paths β€” goal/deliverable become the user/assistant
- * turns the gate reads, model/provider backfill the op row, hooks ride on
- * `host.hooks`. Replaces the per-caller hand-rolled synthetic state that
- * previously drifted (e.g. a verify field added here was missed by heteroFinish).
- */
- private buildStateFromInput(input: OperationCompletionInput) {
- return {
- cost: input.cost ?? { total: null },
- createdAt: input.startedAt,
- error: input.error ?? undefined,
- messages: [
- { content: input.goal ?? '', role: 'user' },
- { content: input.deliverable ?? '', role: 'assistant' },
- ],
- host: { hooks: input.serializedHooks },
- metadata: { assistantMessageId: input.assistantMessageId },
- origin: {
- agentId: input.agentId,
- lineage: { orchestrationRole: input.orchestrationRole },
- topicId: input.topicId,
- userId: input.userId ?? this.userId,
- },
- model: input.model ?? undefined,
- provider: input.provider ?? undefined,
- stepCount: input.stepCount ?? null,
- usage: input.usage ?? undefined,
- };
- }
-
- /**
- * The facts the recall gate needs. The trigger rides on `state.origin` for
- * in-process runs (the appContext spread); synthetic terminals
- * ({@link buildStateFromInput}) have none, so fall back to the op row
- * `recordStart` stamped β€” which also reveals `parentOperationId`, marking
- * internal child runs (verifier/repair/evidence pass it without `isSubAgent`).
- * `trigger: undefined` means neither source knows.
- */
- private async resolveRunRecallFacts(
- operationId: string,
- runOrigin: { trigger?: unknown } | undefined,
- ): Promise<{ isChildRun: boolean; trigger: string | undefined }> {
- if (typeof runOrigin?.trigger === 'string')
- return { isChildRun: false, trigger: runOrigin.trigger };
-
- try {
- const operation = await this.agentOperationModel.findById(operationId);
- return {
- isChildRun: Boolean(operation?.parentOperationId),
- trigger: operation?.trigger ?? undefined,
- };
- } catch (error) {
- log('[%s] Failed to resolve run trigger from op row: %O', operationId, error);
- return { isChildRun: false, trigger: undefined };
- }
- }
-
- /**
- * Push a completion recall β€” but only for runs the user is waiting on.
- * Background executions (scheduled tasks, bots, evals, …) complete constantly
- * and would spam the OS banner. An unknown trigger passes: human-approval
- * chat continuations can reach here without one, and dropping a chat push is
- * worse than a rare stray banner.
- */
- private async recallUserOnCompletion(
- operationId: string,
- event: { agentId?: string; duration?: number; lastAssistantContent?: string; topicId?: string },
- runOrigin: { trigger?: unknown; userId?: string } | undefined,
- ): Promise<void> {
- const { isChildRun, trigger } = await this.resolveRunRecallFacts(operationId, runOrigin);
- if (isChildRun) {
- log('[%s] Skipping completion push for internal child run', operationId);
- return;
- }
- if (trigger !== undefined && !USER_RECALLABLE_TRIGGERS.has(trigger)) {
- log('[%s] Skipping completion push for non-interactive trigger %s', operationId, trigger);
- return;
- }
-
- await notifyAgentRunCompleted({
- agentId: event.agentId || undefined,
- duration: event.duration,
- lastAssistantContent: event.lastAssistantContent,
- operationId,
- topicId: event.topicId,
- userId: runOrigin?.userId || this.userId,
- // Personal runs leave this undefined β‡’ bare deep link; workspace
- // runs carry the id so the business slot can slug-prefix the URL.
- workspaceId: this.workspaceId,
- });
- }
-
- /**
- * Register the operation's Works: entity files edited this round
- * (pptx/xlsx/docx/pdf, …) as `file` Works β€” one version per operation,
- * exported from the sandbox β€” plus github issue/PR Works recovered from
- * hetero / device shell records (codex / claude-code / lobe-local-system
- * `gh` runs), which never pass the skill-tool registration hook.
- *
- * Idempotent per state object: only when EVERY candidate registered (the
- * returned outcome reports `failed === 0`) is a `_fileWorksRegistered` marker
- * stamped onto `state.metadata` so the dispatchHooks backstop (which receives
- * the same state later in the request) skips the duplicate scan. A PARTIAL
- * failure leaves the marker unset so the backstop re-runs and retries just the
- * failed candidates β€” file registration is idempotent per (operation, file)
- * via a DB existence probe, github registration per (work, toolCallId) via
- * the version write's unique guard, so a QStash retry that lost the marker is
- * safe.
- *
- * The gateway/queue executor calls this BEFORE the terminal
- * `coordinator.saveStepResult`: that save publishes `agent_runtime_end`,
- * whose `uiMessages` snapshot the client adopts as the settled message list β€”
- * Work rows must exist by then or the file-Work card stays absent until a
- * manual refresh. When entity edits are present, the executor suppresses the
- * early `visible_output_end`, so perceived loading covers export and
- * registration until the terminal snapshot is published.
- *
- * Awaited, NOT fire-and-forget: on serverless the runtime can freeze the
- * moment the response is sent, silently dropping any still-pending background
- * write. Fully self-guarded β€” a failure only logs, never throws. Both a thrown
- * whole-function failure AND a partial per-file failure (outcome `failed > 0`)
- * leave the marker unset so a later call retries the outstanding files.
- */
- async registerFileWorks(operationId: string, state: any): Promise<void> {
- if (state?.metadata?._fileWorksRegistered) return;
- try {
- // Share visitor runs register under the share scope of their visitor
- // topic (both the file scan below and the anchor lookup that follows).
- const shareVisitor = state?.principal?.actor?.shareVisitor ?? null;
- const accessScope = resolveRunWorkAccessScope({
- shareVisitor,
- topicId: state?.origin?.topicId,
- });
- if (accessScope === null) {
- log('[%s] Skipping Work registration: share visitor run has no topic', operationId);
- return;
- }
-
- const outcome = await registerWorksForOperation({
- agentShareVisitor: shareVisitor,
- // The round's final assistant message β€” the shell github scan stamps the
- // Work display anchor onto it for hetero runs (see registerWorksForOperation).
- assistantMessageId:
- state?.metadata?.workAssistantMessageId ?? state?.metadata?.assistantMessageId ?? null,
- // Live terminal totals: on the pre-snapshot path the op row's cost/usage
- // columns are not persisted yet (recordCompletion runs later), so the
- // registration must not rely on reading them back from the DB.
- finalCost: state?.cost ?? null,
- finalUsage: state?.usage ?? null,
- operationId,
- serverDB: this.serverDB,
- userId: state?.origin?.userId || this.userId,
- workspaceId: this.workspaceId,
- });
- // Skill tools may have registered Works before the terminal file scan.
- // Query the registry instead of inferring output from display messages.
- const works = await new WorkModel(
- this.serverDB,
- state?.origin?.userId || this.userId,
- this.workspaceId,
- accessScope,
- ).listByRootOperation({ includeFileWorks: true, limit: 1, rootOperationId: operationId });
- if (works.length > 0) {
- const assistantMessageId =
- state?.metadata?.workAssistantMessageId ??
- state?.metadata?.assistantMessageId ??
- outcome.anchorMessageId;
- if (!assistantMessageId) {
- log('[%s] No assistant message available for registered Works', operationId);
- return;
- }
- const result = await this.messageModel.update(assistantMessageId, {
- metadata: {
- work: {
- rootOperationId: operationId,
- userMessageId: state?.origin?.sourceMessageId,
- },
- },
- });
- if (!result.success) {
- log('[%s] Failed to stamp Work anchor on %s', operationId, assistantMessageId);
- return;
- }
- }
- // Stamp the idempotency marker ONLY when nothing failed. A partial failure
- // (some files exported/registered, others did not) must NOT be recorded as
- // a completed registration, or the dispatchHooks backstop would skip the
- // retry and the user gets neither a Work nor the edited-files fallback.
- if (state?.metadata && outcome.failed === 0) state.metadata._fileWorksRegistered = true;
- } catch (error) {
- log('[%s] registerWorksForOperation failed (non-fatal): %O', operationId, error);
- }
- }
-
- /**
- * The single terminal-completion entry for every path that does NOT have the
- * in-process runtime's rich `state` in hand: heterogeneous CLI exit
- * (`heteroFinish`), remote-agent done signal (`agentNotify`), and synchronous
- * dispatch failure (`finalizeHeteroDispatchError`). Builds the synthetic state
- * once and runs the SAME pipeline the in-process runtime uses β€” persist the
- * terminal op row, fire onComplete/onError hooks, and (on `done`) run the
- * delivery-checker verify gate. This is what makes those paths true lifecycle
- * peers instead of firing a stripped-down hooks-only funnel.
- */
- async completeOperation(
- input: OperationCompletionInput,
- reason: 'done' | 'error' | 'interrupted',
- options?: CompleteOperationOptions,
- ): Promise<void> {
- await this.dispatchHooks(input.operationId, this.buildStateFromInput(input), reason, options);
- }
-
- /**
- * Dispatch `onComplete` (and `onError` for `reason='error'`) hooks via
- * the global `hookDispatcher`. On the error path, also writes the error
- * back onto the assistant message row so the frontend can render it.
- * Fire-and-forget; unregisters the operation after a settled lifecycle while
- * preserving registrations across retryable critical delivery failures.
- */
- async dispatchHooks(
- operationId: string,
- state: any,
- reason: string,
- options?: CompleteOperationOptions,
- ): Promise<void> {
- // `waiting_for_async_tool` parks the SAME operation: it persists the parked
- // status (the async-tool resume CAS reads it) but must NOT fire `onComplete`
- // or unregister hooks β€” the op resumes under this same id and reaches its
- // real terminal state later, which is when consumers should be notified.
- // `waiting_for_human` is different: the parked segment fires `onComplete`
- // so hook consumers can surface the approval request. A winning decision
- // schedules a fresh continuation operation and then retires this parked
- // segment; the continuation receives the serialized hooks through
- // `host.hooks`.
- // `waiting_for_client` (no client to run the next LLM call) parks the same
- // operation the same way: it resumes under this id or expires to `error`.
- const isAsyncToolPark = reason === 'waiting_for_async_tool' || reason === 'waiting_for_client';
- let shouldRetainHooksForRetry = false;
-
- try {
- const {
- assistantMessageId,
- event,
- metadata,
- origin: runOrigin,
- } = this.buildLifecycleEvent(operationId, state, reason);
-
- // 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,
- options?.settledAsAbandoned,
- );
- if (completionAccepted === false) {
- log('[%s] Skipping hooks for an operation with a conflicting terminal owner', operationId);
- return;
- }
-
- // At this point the parked operation state has been durably projected to
- // agent_operations. Verify the tool rows independently before creating a
- // durable Review so a partial batch can never reach notification UI.
- if (reason === 'waiting_for_human') {
- await this.notifyPendingAgentIntervention(operationId, state);
- }
-
- if (isAsyncToolPark) return;
-
- // `lastAssistantContent` comes off the Redis-backed `state.messages`,
- // while the assistant message row is persisted through a separate
- // `messageModel.update` path. When the two diverge (state entry empty
- // but the DB row holds the full reply β€” Discord bot completions
- // arrived with no content while the app showed the reply), consumers
- // like the IM bot callback silently drop the reply. Recover from the DB
- // row β€” the same source of truth the app UI renders β€” before dispatch.
- if (
- isSuccessLikeCompletionReason(reason) &&
- !event.lastAssistantContent?.trim() &&
- !event.attachments?.length
- ) {
- const recovered = await this.recoverLastAssistantContent(
- operationId,
- assistantMessageId,
- runOrigin.userId || this.userId,
- typeof runOrigin.topicId === 'string' ? runOrigin.topicId : undefined,
- );
- if (recovered) {
- event.lastAssistantContent = recovered;
- const attachments = extractOutboundAttachments([
- { content: recovered, role: 'assistant' },
- ]);
- event.attachments = attachments.length > 0 ? attachments : undefined;
- }
- }
-
- await hookDispatcher.dispatch(operationId, 'onComplete', event, state?.host?.hooks);
-
- // Recall the user when a run finishes with a deliverable while they may be
- // away (push / inbox). Fires on every success-like terminal β€” `done` plus
- // the step/cost caps, which still produce a reply worth recalling β€” to
- // match the desktop completion notification, which notifies on any clean
- // (non-abort, non-error) terminal. Fire-and-forget through the
- // `@/business` slot; the default implementation is a no-op. Sub-agent /
- // group-member completions are internal steps of a parent run, never a
- // user-facing recall β€” in-group members carry `orchestrationRole: 'member'`
- // WITHOUT `isSubAgent` (see execAgentMember), so guard both. The
- // remaining condition β€” only interactive chat runs recall the user β€”
- // lives in recallUserOnCompletion.
- //
- // Agent Share visitor runs execute AS the creator, so this `userId`-scoped
- // recall would otherwise reach the creator's push/inbox for every turn an
- // arbitrary link visitor completes β€” a visitor could spam the owner by
- // repeatedly running the shared agent, and the notification would deep-link
- // into a visitor topic (`topics.senderId`) that is deliberately excluded
- // from creator-facing surfaces.
- if (
- isSuccessLikeCompletionReason(reason) &&
- runOrigin.lineage?.isSubAgent !== true &&
- runOrigin.lineage?.orchestrationRole !== 'member' &&
- !isAgentShareRun(state)
- ) {
- void this.recallUserOnCompletion(operationId, event, runOrigin).catch((error) =>
- log('[%s] Completion notification failed (non-fatal): %O', operationId, error),
- );
- }
-
- // Delivery checker: on a successful completion, run the confirmed verify
- // plan against the deliverable. Fire-and-forget and self-guarded β€” a run
- // without an opted-in plan is a no-op, and failures never affect the run.
- if (reason === 'done') {
- // The task's verify plan is instantiated fire-and-forget at run start; a
- // fast or no-op run can reach completion before it settles. Await the
- // in-flight instantiation (if any) so the gate sees the confirmed plan
- // instead of racing past it and leaving a planned run with no results/card.
- await this.verifyPlanInstantiations.get(operationId);
-
- const messages: any[] = Array.isArray(state?.messages) ? state.messages : [];
- const firstUserMessage = messages.find((m) => m?.role === 'user');
- const goal = firstUserMessage
- ? (extractTextFromMessageContent(firstUserMessage.content) ?? '')
- : '';
- // Surface the delivery-checker card first (a role='verify' message that
- // renders the run's plan + results). Awaited before verification so
- // auto-repair can persist its failure feedback onto this card (the
- // VerifyMessageProcessor then surfaces it into the repair run's context).
- // Self-guarded β€” failures never affect the run.
- await this.createVerifyMessage(
- operationId,
- metadata?.assistantMessageId,
- runOrigin.userId || this.userId,
- );
- // `after`, not a bare `void`: judging is minutes of LLM calls and the
- // step handler must not wait for it, but a detached promise has nobody
- // keeping it scheduled β€” on the serverless path the instance is free to
- // stop running it the moment this response returns. That is not merely a
- // lost verification: entering `verifying` is a durable write, so a run
- // cut off mid-judge stays `verifying` forever. `after` hands the work to
- // the host as post-response work instead (no-op fallback off Next).
- after(() =>
- runVerifyOnCompletion(
- this.serverDB,
- runOrigin.userId || this.userId,
- {
- deliverable: event.lastAssistantContent ?? '',
- goal,
- operationId,
- },
- this.workspaceId,
- ),
- );
- }
-
- if (reason === 'error' || reason === 'interrupted') {
- after(async () => {
- await settleFailedRepair(
- this.serverDB,
- runOrigin.userId || this.userId,
- operationId,
- this.workspaceId,
- );
- });
- }
-
- // Register entity files edited this round as `file` Works. On the
- // gateway/queue path this already ran BEFORE the terminal snapshot (see
- // `registerFileWorks`) and no-ops via the state marker; here it is the
- // backstop for every other terminal path (in-process runtime, hetero
- // completions, already-terminal early exits). Guarded on success-LIKE
- // reasons, not `done` alone: a run stopped by a step/cost cap still
- // produced its edits and persists as status='done'.
- //
- // `waiting_for_human` deliberately does NOT register: the park is not a
- // successful deliverable boundary. The fresh approval continuation is
- // built from the complete authoritative history and performs the real
- // terminal scan. Registering here would freeze pre-approval file content
- // as a completed Work before the user decision has run.
- if (isSuccessLikeCompletionReason(reason)) {
- await this.registerFileWorks(operationId, state);
- }
-
- if (reason === 'error') {
- await hookDispatcher.dispatch(operationId, 'onError', event, state?.host?.hooks);
-
- const assistantMessageId =
- state?.error && !options?.skipErrorMessageWrite
- ? await this.resolveErrorMessageId(operationId, metadata, runOrigin)
- : undefined;
- if (assistantMessageId && state?.error && !options?.skipErrorMessageWrite) {
- // Preserve the semantic error type written by the runtime. Rebuilding
- // this as a generic AgentRuntimeError would lose UI routing data such
- // as quota context and force the client into the fallback card.
- const messageError = formatErrorForState(state.error);
- const errorMessage =
- this.extractErrorMessage(messageError) ||
- this.extractErrorMessage(state.error) ||
- String(state.error);
- try {
- await this.messageModel.update(assistantMessageId, {
- error: {
- ...messageError,
- body: messageError.body ?? { message: errorMessage },
- message: errorMessage,
- },
- });
- } catch (updateError) {
- log(
- '[%s] Failed to update assistant message with error (non-fatal): %O',
- operationId,
- updateError,
- );
- }
- }
- }
- } catch (error) {
- if (
- error instanceof CriticalHookDeliveryError ||
- error instanceof CriticalAgentInterventionPersistenceError
- ) {
- // A queue retry may run in this same process (local callback / warm
- // worker). Keep the in-memory registration until that lifecycle really
- // settles; queue mode can additionally reconstruct from host.hooks.
- shouldRetainHooksForRetry = true;
- throw error;
- }
- log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);
- } finally {
- // Keep hooks registered across an async-tool park so the eventual resume
- // (same operationId) can still fire onComplete/onError. Critical delivery
- // failures likewise keep them until the provider redelivery settles.
- if (!isAsyncToolPark && !shouldRetainHooksForRetry) {
- hookDispatcher.unregister(operationId);
- // The instantiation has settled (awaited above) or this op never opted in
- // β€” drop the entry so the map doesn't grow across the service's lifetime.
- // Kept across an async-tool park: the op resumes under the same id.
- this.verifyPlanInstantiations.delete(operationId);
- }
- }
- }
-
- /**
- * Load the final assistant message row from the DB and return its text
- * content, for completions whose Redis-side state carried no assistant
- * text (see the DB recovery note in {@link dispatchHooks}). Non-fatal: any
- * failure just leaves the event as-built.
- */
- private async recoverLastAssistantContent(
- operationId: string,
- assistantMessageId: string | undefined,
- userId: string,
- topicId?: string,
- ): Promise<string | undefined> {
- if (!assistantMessageId && !topicId) return undefined;
-
- try {
- const messageModel =
- userId === this.userId
- ? this.messageModel
- : new MessageModel(this.serverDB, userId, this.workspaceId, undefined, {
- includeShareVisitor: this.includeShareVisitor,
- });
-
- // 1. The row the event already names (client-runtime `metadata.assistantMessageId`,
- // or the final assistant leaf in state).
- let row = assistantMessageId ? await messageModel.findById(assistantMessageId) : undefined;
- let recoveredFrom = assistantMessageId;
-
- // 2. Otherwise the run's own final assistant row, by the creation-time
- // provenance `call_llm` stamps on every assistant row it creates or
- // reuses (`metadata.operationId`). Unlike "the latest assistant row in
- // the topic", this is bound to THIS operation, so a topic that also
- // holds a concurrent run's rows cannot supply the answer (root cause of
- // the Discord thread bug where the bot kept repeating the same reply).
- if (!extractTextFromMessage(row)?.trim() && topicId) {
- const byOperation = await messageModel.findLatestAssistantByOperationId({
- operationId,
- topicId,
- });
- if (byOperation) {
- row = byOperation;
- recoveredFrom = byOperation.id;
- }
- }
-
- const raw = typeof row?.content === 'string' ? row.content : undefined;
- if (!raw?.trim()) return undefined;
-
- // Multimodal rows store `content` as serialized MessageContentPart[]
- // (see callLlmFinalizer / serializePartsForStorage) β€” sending
- // that verbatim would deliver raw JSON to the bot channel. Gate on the
- // row's `metadata.isMultimodal` flag (the same signal the app UI uses
- // in DisplayContent) rather than sniffing the string, so a legitimate
- // plain-text reply that happens to be a JSON array is preserved as-is.
- // Extract only the text parts; an image-only row recovers nothing.
- const content = extractTextFromMessage(row);
- if (!content?.trim()) return undefined;
-
- // console (not debug) so state/DB divergence stays visible in
- // production logs β€” the silent variant of this is what made
- // the Discord bot empty-reply issue hard to diagnose.
- console.warn(
- `[CompletionLifecycle][${operationId}] completion event had no assistant text; recovered ${content.length} chars from message ${recoveredFrom}`,
- );
- return content;
- } catch (error) {
- log('[%s] recoverLastAssistantContent failed (non-fatal): %O', operationId, error);
- return undefined;
- }
- }
-
- /**
- * The assistant row an error belongs on. The client runtime names it in
- * `metadata.assistantMessageId`; a server `execAgent` turn leaves that unset,
- * so fall back to the run's own newest assistant row (`call_llm` stamps
- * `metadata.operationId` on it). Without this, a server run that fails with
- * no client online β€” a closed tab, a bot, a schedule β€” leaves an empty
- * bubble with no error card. Never the topic's latest row: that may belong
- * to an earlier turn or a concurrent run.
- */
- private async resolveErrorMessageId(
- operationId: string,
- metadata: { assistantMessageId?: string } | undefined,
- runOrigin: { topicId?: string; userId?: string },
- ): Promise<string | undefined> {
- if (metadata?.assistantMessageId) return metadata.assistantMessageId;
- if (!runOrigin.topicId || (runOrigin.userId && runOrigin.userId !== this.userId)) return;
-
- try {
- const row = await this.messageModel.findLatestAssistantByOperationId({
- operationId,
- topicId: runOrigin.topicId,
- });
- return row?.id;
- } catch (error) {
- log('[%s] Failed to resolve the run assistant row for its error: %O', operationId, error);
- return undefined;
- }
- }
-
- private buildLifecycleEvent(operationId: string, state: any, reason: string) {
- const metadata = state?.metadata || {};
- const runOrigin = state?.origin ?? {};
- const messages = normalizeCompletionMessages(
- Array.isArray(state?.messages) ? state.messages : [],
- );
-
- // Pull text content off the **final** assistant turn. Content may be a
- // plain string or an OpenAI-style multimodal part array; for the array
- // case we concatenate the text parts so the reply body is preserved.
- //
- // We deliberately match on `role === 'assistant'` only β€” not on whether
- // the turn has any text β€” so an image-only or tool-output final turn
- // doesn't fall through to an earlier assistant message and ship stale
- // text alongside the current attachments.
- const lastAssistantMessage = findLastAssistantMessage(messages);
- const lastAssistantContent = lastAssistantMessage
- ? extractTextFromMessageContent(lastAssistantMessage.content)
- : undefined;
-
- // Operation-level metadata only carries `assistantMessageId` on the client
- // runtime path; a server `execAgent` turn leaves it unset (`{}` in DB). Fall
- // back to the persisted id on the final assistant message row in state so the
- // completion event can anchor deferred skill synthesis to this turn (skill
- // synthesis deferred from inbound to turn completion so it uses the full
- // trajectory β€” tool sequence + final product β€” not just the user prompt).
- // A metadata value, when present, still wins.
- const assistantMessageId =
- metadata?.assistantMessageId ?? (lastAssistantMessage as { id?: string } | undefined)?.id;
-
- const attachments = extractOutboundAttachments(messages);
-
- const duration = state?.createdAt
- ? Date.now() - new Date(state.createdAt).getTime()
- : undefined;
-
- // On the error path, normalize the runtime error once so the lifecycle
- // event carries the stable taxonomy fields (errorType + attribution + the
- // budget context an admission gate attached). Bot reply renderers switch on
- // these to surface a perceivable cause (network / quota / provider outage /
- // which allowance ran out) instead of an opaque Operation ID. Mirrors the
- // same normalization dispatchHooks runs before writing the error onto the
- // assistant message row.
- const formattedError = state?.error ? formatErrorForState(state.error) : undefined;
-
- return {
- assistantMessageId,
- event: {
- agentId: runOrigin.agentId || '',
- attachments: attachments.length > 0 ? attachments : undefined,
- cost: state?.cost?.total,
- duration,
- errorAttribution: formattedError?.attribution,
- errorBudget: readErrorBudgetContext(formattedError),
- errorHeterogeneous: readHeterogeneousErrorContext(formattedError),
- errorDetail: state?.error,
- errorMessage: this.extractErrorMessage(state?.error) || String(state?.error || ''),
- errorType: formattedError?.type === undefined ? undefined : String(formattedError.type),
- finalState: state,
- lastAssistantContent,
- llmCalls: state?.usage?.llm?.apiCalls,
- operationId,
- reason,
- status: state?.status || reason,
- steps: state?.stepCount || 0,
- toolCalls: state?.usage?.tools?.totalCalls,
- topicId: runOrigin.topicId,
- totalTokens: state?.usage?.llm?.tokens?.total,
- userId: runOrigin.userId || this.userId,
- },
- metadata,
- origin: runOrigin,
- };
- }
-}
-
-// --------------------------------------------------------------------------
-// Outbound attachment extraction
-// --------------------------------------------------------------------------
-
-type OutboundAttachment = {
- data?: string;
- fetchUrl?: string;
- mimeType?: string;
- name?: string;
- type: 'image' | 'file' | 'video' | 'audio';
-};
-
-const DATA_URL_RE = /^data:([^;]+);base64,(.+)$/;
-
-const inferAttachmentTypeFromMime = (mimeType: string | undefined): OutboundAttachment['type'] => {
- if (!mimeType) return 'file';
- if (mimeType.startsWith('image/')) return 'image';
- if (mimeType.startsWith('video/')) return 'video';
- if (mimeType.startsWith('audio/')) return 'audio';
- return 'file';
-};
-
-/**
- * Materialize a `url` field β€” either a `data:` URL (extract base64 inline) or
- * a remote URL (record fetchUrl). Returns undefined for unsupported shapes.
- */
-const buildAttachmentFromUrl = (
- url: string | undefined,
- fallbackType: OutboundAttachment['type'] = 'image',
-): OutboundAttachment | undefined => {
- if (!url || typeof url !== 'string') return undefined;
- const dataMatch = url.match(DATA_URL_RE);
- if (dataMatch) {
- const mimeType = dataMatch[1];
- return {
- data: dataMatch[2],
- mimeType,
- type: inferAttachmentTypeFromMime(mimeType),
- };
- }
- // Bare http(s) URL β€” let the downstream messenger fetch it lazily.
- if (/^https?:\/\//.test(url)) {
- return { fetchUrl: url, type: fallbackType };
- }
- return undefined;
-};
-
-/**
- * Pull text out of a message's `content` field. Accepts both string and
- * OpenAI-style multimodal arrays `[{ type: 'text', text }, { type: 'image_url', image_url: { url } }]`.
- */
-export const extractTextFromMessageContent = (content: unknown): string | undefined => {
- if (typeof content === 'string') return content || undefined;
- if (!Array.isArray(content)) return undefined;
- const parts: string[] = [];
- for (const part of content) {
- if (typeof part === 'string') {
- parts.push(part);
- } else if (part && typeof part === 'object' && (part as any).type === 'text') {
- const text = (part as { text?: unknown }).text;
- if (typeof text === 'string') parts.push(text);
- }
- }
- const joined = parts.join('');
- return joined || undefined;
-};
-
-/**
- * Extract text from either an in-memory message or a DB-rehydrated row.
- * Persisted multimodal content is serialized, so only deserialize when the
- * row's explicit metadata flag identifies that storage representation.
- */
-export const extractTextFromMessage = (message: unknown): string | undefined => {
- if (!isRecord(message)) return undefined;
-
- const metadata = isRecord(message.metadata) ? message.metadata : undefined;
- const content =
- typeof message.content === 'string' && metadata?.isMultimodal === true
- ? (deserializeParts(message.content) ?? message.content)
- : message.content;
-
- return extractTextFromMessageContent(content);
-};
-
-/**
- * Expand display-only assistant groups back into the assistant/tool sequence
- * expected by terminal lifecycle consumers.
- *
- * DB rehydration runs conversation-flow parsing, which folds an entire tool
- * chain β€” including its final toolless assistant turn β€” into one
- * `assistantGroup` whose own content is empty. Completion hooks must inspect
- * the persisted leaf turns rather than that virtual wrapper, otherwise they
- * lose both the final text and the message id used by DB recovery.
- */
-export const normalizeCompletionMessages = (
- messages: unknown[],
-): Record<PropertyKey, unknown>[] => {
- const normalized: Record<PropertyKey, unknown>[] = [];
-
- for (const message of messages) {
- if (!isRecord(message)) continue;
-
- const isAssistantGroup = message.role === 'assistantGroup' || message.role === 'supervisor';
- if (!isAssistantGroup) {
- normalized.push(message);
- continue;
- }
-
- if (!Array.isArray(message.children) || message.children.length === 0) {
- normalized.push({ ...message, role: 'assistant' });
- continue;
- }
-
- const groupStartIndex = normalized.length;
- for (const child of message.children) {
- if (!isRecord(child) || child.council) continue;
-
- normalized.push({ ...child, role: 'assistant' });
-
- if (!Array.isArray(child.tools)) continue;
- for (const tool of child.tools) {
- if (!isRecord(tool) || !isRecord(tool.result)) continue;
-
- normalized.push({
- content: tool.result.content,
- id: tool.result.id,
- role: 'tool',
- tool_call_id: tool.id,
- });
- }
- }
-
- // A virtual group containing only non-message blocks (for example a
- // council block) still marks the latest assistant boundary. Preserve an
- // empty leaf so completion never falls back to stale text from an older
- // turn.
- if (normalized.length === groupStartIndex) {
- normalized.push({ ...message, role: 'assistant' });
- }
- }
-
- return normalized;
-};
-
-/**
- * Find the final assistant boundary after display-only groups have been
- * normalized. Match by role rather than content so an empty/image-only final
- * turn never falls through to stale text from an earlier assistant message.
- */
-export const findLastAssistantMessage = (
- messages: Record<PropertyKey, unknown>[],
-): Record<PropertyKey, unknown> | undefined =>
- messages
- .slice()
- .reverse()
- .find((message) => message.role === 'assistant');
-
-/**
- * Extract image/file parts from a message's `content` array. Each entry is
- * mapped to the JSON-safe outbound attachment shape (data or fetchUrl).
- */
-const extractAttachmentsFromContent = (content: unknown): OutboundAttachment[] => {
- if (!Array.isArray(content)) return [];
- const out: OutboundAttachment[] = [];
- for (const part of content) {
- if (!part || typeof part !== 'object') continue;
- const type = (part as { type?: unknown }).type;
- if (type === 'image_url') {
- const url = (part as { image_url?: { url?: string } }).image_url?.url;
- const att = buildAttachmentFromUrl(url, 'image');
- if (att) out.push(att);
- } else if (type === 'image') {
- // Anthropic-style: { type: 'image', source: { type: 'base64', media_type, data } }
- const source = (part as { source?: { data?: string; media_type?: string; type?: string } })
- .source;
- if (source?.type === 'base64' && source.data) {
- const mimeType = source.media_type;
- out.push({
- data: source.data,
- mimeType,
- type: inferAttachmentTypeFromMime(mimeType),
- });
- } else if (source?.type === 'url') {
- const url = (source as { url?: string }).url;
- const att = buildAttachmentFromUrl(url, 'image');
- if (att) out.push(att);
- }
- } else if (type === 'file' || type === 'file_url') {
- const file = (part as { file?: { url?: string; name?: string; mime_type?: string } }).file;
- const att = buildAttachmentFromUrl(file?.url, 'file');
- if (att) {
- att.name = file?.name ?? att.name;
- att.mimeType = file?.mime_type ?? att.mimeType;
- out.push(att);
- }
- }
- }
- return out;
-};
-
-/**
- * Walk recent messages and collect outbound image/file attachments to send
- * alongside the reply. Scans the last assistant message *and* any tool
- * messages that came after the previous assistant turn β€” tool-generated
- * images (e.g. a drawing tool that returns an image_url result) need to be
- * delivered with the next reply.
- *
- * Deduplicates by data/fetchUrl identity.
- */
-const extractOutboundAttachments = (messages: any[]): OutboundAttachment[] => {
- if (!Array.isArray(messages) || messages.length === 0) return [];
-
- // Walk from the end backwards: collect attachments until we hit the
- // previous assistant turn that already has text β€” that boundary marks
- // "the current reply window".
- const collected: OutboundAttachment[] = [];
- let crossedFinalAssistant = false;
-
- for (let i = messages.length - 1; i >= 0; i--) {
- const msg = messages[i];
- if (!msg || typeof msg !== 'object') continue;
- const role = (msg as { role?: string }).role;
- const content = (msg as { content?: unknown }).content;
-
- if (role === 'assistant') {
- if (!crossedFinalAssistant) {
- // Only the final reply's Markdown expresses an intent to send images.
- // Do not promote generation state or intermediate tool Markdown.
- const attachments: OutboundAttachment[] = [];
- const text = extractTextFromMessageContent(content);
- if (text) {
- for (const url of extractFinalReplyImageUrls(text)) {
- const attachment = buildAttachmentFromUrl(url, 'image');
- if (attachment) attachments.push(attachment);
- }
- }
- attachments.push(...extractAttachmentsFromContent(content));
- collected.unshift(...attachments);
- crossedFinalAssistant = true;
- continue;
- }
- // A previous assistant turn β€” stop walking, we don't want to dredge up
- // attachments from prior conversation rounds.
- break;
- }
-
- if (role === 'tool') {
- // Tool results between the previous assistant turn and the final one.
- collected.unshift(...extractAttachmentsFromContent(content));
- }
- }
-
- // Prepending each message preserves both message and within-message order.
- const seen = new Set<string>();
- const result: OutboundAttachment[] = [];
- for (const att of collected) {
- const key = att.fetchUrl ?? att.data ?? '';
- if (!key || seen.has(key)) continue;
- seen.add(key);
- result.push(att);
- }
- return result;
-};
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts
new file mode 100644
index 00000000000..a40cde05dac
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts
@@ -0,0 +1,112 @@
+/**
+ * Locating the run's own assistant message row in the database.
+ */
+import debug from 'debug';
+
+import { MessageModel } from '@/database/models/message';
+
+import { extractTextFromMessage } from './messageContent';
+import type { CompletionLifecycleDeps } from './types';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+/**
+ * Load the final assistant message row from the DB and return its text
+ * content, for completions whose Redis-side state carried no assistant
+ * text (see the DB recovery note in {@link dispatchHooks}). Non-fatal: any
+ * failure just leaves the event as-built.
+ */
+export async function recoverLastAssistantContent(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ assistantMessageId: string | undefined,
+ userId: string,
+ topicId?: string,
+): Promise<string | undefined> {
+ if (!assistantMessageId && !topicId) return undefined;
+
+ try {
+ const messageModel =
+ userId === deps.userId
+ ? deps.messageModel
+ : new MessageModel(deps.serverDB, userId, deps.workspaceId, undefined, {
+ includeShareVisitor: deps.includeShareVisitor,
+ });
+
+ // 1. The row the event already names (client-runtime `metadata.assistantMessageId`,
+ // or the final assistant leaf in state).
+ let row = assistantMessageId ? await messageModel.findById(assistantMessageId) : undefined;
+ let recoveredFrom = assistantMessageId;
+
+ // 2. Otherwise the run's own final assistant row, by the creation-time
+ // provenance `call_llm` stamps on every assistant row it creates or
+ // reuses (`metadata.operationId`). Unlike "the latest assistant row in
+ // the topic", this is bound to THIS operation, so a topic that also
+ // holds a concurrent run's rows cannot supply the answer (root cause of
+ // the Discord thread bug where the bot kept repeating the same reply).
+ if (!extractTextFromMessage(row)?.trim() && topicId) {
+ const byOperation = await messageModel.findLatestAssistantByOperationId({
+ operationId,
+ topicId,
+ });
+ if (byOperation) {
+ row = byOperation;
+ recoveredFrom = byOperation.id;
+ }
+ }
+
+ const raw = typeof row?.content === 'string' ? row.content : undefined;
+ if (!raw?.trim()) return undefined;
+
+ // Multimodal rows store `content` as serialized MessageContentPart[]
+ // (see callLlmFinalizer / serializePartsForStorage) β€” sending
+ // that verbatim would deliver raw JSON to the bot channel. Gate on the
+ // row's `metadata.isMultimodal` flag (the same signal the app UI uses
+ // in DisplayContent) rather than sniffing the string, so a legitimate
+ // plain-text reply that happens to be a JSON array is preserved as-is.
+ // Extract only the text parts; an image-only row recovers nothing.
+ const content = extractTextFromMessage(row);
+ if (!content?.trim()) return undefined;
+
+ // console (not debug) so state/DB divergence stays visible in
+ // production logs β€” the silent variant of this is what made
+ // the Discord bot empty-reply issue hard to diagnose.
+ console.warn(
+ `[CompletionLifecycle][${operationId}] completion event had no assistant text; recovered ${content.length} chars from message ${recoveredFrom}`,
+ );
+ return content;
+ } catch (error) {
+ log('[%s] recoverLastAssistantContent failed (non-fatal): %O', operationId, error);
+ return undefined;
+ }
+}
+
+/**
+ * The assistant row an error belongs on. The client runtime names it in
+ * `metadata.assistantMessageId`; a server `execAgent` turn leaves that unset,
+ * so fall back to the run's own newest assistant row (`call_llm` stamps
+ * `metadata.operationId` on it). Without this, a server run that fails with
+ * no client online β€” a closed tab, a bot, a schedule β€” leaves an empty
+ * bubble with no error card. Never the topic's latest row: that may belong
+ * to an earlier turn or a concurrent run.
+ */
+export async function resolveErrorMessageId(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ metadata: { assistantMessageId?: string } | undefined,
+ runOrigin: { topicId?: string; userId?: string },
+): Promise<string | undefined> {
+ if (metadata?.assistantMessageId) return metadata.assistantMessageId;
+ if (!runOrigin.topicId || (runOrigin.userId && runOrigin.userId !== deps.userId)) return;
+
+ try {
+ const row = await deps.messageModel.findLatestAssistantByOperationId({
+ operationId,
+ topicId: runOrigin.topicId,
+ });
+ return row?.id;
+ } catch (error) {
+ log('[%s] Failed to resolve the run assistant row for its error: %O', operationId, error);
+ return undefined;
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/fileWorks.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/fileWorks.ts
new file mode 100644
index 00000000000..6f0fcbb7451
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/fileWorks.ts
@@ -0,0 +1,120 @@
+/**
+ * File / GitHub Work registration at the end of a run.
+ */
+import debug from 'debug';
+
+import { WorkModel } from '@/database/models/work';
+import {
+ registerWorksForOperation,
+ resolveRunWorkAccessScope,
+} from '@/server/services/workRegistration';
+
+import type { CompletionLifecycleDeps } from './types';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+/**
+ * Register the operation's Works: entity files edited this round
+ * (pptx/xlsx/docx/pdf, …) as `file` Works β€” one version per operation,
+ * exported from the sandbox β€” plus github issue/PR Works recovered from
+ * hetero / device shell records (codex / claude-code / lobe-local-system
+ * `gh` runs), which never pass the skill-tool registration hook.
+ *
+ * Idempotent per state object: only when EVERY candidate registered (the
+ * returned outcome reports `failed === 0`) is a `_fileWorksRegistered` marker
+ * stamped onto `state.metadata` so the dispatchHooks backstop (which receives
+ * the same state later in the request) skips the duplicate scan. A PARTIAL
+ * failure leaves the marker unset so the backstop re-runs and retries just the
+ * failed candidates β€” file registration is idempotent per (operation, file)
+ * via a DB existence probe, github registration per (work, toolCallId) via
+ * the version write's unique guard, so a QStash retry that lost the marker is
+ * safe.
+ *
+ * The gateway/queue executor calls this BEFORE the terminal
+ * `coordinator.saveStepResult`: that save publishes `agent_runtime_end`,
+ * whose `uiMessages` snapshot the client adopts as the settled message list β€”
+ * Work rows must exist by then or the file-Work card stays absent until a
+ * manual refresh. When entity edits are present, the executor suppresses the
+ * early `visible_output_end`, so perceived loading covers export and
+ * registration until the terminal snapshot is published.
+ *
+ * Awaited, NOT fire-and-forget: on serverless the runtime can freeze the
+ * moment the response is sent, silently dropping any still-pending background
+ * write. Fully self-guarded β€” a failure only logs, never throws. Both a thrown
+ * whole-function failure AND a partial per-file failure (outcome `failed > 0`)
+ * leave the marker unset so a later call retries the outstanding files.
+ */
+export async function registerFileWorks(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ state: any,
+): Promise<void> {
+ if (state?.metadata?._fileWorksRegistered) return;
+ try {
+ // Share visitor runs register under the share scope of their visitor
+ // topic (both the file scan below and the anchor lookup that follows).
+ const shareVisitor = state?.principal?.actor?.shareVisitor ?? null;
+ const accessScope = resolveRunWorkAccessScope({
+ shareVisitor,
+ topicId: state?.origin?.topicId,
+ });
+ if (accessScope === null) {
+ log('[%s] Skipping Work registration: share visitor run has no topic', operationId);
+ return;
+ }
+
+ const outcome = await registerWorksForOperation({
+ agentShareVisitor: shareVisitor,
+ // The round's final assistant message β€” the shell github scan stamps the
+ // Work display anchor onto it for hetero runs (see registerWorksForOperation).
+ assistantMessageId:
+ state?.metadata?.workAssistantMessageId ?? state?.metadata?.assistantMessageId ?? null,
+ // Live terminal totals: on the pre-snapshot path the op row's cost/usage
+ // columns are not persisted yet (recordCompletion runs later), so the
+ // registration must not rely on reading them back from the DB.
+ finalCost: state?.cost ?? null,
+ finalUsage: state?.usage ?? null,
+ operationId,
+ serverDB: deps.serverDB,
+ userId: state?.origin?.userId || deps.userId,
+ workspaceId: deps.workspaceId,
+ });
+ // Skill tools may have registered Works before the terminal file scan.
+ // Query the registry instead of inferring output from display messages.
+ const works = await new WorkModel(
+ deps.serverDB,
+ state?.origin?.userId || deps.userId,
+ deps.workspaceId,
+ accessScope,
+ ).listByRootOperation({ includeFileWorks: true, limit: 1, rootOperationId: operationId });
+ if (works.length > 0) {
+ const assistantMessageId =
+ state?.metadata?.workAssistantMessageId ??
+ state?.metadata?.assistantMessageId ??
+ outcome.anchorMessageId;
+ if (!assistantMessageId) {
+ log('[%s] No assistant message available for registered Works', operationId);
+ return;
+ }
+ const result = await deps.messageModel.update(assistantMessageId, {
+ metadata: {
+ work: {
+ rootOperationId: operationId,
+ userMessageId: state?.origin?.sourceMessageId,
+ },
+ },
+ });
+ if (!result.success) {
+ log('[%s] Failed to stamp Work anchor on %s', operationId, assistantMessageId);
+ return;
+ }
+ }
+ // Stamp the idempotency marker ONLY when nothing failed. A partial failure
+ // (some files exported/registered, others did not) must NOT be recorded as
+ // a completed registration, or the dispatchHooks backstop would skip the
+ // retry and the user gets neither a Work nor the edited-files fallback.
+ if (state?.metadata && outcome.failed === 0) state.metadata._fileWorksRegistered = true;
+ } catch (error) {
+ log('[%s] registerWorksForOperation failed (non-fatal): %O', operationId, error);
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts
new file mode 100644
index 00000000000..3d959339726
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts
@@ -0,0 +1,432 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import * as agentSignalService from '@/server/services/agentSignal';
+import * as verifyServices from '@/server/services/verify';
+import type * as WorkRegistrationModule from '@/server/services/workRegistration';
+
+import { hookDispatcher } from '../hooks';
+import { CompletionLifecycle } from '.';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ // Keep the real scope resolver: it is pure, and the share-visitor test
+ // asserts the scope it derives reaches both the scan and the anchor lookup.
+ ...(await importOriginal<typeof WorkRegistrationModule>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+
+describe('CompletionLifecycle.dispatchHooks β€” lastAssistantContent DB recovery (Discord bot empty-reply)', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const buildDoneState = (assistantContent: string | undefined) => ({
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ { content: assistantContent, id: 'msg-assistant', role: 'assistant' },
+ ],
+ host: { hooks: [] },
+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
+ status: 'done',
+ });
+
+ const setupSpies = (lifecycle: CompletionLifecycle) => {
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
+ vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ vi.spyOn(console, 'warn').mockImplementation(function () {});
+ return vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ };
+
+ it('recovers the reply text from the DB row when the state carries no assistant text', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockResolvedValue({ content: 'the real reply', id: 'msg-assistant' });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(findById).toHaveBeenCalledWith('msg-assistant');
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'the real reply' }),
+ [],
+ );
+ });
+
+ it('extracts final Markdown images when the reply is recovered from the database', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const content = '![Result](https://cdn.example.com/recovered.png)';
+ (lifecycle as any).messageModel = {
+ findById: vi.fn().mockResolvedValue({ content, id: 'msg-assistant' }),
+ };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({
+ attachments: [{ fetchUrl: 'https://cdn.example.com/recovered.png', type: 'image' }],
+ lastAssistantContent: content,
+ }),
+ [],
+ );
+ });
+
+ it('recovers by the final assistantGroup child id when grouped state carries no text', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockResolvedValue({
+ content: 'the grouped reply from DB',
+ id: 'msg-group-final',
+ });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ {
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ {
+ children: [
+ { content: '', id: 'msg-tool-call', tools: [{ id: 'tool-call-1' }] },
+ { content: '', id: 'msg-group-final' },
+ ],
+ content: '',
+ id: 'msg-group',
+ role: 'assistantGroup',
+ },
+ ],
+ host: { hooks: [] },
+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
+ status: 'done',
+ },
+ 'done',
+ );
+
+ expect(findById).toHaveBeenCalledWith('msg-group-final');
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'the grouped reply from DB' }),
+ [],
+ );
+ });
+
+ it('does not hit the DB when the state already carries assistant text', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn();
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState('state reply'), 'done');
+
+ expect(findById).not.toHaveBeenCalled();
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'state reply' }),
+ [],
+ );
+ });
+
+ // The named row can be an empty placeholder while the run's real reply sits
+ // on another row (the Discord thread bug where the bot kept repeating the
+ // same message). Resolve it by the run's own provenance
+ // (`metadata.operationId`), never by "the latest assistant row in the topic" β€”
+ // a topic can hold a concurrent run's rows.
+ it('falls back to operation provenance when the named row is empty', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockResolvedValue({ content: '', id: 'msg-assistant' });
+ const findLatestAssistantByOperationId = vi
+ .fn()
+ .mockResolvedValue({ content: 'final step reply', id: 'msg-final-step' });
+ (lifecycle as any).messageModel = { findById, findLatestAssistantByOperationId };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(findById).toHaveBeenCalledWith('msg-assistant');
+ expect(findLatestAssistantByOperationId).toHaveBeenCalledWith({
+ operationId: 'op-1',
+ topicId: 'tpc-1',
+ });
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'final step reply' }),
+ [],
+ );
+ });
+
+ it('extracts only text parts when the DB row stores serialized multimodal content', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const serialized = JSON.stringify([
+ { text: 'ε›Ύι‡Œζ˜―δΈ€εͺ猫', type: 'text' },
+ { image: 'data:image/png;base64,xxx', type: 'image' },
+ ]);
+ const findById = vi.fn().mockResolvedValue({
+ content: serialized,
+ id: 'msg-assistant',
+ metadata: { isMultimodal: true },
+ });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'ε›Ύι‡Œζ˜―δΈ€εͺ猫' }),
+ [],
+ );
+ });
+
+ it('returns a plain-text reply verbatim even when it looks like a parts array', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ // A legitimate text answer that happens to be a JSON array with `type`
+ // fields β€” without metadata.isMultimodal it must NOT be parsed as parts.
+ const jsonLookalike = '[{"type":"custom","value":1}]';
+ const findById = vi.fn().mockResolvedValue({ content: jsonLookalike, id: 'msg-assistant' });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: jsonLookalike }),
+ [],
+ );
+ });
+
+ it('does not recover raw JSON from an image-only multimodal DB row', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const serialized = JSON.stringify([{ image: 'data:image/png;base64,xxx', type: 'image' }]);
+ const findById = vi.fn().mockResolvedValue({
+ content: serialized,
+ id: 'msg-assistant',
+ metadata: { isMultimodal: true },
+ });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: undefined }),
+ [],
+ );
+ });
+
+ it('leaves the event untouched when the DB row is empty too', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockResolvedValue({ content: '', id: 'msg-assistant' });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: undefined }),
+ [],
+ );
+ });
+
+ it('still dispatches the original event when the DB lookup throws', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockRejectedValue(new Error('db down'));
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: undefined }),
+ [],
+ );
+ });
+
+ it('skips recovery on the error path', async () => {
+ const lifecycle = buildLifecycle();
+ setupSpies(lifecycle);
+ const findById = vi.fn();
+ (lifecycle as any).messageModel = { findById, update: vi.fn().mockResolvedValue(undefined) };
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ { ...buildDoneState(''), error: { message: 'boom' }, status: 'error' },
+ 'error',
+ );
+
+ expect(findById).not.toHaveBeenCalled();
+ });
+});
+
+describe('CompletionLifecycle.emitSignalEvents β€” assistant anchor', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('ships the resolved assistantMessageId on the completed payload for a server turn', async () => {
+ // Regression: on a server execAgent turn the operation metadata has no
+ // assistantMessageId, so the agent.execution.completed event used to carry
+ // assistantMessageId=undefined and the deferred skill-synthesis handler
+ // no-oped. The payload must now anchor to the final assistant message row
+ // (so deferred skill synthesis seeds the skill under the completed turn's
+ // assistant group, not as a floating mainline root).
+ const emitSpy = vi
+ .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
+ .mockResolvedValue(undefined as any);
+
+ const lifecycle = buildLifecycle();
+ const state = {
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ { content: 'final answer', id: 'msg-assistant', role: 'assistant' },
+ ],
+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
+ stepCount: 2,
+ };
+
+ await lifecycle.emitSignalEvents('op-1', state, 'done');
+
+ expect(emitSpy).toHaveBeenCalledTimes(1);
+ const [emission] = emitSpy.mock.calls[0];
+ expect(emission.sourceType).toBe('agent.execution.completed');
+ expect(emission.payload).toMatchObject({
+ anchorMessageId: 'msg-assistant',
+ assistantMessageId: 'msg-assistant',
+ });
+ });
+
+ it('reads a memory-writer run thread when the terminal state carries no messages', async () => {
+ const emitSpy = vi
+ .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
+ .mockResolvedValue(undefined as any);
+ const lifecycle = buildLifecycle();
+ const query = vi.spyOn(lifecycle['messageModel'], 'query').mockResolvedValue([
+ {
+ id: 'msg-tool-call',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'addPreferenceMemory',
+ arguments: JSON.stringify({
+ summary: 'Answer in bullets',
+ title: 'Prefers bullet answers',
+ }),
+ id: 'call_pref',
+ identifier: 'lobe-user-memory',
+ type: 'builtin',
+ },
+ ],
+ },
+ {
+ content: 'Preference memory saved with memoryId: "mem_1" and preferenceId: "pref_1"',
+ id: 'msg-tool-result',
+ role: 'tool',
+ tool_call_id: 'call_pref',
+ },
+ ] as any);
+
+ await lifecycle.emitSignalEvents(
+ 'op-memory',
+ {
+ messages: [],
+ origin: {
+ agentId: 'agent-1',
+ signal: { kind: 'memory', sourceId: 'memory-source-1', topicId: 'tpc-1' },
+ threadId: 'thd-memory',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ },
+ stepCount: 3,
+ usage: {
+ tools: {
+ byTool: [{ calls: 1, errors: 0, name: 'lobe-user-memory/addPreferenceMemory' }],
+ },
+ },
+ },
+ 'done',
+ );
+
+ expect(query).toHaveBeenCalledWith(
+ expect.objectContaining({ threadId: 'thd-memory', topicId: 'tpc-1' }),
+ expect.anything(),
+ );
+ const [emission] = emitSpy.mock.calls[0];
+ expect(emission.payload.selfIteration.mutations[0].data.target).toMatchObject({
+ id: 'pref_1',
+ memoryId: 'mem_1',
+ title: 'Prefers bullet answers',
+ });
+ });
+
+ it('hydrates a persisted self-reflection marker when terminal state metadata lost it', async () => {
+ const emitSpy = vi
+ .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
+ .mockResolvedValue(undefined as any);
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn().mockResolvedValue({
+ metadata: {
+ agentSignal: {
+ agentId: 'agent-1',
+ kind: 'self-reflection',
+ sourceId: 'reflection-source-1',
+ topicId: 'tpc-1',
+ },
+ },
+ }),
+ };
+
+ await lifecycle.emitSignalEvents(
+ 'op-1',
+ {
+ messages: [{ content: 'review complete', id: 'msg-assistant', role: 'assistant' }],
+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
+ stepCount: 1,
+ },
+ 'done',
+ );
+
+ const [emission] = emitSpy.mock.calls[0];
+ expect(emission.payload).toMatchObject({
+ selfIteration: {
+ marker: {
+ agentId: 'agent-1',
+ kind: 'self-reflection',
+ sourceId: 'reflection-source-1',
+ topicId: 'tpc-1',
+ },
+ userId: 'user-1',
+ },
+ });
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.ts
new file mode 100644
index 00000000000..da779256c78
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.ts
@@ -0,0 +1,180 @@
+// @vitest-environment node
+import debug from 'debug';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import type * as WorkRegistrationModule from '@/server/services/workRegistration';
+
+import { CompletionLifecycle, isSuccessLikeCompletionReason } from '.';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ // Keep the real scope resolver: it is pure, and the share-visitor test
+ // asserts the scope it derives reaches both the scan and the anchor lookup.
+ ...(await importOriginal<typeof WorkRegistrationModule>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+
+describe('CompletionLifecycle.recordStart diagnostics', () => {
+ let debugNamespaces: string;
+
+ beforeEach(() => {
+ debugNamespaces = debug.disable();
+ debug.enable('lobe-server:completion-lifecycle');
+ });
+
+ afterEach(() => {
+ debug.enable(debugNamespaces);
+ vi.restoreAllMocks();
+ });
+
+ it.each([undefined, { _hooks: [] }])(
+ 'retains the database failure cause without persisted hooks: %j',
+ async (metadata) => {
+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(
+ new Error('connection refused'),
+ );
+ const output = vi.spyOn(debug, 'log').mockImplementation(() => {});
+
+ expect(await buildLifecycle().recordStart({ operationId: 'op-1', metadata })).toBe(false);
+ expect(output.mock.calls.flat().join(' ')).toContain('connection refused');
+ },
+ );
+
+ it('does not log database parameters containing hook credentials', async () => {
+ const secret = 'synthetic-hook-authorization';
+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(
+ new Error(`Failed query; params: ${secret}`),
+ );
+ const output = vi.spyOn(debug, 'log').mockImplementation(() => {});
+
+ expect(
+ await buildLifecycle().recordStart({
+ operationId: 'op-1',
+ metadata: { _hooks: [{ webhook: { headers: { Authorization: secret } } }] },
+ }),
+ ).toBe(false);
+ expect(output.mock.calls.flat().join(' ')).toContain('Failed to record operation start');
+ expect(output.mock.calls.flat().join(' ')).not.toContain(secret);
+ });
+});
+
+describe('isSuccessLikeCompletionReason', () => {
+ // Regression: file-Work registration was gated on `reason === 'done'` alone,
+ // silently skipping runs stopped by a step/cost cap even though the lifecycle
+ // persists those as status='done' and recovers their assistant content.
+ it('treats capped runs (max_steps / cost_limit) as successful completions', () => {
+ expect(isSuccessLikeCompletionReason('done')).toBe(true);
+ expect(isSuccessLikeCompletionReason('max_steps')).toBe(true);
+ expect(isSuccessLikeCompletionReason('cost_limit')).toBe(true);
+ });
+
+ it('rejects non-success terminal and parked reasons', () => {
+ expect(isSuccessLikeCompletionReason('error')).toBe(false);
+ expect(isSuccessLikeCompletionReason('interrupted')).toBe(false);
+ expect(isSuccessLikeCompletionReason('waiting_for_human')).toBe(false);
+ expect(isSuccessLikeCompletionReason('waiting_for_async_tool')).toBe(false);
+ });
+});
+
+describe('CompletionLifecycle.extractErrorMessage', () => {
+ it('extracts message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {
+ const lifecycle = buildLifecycle();
+ const error = {
+ _responseBody: { provider: 'lobehub' },
+ error: { message: 'Budget exceeded' },
+ errorType: 'InsufficientBudgetForModel',
+ provider: 'lobehub',
+ };
+
+ expect(lifecycle.extractErrorMessage(error)).toBe('Budget exceeded');
+ });
+
+ it('extracts message from ChatCompletionErrorPayload (InvalidProviderAPIKey)', () => {
+ const lifecycle = buildLifecycle();
+ const error = {
+ endpoint: 'https://cdn.example.com/v1',
+ error: {
+ code: '',
+ error: { code: '', message: 'ζ— ζ•ˆηš„δ»€η‰Œ', type: 'new_api_error' },
+ message: 'ζ— ζ•ˆηš„δ»€η‰Œ',
+ status: 401,
+ type: 'new_api_error',
+ },
+ errorType: 'InvalidProviderAPIKey',
+ provider: 'openai',
+ };
+
+ expect(lifecycle.extractErrorMessage(error)).toBe('ζ— ζ•ˆηš„δ»€η‰Œ');
+ });
+
+ it('extracts message from formatted ChatMessageError with body.error.message', () => {
+ const lifecycle = buildLifecycle();
+ const error = {
+ body: { error: { message: 'Rate limit exceeded' } },
+ message: 'InvalidProviderAPIKey',
+ type: 'InvalidProviderAPIKey',
+ };
+
+ expect(lifecycle.extractErrorMessage(error)).toBe('Rate limit exceeded');
+ });
+
+ it('extracts message from ChatMessageError with body.message', () => {
+ const lifecycle = buildLifecycle();
+ const error = {
+ body: { message: 'Something went wrong' },
+ message: 'error',
+ type: 'InternalServerError',
+ };
+
+ expect(lifecycle.extractErrorMessage(error)).toBe('Something went wrong');
+ });
+
+ it('falls back to error.message when body is absent', () => {
+ const lifecycle = buildLifecycle();
+ const error = { message: 'Connection timeout', type: 'NetworkError' };
+
+ expect(lifecycle.extractErrorMessage(error)).toBe('Connection timeout');
+ });
+
+ it('falls back to errorType when message is "error"', () => {
+ const lifecycle = buildLifecycle();
+ const error = { errorType: 'InsufficientBudgetForModel', message: 'error' };
+
+ expect(lifecycle.extractErrorMessage(error)).toBe('InsufficientBudgetForModel');
+ });
+
+ it('returns undefined for null/undefined', () => {
+ const lifecycle = buildLifecycle();
+
+ expect(lifecycle.extractErrorMessage(null)).toBeUndefined();
+ expect(lifecycle.extractErrorMessage(undefined)).toBeUndefined();
+ });
+
+ it('never returns [object Object] for nested error objects', () => {
+ const lifecycle = buildLifecycle();
+ const error = {
+ _responseBody: { provider: 'lobehub' },
+ error: { message: 'Budget exceeded' },
+ errorType: 'InsufficientBudgetForModel',
+ provider: 'lobehub',
+ };
+
+ const result = lifecycle.extractErrorMessage(error);
+ expect(result).not.toBe('[object Object]');
+ expect(typeof result).toBe('string');
+ expect(result).toBe('Budget exceeded');
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts
new file mode 100644
index 00000000000..c38148d4e76
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts
@@ -0,0 +1,348 @@
+// @vitest-environment node
+import { RequestTrigger } from '@lobechat/types';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import * as verifyServices from '@/server/services/verify';
+import type * as WorkRegistrationModule from '@/server/services/workRegistration';
+
+import { hookDispatcher } from '../hooks';
+import { CompletionLifecycle } from '.';
+import { flushMicrotasks, mockNotifyAgentRunCompleted } from './testUtils';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ // Keep the real scope resolver: it is pure, and the share-visitor test
+ // asserts the scope it derives reaches both the scan and the anchor lookup.
+ ...(await importOriginal<typeof WorkRegistrationModule>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+
+describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('awaits the start-time verify-plan instantiation before running the completion gate', async () => {
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ // Control exactly when the fire-and-forget instantiation settles.
+ let settle: () => void = () => {};
+ const instantiation = new Promise<void>((resolve) => {
+ settle = resolve;
+ });
+ const instantiateSpy = vi
+ .spyOn(verifyServices, 'instantiateVerifyPlanOnStart')
+ .mockReturnValue(instantiation);
+ const runVerifySpy = vi
+ .spyOn(verifyServices, 'runVerifyOnCompletion')
+ .mockResolvedValue(undefined);
+
+ // A top-level task op registers the (still-pending) instantiation at start.
+ await lifecycle.recordStart({ operationId: 'op-1', taskId: 'task-1' } as any);
+ expect(instantiateSpy).toHaveBeenCalledTimes(1);
+
+ // Completion fires while the plan instantiation is still in flight.
+ const doneState = { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
+ const dispatch = lifecycle.dispatchHooks('op-1', doneState, 'done');
+
+ // The gate must stay blocked on the pending instantiation, not race past it.
+ await flushMicrotasks();
+ expect(runVerifySpy).not.toHaveBeenCalled();
+
+ // Once the plan lands, the gate proceeds against the now-confirmed plan.
+ settle();
+ await dispatch;
+ expect(runVerifySpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not register an instantiation for a repair / verifier sub-op (parentOperationId set)', async () => {
+ const lifecycle = buildLifecycle();
+ const instantiateSpy = vi
+ .spyOn(verifyServices, 'instantiateVerifyPlanOnStart')
+ .mockResolvedValue(undefined);
+
+ await lifecycle.recordStart({
+ operationId: 'op-2',
+ parentOperationId: 'op-1',
+ taskId: 'task-1',
+ } as any);
+
+ expect(instantiateSpy).not.toHaveBeenCalled();
+ });
+});
+
+describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const parkedState = {
+ host: { hooks: [] },
+ origin: { agentId: 'a' },
+ status: 'waiting_for_async_tool',
+ };
+
+ it('persists the parked status but does NOT fire onComplete or unregister hooks', async () => {
+ const lifecycle = buildLifecycle();
+ const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await lifecycle.dispatchHooks('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();
+ });
+
+ it('treats a waiting_for_client park the same way: persisted, no onComplete, hooks kept', async () => {
+ const lifecycle = buildLifecycle();
+ const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ const clientPark = { ...parkedState, status: 'waiting_for_client' };
+
+ await lifecycle.dispatchHooks('op-1', clientPark, 'waiting_for_client');
+
+ expect(persistSpy).toHaveBeenCalledWith('op-1', clientPark, 'waiting_for_client', undefined);
+ expect(dispatchSpy).not.toHaveBeenCalled();
+ expect(unregisterSpy).not.toHaveBeenCalled();
+ });
+
+ it('fires onComplete and unregisters on a terminal completion', async () => {
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ const doneState = { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
+ await lifecycle.dispatchHooks('op-1', doneState, 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith('op-1', 'onComplete', expect.anything(), []);
+ expect(unregisterSpy).toHaveBeenCalledWith('op-1');
+ });
+});
+
+describe('CompletionLifecycle.dispatchHooks β€” completion notification', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ mockNotifyAgentRunCompleted.mockClear();
+ });
+
+ const stubSideEffects = (lifecycle: CompletionLifecycle) => {
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);
+ // The recall gate falls back to the op row when metadata carries no trigger.
+ (lifecycle as any).agentOperationModel = { findById: vi.fn(async () => null) };
+ };
+
+ const buildDoneState = (origin: Record<string, unknown> = {}) => ({
+ createdAt: new Date(Date.now() - 90_000).toISOString(),
+ messages: [{ content: 'final reply', role: 'assistant' }],
+ host: { hooks: [] },
+ origin: { agentId: 'agt_1', topicId: 'tpc_1', ...origin },
+ status: 'done',
+ });
+
+ it('notifies with fields mapped from the lifecycle event on a done completion', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ userId: 'user-2' }), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
+ expect(mockNotifyAgentRunCompleted).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agt_1',
+ duration: expect.any(Number),
+ lastAssistantContent: 'final reply',
+ operationId: 'op-1',
+ topicId: 'tpc_1',
+ userId: 'user-2',
+ // Personal lifecycle (no workspaceId) forwards undefined β‡’ bare link.
+ workspaceId: undefined,
+ }),
+ );
+ });
+
+ it('forwards the workspace id so a team run gets a workspace-scoped deep link', async () => {
+ const lifecycle = new CompletionLifecycle({} as any, 'user-1', 'ws_1');
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ userId: 'user-2' }), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).toHaveBeenCalledWith(
+ expect.objectContaining({ workspaceId: 'ws_1' }),
+ );
+ });
+
+ // 'task' is TopicTrigger.RunTask (the task-runner funnel), not a RequestTrigger member.
+ it.each(['task', RequestTrigger.Bot, RequestTrigger.Eval, RequestTrigger.Api])(
+ 'does not notify for background %s-triggered completions',
+ async (trigger) => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ trigger }), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ },
+ );
+
+ // Scheduled = a user-deferred chat turn; Cron = the rate-limit auto-resume of
+ // a user's chat turn. Both are "user walked away" runs the recall exists for.
+ it.each([RequestTrigger.Chat, RequestTrigger.Scheduled, RequestTrigger.Cron])(
+ 'notifies for a user-recallable %s-triggered completion',
+ async (trigger) => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ trigger }), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('falls back to the op row trigger when metadata carries none (synthetic hetero path)', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ trigger: RequestTrigger.Bot })),
+ };
+
+ // heteroFinish/agentNotify build metadata via buildStateFromInput β€” no trigger.
+ await lifecycle.dispatchHooks('op-1', buildDoneState(), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('does not notify for internal child runs (verifier/repair pass parentOperationId only)', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ parentOperationId: 'op-parent', trigger: null })),
+ };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('does not notify for sub-agent completions', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ buildDoneState({ lineage: { isSubAgent: true } }),
+ 'done',
+ );
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('does not notify for in-group member completions (orchestrationRole without isSubAgent)', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ // execAgentMember stamps in-group members with orchestrationRole: 'member'
+ // but NOT isSubAgent β€” they are internal steps of the supervisor run.
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ buildDoneState({ lineage: { orchestrationRole: 'member' } }),
+ 'done',
+ );
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('preserves an in-group member role in synthesized completion state', () => {
+ const lifecycle = buildLifecycle();
+
+ const state = (lifecycle as any).buildStateFromInput({
+ operationId: 'op-member',
+ orchestrationRole: 'member',
+ });
+
+ expect(state.origin.lineage.orchestrationRole).toBe('member');
+ });
+
+ it.each(['max_steps', 'cost_limit'])(
+ 'notifies on the success-like capped terminal %s (still produced a deliverable)',
+ async (reason) => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(), reason);
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('does not notify on error / aborted terminals', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, origin: { agentId: 'agt_1' }, status: 'error' },
+ 'error',
+ );
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('a notification rejection never breaks the dispatch pipeline', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+ // Once-only: a persistent mockRejectedValue would survive afterEach
+ // (restoreAllMocks skips plain vi.fn, mockClear keeps implementations)
+ // and leak into later dispatchHooks('done') tests in this file.
+ mockNotifyAgentRunCompleted.mockRejectedValueOnce(new Error('push provider down'));
+
+ const doneState = { host: { hooks: [] }, origin: { agentId: 'agt_1' }, status: 'done' };
+ await expect(lifecycle.dispatchHooks('op-1', doneState, 'done')).resolves.toBeUndefined();
+ await flushMicrotasks();
+
+ expect(hookDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.anything(),
+ [],
+ );
+ expect(hookDispatcher.unregister).toHaveBeenCalledWith('op-1');
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts
new file mode 100644
index 00000000000..3f18488307a
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.dispatchHooks.test.ts
@@ -0,0 +1,408 @@
+// @vitest-environment node
+import { ChatErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as WorkRegistrationModule from '@/server/services/workRegistration';
+
+import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';
+import { CompletionLifecycle } from '.';
+import { mockSettleRunningOperation } from './testUtils';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ // Keep the real scope resolver: it is pure, and the share-visitor test
+ // asserts the scope it derives reaches both the scan and the anchor lookup.
+ ...(await importOriginal<typeof WorkRegistrationModule>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+
+describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('persists budget errors without downgrading them to AgentRuntimeError', async () => {
+ const lifecycle = buildLifecycle();
+ const updateMessage = vi.fn().mockResolvedValue({ success: true });
+ const budget = { required: 12 };
+
+ (lifecycle as any).messageModel = { update: updateMessage };
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ {
+ error: {
+ budget,
+ error: { message: 'Budget exceeded' },
+ errorType: ChatErrorType.FreePlanLimit,
+ provider: 'lobehub',
+ },
+ metadata: { assistantMessageId: 'msg-1' },
+ host: { hooks: [] },
+ status: 'error',
+ },
+ 'error',
+ );
+
+ expect(updateMessage).toHaveBeenCalledWith('msg-1', {
+ error: expect.objectContaining({
+ body: expect.objectContaining({
+ budget,
+ message: 'Budget exceeded',
+ provider: 'lobehub',
+ }),
+ message: 'Budget exceeded',
+ type: ChatErrorType.FreePlanLimit,
+ }),
+ });
+ });
+
+ it("writes the error onto the run's own assistant row when a server run carries no assistantMessageId", async () => {
+ // A server `execAgent` turn leaves `metadata.assistantMessageId` unset; with
+ // no client online (a closed tab, a bot, a schedule) nothing else writes
+ // the error, so the reply row would stay an empty bubble.
+ const lifecycle = buildLifecycle();
+ const updateMessage = vi.fn().mockResolvedValue({ success: true });
+ const findLatestAssistantByOperationId = vi.fn().mockResolvedValue({ id: 'msg-run' });
+
+ (lifecycle as any).messageModel = { findLatestAssistantByOperationId, update: updateMessage };
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ {
+ error: {
+ error: { reason: 'claim_timeout', recoverable: true },
+ errorType: 'ClientLlmExecutorUnavailable',
+ provider: 'lmstudio',
+ },
+ host: { hooks: [] },
+ metadata: {},
+ origin: { topicId: 'tpc-1' },
+ status: 'error',
+ },
+ 'error',
+ );
+
+ expect(findLatestAssistantByOperationId).toHaveBeenCalledWith({
+ operationId: 'op-1',
+ topicId: 'tpc-1',
+ });
+ expect(updateMessage).toHaveBeenCalledWith('msg-run', {
+ error: expect.objectContaining({ type: 'ClientLlmExecutorUnavailable' }),
+ });
+ });
+
+ it('rethrows critical webhook failures after terminal persistence', async () => {
+ const lifecycle = buildLifecycle();
+ const persistCompletion = vi
+ .spyOn(lifecycle as any, 'persistCompletion')
+ .mockResolvedValue(undefined);
+ const dispatch = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockRejectedValue(
+ new CriticalHookDeliveryError('task-on-complete', new Error('qstash down')),
+ );
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await expect(
+ lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, status: 'interrupted' },
+ 'interrupted',
+ ),
+ ).rejects.toThrow('Critical webhook delivery failed: task-on-complete');
+
+ expect(persistCompletion).toHaveBeenCalledBefore(dispatch);
+ });
+
+ it('does not dispatch hooks when another owner already interrupted the operation', async () => {
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(false);
+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await lifecycle.dispatchHooks('op-reclaimed', { host: { hooks: [] }, status: 'done' }, 'done');
+
+ 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 β€” the topic running mark', () => {
+ /**
+ * `recordCompletion` must land for the mark to be converged: the lifecycle
+ * treats an ending whose own row write failed as unproven, and a mark cleared
+ * on an unproven ending reads settled while `agent_operations` still says
+ * `running`.
+ */
+ const acceptingOperationModel = () => ({
+ findById: vi.fn(async () => null),
+ recordCompletion: vi.fn(async () => true),
+ sumChildUsage: vi.fn(async () => undefined),
+ });
+
+ const state = (overrides: Record<string, unknown> = {}) => ({
+ host: { hooks: [] },
+ messages: [{ content: 'final reply', role: 'assistant' }],
+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },
+ status: 'interrupted',
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ mockSettleRunningOperation.mockReset().mockResolvedValue({ status: 'settled' });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('drops the mark when an interrupted run reaches its terminal row', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ // A Stop is a visible ending the user already saw: `active`, the same status
+ // the client writes for an interrupted run.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
+ });
+
+ it('drops the mark for a clean finish, as unread', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
+
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
+ });
+
+ it('drops the mark for a run the step cap stopped, which never runs `finish`', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'max_steps');
+
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
+ });
+
+ it.each(['waiting_for_async_tool', 'waiting_for_client', 'waiting_for_human'])(
+ 'leaves the mark while the same operation is parked in %s',
+ async (reason) => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ status: reason }), reason);
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does nothing for a run with no topic', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ origin: { agentId: 'agt_1' } }), 'interrupted');
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('leaves a lease-expired abandon to the path that settles it', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'abandoned' })),
+ recordCompletion: vi.fn(
+ async (_id: string, params: { status: string }) => params.status === 'abandoned',
+ ),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'error' }), 'error', {
+ settledAsAbandoned: true,
+ skipErrorMessageWrite: true,
+ });
+
+ // `AbandonOperationService` owns the topic there, with its own status.
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('leaves the mark when the terminal row could not be written', async () => {
+ const lifecycle = buildLifecycle();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => null),
+ recordCompletion: vi.fn(async () => {
+ throw new Error('db is down');
+ }),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ // The operation's own end is unproven, so the topic must keep saying so.
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it('leaves the mark when no durable row exists to prove the ending', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => null),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('still converges when another owner already wrote the terminal row', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'interrupted' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ // The run is over β€” someone else just recorded it β€” and hooks still stay
+ // parked with that owner.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Two terminal callbacks can race for the same operation: `recordCompletion`
+ * accepts the first and refuses the second β€” its `where` matches every
+ * in-flight status plus an equal one, so a refusal proves the row already
+ * landed and carries a DIFFERENT outcome. The topic must then be settled for
+ * what landed. Settling for the late callback instead would flip `unread`
+ * (a clean finish) to `active` (an interruption) or the other way round,
+ * depending purely on which of the two reached its settle first.
+ */
+ it('settles for a `done` row when a late `interrupted` callback loses the race', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'done' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'interrupted' }), 'interrupted');
+
+ // The run finished cleanly, so the user may not have watched it.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
+ });
+
+ it('settles for an `interrupted` row when a late `done` callback loses the race', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'interrupted' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
+
+ // The stopping point was a visible interruption, not a clean finish.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
+ });
+
+ it('leaves the mark when the refused row is not an ending either', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ // `idle` is outside `recordCompletion`'s in-flight set, so a row that
+ // never started can refuse a terminal write while still not being over.
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'idle' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('treats losing the race to a newer run as a no-op', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+ mockSettleRunningOperation.mockResolvedValue({ status: 'conflict' });
+
+ await expect(lifecycle.dispatchHooks('op-1', state(), 'interrupted')).resolves.toBeUndefined();
+
+ expect(mockSettleRunningOperation).toHaveBeenCalledTimes(1);
+ });
+
+ it('never fails the completion when the topic cannot be settled', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+ mockSettleRunningOperation.mockRejectedValue(new Error('topic row is locked'));
+
+ await expect(lifecycle.dispatchHooks('op-1', state(), 'interrupted')).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts
new file mode 100644
index 00000000000..e162c6c7b3b
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.fileWorks.test.ts
@@ -0,0 +1,512 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';
+import { WorkModel } from '@/database/models/work';
+import type * as WorkRegistrationModule from '@/server/services/workRegistration';
+import { registerWorksForOperation } from '@/server/services/workRegistration';
+
+import { hookDispatcher } from '../hooks';
+import { CompletionLifecycle, CriticalAgentInterventionPersistenceError } from '.';
+import {
+ mockBuildRuntimeInterventionNotification,
+ mockListWorks,
+ mockNotifyAgentInterventionRequired,
+} from './testUtils';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ // Keep the real scope resolver: it is pure, and the share-visitor test
+ // asserts the scope it derives reaches both the scan and the anchor lookup.
+ ...(await importOriginal<typeof WorkRegistrationModule>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+
+describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ mockBuildRuntimeInterventionNotification.mockReset();
+ mockBuildRuntimeInterventionNotification.mockResolvedValue(undefined);
+ mockNotifyAgentInterventionRequired.mockReset();
+ mockNotifyAgentInterventionRequired.mockResolvedValue(undefined);
+ });
+
+ const pendingNotification: NotifyAgentInterventionRequiredParams = {
+ approvalMode: 'manual' as const,
+ batch: {
+ activityKey: '4369e854-719f-5301-bfa4-1f0742eec6ac',
+ allowedActions: ['approve_tool', 'reject_continue', 'stop'],
+ id: 'batch-1',
+ kind: 'single' as const,
+ sealed: true as const,
+ stepIndex: 3,
+ },
+ context: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ },
+ items: [
+ {
+ allowedActions: ['approve_tool', 'reject_continue', 'stop'],
+ interactionKind: 'tool_approval' as const,
+ requestRevision: { hash: 'a'.repeat(64), version: 0 },
+ sourceRef: {
+ toolCallId: 'call-1',
+ toolMessageId: 'tool-1',
+ type: 'runtime' as const,
+ },
+ summary: 'Run command',
+ surface: 'binary' as const,
+ },
+ ],
+ summary: 'Approval required',
+ systemActionEligibility: 'safe_single_binary' as const,
+ userId: 'user-1',
+ };
+
+ const stubDurablePendingRows = (lifecycle: CompletionLifecycle) => {
+ (lifecycle as any).messageModel = {
+ findById: vi.fn().mockResolvedValue({
+ id: 'tool-1',
+ parentId: 'assistant-1',
+ role: 'tool',
+ topicId: 'topic-1',
+ }),
+ findMessagePlugin: vi.fn().mockResolvedValue({
+ intervention: {
+ batchId: 'batch-1',
+ itemIndex: 0,
+ operationId: 'op-1',
+ status: 'pending',
+ stepIndex: 3,
+ },
+ toolCallId: 'call-1',
+ }),
+ };
+ };
+
+ it('publishes Review only after operation and every sealed batch row are durable', async () => {
+ const lifecycle = buildLifecycle();
+ const order: string[] = [];
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockImplementation(async () => {
+ order.push('persist-operation');
+ return true;
+ });
+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
+ mockNotifyAgentInterventionRequired.mockImplementation(async () => {
+ order.push('notify');
+ });
+ (lifecycle as any).messageModel = {
+ findById: vi.fn().mockImplementation(async () => {
+ order.push('read-message');
+ return {
+ id: 'tool-1',
+ parentId: 'assistant-1',
+ role: 'tool',
+ topicId: 'topic-1',
+ };
+ }),
+ findMessagePlugin: vi.fn().mockImplementation(async () => {
+ order.push('read-plugin');
+ return {
+ intervention: {
+ batchId: 'batch-1',
+ itemIndex: 0,
+ operationId: 'op-1',
+ status: 'pending',
+ stepIndex: 3,
+ },
+ toolCallId: 'call-1',
+ };
+ }),
+ };
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ 'waiting_for_human',
+ );
+
+ expect(mockNotifyAgentInterventionRequired).toHaveBeenCalledWith(pendingNotification);
+ expect(order[0]).toBe('persist-operation');
+ expect(order.at(-1)).toBe('notify');
+ });
+
+ it('fails the parked lifecycle when one row is outside the sealed batch', async () => {
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
+ (lifecycle as any).messageModel = {
+ findById: vi.fn().mockResolvedValue({
+ id: 'tool-1',
+ parentId: 'assistant-1',
+ role: 'tool',
+ topicId: 'topic-1',
+ }),
+ findMessagePlugin: vi.fn().mockResolvedValue({
+ intervention: {
+ batchId: 'late-batch',
+ itemIndex: 0,
+ operationId: 'op-1',
+ status: 'pending',
+ stepIndex: 3,
+ },
+ toolCallId: 'call-1',
+ }),
+ };
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await expect(
+ lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ 'waiting_for_human',
+ ),
+ ).rejects.toBeInstanceOf(CriticalAgentInterventionPersistenceError);
+
+ expect(mockNotifyAgentInterventionRequired).not.toHaveBeenCalled();
+ });
+
+ it('propagates a durable Review create failure so the parked lifecycle can retry', async () => {
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
+ mockNotifyAgentInterventionRequired.mockRejectedValueOnce(new Error('database unavailable'));
+ stubDurablePendingRows(lifecycle);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ const unregister = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await expect(
+ lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ 'waiting_for_human',
+ ),
+ ).rejects.toMatchObject({
+ cause: expect.objectContaining({ message: 'database unavailable' }),
+ name: 'CriticalAgentInterventionPersistenceError',
+ });
+
+ expect(hookDispatcher.dispatch).not.toHaveBeenCalled();
+ expect(unregister).not.toHaveBeenCalled();
+ });
+
+ it('continues after post-create push fanout fails inside the business slot', async () => {
+ const lifecycle = buildLifecycle();
+ const pushFanout = vi.fn().mockRejectedValue(new Error('APNs unavailable'));
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
+ mockNotifyAgentInterventionRequired.mockImplementation(async () => {
+ // Cloud owns this boundary: the generic row is already durable here, so
+ // downstream delivery is best-effort and must not reject the slot.
+ await pushFanout().catch(() => undefined);
+ });
+ stubDurablePendingRows(lifecycle);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ await expect(
+ lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ 'waiting_for_human',
+ ),
+ ).resolves.toBeUndefined();
+
+ expect(pushFanout).toHaveBeenCalledOnce();
+ expect(hookDispatcher.dispatch).toHaveBeenCalledOnce();
+ });
+
+ it('does not build a Review when the parked operation persistence loses its CAS', async () => {
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(false);
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ 'waiting_for_human',
+ );
+
+ expect(mockBuildRuntimeInterventionNotification).not.toHaveBeenCalled();
+ expect(mockNotifyAgentInterventionRequired).not.toHaveBeenCalled();
+ });
+
+ // Regression: the park is not a completed deliverable boundary. The fresh
+ // continuation sees the complete history and performs the terminal scan;
+ // registering here would freeze pre-approval file content too early.
+ it('does NOT register on a human-approval park before its continuation', async () => {
+ const mockRegister = vi.mocked(registerWorksForOperation);
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+
+ const parkedState = {
+ host: { hooks: [] },
+ origin: { agentId: 'a' },
+ status: 'waiting_for_human',
+ };
+ await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_human');
+
+ expect(mockRegister).not.toHaveBeenCalled();
+ });
+
+ it('does NOT register on an async-tool park (same op resumes and registers later)', async () => {
+ const mockRegister = vi.mocked(registerWorksForOperation);
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+
+ const parkedState = {
+ host: { hooks: [] },
+ origin: { agentId: 'a' },
+ status: 'waiting_for_async_tool',
+ };
+ await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_async_tool');
+
+ expect(mockRegister).not.toHaveBeenCalled();
+ });
+});
+
+describe('CompletionLifecycle.registerFileWorks', () => {
+ const mockRegister = vi.mocked(registerWorksForOperation);
+ beforeEach(() => {
+ mockListWorks.mockReset();
+ });
+
+ it('anchors an already registered Work after a folded tool turn with no file scan candidates', async () => {
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);
+ const lifecycle = buildLifecycle();
+ const update = vi
+ .spyOn(lifecycle['messageModel'], 'update')
+ .mockResolvedValue({ success: true });
+ const state = {
+ messages: [{ id: 'display-group', role: 'assistantGroup', children: [] }],
+ metadata: { workAssistantMessageId: 'final-assistant' },
+ origin: { sourceMessageId: 'source-user' },
+ };
+
+ await lifecycle.registerFileWorks('op-1', state);
+
+ expect(mockListWorks).toHaveBeenCalledWith({
+ includeFileWorks: true,
+ limit: 1,
+ rootOperationId: 'op-1',
+ });
+ expect(update).toHaveBeenCalledWith('final-assistant', {
+ metadata: { work: { rootOperationId: 'op-1', userMessageId: 'source-user' } },
+ });
+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
+ });
+
+ it('does not anchor a reply when only other operations have Works', async () => {
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+ const update = vi
+ .spyOn(lifecycle['messageModel'], 'update')
+ .mockResolvedValue({ success: true });
+
+ await lifecycle.registerFileWorks('op-1', {
+ metadata: { assistantMessageId: 'final-assistant' },
+ });
+
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('withholds the completion marker when an anchor write fails and retries it', async () => {
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);
+ const lifecycle = buildLifecycle();
+ const update = vi
+ .spyOn(lifecycle['messageModel'], 'update')
+ .mockResolvedValueOnce({ success: false })
+ .mockResolvedValueOnce({ success: true });
+ const state = { metadata: { assistantMessageId: 'final-assistant' } };
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
+ expect(update).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps registration retryable until the explicit final assistant id is available', async () => {
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);
+ const lifecycle = buildLifecycle();
+ const update = vi
+ .spyOn(lifecycle['messageModel'], 'update')
+ .mockResolvedValue({ success: true });
+ const state: { metadata: { assistantMessageId?: string } } = { metadata: {} };
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(update).not.toHaveBeenCalled();
+ expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');
+ state.metadata.assistantMessageId = 'final-assistant';
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
+ });
+
+ it('preserves completion idempotency when the shell scanner resolved a fallback anchor', async () => {
+ mockRegister.mockResolvedValue({ anchorMessageId: 'shell-assistant', attempted: 1, failed: 0 });
+ mockListWorks.mockResolvedValue([{ id: 'registered-shell-work' }]);
+ const lifecycle = buildLifecycle();
+ const update = vi
+ .spyOn(lifecycle['messageModel'], 'update')
+ .mockResolvedValue({ success: true });
+ const state = { metadata: {} };
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(update).toHaveBeenCalledWith('shell-assistant', {
+ metadata: { work: { rootOperationId: 'op-1', userMessageId: undefined } },
+ });
+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
+ mockRegister.mockClear();
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).not.toHaveBeenCalled();
+ });
+
+ it('registers once and stamps the state marker so later calls skip', async () => {
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 1, failed: 0 });
+ const lifecycle = buildLifecycle();
+ const state = {
+ cost: { total: 1.25 },
+ metadata: {},
+ origin: { userId: 'user-2' },
+ usage: { llm: { apiCalls: 2 } },
+ } as any;
+
+ await lifecycle.registerFileWorks('op-1', state);
+
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ // The terminal state's live totals ride along: on the pre-snapshot path the
+ // op row's cost/usage columns are not persisted yet.
+ expect(mockRegister).toHaveBeenCalledWith(
+ expect.objectContaining({
+ finalCost: { total: 1.25 },
+ finalUsage: { llm: { apiCalls: 2 } },
+ operationId: 'op-1',
+ userId: 'user-2',
+ }),
+ );
+ expect(state.metadata._fileWorksRegistered).toBe(true);
+
+ // The dispatchHooks backstop receives the same state later in the request β€”
+ // the marker must make that second call a no-op (no duplicate scan/export).
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ });
+
+ it('never throws and leaves the marker unset on failure so a later call retries', async () => {
+ mockRegister.mockClear();
+ mockRegister.mockRejectedValueOnce(new Error('sandbox export failed'));
+ const lifecycle = buildLifecycle();
+ const state = { metadata: {} } as any;
+
+ await expect(lifecycle.registerFileWorks('op-1', state)).resolves.toBeUndefined();
+ expect(state.metadata._fileWorksRegistered).toBeUndefined();
+
+ mockRegister.mockResolvedValueOnce({ attempted: 1, failed: 0 });
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).toHaveBeenCalledTimes(2);
+ expect(state.metadata._fileWorksRegistered).toBe(true);
+ });
+
+ it('leaves the marker unset on a PARTIAL failure, then stamps it once all files land', async () => {
+ // Regression: registerWorksForOperation swallows per-file failures and
+ // never rejects, so a partial failure resolves normally. The marker must be
+ // gated on the outcome (`failed === 0`), NOT stamped unconditionally β€” else
+ // the dispatchHooks backstop skips the retry and the user gets neither a Work
+ // nor the edited-files fallback card for the file that failed to export.
+ mockRegister.mockClear();
+ const lifecycle = buildLifecycle();
+ const state = { metadata: {} } as any;
+
+ // One of two files failed to export/register this round.
+ mockRegister.mockResolvedValueOnce({ attempted: 2, failed: 1 });
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(state.metadata._fileWorksRegistered).toBeUndefined();
+
+ // The backstop retries; the previously-registered file short-circuits on the
+ // DB probe and the failed one now lands β†’ failed=0 β†’ marker set.
+ mockRegister.mockResolvedValueOnce({ attempted: 2, failed: 0 });
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).toHaveBeenCalledTimes(2);
+ expect(state.metadata._fileWorksRegistered).toBe(true);
+ });
+
+ it('tolerates a state without metadata', async () => {
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+
+ await expect(lifecycle.registerFileWorks('op-1', {} as any)).resolves.toBeUndefined();
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ });
+
+ it('registers and anchors a share visitor run under its visitor-topic share scope', async () => {
+ mockRegister.mockClear();
+ vi.mocked(WorkModel).mockClear();
+ mockRegister.mockResolvedValue({ attempted: 1, failed: 0 });
+ mockListWorks.mockResolvedValue([{ id: 'visitor-file-work' }]);
+ const lifecycle = buildLifecycle();
+ const update = vi
+ .spyOn(lifecycle['messageModel'], 'update')
+ .mockResolvedValue({ success: true });
+ const shareVisitor = { agentId: 'agt_1', shareId: 'share-1', visitorUserId: 'visitor-1' };
+ const state = {
+ metadata: { workAssistantMessageId: 'final-assistant' },
+ origin: { sourceMessageId: 'source-user', topicId: 'tpc_visitor', userId: 'user-1' },
+ principal: { actor: { shareVisitor } },
+ };
+
+ await lifecycle.registerFileWorks('op-1', state);
+
+ expect(mockRegister).toHaveBeenCalledWith(
+ expect.objectContaining({ agentShareVisitor: shareVisitor, operationId: 'op-1' }),
+ );
+ // The anchor lookup must read through the SAME scope the scan wrote under,
+ // or the visitor's Work is never found and the chip never renders.
+ expect(vi.mocked(WorkModel)).toHaveBeenCalledWith(expect.anything(), 'user-1', undefined, {
+ shareId: 'share-1',
+ topicId: 'tpc_visitor',
+ type: 'agentShare',
+ visitorUserId: 'visitor-1',
+ });
+ expect(update).toHaveBeenCalledWith('final-assistant', {
+ metadata: { work: { rootOperationId: 'op-1', userMessageId: 'source-user' } },
+ });
+ });
+
+ it('skips a share visitor run that has no topic instead of registering unscoped', async () => {
+ mockRegister.mockClear();
+ const lifecycle = buildLifecycle();
+ const state = {
+ metadata: {},
+ origin: { userId: 'user-1' },
+ principal: { actor: { shareVisitor: { shareId: 'share-1', visitorUserId: 'visitor-1' } } },
+ };
+
+ await expect(lifecycle.registerFileWorks('op-1', state)).resolves.toBeUndefined();
+ expect(mockRegister).not.toHaveBeenCalled();
+ expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.ts
new file mode 100644
index 00000000000..b93d592fdec
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.ts
@@ -0,0 +1,499 @@
+// @vitest-environment node
+import { type Message, parse } from '@lobechat/conversation-flow';
+import { describe, expect, it, vi } from 'vitest';
+
+import type * as WorkRegistrationModule from '@/server/services/workRegistration';
+
+import { CompletionLifecycle } from '.';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
+ // Keep the real scope resolver: it is pure, and the share-visitor test
+ // asserts the scope it derives reaches both the scan and the anchor lookup.
+ ...(await importOriginal<typeof WorkRegistrationModule>()),
+ registerWorksForOperation: vi.fn(),
+}));
+
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+
+describe('CompletionLifecycle.buildLifecycleEvent', () => {
+ const callBuild = (state: unknown, reason = 'completed') =>
+ (buildLifecycle() as any).buildLifecycleEvent('op-1', state, reason);
+
+ it('attaches Markdown images explicitly included in the final reply without changing its text', () => {
+ const url = 'https://cdn.example.com/f/file_image';
+ const content = `Here is the result: ![Result](${url})`;
+ const { event } = callBuild({ messages: [{ role: 'assistant', content }] });
+ expect(event.attachments).toEqual([{ fetchUrl: url, type: 'image' }]);
+ expect(event.lastAssistantContent).toBe(content);
+ });
+
+ it('preserves the order of distinct final-reply images', () => {
+ const { event } = callBuild({
+ messages: [
+ {
+ role: 'assistant',
+ content:
+ '![Before](https://cdn.example.com/before.png) ![After](https://cdn.example.com/after.png)',
+ },
+ ],
+ });
+ expect(event.attachments?.map((attachment: any) => attachment.fetchUrl)).toEqual([
+ 'https://cdn.example.com/before.png',
+ 'https://cdn.example.com/after.png',
+ ]);
+ });
+
+ it('parses reference images in final text parts and deduplicates structured images', () => {
+ const url = 'https://cdn.example.com/result.png';
+ const { event } = callBuild({
+ messages: [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'text', text: `![one][result] ![two](${url})\n\n[result]: ${url}` },
+ { type: 'image_url', image_url: { url } },
+ ],
+ },
+ ],
+ });
+ expect(event.attachments).toEqual([{ fetchUrl: url, type: 'image' }]);
+ });
+
+ it('does not promote tool state, tool Markdown, or an earlier reply to final attachments', () => {
+ const url = 'https://cdn.example.com/intermediate.png';
+ const { event } = callBuild({
+ messages: [
+ { role: 'assistant', content: `![earlier](${url})` },
+ { role: 'user', content: 'Analyze the result without sending an image.' },
+ { role: 'assistant', content: '', tools: [{ id: 'call-image' }] },
+ {
+ role: 'tool',
+ content: `![tool result](${url})`,
+ state: { generations: [{ asset: { url, type: 'image' } }] },
+ },
+ { role: 'assistant', content: 'The composition is balanced.' },
+ ],
+ });
+ expect(event.attachments).toBeUndefined();
+ });
+
+ it('does not treat ordinary links, code, escaped syntax or unsafe schemes as images', () => {
+ const content = [
+ 'https://cdn.example.com/plain.png',
+ '[download](https://cdn.example.com/download.png)',
+ '`![inline](https://cdn.example.com/inline.png)`',
+ '```md\n![fenced](https://cdn.example.com/fenced.png)\n```',
+ '\\![escaped](https://cdn.example.com/escaped.png)',
+ '![unsafe](file:///tmp/image.png)',
+ '![unsafe](javascript:alert)',
+ ].join('\n\n');
+ const { event } = callBuild({ messages: [{ role: 'assistant', content }] });
+ expect(event.attachments).toBeUndefined();
+ });
+
+ it('extracts text content from a plain-string final assistant turn', () => {
+ const state = {
+ messages: [
+ { content: 'user prompt', role: 'user' },
+ { content: 'final answer', role: 'assistant' },
+ ],
+ origin: { agentId: 'agent-1', userId: 'user-1' },
+ };
+
+ const { event } = callBuild(state);
+
+ expect(event.lastAssistantContent).toBe('final answer');
+ expect(event.attachments).toBeUndefined();
+ });
+
+ it('preserves the final answer after DB messages are parsed into an assistantGroup', () => {
+ const dbMessages: Message[] = [
+ {
+ content: 'user prompt',
+ createdAt: 0,
+ id: 'msg-user',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ content: '',
+ createdAt: 1,
+ id: 'msg-tool-call',
+ parentId: 'msg-user',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'builtin',
+ result_msg_id: 'msg-tool-result',
+ type: 'default',
+ },
+ ],
+ updatedAt: 1,
+ },
+ {
+ content: 'tool result',
+ createdAt: 2,
+ id: 'msg-tool-result',
+ parentId: 'msg-tool-call',
+ role: 'tool',
+ tool_call_id: 'tool-call-1',
+ updatedAt: 2,
+ },
+ {
+ content: 'final answer after tool use',
+ createdAt: 3,
+ id: 'msg-final',
+ parentId: 'msg-tool-result',
+ role: 'assistant',
+ updatedAt: 3,
+ },
+ ];
+ const { flatList } = parse(dbMessages);
+
+ expect(flatList.at(-1)?.role).toBe('assistantGroup');
+
+ const { assistantMessageId, event } = callBuild({ messages: flatList, metadata: {} });
+
+ expect(assistantMessageId).toBe('msg-final');
+ expect(event.lastAssistantContent).toBe('final answer after tool use');
+ });
+
+ it('extracts the final assistant leaf from an assistantGroup', () => {
+ const state = {
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ {
+ children: [
+ {
+ content: '',
+ id: 'msg-tool-call',
+ tools: [
+ {
+ id: 'tool-call-1',
+ result: { content: 'tool result', id: 'msg-tool-result' },
+ },
+ ],
+ },
+ { content: 'grouped final answer', id: 'msg-final' },
+ ],
+ content: '',
+ id: 'msg-group',
+ role: 'assistantGroup',
+ },
+ ],
+ origin: { agentId: 'agent-1', userId: 'user-1' },
+ };
+
+ const { assistantMessageId, event } = callBuild(state);
+
+ expect(assistantMessageId).toBe('msg-final');
+ expect(event.lastAssistantContent).toBe('grouped final answer');
+ });
+
+ it('keeps the final empty assistantGroup leaf instead of falling back to stale text', () => {
+ const state = {
+ messages: [
+ { content: 'stale prior answer', id: 'msg-stale', role: 'assistant' },
+ { content: 'follow-up prompt', id: 'msg-user', role: 'user' },
+ {
+ children: [{ content: '', id: 'msg-final' }],
+ content: '',
+ id: 'msg-group',
+ role: 'assistantGroup',
+ },
+ ],
+ metadata: {},
+ };
+
+ const { assistantMessageId, event } = callBuild(state);
+
+ expect(assistantMessageId).toBe('msg-final');
+ expect(event.lastAssistantContent).toBeUndefined();
+ });
+
+ it('treats an empty assistantGroup as the final assistant boundary', () => {
+ const state = {
+ messages: [
+ { content: 'stale prior answer', id: 'msg-stale', role: 'assistant' },
+ { children: [], content: '', id: 'msg-empty-group', role: 'assistantGroup' },
+ ],
+ metadata: {},
+ };
+
+ const { assistantMessageId, event } = callBuild(state);
+
+ expect(assistantMessageId).toBe('msg-empty-group');
+ expect(event.lastAssistantContent).toBeUndefined();
+ });
+
+ it('extracts attachments from grouped assistant and tool-result leaves', () => {
+ const state = {
+ messages: [
+ {
+ children: [
+ {
+ content: '',
+ id: 'msg-tool-call',
+ tools: [
+ {
+ id: 'tool-call-1',
+ result: {
+ content: [
+ {
+ image_url: { url: 'https://cdn.example.com/tool.png' },
+ type: 'image_url',
+ },
+ ],
+ id: 'msg-tool-result',
+ },
+ },
+ ],
+ },
+ {
+ content: [
+ { text: 'done', type: 'text' },
+ {
+ image_url: { url: 'https://cdn.example.com/final.png' },
+ type: 'image_url',
+ },
+ ],
+ id: 'msg-final',
+ },
+ ],
+ content: '',
+ id: 'msg-group',
+ role: 'assistantGroup',
+ },
+ ],
+ metadata: {},
+ };
+
+ const { event } = callBuild(state);
+
+ expect(event.lastAssistantContent).toBe('done');
+ expect(event.attachments).toEqual([
+ expect.objectContaining({ fetchUrl: 'https://cdn.example.com/tool.png', type: 'image' }),
+ expect.objectContaining({ fetchUrl: 'https://cdn.example.com/final.png', type: 'image' }),
+ ]);
+ });
+
+ it('concatenates text parts from a multimodal final assistant turn', () => {
+ const state = {
+ messages: [
+ {
+ content: [
+ { text: 'here is the image: ', type: 'text' },
+ { image_url: { url: 'https://cdn.example.com/a.png' }, type: 'image_url' },
+ { text: '\n\nhope it helps', type: 'text' },
+ ],
+ role: 'assistant',
+ },
+ ],
+ metadata: {},
+ };
+
+ const { event } = callBuild(state);
+
+ expect(event.lastAssistantContent).toBe('here is the image: \n\nhope it helps');
+ expect(event.attachments).toEqual([
+ expect.objectContaining({ fetchUrl: 'https://cdn.example.com/a.png', type: 'image' }),
+ ]);
+ });
+
+ it('returns undefined text for image-only final assistant turn (no fallback to earlier text)', () => {
+ // Regression: the previous implementation `.find(m => role === 'assistant' && hasText)`
+ // would skip the image-only final turn and walk back to the earlier text
+ // turn, shipping stale prose alongside the current image. The fix matches
+ // on role only β€” text must be undefined when the final turn has no text.
+ const state = {
+ messages: [
+ { content: 'stale prior text', role: 'assistant' },
+ { content: 'follow-up prompt', role: 'user' },
+ {
+ content: [{ image_url: { url: 'https://cdn.example.com/new.png' }, type: 'image_url' }],
+ role: 'assistant',
+ },
+ ],
+ metadata: {},
+ };
+
+ const { event } = callBuild(state);
+
+ expect(event.lastAssistantContent).toBeUndefined();
+ expect(event.attachments).toEqual([
+ expect.objectContaining({ fetchUrl: 'https://cdn.example.com/new.png', type: 'image' }),
+ ]);
+ });
+
+ it('returns undefined text when there are no assistant messages', () => {
+ const state = {
+ messages: [{ content: 'just a user prompt', role: 'user' }],
+ metadata: {},
+ };
+
+ const { event } = callBuild(state);
+
+ expect(event.lastAssistantContent).toBeUndefined();
+ expect(event.attachments).toBeUndefined();
+ });
+
+ it('returns undefined text when content is an empty string', () => {
+ // `extractTextFromMessageContent` returns undefined for empty strings, so
+ // an empty-string final assistant turn must not pretend it has text.
+ const state = {
+ messages: [{ content: '', role: 'assistant' }],
+ metadata: {},
+ };
+
+ const { event } = callBuild(state);
+
+ expect(event.lastAssistantContent).toBeUndefined();
+ });
+
+ it('handles missing messages array gracefully', () => {
+ const { event } = callBuild({ origin: { agentId: 'a' } });
+
+ expect(event.lastAssistantContent).toBeUndefined();
+ expect(event.attachments).toBeUndefined();
+ expect(event.agentId).toBe('a');
+ });
+
+ it('preserves safe external-agent context on completion hooks', () => {
+ const { event } = callBuild(
+ {
+ error: {
+ type: 'AgentRuntimeError',
+ body: {
+ agentType: 'claude-code',
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ stderr: 'secret path',
+ rateLimitInfo: { status: 'rejected', rateLimitType: 'seven_day', resetsAt: 1789826400 },
+ },
+ },
+ origin: { agentId: 'agent-1', userId: 'user-1' },
+ },
+ 'error',
+ );
+ expect(event.errorAttribution).toBe('user');
+ expect(event.errorHeterogeneous).toEqual({
+ agentType: 'claude-code',
+ kind: 'usage_limit',
+ rateLimitType: 'seven_day',
+ resetsAt: 1789826400,
+ });
+ });
+
+ it('populates errorType + attribution from the normalized error on the error path', () => {
+ // Regression: the event previously carried only errorDetail/errorMessage, so
+ // bot reply renderers never saw the stable code/attribution and always fell
+ // back to the opaque Operation ID. buildLifecycleEvent must normalize the
+ // runtime error via formatErrorForState and surface these taxonomy fields.
+ const state = {
+ error: { error: { message: 'fetch failed' }, errorType: 'ProviderNetworkError' },
+ origin: { agentId: 'agent-1', userId: 'user-1' },
+ };
+
+ const { event } = callBuild(state, 'error');
+
+ expect(event.errorType).toBe('ProviderNetworkError');
+ expect(event.errorAttribution).toBe('system');
+ expect(event.errorMessage).toBe('fetch failed');
+ });
+
+ it('carries the budget context of an exhausted allowance onto the event', () => {
+ // Without this the bot reply can only say "not enough credits": which
+ // allowance ran out, and by how much, lived in the error body and stopped
+ // at the lifecycle boundary.
+ const state = {
+ error: {
+ budget: {
+ availableCredits: 7_242_747,
+ budgetTypeAtError: 'workspace_member',
+ requiredCredits: 197_391,
+ shortfallCredits: 0,
+ },
+ error: { message: 'Workspace budget exceeded' },
+ errorType: 'InsufficientBudgetForModel',
+ },
+ origin: { agentId: 'agent-1', userId: 'user-1' },
+ };
+
+ const { event } = callBuild(state, 'error');
+
+ expect(event.errorBudget).toEqual({
+ availableCredits: 7_242_747,
+ budgetTypeAtError: 'workspace_member',
+ requiredCredits: 197_391,
+ shortfallCredits: 0,
+ });
+ });
+
+ it('leaves errorType + attribution undefined when there is no error', () => {
+ const { event } = callBuild({ messages: [], metadata: {} }, 'done');
+
+ expect(event.errorType).toBeUndefined();
+ expect(event.errorAttribution).toBeUndefined();
+ });
+
+ it('resolves assistantMessageId from the final assistant message row when metadata omits it', () => {
+ // Regression: a server execAgent turn carries operation-level metadata
+ // ({} in DB) with no assistantMessageId, so the completion event previously
+ // shipped assistantMessageId=undefined and the deferred skill-synthesis
+ // handler no-oped. The id must fall back to the persisted id on the final
+ // assistant message row in state (deferred skill synthesis needs the
+ // anchor to seed the skill under the assistant group, not under the user
+ // message).
+ const state = {
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ { content: 'tool result', id: 'msg-tool', role: 'tool' },
+ { content: 'final answer', id: 'msg-assistant', role: 'assistant' },
+ { content: 'trailing tool result', id: 'msg-tool-2', role: 'tool' },
+ ],
+ origin: { agentId: 'agent-1', userId: 'user-1' },
+ };
+
+ const { assistantMessageId } = callBuild(state, 'done');
+
+ expect(assistantMessageId).toBe('msg-assistant');
+ });
+
+ it('prefers metadata.assistantMessageId over the state row (client runtime path)', () => {
+ // The client runtime path supplies assistantMessageId on operation metadata;
+ // it must win over the state-row fallback so the anchor stays the id the
+ // client already persisted the parked candidate against.
+ const state = {
+ messages: [{ content: 'final answer', id: 'msg-from-state', role: 'assistant' }],
+ metadata: { assistantMessageId: 'msg-from-metadata' },
+ origin: { agentId: 'agent-1' },
+ };
+
+ const { assistantMessageId } = callBuild(state, 'done');
+
+ expect(assistantMessageId).toBe('msg-from-metadata');
+ });
+
+ it('leaves assistantMessageId undefined when neither metadata nor a state row carries it', () => {
+ const { assistantMessageId } = callBuild(
+ { messages: [{ content: 'just a user prompt', role: 'user' }], metadata: {} },
+ 'done',
+ );
+
+ expect(assistantMessageId).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
new file mode 100644
index 00000000000..b197cfa06a2
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
@@ -0,0 +1,580 @@
+import debug from 'debug';
+
+import {
+ AgentOperationModel,
+ type RecordOperationStartParams,
+} from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type { LobeChatDatabase } from '@/database/type';
+import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
+import {
+ instantiateVerifyPlanOnStart,
+ runVerifyOnCompletion,
+ settleFailedRepair,
+} from '@/server/services/verify';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';
+import { recoverLastAssistantContent, resolveErrorMessageId } from './assistantMessage';
+import { registerFileWorks } from './fileWorks';
+import {
+ CriticalAgentInterventionPersistenceError,
+ notifyPendingAgentIntervention,
+} from './intervention';
+import { buildLifecycleEvent, extractErrorMessage } from './lifecycleEvent';
+import { extractOutboundAttachments, extractTextFromMessageContent } from './messageContent';
+import { persistCompletion } from './persistence';
+import { recallUserOnCompletion } from './recall';
+import { emitSignalEvents, isAgentShareRun } from './signals';
+import type {
+ CompleteOperationOptions,
+ CompletionLifecycleDeps,
+ OperationCompletionInput,
+ SignalEvent,
+} from './types';
+
+export { CriticalAgentInterventionPersistenceError } from './intervention';
+export {
+ extractTextFromMessage,
+ extractTextFromMessageContent,
+ findLastAssistantMessage,
+ normalizeCompletionMessages,
+} from './messageContent';
+export { isAgentShareRun } from './signals';
+export type { CompleteOperationOptions, OperationCompletionInput } from './types';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+/**
+ * Terminal reasons this lifecycle treats as a successful completion: the run
+ * produced a deliverable, even when it was stopped by a step/cost cap rather
+ * than finishing naturally. `persistCompletion` stores all three with
+ * status='done', and success-side effects (assistant-content recovery,
+ * file-Work registration) must cover the capped reasons too β€” gating them on
+ * `reason === 'done'` alone silently drops capped runs' artifacts.
+ */
+export const isSuccessLikeCompletionReason = (reason: string): boolean =>
+ reason === 'done' ||
+ reason === 'max_steps' ||
+ reason === 'cost_limit' ||
+ reason === 'tool_call_repeat_limit';
+
+/**
+ * Owns everything that happens once an operation reaches a terminal state:
+ * building the lifecycle event payload, emitting completion AgentSignal source
+ * events, dispatching `onComplete`/`onError` hooks, and writing the final
+ * error back onto the assistant message row.
+ *
+ * Ordinary side-effect errors are logged and remain non-fatal. Critical
+ * no-fallback webhook failures are rethrown after terminal persistence so a
+ * queue execution can retry the control-flow handoff.
+ */
+export class CompletionLifecycle {
+ private readonly messageModel: MessageModel;
+ private readonly agentOperationModel: AgentOperationModel;
+ private readonly workspaceId?: string;
+ /**
+ * In-flight verify-plan instantiations started in {@link recordStart}, keyed by
+ * operationId. `dispatchHooks` awaits the matching one before running the
+ * completion gate so a very short / no-op task run can't race past its own plan
+ * (instantiation is fire-and-forget at start and may not have settled yet).
+ */
+ private readonly verifyPlanInstantiations = new Map<string, Promise<void>>();
+
+ constructor(
+ private readonly serverDB: LobeChatDatabase,
+ private readonly userId: string,
+ workspaceId?: string,
+ options?: {
+ /**
+ * Opt IN to agent-share visitor rows on this service's `messageModel`.
+ * Reserved for share-runtime callers driving a visitor turn under the
+ * creator's identity.
+ */
+ includeShareVisitor?: boolean;
+ },
+ ) {
+ this.workspaceId = workspaceId;
+ this.includeShareVisitor = options?.includeShareVisitor ?? false;
+ this.messageModel = new MessageModel(serverDB, userId, workspaceId, undefined, {
+ includeShareVisitor: this.includeShareVisitor,
+ });
+ this.agentOperationModel = new AgentOperationModel(serverDB, userId, workspaceId);
+ }
+
+ private readonly includeShareVisitor: boolean;
+
+ /**
+ * The instance state the extracted completion steps read. Built per call so
+ * the steps always see the current models.
+ */
+ private deps(): CompletionLifecycleDeps {
+ return {
+ agentOperationModel: this.agentOperationModel,
+ includeShareVisitor: this.includeShareVisitor,
+ messageModel: this.messageModel,
+ serverDB: this.serverDB,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+ }
+
+ /**
+ * Persist the initial `agent_operations` row when an operation is created.
+ * Returns whether the row write succeeded so security-sensitive callers can
+ * require durable state before dispatch. Other runtime paths may preserve
+ * the historical non-blocking behavior by ignoring the result.
+ */
+ async recordStart(params: RecordOperationStartParams): Promise<boolean> {
+ let persisted = true;
+ try {
+ await this.agentOperationModel.recordStart(params);
+ } catch (error) {
+ persisted = false;
+ // Hook configuration may contain inline authorization headers. Never log
+ // a database error that could repeat its bound metadata parameters.
+ const hooks = params.metadata?._hooks;
+ if (hooks && (!Array.isArray(hooks) || hooks.length > 0))
+ log('[%s] Failed to record operation start (non-fatal)', params.operationId);
+ else log('[%s] Failed to record operation start (non-fatal): %O', params.operationId, error);
+ }
+
+ // Auto-instantiate the task's verify plan at run start so the completion gate
+ // fires. Only for a top-level task operation β€” repair / verifier sub-agents
+ // (which carry a parentOperationId) get their plan from the repair path, not
+ // here. Fire-and-forget; never blocks startup. We keep the promise (instead of
+ // void-ing it) so `dispatchHooks` can await it before the completion gate runs
+ // β€” a fast run can otherwise complete first and the gate would no-op on a plan
+ // that lands moments later. (instantiateVerifyPlanOnStart never rejects.)
+ if (params.taskId && !params.parentOperationId) {
+ this.verifyPlanInstantiations.set(
+ params.operationId,
+ instantiateVerifyPlanOnStart(
+ this.serverDB,
+ this.userId,
+ { operationId: params.operationId, taskId: params.taskId },
+ this.workspaceId,
+ ),
+ );
+ }
+
+ return persisted;
+ }
+
+ /**
+ * Persist terminal state to `agent_operations`. Fire-and-forget: a DB
+ * outage must never block hook dispatch or the executor's terminal
+ * cleanup path.
+ */
+ private async persistCompletion(
+ operationId: string,
+ state: any,
+ reason: string,
+ settledAsAbandoned?: boolean,
+ ): Promise<boolean> {
+ return persistCompletion(this.deps(), operationId, state, reason, settledAsAbandoned);
+ }
+
+ /**
+ * Extract a human-readable error message from the agent state error object.
+ * Handles both raw `ChatCompletionErrorPayload` (from runtime.step catch) and
+ * formatted `ChatMessageError` (from executeStep catch).
+ *
+ * Public so callers can use the same formatting when surfacing errors
+ * outside the hook dispatch path (e.g. trace snapshot finalize).
+ */
+ extractErrorMessage(error: any): string | undefined {
+ return extractErrorMessage(error);
+ }
+
+ /**
+ * Emit completion AgentSignal source events and return compact snapshot
+ * events for attachment to the trace step. Fire-and-forget.
+ */
+ async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {
+ return emitSignalEvents(this.deps(), operationId, state, reason);
+ }
+
+ /**
+ * Insert a `role='verify'` message that renders the Agent Run delivery-checker
+ * card (plan + results, read off `metadata.verifyOperationId`). Only created
+ * when the run actually has a verify plan. Self-guarded β€” failures never affect
+ * the run; the card is purely additive UI.
+ */
+ private async createVerifyMessage(
+ operationId: string,
+ assistantMessageId: string | undefined,
+ userId: string,
+ ): Promise<void> {
+ try {
+ const run = await new VerifyRunModel(this.serverDB, userId).findByOperation(operationId);
+ if (!run?.plan?.length) return;
+
+ const op = await new AgentOperationModel(this.serverDB, userId).findById(operationId);
+ if (!op?.topicId) return;
+
+ const messageModel = new MessageModel(this.serverDB, userId, undefined, undefined, {
+ includeShareVisitor: this.includeShareVisitor,
+ });
+ await messageModel.create({
+ agentId: op.agentId ?? undefined,
+ content: '',
+ groupId: op.chatGroupId ?? undefined,
+ metadata: { verifyOperationId: operationId },
+ parentId: assistantMessageId,
+ role: 'verify',
+ threadId: op.threadId ?? undefined,
+ topicId: op.topicId,
+ });
+ } catch (error) {
+ log('createVerifyMessage failed for op %s (non-fatal): %O', operationId, error);
+ }
+ }
+
+ /**
+ * Expand a normalized {@link OperationCompletionInput} into the runtime `state`
+ * shape `dispatchHooks` consumes. The SINGLE place that mirrors the runtime
+ * state for non-in-process paths β€” goal/deliverable become the user/assistant
+ * turns the gate reads, model/provider backfill the op row, hooks ride on
+ * `host.hooks`. Replaces the per-caller hand-rolled synthetic state that
+ * previously drifted (e.g. a verify field added here was missed by heteroFinish).
+ */
+ private buildStateFromInput(input: OperationCompletionInput) {
+ return {
+ cost: input.cost ?? { total: null },
+ createdAt: input.startedAt,
+ error: input.error ?? undefined,
+ messages: [
+ { content: input.goal ?? '', role: 'user' },
+ { content: input.deliverable ?? '', role: 'assistant' },
+ ],
+ host: { hooks: input.serializedHooks },
+ metadata: { assistantMessageId: input.assistantMessageId },
+ origin: {
+ agentId: input.agentId,
+ lineage: { orchestrationRole: input.orchestrationRole },
+ topicId: input.topicId,
+ userId: input.userId ?? this.userId,
+ },
+ model: input.model ?? undefined,
+ provider: input.provider ?? undefined,
+ stepCount: input.stepCount ?? null,
+ usage: input.usage ?? undefined,
+ };
+ }
+
+ /**
+ * Register the operation's Works (edited entity files plus github issue/PR
+ * Works). Idempotent per state object; see `registerFileWorks` in
+ * `./fileWorks` for the marker and retry contract.
+ */
+ async registerFileWorks(operationId: string, state: any): Promise<void> {
+ return registerFileWorks(this.deps(), operationId, state);
+ }
+
+ /**
+ * The single terminal-completion entry for every path that does NOT have the
+ * in-process runtime's rich `state` in hand: heterogeneous CLI exit
+ * (`heteroFinish`), remote-agent done signal (`agentNotify`), and synchronous
+ * dispatch failure (`finalizeHeteroDispatchError`). Builds the synthetic state
+ * once and runs the SAME pipeline the in-process runtime uses β€” persist the
+ * terminal op row, fire onComplete/onError hooks, and (on `done`) run the
+ * delivery-checker verify gate. This is what makes those paths true lifecycle
+ * peers instead of firing a stripped-down hooks-only funnel.
+ */
+ async completeOperation(
+ input: OperationCompletionInput,
+ reason: 'done' | 'error' | 'interrupted',
+ options?: CompleteOperationOptions,
+ ): Promise<void> {
+ await this.dispatchHooks(input.operationId, this.buildStateFromInput(input), reason, options);
+ }
+
+ /**
+ * Dispatch `onComplete` (and `onError` for `reason='error'`) hooks via
+ * the global `hookDispatcher`. On the error path, also writes the error
+ * back onto the assistant message row so the frontend can render it.
+ * Fire-and-forget; unregisters the operation after a settled lifecycle while
+ * preserving registrations across retryable critical delivery failures.
+ */
+ async dispatchHooks(
+ operationId: string,
+ state: any,
+ reason: string,
+ options?: CompleteOperationOptions,
+ ): Promise<void> {
+ // `waiting_for_async_tool` parks the SAME operation: it persists the parked
+ // status (the async-tool resume CAS reads it) but must NOT fire `onComplete`
+ // or unregister hooks β€” the op resumes under this same id and reaches its
+ // real terminal state later, which is when consumers should be notified.
+ // `waiting_for_human` is different: the parked segment fires `onComplete`
+ // so hook consumers can surface the approval request. A winning decision
+ // schedules a fresh continuation operation and then retires this parked
+ // segment; the continuation receives the serialized hooks through
+ // `host.hooks`.
+ // `waiting_for_client` (no client to run the next LLM call) parks the same
+ // operation the same way: it resumes under this id or expires to `error`.
+ const isAsyncToolPark = reason === 'waiting_for_async_tool' || reason === 'waiting_for_client';
+ let shouldRetainHooksForRetry = false;
+
+ try {
+ const {
+ assistantMessageId,
+ event,
+ metadata,
+ origin: runOrigin,
+ } = this.buildLifecycleEvent(operationId, state, reason);
+
+ // 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,
+ options?.settledAsAbandoned,
+ );
+ if (completionAccepted === false) {
+ log('[%s] Skipping hooks for an operation with a conflicting terminal owner', operationId);
+ return;
+ }
+
+ // At this point the parked operation state has been durably projected to
+ // agent_operations. Verify the tool rows independently before creating a
+ // durable Review so a partial batch can never reach notification UI.
+ if (reason === 'waiting_for_human') {
+ await this.notifyPendingAgentIntervention(operationId, state);
+ }
+
+ if (isAsyncToolPark) return;
+
+ // `lastAssistantContent` comes off the Redis-backed `state.messages`,
+ // while the assistant message row is persisted through a separate
+ // `messageModel.update` path. When the two diverge (state entry empty
+ // but the DB row holds the full reply β€” Discord bot completions
+ // arrived with no content while the app showed the reply), consumers
+ // like the IM bot callback silently drop the reply. Recover from the DB
+ // row β€” the same source of truth the app UI renders β€” before dispatch.
+ if (
+ isSuccessLikeCompletionReason(reason) &&
+ !event.lastAssistantContent?.trim() &&
+ !event.attachments?.length
+ ) {
+ const recovered = await this.recoverLastAssistantContent(
+ operationId,
+ assistantMessageId,
+ runOrigin.userId || this.userId,
+ typeof runOrigin.topicId === 'string' ? runOrigin.topicId : undefined,
+ );
+ if (recovered) {
+ event.lastAssistantContent = recovered;
+ const attachments = extractOutboundAttachments([
+ { content: recovered, role: 'assistant' },
+ ]);
+ event.attachments = attachments.length > 0 ? attachments : undefined;
+ }
+ }
+
+ await hookDispatcher.dispatch(operationId, 'onComplete', event, state?.host?.hooks);
+
+ // Recall the user when a run finishes with a deliverable while they may be
+ // away (push / inbox). Fires on every success-like terminal β€” `done` plus
+ // the step/cost caps, which still produce a reply worth recalling β€” to
+ // match the desktop completion notification, which notifies on any clean
+ // (non-abort, non-error) terminal. Fire-and-forget through the
+ // `@/business` slot; the default implementation is a no-op. Sub-agent /
+ // group-member completions are internal steps of a parent run, never a
+ // user-facing recall β€” in-group members carry `orchestrationRole: 'member'`
+ // WITHOUT `isSubAgent` (see execAgentMember), so guard both. The
+ // remaining condition β€” only interactive chat runs recall the user β€”
+ // lives in recallUserOnCompletion.
+ //
+ // Agent Share visitor runs execute AS the creator, so this `userId`-scoped
+ // recall would otherwise reach the creator's push/inbox for every turn an
+ // arbitrary link visitor completes β€” a visitor could spam the owner by
+ // repeatedly running the shared agent, and the notification would deep-link
+ // into a visitor topic (`topics.senderId`) that is deliberately excluded
+ // from creator-facing surfaces.
+ if (
+ isSuccessLikeCompletionReason(reason) &&
+ runOrigin.lineage?.isSubAgent !== true &&
+ runOrigin.lineage?.orchestrationRole !== 'member' &&
+ !isAgentShareRun(state)
+ ) {
+ void this.recallUserOnCompletion(operationId, event, runOrigin).catch((error) =>
+ log('[%s] Completion notification failed (non-fatal): %O', operationId, error),
+ );
+ }
+
+ // Delivery checker: on a successful completion, run the confirmed verify
+ // plan against the deliverable. Fire-and-forget and self-guarded β€” a run
+ // without an opted-in plan is a no-op, and failures never affect the run.
+ if (reason === 'done') {
+ // The task's verify plan is instantiated fire-and-forget at run start; a
+ // fast or no-op run can reach completion before it settles. Await the
+ // in-flight instantiation (if any) so the gate sees the confirmed plan
+ // instead of racing past it and leaving a planned run with no results/card.
+ await this.verifyPlanInstantiations.get(operationId);
+
+ const messages: any[] = Array.isArray(state?.messages) ? state.messages : [];
+ const firstUserMessage = messages.find((m) => m?.role === 'user');
+ const goal = firstUserMessage
+ ? (extractTextFromMessageContent(firstUserMessage.content) ?? '')
+ : '';
+ // Surface the delivery-checker card first (a role='verify' message that
+ // renders the run's plan + results). Awaited before verification so
+ // auto-repair can persist its failure feedback onto this card (the
+ // VerifyMessageProcessor then surfaces it into the repair run's context).
+ // Self-guarded β€” failures never affect the run.
+ await this.createVerifyMessage(
+ operationId,
+ metadata?.assistantMessageId,
+ runOrigin.userId || this.userId,
+ );
+ // `after`, not a bare `void`: judging is minutes of LLM calls and the
+ // step handler must not wait for it, but a detached promise has nobody
+ // keeping it scheduled β€” on the serverless path the instance is free to
+ // stop running it the moment this response returns. That is not merely a
+ // lost verification: entering `verifying` is a durable write, so a run
+ // cut off mid-judge stays `verifying` forever. `after` hands the work to
+ // the host as post-response work instead (no-op fallback off Next).
+ after(() =>
+ runVerifyOnCompletion(
+ this.serverDB,
+ runOrigin.userId || this.userId,
+ {
+ deliverable: event.lastAssistantContent ?? '',
+ goal,
+ operationId,
+ },
+ this.workspaceId,
+ ),
+ );
+ }
+
+ if (reason === 'error' || reason === 'interrupted') {
+ after(async () => {
+ await settleFailedRepair(
+ this.serverDB,
+ runOrigin.userId || this.userId,
+ operationId,
+ this.workspaceId,
+ );
+ });
+ }
+
+ // Register entity files edited this round as `file` Works. On the
+ // gateway/queue path this already ran BEFORE the terminal snapshot (see
+ // `registerFileWorks`) and no-ops via the state marker; here it is the
+ // backstop for every other terminal path (in-process runtime, hetero
+ // completions, already-terminal early exits). Guarded on success-LIKE
+ // reasons, not `done` alone: a run stopped by a step/cost cap still
+ // produced its edits and persists as status='done'.
+ //
+ // `waiting_for_human` deliberately does NOT register: the park is not a
+ // successful deliverable boundary. The fresh approval continuation is
+ // built from the complete authoritative history and performs the real
+ // terminal scan. Registering here would freeze pre-approval file content
+ // as a completed Work before the user decision has run.
+ if (isSuccessLikeCompletionReason(reason)) {
+ await this.registerFileWorks(operationId, state);
+ }
+
+ if (reason === 'error') {
+ await hookDispatcher.dispatch(operationId, 'onError', event, state?.host?.hooks);
+
+ const assistantMessageId =
+ state?.error && !options?.skipErrorMessageWrite
+ ? await this.resolveErrorMessageId(operationId, metadata, runOrigin)
+ : undefined;
+ if (assistantMessageId && state?.error && !options?.skipErrorMessageWrite) {
+ // Preserve the semantic error type written by the runtime. Rebuilding
+ // this as a generic AgentRuntimeError would lose UI routing data such
+ // as quota context and force the client into the fallback card.
+ const messageError = formatErrorForState(state.error);
+ const errorMessage =
+ this.extractErrorMessage(messageError) ||
+ this.extractErrorMessage(state.error) ||
+ String(state.error);
+ try {
+ await this.messageModel.update(assistantMessageId, {
+ error: {
+ ...messageError,
+ body: messageError.body ?? { message: errorMessage },
+ message: errorMessage,
+ },
+ });
+ } catch (updateError) {
+ log(
+ '[%s] Failed to update assistant message with error (non-fatal): %O',
+ operationId,
+ updateError,
+ );
+ }
+ }
+ }
+ } catch (error) {
+ if (
+ error instanceof CriticalHookDeliveryError ||
+ error instanceof CriticalAgentInterventionPersistenceError
+ ) {
+ // A queue retry may run in this same process (local callback / warm
+ // worker). Keep the in-memory registration until that lifecycle really
+ // settles; queue mode can additionally reconstruct from host.hooks.
+ shouldRetainHooksForRetry = true;
+ throw error;
+ }
+ log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);
+ } finally {
+ // Keep hooks registered across an async-tool park so the eventual resume
+ // (same operationId) can still fire onComplete/onError. Critical delivery
+ // failures likewise keep them until the provider redelivery settles.
+ if (!isAsyncToolPark && !shouldRetainHooksForRetry) {
+ hookDispatcher.unregister(operationId);
+ // The instantiation has settled (awaited above) or this op never opted in
+ // β€” drop the entry so the map doesn't grow across the service's lifetime.
+ // Kept across an async-tool park: the op resumes under the same id.
+ this.verifyPlanInstantiations.delete(operationId);
+ }
+ }
+ }
+
+ private async notifyPendingAgentIntervention(operationId: string, state: any): Promise<void> {
+ return notifyPendingAgentIntervention(this.deps(), operationId, state);
+ }
+
+ private async recallUserOnCompletion(
+ operationId: string,
+ event: { agentId?: string; duration?: number; lastAssistantContent?: string; topicId?: string },
+ runOrigin: { trigger?: unknown; userId?: string } | undefined,
+ ): Promise<void> {
+ return recallUserOnCompletion(this.deps(), operationId, event, runOrigin);
+ }
+
+ private async recoverLastAssistantContent(
+ operationId: string,
+ assistantMessageId: string | undefined,
+ userId: string,
+ topicId?: string,
+ ): Promise<string | undefined> {
+ return recoverLastAssistantContent(
+ this.deps(),
+ operationId,
+ assistantMessageId,
+ userId,
+ topicId,
+ );
+ }
+
+ private async resolveErrorMessageId(
+ operationId: string,
+ metadata: { assistantMessageId?: string } | undefined,
+ runOrigin: { topicId?: string; userId?: string },
+ ): Promise<string | undefined> {
+ return resolveErrorMessageId(this.deps(), operationId, metadata, runOrigin);
+ }
+
+ private buildLifecycleEvent(operationId: string, state: any, reason: string) {
+ return buildLifecycleEvent(this.userId, operationId, state, reason);
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/intervention.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/intervention.ts
new file mode 100644
index 00000000000..60531700fcf
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/intervention.ts
@@ -0,0 +1,85 @@
+/**
+ * Durable Review publication for a run parked on human approval.
+ */
+import pMap from 'p-map';
+
+import { notifyAgentInterventionRequired } from '@/business/server/agent-run/agentInterventionReview';
+
+import { buildRuntimeInterventionNotification } from '../agentInterventionNotification';
+import type { CompletionLifecycleDeps } from './types';
+
+/**
+ * A parked human-approval run is not safely published until its generic Review
+ * batch is durable. Unlike ordinary notification fanout, this error must reach
+ * the queue/request boundary so the idempotent lifecycle delivery can retry.
+ */
+export class CriticalAgentInterventionPersistenceError extends Error {
+ constructor(operationId: string, cause: unknown) {
+ super(`Failed to persist intervention Review for parked operation ${operationId}`, { cause });
+ this.name = 'CriticalAgentInterventionPersistenceError';
+ }
+}
+
+/**
+ * Publish a provider-neutral Review snapshot only after every referenced tool
+ * row can be read back as a member of this exact sealed parked batch. The
+ * business slot is idempotent by batch id; repeated lifecycle delivery is
+ * therefore safe, while a partial/mismatched write fails closed.
+ */
+export async function notifyPendingAgentIntervention(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ state: any,
+): Promise<void> {
+ try {
+ const notification = await buildRuntimeInterventionNotification({
+ operationId,
+ state,
+ userId: state?.origin?.userId || deps.userId,
+ workspaceId: deps.workspaceId,
+ });
+ if (!notification) return;
+
+ const persistedRows = await pMap(
+ notification.items,
+ async (item, itemIndex) => {
+ if (item.sourceRef.type !== 'runtime') return;
+ const [message, plugin] = await Promise.all([
+ deps.messageModel.findById(item.sourceRef.toolMessageId),
+ deps.messageModel.findMessagePlugin(item.sourceRef.toolMessageId),
+ ]);
+ if (
+ !message ||
+ message.role !== 'tool' ||
+ message.parentId !== notification.context.assistantMessageId ||
+ message.topicId !== notification.context.topicId ||
+ !plugin ||
+ plugin.toolCallId !== item.sourceRef.toolCallId ||
+ plugin.intervention?.status !== 'pending' ||
+ plugin.intervention.operationId !== operationId ||
+ plugin.intervention.batchId !== notification.batch.id ||
+ plugin.intervention.stepIndex !== notification.batch.stepIndex ||
+ plugin.intervention.itemIndex !== itemIndex
+ ) {
+ return;
+ }
+ return true;
+ },
+ { concurrency: 5 },
+ );
+
+ if (persistedRows.some((persisted) => persisted !== true)) {
+ throw new Error(
+ 'Cannot create intervention Review because the sealed pending batch is not durable',
+ );
+ }
+
+ // Contract boundary: Cloud resolves only after the generic batch is
+ // durable. Push/Live Activity fanout failures are handled inside the
+ // Cloud override and must not reject this call after persistence.
+ await notifyAgentInterventionRequired(notification);
+ } catch (error) {
+ if (error instanceof CriticalAgentInterventionPersistenceError) throw error;
+ throw new CriticalAgentInterventionPersistenceError(operationId, error);
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts
new file mode 100644
index 00000000000..94ea6d83796
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts
@@ -0,0 +1,126 @@
+/**
+ * The lifecycle event payload every completion consumer receives.
+ */
+import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';
+
+import {
+ formatErrorForState,
+ readErrorBudgetContext,
+} from '@/server/modules/AgentRuntime/formatErrorForState';
+
+import {
+ extractOutboundAttachments,
+ extractTextFromMessageContent,
+ findLastAssistantMessage,
+ normalizeCompletionMessages,
+} from './messageContent';
+
+/**
+ * Extract a human-readable error message from the agent state error object.
+ * Handles both raw `ChatCompletionErrorPayload` (from runtime.step catch) and
+ * formatted `ChatMessageError` (from executeStep catch).
+ *
+ * Public so callers can use the same formatting when surfacing errors
+ * outside the hook dispatch path (e.g. trace snapshot finalize).
+ */
+export function extractErrorMessage(error: any): string | undefined {
+ if (!error) return undefined;
+
+ // Path B: formatted ChatMessageError β€” { body, message, type }
+ if (error.body) {
+ const body = error.body;
+ // OpenAI-style: body.error.message
+ if (body.error?.message) return body.error.message;
+ if (body.message) return body.message;
+ }
+
+ // Path A: raw ChatCompletionErrorPayload β€” { errorType, error: {...}, provider }
+ if (error.error) {
+ const inner = error.error;
+ if (inner.error?.message) return inner.error.message;
+ if (inner.message) return inner.message;
+ }
+
+ if (error.message && error.message !== 'error') return error.message;
+ if (error.type || error.errorType) return String(error.type || error.errorType);
+
+ return undefined;
+}
+
+export function buildLifecycleEvent(
+ userId: string,
+ operationId: string,
+ state: any,
+ reason: string,
+) {
+ const metadata = state?.metadata || {};
+ const runOrigin = state?.origin ?? {};
+ const messages = normalizeCompletionMessages(
+ Array.isArray(state?.messages) ? state.messages : [],
+ );
+
+ // Pull text content off the **final** assistant turn. Content may be a
+ // plain string or an OpenAI-style multimodal part array; for the array
+ // case we concatenate the text parts so the reply body is preserved.
+ //
+ // We deliberately match on `role === 'assistant'` only β€” not on whether
+ // the turn has any text β€” so an image-only or tool-output final turn
+ // doesn't fall through to an earlier assistant message and ship stale
+ // text alongside the current attachments.
+ const lastAssistantMessage = findLastAssistantMessage(messages);
+ const lastAssistantContent = lastAssistantMessage
+ ? extractTextFromMessageContent(lastAssistantMessage.content)
+ : undefined;
+
+ // Operation-level metadata only carries `assistantMessageId` on the client
+ // runtime path; a server `execAgent` turn leaves it unset (`{}` in DB). Fall
+ // back to the persisted id on the final assistant message row in state so the
+ // completion event can anchor deferred skill synthesis to this turn (skill
+ // synthesis deferred from inbound to turn completion so it uses the full
+ // trajectory β€” tool sequence + final product β€” not just the user prompt).
+ // A metadata value, when present, still wins.
+ const assistantMessageId =
+ metadata?.assistantMessageId ?? (lastAssistantMessage as { id?: string } | undefined)?.id;
+
+ const attachments = extractOutboundAttachments(messages);
+
+ const duration = state?.createdAt ? Date.now() - new Date(state.createdAt).getTime() : undefined;
+
+ // On the error path, normalize the runtime error once so the lifecycle
+ // event carries the stable taxonomy fields (errorType + attribution + the
+ // budget context an admission gate attached). Bot reply renderers switch on
+ // these to surface a perceivable cause (network / quota / provider outage /
+ // which allowance ran out) instead of an opaque Operation ID. Mirrors the
+ // same normalization dispatchHooks runs before writing the error onto the
+ // assistant message row.
+ const formattedError = state?.error ? formatErrorForState(state.error) : undefined;
+
+ return {
+ assistantMessageId,
+ event: {
+ agentId: runOrigin.agentId || '',
+ attachments: attachments.length > 0 ? attachments : undefined,
+ cost: state?.cost?.total,
+ duration,
+ errorAttribution: formattedError?.attribution,
+ errorBudget: readErrorBudgetContext(formattedError),
+ errorHeterogeneous: readHeterogeneousErrorContext(formattedError),
+ errorDetail: state?.error,
+ errorMessage: extractErrorMessage(state?.error) || String(state?.error || ''),
+ errorType: formattedError?.type === undefined ? undefined : String(formattedError.type),
+ finalState: state,
+ lastAssistantContent,
+ llmCalls: state?.usage?.llm?.apiCalls,
+ operationId,
+ reason,
+ status: state?.status || reason,
+ steps: state?.stepCount || 0,
+ toolCalls: state?.usage?.tools?.totalCalls,
+ topicId: runOrigin.topicId,
+ totalTokens: state?.usage?.llm?.tokens?.total,
+ userId: runOrigin.userId || userId,
+ },
+ metadata,
+ origin: runOrigin,
+ };
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/messageContent.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/messageContent.ts
new file mode 100644
index 00000000000..cbf197ddde0
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/messageContent.ts
@@ -0,0 +1,271 @@
+/**
+ * Text and outbound-attachment extraction from completion messages.
+ */
+import { deserializeParts } from '@lobechat/utils';
+import { isRecord } from '@lobechat/utils/object';
+
+import { extractFinalReplyImageUrls } from '../finalReplyImages';
+
+// --------------------------------------------------------------------------
+// Outbound attachment extraction
+// --------------------------------------------------------------------------
+
+type OutboundAttachment = {
+ data?: string;
+ fetchUrl?: string;
+ mimeType?: string;
+ name?: string;
+ type: 'image' | 'file' | 'video' | 'audio';
+};
+
+const DATA_URL_RE = /^data:([^;]+);base64,(.+)$/;
+
+const inferAttachmentTypeFromMime = (mimeType: string | undefined): OutboundAttachment['type'] => {
+ if (!mimeType) return 'file';
+ if (mimeType.startsWith('image/')) return 'image';
+ if (mimeType.startsWith('video/')) return 'video';
+ if (mimeType.startsWith('audio/')) return 'audio';
+ return 'file';
+};
+
+/**
+ * Materialize a `url` field β€” either a `data:` URL (extract base64 inline) or
+ * a remote URL (record fetchUrl). Returns undefined for unsupported shapes.
+ */
+const buildAttachmentFromUrl = (
+ url: string | undefined,
+ fallbackType: OutboundAttachment['type'] = 'image',
+): OutboundAttachment | undefined => {
+ if (!url || typeof url !== 'string') return undefined;
+ const dataMatch = url.match(DATA_URL_RE);
+ if (dataMatch) {
+ const mimeType = dataMatch[1];
+ return {
+ data: dataMatch[2],
+ mimeType,
+ type: inferAttachmentTypeFromMime(mimeType),
+ };
+ }
+ // Bare http(s) URL β€” let the downstream messenger fetch it lazily.
+ if (/^https?:\/\//.test(url)) {
+ return { fetchUrl: url, type: fallbackType };
+ }
+ return undefined;
+};
+
+/**
+ * Pull text out of a message's `content` field. Accepts both string and
+ * OpenAI-style multimodal arrays `[{ type: 'text', text }, { type: 'image_url', image_url: { url } }]`.
+ */
+export const extractTextFromMessageContent = (content: unknown): string | undefined => {
+ if (typeof content === 'string') return content || undefined;
+ if (!Array.isArray(content)) return undefined;
+ const parts: string[] = [];
+ for (const part of content) {
+ if (typeof part === 'string') {
+ parts.push(part);
+ } else if (part && typeof part === 'object' && (part as any).type === 'text') {
+ const text = (part as { text?: unknown }).text;
+ if (typeof text === 'string') parts.push(text);
+ }
+ }
+ const joined = parts.join('');
+ return joined || undefined;
+};
+
+/**
+ * Extract text from either an in-memory message or a DB-rehydrated row.
+ * Persisted multimodal content is serialized, so only deserialize when the
+ * row's explicit metadata flag identifies that storage representation.
+ */
+export const extractTextFromMessage = (message: unknown): string | undefined => {
+ if (!isRecord(message)) return undefined;
+
+ const metadata = isRecord(message.metadata) ? message.metadata : undefined;
+ const content =
+ typeof message.content === 'string' && metadata?.isMultimodal === true
+ ? (deserializeParts(message.content) ?? message.content)
+ : message.content;
+
+ return extractTextFromMessageContent(content);
+};
+
+/**
+ * Expand display-only assistant groups back into the assistant/tool sequence
+ * expected by terminal lifecycle consumers.
+ *
+ * DB rehydration runs conversation-flow parsing, which folds an entire tool
+ * chain β€” including its final toolless assistant turn β€” into one
+ * `assistantGroup` whose own content is empty. Completion hooks must inspect
+ * the persisted leaf turns rather than that virtual wrapper, otherwise they
+ * lose both the final text and the message id used by DB recovery.
+ */
+export const normalizeCompletionMessages = (
+ messages: unknown[],
+): Record<PropertyKey, unknown>[] => {
+ const normalized: Record<PropertyKey, unknown>[] = [];
+
+ for (const message of messages) {
+ if (!isRecord(message)) continue;
+
+ const isAssistantGroup = message.role === 'assistantGroup' || message.role === 'supervisor';
+ if (!isAssistantGroup) {
+ normalized.push(message);
+ continue;
+ }
+
+ if (!Array.isArray(message.children) || message.children.length === 0) {
+ normalized.push({ ...message, role: 'assistant' });
+ continue;
+ }
+
+ const groupStartIndex = normalized.length;
+ for (const child of message.children) {
+ if (!isRecord(child) || child.council) continue;
+
+ normalized.push({ ...child, role: 'assistant' });
+
+ if (!Array.isArray(child.tools)) continue;
+ for (const tool of child.tools) {
+ if (!isRecord(tool) || !isRecord(tool.result)) continue;
+
+ normalized.push({
+ content: tool.result.content,
+ id: tool.result.id,
+ role: 'tool',
+ tool_call_id: tool.id,
+ });
+ }
+ }
+
+ // A virtual group containing only non-message blocks (for example a
+ // council block) still marks the latest assistant boundary. Preserve an
+ // empty leaf so completion never falls back to stale text from an older
+ // turn.
+ if (normalized.length === groupStartIndex) {
+ normalized.push({ ...message, role: 'assistant' });
+ }
+ }
+
+ return normalized;
+};
+
+/**
+ * Find the final assistant boundary after display-only groups have been
+ * normalized. Match by role rather than content so an empty/image-only final
+ * turn never falls through to stale text from an earlier assistant message.
+ */
+export const findLastAssistantMessage = (
+ messages: Record<PropertyKey, unknown>[],
+): Record<PropertyKey, unknown> | undefined =>
+ messages
+ .slice()
+ .reverse()
+ .find((message) => message.role === 'assistant');
+
+/**
+ * Extract image/file parts from a message's `content` array. Each entry is
+ * mapped to the JSON-safe outbound attachment shape (data or fetchUrl).
+ */
+const extractAttachmentsFromContent = (content: unknown): OutboundAttachment[] => {
+ if (!Array.isArray(content)) return [];
+ const out: OutboundAttachment[] = [];
+ for (const part of content) {
+ if (!part || typeof part !== 'object') continue;
+ const type = (part as { type?: unknown }).type;
+ if (type === 'image_url') {
+ const url = (part as { image_url?: { url?: string } }).image_url?.url;
+ const att = buildAttachmentFromUrl(url, 'image');
+ if (att) out.push(att);
+ } else if (type === 'image') {
+ // Anthropic-style: { type: 'image', source: { type: 'base64', media_type, data } }
+ const source = (part as { source?: { data?: string; media_type?: string; type?: string } })
+ .source;
+ if (source?.type === 'base64' && source.data) {
+ const mimeType = source.media_type;
+ out.push({
+ data: source.data,
+ mimeType,
+ type: inferAttachmentTypeFromMime(mimeType),
+ });
+ } else if (source?.type === 'url') {
+ const url = (source as { url?: string }).url;
+ const att = buildAttachmentFromUrl(url, 'image');
+ if (att) out.push(att);
+ }
+ } else if (type === 'file' || type === 'file_url') {
+ const file = (part as { file?: { url?: string; name?: string; mime_type?: string } }).file;
+ const att = buildAttachmentFromUrl(file?.url, 'file');
+ if (att) {
+ att.name = file?.name ?? att.name;
+ att.mimeType = file?.mime_type ?? att.mimeType;
+ out.push(att);
+ }
+ }
+ }
+ return out;
+};
+
+/**
+ * Walk recent messages and collect outbound image/file attachments to send
+ * alongside the reply. Scans the last assistant message *and* any tool
+ * messages that came after the previous assistant turn β€” tool-generated
+ * images (e.g. a drawing tool that returns an image_url result) need to be
+ * delivered with the next reply.
+ *
+ * Deduplicates by data/fetchUrl identity.
+ */
+export const extractOutboundAttachments = (messages: any[]): OutboundAttachment[] => {
+ if (!Array.isArray(messages) || messages.length === 0) return [];
+
+ // Walk from the end backwards: collect attachments until we hit the
+ // previous assistant turn that already has text β€” that boundary marks
+ // "the current reply window".
+ const collected: OutboundAttachment[] = [];
+ let crossedFinalAssistant = false;
+
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (!msg || typeof msg !== 'object') continue;
+ const role = (msg as { role?: string }).role;
+ const content = (msg as { content?: unknown }).content;
+
+ if (role === 'assistant') {
+ if (!crossedFinalAssistant) {
+ // Only the final reply's Markdown expresses an intent to send images.
+ // Do not promote generation state or intermediate tool Markdown.
+ const attachments: OutboundAttachment[] = [];
+ const text = extractTextFromMessageContent(content);
+ if (text) {
+ for (const url of extractFinalReplyImageUrls(text)) {
+ const attachment = buildAttachmentFromUrl(url, 'image');
+ if (attachment) attachments.push(attachment);
+ }
+ }
+ attachments.push(...extractAttachmentsFromContent(content));
+ collected.unshift(...attachments);
+ crossedFinalAssistant = true;
+ continue;
+ }
+ // A previous assistant turn β€” stop walking, we don't want to dredge up
+ // attachments from prior conversation rounds.
+ break;
+ }
+
+ if (role === 'tool') {
+ // Tool results between the previous assistant turn and the final one.
+ collected.unshift(...extractAttachmentsFromContent(content));
+ }
+ }
+
+ // Prepending each message preserves both message and within-message order.
+ const seen = new Set<string>();
+ const result: OutboundAttachment[] = [];
+ for (const att of collected) {
+ const key = att.fetchUrl ?? att.data ?? '';
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ result.push(att);
+ }
+ return result;
+};
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
new file mode 100644
index 00000000000..14ac1266157
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
@@ -0,0 +1,308 @@
+/**
+ * Terminal persistence: the `agent_operations` completion row, the topic
+ * running mark, and the topic usage rollup.
+ */
+import { isParkedStatus } from '@lobechat/agent-runtime';
+import { type AgentOperationStatus, isAgentOperationInFlight } from '@lobechat/types';
+import debug from 'debug';
+
+import type { ChildUsageRollup } from '@/database/models/agentOperation';
+import { TopicModel } from '@/database/models/topic';
+import { recomputeTopicUsage } from '@/database/models/topicUsage';
+import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';
+
+import type { CompletionLifecycleDeps } from './types';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+/**
+ * The topic status a finished run leaves behind, mirroring what the client
+ * writes for the same outcome (`executeGatewayAgent`'s `onSessionComplete`) and
+ * what `agentNotify` does for the remote path: only a clean finish is something
+ * the user may not have watched (`unread`); every other ending is an
+ * interruption they already saw (`active`).
+ *
+ * Agrees with the one existing server-side settle, too:
+ * `ServerOperationStore.clearRunningMark` hardcodes `unread`, and it only ever
+ * runs from the `finish` executor β€” the success path, where this helper returns
+ * `unread` as well.
+ */
+const topicStatusForTerminalRun = (status: string): 'active' | 'unread' =>
+ status === 'done' ? 'unread' : 'active';
+
+/**
+ * Map a completion reason to the terminal `agent_operations.status` value.
+ * `waiting_for_human` / `waiting_for_async_tool` keep their own status so
+ * analytics can distinguish paused ops from terminal ones.
+ */
+export function statusForReason(
+ reason: string,
+):
+ | 'done'
+ | 'error'
+ | 'interrupted'
+ | 'waiting_for_human'
+ | 'waiting_for_async_tool'
+ | 'waiting_for_client' {
+ switch (reason) {
+ case 'error': {
+ return 'error';
+ }
+ case 'interrupted': {
+ return 'interrupted';
+ }
+ case 'waiting_for_human': {
+ return 'waiting_for_human';
+ }
+ case 'waiting_for_async_tool': {
+ return 'waiting_for_async_tool';
+ }
+ case 'waiting_for_client': {
+ return 'waiting_for_client';
+ }
+ default: {
+ return 'done';
+ }
+ }
+}
+
+/**
+ * Persist terminal state to `agent_operations`. Fire-and-forget: a DB
+ * outage must never block hook dispatch or the executor's terminal
+ * cleanup path.
+ */
+export async function persistCompletion(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ state: any,
+ reason: string,
+ settledAsAbandoned?: boolean,
+): Promise<boolean> {
+ 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 === 'waiting_for_client'
+ ? reason
+ : statusForReason(reason);
+
+ const runOrigin = state?.origin ?? {};
+ const agentId = runOrigin.agentId;
+ const topicId = runOrigin.topicId;
+ const traceS3Key =
+ agentId && topicId ? buildFinalSnapshotKey(agentId, topicId, operationId) : null;
+
+ const processingTimeMs = state?.createdAt
+ ? Date.now() - new Date(state.createdAt).getTime()
+ : null;
+
+ const runtimeStatus = 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(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
+ // tree it forked rather than only the tokens its own turns burned.
+ //
+ // Re-derived from the child rows on every write instead of accumulated onto
+ // this one: `recordCompletion` is a wholesale SET, and this method runs again
+ // each time the op parks and resumes β€” an additive rollup would multiply. The
+ // SUM is exact however often it re-runs.
+ //
+ // Skipped for sub-agents and group members themselves: nested sub-agents are
+ // rejected up front, so a child never has children of its own and the query
+ // would always return zero.
+ const rollup =
+ runOrigin.lineage?.isSubAgent === true ? undefined : await sumChildUsage(deps, operationId);
+
+ const add = (own: number | null | undefined, child: number): number | null => {
+ if (!child) return own ?? null;
+ return (own ?? 0) + child;
+ };
+
+ let completionDurable = false;
+ let conflictingTerminalOwner = false;
+ // The status the durable row actually carries. Usually this callback's own,
+ // but NOT when a terminal owner got there first with a different one β€” see
+ // the fallback below.
+ let durableStatus: AgentOperationStatus = status;
+ try {
+ const accepted = await deps.agentOperationModel.recordCompletion(operationId, {
+ completedAt,
+ completionReason,
+ cost: state?.cost ?? null,
+ error: state?.error ?? null,
+ interruption: state?.interruption ?? null,
+ llmCalls: add(state?.usage?.llm?.apiCalls, rollup?.llmCalls ?? 0),
+ // Backfill the executed model/provider when the terminal state carries
+ // them. The in-process runtime sets neither on `state` (the op already
+ // holds them from recordStart) so these stay undefined and recordCompletion
+ // skips them β€” a no-op. A heterogeneous run, which only learns its real
+ // model from the CLI stream, feeds them in via the synthetic state built in
+ // heteroFinish; the verify gate keys off op.model/provider, so dropping this
+ // backfill would leave op.model null and silently skip verify.
+ model: state?.model,
+ processingTimeMs,
+ provider: state?.provider,
+ status,
+ stepCount: state?.stepCount ?? null,
+ toolCalls: add(state?.usage?.tools?.totalCalls, rollup?.toolCalls ?? 0),
+ totalCost: add(state?.cost?.total, rollup?.totalCost ?? 0),
+ totalInputTokens: add(state?.usage?.llm?.tokens?.input, rollup?.totalInputTokens ?? 0),
+ totalOutputTokens: add(state?.usage?.llm?.tokens?.output, rollup?.totalOutputTokens ?? 0),
+ totalTokens: add(state?.usage?.llm?.tokens?.total, rollup?.totalTokens ?? 0),
+ traceS3Key,
+ // The `usage` / `cost` blobs stay the op's OWN accumulator, un-rolled-up:
+ // they are the runtime's counter, and the executor reads them back as state
+ // (the cost-limit gate compares `state.cost.total` against the budget). Only
+ // the scalar columns β€” the reporting surface β€” carry the whole tree.
+ usage: state?.usage ?? null,
+ });
+ if (accepted) {
+ completionDurable = true;
+ } else {
+ const operation = await deps.agentOperationModel.findById(operationId);
+ // Preserve the historical best-effort behavior when no durable start
+ // row exists, but never let a conflicting terminal owner be replaced.
+ conflictingTerminalOwner = !!operation;
+ // Someone else wrote a terminal row: the run is over even though this
+ // call is not the one that recorded it.
+ completionDurable = conflictingTerminalOwner;
+ // `recordCompletion` only refuses a row that is ALREADY terminal with a
+ // different status than this callback carries (its `where` matches every
+ // in-flight status, plus an equal one). So the row it refused is the
+ // authoritative outcome, and the topic must be settled for what landed β€”
+ // not for what this late callback is carrying. Two racing terminal
+ // callbacks (`done` vs `error`/`interrupted`) would otherwise write
+ // whichever one arrived second, `unread` and `active` included.
+ if (operation) durableStatus = operation.status;
+ }
+ } catch (error) {
+ log('[%s] Failed to persist operation completion (non-fatal): %O', operationId, error);
+ }
+
+ // The run is over durably β€” converge the topic's running mark, or it outlives
+ // the run (see `settleTopicRunningMark`). Deliberately not attempted when the
+ // completion above did not land: a DB error or a missing start row leaves the
+ // operation's own end unproven, and a mark cleared on an unproven ending
+ // reads as settled while `agent_operations` still says `running`.
+ if (completionDurable) {
+ await settleTopicRunningMark(deps, { operationId, status: durableStatus, topicId });
+ }
+
+ if (conflictingTerminalOwner) return false;
+
+ // The topic rollup's tool / human-interaction stats derive from the
+ // operation rows written above (`recomputeTopicUsage` reads their usage/cost
+ // blobs), but its usual trigger is the assistant message's usage write,
+ // which can land BEFORE this terminal persist. Refresh here so this op's
+ // tool spend shows up without waiting for the next message mutation.
+ // Idempotent (pure derived projection) and non-fatal.
+ if (topicId) {
+ try {
+ await deps.serverDB.transaction((trx) =>
+ recomputeTopicUsage(trx, deps.userId, topicId, deps.workspaceId),
+ );
+ } catch (error) {
+ log('[%s] Failed to recompute topic usage rollup (non-fatal): %O', operationId, error);
+ }
+ }
+
+ return true;
+}
+
+/**
+ * Drop the topic's `runningOperation` mark when a run reaches its terminal row.
+ *
+ * The ONLY server-side settle used to be `ServerOperationStore.clearRunningMark`,
+ * and it runs from a single place: the `finish` executor. Every ending that
+ * never emits a `finish` instruction therefore wrote a terminal
+ * `agent_operations` row and left the topic exactly as the run's start had left
+ * it β€” `status = 'running'` with `metadata.runningOperation` naming an operation
+ * that had already finished:
+ *
+ * - a Stop is persisted at the step boundary (`AgentRuntimeService.executeStep`
+ * sets the state to `interrupted` once the in-flight step returns), and the
+ * following delivery usually finds the operation already terminal;
+ * - `interruptOperation` settles a client-parked run itself, and
+ * `buildShareAbortResult` settles a revoked share visitor run;
+ * - a loop stopped by `max_steps` / `cost_limit` ends without the agent asking
+ * to finish.
+ *
+ * Nothing then revisited the row: the client's own settle is a single attempt
+ * that a transient server refusal discards, and the client watchdog only runs
+ * with that user's sidebar open. Observed 2026-10-13 on a self-hosted
+ * deployment as a topic shown "running" for 45 minutes whose operation row had
+ * been `interrupted` since 03:33:58Z with `topics.updated_at` frozen at the
+ * run's start β€” `settleRunningOperation` always bumps `updated_at`, so that
+ * timestamp is proof no settle ever reached the row. 16 rows of the same shape,
+ * the oldest two months old.
+ *
+ * Persisting the terminal row is the moment the run is over, so converging
+ * here covers every ending above (and any future one) instead of adding a call
+ * to each caller. Compare-and-clear, exactly as the executor's adapter does:
+ * only the operation the mark names β€” or one of its children β€” may drop it, so
+ * a newer run that claimed the topic meanwhile is left alone and answers
+ * `conflict`. Best-effort: a topic that cannot be reached must not fail the
+ * completion it already persisted.
+ */
+export async function settleTopicRunningMark(
+ deps: CompletionLifecycleDeps,
+ params: {
+ operationId: string;
+ status: AgentOperationStatus;
+ topicId?: string;
+ },
+): Promise<void> {
+ const { operationId, status, topicId } = params;
+
+ // No topic to settle (a sub-agent run, a bot thread, a verify pass).
+ if (!topicId) return;
+ // Only an ending may drop the mark. Not merely the parked three: the fallback
+ // above settles for the status read back from the row rather than one this
+ // callback authored, and `idle` / `running` are no more of an ending than a
+ // pause is. `isAgentOperationInFlight` is the shared authority for both.
+ if (isAgentOperationInFlight(status)) return;
+ // A lease-expired abandon settles the topic on its own path with its own
+ // status (`AbandonOperationService`); leave that one to it.
+ if (status === 'abandoned') return;
+
+ try {
+ const topicModel = new TopicModel(deps.serverDB, deps.userId, deps.workspaceId, undefined, {
+ includeShareVisitor: deps.includeShareVisitor,
+ });
+
+ const settled = await topicModel.settleRunningOperation(
+ topicId,
+ operationId,
+ topicStatusForTerminalRun(status),
+ );
+
+ // `missing` (another writer already cleared it) and `conflict` (a newer run
+ // owns the mark) are both correct no-ops, not failures.
+ if (settled.status !== 'settled') {
+ log('[%s] Topic running mark left alone: %s', operationId, settled.status);
+ }
+ } catch (error) {
+ log('[%s] Failed to settle the topic running mark (non-fatal): %O', operationId, error);
+ }
+}
+
+/** Best-effort child-usage rollup β€” a DB hiccup must not fail the completion write. */
+export async function sumChildUsage(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+): Promise<ChildUsageRollup | undefined> {
+ try {
+ return await deps.agentOperationModel.sumChildUsage(operationId);
+ } catch (error) {
+ log('[%s] Failed to sum child operation usage (non-fatal): %O', operationId, error);
+ return undefined;
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/recall.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/recall.ts
new file mode 100644
index 00000000000..3d5bcf77bff
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/recall.ts
@@ -0,0 +1,90 @@
+/**
+ * Completion push recall for runs the user is waiting on.
+ */
+import { RequestTrigger } from '@lobechat/types';
+import debug from 'debug';
+
+import { notifyAgentRunCompleted } from '@/business/server/agent-run/notifyAgentRunCompleted';
+
+import type { CompletionLifecycleDeps } from './types';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+/**
+ * Triggers whose completion recalls the user with a push notification. Beyond
+ * plain chat: `Scheduled` is a user-deferred chat turn ("send this in 3
+ * hours"), and `Cron` is today stamped only by the rate-limit auto-resume of a
+ * user's own chat turn (see scheduledRunKinds) β€” both are exactly the "user
+ * walked away mid-conversation" case the recall exists for. Everything else
+ * (task runner, bots, evals, API, agent-signal self-iterations, …) is
+ * background work and stays silent.
+ */
+const USER_RECALLABLE_TRIGGERS = new Set<string>([
+ RequestTrigger.Chat,
+ RequestTrigger.Cron,
+ RequestTrigger.Scheduled,
+]);
+
+/**
+ * The facts the recall gate needs. The trigger rides on `state.origin` for
+ * in-process runs (the appContext spread); synthetic terminals
+ * ({@link buildStateFromInput}) have none, so fall back to the op row
+ * `recordStart` stamped β€” which also reveals `parentOperationId`, marking
+ * internal child runs (verifier/repair/evidence pass it without `isSubAgent`).
+ * `trigger: undefined` means neither source knows.
+ */
+export async function resolveRunRecallFacts(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ runOrigin: { trigger?: unknown } | undefined,
+): Promise<{ isChildRun: boolean; trigger: string | undefined }> {
+ if (typeof runOrigin?.trigger === 'string')
+ return { isChildRun: false, trigger: runOrigin.trigger };
+
+ try {
+ const operation = await deps.agentOperationModel.findById(operationId);
+ return {
+ isChildRun: Boolean(operation?.parentOperationId),
+ trigger: operation?.trigger ?? undefined,
+ };
+ } catch (error) {
+ log('[%s] Failed to resolve run trigger from op row: %O', operationId, error);
+ return { isChildRun: false, trigger: undefined };
+ }
+}
+
+/**
+ * Push a completion recall β€” but only for runs the user is waiting on.
+ * Background executions (scheduled tasks, bots, evals, …) complete constantly
+ * and would spam the OS banner. An unknown trigger passes: human-approval
+ * chat continuations can reach here without one, and dropping a chat push is
+ * worse than a rare stray banner.
+ */
+export async function recallUserOnCompletion(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ event: { agentId?: string; duration?: number; lastAssistantContent?: string; topicId?: string },
+ runOrigin: { trigger?: unknown; userId?: string } | undefined,
+): Promise<void> {
+ const { isChildRun, trigger } = await resolveRunRecallFacts(deps, operationId, runOrigin);
+ if (isChildRun) {
+ log('[%s] Skipping completion push for internal child run', operationId);
+ return;
+ }
+ if (trigger !== undefined && !USER_RECALLABLE_TRIGGERS.has(trigger)) {
+ log('[%s] Skipping completion push for non-interactive trigger %s', operationId, trigger);
+ return;
+ }
+
+ await notifyAgentRunCompleted({
+ agentId: event.agentId || undefined,
+ duration: event.duration,
+ lastAssistantContent: event.lastAssistantContent,
+ operationId,
+ topicId: event.topicId,
+ userId: runOrigin?.userId || deps.userId,
+ // Personal runs leave this undefined β‡’ bare deep link; workspace
+ // runs carry the id so the business slot can slug-prefix the URL.
+ workspaceId: deps.workspaceId,
+ });
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts
new file mode 100644
index 00000000000..6ceccc74d60
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts
@@ -0,0 +1,225 @@
+/**
+ * Completion Agent Signal source events.
+ */
+import { isRecord } from '@lobechat/utils/object';
+import debug from 'debug';
+
+import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
+import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
+import { parseAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';
+import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
+
+import { buildLifecycleEvent, extractErrorMessage } from './lifecycleEvent';
+import type { CompletionLifecycleDeps, SignalEvent } from './types';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+/**
+ * Whether a lifecycle event's `metadata` belongs to an Agent Share visitor
+ * run. `principal.actor.shareVisitor.visitorUserId` is stamped once at operation
+ * creation (`AgentRuntimeService.createOperation`'s `initialState.metadata`)
+ * and rides the state through to the terminal event β€” mirrors
+ * `GatewayStreamNotifier`'s share-visitor check, the sibling chokepoint that
+ * scrubs the creator's `AgentState` off the visitor's WS channel.
+ *
+ * Exported so every OTHER chokepoint that emits a `userId`-scoped Agent
+ * Signal source event on the runtime's `state`/operation metadata (the
+ * `runtime.before_step` / `runtime.after_step` emissions in
+ * `AgentRuntimeService`) can reuse the exact same check instead of
+ * hand-rolling their own.
+ */
+export const isAgentShareRun = (
+ state:
+ { principal?: { actor?: { shareVisitor?: { visitorUserId?: string } } } } | undefined | null,
+): boolean => Boolean(state?.principal?.actor?.shareVisitor?.visitorUserId);
+
+const toAgentSignalSnapshotEvents = (
+ emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,
+): SignalEvent[] => {
+ if (!emission || emission.deduped) return [];
+ return toAgentSignalTraceEvents({
+ actions: emission.orchestration.actions,
+ results: emission.orchestration.results,
+ signals: emission.orchestration.emittedSignals,
+ source: emission.source,
+ });
+};
+
+/**
+ * Emit completion AgentSignal source events and return compact snapshot
+ * events for attachment to the trace step. Fire-and-forget.
+ */
+export async function emitSignalEvents(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ state: any,
+ reason: string,
+): Promise<SignalEvent[]> {
+ try {
+ const {
+ assistantMessageId,
+ metadata,
+ origin: runOrigin,
+ } = buildLifecycleEvent(deps.userId, operationId, state, reason);
+
+ // Agent Share visitor runs execute AS the creator (`runOrigin.userId` is
+ // the creator's id β€” see `isAgentShareRun`'s JSDoc), so every completion
+ // signal below (`agent.execution.completed` / `.failed`) would otherwise
+ // run synchronous policy processing and record creator-scoped windows /
+ // telemetry for a run an anonymous link visitor triggered. Suppress the
+ // whole emission rather than merely re-scoping it: a share visitor has no
+ // Agent Signal identity of its own to attribute this to.
+ if (isAgentShareRun(state)) {
+ log(
+ '[completion-lifecycle] skip agent signal emission for share visitor run op=%s reason=%s',
+ operationId,
+ reason,
+ );
+ return [];
+ }
+
+ let selfIteration =
+ reason === 'error' ? undefined : extractSelfIterationCompletionPayload(state);
+ if (reason !== 'error' && !selfIteration) {
+ try {
+ const operation = await deps.agentOperationModel.findById(operationId);
+ const operationMetadata = operation?.metadata;
+ if (operationMetadata?.agentSignal) {
+ selfIteration = extractSelfIterationCompletionPayload({
+ ...state,
+ origin: {
+ ...runOrigin,
+ signal: parseAgentSignalMarker(operationMetadata.agentSignal),
+ userId: runOrigin.userId || deps.userId,
+ },
+ });
+ }
+ } catch (error) {
+ log(
+ '[completion-lifecycle] failed to hydrate Agent Signal marker op=%s: %O',
+ operationId,
+ error,
+ );
+ }
+ }
+ // A memory-writer run's terminal state may not carry the tool calls that
+ // name the written memory (messages live in the DB). When the receipt would
+ // fall back to a generic "Memory saved" with no id, re-read the run's own
+ // thread so it can name the memory and offer undo.
+ const memoryTargetUnresolved = selfIteration?.mutations.some((mutation) => {
+ const target = isRecord(mutation.data) ? mutation.data.target : undefined;
+ return !isRecord(target) || !target.id;
+ });
+ if (selfIteration?.marker.kind === 'memory' && memoryTargetUnresolved && runOrigin.threadId) {
+ try {
+ const messages = await deps.messageModel.query(
+ {
+ agentId: runOrigin.agentId,
+ threadId: runOrigin.threadId,
+ topicId: runOrigin.topicId,
+ },
+ { allowShareVisitor: true },
+ );
+ selfIteration =
+ extractSelfIterationCompletionPayload({
+ ...state,
+ messages,
+ origin: { ...runOrigin, signal: selfIteration.marker, userId: selfIteration.userId },
+ }) ?? selfIteration;
+ } catch (error) {
+ log(
+ '[completion-lifecycle] failed to load memory-writer messages op=%s: %O',
+ operationId,
+ error,
+ );
+ }
+ }
+ if (reason !== 'error') {
+ log(
+ '[completion-lifecycle] emit agent.execution.completed op=%s userId=%s assistant=%s metaAssistant=%s selfIteration=%s',
+ operationId,
+ runOrigin.userId || deps.userId,
+ assistantMessageId ?? 'undefined',
+ metadata?.assistantMessageId ?? 'undefined',
+ selfIteration
+ ? `kind=${selfIteration.marker?.kind} mutations=${selfIteration.mutations?.length}`
+ : 'ABSENT',
+ );
+ }
+ const completionSignalEmission =
+ reason === 'error'
+ ? await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: runOrigin.agentId,
+ errorMessage: extractErrorMessage(state?.error),
+ operationId,
+ reason,
+ serializedContext: undefined,
+ topicId: runOrigin.topicId,
+ turnCount: state?.stepCount || 0,
+ },
+ sourceId: `${operationId}:complete:${reason}`,
+ sourceType: 'agent.execution.failed',
+ },
+ {
+ agentId: runOrigin.agentId,
+ db: deps.serverDB,
+ userId: runOrigin.userId || deps.userId,
+ workspaceId: deps.workspaceId,
+ },
+ { ignoreError: true },
+ )
+ : await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: runOrigin.agentId,
+ // Anchor the deferred skill synthesis to the completed assistant
+ // turn: the completion-stage skill handler walks this id back
+ // to the user message to read the parked candidate and seeds
+ // the skill under the assistant group β€” instead of synthesizing
+ // from the user prompt alone at inbound time. Resolved from
+ // the final assistant message row when operation metadata omits
+ // it (the server execAgent path).
+ anchorMessageId: assistantMessageId,
+ assistantMessageId,
+ operationId,
+ // Carry the completion reason so completion-stage consumers can
+ // tell a finished turn from a non-terminal pause
+ // (waiting_for_async_tool / waiting_for_human), which reuse this
+ // same source.
+ reason,
+ // Self-iteration runs carry their finalState tool outcomes here
+ // (the one point finalState is in hand) so the completion policy
+ // can project receipts. Undefined for every other agent.
+ selfIteration,
+ serializedContext: undefined,
+ steps: state?.stepCount || 0,
+ topicId: runOrigin.topicId,
+ turnCount: state?.stepCount || 0,
+ },
+ sourceId: `${operationId}:complete:${reason}`,
+ sourceType: 'agent.execution.completed',
+ },
+ {
+ agentId: runOrigin.agentId,
+ db: deps.serverDB,
+ userId: runOrigin.userId || deps.userId,
+ workspaceId: deps.workspaceId,
+ },
+ { ignoreError: true },
+ );
+
+ log(
+ '[completion-lifecycle] emission done op=%s reason=%s deduped=%s',
+ operationId,
+ reason,
+ (completionSignalEmission as { deduped?: boolean } | undefined)?.deduped ?? 'n/a',
+ );
+
+ return toAgentSignalSnapshotEvents(completionSignalEmission);
+ } catch (error) {
+ log('[%s] Completion signal emission error (non-fatal): %O', operationId, error);
+ return [];
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/testUtils.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/testUtils.ts
new file mode 100644
index 00000000000..d49c95796d8
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/testUtils.ts
@@ -0,0 +1,50 @@
+/**
+ * Shared fakes for the CompletionLifecycle scenario tests. Each test file keeps
+ * its own `vi.mock` calls (Vitest hoists them per file) and points the
+ * factories here, so every file observes the same mock functions.
+ */
+import { vi } from 'vitest';
+
+import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';
+
+// Default async no-op implementation: the production code chains `.catch` on
+// the returned promise, so a bare vi.fn() (returning undefined) would throw
+// inside every unrelated `done`-path test. mockRestore/mockReset fall back to
+// this original implementation.
+export const mockBuildRuntimeInterventionNotification = vi.fn<
+ () => Promise<NotifyAgentInterventionRequiredParams | undefined>
+>(async () => undefined);
+export const mockNotifyAgentInterventionRequired = vi.fn(async () => {});
+export const mockNotifyAgentRunCompleted = vi.fn(async () => {});
+export const mockListWorks = vi.fn(async (): Promise<{ id: string }[]> => []);
+export const mockSettleRunningOperation = vi.fn(async () => ({ status: 'settled' as const }));
+
+export const workModelModule = () => ({
+ WorkModel: vi.fn(function () {
+ return { listByRootOperation: mockListWorks };
+ }),
+});
+
+// `TopicModel.settleRunningOperation` is a class FIELD (bound per instance, not
+// on the prototype), so observing it means swapping the class. This is the only
+// TopicModel use in the lifecycle, and the tests assert both that it runs for a
+// finished run and that it is deliberately skipped otherwise.
+export const topicModelModule = () => ({
+ TopicModel: vi.fn(function () {
+ return { settleRunningOperation: mockSettleRunningOperation };
+ }),
+});
+
+export const agentInterventionReviewModule = () => ({
+ notifyAgentInterventionRequired: mockNotifyAgentInterventionRequired,
+});
+
+export const notifyAgentRunCompletedModule = () => ({
+ notifyAgentRunCompleted: mockNotifyAgentRunCompleted,
+});
+
+export const agentInterventionNotificationModule = () => ({
+ buildRuntimeInterventionNotification: mockBuildRuntimeInterventionNotification,
+});
+
+export const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
new file mode 100644
index 00000000000..91e1d6ed347
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
@@ -0,0 +1,84 @@
+import type { AgentOperationModel } from '@/database/models/agentOperation';
+import type { MessageModel } from '@/database/models/message';
+import type { LobeChatDatabase } from '@/database/type';
+
+import type { SerializedHook } from '../hooks';
+
+export type SignalEvent = { [key: string]: unknown; type: string };
+
+/**
+ * Normalized terminal-completion input for {@link CompletionLifecycle.completeOperation}.
+ *
+ * This is the single typed shape every NON-in-process terminal path passes in β€”
+ * heterogeneous CLI exit (`heteroFinish`), remote-agent done signal
+ * (`agentNotify`), and synchronous dispatch failure
+ * (`finalizeHeteroDispatchError`). `completeOperation` expands it into the
+ * runtime `state` shape `dispatchHooks` consumes via one builder, so there is
+ * exactly ONE place that mirrors the runtime state β€” no per-caller hand-rolled
+ * synthetic state to drift.
+ *
+ * The in-process runtime keeps calling `dispatchHooks` with its real, rich
+ * `state` directly (full message array, interruption, …) β€” it needs no synthesis.
+ */
+export interface OperationCompletionInput {
+ /** Owning agent id β€” trace snapshot key + the lifecycle event's `agentId`. */
+ agentId?: string;
+ /** Final assistant message row id β€” anchors the verify card / error bubble. */
+ assistantMessageId?: string;
+ cost?: { total?: number | null } | null;
+ /** Final assistant deliverable text β€” the verify gate's input + bot rendering. */
+ deliverable?: string;
+ /** Terminal error payload (error path only). */
+ error?: unknown;
+ /**
+ * The user goal (first user turn) β€” the verify gate judges against it. Typed
+ * `unknown` because message content is polymorphic (string or multimodal part
+ * array); `dispatchHooks` normalizes it to text the same way it does the
+ * in-process path's user turn.
+ */
+ goal?: unknown;
+ /** Executed model β€” the verify gate keys off `op.model`, so hetero backfills it. */
+ model?: string | null;
+ operationId: string;
+ /** Group orchestration role; members must not trigger user-facing completion recalls. */
+ orchestrationRole?: 'member' | 'supervisor';
+ /** Executed provider β€” see {@link OperationCompletionInput.model}. */
+ provider?: string | null;
+ /** Serialized webhook hooks (queue mode); ignored in local in-memory mode. */
+ serializedHooks?: SerializedHook[];
+ /** When the run started, so the terminal row keeps its processing time. */
+ startedAt?: Date | string;
+ stepCount?: number | null;
+ topicId?: string;
+ /** Trace / usage aggregates (llm calls, tokens, tool calls). */
+ usage?: unknown;
+ userId?: string;
+}
+
+/** 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
+ * dispatch-failure path, which surfaces a device-specific `detail`).
+ */
+ skipErrorMessageWrite?: boolean;
+}
+
+/** What the extracted completion steps read off a `CompletionLifecycle` instance. */
+export interface CompletionLifecycleDeps {
+ agentOperationModel: AgentOperationModel;
+ includeShareVisitor: boolean;
+ messageModel: MessageModel;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
deleted file mode 100644
index a19778e7a7e..00000000000
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ /dev/null
@@ -1,2280 +0,0 @@
-// @vitest-environment node
-import { type Message, parse } from '@lobechat/conversation-flow';
-import { ChatErrorType, RequestTrigger } from '@lobechat/types';
-import debug from 'debug';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';
-import { AgentOperationModel } from '@/database/models/agentOperation';
-import { WorkModel } from '@/database/models/work';
-import * as agentSignalService from '@/server/services/agentSignal';
-import * as verifyServices from '@/server/services/verify';
-import type * as WorkRegistrationModule from '@/server/services/workRegistration';
-import { registerWorksForOperation } from '@/server/services/workRegistration';
-
-import {
- CompletionLifecycle,
- CriticalAgentInterventionPersistenceError,
- isSuccessLikeCompletionReason,
-} from '../CompletionLifecycle';
-import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';
-
-// Default async no-op implementation: the production code chains `.catch` on
-// the returned promise, so a bare vi.fn() (returning undefined) would throw
-// inside every unrelated `done`-path test. mockRestore/mockReset fall back to
-// this original implementation.
-const {
- mockBuildRuntimeInterventionNotification,
- mockNotifyAgentInterventionRequired,
- mockNotifyAgentRunCompleted,
- mockListWorks,
- mockSettleRunningOperation,
-} = vi.hoisted(() => ({
- mockBuildRuntimeInterventionNotification: vi.fn<
- () => Promise<NotifyAgentInterventionRequiredParams | undefined>
- >(async () => undefined),
- mockNotifyAgentInterventionRequired: vi.fn(async () => {}),
- mockNotifyAgentRunCompleted: vi.fn(async () => {}),
- mockListWorks: vi.fn(async (): Promise<{ id: string }[]> => []),
- mockSettleRunningOperation: vi.fn(async () => ({ status: 'settled' as const })),
-}));
-
-vi.mock('@/database/models/work', () => ({
- WorkModel: vi.fn(function () {
- return { listByRootOperation: mockListWorks };
- }),
-}));
-
-// `TopicModel.settleRunningOperation` is a class FIELD (bound per instance, not
-// on the prototype), so observing it means swapping the class. This is the only
-// TopicModel use in the lifecycle, and the tests below assert both that it runs
-// for a finished run and that it is deliberately skipped otherwise.
-vi.mock('@/database/models/topic', () => ({
- TopicModel: vi.fn(function () {
- return { settleRunningOperation: mockSettleRunningOperation };
- }),
-}));
-
-vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({
- notifyAgentInterventionRequired: mockNotifyAgentInterventionRequired,
-}));
-
-vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({
- notifyAgentRunCompleted: mockNotifyAgentRunCompleted,
-}));
-
-vi.mock('../agentInterventionNotification', () => ({
- buildRuntimeInterventionNotification: mockBuildRuntimeInterventionNotification,
-}));
-
-vi.mock('@/server/services/workRegistration', async (importOriginal) => ({
- // Keep the real scope resolver: it is pure, and the share-visitor test below
- // asserts the scope it derives reaches both the scan and the anchor lookup.
- ...(await importOriginal<typeof WorkRegistrationModule>()),
- registerWorksForOperation: vi.fn(),
-}));
-
-const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));
-
-const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
-
-describe('CompletionLifecycle.recordStart diagnostics', () => {
- let debugNamespaces: string;
-
- beforeEach(() => {
- debugNamespaces = debug.disable();
- debug.enable('lobe-server:completion-lifecycle');
- });
-
- afterEach(() => {
- debug.enable(debugNamespaces);
- vi.restoreAllMocks();
- });
-
- it.each([undefined, { _hooks: [] }])(
- 'retains the database failure cause without persisted hooks: %j',
- async (metadata) => {
- vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(
- new Error('connection refused'),
- );
- const output = vi.spyOn(debug, 'log').mockImplementation(() => {});
-
- expect(await buildLifecycle().recordStart({ operationId: 'op-1', metadata })).toBe(false);
- expect(output.mock.calls.flat().join(' ')).toContain('connection refused');
- },
- );
-
- it('does not log database parameters containing hook credentials', async () => {
- const secret = 'synthetic-hook-authorization';
- vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(
- new Error(`Failed query; params: ${secret}`),
- );
- const output = vi.spyOn(debug, 'log').mockImplementation(() => {});
-
- expect(
- await buildLifecycle().recordStart({
- operationId: 'op-1',
- metadata: { _hooks: [{ webhook: { headers: { Authorization: secret } } }] },
- }),
- ).toBe(false);
- expect(output.mock.calls.flat().join(' ')).toContain('Failed to record operation start');
- expect(output.mock.calls.flat().join(' ')).not.toContain(secret);
- });
-});
-
-describe('isSuccessLikeCompletionReason', () => {
- // Regression: file-Work registration was gated on `reason === 'done'` alone,
- // silently skipping runs stopped by a step/cost cap even though the lifecycle
- // persists those as status='done' and recovers their assistant content.
- it('treats capped runs (max_steps / cost_limit) as successful completions', () => {
- expect(isSuccessLikeCompletionReason('done')).toBe(true);
- expect(isSuccessLikeCompletionReason('max_steps')).toBe(true);
- expect(isSuccessLikeCompletionReason('cost_limit')).toBe(true);
- });
-
- it('rejects non-success terminal and parked reasons', () => {
- expect(isSuccessLikeCompletionReason('error')).toBe(false);
- expect(isSuccessLikeCompletionReason('interrupted')).toBe(false);
- expect(isSuccessLikeCompletionReason('waiting_for_human')).toBe(false);
- expect(isSuccessLikeCompletionReason('waiting_for_async_tool')).toBe(false);
- });
-});
-
-describe('CompletionLifecycle.extractErrorMessage', () => {
- it('extracts message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {
- const lifecycle = buildLifecycle();
- const error = {
- _responseBody: { provider: 'lobehub' },
- error: { message: 'Budget exceeded' },
- errorType: 'InsufficientBudgetForModel',
- provider: 'lobehub',
- };
-
- expect(lifecycle.extractErrorMessage(error)).toBe('Budget exceeded');
- });
-
- it('extracts message from ChatCompletionErrorPayload (InvalidProviderAPIKey)', () => {
- const lifecycle = buildLifecycle();
- const error = {
- endpoint: 'https://cdn.example.com/v1',
- error: {
- code: '',
- error: { code: '', message: 'ζ— ζ•ˆηš„δ»€η‰Œ', type: 'new_api_error' },
- message: 'ζ— ζ•ˆηš„δ»€η‰Œ',
- status: 401,
- type: 'new_api_error',
- },
- errorType: 'InvalidProviderAPIKey',
- provider: 'openai',
- };
-
- expect(lifecycle.extractErrorMessage(error)).toBe('ζ— ζ•ˆηš„δ»€η‰Œ');
- });
-
- it('extracts message from formatted ChatMessageError with body.error.message', () => {
- const lifecycle = buildLifecycle();
- const error = {
- body: { error: { message: 'Rate limit exceeded' } },
- message: 'InvalidProviderAPIKey',
- type: 'InvalidProviderAPIKey',
- };
-
- expect(lifecycle.extractErrorMessage(error)).toBe('Rate limit exceeded');
- });
-
- it('extracts message from ChatMessageError with body.message', () => {
- const lifecycle = buildLifecycle();
- const error = {
- body: { message: 'Something went wrong' },
- message: 'error',
- type: 'InternalServerError',
- };
-
- expect(lifecycle.extractErrorMessage(error)).toBe('Something went wrong');
- });
-
- it('falls back to error.message when body is absent', () => {
- const lifecycle = buildLifecycle();
- const error = { message: 'Connection timeout', type: 'NetworkError' };
-
- expect(lifecycle.extractErrorMessage(error)).toBe('Connection timeout');
- });
-
- it('falls back to errorType when message is "error"', () => {
- const lifecycle = buildLifecycle();
- const error = { errorType: 'InsufficientBudgetForModel', message: 'error' };
-
- expect(lifecycle.extractErrorMessage(error)).toBe('InsufficientBudgetForModel');
- });
-
- it('returns undefined for null/undefined', () => {
- const lifecycle = buildLifecycle();
-
- expect(lifecycle.extractErrorMessage(null)).toBeUndefined();
- expect(lifecycle.extractErrorMessage(undefined)).toBeUndefined();
- });
-
- it('never returns [object Object] for nested error objects', () => {
- const lifecycle = buildLifecycle();
- const error = {
- _responseBody: { provider: 'lobehub' },
- error: { message: 'Budget exceeded' },
- errorType: 'InsufficientBudgetForModel',
- provider: 'lobehub',
- };
-
- const result = lifecycle.extractErrorMessage(error);
- expect(result).not.toBe('[object Object]');
- expect(typeof result).toBe('string');
- expect(result).toBe('Budget exceeded');
- });
-});
-
-describe('CompletionLifecycle.buildLifecycleEvent', () => {
- const callBuild = (state: unknown, reason = 'completed') =>
- (buildLifecycle() as any).buildLifecycleEvent('op-1', state, reason);
-
- it('attaches Markdown images explicitly included in the final reply without changing its text', () => {
- const url = 'https://cdn.example.com/f/file_image';
- const content = `Here is the result: ![Result](${url})`;
- const { event } = callBuild({ messages: [{ role: 'assistant', content }] });
- expect(event.attachments).toEqual([{ fetchUrl: url, type: 'image' }]);
- expect(event.lastAssistantContent).toBe(content);
- });
-
- it('preserves the order of distinct final-reply images', () => {
- const { event } = callBuild({
- messages: [
- {
- role: 'assistant',
- content:
- '![Before](https://cdn.example.com/before.png) ![After](https://cdn.example.com/after.png)',
- },
- ],
- });
- expect(event.attachments?.map((attachment: any) => attachment.fetchUrl)).toEqual([
- 'https://cdn.example.com/before.png',
- 'https://cdn.example.com/after.png',
- ]);
- });
-
- it('parses reference images in final text parts and deduplicates structured images', () => {
- const url = 'https://cdn.example.com/result.png';
- const { event } = callBuild({
- messages: [
- {
- role: 'assistant',
- content: [
- { type: 'text', text: `![one][result] ![two](${url})\n\n[result]: ${url}` },
- { type: 'image_url', image_url: { url } },
- ],
- },
- ],
- });
- expect(event.attachments).toEqual([{ fetchUrl: url, type: 'image' }]);
- });
-
- it('does not promote tool state, tool Markdown, or an earlier reply to final attachments', () => {
- const url = 'https://cdn.example.com/intermediate.png';
- const { event } = callBuild({
- messages: [
- { role: 'assistant', content: `![earlier](${url})` },
- { role: 'user', content: 'Analyze the result without sending an image.' },
- { role: 'assistant', content: '', tools: [{ id: 'call-image' }] },
- {
- role: 'tool',
- content: `![tool result](${url})`,
- state: { generations: [{ asset: { url, type: 'image' } }] },
- },
- { role: 'assistant', content: 'The composition is balanced.' },
- ],
- });
- expect(event.attachments).toBeUndefined();
- });
-
- it('does not treat ordinary links, code, escaped syntax or unsafe schemes as images', () => {
- const content = [
- 'https://cdn.example.com/plain.png',
- '[download](https://cdn.example.com/download.png)',
- '`![inline](https://cdn.example.com/inline.png)`',
- '```md\n![fenced](https://cdn.example.com/fenced.png)\n```',
- '\\![escaped](https://cdn.example.com/escaped.png)',
- '![unsafe](file:///tmp/image.png)',
- '![unsafe](javascript:alert)',
- ].join('\n\n');
- const { event } = callBuild({ messages: [{ role: 'assistant', content }] });
- expect(event.attachments).toBeUndefined();
- });
-
- it('extracts text content from a plain-string final assistant turn', () => {
- const state = {
- messages: [
- { content: 'user prompt', role: 'user' },
- { content: 'final answer', role: 'assistant' },
- ],
- origin: { agentId: 'agent-1', userId: 'user-1' },
- };
-
- const { event } = callBuild(state);
-
- expect(event.lastAssistantContent).toBe('final answer');
- expect(event.attachments).toBeUndefined();
- });
-
- it('preserves the final answer after DB messages are parsed into an assistantGroup', () => {
- const dbMessages: Message[] = [
- {
- content: 'user prompt',
- createdAt: 0,
- id: 'msg-user',
- role: 'user',
- updatedAt: 0,
- },
- {
- content: '',
- createdAt: 1,
- id: 'msg-tool-call',
- parentId: 'msg-user',
- role: 'assistant',
- tools: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'builtin',
- result_msg_id: 'msg-tool-result',
- type: 'default',
- },
- ],
- updatedAt: 1,
- },
- {
- content: 'tool result',
- createdAt: 2,
- id: 'msg-tool-result',
- parentId: 'msg-tool-call',
- role: 'tool',
- tool_call_id: 'tool-call-1',
- updatedAt: 2,
- },
- {
- content: 'final answer after tool use',
- createdAt: 3,
- id: 'msg-final',
- parentId: 'msg-tool-result',
- role: 'assistant',
- updatedAt: 3,
- },
- ];
- const { flatList } = parse(dbMessages);
-
- expect(flatList.at(-1)?.role).toBe('assistantGroup');
-
- const { assistantMessageId, event } = callBuild({ messages: flatList, metadata: {} });
-
- expect(assistantMessageId).toBe('msg-final');
- expect(event.lastAssistantContent).toBe('final answer after tool use');
- });
-
- it('extracts the final assistant leaf from an assistantGroup', () => {
- const state = {
- messages: [
- { content: 'user prompt', id: 'msg-user', role: 'user' },
- {
- children: [
- {
- content: '',
- id: 'msg-tool-call',
- tools: [
- {
- id: 'tool-call-1',
- result: { content: 'tool result', id: 'msg-tool-result' },
- },
- ],
- },
- { content: 'grouped final answer', id: 'msg-final' },
- ],
- content: '',
- id: 'msg-group',
- role: 'assistantGroup',
- },
- ],
- origin: { agentId: 'agent-1', userId: 'user-1' },
- };
-
- const { assistantMessageId, event } = callBuild(state);
-
- expect(assistantMessageId).toBe('msg-final');
- expect(event.lastAssistantContent).toBe('grouped final answer');
- });
-
- it('keeps the final empty assistantGroup leaf instead of falling back to stale text', () => {
- const state = {
- messages: [
- { content: 'stale prior answer', id: 'msg-stale', role: 'assistant' },
- { content: 'follow-up prompt', id: 'msg-user', role: 'user' },
- {
- children: [{ content: '', id: 'msg-final' }],
- content: '',
- id: 'msg-group',
- role: 'assistantGroup',
- },
- ],
- metadata: {},
- };
-
- const { assistantMessageId, event } = callBuild(state);
-
- expect(assistantMessageId).toBe('msg-final');
- expect(event.lastAssistantContent).toBeUndefined();
- });
-
- it('treats an empty assistantGroup as the final assistant boundary', () => {
- const state = {
- messages: [
- { content: 'stale prior answer', id: 'msg-stale', role: 'assistant' },
- { children: [], content: '', id: 'msg-empty-group', role: 'assistantGroup' },
- ],
- metadata: {},
- };
-
- const { assistantMessageId, event } = callBuild(state);
-
- expect(assistantMessageId).toBe('msg-empty-group');
- expect(event.lastAssistantContent).toBeUndefined();
- });
-
- it('extracts attachments from grouped assistant and tool-result leaves', () => {
- const state = {
- messages: [
- {
- children: [
- {
- content: '',
- id: 'msg-tool-call',
- tools: [
- {
- id: 'tool-call-1',
- result: {
- content: [
- {
- image_url: { url: 'https://cdn.example.com/tool.png' },
- type: 'image_url',
- },
- ],
- id: 'msg-tool-result',
- },
- },
- ],
- },
- {
- content: [
- { text: 'done', type: 'text' },
- {
- image_url: { url: 'https://cdn.example.com/final.png' },
- type: 'image_url',
- },
- ],
- id: 'msg-final',
- },
- ],
- content: '',
- id: 'msg-group',
- role: 'assistantGroup',
- },
- ],
- metadata: {},
- };
-
- const { event } = callBuild(state);
-
- expect(event.lastAssistantContent).toBe('done');
- expect(event.attachments).toEqual([
- expect.objectContaining({ fetchUrl: 'https://cdn.example.com/tool.png', type: 'image' }),
- expect.objectContaining({ fetchUrl: 'https://cdn.example.com/final.png', type: 'image' }),
- ]);
- });
-
- it('concatenates text parts from a multimodal final assistant turn', () => {
- const state = {
- messages: [
- {
- content: [
- { text: 'here is the image: ', type: 'text' },
- { image_url: { url: 'https://cdn.example.com/a.png' }, type: 'image_url' },
- { text: '\n\nhope it helps', type: 'text' },
- ],
- role: 'assistant',
- },
- ],
- metadata: {},
- };
-
- const { event } = callBuild(state);
-
- expect(event.lastAssistantContent).toBe('here is the image: \n\nhope it helps');
- expect(event.attachments).toEqual([
- expect.objectContaining({ fetchUrl: 'https://cdn.example.com/a.png', type: 'image' }),
- ]);
- });
-
- it('returns undefined text for image-only final assistant turn (no fallback to earlier text)', () => {
- // Regression: the previous implementation `.find(m => role === 'assistant' && hasText)`
- // would skip the image-only final turn and walk back to the earlier text
- // turn, shipping stale prose alongside the current image. The fix matches
- // on role only β€” text must be undefined when the final turn has no text.
- const state = {
- messages: [
- { content: 'stale prior text', role: 'assistant' },
- { content: 'follow-up prompt', role: 'user' },
- {
- content: [{ image_url: { url: 'https://cdn.example.com/new.png' }, type: 'image_url' }],
- role: 'assistant',
- },
- ],
- metadata: {},
- };
-
- const { event } = callBuild(state);
-
- expect(event.lastAssistantContent).toBeUndefined();
- expect(event.attachments).toEqual([
- expect.objectContaining({ fetchUrl: 'https://cdn.example.com/new.png', type: 'image' }),
- ]);
- });
-
- it('returns undefined text when there are no assistant messages', () => {
- const state = {
- messages: [{ content: 'just a user prompt', role: 'user' }],
- metadata: {},
- };
-
- const { event } = callBuild(state);
-
- expect(event.lastAssistantContent).toBeUndefined();
- expect(event.attachments).toBeUndefined();
- });
-
- it('returns undefined text when content is an empty string', () => {
- // `extractTextFromMessageContent` returns undefined for empty strings, so
- // an empty-string final assistant turn must not pretend it has text.
- const state = {
- messages: [{ content: '', role: 'assistant' }],
- metadata: {},
- };
-
- const { event } = callBuild(state);
-
- expect(event.lastAssistantContent).toBeUndefined();
- });
-
- it('handles missing messages array gracefully', () => {
- const { event } = callBuild({ origin: { agentId: 'a' } });
-
- expect(event.lastAssistantContent).toBeUndefined();
- expect(event.attachments).toBeUndefined();
- expect(event.agentId).toBe('a');
- });
-
- it('preserves safe external-agent context on completion hooks', () => {
- const { event } = callBuild(
- {
- error: {
- type: 'AgentRuntimeError',
- body: {
- agentType: 'claude-code',
- code: 'rate_limit',
- details: { kind: 'usage_limit' },
- stderr: 'secret path',
- rateLimitInfo: { status: 'rejected', rateLimitType: 'seven_day', resetsAt: 1789826400 },
- },
- },
- origin: { agentId: 'agent-1', userId: 'user-1' },
- },
- 'error',
- );
- expect(event.errorAttribution).toBe('user');
- expect(event.errorHeterogeneous).toEqual({
- agentType: 'claude-code',
- kind: 'usage_limit',
- rateLimitType: 'seven_day',
- resetsAt: 1789826400,
- });
- });
-
- it('populates errorType + attribution from the normalized error on the error path', () => {
- // Regression: the event previously carried only errorDetail/errorMessage, so
- // bot reply renderers never saw the stable code/attribution and always fell
- // back to the opaque Operation ID. buildLifecycleEvent must normalize the
- // runtime error via formatErrorForState and surface these taxonomy fields.
- const state = {
- error: { error: { message: 'fetch failed' }, errorType: 'ProviderNetworkError' },
- origin: { agentId: 'agent-1', userId: 'user-1' },
- };
-
- const { event } = callBuild(state, 'error');
-
- expect(event.errorType).toBe('ProviderNetworkError');
- expect(event.errorAttribution).toBe('system');
- expect(event.errorMessage).toBe('fetch failed');
- });
-
- it('carries the budget context of an exhausted allowance onto the event', () => {
- // Without this the bot reply can only say "not enough credits": which
- // allowance ran out, and by how much, lived in the error body and stopped
- // at the lifecycle boundary.
- const state = {
- error: {
- budget: {
- availableCredits: 7_242_747,
- budgetTypeAtError: 'workspace_member',
- requiredCredits: 197_391,
- shortfallCredits: 0,
- },
- error: { message: 'Workspace budget exceeded' },
- errorType: 'InsufficientBudgetForModel',
- },
- origin: { agentId: 'agent-1', userId: 'user-1' },
- };
-
- const { event } = callBuild(state, 'error');
-
- expect(event.errorBudget).toEqual({
- availableCredits: 7_242_747,
- budgetTypeAtError: 'workspace_member',
- requiredCredits: 197_391,
- shortfallCredits: 0,
- });
- });
-
- it('leaves errorType + attribution undefined when there is no error', () => {
- const { event } = callBuild({ messages: [], metadata: {} }, 'done');
-
- expect(event.errorType).toBeUndefined();
- expect(event.errorAttribution).toBeUndefined();
- });
-
- it('resolves assistantMessageId from the final assistant message row when metadata omits it', () => {
- // Regression: a server execAgent turn carries operation-level metadata
- // ({} in DB) with no assistantMessageId, so the completion event previously
- // shipped assistantMessageId=undefined and the deferred skill-synthesis
- // handler no-oped. The id must fall back to the persisted id on the final
- // assistant message row in state (deferred skill synthesis needs the
- // anchor to seed the skill under the assistant group, not under the user
- // message).
- const state = {
- messages: [
- { content: 'user prompt', id: 'msg-user', role: 'user' },
- { content: 'tool result', id: 'msg-tool', role: 'tool' },
- { content: 'final answer', id: 'msg-assistant', role: 'assistant' },
- { content: 'trailing tool result', id: 'msg-tool-2', role: 'tool' },
- ],
- origin: { agentId: 'agent-1', userId: 'user-1' },
- };
-
- const { assistantMessageId } = callBuild(state, 'done');
-
- expect(assistantMessageId).toBe('msg-assistant');
- });
-
- it('prefers metadata.assistantMessageId over the state row (client runtime path)', () => {
- // The client runtime path supplies assistantMessageId on operation metadata;
- // it must win over the state-row fallback so the anchor stays the id the
- // client already persisted the parked candidate against.
- const state = {
- messages: [{ content: 'final answer', id: 'msg-from-state', role: 'assistant' }],
- metadata: { assistantMessageId: 'msg-from-metadata' },
- origin: { agentId: 'agent-1' },
- };
-
- const { assistantMessageId } = callBuild(state, 'done');
-
- expect(assistantMessageId).toBe('msg-from-metadata');
- });
-
- it('leaves assistantMessageId undefined when neither metadata nor a state row carries it', () => {
- const { assistantMessageId } = callBuild(
- { messages: [{ content: 'just a user prompt', role: 'user' }], metadata: {} },
- 'done',
- );
-
- expect(assistantMessageId).toBeUndefined();
- });
-});
-
-describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it('persists budget errors without downgrading them to AgentRuntimeError', async () => {
- const lifecycle = buildLifecycle();
- const updateMessage = vi.fn().mockResolvedValue({ success: true });
- const budget = { required: 12 };
-
- (lifecycle as any).messageModel = { update: updateMessage };
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await lifecycle.dispatchHooks(
- 'op-1',
- {
- error: {
- budget,
- error: { message: 'Budget exceeded' },
- errorType: ChatErrorType.FreePlanLimit,
- provider: 'lobehub',
- },
- metadata: { assistantMessageId: 'msg-1' },
- host: { hooks: [] },
- status: 'error',
- },
- 'error',
- );
-
- expect(updateMessage).toHaveBeenCalledWith('msg-1', {
- error: expect.objectContaining({
- body: expect.objectContaining({
- budget,
- message: 'Budget exceeded',
- provider: 'lobehub',
- }),
- message: 'Budget exceeded',
- type: ChatErrorType.FreePlanLimit,
- }),
- });
- });
-
- it("writes the error onto the run's own assistant row when a server run carries no assistantMessageId", async () => {
- // A server `execAgent` turn leaves `metadata.assistantMessageId` unset; with
- // no client online (a closed tab, a bot, a schedule) nothing else writes
- // the error, so the reply row would stay an empty bubble.
- const lifecycle = buildLifecycle();
- const updateMessage = vi.fn().mockResolvedValue({ success: true });
- const findLatestAssistantByOperationId = vi.fn().mockResolvedValue({ id: 'msg-run' });
-
- (lifecycle as any).messageModel = { findLatestAssistantByOperationId, update: updateMessage };
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await lifecycle.dispatchHooks(
- 'op-1',
- {
- error: {
- error: { reason: 'claim_timeout', recoverable: true },
- errorType: 'ClientLlmExecutorUnavailable',
- provider: 'lmstudio',
- },
- host: { hooks: [] },
- metadata: {},
- origin: { topicId: 'tpc-1' },
- status: 'error',
- },
- 'error',
- );
-
- expect(findLatestAssistantByOperationId).toHaveBeenCalledWith({
- operationId: 'op-1',
- topicId: 'tpc-1',
- });
- expect(updateMessage).toHaveBeenCalledWith('msg-run', {
- error: expect.objectContaining({ type: 'ClientLlmExecutorUnavailable' }),
- });
- });
-
- it('rethrows critical webhook failures after terminal persistence', async () => {
- const lifecycle = buildLifecycle();
- const persistCompletion = vi
- .spyOn(lifecycle as any, 'persistCompletion')
- .mockResolvedValue(undefined);
- const dispatch = vi
- .spyOn(hookDispatcher, 'dispatch')
- .mockRejectedValue(
- new CriticalHookDeliveryError('task-on-complete', new Error('qstash down')),
- );
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await expect(
- lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, status: 'interrupted' },
- 'interrupted',
- ),
- ).rejects.toThrow('Critical webhook delivery failed: task-on-complete');
-
- expect(persistCompletion).toHaveBeenCalledBefore(dispatch);
- });
-
- it('does not dispatch hooks when another owner already interrupted the operation', async () => {
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(false);
- const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await lifecycle.dispatchHooks('op-reclaimed', { host: { hooks: [] }, status: 'done' }, 'done');
-
- 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 β€” the topic running mark', () => {
- /**
- * `recordCompletion` must land for the mark to be converged: the lifecycle
- * treats an ending whose own row write failed as unproven, and a mark cleared
- * on an unproven ending reads settled while `agent_operations` still says
- * `running`.
- */
- const acceptingOperationModel = () => ({
- findById: vi.fn(async () => null),
- recordCompletion: vi.fn(async () => true),
- sumChildUsage: vi.fn(async () => undefined),
- });
-
- const state = (overrides: Record<string, unknown> = {}) => ({
- host: { hooks: [] },
- messages: [{ content: 'final reply', role: 'assistant' }],
- origin: { agentId: 'agt_1', topicId: 'tpc_1' },
- status: 'interrupted',
- ...overrides,
- });
-
- beforeEach(() => {
- mockSettleRunningOperation.mockReset().mockResolvedValue({ status: 'settled' });
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it('drops the mark when an interrupted run reaches its terminal row', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
-
- await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
-
- // A Stop is a visible ending the user already saw: `active`, the same status
- // the client writes for an interrupted run.
- expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
- });
-
- it('drops the mark for a clean finish, as unread', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
-
- await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
-
- expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
- });
-
- it('drops the mark for a run the step cap stopped, which never runs `finish`', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
-
- await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'max_steps');
-
- expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
- });
-
- it.each(['waiting_for_async_tool', 'waiting_for_client', 'waiting_for_human'])(
- 'leaves the mark while the same operation is parked in %s',
- async (reason) => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
-
- await lifecycle.dispatchHooks('op-1', state({ status: reason }), reason);
-
- expect(mockSettleRunningOperation).not.toHaveBeenCalled();
- },
- );
-
- it('does nothing for a run with no topic', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
-
- await lifecycle.dispatchHooks('op-1', state({ origin: { agentId: 'agt_1' } }), 'interrupted');
-
- expect(mockSettleRunningOperation).not.toHaveBeenCalled();
- });
-
- it('leaves a lease-expired abandon to the path that settles it', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => ({ id: 'op-1', status: 'abandoned' })),
- recordCompletion: vi.fn(
- async (_id: string, params: { status: string }) => params.status === 'abandoned',
- ),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state({ status: 'error' }), 'error', {
- settledAsAbandoned: true,
- skipErrorMessageWrite: true,
- });
-
- // `AbandonOperationService` owns the topic there, with its own status.
- expect(mockSettleRunningOperation).not.toHaveBeenCalled();
- });
-
- it('leaves the mark when the terminal row could not be written', async () => {
- const lifecycle = buildLifecycle();
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => null),
- recordCompletion: vi.fn(async () => {
- throw new Error('db is down');
- }),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
-
- // The operation's own end is unproven, so the topic must keep saying so.
- expect(mockSettleRunningOperation).not.toHaveBeenCalled();
- consoleError.mockRestore();
- });
-
- it('leaves the mark when no durable row exists to prove the ending', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => null),
- recordCompletion: vi.fn(async () => false),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
-
- expect(mockSettleRunningOperation).not.toHaveBeenCalled();
- });
-
- it('still converges when another owner already wrote the terminal row', async () => {
- const lifecycle = buildLifecycle();
- const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => ({ id: 'op-1', status: 'interrupted' })),
- recordCompletion: vi.fn(async () => false),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
-
- // The run is over β€” someone else just recorded it β€” and hooks still stay
- // parked with that owner.
- expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
- expect(dispatch).not.toHaveBeenCalled();
- });
-
- /**
- * Two terminal callbacks can race for the same operation: `recordCompletion`
- * accepts the first and refuses the second β€” its `where` matches every
- * in-flight status plus an equal one, so a refusal proves the row already
- * landed and carries a DIFFERENT outcome. The topic must then be settled for
- * what landed. Settling for the late callback instead would flip `unread`
- * (a clean finish) to `active` (an interruption) or the other way round,
- * depending purely on which of the two reached its settle first.
- */
- it('settles for a `done` row when a late `interrupted` callback loses the race', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => ({ id: 'op-1', status: 'done' })),
- recordCompletion: vi.fn(async () => false),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state({ status: 'interrupted' }), 'interrupted');
-
- // The run finished cleanly, so the user may not have watched it.
- expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
- });
-
- it('settles for an `interrupted` row when a late `done` callback loses the race', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => ({ id: 'op-1', status: 'interrupted' })),
- recordCompletion: vi.fn(async () => false),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
-
- // The stopping point was a visible interruption, not a clean finish.
- expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
- });
-
- it('leaves the mark when the refused row is not an ending either', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = {
- // `idle` is outside `recordCompletion`'s in-flight set, so a row that
- // never started can refuse a terminal write while still not being over.
- findById: vi.fn(async () => ({ id: 'op-1', status: 'idle' })),
- recordCompletion: vi.fn(async () => false),
- sumChildUsage: vi.fn(async () => undefined),
- };
-
- await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
-
- expect(mockSettleRunningOperation).not.toHaveBeenCalled();
- });
-
- it('treats losing the race to a newer run as a no-op', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
- mockSettleRunningOperation.mockResolvedValue({ status: 'conflict' });
-
- await expect(lifecycle.dispatchHooks('op-1', state(), 'interrupted')).resolves.toBeUndefined();
-
- expect(mockSettleRunningOperation).toHaveBeenCalledTimes(1);
- });
-
- it('never fails the completion when the topic cannot be settled', async () => {
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = acceptingOperationModel();
- mockSettleRunningOperation.mockRejectedValue(new Error('topic row is locked'));
-
- await expect(lifecycle.dispatchHooks('op-1', state(), 'interrupted')).resolves.toBeUndefined();
- });
-});
-
-describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it('awaits the start-time verify-plan instantiation before running the completion gate', async () => {
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- // Control exactly when the fire-and-forget instantiation settles.
- let settle: () => void = () => {};
- const instantiation = new Promise<void>((resolve) => {
- settle = resolve;
- });
- const instantiateSpy = vi
- .spyOn(verifyServices, 'instantiateVerifyPlanOnStart')
- .mockReturnValue(instantiation);
- const runVerifySpy = vi
- .spyOn(verifyServices, 'runVerifyOnCompletion')
- .mockResolvedValue(undefined);
-
- // A top-level task op registers the (still-pending) instantiation at start.
- await lifecycle.recordStart({ operationId: 'op-1', taskId: 'task-1' } as any);
- expect(instantiateSpy).toHaveBeenCalledTimes(1);
-
- // Completion fires while the plan instantiation is still in flight.
- const doneState = { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
- const dispatch = lifecycle.dispatchHooks('op-1', doneState, 'done');
-
- // The gate must stay blocked on the pending instantiation, not race past it.
- await flushMicrotasks();
- expect(runVerifySpy).not.toHaveBeenCalled();
-
- // Once the plan lands, the gate proceeds against the now-confirmed plan.
- settle();
- await dispatch;
- expect(runVerifySpy).toHaveBeenCalledTimes(1);
- });
-
- it('does not register an instantiation for a repair / verifier sub-op (parentOperationId set)', async () => {
- const lifecycle = buildLifecycle();
- const instantiateSpy = vi
- .spyOn(verifyServices, 'instantiateVerifyPlanOnStart')
- .mockResolvedValue(undefined);
-
- await lifecycle.recordStart({
- operationId: 'op-2',
- parentOperationId: 'op-1',
- taskId: 'task-1',
- } as any);
-
- expect(instantiateSpy).not.toHaveBeenCalled();
- });
-});
-
-describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- const parkedState = {
- host: { hooks: [] },
- origin: { agentId: 'a' },
- status: 'waiting_for_async_tool',
- };
-
- it('persists the parked status but does NOT fire onComplete or unregister hooks', async () => {
- const lifecycle = buildLifecycle();
- const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await lifecycle.dispatchHooks('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();
- });
-
- it('treats a waiting_for_client park the same way: persisted, no onComplete, hooks kept', async () => {
- const lifecycle = buildLifecycle();
- const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
- const clientPark = { ...parkedState, status: 'waiting_for_client' };
-
- await lifecycle.dispatchHooks('op-1', clientPark, 'waiting_for_client');
-
- expect(persistSpy).toHaveBeenCalledWith('op-1', clientPark, 'waiting_for_client', undefined);
- expect(dispatchSpy).not.toHaveBeenCalled();
- expect(unregisterSpy).not.toHaveBeenCalled();
- });
-
- it('fires onComplete and unregisters on a terminal completion', async () => {
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- const doneState = { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
- await lifecycle.dispatchHooks('op-1', doneState, 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith('op-1', 'onComplete', expect.anything(), []);
- expect(unregisterSpy).toHaveBeenCalledWith('op-1');
- });
-});
-
-describe('CompletionLifecycle.dispatchHooks β€” completion notification', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- mockNotifyAgentRunCompleted.mockClear();
- });
-
- const stubSideEffects = (lifecycle: CompletionLifecycle) => {
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
- vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);
- // The recall gate falls back to the op row when metadata carries no trigger.
- (lifecycle as any).agentOperationModel = { findById: vi.fn(async () => null) };
- };
-
- const buildDoneState = (origin: Record<string, unknown> = {}) => ({
- createdAt: new Date(Date.now() - 90_000).toISOString(),
- messages: [{ content: 'final reply', role: 'assistant' }],
- host: { hooks: [] },
- origin: { agentId: 'agt_1', topicId: 'tpc_1', ...origin },
- status: 'done',
- });
-
- it('notifies with fields mapped from the lifecycle event on a done completion', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks('op-1', buildDoneState({ userId: 'user-2' }), 'done');
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
- expect(mockNotifyAgentRunCompleted).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'agt_1',
- duration: expect.any(Number),
- lastAssistantContent: 'final reply',
- operationId: 'op-1',
- topicId: 'tpc_1',
- userId: 'user-2',
- // Personal lifecycle (no workspaceId) forwards undefined β‡’ bare link.
- workspaceId: undefined,
- }),
- );
- });
-
- it('forwards the workspace id so a team run gets a workspace-scoped deep link', async () => {
- const lifecycle = new CompletionLifecycle({} as any, 'user-1', 'ws_1');
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks('op-1', buildDoneState({ userId: 'user-2' }), 'done');
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).toHaveBeenCalledWith(
- expect.objectContaining({ workspaceId: 'ws_1' }),
- );
- });
-
- // 'task' is TopicTrigger.RunTask (the task-runner funnel), not a RequestTrigger member.
- it.each(['task', RequestTrigger.Bot, RequestTrigger.Eval, RequestTrigger.Api])(
- 'does not notify for background %s-triggered completions',
- async (trigger) => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks('op-1', buildDoneState({ trigger }), 'done');
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
- },
- );
-
- // Scheduled = a user-deferred chat turn; Cron = the rate-limit auto-resume of
- // a user's chat turn. Both are "user walked away" runs the recall exists for.
- it.each([RequestTrigger.Chat, RequestTrigger.Scheduled, RequestTrigger.Cron])(
- 'notifies for a user-recallable %s-triggered completion',
- async (trigger) => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks('op-1', buildDoneState({ trigger }), 'done');
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
- },
- );
-
- it('falls back to the op row trigger when metadata carries none (synthetic hetero path)', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => ({ trigger: RequestTrigger.Bot })),
- };
-
- // heteroFinish/agentNotify build metadata via buildStateFromInput β€” no trigger.
- await lifecycle.dispatchHooks('op-1', buildDoneState(), 'done');
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
- });
-
- it('does not notify for internal child runs (verifier/repair pass parentOperationId only)', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn(async () => ({ parentOperationId: 'op-parent', trigger: null })),
- };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(), 'done');
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
- });
-
- it('does not notify for sub-agent completions', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks(
- 'op-1',
- buildDoneState({ lineage: { isSubAgent: true } }),
- 'done',
- );
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
- });
-
- it('does not notify for in-group member completions (orchestrationRole without isSubAgent)', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- // execAgentMember stamps in-group members with orchestrationRole: 'member'
- // but NOT isSubAgent β€” they are internal steps of the supervisor run.
- await lifecycle.dispatchHooks(
- 'op-1',
- buildDoneState({ lineage: { orchestrationRole: 'member' } }),
- 'done',
- );
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
- });
-
- it('preserves an in-group member role in synthesized completion state', () => {
- const lifecycle = buildLifecycle();
-
- const state = (lifecycle as any).buildStateFromInput({
- operationId: 'op-member',
- orchestrationRole: 'member',
- });
-
- expect(state.origin.lineage.orchestrationRole).toBe('member');
- });
-
- it.each(['max_steps', 'cost_limit'])(
- 'notifies on the success-like capped terminal %s (still produced a deliverable)',
- async (reason) => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(), reason);
- await flushMicrotasks();
-
- expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
- },
- );
-
- it('does not notify on error / aborted terminals', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
-
- await lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, origin: { agentId: 'agt_1' }, status: 'error' },
- 'error',
- );
-
- expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
- });
-
- it('a notification rejection never breaks the dispatch pipeline', async () => {
- const lifecycle = buildLifecycle();
- stubSideEffects(lifecycle);
- // Once-only: a persistent mockRejectedValue would survive afterEach
- // (restoreAllMocks skips plain vi.fn, mockClear keeps implementations)
- // and leak into later dispatchHooks('done') tests in this file.
- mockNotifyAgentRunCompleted.mockRejectedValueOnce(new Error('push provider down'));
-
- const doneState = { host: { hooks: [] }, origin: { agentId: 'agt_1' }, status: 'done' };
- await expect(lifecycle.dispatchHooks('op-1', doneState, 'done')).resolves.toBeUndefined();
- await flushMicrotasks();
-
- expect(hookDispatcher.dispatch).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.anything(),
- [],
- );
- expect(hookDispatcher.unregister).toHaveBeenCalledWith('op-1');
- });
-});
-
-describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- mockBuildRuntimeInterventionNotification.mockReset();
- mockBuildRuntimeInterventionNotification.mockResolvedValue(undefined);
- mockNotifyAgentInterventionRequired.mockReset();
- mockNotifyAgentInterventionRequired.mockResolvedValue(undefined);
- });
-
- const pendingNotification: NotifyAgentInterventionRequiredParams = {
- approvalMode: 'manual' as const,
- batch: {
- activityKey: '4369e854-719f-5301-bfa4-1f0742eec6ac',
- allowedActions: ['approve_tool', 'reject_continue', 'stop'],
- id: 'batch-1',
- kind: 'single' as const,
- sealed: true as const,
- stepIndex: 3,
- },
- context: {
- assistantMessageId: 'assistant-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- },
- items: [
- {
- allowedActions: ['approve_tool', 'reject_continue', 'stop'],
- interactionKind: 'tool_approval' as const,
- requestRevision: { hash: 'a'.repeat(64), version: 0 },
- sourceRef: {
- toolCallId: 'call-1',
- toolMessageId: 'tool-1',
- type: 'runtime' as const,
- },
- summary: 'Run command',
- surface: 'binary' as const,
- },
- ],
- summary: 'Approval required',
- systemActionEligibility: 'safe_single_binary' as const,
- userId: 'user-1',
- };
-
- const stubDurablePendingRows = (lifecycle: CompletionLifecycle) => {
- (lifecycle as any).messageModel = {
- findById: vi.fn().mockResolvedValue({
- id: 'tool-1',
- parentId: 'assistant-1',
- role: 'tool',
- topicId: 'topic-1',
- }),
- findMessagePlugin: vi.fn().mockResolvedValue({
- intervention: {
- batchId: 'batch-1',
- itemIndex: 0,
- operationId: 'op-1',
- status: 'pending',
- stepIndex: 3,
- },
- toolCallId: 'call-1',
- }),
- };
- };
-
- it('publishes Review only after operation and every sealed batch row are durable', async () => {
- const lifecycle = buildLifecycle();
- const order: string[] = [];
- vi.spyOn(lifecycle as any, 'persistCompletion').mockImplementation(async () => {
- order.push('persist-operation');
- return true;
- });
- mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
- mockNotifyAgentInterventionRequired.mockImplementation(async () => {
- order.push('notify');
- });
- (lifecycle as any).messageModel = {
- findById: vi.fn().mockImplementation(async () => {
- order.push('read-message');
- return {
- id: 'tool-1',
- parentId: 'assistant-1',
- role: 'tool',
- topicId: 'topic-1',
- };
- }),
- findMessagePlugin: vi.fn().mockImplementation(async () => {
- order.push('read-plugin');
- return {
- intervention: {
- batchId: 'batch-1',
- itemIndex: 0,
- operationId: 'op-1',
- status: 'pending',
- stepIndex: 3,
- },
- toolCallId: 'call-1',
- };
- }),
- };
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
- 'waiting_for_human',
- );
-
- expect(mockNotifyAgentInterventionRequired).toHaveBeenCalledWith(pendingNotification);
- expect(order[0]).toBe('persist-operation');
- expect(order.at(-1)).toBe('notify');
- });
-
- it('fails the parked lifecycle when one row is outside the sealed batch', async () => {
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
- mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
- (lifecycle as any).messageModel = {
- findById: vi.fn().mockResolvedValue({
- id: 'tool-1',
- parentId: 'assistant-1',
- role: 'tool',
- topicId: 'topic-1',
- }),
- findMessagePlugin: vi.fn().mockResolvedValue({
- intervention: {
- batchId: 'late-batch',
- itemIndex: 0,
- operationId: 'op-1',
- status: 'pending',
- stepIndex: 3,
- },
- toolCallId: 'call-1',
- }),
- };
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await expect(
- lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
- 'waiting_for_human',
- ),
- ).rejects.toBeInstanceOf(CriticalAgentInterventionPersistenceError);
-
- expect(mockNotifyAgentInterventionRequired).not.toHaveBeenCalled();
- });
-
- it('propagates a durable Review create failure so the parked lifecycle can retry', async () => {
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
- mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
- mockNotifyAgentInterventionRequired.mockRejectedValueOnce(new Error('database unavailable'));
- stubDurablePendingRows(lifecycle);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- const unregister = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await expect(
- lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
- 'waiting_for_human',
- ),
- ).rejects.toMatchObject({
- cause: expect.objectContaining({ message: 'database unavailable' }),
- name: 'CriticalAgentInterventionPersistenceError',
- });
-
- expect(hookDispatcher.dispatch).not.toHaveBeenCalled();
- expect(unregister).not.toHaveBeenCalled();
- });
-
- it('continues after post-create push fanout fails inside the business slot', async () => {
- const lifecycle = buildLifecycle();
- const pushFanout = vi.fn().mockRejectedValue(new Error('APNs unavailable'));
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);
- mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);
- mockNotifyAgentInterventionRequired.mockImplementation(async () => {
- // Cloud owns this boundary: the generic row is already durable here, so
- // downstream delivery is best-effort and must not reject the slot.
- await pushFanout().catch(() => undefined);
- });
- stubDurablePendingRows(lifecycle);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- await expect(
- lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
- 'waiting_for_human',
- ),
- ).resolves.toBeUndefined();
-
- expect(pushFanout).toHaveBeenCalledOnce();
- expect(hookDispatcher.dispatch).toHaveBeenCalledOnce();
- });
-
- it('does not build a Review when the parked operation persistence loses its CAS', async () => {
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(false);
-
- await lifecycle.dispatchHooks(
- 'op-1',
- { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
- 'waiting_for_human',
- );
-
- expect(mockBuildRuntimeInterventionNotification).not.toHaveBeenCalled();
- expect(mockNotifyAgentInterventionRequired).not.toHaveBeenCalled();
- });
-
- // Regression: the park is not a completed deliverable boundary. The fresh
- // continuation sees the complete history and performs the terminal scan;
- // registering here would freeze pre-approval file content too early.
- it('does NOT register on a human-approval park before its continuation', async () => {
- const mockRegister = vi.mocked(registerWorksForOperation);
- mockRegister.mockClear();
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
-
- const parkedState = {
- host: { hooks: [] },
- origin: { agentId: 'a' },
- status: 'waiting_for_human',
- };
- await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_human');
-
- expect(mockRegister).not.toHaveBeenCalled();
- });
-
- it('does NOT register on an async-tool park (same op resumes and registers later)', async () => {
- const mockRegister = vi.mocked(registerWorksForOperation);
- mockRegister.mockClear();
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- const lifecycle = buildLifecycle();
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
-
- const parkedState = {
- host: { hooks: [] },
- origin: { agentId: 'a' },
- status: 'waiting_for_async_tool',
- };
- await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_async_tool');
-
- expect(mockRegister).not.toHaveBeenCalled();
- });
-});
-
-describe('CompletionLifecycle.dispatchHooks β€” lastAssistantContent DB recovery (Discord bot empty-reply)', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- const buildDoneState = (assistantContent: string | undefined) => ({
- messages: [
- { content: 'user prompt', id: 'msg-user', role: 'user' },
- { content: assistantContent, id: 'msg-assistant', role: 'assistant' },
- ],
- host: { hooks: [] },
- origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
- status: 'done',
- });
-
- const setupSpies = (lifecycle: CompletionLifecycle) => {
- vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
- vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
- vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);
- vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
- vi.spyOn(console, 'warn').mockImplementation(function () {});
- return vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
- };
-
- it('recovers the reply text from the DB row when the state carries no assistant text', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const findById = vi.fn().mockResolvedValue({ content: 'the real reply', id: 'msg-assistant' });
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(findById).toHaveBeenCalledWith('msg-assistant');
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: 'the real reply' }),
- [],
- );
- });
-
- it('extracts final Markdown images when the reply is recovered from the database', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const content = '![Result](https://cdn.example.com/recovered.png)';
- (lifecycle as any).messageModel = {
- findById: vi.fn().mockResolvedValue({ content, id: 'msg-assistant' }),
- };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({
- attachments: [{ fetchUrl: 'https://cdn.example.com/recovered.png', type: 'image' }],
- lastAssistantContent: content,
- }),
- [],
- );
- });
-
- it('recovers by the final assistantGroup child id when grouped state carries no text', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const findById = vi.fn().mockResolvedValue({
- content: 'the grouped reply from DB',
- id: 'msg-group-final',
- });
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks(
- 'op-1',
- {
- messages: [
- { content: 'user prompt', id: 'msg-user', role: 'user' },
- {
- children: [
- { content: '', id: 'msg-tool-call', tools: [{ id: 'tool-call-1' }] },
- { content: '', id: 'msg-group-final' },
- ],
- content: '',
- id: 'msg-group',
- role: 'assistantGroup',
- },
- ],
- host: { hooks: [] },
- origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
- status: 'done',
- },
- 'done',
- );
-
- expect(findById).toHaveBeenCalledWith('msg-group-final');
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: 'the grouped reply from DB' }),
- [],
- );
- });
-
- it('does not hit the DB when the state already carries assistant text', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const findById = vi.fn();
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState('state reply'), 'done');
-
- expect(findById).not.toHaveBeenCalled();
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: 'state reply' }),
- [],
- );
- });
-
- // The named row can be an empty placeholder while the run's real reply sits
- // on another row (the Discord thread bug where the bot kept repeating the
- // same message). Resolve it by the run's own provenance
- // (`metadata.operationId`), never by "the latest assistant row in the topic" β€”
- // a topic can hold a concurrent run's rows.
- it('falls back to operation provenance when the named row is empty', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const findById = vi.fn().mockResolvedValue({ content: '', id: 'msg-assistant' });
- const findLatestAssistantByOperationId = vi
- .fn()
- .mockResolvedValue({ content: 'final step reply', id: 'msg-final-step' });
- (lifecycle as any).messageModel = { findById, findLatestAssistantByOperationId };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(findById).toHaveBeenCalledWith('msg-assistant');
- expect(findLatestAssistantByOperationId).toHaveBeenCalledWith({
- operationId: 'op-1',
- topicId: 'tpc-1',
- });
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: 'final step reply' }),
- [],
- );
- });
-
- it('extracts only text parts when the DB row stores serialized multimodal content', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const serialized = JSON.stringify([
- { text: 'ε›Ύι‡Œζ˜―δΈ€εͺ猫', type: 'text' },
- { image: 'data:image/png;base64,xxx', type: 'image' },
- ]);
- const findById = vi.fn().mockResolvedValue({
- content: serialized,
- id: 'msg-assistant',
- metadata: { isMultimodal: true },
- });
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: 'ε›Ύι‡Œζ˜―δΈ€εͺ猫' }),
- [],
- );
- });
-
- it('returns a plain-text reply verbatim even when it looks like a parts array', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- // A legitimate text answer that happens to be a JSON array with `type`
- // fields β€” without metadata.isMultimodal it must NOT be parsed as parts.
- const jsonLookalike = '[{"type":"custom","value":1}]';
- const findById = vi.fn().mockResolvedValue({ content: jsonLookalike, id: 'msg-assistant' });
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: jsonLookalike }),
- [],
- );
- });
-
- it('does not recover raw JSON from an image-only multimodal DB row', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const serialized = JSON.stringify([{ image: 'data:image/png;base64,xxx', type: 'image' }]);
- const findById = vi.fn().mockResolvedValue({
- content: serialized,
- id: 'msg-assistant',
- metadata: { isMultimodal: true },
- });
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: undefined }),
- [],
- );
- });
-
- it('leaves the event untouched when the DB row is empty too', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const findById = vi.fn().mockResolvedValue({ content: '', id: 'msg-assistant' });
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: undefined }),
- [],
- );
- });
-
- it('still dispatches the original event when the DB lookup throws', async () => {
- const lifecycle = buildLifecycle();
- const dispatchSpy = setupSpies(lifecycle);
- const findById = vi.fn().mockRejectedValue(new Error('db down'));
- (lifecycle as any).messageModel = { findById };
-
- await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- 'op-1',
- 'onComplete',
- expect.objectContaining({ lastAssistantContent: undefined }),
- [],
- );
- });
-
- it('skips recovery on the error path', async () => {
- const lifecycle = buildLifecycle();
- setupSpies(lifecycle);
- const findById = vi.fn();
- (lifecycle as any).messageModel = { findById, update: vi.fn().mockResolvedValue(undefined) };
-
- await lifecycle.dispatchHooks(
- 'op-1',
- { ...buildDoneState(''), error: { message: 'boom' }, status: 'error' },
- 'error',
- );
-
- expect(findById).not.toHaveBeenCalled();
- });
-});
-
-describe('CompletionLifecycle.emitSignalEvents β€” assistant anchor', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it('ships the resolved assistantMessageId on the completed payload for a server turn', async () => {
- // Regression: on a server execAgent turn the operation metadata has no
- // assistantMessageId, so the agent.execution.completed event used to carry
- // assistantMessageId=undefined and the deferred skill-synthesis handler
- // no-oped. The payload must now anchor to the final assistant message row
- // (so deferred skill synthesis seeds the skill under the completed turn's
- // assistant group, not as a floating mainline root).
- const emitSpy = vi
- .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
- .mockResolvedValue(undefined as any);
-
- const lifecycle = buildLifecycle();
- const state = {
- messages: [
- { content: 'user prompt', id: 'msg-user', role: 'user' },
- { content: 'final answer', id: 'msg-assistant', role: 'assistant' },
- ],
- origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
- stepCount: 2,
- };
-
- await lifecycle.emitSignalEvents('op-1', state, 'done');
-
- expect(emitSpy).toHaveBeenCalledTimes(1);
- const [emission] = emitSpy.mock.calls[0];
- expect(emission.sourceType).toBe('agent.execution.completed');
- expect(emission.payload).toMatchObject({
- anchorMessageId: 'msg-assistant',
- assistantMessageId: 'msg-assistant',
- });
- });
-
- it('reads a memory-writer run thread when the terminal state carries no messages', async () => {
- const emitSpy = vi
- .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
- .mockResolvedValue(undefined as any);
- const lifecycle = buildLifecycle();
- const query = vi.spyOn(lifecycle['messageModel'], 'query').mockResolvedValue([
- {
- id: 'msg-tool-call',
- role: 'assistant',
- tools: [
- {
- apiName: 'addPreferenceMemory',
- arguments: JSON.stringify({
- summary: 'Answer in bullets',
- title: 'Prefers bullet answers',
- }),
- id: 'call_pref',
- identifier: 'lobe-user-memory',
- type: 'builtin',
- },
- ],
- },
- {
- content: 'Preference memory saved with memoryId: "mem_1" and preferenceId: "pref_1"',
- id: 'msg-tool-result',
- role: 'tool',
- tool_call_id: 'call_pref',
- },
- ] as any);
-
- await lifecycle.emitSignalEvents(
- 'op-memory',
- {
- messages: [],
- origin: {
- agentId: 'agent-1',
- signal: { kind: 'memory', sourceId: 'memory-source-1', topicId: 'tpc-1' },
- threadId: 'thd-memory',
- topicId: 'tpc-1',
- userId: 'user-1',
- },
- stepCount: 3,
- usage: {
- tools: {
- byTool: [{ calls: 1, errors: 0, name: 'lobe-user-memory/addPreferenceMemory' }],
- },
- },
- },
- 'done',
- );
-
- expect(query).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: 'thd-memory', topicId: 'tpc-1' }),
- expect.anything(),
- );
- const [emission] = emitSpy.mock.calls[0];
- expect(emission.payload.selfIteration.mutations[0].data.target).toMatchObject({
- id: 'pref_1',
- memoryId: 'mem_1',
- title: 'Prefers bullet answers',
- });
- });
-
- it('hydrates a persisted self-reflection marker when terminal state metadata lost it', async () => {
- const emitSpy = vi
- .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
- .mockResolvedValue(undefined as any);
- const lifecycle = buildLifecycle();
- (lifecycle as any).agentOperationModel = {
- findById: vi.fn().mockResolvedValue({
- metadata: {
- agentSignal: {
- agentId: 'agent-1',
- kind: 'self-reflection',
- sourceId: 'reflection-source-1',
- topicId: 'tpc-1',
- },
- },
- }),
- };
-
- await lifecycle.emitSignalEvents(
- 'op-1',
- {
- messages: [{ content: 'review complete', id: 'msg-assistant', role: 'assistant' }],
- origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
- stepCount: 1,
- },
- 'done',
- );
-
- const [emission] = emitSpy.mock.calls[0];
- expect(emission.payload).toMatchObject({
- selfIteration: {
- marker: {
- agentId: 'agent-1',
- kind: 'self-reflection',
- sourceId: 'reflection-source-1',
- topicId: 'tpc-1',
- },
- userId: 'user-1',
- },
- });
- });
-});
-
-describe('CompletionLifecycle.registerFileWorks', () => {
- const mockRegister = vi.mocked(registerWorksForOperation);
- beforeEach(() => {
- mockListWorks.mockReset();
- });
-
- it('anchors an already registered Work after a folded tool turn with no file scan candidates', async () => {
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);
- const lifecycle = buildLifecycle();
- const update = vi
- .spyOn(lifecycle['messageModel'], 'update')
- .mockResolvedValue({ success: true });
- const state = {
- messages: [{ id: 'display-group', role: 'assistantGroup', children: [] }],
- metadata: { workAssistantMessageId: 'final-assistant' },
- origin: { sourceMessageId: 'source-user' },
- };
-
- await lifecycle.registerFileWorks('op-1', state);
-
- expect(mockListWorks).toHaveBeenCalledWith({
- includeFileWorks: true,
- limit: 1,
- rootOperationId: 'op-1',
- });
- expect(update).toHaveBeenCalledWith('final-assistant', {
- metadata: { work: { rootOperationId: 'op-1', userMessageId: 'source-user' } },
- });
- expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
- });
-
- it('does not anchor a reply when only other operations have Works', async () => {
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- const lifecycle = buildLifecycle();
- const update = vi
- .spyOn(lifecycle['messageModel'], 'update')
- .mockResolvedValue({ success: true });
-
- await lifecycle.registerFileWorks('op-1', {
- metadata: { assistantMessageId: 'final-assistant' },
- });
-
- expect(update).not.toHaveBeenCalled();
- });
-
- it('withholds the completion marker when an anchor write fails and retries it', async () => {
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);
- const lifecycle = buildLifecycle();
- const update = vi
- .spyOn(lifecycle['messageModel'], 'update')
- .mockResolvedValueOnce({ success: false })
- .mockResolvedValueOnce({ success: true });
- const state = { metadata: { assistantMessageId: 'final-assistant' } };
- await lifecycle.registerFileWorks('op-1', state);
- expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');
- await lifecycle.registerFileWorks('op-1', state);
- expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
- expect(update).toHaveBeenCalledTimes(2);
- });
-
- it('keeps registration retryable until the explicit final assistant id is available', async () => {
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);
- const lifecycle = buildLifecycle();
- const update = vi
- .spyOn(lifecycle['messageModel'], 'update')
- .mockResolvedValue({ success: true });
- const state: { metadata: { assistantMessageId?: string } } = { metadata: {} };
- await lifecycle.registerFileWorks('op-1', state);
- expect(update).not.toHaveBeenCalled();
- expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');
- state.metadata.assistantMessageId = 'final-assistant';
- await lifecycle.registerFileWorks('op-1', state);
- expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
- });
-
- it('preserves completion idempotency when the shell scanner resolved a fallback anchor', async () => {
- mockRegister.mockResolvedValue({ anchorMessageId: 'shell-assistant', attempted: 1, failed: 0 });
- mockListWorks.mockResolvedValue([{ id: 'registered-shell-work' }]);
- const lifecycle = buildLifecycle();
- const update = vi
- .spyOn(lifecycle['messageModel'], 'update')
- .mockResolvedValue({ success: true });
- const state = { metadata: {} };
- await lifecycle.registerFileWorks('op-1', state);
- expect(update).toHaveBeenCalledWith('shell-assistant', {
- metadata: { work: { rootOperationId: 'op-1', userMessageId: undefined } },
- });
- expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);
- mockRegister.mockClear();
- await lifecycle.registerFileWorks('op-1', state);
- expect(mockRegister).not.toHaveBeenCalled();
- });
-
- it('registers once and stamps the state marker so later calls skip', async () => {
- mockRegister.mockClear();
- mockRegister.mockResolvedValue({ attempted: 1, failed: 0 });
- const lifecycle = buildLifecycle();
- const state = {
- cost: { total: 1.25 },
- metadata: {},
- origin: { userId: 'user-2' },
- usage: { llm: { apiCalls: 2 } },
- } as any;
-
- await lifecycle.registerFileWorks('op-1', state);
-
- expect(mockRegister).toHaveBeenCalledTimes(1);
- // The terminal state's live totals ride along: on the pre-snapshot path the
- // op row's cost/usage columns are not persisted yet.
- expect(mockRegister).toHaveBeenCalledWith(
- expect.objectContaining({
- finalCost: { total: 1.25 },
- finalUsage: { llm: { apiCalls: 2 } },
- operationId: 'op-1',
- userId: 'user-2',
- }),
- );
- expect(state.metadata._fileWorksRegistered).toBe(true);
-
- // The dispatchHooks backstop receives the same state later in the request β€”
- // the marker must make that second call a no-op (no duplicate scan/export).
- await lifecycle.registerFileWorks('op-1', state);
- expect(mockRegister).toHaveBeenCalledTimes(1);
- });
-
- it('never throws and leaves the marker unset on failure so a later call retries', async () => {
- mockRegister.mockClear();
- mockRegister.mockRejectedValueOnce(new Error('sandbox export failed'));
- const lifecycle = buildLifecycle();
- const state = { metadata: {} } as any;
-
- await expect(lifecycle.registerFileWorks('op-1', state)).resolves.toBeUndefined();
- expect(state.metadata._fileWorksRegistered).toBeUndefined();
-
- mockRegister.mockResolvedValueOnce({ attempted: 1, failed: 0 });
- await lifecycle.registerFileWorks('op-1', state);
- expect(mockRegister).toHaveBeenCalledTimes(2);
- expect(state.metadata._fileWorksRegistered).toBe(true);
- });
-
- it('leaves the marker unset on a PARTIAL failure, then stamps it once all files land', async () => {
- // Regression: registerWorksForOperation swallows per-file failures and
- // never rejects, so a partial failure resolves normally. The marker must be
- // gated on the outcome (`failed === 0`), NOT stamped unconditionally β€” else
- // the dispatchHooks backstop skips the retry and the user gets neither a Work
- // nor the edited-files fallback card for the file that failed to export.
- mockRegister.mockClear();
- const lifecycle = buildLifecycle();
- const state = { metadata: {} } as any;
-
- // One of two files failed to export/register this round.
- mockRegister.mockResolvedValueOnce({ attempted: 2, failed: 1 });
- await lifecycle.registerFileWorks('op-1', state);
- expect(state.metadata._fileWorksRegistered).toBeUndefined();
-
- // The backstop retries; the previously-registered file short-circuits on the
- // DB probe and the failed one now lands β†’ failed=0 β†’ marker set.
- mockRegister.mockResolvedValueOnce({ attempted: 2, failed: 0 });
- await lifecycle.registerFileWorks('op-1', state);
- expect(mockRegister).toHaveBeenCalledTimes(2);
- expect(state.metadata._fileWorksRegistered).toBe(true);
- });
-
- it('tolerates a state without metadata', async () => {
- mockRegister.mockClear();
- mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
- const lifecycle = buildLifecycle();
-
- await expect(lifecycle.registerFileWorks('op-1', {} as any)).resolves.toBeUndefined();
- expect(mockRegister).toHaveBeenCalledTimes(1);
- });
-
- it('registers and anchors a share visitor run under its visitor-topic share scope', async () => {
- mockRegister.mockClear();
- vi.mocked(WorkModel).mockClear();
- mockRegister.mockResolvedValue({ attempted: 1, failed: 0 });
- mockListWorks.mockResolvedValue([{ id: 'visitor-file-work' }]);
- const lifecycle = buildLifecycle();
- const update = vi
- .spyOn(lifecycle['messageModel'], 'update')
- .mockResolvedValue({ success: true });
- const shareVisitor = { agentId: 'agt_1', shareId: 'share-1', visitorUserId: 'visitor-1' };
- const state = {
- metadata: { workAssistantMessageId: 'final-assistant' },
- origin: { sourceMessageId: 'source-user', topicId: 'tpc_visitor', userId: 'user-1' },
- principal: { actor: { shareVisitor } },
- };
-
- await lifecycle.registerFileWorks('op-1', state);
-
- expect(mockRegister).toHaveBeenCalledWith(
- expect.objectContaining({ agentShareVisitor: shareVisitor, operationId: 'op-1' }),
- );
- // The anchor lookup must read through the SAME scope the scan wrote under,
- // or the visitor's Work is never found and the chip never renders.
- expect(vi.mocked(WorkModel)).toHaveBeenCalledWith(expect.anything(), 'user-1', undefined, {
- shareId: 'share-1',
- topicId: 'tpc_visitor',
- type: 'agentShare',
- visitorUserId: 'visitor-1',
- });
- expect(update).toHaveBeenCalledWith('final-assistant', {
- metadata: { work: { rootOperationId: 'op-1', userMessageId: 'source-user' } },
- });
- });
-
- it('skips a share visitor run that has no topic instead of registering unscoped', async () => {
- mockRegister.mockClear();
- const lifecycle = buildLifecycle();
- const state = {
- metadata: {},
- origin: { userId: 'user-1' },
- principal: { actor: { shareVisitor: { shareId: 'share-1', visitorUserId: 'visitor-1' } } },
- };
-
- await expect(lifecycle.registerFileWorks('op-1', state)).resolves.toBeUndefined();
- expect(mockRegister).not.toHaveBeenCalled();
- expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');
- });
-});
diff --git a/packages/agent-signal/README.md b/packages/agent-signal/README.md
index cc705e7945f..dabc87d719e 100644
--- a/packages/agent-signal/README.md
+++ b/packages/agent-signal/README.md
@@ -97,8 +97,8 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv
| Source event | Constant | Primary producer | Payload intent |
| ------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
-| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle.ts) | Server agent execution completed with operation, step, topic, and context metadata. |
-| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |
+| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution completed with operation, step, topic, and context metadata. |
+| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |
| `agent.user.message` | `AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage` | [Workflow bridge](../../apps/server/src/workflows/agentSignal/run.ts), [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts) | User feedback/message content that policies can analyze for memory, prompt, document, or skill changes. |
| `bot.message.merged` | `AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged` | [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts) | Bot-platform message content merged into a conversation scope. |
| `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway error for a client-side runtime operation. |