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 1732-line HeterogeneousPersistenceHandler into cohesive modules (#21122)

Arvin Xuea1b565b8a8b
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
deleted file mode 100644
index 70fcb2c2d84..00000000000
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ /dev/null
@@ -1,1732 +0,0 @@
-import {
- type AgentInterventionInteractionKind,
- type AgentInterventionProvider,
- type AgentInterventionRequestData,
- type AgentStreamEvent,
- sanitizeAgentInterventionRequestForReview,
-} from '@lobechat/agent-gateway-client';
-import { LOADING_FLAT } from '@lobechat/const';
-import type {
- MainAgentIntent,
- MainAgentInterventionTransition,
- MainAgentReduceCtx,
- MainAgentRunState,
- MainAgentTurnToolState,
- SubagentIntent,
- SubagentRunSnapshot,
- ToolCallPayload,
-} from '@lobechat/heterogeneous-agents';
-import {
- createMainAgentRunState,
- reduceMainAgent,
- rehydrateSubagentRunsState,
-} from '@lobechat/heterogeneous-agents';
-import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';
-import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';
-import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types';
-import { createNanoId } from '@lobechat/utils';
-import debug from 'debug';
-
-import {
- deriveAgentInterventionActivityKey,
- hashAgentInterventionRequestRevision,
-} from '@/business/server/agent-run/agentInterventionIdentity';
-import {
- acknowledgeAgentInterventionProducerResolution,
- type AgentInterventionAllowedAction,
- type AgentInterventionReviewDetail,
- notifyAgentInterventionRequired,
- type NotifyAgentInterventionRequiredParams,
-} from '@/business/server/agent-run/agentInterventionReview';
-import type { MessageModel } from '@/database/models/message';
-import type { ThreadModel } from '@/database/models/thread';
-import type { TopicModel } from '@/database/models/topic';
-import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
-
-import {
- heteroProvenance,
- persistCodexTurnProvenance,
- restoreHeteroProvenance,
-} from './heteroProvenance';
-
-const log = debug('lobe-server:hetero-agent:persistence');
-
-const generateThreadId = () => `thd_${createNanoId(16)()}`;
-
-/**
- * Stable 32-bit FNV-1a hash of a string. Cheap to compute, collision odds are
- * negligible at this scope (a few thousand events per operation), and the
- * output is short enough to keep the per-operation `processedKeys` set small.
- */
-const fnv1a = (input: string): string => {
- let hash = 0x81_1c_9d_c5;
- for (let i = 0; i < input.length; i += 1) {
- hash ^= input.charCodeAt(i);
- // FNV prime 0x01000193, applied via bit shifts to stay in 32-bit math.
- hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0;
- }
- return hash.toString(36);
-};
-
-/**
- * Per-event idempotency key. CLI BatchIngester retries the SAME event objects
- * on transient failures, so the same `(stepIndex, type, data)` triple is
- * stable across retries β€” and distinct between back-to-back events even when
- * they share a millisecond timestamp.
- *
- * Why not just `(stepIndex, type, timestamp)`: producers stamp events with
- * `Date.now()` (see `claudeCode.ts` / `codex.ts` adapters), and CC bursts
- * multiple `stream_chunk` events through the same step within a single
- * millisecond. Without a content fingerprint, later chunks would collide with
- * earlier ones, get treated as duplicates, and be dropped β€” silently
- * truncating assistant output.
- *
- * Why not hash full `data`: tools_calling payloads can carry large argument
- * strings; a stable JSON.stringify on every event is cheap enough but the
- * resulting key would balloon the `processedKeys` set. Hashing keeps the key
- * bounded.
- */
-const eventKey = (event: AgentStreamEvent): string => {
- // Fingerprint the data via stable JSON. Order is irrelevant β€” adapters
- // produce events with consistent key order, and even if they didn't, the
- // important property is "same event input β†’ same output", which holds.
- const dataJson = (() => {
- try {
- return JSON.stringify(event.data ?? null);
- } catch {
- // Cyclic / unstringifiable payload: fall back to a coarse fingerprint.
- // Real wire data is always JSON-serializable, so this branch only fires
- // on bad test inputs.
- return String(typeof event.data);
- }
- })();
- return `${event.stepIndex}:${event.type}:${event.timestamp}:${fnv1a(dataJson)}`;
-};
-
-interface AssistantDbSnapshot {
- content: string;
- metadata: Record<string, any>;
- model: string | undefined;
- parentId: string | null | undefined;
- provider: string | undefined;
- reasoning: string;
- reasoningSnapshotSeq: number;
- textSnapshotSeq: number;
- tools: ChatToolPayload[];
-}
-
-interface AssistantMessageDbLike {
- content?: unknown;
- metadata?: Record<string, any> | null;
- model?: string;
- parentId?: string | null;
- provider?: string;
- reasoning?: { content?: string } | null;
- tools?: ChatToolPayload[] | null;
-}
-
-/**
- * Per-operation in-memory state. Lifetime spans the whole CLI run from first
- * `heteroIngest` batch through `heteroFinish`. Main-agent state is projected
- * back from DB at each ingest boundary; active subagent run state is still the
- * in-memory part of the operation.
- */
-interface OperationState {
- agentId: string | null;
- /** Native turn boundary shared by the user prompt and every assistant/tool step. */
- codexTurnId?: string;
- /**
- * CC-native session id this run is producing, captured off the stream_start
- * event stream and stamped on every persisted message's
- * `metadata.heteroSessionId`. Run-global and stable; a change ACROSS a topic
- * (visible only because it's copied per-message) means CC forked a new
- * session β€” the forensic signal for a lost-`--resume` "session break".
- * Recovered on a cold replica from the current assistant's stamped metadata.
- */
- heteroSessionId: string | undefined;
- /** Last DB-confirmed tool-state seq, scoped to this operation. */
- lastAppliedToolStateSeqByCallId: Map<string, number>;
- lastStepIndex: number;
- main: MainAgentRunState;
- /** `(operationId, toolCallId, transition)` notification dedupe ledger. */
- notifiedInterventionTransitions: Set<string>;
- operationId: string;
- processedKeys: Set<string>;
- /**
- * Publish gate, peer of `processedKeys` but for the live-stream sink.
- * Persistence and publish fail independently: a batch can persist fully
- * yet die inside the publish loop β€” its retry must republish ONLY the
- * unpublished tail β€” while a batch whose tRPC response was lost after
- * full success must republish nothing. Keyed by `eventKey`, latched only
- * after the event's XADD succeeds.
- */
- publishedKeys: Set<string>;
- /** User message answered by this operation, checked against its topic/thread before stamping. */
- sourceUserMessageId?: string;
- /** Isolation thread that owns this heterogeneous run, when applicable. */
- threadId: string | undefined;
- /**
- * Run-global DB index for every tool message in the topic, keyed by
- * `tool_call_id`. Main and subagent reducers keep only their per-turn maps;
- * this map lets a `tool_result` land even when its `tools_calling` was
- * reduced by another serverless replica.
- */
- toolMsgIdByCallId: Map<string, string>;
- topicId: string;
-}
-
-/**
- * Module-level singleton: `Map<operationId, OperationState>`. Service
- * instances are constructed per-request via the tRPC procedure middleware,
- * so per-instance state would not survive across requests. Keying off the
- * shared map lets two ingest batches for the same operationId share their
- * tool map / accumulated content / subagent runs.
- */
-const operationStates = new Map<string, OperationState>();
-
-/** Test-only reset hook to clear the singleton between specs. */
-export const __resetOperationStatesForTesting = () => operationStates.clear();
-
-export class StaleHeteroOperationError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'StaleHeteroOperationError';
- }
-}
-
-export interface HeterogeneousPersistenceHandlerDeps {
- /**
- * Liveness probe against the operation row, used only when the topic has lost
- * its `runningOperation` marker: it answers whether this operation is still
- * `running` and still owns this topic, i.e. whether the producer behind the
- * batch is alive. Optional so standalone/test callers keep the marker-only
- * behaviour.
- */
- isOperationLiveOnTopic?: (operationId: string, topicId: string) => Promise<boolean>;
- messageModel: MessageModel;
- threadModel: ThreadModel;
- topicModel: TopicModel;
- userId?: string;
- workspaceId?: string;
-}
-
-interface StoredHeterogeneousIntervention {
- deadline?: number;
- interactionKind?: AgentInterventionInteractionKind;
- notificationTransition?: MainAgentInterventionTransition;
- provider?: AgentInterventionProvider;
- resolutionRequestId?: string;
- summary?: string;
- transition?: MainAgentInterventionTransition;
-}
-
-const HETEROGENEOUS_INTERVENTION_STATE_KEY = 'heterogeneousIntervention';
-const MAX_INTERVENTION_SUMMARY_LENGTH = 160;
-
-const interventionSummary = (
- request?: AgentInterventionRequestData,
- reviewDetail?: Extract<
- AgentInterventionReviewDetail,
- { type: 'permission' | 'plan' | 'question' }
- >,
-): string => {
- if (reviewDetail?.type === 'question') {
- const question = reviewDetail.questions[0]?.question.trim().replaceAll(/\s+/g, ' ');
- if (question) {
- const characters = [...question];
- return characters.length > MAX_INTERVENTION_SUMMARY_LENGTH
- ? `${characters.slice(0, MAX_INTERVENTION_SUMMARY_LENGTH - 1).join('')}…`
- : question;
- }
- }
-
- const provider = request?.provider ?? 'heterogeneous-agent';
- const kind = request?.interactionKind ?? 'question';
- const apiName = request?.apiName || 'interaction';
- return `${provider} ${kind}: ${apiName}`.slice(0, MAX_INTERVENTION_SUMMARY_LENGTH);
-};
-
-const buildHeterogeneousReviewDetail = (
- request: AgentInterventionRequestData,
-): Extract<AgentInterventionReviewDetail, { type: 'permission' | 'plan' | 'question' }> => {
- const parsed = JSON.parse(request.arguments) as {
- questions: Array<{
- header: string;
- multiSelect: boolean;
- options: Array<{ description?: string; id?: string; label: string }>;
- question: string;
- }>;
- };
- const questions = parsed.questions.map((question, questionIndex) => ({
- header: question.header || undefined,
- id: `question_${questionIndex + 1}`,
- multiple: question.multiSelect,
- options: question.options.map((option) => ({
- description: option.description,
- id: option.id ?? option.label,
- label: option.label,
- })),
- question: question.question,
- }));
- const first = questions[0];
-
- switch (request.interactionKind) {
- case 'permission': {
- return {
- description: first.header,
- options: first.options,
- title: first.question,
- type: 'permission',
- };
- }
- case 'plan': {
- return {
- content: first.question,
- options: first.options,
- title: first.header ?? 'Review plan',
- type: 'plan',
- };
- }
- case 'question': {
- return {
- // The shared AskUser form offers "write your own" on every question,
- // plus whole-form freeform and a supplement note, and the producer's
- // bridge formats all three. Declare them so the claim accepts typed
- // answers instead of treating them as off-list selections.
- answerPolicy: { allowFreeform: true, allowSupplement: true },
- questions: questions.map((question) => ({ ...question, allowCustomAnswer: true })),
- title: first.header,
- type: 'question',
- };
- }
- default: {
- throw new Error('Unsupported heterogeneous intervention kind');
- }
- }
-};
-
-const heterogeneousActionsFor = (
- interactionKind: AgentInterventionInteractionKind,
-): AgentInterventionAllowedAction[] =>
- interactionKind === 'question'
- ? ['submit_answers', 'skip_interaction']
- : ['select_provider_option', 'skip_interaction'];
-
-const INTERVENTION_TRANSITIONS = new Set<MainAgentInterventionTransition>([
- 'cancelled',
- 'pending',
- 'resolved',
- 'session_ended',
- 'timed_out',
-]);
-
-const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([
- 'permission',
- 'plan',
- 'question',
-]);
-
-/** The raw text a CLI would have echoed into the answer for this failure. */
-const errorEchoText = (error: { body?: Record<string, unknown>; message?: string }): string => {
- const body = error.body ?? {};
- const candidate = [body.stderr, body.message, error.message].find(
- (value): value is string => typeof value === 'string' && value.trim().length > 0,
- );
-
- return candidate ?? '';
-};
-
-const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>([
- 'claude-code',
- 'cursor',
- 'devin',
- 'droid',
- 'qoder',
-]);
-
-/**
- * Server-side persistence for `lh hetero exec` event streams. Mirrors the
- * desktop renderer's `executeHeterogeneousAgent` (1.8k lines) for the DB
- * concerns only β€” IPC, store dispatch, notifications, refresh hooks all
- * live host-side and are intentionally absent here.
- *
- * Phase 2b scope:
- *
- * 1. 3-phase tool persist (assistant.tools[] pre-register β†’ tool message
- * create β†’ backfill `result_msg_id`)
- * 2. Subagent thread + per-turn assistant chaining + finalize on parent
- * tool_result
- * 3. Step boundary handling (new assistant per `stream_start { newStep }`)
- * 4. Per-turn metadata persistence (`step_complete` w/ `phase=turn_metadata`)
- * 5. Final content / reasoning flush on `agent_runtime_end` / `error`
- *
- * Failure semantics (differs from the renderer's optimistic UI posture):
- *
- * - DB writes propagate exceptions instead of swallowing them. A throw
- * bubbles to `ingest`, leaving the offending event un-marked in
- * `processedKeys` so the BatchIngester's outer retry replays it.
- * Idempotent state updates (per-tool `persistedIds`, payload de-dup,
- * `ThreadModel.onConflictDoNothing`) make replays safe.
- * - Renderer-only "log + continue" no longer applies β€” the server is
- * authoritative for cloud runs, so silent partial writes would diverge
- * DB from what the WS subscribers see.
- *
- * Multi-replica caveat: state is per-Node-process. Cloud sandbox routing
- * must be sticky to a single replica per operationId, otherwise turn
- * boundaries on the second replica would lose the chain-parent and
- * pre-existing tool map. (Phase 3 sandbox owns the endpoint per-instance,
- * so this is not a problem in practice.)
- */
-export class HeterogeneousPersistenceHandler {
- private readonly deps: HeterogeneousPersistenceHandlerDeps;
-
- constructor(deps: HeterogeneousPersistenceHandlerDeps) {
- this.deps = deps;
- }
-
- /**
- * Process a batch of events for an operation. Sequential within the batch.
- *
- * Idempotency contract: an event is marked `processed` ONLY after its
- * handler resolves cleanly. If a handler throws, the event stays unmarked
- * so a follow-up retry processes it again, and the throw bubbles to
- * `heteroIngest` β†’ tRPC β†’ BatchIngester so the producer re-sends. Events
- * that already succeeded earlier in the batch are skipped on retry via
- * the dedupe map, so the retry only re-runs the failed event onward.
- */
- async ingest(params: {
- assistantMessageId?: string;
- events: AgentStreamEvent[];
- operationId: string;
- topicId: string;
- }): Promise<void> {
- const state = await this.loadOrCreateState(
- params.operationId,
- params.topicId,
- params.assistantMessageId,
- );
- const batchMaxStepIndex = Math.max(...params.events.map((event) => event.stepIndex));
-
- // A different Lambda may have already processed `stream_start { newStep }`
- // and persisted `heteroCurrentMsgId` for this operation. Warm instances keep
- // their operation state in memory, so without an explicit resync they would
- // keep appending later-step chunks to the PREVIOUS assistant row. Only resync
- // when the incoming batch advances beyond the step this instance has seen.
- if (batchMaxStepIndex > state.lastStepIndex) {
- await this.syncAssistantPointerForAdvancedStep(state);
- }
-
- await this.refreshToolMessageIndex(state);
- await this.refreshMainStateFromDb(state);
- await this.refreshSubagentRunsFromDb(state);
-
- for (const event of params.events) {
- const key = eventKey(event);
- if (state.processedKeys.has(key)) {
- log('skip duplicate event %s op=%s', key, state.operationId);
- continue;
- }
-
- // NOTE: do NOT mark `processed` before the handler runs. Marking up
- // front would silently swallow event-level failures β€” the BatchIngester
- // would ack OK while DB state diverges from the renderer's view. Mark
- // only on success so a retry can complete the lost write.
- await this.handleEvent(state, event);
- state.processedKeys.add(key);
- state.lastStepIndex = Math.max(state.lastStepIndex, event.stepIndex);
- }
-
- // Flush accumulated content after every batch so a subsequent replica
- // picking up this operation always sees the latest content in the DB,
- // even if it never processes a step boundary or terminal event.
- await this.flushBatchContent(state);
- }
-
- /**
- * Events of the batch not yet successfully published to the live stream.
- * See `OperationState.publishedKeys` for why this gate is separate from
- * the persistence dedupe. Without state (already finished, or a retry on
- * a cold replica) every event is treated as unpublished β€” degrading to
- * republish-all. Main-agent text/reasoning survive that via their
- * `replace`-snapshot seq guards; the accepted cross-replica residuals are
- * subagent text (append semantics), tool lifecycle replays (benign client
- * upserts), and a duplicate trace fold β€” closing those needs a durable
- * publish identity (tracked follow-up), not a bigger in-memory map.
- */
- filterUnpublishedEvents(operationId: string, events: AgentStreamEvent[]): AgentStreamEvent[] {
- const state = operationStates.get(operationId);
- if (!state) return events;
-
- return events.filter((event) => !state.publishedKeys.has(eventKey(event)));
- }
-
- /** Latch an event as published so a batch retry skips its XADD. */
- markEventPublished(operationId: string, event: AgentStreamEvent): void {
- operationStates.get(operationId)?.publishedKeys.add(eventKey(event));
- }
-
- /**
- * Flush trailing accumulators and drop the per-operation state.
- *
- * Resume id source: CC's `--resume <sessionId>` token comes from the
- * adapter's cached `system:init.session_id`. The heterogeneous-agent service
- * settles topic-level resume ownership after this flush.
- *
- * Use when:
- * - A heterogeneous operation reaches a terminal producer callback.
- *
- * Expects:
- * - The operation state was created by ingest or can be bootstrapped from the topic marker.
- *
- * Returns:
- * - A promise that resolves after any finish-only error is projected and state is released.
- */
- async finish(params: {
- assistantMessageId?: string;
- error?: { body?: Record<string, unknown>; message: string; type: string };
- operationId: string;
- result: 'success' | 'error' | 'cancelled';
- /**
- * Needed to bootstrap state for a failed run that never ingested: a
- * process-level failure (spawn ENOENT, auth printed straight to stderr)
- * produces ZERO stream events, so no ingest ever created an
- * `OperationState` for this op.
- */
- topicId?: string;
- }): Promise<void> {
- let state = operationStates.get(params.operationId);
-
- // A run that died before producing any stream event has no state β€” but its
- // terminal error must still land on the assistant message HERE, before the
- // caller publishes `agent_runtime_end`. The client refetches messages on
- // that event, so deferring the write to CompletionLifecycle (which runs
- // after the publish) races the refetch and the error card doesn't render
- // live. Bootstrap from topic.metadata.runningOperation like ingest does;
- // a stale/mismatched operation stays a no-op.
- if (!state && params.result === 'error' && params.error && params.topicId) {
- try {
- state = await this.loadOrCreateState(
- params.operationId,
- params.topicId,
- params.assistantMessageId,
- true,
- );
- } catch (error) {
- log(
- 'finish bootstrap failed op=%s topic=%s err=%O',
- params.operationId,
- params.topicId,
- error,
- );
- return;
- }
- }
- if (!state) return;
-
- try {
- if (params.error) await this.persistFinishError(state, params.error);
- } finally {
- operationStates.delete(params.operationId);
- }
- }
-
- /**
- * Persist the CLI's native session id onto `topic.metadata.heteroSessionId`.
- * `TopicModel.updateMetadata` merges into existing JSONB so this does NOT
- * clobber `runningOperation` / `workingDirectory` / other peer fields.
- */
- private async persistSessionId(topicId: string, sessionId: string): Promise<void> {
- try {
- await this.deps.topicModel.updateMetadata(topicId, { heteroSessionId: sessionId });
- log('persisted sessionId topic=%s sessionId=%s', topicId, sessionId);
- } catch (err) {
- log('persistSessionId failed topic=%s err=%O', topicId, err);
- }
- }
-
- // ─── State management ────────────────────────────────────────────────────
-
- private async loadOrCreateState(
- operationId: string,
- topicId: string,
- seedAssistantMessageId?: string,
- allowMissingRunningOperation = false,
- ): Promise<OperationState> {
- let state = operationStates.get(operationId);
- if (state) {
- // Defensive: caller mismatch on topicId would corrupt persistence β€”
- // assert and throw rather than silently writing to the wrong topic.
- if (state.topicId !== topicId) {
- throw new Error(
- `Operation ${operationId} is already bound to topic ${state.topicId}, not ${topicId}`,
- );
- }
- return state;
- }
-
- const topic = await this.deps.topicModel.findById(topicId);
- const marker = topic?.metadata?.runningOperation;
- const running =
- marker?.operationId === operationId
- ? marker
- : marker?.childOperations?.find((child) => child.operationId === operationId);
-
- if (!running) {
- // Two different fates were collapsed into one refusal here.
- //
- // A marker naming ANOTHER operation means a newer run owns the topic:
- // this batch is genuinely late and has to be dropped, or it would keep
- // mutating a turn the conversation has already moved past.
- //
- // NO marker at all is a different story. The marker is a best-effort
- // rendering pointer that a client can settle on nothing more than a
- // transport signal β€” a raw `session_complete`, or one multiplexed socket
- // failing auth for every operation on the tab β€” while the producer is
- // still running and streaming. Refusing there throws away the whole
- // remaining output of a live CLI, which then burns minutes of work
- // nobody stores. The operation row is the authority on liveness, so ask
- // it: still `running`, still bound to THIS topic β‡’ keep persisting
- // without a marker. The turn's own pointers (`heteroCurrentMsgId`, the
- // seeded assistant message) carry the rest.
- const producerStillOwnsTopic =
- !marker && (await this.deps.isOperationLiveOnTopic?.(operationId, topicId));
-
- if (producerStillOwnsTopic) {
- log('marker missing but operation still running op=%s topic=%s', operationId, topicId);
- } else if (!(allowMissingRunningOperation && seedAssistantMessageId)) {
- throw new StaleHeteroOperationError(
- marker
- ? `Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${marker.operationId}`
- : `Stale hetero operation ${operationId} on topic ${topicId}; no active runningOperation`,
- );
- }
- }
-
- // Prefer the assistantMessageId forwarded in the ingest payload (sandbox path).
- // The orchestrator already has it in-memory and passes it through env β†’ CLI β†’ tRPC,
- // so this path avoids depending on `runningOperation.assistantMessageId`
- // itself being readable on this replica. We still require the topic's
- // runningOperation binding to match `operationId`, otherwise late/retried
- // batches after finish could keep mutating a completed turn.
- // Fall back to topic.metadata for desktop / old-CLI callers that lack the field.
- // `heteroCurrentMsgId` is the last resort and is scoped to this operation:
- // it is the only pointer left once a marker has been cleared out from under
- // a still-running producer (see the liveness check above).
- const currentMsgIdForOperation =
- topic?.metadata?.heteroCurrentMsgId?.operationId === operationId
- ? topic?.metadata?.heteroCurrentMsgId?.msgId
- : undefined;
- const baseAssistantMessageId =
- seedAssistantMessageId ?? running?.assistantMessageId ?? currentMsgIdForOperation;
-
- if (!baseAssistantMessageId) {
- throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);
- }
-
- const baseAssistantMessage = await this.deps.messageModel.findById(baseAssistantMessageId);
-
- if (seedAssistantMessageId) {
- if (!baseAssistantMessage) {
- throw new Error(
- `Seeded assistantMessageId ${seedAssistantMessageId} was not found for topic ${topicId}`,
- );
- }
- if (baseAssistantMessage.topicId !== topicId) {
- throw new Error(
- `Seeded assistantMessageId ${seedAssistantMessageId} does not belong to topic ${topicId}`,
- );
- }
- }
-
- // Prefer the latest step's assistant message id (written by handleStepStart)
- // over the initial placeholder β€” so a new replica after a step boundary uses
- // the correct message rather than the stale initial one.
- // Guard: only use heteroCurrentMsgId when it belongs to THIS operation.
- // A stale value from a previous run must not override the new operation's
- // seeded assistantMessageId (P1 fix).
- const stored = topic?.metadata?.heteroCurrentMsgId;
- const currentAssistantMessageId =
- stored?.operationId === operationId
- ? (stored.msgId ?? baseAssistantMessageId)
- : baseAssistantMessageId;
-
- state = {
- // A direct @Agent run keeps the topic under the conversation owner while
- // the seeded assistant belongs to the executing target Agent. Every
- // follow-up step and tool row must inherit the assistant author, not the
- // topic owner, or the post-tool answer appears to switch back to Lobe AI.
- // Legacy/finish-only callers may not have a readable assistant row; keep
- // the historical topic-owner fallback for those paths.
- agentId: baseAssistantMessage?.agentId ?? topic?.agentId ?? null,
- // Left undefined until the run's own stream_start reports it (or a cold
- // replica recovers it from a stamped message). NOT seeded from
- // topic.metadata.heteroSessionId: that holds the id we ASKED CC to resume,
- // which differs from the actual id when a fork/new session occurred.
- heteroSessionId: undefined,
- sourceUserMessageId: baseAssistantMessage?.parentId ?? undefined,
- lastStepIndex: 0,
- lastAppliedToolStateSeqByCallId: new Map(),
- main: createMainAgentRunState(currentAssistantMessageId),
- operationId,
- notifiedInterventionTransitions: new Set(),
- processedKeys: new Set(),
- publishedKeys: new Set(),
- toolMsgIdByCallId: new Map(),
- threadId: running?.threadId ?? undefined,
- topicId,
- };
- await this.refreshToolMessageIndex(state);
- await this.refreshMainStateFromDb(state);
- operationStates.set(operationId, state);
- log(
- 'created state for operation %s on topic %s msgId=%s tools=%d restored(content=%d tools=%d)',
- operationId,
- topicId,
- currentAssistantMessageId,
- state.toolMsgIdByCallId.size,
- state.main.accContent.length,
- state.main.toolState.payloads.length,
- );
- return state;
- }
-
- private createEmptyMainToolState(): MainAgentTurnToolState {
- return { payloads: [], persistedIds: new Set(), toolMsgIdByCallId: new Map() };
- }
-
- private toAssistantSnapshot(
- message: AssistantMessageDbLike | null | undefined,
- ): AssistantDbSnapshot {
- const rawContent = (message?.content ?? '') as string;
- const metadata = ((message?.metadata as Record<string, any> | null) ?? {}) as Record<
- string,
- any
- >;
- const textSnapshotSeq = Number(metadata.heteroTextSnapshotSeq ?? 0);
- const reasoningSnapshotSeq = Number(metadata.heteroReasoningSnapshotSeq ?? 0);
- return {
- content: rawContent === LOADING_FLAT ? '' : rawContent,
- metadata,
- model: message?.model,
- parentId: message?.parentId,
- provider: message?.provider,
- reasoning: (message?.reasoning as { content?: string } | null)?.content ?? '',
- reasoningSnapshotSeq: Number.isFinite(reasoningSnapshotSeq) ? reasoningSnapshotSeq : 0,
- textSnapshotSeq: Number.isFinite(textSnapshotSeq) ? textSnapshotSeq : 0,
- tools: (message?.tools ?? []) as ChatToolPayload[],
- };
- }
-
- private toToolPayload(tool: ChatToolPayload): ToolCallPayload {
- return {
- apiName: tool.apiName,
- arguments: tool.arguments,
- id: tool.id,
- identifier: tool.identifier,
- type: tool.type,
- };
- }
-
- private buildMainToolStateFromSnapshot(
- snapshot: AssistantDbSnapshot,
- toolMsgIdByCallId: Map<string, string>,
- ): MainAgentTurnToolState {
- const toolState = this.createEmptyMainToolState();
- const seen = new Set<string>();
-
- for (const tool of snapshot.tools) {
- if (!tool.id || seen.has(tool.id)) continue;
- const toolMessageId = tool.result_msg_id ?? toolMsgIdByCallId.get(tool.id);
- if (!toolMessageId) continue;
-
- seen.add(tool.id);
- toolState.payloads.push(this.toToolPayload(tool));
- toolState.persistedIds.add(tool.id);
- toolState.toolMsgIdByCallId.set(tool.id, toolMessageId);
- }
-
- return toolState;
- }
-
- private async refreshToolMessageIndex(state: OperationState): Promise<void> {
- const toolPlugins = await this.deps.messageModel.listMessagePluginsByTopic(state.topicId);
- for (const plugin of toolPlugins) {
- if (plugin.toolCallId) state.toolMsgIdByCallId.set(plugin.toolCallId, plugin.id);
- if (plugin.toolCallId && plugin.state && typeof plugin.state === 'object') {
- const stored = (plugin.state as Record<string, unknown>)[
- HETEROGENEOUS_INTERVENTION_STATE_KEY
- ];
- if (stored && typeof stored === 'object') {
- const metadata = stored as Record<string, unknown>;
- const transition = INTERVENTION_TRANSITIONS.has(
- metadata.transition as MainAgentInterventionTransition,
- )
- ? (metadata.transition as MainAgentInterventionTransition)
- : undefined;
- const interactionKind = INTERVENTION_KINDS.has(
- metadata.interactionKind as AgentInterventionInteractionKind,
- )
- ? (metadata.interactionKind as AgentInterventionInteractionKind)
- : undefined;
- const provider = INTERVENTION_PROVIDERS.has(
- metadata.provider as AgentInterventionProvider,
- )
- ? (metadata.provider as AgentInterventionProvider)
- : undefined;
-
- if (transition) {
- const request =
- typeof plugin.apiName === 'string' &&
- typeof plugin.arguments === 'string' &&
- typeof plugin.identifier === 'string' &&
- typeof metadata.deadline === 'number'
- ? {
- apiName: plugin.apiName,
- arguments: plugin.arguments,
- deadline: metadata.deadline,
- identifier: plugin.identifier,
- interactionKind,
- provider,
- toolCallId: plugin.toolCallId,
- }
- : undefined;
- state.main.interventionsByCallId.set(plugin.toolCallId, {
- intervention:
- plugin.intervention ??
- (transition === 'pending'
- ? { status: 'pending' }
- : transition === 'resolved'
- ? { status: 'approved' }
- : { rejectedReason: transition, status: 'rejected' }),
- request,
- resolutionRequestId:
- typeof metadata.resolutionRequestId === 'string'
- ? metadata.resolutionRequestId
- : undefined,
- transition,
- });
-
- if (metadata.notificationTransition === transition) {
- state.notifiedInterventionTransitions.add(
- `${state.operationId}:${plugin.toolCallId}:${transition}`,
- );
- }
- }
- }
- }
- if (
- plugin.toolCallId &&
- plugin.metadata?.heterogeneousToolStateOperationId === state.operationId &&
- typeof plugin.metadata.heterogeneousToolStateSeq === 'number'
- ) {
- state.lastAppliedToolStateSeqByCallId.set(
- plugin.toolCallId,
- Math.max(
- state.lastAppliedToolStateSeqByCallId.get(plugin.toolCallId) ?? 0,
- plugin.metadata.heterogeneousToolStateSeq,
- ),
- );
- }
- }
- }
-
- /**
- * Rehydrate reducer state from the DB projection of the current assistant.
- * This preserves the shared pure reducer as the single state machine while
- * keeping the serverless-specific "another replica already wrote this"
- * recovery outside the package.
- */
- private async refreshMainStateFromDb(state: OperationState): Promise<void> {
- const currentMsg = await this.deps.messageModel.findById(state.main.currentAssistantId);
- const snapshot = this.toAssistantSnapshot(currentMsg);
-
- // Recover the in-flight turn's CC message.id so a replayed `newStep` (cold
- // replica retry) is recognized as the SAME turn β€” no duplicate assistant,
- // no usage-only empty shell. Mirrors the subagent path's recovery of
- // `currentSubagentMessageId` from `metadata.subagentMessageId`.
- if (typeof snapshot.metadata.mainMessageId === 'string') {
- state.main.currentMainMessageId = snapshot.metadata.mainMessageId;
- }
-
- // Recover the run's CC session id from a previously-stamped message so a
- // cold replica that never saw this run's stream_start still stamps the
- // right session id on the messages it persists.
- restoreHeteroProvenance(state, snapshot.metadata);
-
- if (snapshot.textSnapshotSeq > state.main.lastTextSnapshotSeq) {
- state.main.accContent = snapshot.content;
- state.main.lastTextSnapshotSeq = snapshot.textSnapshotSeq;
- state.main.turnMetadata = snapshot.metadata;
- } else {
- if (snapshot.content.length > state.main.accContent.length) {
- state.main.accContent = snapshot.content;
- }
- if (
- Object.keys(state.main.turnMetadata).length === 0 &&
- Object.keys(snapshot.metadata).length > 0
- ) {
- state.main.turnMetadata = snapshot.metadata;
- }
- }
-
- // Seq-guarded reasoning restore mirrors the text path above; the length
- // heuristic stays as the fallback for legacy rows without a stamped seq.
- if (snapshot.reasoningSnapshotSeq > state.main.lastReasoningSnapshotSeq) {
- state.main.accReasoning = snapshot.reasoning;
- state.main.lastReasoningSnapshotSeq = snapshot.reasoningSnapshotSeq;
- } else if (snapshot.reasoning.length > state.main.accReasoning.length) {
- state.main.accReasoning = snapshot.reasoning;
- }
-
- const dbToolState = this.buildMainToolStateFromSnapshot(snapshot, state.toolMsgIdByCallId);
- for (const [toolCallId, toolMessageId] of dbToolState.toolMsgIdByCallId) {
- state.toolMsgIdByCallId.set(toolCallId, toolMessageId);
- }
- if (
- dbToolState.payloads.length > state.main.toolState.payloads.length ||
- dbToolState.persistedIds.size > state.main.toolState.persistedIds.size
- ) {
- state.main.toolState = dbToolState;
- }
-
- if (snapshot.model) state.main.turnModel = snapshot.model;
- if (snapshot.provider) state.main.turnProvider = snapshot.provider;
-
- // Recover the chain spine from the DB. The next normal
- // turn parents off the run's latest main-thread message that is neither a
- // tool nor a TOOLLESS signal callback (a tools-bearing signal turn is
- // main-chain β€” see `getLatestSpineMessageId`); reading it straight
- // from the DB (independent of
- // `currentAssistantId`, which can regress to the seed placeholder on a cold
- // / non-sticky replica β€” see the multi-replica caveat on the class) keeps
- // consecutive cold-replica steps chained linearly instead of forking onto a
- // stale node. Signal turns still anchor off `lastToolMsgIdEver`, which is
- // maintained in-memory across the run's tool batches.
- const spineId = await this.deps.messageModel.getLatestSpineMessageId({
- threadId: state.threadId ?? null,
- topicId: state.topicId,
- });
- if (spineId) state.main.lastSpineMessageId = spineId;
- }
-
- /**
- * Rebuild the in-flight subagent runs (`state.main.subagents`) from DB.
- *
- * The shared reducer keys runs by `parentToolCallId` and only lazy-creates a
- * thread when the run is ABSENT from this map. On a cold serverless replica
- * `createMainAgentRunState` seeds an empty map, so a subagent event whose
- * thread already exists (created by an earlier batch / another replica) would
- * fork a brand-new thread β€” the "ε€§ι‡ζ— ζ„δΉ‰ηš„ Subagent" bug. `refreshMainStateFromDb`
- * rebuilds the main-agent half; this rebuilds the subagent half the same way.
- *
- * Merge semantics: only runs MISSING from the in-memory map are rehydrated, so
- * a warm replica's live per-turn accumulators (`accContent`, current
- * `toolState`) are never clobbered by the DB projection.
- *
- * Finalized (`Active`) spawns are NOT rehydrated as live runs (a completed
- * spawn is never resurrected β€” that would mint spurious empty assistants and
- * re-finalize churn), but their `sourceToolCallId` IS recorded in
- * `finalizedParents` so a REPLAYED first-event on a cold replica can't fork a
- * duplicate thread for a spawn that already finished (the "δΈ€ζ¨‘δΈ€ζ ·ηš„δΈ€δΈͺ
- * thread" bug). This mirrors #15838's main-turn idempotency for the subagent
- * thread-create step: dedup keyed by the DB-homed `sourceToolCallId`,
- * independent of in-memory state and of thread status.
- *
- * Best-effort: any DB hiccup (or a partial test mock without the query
- * methods) leaves `state.main.subagents` untouched rather than aborting the
- * whole ingest.
- */
- private async refreshSubagentRunsFromDb(state: OperationState): Promise<void> {
- try {
- const threads = await this.deps.threadModel.queryByTopicId(state.topicId);
- const existing = state.main.subagents.runs;
- const snapshots: SubagentRunSnapshot[] = [];
- // Union with any parents finalized in-memory on a warm replica.
- const finalizedParents = new Set(state.main.subagents.finalizedParents);
-
- for (const thread of threads ?? []) {
- if (thread.type !== ThreadType.Isolation) continue;
- const meta = thread.metadata as { operationId?: string; sourceToolCallId?: string } | null;
- // Operation-scoped: only attend to threads THIS operation created.
- // Topics are reused across turns, so a prior run that crashed / was
- // cancelled without an ingested terminal event can leave its subagent
- // thread stuck in `Processing`. Without this guard the next operation
- // would merge that unrelated thread into its reducer state and then
- // finalize/mutate it on its own terminal drain. Threads written before
- // this field existed have no `operationId` and are skipped (safe β€” we
- // can't attribute them, and the live run re-creates what it needs).
- if (meta?.operationId !== state.operationId) continue;
- const parentToolCallId = meta?.sourceToolCallId;
- if (!parentToolCallId || existing.has(parentToolCallId)) continue;
-
- // Finalized spawn β†’ remember the key (blocks duplicate create), don't
- // rehydrate it as a live run.
- if (thread.status !== ThreadStatus.Processing) {
- finalizedParents.add(parentToolCallId);
- continue;
- }
-
- const messages = await this.deps.messageModel.query({
- threadId: thread.id,
- topicId: state.topicId,
- });
- const snapshot = this.buildSubagentSnapshot(parentToolCallId, thread.id, messages);
- if (snapshot) snapshots.push(snapshot);
- }
-
- // Nothing new to project: no rehydratable runs AND no finalized keys
- // beyond what memory already tracked (the set started as a copy of it and
- // only grows, so an unchanged size means no new Active threads were found).
- if (
- snapshots.length === 0 &&
- finalizedParents.size === state.main.subagents.finalizedParents.size
- ) {
- return;
- }
-
- // Union: rehydrated (missing) runs + the in-memory ones (which win, since
- // they carry live accumulators the DB hasn't caught up to yet) + the
- // finalized-parent guard set.
- const merged = rehydrateSubagentRunsState(snapshots, [...finalizedParents]);
- for (const [parentToolCallId, run] of existing) merged.runs.set(parentToolCallId, run);
- state.main = { ...state.main, subagents: merged };
- } catch (err) {
- log('refreshSubagentRunsFromDb failed op=%s err=%O', state.operationId, err);
- }
- }
-
- /**
- * Reconstruct one {@link SubagentRunSnapshot} from a thread's persisted
- * messages (ordered `createdAt` asc by the query). Returns undefined when the
- * thread has no assistant yet β€” without one there is nothing to attach a
- * continuation turn to, and the first-event path will (correctly) seed it.
- */
- private buildSubagentSnapshot(
- parentToolCallId: string,
- threadId: string,
- messages: Array<{
- id: string;
- metadata?: Record<string, any> | null;
- parentId?: string | null;
- role: string;
- tool_call_id?: string;
- }>,
- ): SubagentRunSnapshot | undefined {
- const assistants = messages.filter((m) => m.role === 'assistant');
- const currentAssistant = assistants.at(-1);
- if (!currentAssistant) return undefined;
-
- const toolRows = messages.filter((m) => m.role === 'tool' && m.tool_call_id);
- // Chain rule: the next turn's assistant parents off the
- // prior assistant (the spine), not its last child tool β€” recover the anchor
- // as the current assistant itself (matches the subagent reducer, and is
- // fork-resistant since it reads the thread's real latest assistant from DB).
- const lastChainParentId = currentAssistant.id;
- // Recover the in-flight turn's CC message.id so a continuation event is
- // recognized as the SAME turn (no spurious boundary β†’ no fragmentation).
- const currentSubagentMessageId =
- typeof currentAssistant.metadata?.subagentMessageId === 'string'
- ? currentAssistant.metadata.subagentMessageId
- : undefined;
-
- return {
- currentAssistantId: currentAssistant.id,
- currentSubagentMessageId,
- lastChainParentId,
- lifetimeToolCallIds: toolRows.map((m) => m.tool_call_id!),
- parentToolCallId,
- threadId,
- };
- }
-
- private async syncAssistantPointerForAdvancedStep(state: OperationState): Promise<void> {
- const topic = await this.deps.topicModel.findById(state.topicId);
- const marker = topic?.metadata?.runningOperation;
- const running =
- marker?.operationId === state.operationId
- ? marker
- : marker?.childOperations?.find((child) => child.operationId === state.operationId);
-
- // Same split as `loadOrCreateState`: another operation on the marker means
- // this run has been superseded and must stop writing, while a marker that
- // is simply gone can be a live producer whose topic was settled by a
- // transport signal. In the latter case `heteroCurrentMsgId` β€” repointed by
- // this operation's own ingest β€” is a complete substitute for the pointer
- // this sync would have read off the marker.
- if (
- !running &&
- (marker || !(await this.deps.isOperationLiveOnTopic?.(state.operationId, state.topicId)))
- ) {
- throw new StaleHeteroOperationError(
- `Stale hetero operation ${state.operationId} on topic ${state.topicId}; current operation is ${marker?.operationId ?? 'unknown'}`,
- );
- }
-
- const stored = topic?.metadata?.heteroCurrentMsgId;
- const authoritativeAssistantMessageId =
- stored?.operationId === state.operationId
- ? (stored.msgId ?? running?.assistantMessageId)
- : running?.assistantMessageId;
-
- if (
- !authoritativeAssistantMessageId ||
- authoritativeAssistantMessageId === state.main.currentAssistantId
- ) {
- return;
- }
-
- state.main = {
- ...state.main,
- accContent: '',
- accReasoning: '',
- currentAssistantId: authoritativeAssistantMessageId,
- lastReasoningSnapshotSeq: 0,
- lastTextSnapshotSeq: 0,
- toolState: this.createEmptyMainToolState(),
- turnMetadata: {},
- };
- await this.refreshToolMessageIndex(state);
- await this.refreshMainStateFromDb(state);
-
- log(
- 'synced warm state op=%s to assistant=%s after step advance',
- state.operationId,
- authoritativeAssistantMessageId,
- );
- }
-
- // ─── Event dispatch ──────────────────────────────────────────────────────
-
- private async handleEvent(state: OperationState, event: AgentStreamEvent): Promise<void> {
- await this.reduceAndApply(state, event);
- }
-
- // ─── Main-agent reducer interpreter ──────────────────────────────────────
-
- private mainReduceCtx(state: OperationState): MainAgentReduceCtx {
- return {
- agentId: state.agentId,
- newId: (kind) => (kind === 'thread' ? generateThreadId() : `msg_${createNanoId(18)()}`),
- topicId: state.topicId,
- };
- }
-
- /**
- * Single reducer entry point for the server persistence path. The reducer owns
- * both the main thread and nested subagent runs; this interpreter only applies
- * declarative intents to DB models. State commits after every intent succeeds,
- * so a failing DB write leaves the event unmarked and the BatchIngester retry
- * replays it against the previous reducer state.
- */
- private async reduceAndApply(state: OperationState, event: AgentStreamEvent) {
- // Capture the CC-native session id off the stream_start stream so every
- // message persisted below carries the session it belongs to. Stable per
- // run; the copy is what makes a mid-topic session fork detectable.
- if (event.type === 'stream_start') {
- const sid = (event.data as { sessionId?: string } | undefined)?.sessionId;
- if (typeof sid === 'string' && sid.length > 0 && sid !== state.heteroSessionId) {
- state.heteroSessionId = sid;
- // Persist the resume token the moment CC reports it, not only on a clean
- // `finish()`. A stuck run is abandoned by the inactivity watchdog via
- // AbandonOperationService, which never calls finish() β€” so a run that
- // produced a valid session id but got killed before finishing would
- // otherwise leave `topic.metadata.heteroSessionId` empty, forcing the
- // next turn to spawn a fresh CC session and drop all `--resume` history.
- // Writing it here makes resume survive abandon. The terminal service
- // path may still overwrite it after verifying topic ownership.
- await this.persistSessionId(state.topicId, sid);
- }
- }
-
- if (event.type === 'stream_start' && typeof event.data?.codexTurnId === 'string') {
- state.codexTurnId = event.data.codexTurnId;
- await persistCodexTurnProvenance(this.deps.messageModel, state);
- }
-
- const { intents, state: next } = reduceMainAgent(state.main, event, this.mainReduceCtx(state));
-
- for (const intent of intents) {
- if ('threadId' in intent) {
- await this.applySubagentIntent(state, intent as SubagentIntent);
- } else {
- await this.applyMainIntent(state, intent as MainAgentIntent, event.stepIndex);
- }
- }
-
- state.main = next;
- }
-
- private async applyMainIntent(state: OperationState, intent: MainAgentIntent, stepIndex: number) {
- switch (intent.kind) {
- case 'createAssistant': {
- const createMetadata: Record<string, any> = {
- ...heteroProvenance(state, intent.mainMessageId),
- };
- if (intent.signal) createMetadata.signal = intent.signal;
- // Persist the turn's CC message.id so a cold replica can recover
- // `currentMainMessageId` (via refreshMainStateFromDb) and dedupe a
- // replayed `newStep` instead of forking a duplicate + empty shell.
- if (intent.mainMessageId) createMetadata.mainMessageId = intent.mainMessageId;
- await this.deps.messageModel.create(
- {
- agentId: intent.agentId ?? undefined,
- content: '',
- ...(Object.keys(createMetadata).length > 0 ? { metadata: createMetadata } : {}),
- model: intent.model,
- parentId: intent.parentId,
- provider: intent.provider,
- role: 'assistant',
- threadId: state.threadId,
- topicId: intent.topicId ?? state.topicId,
- } as any,
- intent.messageId,
- );
-
- if (this.deps.topicModel.updateRunningOperationAssistantMessage) {
- await this.deps.topicModel.updateRunningOperationAssistantMessage(
- state.topicId,
- state.operationId,
- intent.messageId,
- );
- } else {
- await this.deps.topicModel.updateMetadata(state.topicId, {
- heteroCurrentMsgId: { msgId: intent.messageId, operationId: state.operationId },
- });
- }
- return;
- }
-
- case 'persistAssistant': {
- const update: Record<string, any> = {};
- if (intent.content !== undefined) update.content = intent.content;
- if (intent.reasoning !== undefined) update.reasoning = { content: intent.reasoning };
- if (intent.model) update.model = intent.model;
- if (intent.provider) update.provider = intent.provider;
- if (intent.metadata) update.metadata = intent.metadata;
- if (Object.keys(update).length > 0) {
- await this.deps.messageModel.update(intent.messageId, update);
- }
- return;
- }
-
- // Token-level live updates are renderer-only. The server persists durable
- // snapshots via persistAssistant / persistToolBatch / flushBatchContent.
- case 'streamContent': {
- return;
- }
-
- case 'persistToolBatch': {
- const buildUpdate = (withResult: boolean) =>
- this.buildToolBatchUpdate(intent.tools, {
- content: intent.content,
- reasoning: intent.reasoning,
- withResult,
- });
-
- // Phase 1: assistant.tools[] without result_msg_id.
- await this.deps.messageModel.update(intent.assistantMessageId, buildUpdate(false));
-
- // Phase 2: create new tool rows with reducer-preallocated ids.
- for (const tool of intent.tools) {
- if (!tool.isNew) continue;
- const toolMetadata = heteroProvenance(state, state.main.currentMainMessageId);
- await this.deps.messageModel.create(
- {
- agentId: state.agentId ?? undefined,
- content: '',
- ...(Object.keys(toolMetadata).length > 0 ? { metadata: toolMetadata } : {}),
- parentId: intent.assistantMessageId,
- plugin: {
- apiName: tool.payload.apiName,
- arguments: tool.payload.arguments,
- identifier: tool.payload.identifier,
- type: tool.payload.type,
- },
- role: 'tool',
- threadId: state.threadId,
- tool_call_id: tool.payload.id,
- topicId: state.topicId,
- } as any,
- tool.toolMessageId,
- );
- state.toolMsgIdByCallId.set(tool.payload.id, tool.toolMessageId);
- }
-
- // Phase 3: backfill result_msg_id.
- await this.deps.messageModel.update(intent.assistantMessageId, buildUpdate(true));
- return;
- }
-
- case 'resolveToolResult': {
- await this.applyToolResult(state, intent);
- return;
- }
-
- case 'updateToolState': {
- await this.applyToolState(state, intent);
- return;
- }
-
- case 'setToolIntervention': {
- await this.applyToolIntervention(state, intent, stepIndex);
- return;
- }
-
- case 'recordUsage': {
- const update: Record<string, any> = {};
- if (intent.usage !== undefined) {
- // This overwrites the row's metadata wholesale, so re-stamp the
- // provenance the createAssistant write put there, or usage would wipe it.
- update.metadata = {
- ...state.main.turnMetadata,
- ...heteroProvenance(state, state.main.currentMainMessageId),
- usage: intent.usage,
- };
- }
- if (intent.model) update.model = intent.model;
- if (intent.provider) update.provider = intent.provider;
- if (Object.keys(update).length > 0) {
- await this.deps.messageModel.update(intent.messageId, update);
- }
- return;
- }
-
- case 'setError': {
- // Normalize the CLI agent's wire error data through the SAME canonical
- // formatter the in-process runtime uses, so a hetero error is classified
- // (attribution/category/retryable) identically and the renderer never sees
- // a second, hetero-only error shape.
- const update: Record<string, any> = { error: formatErrorForState(intent.errorData) };
- if (intent.clearContent) update.content = '';
- await this.deps.messageModel.update(intent.messageId, update);
- return;
- }
- }
- }
-
- private async applyToolResult(
- state: OperationState,
- intent: {
- content: string;
- isError: boolean;
- pluginState?: Record<string, any>;
- toolCallId: string;
- },
- ) {
- const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
- if (!toolMsgId) {
- log('tool_result for unknown toolCallId=%s op=%s', intent.toolCallId, state.operationId);
- return;
- }
-
- const result = await this.deps.messageModel.updateToolMessage(toolMsgId, {
- content: intent.content,
- pluginError: intent.isError ? { message: intent.content } : undefined,
- pluginState: intent.pluginState,
- });
- if (!result.success) {
- throw new Error(`Failed to persist tool_result for message ${toolMsgId}`);
- }
- }
-
- private async applyToolState(
- state: OperationState,
- intent: {
- pluginState: Record<string, unknown>;
- snapshotSeq: number;
- toolCallId: string;
- },
- ): Promise<void> {
- const lastApplied = state.lastAppliedToolStateSeqByCallId.get(intent.toolCallId) ?? 0;
- if (intent.snapshotSeq <= lastApplied) return;
-
- const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
- if (!toolMsgId) {
- throw new Error(
- `tool_state for unknown toolCallId=${intent.toolCallId} op=${state.operationId}`,
- );
- }
-
- const result = await this.deps.messageModel.updateToolMessage(toolMsgId, {
- heterogeneousToolState: {
- operationId: state.operationId,
- snapshotSeq: intent.snapshotSeq,
- },
- pluginState: intent.pluginState,
- });
- if (!result.success) {
- throw new Error(`Failed to persist tool_state for message ${toolMsgId}`);
- }
-
- state.lastAppliedToolStateSeqByCallId.set(
- intent.toolCallId,
- result.snapshotSeq ?? intent.snapshotSeq,
- );
- }
-
- private async applyToolIntervention(
- state: OperationState,
- intent: Extract<MainAgentIntent, { kind: 'setToolIntervention' }>,
- stepIndex: number,
- ): Promise<void> {
- const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
- if (!toolMsgId) {
- throw new Error(
- `intervention for unknown toolCallId=${intent.toolCallId} op=${state.operationId}`,
- );
- }
-
- const reviewRequest = sanitizeAgentInterventionRequestForReview(intent.request);
- const reviewDetail = reviewRequest ? buildHeterogeneousReviewDetail(reviewRequest) : undefined;
- const summary = interventionSummary(intent.request, reviewDetail);
- const transitionKey = `${state.operationId}:${intent.toolCallId}:${intent.transition}`;
- const pendingTransitionKey = `${state.operationId}:${intent.toolCallId}:pending`;
- const requiresPendingReviewNotification =
- !!this.deps.userId &&
- !state.notifiedInterventionTransitions.has(transitionKey) &&
- !state.notifiedInterventionTransitions.has(pendingTransitionKey);
- if (
- requiresPendingReviewNotification &&
- (!reviewRequest?.interactionKind || !reviewRequest.provider || !reviewDetail)
- ) {
- throw new Error(
- `Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,
- );
- }
- const durableState: StoredHeterogeneousIntervention = {
- deadline: intent.request?.deadline,
- interactionKind: intent.request?.interactionKind,
- provider: intent.request?.provider,
- resolutionRequestId: intent.resolutionRequestId,
- summary,
- transition: intent.transition,
- };
-
- // Persist before any business side effect. The existing JSON plugin-state
- // column carries only correlation metadata; no schema/migration is needed.
- await this.deps.messageModel.updateMessagePlugin(toolMsgId, {
- intervention: intent.intervention,
- });
- await this.deps.messageModel.updatePluginState(toolMsgId, {
- [HETEROGENEOUS_INTERVENTION_STATE_KEY]: durableState,
- });
-
- if (!this.deps.userId || state.notifiedInterventionTransitions.has(transitionKey)) return;
-
- if (!state.notifiedInterventionTransitions.has(pendingTransitionKey)) {
- if (!reviewRequest?.interactionKind || !reviewRequest.provider || !reviewDetail) {
- throw new Error(
- `Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,
- );
- }
- const assistantMessageId = state.main.currentAssistantId;
- if (!assistantMessageId) {
- throw new Error(
- `Missing assistant owner for heterogeneous intervention toolCallId=${intent.toolCallId}`,
- );
- }
- // Heterogeneous callbacks are individually sealed. Include the tool call
- // so two concurrent interventions emitted by one assistant step never
- // claim the same batch identity with conflicting item-0 contents.
- const batchId = `${state.operationId}:${stepIndex}:${assistantMessageId}:${intent.toolCallId}`;
- // The generic Web source bridge reads the same authoritative correlation
- // from the tool row. Stamp it before notify so a card can never appear
- // actionable while its operation/batch locator is still absent.
- await this.deps.messageModel.updateMessagePlugin(toolMsgId, {
- intervention: {
- ...intent.intervention,
- batchId,
- itemIndex: 0,
- operationId: state.operationId,
- stepIndex,
- },
- });
- const allowedActions = heterogeneousActionsFor(reviewRequest.interactionKind);
- const notification: NotifyAgentInterventionRequiredParams = {
- agentId: state.agentId ?? undefined,
- approvalMode: 'manual',
- batch: {
- activityKey: deriveAgentInterventionActivityKey({
- batchId,
- operationId: state.operationId,
- userId: this.deps.userId,
- workspaceId: this.deps.workspaceId,
- }),
- allowedActions: [],
- id: batchId,
- kind: 'single',
- sealed: true,
- stepIndex,
- },
- context: {
- agentId: state.agentId ?? undefined,
- assistantMessageId,
- operationId: state.operationId,
- topicId: state.topicId,
- workspaceId: this.deps.workspaceId,
- },
- deadline: reviewRequest.deadline,
- items: [
- {
- allowedActions,
- detail: reviewDetail,
- interactionKind: reviewRequest.interactionKind,
- provider: reviewRequest.provider,
- requestRevision: {
- hash: hashAgentInterventionRequestRevision(intent.request?.arguments ?? ''),
- version: 1,
- },
- sourceRef: {
- operationId: state.operationId,
- toolCallId: intent.toolCallId,
- type: 'heterogeneous',
- },
- summary,
- surface: 'form',
- },
- ],
- summary,
- systemActionEligibility: 'review_only',
- userId: this.deps.userId,
- workspaceId: this.deps.workspaceId,
- };
- await notifyAgentInterventionRequired(notification);
- state.notifiedInterventionTransitions.add(pendingTransitionKey);
- }
-
- if (intent.transition !== 'pending') {
- await acknowledgeAgentInterventionProducerResolution({
- operationId: state.operationId,
- ownerUserId: this.deps.userId,
- resolutionRequestId: intent.resolutionRequestId,
- status: intent.transition,
- toolCallId: intent.toolCallId,
- workspaceId: this.deps.workspaceId,
- });
- }
- state.notifiedInterventionTransitions.add(transitionKey);
-
- // Cold-replica dedupe marker. Cloud's override must still use the same
- // `(operationId, toolCallId, transition)` idempotency key because a process
- // can die after the external side effect but before this best-effort stamp.
- await this.deps.messageModel.updatePluginState(toolMsgId, {
- [HETEROGENEOUS_INTERVENTION_STATE_KEY]: {
- ...durableState,
- notificationTransition: intent.transition,
- },
- });
- }
-
- private buildToolBatchUpdate(
- tools: Array<{ payload: ToolCallPayload; toolMessageId: string }>,
- options: { content?: string; reasoning?: string; withResult: boolean },
- ): Record<string, any> {
- const update: Record<string, any> = {
- tools: tools.map(({ payload, toolMessageId }) =>
- options.withResult ? { ...payload, result_msg_id: toolMessageId } : { ...payload },
- ),
- };
- if (options.content) update.content = options.content;
- if (options.reasoning) update.reasoning = { content: options.reasoning };
- return update;
- }
-
- /**
- * Persist an error supplied only by `heteroFinish` without rewriting streamed content.
- *
- * `heteroIngest` is the single writer for content and reasoning. A finish request can
- * reach a warm serverless replica whose accumulator predates a newer snapshot written
- * by another replica; replaying that accumulator here would roll the final answer back.
- */
- private async persistFinishError(
- state: OperationState,
- error: { body?: Record<string, unknown>; message: string; type: string },
- ) {
- const updateValue: Record<string, any> = {};
- const clearsEcho = error.body?.clearEchoedContent === true;
- // One read serves both decisions below.
- const persisted =
- clearsEcho || !isHeteroStatusGuideErrorData(error.body)
- ? await this.deps.messageModel.findById(state.main.currentAssistantId)
- : undefined;
- // `clearEchoedContent` marks an error the CLI may ALSO have printed into
- // the answer β€” it does not mean the answer is disposable. Quota rejections
- // carry the flag too, and a run that worked for ten minutes before its
- // weekly window closed must keep what it wrote, so only an exact echo is
- // dropped (same rule as the client and the coordinator reducer).
- if (clearsEcho && isEchoedErrorText(persisted?.content, errorEchoText(error))) {
- updateValue.content = '';
- }
- // Same canonical normalization as the in-stream `setError` path β€” the CLI's
- // free-form `{ message, type }` runs through formatErrorForState so the
- // finish-only write and the in-stream write produce one classified error shape.
- // A structured `body` (status-guide error: agentType + code) passes
- // through untouched β€” the client's guide UI gates on it.
- //
- // Never DOWNGRADE, though: the in-stream `setError` path may already have
- // persisted the adapter's classified status-guide error on this assistant,
- // while older CLIs flatten the finish error to a bare `{ message }`.
- // Overwriting would demote the client from the dedicated guide card to
- // the generic error alert β€” keep the richer persisted error instead.
- const overwritesGuideError =
- !isHeteroStatusGuideErrorData(error.body) &&
- isHeteroStatusGuideErrorData(persisted?.error?.body);
- if (!overwritesGuideError) updateValue.error = formatErrorForState(error);
-
- if (Object.keys(updateValue).length > 0) {
- await this.deps.messageModel.update(state.main.currentAssistantId, updateValue);
- }
- }
-
- /**
- * Write accumulated content/reasoning to DB after every ingest batch.
- * This ensures a subsequent replica always finds the latest text in the DB
- * even if the current replica never processes a step-boundary or terminal
- * event (which are the normal flush triggers).
- */
- private async flushBatchContent(state: OperationState): Promise<void> {
- if (!state.main.accContent && !state.main.accReasoning) return;
- const update: Record<string, any> = {};
- if (state.main.accContent) update.content = state.main.accContent;
- if (state.main.accReasoning) update.reasoning = { content: state.main.accReasoning };
- if (Object.keys(state.main.turnMetadata).length > 0) update.metadata = state.main.turnMetadata;
- await this.deps.messageModel.update(state.main.currentAssistantId, update);
- }
-
- private async applySubagentIntent(state: OperationState, intent: SubagentIntent) {
- switch (intent.kind) {
- case 'createThread': {
- await this.deps.threadModel.create({
- id: intent.threadId,
- metadata: {
- // Stamp the owning hetero operation so `refreshSubagentRunsFromDb`
- // only rehydrates threads from THIS run β€” never a stale Processing
- // thread a prior crashed/cancelled run left on the same topic.
- operationId: state.operationId,
- sourceToolCallId: intent.sourceToolCallId,
- startedAt: new Date().toISOString(),
- subagentType: intent.subagentType,
- },
- sourceMessageId: intent.sourceMessageId,
- status: ThreadStatus.Processing,
- title: intent.title,
- topicId: intent.topicId ?? state.topicId,
- type: ThreadType.Isolation,
- } as any);
- return;
- }
-
- case 'createMessage': {
- const subMetadata: Record<string, any> = {
- ...heteroProvenance(state, intent.subagentMessageId),
- };
- // Persist the turn's CC message.id so a cold replica can recover
- // `currentSubagentMessageId` (via buildSubagentSnapshot) and avoid
- // a spurious turn boundary that fragments one CC turn into multiple
- // in-thread assistant rows + empty shells.
- if (intent.subagentMessageId) subMetadata.subagentMessageId = intent.subagentMessageId;
- await this.deps.messageModel.create(
- {
- agentId: intent.agentId ?? undefined,
- content: intent.content,
- ...(Object.keys(subMetadata).length > 0 ? { metadata: subMetadata } : {}),
- parentId: intent.parentId,
- role: intent.role,
- threadId: intent.threadId,
- topicId: intent.topicId ?? state.topicId,
- } as any,
- intent.messageId,
- );
- return;
- }
-
- // Live in-memory UI updates have no server surface; durable writes land
- // via persistContent / persistToolBatch.
- case 'streamContent': {
- return;
- }
-
- case 'resolveToolResult': {
- await this.applyToolResult(state, intent);
- return;
- }
-
- case 'updateToolState': {
- await this.applyToolState(state, intent);
- return;
- }
-
- case 'persistContent': {
- const update: Record<string, any> = {};
- if (intent.content) update.content = intent.content;
- if (intent.reasoning) update.reasoning = { content: intent.reasoning };
- if (Object.keys(update).length > 0) {
- await this.deps.messageModel.update(intent.messageId, update);
- }
- return;
- }
-
- case 'persistToolBatch': {
- const buildUpdate = (withResult: boolean) =>
- this.buildToolBatchUpdate(intent.tools, {
- content: intent.content,
- reasoning: intent.reasoning,
- withResult,
- });
-
- // Phase 1: pre-register assistant.tools[] (no result_msg_id yet).
- await this.deps.messageModel.update(intent.assistantMessageId, buildUpdate(false));
-
- // Phase 2: create rows for new tools with their pre-allocated ids and
- // register them in the global tool-message map for tool_result lookup.
- for (const t of intent.tools) {
- if (!t.isNew) continue;
- const subToolMetadata = heteroProvenance(state, intent.subagentMessageId);
- await this.deps.messageModel.create(
- {
- agentId: state.agentId ?? undefined,
- content: '',
- ...(Object.keys(subToolMetadata).length > 0 ? { metadata: subToolMetadata } : {}),
- parentId: intent.assistantMessageId,
- plugin: {
- apiName: t.payload.apiName,
- arguments: t.payload.arguments,
- identifier: t.payload.identifier,
- type: t.payload.type,
- },
- role: 'tool',
- threadId: intent.threadId,
- tool_call_id: t.payload.id,
- topicId: state.topicId,
- } as any,
- t.toolMessageId,
- );
- state.toolMsgIdByCallId.set(t.payload.id, t.toolMessageId);
- }
-
- // Phase 3: backfill result_msg_id on assistant.tools[].
- await this.deps.messageModel.update(intent.assistantMessageId, buildUpdate(true));
- return;
- }
-
- case 'recordUsage': {
- await this.deps.messageModel.update(intent.messageId, {
- // Wholesale metadata overwrite β€” re-stamp the session + message
- // provenance the createMessage write put there, or usage would wipe it.
- metadata: {
- ...heteroProvenance(state, intent.subagentMessageId),
- usage: intent.usage as any,
- },
- ...(intent.model && { model: intent.model }),
- ...(intent.provider && { provider: intent.provider }),
- });
- return;
- }
-
- case 'finalizeThread': {
- await this.deps.threadModel.update(intent.threadId, { status: ThreadStatus.Active });
- return;
- }
- }
- }
-}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
new file mode 100644
index 00000000000..6f3e886bfdc
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
@@ -0,0 +1,385 @@
+import type {
+ MainAgentIntent,
+ SubagentIntent,
+ ToolCallPayload,
+} from '@lobechat/heterogeneous-agents';
+import { ThreadStatus, ThreadType } from '@lobechat/types';
+import debug from 'debug';
+
+import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
+
+import { heteroProvenance } from '../heteroProvenance';
+import { applyToolIntervention } from './intervention';
+import type { HeterogeneousPersistenceHandlerDeps, OperationState } from './types';
+
+const log = debug('lobe-server:hetero-agent:persistence');
+
+export async function applyMainIntent(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+ intent: MainAgentIntent,
+ stepIndex: number,
+) {
+ switch (intent.kind) {
+ case 'createAssistant': {
+ const createMetadata: Record<string, any> = {
+ ...heteroProvenance(state, intent.mainMessageId),
+ };
+ if (intent.signal) createMetadata.signal = intent.signal;
+ // Persist the turn's CC message.id so a cold replica can recover
+ // `currentMainMessageId` (via refreshMainStateFromDb) and dedupe a
+ // replayed `newStep` instead of forking a duplicate + empty shell.
+ if (intent.mainMessageId) createMetadata.mainMessageId = intent.mainMessageId;
+ await deps.messageModel.create(
+ {
+ agentId: intent.agentId ?? undefined,
+ content: '',
+ ...(Object.keys(createMetadata).length > 0 ? { metadata: createMetadata } : {}),
+ model: intent.model,
+ parentId: intent.parentId,
+ provider: intent.provider,
+ role: 'assistant',
+ threadId: state.threadId,
+ topicId: intent.topicId ?? state.topicId,
+ } as any,
+ intent.messageId,
+ );
+
+ if (deps.topicModel.updateRunningOperationAssistantMessage) {
+ await deps.topicModel.updateRunningOperationAssistantMessage(
+ state.topicId,
+ state.operationId,
+ intent.messageId,
+ );
+ } else {
+ await deps.topicModel.updateMetadata(state.topicId, {
+ heteroCurrentMsgId: { msgId: intent.messageId, operationId: state.operationId },
+ });
+ }
+ return;
+ }
+
+ case 'persistAssistant': {
+ const update: Record<string, any> = {};
+ if (intent.content !== undefined) update.content = intent.content;
+ if (intent.reasoning !== undefined) update.reasoning = { content: intent.reasoning };
+ if (intent.model) update.model = intent.model;
+ if (intent.provider) update.provider = intent.provider;
+ if (intent.metadata) update.metadata = intent.metadata;
+ if (Object.keys(update).length > 0) {
+ await deps.messageModel.update(intent.messageId, update);
+ }
+ return;
+ }
+
+ // Token-level live updates are renderer-only. The server persists durable
+ // snapshots via persistAssistant / persistToolBatch / flushBatchContent.
+ case 'streamContent': {
+ return;
+ }
+
+ case 'persistToolBatch': {
+ const buildUpdate = (withResult: boolean) =>
+ buildToolBatchUpdate(intent.tools, {
+ content: intent.content,
+ reasoning: intent.reasoning,
+ withResult,
+ });
+
+ // Phase 1: assistant.tools[] without result_msg_id.
+ await deps.messageModel.update(intent.assistantMessageId, buildUpdate(false));
+
+ // Phase 2: create new tool rows with reducer-preallocated ids.
+ for (const tool of intent.tools) {
+ if (!tool.isNew) continue;
+ const toolMetadata = heteroProvenance(state, state.main.currentMainMessageId);
+ await deps.messageModel.create(
+ {
+ agentId: state.agentId ?? undefined,
+ content: '',
+ ...(Object.keys(toolMetadata).length > 0 ? { metadata: toolMetadata } : {}),
+ parentId: intent.assistantMessageId,
+ plugin: {
+ apiName: tool.payload.apiName,
+ arguments: tool.payload.arguments,
+ identifier: tool.payload.identifier,
+ type: tool.payload.type,
+ },
+ role: 'tool',
+ threadId: state.threadId,
+ tool_call_id: tool.payload.id,
+ topicId: state.topicId,
+ } as any,
+ tool.toolMessageId,
+ );
+ state.toolMsgIdByCallId.set(tool.payload.id, tool.toolMessageId);
+ }
+
+ // Phase 3: backfill result_msg_id.
+ await deps.messageModel.update(intent.assistantMessageId, buildUpdate(true));
+ return;
+ }
+
+ case 'resolveToolResult': {
+ await applyToolResult(deps, state, intent);
+ return;
+ }
+
+ case 'updateToolState': {
+ await applyToolState(deps, state, intent);
+ return;
+ }
+
+ case 'setToolIntervention': {
+ await applyToolIntervention(deps, state, intent, stepIndex);
+ return;
+ }
+
+ case 'recordUsage': {
+ const update: Record<string, any> = {};
+ if (intent.usage !== undefined) {
+ // This overwrites the row's metadata wholesale, so re-stamp the
+ // provenance the createAssistant write put there, or usage would wipe it.
+ update.metadata = {
+ ...state.main.turnMetadata,
+ ...heteroProvenance(state, state.main.currentMainMessageId),
+ usage: intent.usage,
+ };
+ }
+ if (intent.model) update.model = intent.model;
+ if (intent.provider) update.provider = intent.provider;
+ if (Object.keys(update).length > 0) {
+ await deps.messageModel.update(intent.messageId, update);
+ }
+ return;
+ }
+
+ case 'setError': {
+ // Normalize the CLI agent's wire error data through the SAME canonical
+ // formatter the in-process runtime uses, so a hetero error is classified
+ // (attribution/category/retryable) identically and the renderer never sees
+ // a second, hetero-only error shape.
+ const update: Record<string, any> = { error: formatErrorForState(intent.errorData) };
+ if (intent.clearContent) update.content = '';
+ await deps.messageModel.update(intent.messageId, update);
+ return;
+ }
+ }
+}
+
+async function applyToolResult(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+ intent: {
+ content: string;
+ isError: boolean;
+ pluginState?: Record<string, any>;
+ toolCallId: string;
+ },
+) {
+ const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) {
+ log('tool_result for unknown toolCallId=%s op=%s', intent.toolCallId, state.operationId);
+ return;
+ }
+
+ const result = await deps.messageModel.updateToolMessage(toolMsgId, {
+ content: intent.content,
+ pluginError: intent.isError ? { message: intent.content } : undefined,
+ pluginState: intent.pluginState,
+ });
+ if (!result.success) {
+ throw new Error(`Failed to persist tool_result for message ${toolMsgId}`);
+ }
+}
+
+async function applyToolState(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+ intent: {
+ pluginState: Record<string, unknown>;
+ snapshotSeq: number;
+ toolCallId: string;
+ },
+): Promise<void> {
+ const lastApplied = state.lastAppliedToolStateSeqByCallId.get(intent.toolCallId) ?? 0;
+ if (intent.snapshotSeq <= lastApplied) return;
+
+ const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) {
+ throw new Error(
+ `tool_state for unknown toolCallId=${intent.toolCallId} op=${state.operationId}`,
+ );
+ }
+
+ const result = await deps.messageModel.updateToolMessage(toolMsgId, {
+ heterogeneousToolState: {
+ operationId: state.operationId,
+ snapshotSeq: intent.snapshotSeq,
+ },
+ pluginState: intent.pluginState,
+ });
+ if (!result.success) {
+ throw new Error(`Failed to persist tool_state for message ${toolMsgId}`);
+ }
+
+ state.lastAppliedToolStateSeqByCallId.set(
+ intent.toolCallId,
+ result.snapshotSeq ?? intent.snapshotSeq,
+ );
+}
+
+function buildToolBatchUpdate(
+ tools: Array<{ payload: ToolCallPayload; toolMessageId: string }>,
+ options: { content?: string; reasoning?: string; withResult: boolean },
+): Record<string, any> {
+ const update: Record<string, any> = {
+ tools: tools.map(({ payload, toolMessageId }) =>
+ options.withResult ? { ...payload, result_msg_id: toolMessageId } : { ...payload },
+ ),
+ };
+ if (options.content) update.content = options.content;
+ if (options.reasoning) update.reasoning = { content: options.reasoning };
+ return update;
+}
+
+export async function applySubagentIntent(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+ intent: SubagentIntent,
+) {
+ switch (intent.kind) {
+ case 'createThread': {
+ await deps.threadModel.create({
+ id: intent.threadId,
+ metadata: {
+ // Stamp the owning hetero operation so `refreshSubagentRunsFromDb`
+ // only rehydrates threads from THIS run β€” never a stale Processing
+ // thread a prior crashed/cancelled run left on the same topic.
+ operationId: state.operationId,
+ sourceToolCallId: intent.sourceToolCallId,
+ startedAt: new Date().toISOString(),
+ subagentType: intent.subagentType,
+ },
+ sourceMessageId: intent.sourceMessageId,
+ status: ThreadStatus.Processing,
+ title: intent.title,
+ topicId: intent.topicId ?? state.topicId,
+ type: ThreadType.Isolation,
+ } as any);
+ return;
+ }
+
+ case 'createMessage': {
+ const subMetadata: Record<string, any> = {
+ ...heteroProvenance(state, intent.subagentMessageId),
+ };
+ // Persist the turn's CC message.id so a cold replica can recover
+ // `currentSubagentMessageId` (via buildSubagentSnapshot) and avoid
+ // a spurious turn boundary that fragments one CC turn into multiple
+ // in-thread assistant rows + empty shells.
+ if (intent.subagentMessageId) subMetadata.subagentMessageId = intent.subagentMessageId;
+ await deps.messageModel.create(
+ {
+ agentId: intent.agentId ?? undefined,
+ content: intent.content,
+ ...(Object.keys(subMetadata).length > 0 ? { metadata: subMetadata } : {}),
+ parentId: intent.parentId,
+ role: intent.role,
+ threadId: intent.threadId,
+ topicId: intent.topicId ?? state.topicId,
+ } as any,
+ intent.messageId,
+ );
+ return;
+ }
+
+ // Live in-memory UI updates have no server surface; durable writes land
+ // via persistContent / persistToolBatch.
+ case 'streamContent': {
+ return;
+ }
+
+ case 'resolveToolResult': {
+ await applyToolResult(deps, state, intent);
+ return;
+ }
+
+ case 'updateToolState': {
+ await applyToolState(deps, state, intent);
+ return;
+ }
+
+ case 'persistContent': {
+ const update: Record<string, any> = {};
+ if (intent.content) update.content = intent.content;
+ if (intent.reasoning) update.reasoning = { content: intent.reasoning };
+ if (Object.keys(update).length > 0) {
+ await deps.messageModel.update(intent.messageId, update);
+ }
+ return;
+ }
+
+ case 'persistToolBatch': {
+ const buildUpdate = (withResult: boolean) =>
+ buildToolBatchUpdate(intent.tools, {
+ content: intent.content,
+ reasoning: intent.reasoning,
+ withResult,
+ });
+
+ // Phase 1: pre-register assistant.tools[] (no result_msg_id yet).
+ await deps.messageModel.update(intent.assistantMessageId, buildUpdate(false));
+
+ // Phase 2: create rows for new tools with their pre-allocated ids and
+ // register them in the global tool-message map for tool_result lookup.
+ for (const t of intent.tools) {
+ if (!t.isNew) continue;
+ const subToolMetadata = heteroProvenance(state, intent.subagentMessageId);
+ await deps.messageModel.create(
+ {
+ agentId: state.agentId ?? undefined,
+ content: '',
+ ...(Object.keys(subToolMetadata).length > 0 ? { metadata: subToolMetadata } : {}),
+ parentId: intent.assistantMessageId,
+ plugin: {
+ apiName: t.payload.apiName,
+ arguments: t.payload.arguments,
+ identifier: t.payload.identifier,
+ type: t.payload.type,
+ },
+ role: 'tool',
+ threadId: intent.threadId,
+ tool_call_id: t.payload.id,
+ topicId: state.topicId,
+ } as any,
+ t.toolMessageId,
+ );
+ state.toolMsgIdByCallId.set(t.payload.id, t.toolMessageId);
+ }
+
+ // Phase 3: backfill result_msg_id on assistant.tools[].
+ await deps.messageModel.update(intent.assistantMessageId, buildUpdate(true));
+ return;
+ }
+
+ case 'recordUsage': {
+ await deps.messageModel.update(intent.messageId, {
+ // Wholesale metadata overwrite β€” re-stamp the session + message
+ // provenance the createMessage write put there, or usage would wipe it.
+ metadata: {
+ ...heteroProvenance(state, intent.subagentMessageId),
+ usage: intent.usage as any,
+ },
+ ...(intent.model && { model: intent.model }),
+ ...(intent.provider && { provider: intent.provider }),
+ });
+ return;
+ }
+
+ case 'finalizeThread': {
+ await deps.threadModel.update(intent.threadId, { status: ThreadStatus.Active });
+ return;
+ }
+ }
+}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.ts
new file mode 100644
index 00000000000..2277feda50f
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.ts
@@ -0,0 +1,220 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { vi } from 'vitest';
+
+import { HeterogeneousPersistenceHandler } from '.';
+
+interface FakeMessage {
+ agentId: string | null;
+ content: string;
+ error?: any;
+ id: string;
+ metadata?: any;
+ model?: string;
+ parentId?: string | null;
+ plugin?: any;
+ pluginError?: any;
+ pluginState?: any;
+ provider?: string;
+ reasoning?: any;
+ role: 'assistant' | 'user' | 'tool' | 'task' | 'system';
+ threadId?: string | null;
+ tool_call_id?: string;
+ tools?: any[];
+ topicId: string | null;
+}
+
+interface FakeThread {
+ id: string;
+ metadata?: any;
+ sourceMessageId?: string | null;
+ status: string;
+ title: string;
+ topicId: string;
+ type: string;
+}
+
+export const createHarness = (
+ params: {
+ assistantMessageId?: string;
+ operationId?: string;
+ topicAgentId?: string | null;
+ topicId?: string;
+ userId?: string | null;
+ } = {},
+) => {
+ const operationId = params.operationId ?? 'op-test';
+ const topicId = params.topicId ?? 'topic-test';
+ const assistantMessageId = params.assistantMessageId ?? 'asst-seeded';
+ const topicAgentId = params.topicAgentId ?? null;
+
+ let nextSeq = 0;
+ const messages = new Map<string, FakeMessage>();
+ const threads = new Map<string, FakeThread>();
+
+ messages.set(assistantMessageId, {
+ agentId: topicAgentId,
+ content: '',
+ id: assistantMessageId,
+ role: 'assistant',
+ topicId,
+ });
+
+ const messageModel = {
+ create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {
+ nextSeq += 1;
+ const msgId = id ?? `msg_${nextSeq}`;
+ const msg: FakeMessage = {
+ agentId: input.agentId ?? null,
+ content: input.content ?? '',
+ id: msgId,
+ metadata: input.metadata,
+ model: input.model,
+ parentId: input.parentId ?? null,
+ plugin: input.plugin,
+ provider: input.provider,
+ role: input.role!,
+ threadId: input.threadId ?? null,
+ tool_call_id: input.tool_call_id,
+ topicId: input.topicId ?? null,
+ };
+ messages.set(msgId, msg);
+ return msg;
+ }),
+ update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ messages.set(id, { ...existing, ...patch });
+ return { success: true };
+ }),
+ updateToolMessage: vi.fn(
+ async (
+ id: string,
+ patch: {
+ content?: string;
+ heterogeneousToolState?: { operationId: string; snapshotSeq: number };
+ metadata?: any;
+ pluginError?: any;
+ pluginState?: any;
+ },
+ ) => {
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ const snapshot = patch.heterogeneousToolState;
+ const currentSeq =
+ snapshot && existing.metadata?.heterogeneousToolStateOperationId === snapshot.operationId
+ ? (existing.metadata.heterogeneousToolStateSeq ?? 0)
+ : 0;
+ if (snapshot && snapshot.snapshotSeq <= currentSeq) {
+ return { applied: false, snapshotSeq: currentSeq, success: true };
+ }
+ messages.set(id, {
+ ...existing,
+ content: patch.content ?? existing.content,
+ metadata: snapshot
+ ? {
+ ...existing.metadata,
+ ...patch.metadata,
+ heterogeneousToolStateOperationId: snapshot.operationId,
+ heterogeneousToolStateSeq: snapshot.snapshotSeq,
+ }
+ : (patch.metadata ?? existing.metadata),
+ pluginError: patch.pluginError,
+ pluginState: patch.pluginState ?? existing.pluginState,
+ });
+ return {
+ applied: true,
+ snapshotSeq: snapshot?.snapshotSeq,
+ success: true,
+ };
+ },
+ ),
+ findById: vi.fn(async (id: string) => messages.get(id) ?? null),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (m) =>
+ m.topicId === topicId &&
+ m.role !== 'tool' &&
+ m.threadId === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
+ listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
+ updateMessagePlugin: vi.fn(async (id: string, patch: Record<string, unknown>) => {
+ const existing = messages.get(id);
+ if (existing) messages.set(id, { ...existing, plugin: { ...existing.plugin, ...patch } });
+ }),
+ updatePluginState: vi.fn(async (id: string, patch: Record<string, unknown>) => {
+ const existing = messages.get(id);
+ if (existing) {
+ messages.set(id, { ...existing, pluginState: { ...existing.pluginState, ...patch } });
+ }
+ }),
+ };
+
+ const threadModel = {
+ create: vi.fn(async (input: Partial<FakeThread>) => {
+ const thread: FakeThread = {
+ id: input.id!,
+ metadata: input.metadata,
+ sourceMessageId: input.sourceMessageId,
+ status: input.status ?? 'active',
+ title: input.title ?? '',
+ topicId: input.topicId ?? topicId,
+ type: input.type ?? 'isolation',
+ };
+ threads.set(thread.id, thread);
+ return thread;
+ }),
+ update: vi.fn(async (id: string, patch: Partial<FakeThread>) => {
+ const existing = threads.get(id);
+ if (existing) threads.set(id, { ...existing, ...patch });
+ }),
+ };
+
+ const topicModel = {
+ findById: vi.fn(async () => ({
+ agentId: topicAgentId,
+ id: topicId,
+ metadata: { runningOperation: { assistantMessageId, operationId } },
+ })),
+ updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
+ };
+
+ const handler = new HeterogeneousPersistenceHandler({
+ messageModel: messageModel as any,
+ threadModel: threadModel as any,
+ topicModel: topicModel as any,
+ userId: params.userId === null ? undefined : (params.userId ?? 'user-test'),
+ });
+
+ return {
+ assistantMessageId,
+ handler,
+ messageModel,
+ messages,
+ operationId,
+ threadModel,
+ threads,
+ topicId,
+ topicModel,
+ };
+};
+
+export const buildEvent = (
+ type: AgentStreamEvent['type'],
+ stepIndex: number,
+ data: Record<string, unknown>,
+ timestamp = 1_700_000_000_000 + stepIndex,
+): AgentStreamEvent => ({
+ data,
+ operationId: 'op-test',
+ stepIndex,
+ timestamp,
+ type,
+});
+
+export const ingest = async (h: ReturnType<typeof createHarness>, events: AgentStreamEvent[]) =>
+ h.handler.ingest({ events, operationId: h.operationId, topicId: h.topicId });
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.codexTurnProvenance.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.ts
similarity index 97%
rename from apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.codexTurnProvenance.test.ts
rename to apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.ts
index 80e57869876..48bbd05c67d 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.codexTurnProvenance.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.ts
@@ -1,10 +1,7 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
+import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } from '.';
interface FakeMessage {
agentId: string | null;
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
similarity index 98%
rename from apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
rename to apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
index 3bd940d7e04..44aa76c0794 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
@@ -2,10 +2,7 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
+import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } from '.';
/**
* Regression for the remote-device chain-fork (observed on tpc_3DKmFfAmx9YA):
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.ts
new file mode 100644
index 00000000000..fb250ea37aa
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.ts
@@ -0,0 +1,432 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness, ingest } from './eventBranchesTestUtils';
+
+const { acknowledgeAgentInterventionProducerResolution, notifyAgentInterventionRequired } =
+ vi.hoisted(() => ({
+ acknowledgeAgentInterventionProducerResolution: vi.fn(),
+ notifyAgentInterventionRequired: vi.fn(),
+ }));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({
+ acknowledgeAgentInterventionProducerResolution,
+ notifyAgentInterventionRequired,
+}));
+
+/**
+ * Branch-coverage tests against every event type / sub-type the renderer
+ * (`heterogeneousAgentExecutor.ts:1314–1632`) dispatches on. Each describe
+ * block names the event variant; each `it` covers one observable behavior
+ * the renderer encodes for that variant. See `cc-stream-chain-reference.md`
+ * for the source-of-truth table the renderer is keyed off of.
+ *
+ * Sibling specs:
+ * - `index.test.ts`, `index.stepBoundaries.test.ts`, `index.terminal.test.ts`,
+ * `index.replicaState.test.ts`: state bootstrap + idempotency + 3-phase
+ * persist + subagent lifecycle (the structural contract).
+ * - `index.eventBranchesLifecycle.test.ts`, `index.interventionAck.test.ts`:
+ * the remaining event variants of this suite.
+ * - `index.fixture.test.ts`: end-to-end replay
+ * of a real CC trace.
+ */
+
+describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ acknowledgeAgentInterventionProducerResolution.mockReset();
+ notifyAgentInterventionRequired.mockReset();
+ });
+ afterEach(() => __resetOperationStatesForTesting());
+
+ // ─── step_complete ────────────────────────────────────────────────────────
+
+ describe('step_complete', () => {
+ it('phase=turn_metadata with usage writes assistant.metadata.usage and caches model/provider', async () => {
+ const h = createHarness();
+ const usage = { totalInputTokens: 100, totalOutputTokens: 50, totalTokens: 150 };
+
+ await ingest(h, [
+ buildEvent('step_complete', 0, {
+ model: 'claude-opus-4-7',
+ phase: 'turn_metadata',
+ provider: 'claude-code',
+ usage,
+ }),
+ ]);
+
+ expect(h.messageModel.update).toHaveBeenCalledWith(
+ h.assistantMessageId,
+ expect.objectContaining({ metadata: { usage } }),
+ );
+ });
+
+ it('phase=turn_metadata WITHOUT usage only caches model/provider for the next step', async () => {
+ const h = createHarness();
+
+ // turn_metadata with no usage β†’ no DB write yet, but lastModel/lastProvider
+ // should propagate to the NEXT step's create assistant call.
+ await ingest(h, [
+ buildEvent('step_complete', 0, {
+ model: 'claude-opus-4-7',
+ phase: 'turn_metadata',
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_start', 1, { newStep: true }),
+ ]);
+
+ // First update would be the prev-step flush of nothing β€” no model/provider
+ // because pre-cache occurred AFTER turn_metadata. But the new assistant
+ // create should carry both.
+ const newAssistantCall = h.messageModel.create.mock.calls.find(
+ (call) => call[0]?.role === 'assistant',
+ );
+ expect(newAssistantCall?.[0]).toMatchObject({
+ model: 'claude-opus-4-7',
+ provider: 'claude-code',
+ });
+ });
+
+ it('phase=result_usage is ignored (renderer line 1399–1402: would clobber per-step usage)', async () => {
+ const h = createHarness();
+
+ await ingest(h, [
+ buildEvent('step_complete', 0, {
+ phase: 'result_usage',
+ usage: { totalInputTokens: 9999 },
+ }),
+ ]);
+
+ // No update on assistant for result_usage
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ });
+
+ it('unknown phase is dropped silently', async () => {
+ const h = createHarness();
+ await ingest(h, [buildEvent('step_complete', 0, { phase: 'something_new' })]);
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ });
+ });
+
+ // ─── stream_start ─────────────────────────────────────────────────────────
+
+ describe('stream_start', () => {
+ it('without newStep (CLI init) backfills the placeholder with the CLI model/provider', async () => {
+ const h = createHarness();
+ const beforeCreates = h.messageModel.create.mock.calls.length;
+
+ await ingest(h, [
+ buildEvent('stream_start', 0, {
+ model: 'claude-sonnet-4-5',
+ provider: 'claude-code',
+ }),
+ ]);
+
+ // The init event carries the CLI's authoritative model/provider β€” it must
+ // backfill the placeholder (which was created with only `provider`, no
+ // model) so the model tag shows the real CLI model from the first turn,
+ // even without any usage-bearing turn_metadata.
+ const asst = h.messages.get(h.assistantMessageId);
+ expect(asst?.model).toBe('claude-sonnet-4-5');
+ expect(asst?.provider).toBe('claude-code');
+ // No new assistant row is created β€” only the placeholder is patched.
+ expect(h.messageModel.create.mock.calls.length).toBe(beforeCreates);
+ });
+
+ it('without newStep and no model/provider is a no-op', async () => {
+ const h = createHarness();
+ const beforeUpdates = h.messageModel.update.mock.calls.length;
+ const beforeCreates = h.messageModel.create.mock.calls.length;
+
+ await ingest(h, [buildEvent('stream_start', 0, {})]);
+
+ expect(h.messageModel.update.mock.calls.length).toBe(beforeUpdates);
+ expect(h.messageModel.create.mock.calls.length).toBe(beforeCreates);
+ });
+
+ it('with newStep but no prior tools chains the new assistant off the previous assistant', async () => {
+ const h = createHarness();
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'plain step' }),
+ buildEvent('stream_start', 1, { newStep: true }),
+ ]);
+
+ const newAsst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== h.assistantMessageId,
+ );
+ // No tool messages β†’ falls back to prev assistant id
+ expect(newAsst?.parentId).toBe(h.assistantMessageId);
+ });
+ });
+
+ // ─── stream_chunk ─────────────────────────────────────────────────────────
+
+ describe('stream_chunk', () => {
+ it('main-side text accumulates without writing to DB until step boundary', async () => {
+ const h = createHarness();
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hi ' }),
+ buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'there' }),
+ ]);
+
+ // Text is flushed to DB at end of each batch (multi-replica fix)
+ expect(h.messageModel.update).toHaveBeenCalledWith(h.assistantMessageId, {
+ content: 'hi there',
+ });
+ });
+
+ it('main-side reasoning accumulates separately from text', async () => {
+ const h = createHarness();
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, { chunkType: 'reasoning', reasoning: 'thinking ' }),
+ buildEvent('stream_chunk', 1, { chunkType: 'reasoning', reasoning: 'more' }),
+ buildEvent('agent_runtime_end', 2, { reason: 'success' }),
+ ]);
+
+ const asst = h.messages.get(h.assistantMessageId)!;
+ expect(asst.reasoning).toEqual({ content: 'thinking more' });
+ });
+
+ it('subagent-tagged text routes to the run accumulator, NOT the main one', async () => {
+ const h = createHarness();
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ };
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'subagent thought',
+ subagent: subagentCtx,
+ }),
+ buildEvent('agent_runtime_end', 1, { reason: 'success' }),
+ ]);
+
+ const main = h.messages.get(h.assistantMessageId)!;
+ expect(main.content).toBe(''); // Main untouched
+
+ const threadId = [...h.threads.keys()][0];
+ const subAssts = [...h.messages.values()].filter(
+ (m) => m.threadId === threadId && m.role === 'assistant',
+ );
+ // After agent_runtime_end β†’ finalize without resultContent β†’ flush
+ // accumulated content onto the in-thread assistant
+ expect(subAssts.some((m) => m.content === 'subagent thought')).toBe(true);
+ });
+
+ it('subagent-tagged reasoning routes to the run reasoning accumulator', async () => {
+ const h = createHarness();
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ };
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'reasoning',
+ reasoning: 'subagent thinks hard',
+ subagent: subagentCtx,
+ }),
+ buildEvent('agent_runtime_end', 1, { reason: 'success' }),
+ ]);
+
+ const threadId = [...h.threads.keys()][0];
+ const flushed = [...h.messages.values()].find(
+ (m) =>
+ m.threadId === threadId &&
+ m.role === 'assistant' &&
+ m.reasoning?.content === 'subagent thinks hard',
+ );
+ expect(flushed).toBeDefined();
+ });
+
+ it('persists tool_state DB-first and drops stale in-operation snapshots', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'todo_list',
+ arguments: '{}',
+ id: 'todo-1',
+ identifier: 'codex',
+ type: 'default',
+ },
+ ],
+ }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'tool_state',
+ pluginState: { todos: { items: [{ status: 'processing', text: 'Implement' }] } },
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ toolCallId: 'todo-1',
+ }),
+ buildEvent('stream_chunk', 2, {
+ chunkType: 'tool_state',
+ pluginState: { stale: true },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'todo-1',
+ }),
+ ]);
+
+ const stateWrites = h.messageModel.updateToolMessage.mock.calls.filter(
+ ([, patch]) => patch.heterogeneousToolState,
+ );
+ expect(stateWrites).toHaveLength(1);
+ expect(stateWrites[0][1]).toMatchObject({
+ heterogeneousToolState: { operationId: h.operationId, snapshotSeq: 2 },
+ pluginState: {
+ todos: { items: [{ status: 'processing', text: 'Implement' }] },
+ },
+ });
+ const toolMessage = [...h.messages.values()].find(
+ (message) => message.tool_call_id === 'todo-1',
+ );
+ expect(toolMessage?.metadata).toMatchObject({
+ heterogeneousToolStateOperationId: h.operationId,
+ heterogeneousToolStateSeq: 2,
+ });
+ expect(toolMessage?.pluginState).not.toEqual({ stale: true });
+ });
+
+ it('restores the tool-state watermark from DB after a cold operation-state reset', async () => {
+ const h = createHarness();
+ h.messages.set('tool-existing', {
+ agentId: null,
+ content: '',
+ id: 'tool-existing',
+ metadata: {
+ heterogeneousToolStateOperationId: h.operationId,
+ heterogeneousToolStateSeq: 4,
+ },
+ pluginState: { current: true },
+ role: 'tool',
+ tool_call_id: 'todo-existing',
+ topicId: h.topicId,
+ });
+ h.messageModel.listMessagePluginsByTopic.mockResolvedValue([
+ {
+ id: 'tool-existing',
+ metadata: h.messages.get('tool-existing')?.metadata,
+ toolCallId: 'todo-existing',
+ },
+ ] as any);
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tool_state',
+ pluginState: { stale: true },
+ snapshotMode: 'replace',
+ snapshotSeq: 3,
+ toolCallId: 'todo-existing',
+ }),
+ ]);
+
+ expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
+ expect(h.messages.get('tool-existing')?.pluginState).toEqual({ current: true });
+ });
+
+ it('tools_calling with empty array is a no-op', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [] }),
+ ]);
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ expect(h.messageModel.create).not.toHaveBeenCalled();
+ });
+
+ it('unknown chunkType is dropped silently', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, { chunkType: 'mystery_chunk', payload: 42 } as any),
+ ]);
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ expect(h.messageModel.create).not.toHaveBeenCalled();
+ });
+ });
+
+ // ─── tool_result ──────────────────────────────────────────────────────────
+
+ describe('tool_result', () => {
+ const buildToolFlow = (
+ h: ReturnType<typeof createHarness>,
+ toolResultData: Record<string, unknown>,
+ ) =>
+ ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'TodoWrite',
+ arguments: '{"todos":[]}',
+ id: 'tc-1',
+ identifier: 'todo-write',
+ type: 'default',
+ },
+ ],
+ }),
+ buildEvent('tool_result', 1, { ...toolResultData, toolCallId: 'tc-1' }),
+ ]);
+
+ it('writes content + pluginState (TodoWrite synth) atomically through updateToolMessage', async () => {
+ const h = createHarness();
+ const todos = [
+ { content: 'Read code', id: 't1', status: 'pending' },
+ { content: 'Write tests', id: 't2', status: 'in_progress' },
+ ];
+
+ await buildToolFlow(h, {
+ content: 'todos updated',
+ pluginState: { todos },
+ });
+
+ const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
+ expect(toolMsg?.content).toBe('todos updated');
+ expect(toolMsg?.pluginState).toEqual({ todos });
+ // Critical: the renderer's TodoWrite synth (adapter line 546–553) puts
+ // todos on `pluginState` β€” we transparently persist them through
+ // updateToolMessage, so selectTodosFromMessages reads them.
+ expect(h.messageModel.updateToolMessage).toHaveBeenCalledWith(
+ toolMsg?.id,
+ expect.objectContaining({ pluginState: { todos } }),
+ );
+ });
+
+ it('isError=true sets pluginError', async () => {
+ const h = createHarness();
+ await buildToolFlow(h, {
+ content: 'ENOENT no such file',
+ isError: true,
+ });
+
+ const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
+ expect(toolMsg?.pluginError).toEqual({ message: 'ENOENT no such file' });
+ });
+
+ it('unknown toolCallId logs and drops without throwing', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('tool_result', 0, {
+ content: 'orphan',
+ toolCallId: 'tc-never-seen',
+ }),
+ ]);
+ // Handler swallows unknown ids β€” no crash, no DB write
+ expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
+ });
+
+ it('tool_result without toolCallId is dropped (defensive)', async () => {
+ const h = createHarness();
+ await ingest(h, [buildEvent('tool_result', 0, { content: 'x' })]);
+ expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranchesLifecycle.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranchesLifecycle.test.ts
new file mode 100644
index 00000000000..3c818772bc6
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranchesLifecycle.test.ts
@@ -0,0 +1,328 @@
+// @vitest-environment node
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness, ingest } from './eventBranchesTestUtils';
+
+const { acknowledgeAgentInterventionProducerResolution, notifyAgentInterventionRequired } =
+ vi.hoisted(() => ({
+ acknowledgeAgentInterventionProducerResolution: vi.fn(),
+ notifyAgentInterventionRequired: vi.fn(),
+ }));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({
+ acknowledgeAgentInterventionProducerResolution,
+ notifyAgentInterventionRequired,
+}));
+
+describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ acknowledgeAgentInterventionProducerResolution.mockReset();
+ notifyAgentInterventionRequired.mockReset();
+ });
+ afterEach(() => __resetOperationStatesForTesting());
+
+ // ─── agent_runtime_end / error ────────────────────────────────────────────
+
+ describe('terminal events', () => {
+ it('agent_runtime_end flushes content + reasoning + model/provider', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('step_complete', 0, {
+ model: 'claude-opus-4-7',
+ phase: 'turn_metadata',
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'final text' }),
+ buildEvent('stream_chunk', 2, { chunkType: 'reasoning', reasoning: 'final reasoning' }),
+ buildEvent('agent_runtime_end', 3, { reason: 'success' }),
+ ]);
+
+ const asst = h.messages.get(h.assistantMessageId)!;
+ expect(asst.content).toBe('final text');
+ expect(asst.reasoning).toEqual({ content: 'final reasoning' });
+ expect(asst.model).toBe('claude-opus-4-7');
+ expect(asst.provider).toBe('claude-code');
+ });
+
+ it('error event writes a ChatMessageError onto the assistant', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('error', 0, {
+ message: 'connection timeout',
+ type: 'AgentRuntimeError',
+ }),
+ ]);
+ const asst = h.messages.get(h.assistantMessageId)!;
+ expect(asst.error).toMatchObject({
+ message: 'connection timeout',
+ type: 'AgentRuntimeError',
+ });
+ });
+
+ it('error with AuthRequired code + matching content suppresses the echoed content', async () => {
+ const h = createHarness();
+ // CC streams the auth error into the text stream BEFORE emitting the
+ // structured error. Without echo suppression, the assistant ends up
+ // with both the raw stderr AND the structured error β€” duplicates.
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'auth required - sign in again',
+ }),
+ buildEvent('error', 1, {
+ code: 'AuthRequired',
+ message: 'auth required - sign in again',
+ type: 'AgentRuntimeError',
+ }),
+ ]);
+ const asst = h.messages.get(h.assistantMessageId)!;
+ expect(asst.content).toBe('');
+ expect(asst.error).toBeDefined();
+ });
+
+ it('error with non-AuthRequired code preserves the streamed content', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'partial answer',
+ }),
+ buildEvent('error', 1, {
+ message: 'partial answer',
+ type: 'AgentRuntimeError',
+ }),
+ ]);
+ const asst = h.messages.get(h.assistantMessageId)!;
+ expect(asst.content).toBe('partial answer');
+ expect(asst.error).toBeDefined();
+ });
+
+ it('error with explicit clearEchoedContent flag suppresses echoed content', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'oops timeout',
+ }),
+ buildEvent('error', 1, {
+ clearEchoedContent: true,
+ message: 'oops timeout',
+ type: 'AgentRuntimeError',
+ }),
+ ]);
+ const asst = h.messages.get(h.assistantMessageId)!;
+ expect(asst.content).toBe('');
+ });
+
+ it('terminal event drains orphan subagent runs (no resultContent)', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'partial subagent thought',
+ subagent: {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ },
+ }),
+ // No tool_result for tc-spawn β€” CLI crashed mid-spawn
+ buildEvent('agent_runtime_end', 1, { reason: 'cancelled' }),
+ ]);
+
+ const threadId = [...h.threads.keys()][0];
+ // Orphan flush wrote the accumulated content onto the in-thread assistant
+ const flushed = [...h.messages.values()].find(
+ (m) =>
+ m.threadId === threadId &&
+ m.role === 'assistant' &&
+ m.content === 'partial subagent thought',
+ );
+ expect(flushed).toBeDefined();
+ // Subagent run cleaned up on terminal
+ expect([...h.threads.keys()]).toHaveLength(1);
+ });
+ });
+
+ // ─── No-op event types ────────────────────────────────────────────────────
+
+ describe('no-op event types', () => {
+ it.each([
+ ['tool_start', { parentMessageId: 'asst-seeded', toolCalling: { id: 'tc-1' } }],
+ ['tool_end', { isSuccess: true, toolCallId: 'tc-1' }],
+ ['stream_end', {}],
+ ['agent_runtime_init', { state: 'idle' }],
+ ['step_complete', { phase: 'operation_heartbeat' }],
+ ['tool_execute', { apiName: 'Read', toolCallId: 'tc-1' }],
+ ['stream_retry', { attempt: 1 }],
+ ])('drops %s without DB writes', async (type, data) => {
+ const h = createHarness();
+ const beforeCreates = h.messageModel.create.mock.calls.length;
+ const beforeUpdates = h.messageModel.update.mock.calls.length;
+ const beforeToolUpdates = h.messageModel.updateToolMessage.mock.calls.length;
+ const beforeThreads = h.threadModel.create.mock.calls.length;
+
+ await ingest(h, [buildEvent(type as AgentStreamEvent['type'], 0, data)]);
+
+ expect(h.messageModel.create.mock.calls.length).toBe(beforeCreates);
+ expect(h.messageModel.update.mock.calls.length).toBe(beforeUpdates);
+ expect(h.messageModel.updateToolMessage.mock.calls.length).toBe(beforeToolUpdates);
+ expect(h.threadModel.create.mock.calls.length).toBe(beforeThreads);
+ });
+ });
+
+ // ─── Subagent-specific edge cases ─────────────────────────────────────────
+
+ describe('subagent edge cases', () => {
+ it('subagent tool_result updates the in-thread tool message via the global toolMsgIdByCallId', async () => {
+ const h = createHarness();
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ };
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ subagent: subagentCtx,
+ toolsCalling: [
+ {
+ apiName: 'Read',
+ arguments: '{}',
+ id: 'inner-tc',
+ identifier: 'read',
+ type: 'default',
+ },
+ ],
+ }),
+ // tool_result for the SUBAGENT's inner tool β€” NOT the spawn parent
+ buildEvent('tool_result', 1, {
+ content: 'file contents',
+ toolCallId: 'inner-tc',
+ }),
+ ]);
+
+ const threadId = [...h.threads.keys()][0];
+ const innerTool = [...h.messages.values()].find(
+ (m) => m.threadId === threadId && m.role === 'tool',
+ );
+ expect(innerTool?.content).toBe('file contents');
+ });
+
+ it('multiple subagent spawns coexist independently (each with its own thread)', async () => {
+ const h = createHarness();
+
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'first',
+ subagent: {
+ parentToolCallId: 'tc-spawn-A',
+ spawnMetadata: { prompt: 'task A', subagentType: 'Explore' },
+ subagentMessageId: 'sub-A-1',
+ },
+ }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'text',
+ content: 'second',
+ subagent: {
+ parentToolCallId: 'tc-spawn-B',
+ spawnMetadata: { prompt: 'task B', subagentType: 'Plan' },
+ subagentMessageId: 'sub-B-1',
+ },
+ }),
+ buildEvent('agent_runtime_end', 2, { reason: 'success' }),
+ ]);
+
+ expect(h.threads.size).toBe(2);
+ const titles = [...h.threads.values()].map((t) => t.title);
+ expect(titles).toContain('Explore');
+ expect(titles).toContain('Plan');
+ });
+
+ it('subagent first-event uses description for title, falls back to subagentType', async () => {
+ const h = createHarness();
+ // No description β†’ fallback to subagentType
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'x',
+ subagent: {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'Worker' },
+ subagentMessageId: 'sub-1',
+ },
+ }),
+ ]);
+ expect([...h.threads.values()][0].title).toBe('Worker');
+ });
+
+ it('subagent description longer than 80 chars is truncated for the thread title', async () => {
+ const h = createHarness();
+ const longDesc = 'a'.repeat(120);
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'x',
+ subagent: {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { description: longDesc, prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ },
+ }),
+ ]);
+ expect([...h.threads.values()][0].title).toHaveLength(80);
+ });
+
+ it('subagent with NO subagentMessageId still creates the thread (treated as a single turn)', async () => {
+ const h = createHarness();
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'no-turn-id text',
+ subagent: {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ // subagentMessageId omitted
+ },
+ }),
+ buildEvent('agent_runtime_end', 1, { reason: 'success' }),
+ ]);
+
+ expect(h.threads.size).toBe(1);
+ const flushed = [...h.messages.values()].find((m) => m.content === 'no-turn-id text');
+ expect(flushed).toBeDefined();
+ });
+
+ it('finalize on parent tool_result creates the terminal in-thread assistant carrying resultContent', async () => {
+ const h = createHarness();
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ };
+ await ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'thinking',
+ subagent: subagentCtx,
+ }),
+ buildEvent('tool_result', 1, {
+ content: 'final summary',
+ toolCallId: 'tc-spawn',
+ }),
+ ]);
+
+ const threadId = [...h.threads.keys()][0];
+ const threadAssts = [...h.messages.values()].filter(
+ (m) => m.threadId === threadId && m.role === 'assistant',
+ );
+ // Terminal assistant has the authoritative summary
+ expect(threadAssts.at(-1)?.content).toBe('final summary');
+ // Run state cleaned up after finalize
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.ts
similarity index 98%
rename from apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
rename to apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.ts
index 01232c1f821..8d6aba5e014 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.ts
@@ -2,10 +2,7 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
+import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } from '.';
/**
* Synthetic fixture mirroring the shape of a real CC run captured under
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts
new file mode 100644
index 00000000000..1051380bc7c
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts
@@ -0,0 +1,505 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness, ingest } from './eventBranchesTestUtils';
+
+const { acknowledgeAgentInterventionProducerResolution, notifyAgentInterventionRequired } =
+ vi.hoisted(() => ({
+ acknowledgeAgentInterventionProducerResolution: vi.fn(),
+ notifyAgentInterventionRequired: vi.fn(),
+ }));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({
+ acknowledgeAgentInterventionProducerResolution,
+ notifyAgentInterventionRequired,
+}));
+
+describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ acknowledgeAgentInterventionProducerResolution.mockReset();
+ notifyAgentInterventionRequired.mockReset();
+ });
+ afterEach(() => __resetOperationStatesForTesting());
+
+ describe('agent_intervention producer ACK', () => {
+ const materializeAskUserTool = async (
+ h: ReturnType<typeof createHarness>,
+ toolCallId: string,
+ ) =>
+ ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ }),
+ ]);
+
+ const missingProviderRequest = (toolCallId: string) =>
+ buildEvent('agent_intervention_request', 1, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Question',
+ options: [{ label: 'Continue' }, { label: 'Stop' }],
+ question: 'Proceed?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ toolCallId,
+ });
+
+ it('rejects an invalid first Cloud review before any intervention side effect', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const toolCallId = 'invalid-cloud-question';
+ await materializeAskUserTool(h, toolCallId);
+ h.messageModel.updateMessagePlugin.mockClear();
+ h.messageModel.updatePluginState.mockClear();
+
+ await expect(ingest(h, [missingProviderRequest(toolCallId)])).rejects.toThrow(
+ `Unsafe heterogeneous intervention review payload toolCallId=${toolCallId}`,
+ );
+
+ expect(h.messageModel.updateMessagePlugin).not.toHaveBeenCalled();
+ expect(h.messageModel.updatePluginState).not.toHaveBeenCalled();
+ expect(notifyAgentInterventionRequired).not.toHaveBeenCalled();
+ expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
+ const toolMessage = [...h.messages.values()].find(
+ (message) => message.tool_call_id === toolCallId,
+ );
+ expect(toolMessage?.plugin).not.toHaveProperty('intervention');
+ expect(toolMessage?.pluginState).toBeUndefined();
+ });
+
+ it('preserves legacy intervention persistence without a userId', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test', userId: null });
+ const toolCallId = 'legacy-question';
+ await materializeAskUserTool(h, toolCallId);
+ h.messageModel.updateMessagePlugin.mockClear();
+ h.messageModel.updatePluginState.mockClear();
+
+ await expect(ingest(h, [missingProviderRequest(toolCallId)])).resolves.toBeUndefined();
+
+ expect(h.messageModel.updateMessagePlugin).toHaveBeenCalledTimes(1);
+ expect(h.messageModel.updatePluginState).toHaveBeenCalledTimes(1);
+ expect(notifyAgentInterventionRequired).not.toHaveBeenCalled();
+ expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
+ const toolMessage = [...h.messages.values()].find(
+ (message) => message.tool_call_id === toolCallId,
+ );
+ expect(toolMessage?.plugin?.intervention).toEqual({ status: 'pending' });
+ expect(toolMessage?.pluginState?.heterogeneousIntervention).toMatchObject({
+ transition: 'pending',
+ });
+ });
+
+ it('canonicalizes an omitted Claude multiSelect before durable review notification', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Producer ACK E2E',
+ options: [
+ { description: 'Proceed with validation.', label: 'Continue' },
+ { description: 'Halt validation.', label: 'Stop' },
+ ],
+ question: 'Continue read only validation?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'claude-question-1',
+ }),
+ ]);
+
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ expect(notifyAgentInterventionRequired.mock.calls[0][0]).toMatchObject({
+ items: [
+ {
+ detail: {
+ questions: [
+ {
+ header: 'Producer ACK E2E',
+ id: 'question_1',
+ multiple: false,
+ options: [
+ {
+ description: 'Proceed with validation.',
+ id: 'Continue',
+ label: 'Continue',
+ },
+ {
+ description: 'Halt validation.',
+ id: 'Stop',
+ label: 'Stop',
+ },
+ ],
+ question: 'Continue read only validation?',
+ },
+ ],
+ title: 'Producer ACK E2E',
+ type: 'question',
+ },
+ interactionKind: 'question',
+ provider: 'claude-code',
+ summary: 'Continue read only validation?',
+ },
+ ],
+ summary: 'Continue read only validation?',
+ });
+ expect(h.messageModel.updatePluginState).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ heterogeneousIntervention: expect.objectContaining({
+ interactionKind: 'question',
+ provider: 'claude-code',
+ }),
+ }),
+ );
+ });
+
+ it('lets the user type their own answer to a heterogeneous question', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Stack',
+ multiSelect: false,
+ options: [{ label: 'React' }, { label: 'Vue' }],
+ question: 'Which framework?',
+ },
+ {
+ header: 'Targets',
+ multiSelect: true,
+ options: [{ label: 'Web' }, { label: 'Desktop' }],
+ question: 'Which targets?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'claude-question-custom',
+ }),
+ ]);
+
+ // The shared AskUser form always offers "write your own", "type
+ // directly" and a supplement note; without these capabilities the claim
+ // rejects every typed answer as not matching the request.
+ const detail = notifyAgentInterventionRequired.mock.calls[0][0].items[0].detail;
+ expect(detail).toMatchObject({
+ answerPolicy: { allowFreeform: true, allowSupplement: true },
+ questions: [
+ { allowCustomAnswer: true, question: 'Which framework?' },
+ { allowCustomAnswer: true, question: 'Which targets?' },
+ ],
+ type: 'question',
+ });
+ });
+
+ it('uses only the sanitized first question for a multi-question summary', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ privateRawArgument: 'must not appear in the summary',
+ questions: [
+ {
+ header: 'Validation',
+ multiSelect: false,
+ options: [
+ {
+ description: 'Sensitive option detail',
+ label: 'Continue',
+ },
+ ],
+ question: 'Which validation path should I use?',
+ },
+ {
+ header: 'Follow-up',
+ multiSelect: false,
+ options: [{ label: 'Production' }],
+ question: 'Which environment should I target?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'claude-question-summary',
+ }),
+ ]);
+
+ const notification = notifyAgentInterventionRequired.mock.calls[0][0];
+ expect(notification.summary).toBe('Which validation path should I use?');
+ expect(notification.items[0].summary).toBe('Which validation path should I use?');
+ });
+
+ it('normalizes and safely truncates a long question summary', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const longQuestion = ` Confirm\n\t${'πŸ˜€'.repeat(170)} now? `;
+
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Long question',
+ multiSelect: false,
+ options: [{ label: 'Continue' }],
+ question: longQuestion,
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'claude-long-question-summary',
+ }),
+ ]);
+
+ const summary = notifyAgentInterventionRequired.mock.calls[0][0].summary;
+ expect(summary).toBe(`Confirm ${'πŸ˜€'.repeat(151)}…`);
+ expect([...summary]).toHaveLength(160);
+ });
+
+ it('keeps the technical fallback when the sanitized question has no visible text', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Blank question',
+ multiSelect: false,
+ options: [{ label: 'Continue' }],
+ question: ' \n\t ',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'claude-blank-question-summary',
+ }),
+ ]);
+
+ const notification = notifyAgentInterventionRequired.mock.calls[0][0];
+ expect(notification.summary).toBe('claude-code question: askUserQuestion');
+ expect(notification.items[0].summary).toBe('claude-code question: askUserQuestion');
+ });
+
+ it('notifies pending once, ignores the publish leg, and notifies terminal only on ACK', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const requestId = '018fbd8e-7baf-7c6d-8000-000000000001';
+ const request = buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ privateRawArgument: 'must be stripped',
+ questions: [
+ {
+ header: 'Permission',
+ multiSelect: false,
+ options: [
+ { id: 'allow', label: 'Allow', raw: 'strip me' },
+ { id: 'deny', label: 'Deny' },
+ ],
+ question: 'Run command?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'devin',
+ interactionKind: 'permission',
+ provider: 'devin',
+ toolCallId: 'permission-1',
+ });
+
+ await ingest(h, [request]);
+ await ingest(h, [{ ...request, timestamp: request.timestamp + 1 }]);
+
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ const pending = notifyAgentInterventionRequired.mock.calls[0][0];
+ expect(pending).toMatchObject({
+ agentId: 'agent-test',
+ approvalMode: 'manual',
+ batch: {
+ allowedActions: [],
+ id: 'op-test:0:asst-seeded:permission-1',
+ kind: 'single',
+ sealed: true,
+ stepIndex: 0,
+ },
+ context: {
+ assistantMessageId: 'asst-seeded',
+ operationId: 'op-test',
+ topicId: 'topic-test',
+ },
+ items: [
+ {
+ allowedActions: ['select_provider_option', 'skip_interaction'],
+ detail: {
+ description: 'Permission',
+ options: [
+ { description: undefined, id: 'allow', label: 'Allow' },
+ { description: undefined, id: 'deny', label: 'Deny' },
+ ],
+ title: 'Run command?',
+ type: 'permission',
+ },
+ interactionKind: 'permission',
+ provider: 'devin',
+ sourceRef: {
+ operationId: 'op-test',
+ toolCallId: 'permission-1',
+ type: 'heterogeneous',
+ },
+ surface: 'form',
+ },
+ ],
+ systemActionEligibility: 'review_only',
+ });
+ expect(pending.batch.activityKey).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ );
+ expect(pending.items[0].requestRevision).toEqual({
+ hash: expect.stringMatching(/^[0-9a-f]{64}$/),
+ version: 1,
+ });
+ expect(JSON.stringify(pending)).not.toContain('privateRawArgument');
+
+ await ingest(h, [
+ buildEvent('agent_intervention_response', 1, {
+ producerAck: false,
+ resolutionRequestId: requestId,
+ result: { 'Run command?': 'allow' },
+ toolCallId: 'permission-1',
+ }),
+ ]);
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
+
+ const producerAck = buildEvent('agent_intervention_response', 2, {
+ producerAck: true,
+ resolutionRequestId: requestId,
+ result: { 'Run command?': 'allow' },
+ toolCallId: 'permission-1',
+ });
+ await ingest(h, [producerAck]);
+ await ingest(h, [{ ...producerAck, timestamp: producerAck.timestamp + 1 }]);
+
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledTimes(1);
+ expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledWith({
+ operationId: 'op-test',
+ ownerUserId: 'user-test',
+ resolutionRequestId: requestId,
+ status: 'resolved',
+ toolCallId: 'permission-1',
+ workspaceId: undefined,
+ });
+ });
+
+ it('gives concurrent callbacks in one assistant step distinct sealed batch identities', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const intervention = (toolCallId: string) =>
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Question',
+ multiSelect: false,
+ options: [{ label: 'Continue' }],
+ question: `Continue ${toolCallId}?`,
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId,
+ });
+
+ await ingest(h, [intervention('question-1'), intervention('question-2')]);
+
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(2);
+ const notifications = notifyAgentInterventionRequired.mock.calls.map(([params]) => params);
+ expect(notifications.map(({ batch }) => batch.id)).toEqual([
+ 'op-test:0:asst-seeded:question-1',
+ 'op-test:0:asst-seeded:question-2',
+ ]);
+ expect(new Set(notifications.map(({ batch }) => batch.activityKey)).size).toBe(2);
+ expect(notifications.every(({ batch }) => batch.allowedActions.length === 0)).toBe(true);
+ for (const notification of notifications) {
+ expect(notification.items[0].allowedActions).toEqual([
+ 'submit_answers',
+ 'skip_interaction',
+ ]);
+ }
+ });
+
+ it('matches Web plan actions without advertising reserved cancel', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Plan',
+ multiSelect: false,
+ options: [{ id: 'accept', label: 'Accept plan' }],
+ question: 'Proceed with this plan?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'cursor',
+ interactionKind: 'plan',
+ provider: 'cursor',
+ toolCallId: 'plan-1',
+ }),
+ ]);
+
+ const pending = notifyAgentInterventionRequired.mock.calls[0][0];
+ expect(pending.items[0]).toMatchObject({
+ allowedActions: ['select_provider_option', 'skip_interaction'],
+ interactionKind: 'plan',
+ });
+ expect(pending.items[0].allowedActions).not.toContain('cancel_interaction');
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.ts
similarity index 98%
rename from apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
rename to apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.ts
index 12cf4f96e59..47771bd6002 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.ts
@@ -2,10 +2,7 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
+import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } from '.';
/**
* Regression for the MAIN-chain analog of #15808 (which only fixed the SUBAGENT
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.replicaState.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.replicaState.test.ts
new file mode 100644
index 00000000000..f007fbd8c31
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.replicaState.test.ts
@@ -0,0 +1,404 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import type { FakeTopicMetadata } from './testUtils';
+import { buildEvent, createHarness } from './testUtils';
+
+describe('HeterogeneousPersistenceHandler', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ afterEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ describe('cold replica state restoration (Vercel serverless)', () => {
+ it('restores accumulatedContent from DB so a cold instance does not truncate previous text', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Batch 1 (warm instance): stream two text chunks, flush happens via flushBatchContent
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hello ' }, 1000),
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'world' }, 1001),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // DB should have the partial content written by flushBatchContent
+ expect(h.messages.get('asst-1')?.content).toBe('hello world');
+
+ // Simulate cold replica: drop the in-memory operation state
+ __resetOperationStatesForTesting();
+
+ // Batch 2 (cold instance): receives more text.
+ // Without restoration the new instance would start with accumulatedContent='' and
+ // write only " more" β€” truncating "hello world".
+ await h.handler.ingest({
+ events: [buildEvent('agent_runtime_end', 0, { reason: 'success' }, 2000)],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // The terminal flush should preserve the previously accumulated content.
+ expect(h.messages.get('asst-1')?.content).toBe('hello world');
+ });
+
+ it('restores toolState.payloads and persistedIds so cold replica does not duplicate tools or overwrite tools[]', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Batch 1 (warm): persist tool1
+ const tool1: any = {
+ apiName: 'tool1',
+ arguments: '{}',
+ id: 'tc-1',
+ identifier: 'tool1',
+ type: 'default',
+ };
+ await h.handler.ingest({
+ events: [
+ buildEvent(
+ 'stream_chunk',
+ 0,
+ { chunkType: 'tools_calling', toolsCalling: [tool1] },
+ 1000,
+ ),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // assistant.tools[] should have tool1
+ const asstAfterBatch1 = h.messages.get('asst-1')!;
+ expect(asstAfterBatch1.tools).toHaveLength(1);
+ expect(asstAfterBatch1.tools![0].id).toBe('tc-1');
+ // tool message created for tool1
+ const toolMsgsBatch1 = [...h.messages.values()].filter((m) => m.role === 'tool');
+ expect(toolMsgsBatch1).toHaveLength(1);
+
+ // Simulate cold replica: drop in-memory state
+ __resetOperationStatesForTesting();
+
+ // Batch 2 (cold): receives tool2 β€” should ADD to tools[], not overwrite
+ const tool2: any = {
+ apiName: 'tool2',
+ arguments: '{}',
+ id: 'tc-2',
+ identifier: 'tool2',
+ type: 'default',
+ };
+ await h.handler.ingest({
+ events: [
+ buildEvent(
+ 'stream_chunk',
+ 1,
+ { chunkType: 'tools_calling', toolsCalling: [tool2] },
+ 2000,
+ ),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const asstAfterBatch2 = h.messages.get('asst-1')!;
+ // Both tools should be present β€” cold restore kept tool1 in payloads
+ expect(asstAfterBatch2.tools).toHaveLength(2);
+
+ // tool1 should NOT be duplicated β€” persistedIds was restored
+ const allToolMsgs = [...h.messages.values()].filter((m) => m.role === 'tool');
+ const tool1Msgs = allToolMsgs.filter((m) => m.tool_call_id === 'tc-1');
+ expect(tool1Msgs).toHaveLength(1);
+ });
+ });
+
+ describe('warm replica step resync', () => {
+ it('reports a late advanced batch as stale after its operation was removed', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValue({ agentId: null, id: 'topic-1', metadata: {} });
+
+ await expect(
+ h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'late' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow('Stale hetero operation op-1');
+ });
+
+ it('switches to the DB-persisted step assistant when a later-step batch lands on a stale warm replica', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ h.messages.set('asst-2', {
+ agentId: null,
+ content: '',
+ id: 'asst-2',
+ parentId: 'asst-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+ });
+
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ heteroCurrentMsgId: { msgId: 'asst-2', operationId: 'op-1' },
+ runningOperation: {
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ },
+ } satisfies FakeTopicMetadata,
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'step2' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(h.messages.get('asst-1')?.content).toBe('step1');
+ expect(h.messages.get('asst-2')?.content).toBe('step2');
+ });
+ });
+
+ describe('per-message session provenance (heteroSessionId / heteroMessageId)', () => {
+ it('stamps the CC session id + turn message id on the assistant, its tools, and its usage', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const tool = {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-1',
+ identifier: 'bash',
+ type: 'default',
+ };
+
+ await h.handler.ingest({
+ events: [
+ // system.init: carries the CC session id but opens no new assistant.
+ buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
+ // A real turn boundary: opens a new assistant for CC message cc-1.
+ buildEvent('stream_start', 1, {
+ messageId: 'cc-1',
+ newStep: true,
+ sessionId: 'sess-A',
+ }),
+ buildEvent('stream_chunk', 2, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('step_complete', 3, {
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 1, totalOutputTokens: 1, totalTokens: 2 },
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const assistant = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ )!;
+ expect(assistant.metadata).toMatchObject({
+ heteroMessageId: 'cc-1',
+ heteroSessionId: 'sess-A',
+ });
+
+ const toolRow = [...h.messages.values()].find((m) => m.role === 'tool')!;
+ expect(toolRow.metadata).toMatchObject({
+ heteroMessageId: 'cc-1',
+ heteroSessionId: 'sess-A',
+ });
+
+ // recordUsage overwrites the row's metadata wholesale β€” provenance must survive.
+ const usageWrite = h.messageModel.update.mock.calls.find(
+ ([, patch]: [string, any]) => patch?.metadata?.usage,
+ )!;
+ expect(usageWrite[1].metadata).toMatchObject({
+ heteroMessageId: 'cc-1',
+ heteroSessionId: 'sess-A',
+ usage: { totalTokens: 2 },
+ });
+ });
+
+ it('records a mid-topic session fork per-message so a diff pinpoints the break', async () => {
+ // The tpc_PZAmvtpkfHE1 scenario: `--resume` failed, CC opened a fresh
+ // session mid-conversation, and the topic-level single heteroSessionId
+ // could not show WHERE the history was lost. Per-message stamping does.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
+ buildEvent('stream_start', 1, { messageId: 'cc-1', newStep: true, sessionId: 'sess-A' }),
+ buildEvent('stream_chunk', 2, { chunkType: 'text', content: 'turn 1' }),
+ // Next turn resumes into a DIFFERENT session β€” the fork.
+ buildEvent('stream_start', 3, { messageId: 'cc-2', newStep: true, sessionId: 'sess-B' }),
+ buildEvent('stream_chunk', 4, { chunkType: 'text', content: 'turn 2' }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const newAssistants = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ );
+ const sessById = new Map(
+ newAssistants.map((m) => [m.metadata?.heteroMessageId, m.metadata?.heteroSessionId]),
+ );
+ expect(sessById.get('cc-1')).toBe('sess-A');
+ expect(sessById.get('cc-2')).toBe('sess-B');
+ });
+
+ it('stamps heteroMessageId on the FIRST (seeded) turn, not just later newStep turns', async () => {
+ // The first CC assistant follows system:init with NO newStep β€” it lands on
+ // the pre-seeded assistant. The adapter now carries the turn's message.id on
+ // that non-newStep stream_start so the seed assistant + its first-turn tool
+ // and usage rows get heteroMessageId β€” the common first turn of a
+ // resumed/forked operation this forensic data exists to diagnose.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const tool = {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-1',
+ identifier: 'bash',
+ type: 'default',
+ };
+
+ await h.handler.ingest({
+ events: [
+ // system:init carries the session id but opens no new assistant.
+ buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
+ // First assistant after init: non-newStep stream_start carrying the
+ // seed turn's CC message.id (what the adapter now emits).
+ buildEvent('stream_start', 1, { messageId: 'cc-seed', sessionId: 'sess-A' }),
+ buildEvent('stream_chunk', 2, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('step_complete', 3, {
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 1, totalOutputTokens: 1, totalTokens: 2 },
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // The seeded assistant's usage write re-stamps the provenance.
+ const seedUsageWrite = h.messageModel.update.mock.calls.find(
+ ([id, patch]: [string, any]) => id === 'asst-init' && patch?.metadata?.usage,
+ )!;
+ expect(seedUsageWrite[1].metadata).toMatchObject({
+ heteroMessageId: 'cc-seed',
+ heteroSessionId: 'sess-A',
+ });
+
+ const toolRow = [...h.messages.values()].find((m) => m.role === 'tool')!;
+ expect(toolRow.metadata).toMatchObject({
+ heteroMessageId: 'cc-seed',
+ heteroSessionId: 'sess-A',
+ });
+ });
+
+ it('stamps the subagent turn message id on subagent tool + usage rows', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn',
+ spawnMetadata: { prompt: 'p', subagentType: 'Explore' },
+ subagentMessageId: 'sub-1',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'tools_calling',
+ subagent: subagentCtx,
+ toolsCalling: [
+ {
+ apiName: 'Read',
+ arguments: '{}',
+ id: 'inner-tc',
+ identifier: 'read',
+ type: 'default',
+ },
+ ],
+ }),
+ buildEvent('step_complete', 2, {
+ phase: 'turn_metadata',
+ subagent: subagentCtx,
+ usage: { totalInputTokens: 1, totalOutputTokens: 1, totalTokens: 2 },
+ }),
+ buildEvent('agent_runtime_end', 3, { reason: 'success' }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const threadId = [...h.threads.keys()][0];
+
+ // The subagent's inner tool row carries the subagent turn's message id.
+ const innerTool = [...h.messages.values()].find(
+ (m) => m.threadId === threadId && m.role === 'tool',
+ )!;
+ expect(innerTool.metadata).toMatchObject({
+ heteroMessageId: 'sub-1',
+ heteroSessionId: 'sess-A',
+ });
+
+ // recordUsage overwrites the subagent assistant's metadata wholesale β€” the
+ // heteroMessageId createMessage stamped must survive it.
+ const subUsageWrite = h.messageModel.update.mock.calls.find(
+ ([, patch]: [string, any]) => patch?.metadata?.usage,
+ )!;
+ expect(subUsageWrite[1].metadata).toMatchObject({
+ heteroMessageId: 'sub-1',
+ heteroSessionId: 'sess-A',
+ usage: { totalTokens: 2 },
+ });
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts
new file mode 100644
index 00000000000..9dc17664bcf
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts
@@ -0,0 +1,694 @@
+// @vitest-environment node
+import { ThreadStatus } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import type { FakeTopicMetadata } from './testUtils';
+import { buildEvent, createHarness } from './testUtils';
+
+describe('HeterogeneousPersistenceHandler', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ afterEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ describe('step boundaries (stream_start newStep)', () => {
+ it('recovers an isolation run from the thread spine instead of the projected topic reply', async () => {
+ const h = createHarness({
+ assistantMessageId: 'thread-asst-1',
+ operationId: 'op-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ h.messages.set('projected-topic-reply', {
+ agentId: 'target-agent',
+ content: 'projected answer',
+ id: 'projected-topic-reply',
+ role: 'assistant',
+ threadId: null,
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const nextThreadAssistant = [...h.messages.values()].find(
+ (message) =>
+ message.role === 'assistant' &&
+ message.threadId === 'thread-1' &&
+ message.id !== 'thread-asst-1',
+ );
+ expect(nextThreadAssistant?.parentId).toBe('thread-asst-1');
+ expect(h.messageModel.getLatestSpineMessageId).toHaveBeenCalledWith({
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('flushes prior content, opens a new assistant chained off the prior assistant (spine)', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const tool = {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-1',
+ identifier: 'bash',
+ type: 'default',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1 ' }),
+ buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('tool_result', 2, {
+ content: 'ok',
+ toolCallId: 'tc-1',
+ }),
+ buildEvent('stream_start', 3, { newStep: true }),
+ buildEvent('stream_chunk', 4, { chunkType: 'text', content: 'step2' }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // First step: asst-1 got content + tools.
+ // After step boundary (phase 2 spine rule): a NEW assistant is created
+ // chained off the prior assistant (asst-1), with the tool as an inline
+ // child β€” the read side reconstructs the zigzag.
+ const newAssistants = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.id !== 'asst-1',
+ );
+ expect(newAssistants).toHaveLength(1);
+ expect(newAssistants[0].parentId).toBe('asst-1');
+ });
+
+ it('chains off the prior assistant (spine) across a multi-replica boundary, recovered from DB', async () => {
+ // Phase 2: the chain parent is the run's latest non-tool / non-signal
+ // scoped message, recovered from the DB (`getLatestSpineMessageId`)
+ // independent of the in-memory current-assistant pointer. So even when the
+ // prior step's tools_calling drained on a DIFFERENT replica (this replica's
+ // toolState stays empty), step 2 still chains off step 1's assistant β€” a
+ // linear spine, not a fork.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Track topic.metadata so updateMetadata({heteroCurrentMsgId}) becomes
+ // observable to subsequent findById calls β€” the default harness mock is
+ // a no-op which would mask the bug behind a sync-rollback artifact.
+ const metaState: FakeTopicMetadata = {
+ runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
+ };
+ h.topicModel.findById.mockImplementation(async (id: string) => {
+ if (id !== 'topic-1') return null;
+ return { agentId: null, id, metadata: { ...metaState } };
+ });
+ h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
+ Object.assign(metaState, patch);
+ });
+
+ // ── Batch 1: this replica drains step 1's stream_start ──
+ // No tools yet on this asst β†’ handleStepStart chains step 1 off
+ // 'asst-init' (correct, since asst-init had no tools).
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step1Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ )!;
+ expect(step1Asst).toBeDefined();
+ expect(step1Asst.parentId).toBe('asst-init');
+
+ // ── Simulate "another replica drained step 1's tools_calling + result" ──
+ // The other replica would have:
+ // 1. Created a tool message
+ // 2. Rewritten step1Asst.tools[] with result_msg_id pointing at it
+ // Both writes hit DB. THIS replica's in-memory state.toolState stays []
+ // (reset by handleStepStart) and has no idea this happened.
+ h.messages.set('tool-other-replica', {
+ agentId: null,
+ content: 'result body',
+ id: 'tool-other-replica',
+ parentId: step1Asst.id,
+ role: 'tool',
+ tool_call_id: 'tc-1',
+ topicId: 'topic-1',
+ });
+ h.messages.set(step1Asst.id, {
+ ...h.messages.get(step1Asst.id)!,
+ model: 'claude-sonnet-4-6',
+ provider: 'claude-code',
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-1',
+ identifier: 'bash',
+ result_msg_id: 'tool-other-replica',
+ type: 'default',
+ },
+ ],
+ });
+
+ // ── Batch 2: step 2 stream_start lands back on THIS replica ──
+ // The DB spine query returns step1Asst (the latest non-tool main message),
+ // so step 2 chains off it regardless of this replica's empty toolState.
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 2, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step2Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
+ );
+ expect(step2Asst).toBeDefined();
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
+ // And the new assistant should inherit model/provider that the other
+ // replica wrote β€” refresh also restores lastModel/lastProvider so we
+ // no longer create assistants with model=null/provider=null on the
+ // replica that didn't drain step_complete.
+ expect(step2Asst!.model).toBe('claude-sonnet-4-6');
+ expect(step2Asst!.provider).toBe('claude-code');
+ });
+
+ it('chains off the spine regardless of the prior step tool backfill state', async () => {
+ // Phase 2: the chain anchors to the spine (latest non-tool main message),
+ // so the prior step's tool-row / result_msg_id backfill timing β€” which
+ // used to matter for the tool anchor β€” no longer affects the chain. Even
+ // with a tool row present but no tools[] backfill, step 2 chains off the
+ // prior assistant.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const metaState: FakeTopicMetadata = {
+ runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
+ };
+ h.topicModel.findById.mockImplementation(async (id: string) => {
+ if (id !== 'topic-1') return null;
+ return { agentId: null, id, metadata: { ...metaState } };
+ });
+ h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
+ Object.assign(metaState, patch);
+ });
+
+ // ── Batch 1: this replica drains step 1's stream_start (no tools yet) ──
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const step1Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ )!;
+
+ // ── Other replica created the tool ROW but NOT the tools[] backfill ──
+ // Note: step1Asst.tools[] is intentionally left WITHOUT result_msg_id,
+ // so the ingest refresh cannot recover the anchor.
+ h.messages.set('tool-row-only', {
+ agentId: null,
+ content: 'result body',
+ id: 'tool-row-only',
+ parentId: step1Asst.id,
+ role: 'tool',
+ threadId: null,
+ tool_call_id: 'tc-1',
+ topicId: 'topic-1',
+ });
+
+ // ── Batch 2: step 2 stream_start lands on THIS (empty-state) replica ──
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 2, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step2Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
+ );
+ expect(step2Asst).toBeDefined();
+ // Chains off the prior assistant (spine) β†’ wire stays linear; the tool is inline.
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
+ });
+
+ it('chains off the spine when parallel tools are only partially backfilled', async () => {
+ // Regression for main-chain breaks with parallel/multi tool calls:
+ // tool A is visible in assistant.tools[].result_msg_id, while tool B's
+ // row exists but Phase 3 has not backfilled assistant.tools[] yet. The
+ // step anchor must be tool B, not the earlier resolved tool A.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const metaState: FakeTopicMetadata = {
+ runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
+ };
+ h.topicModel.findById.mockImplementation(async (id: string) => {
+ if (id !== 'topic-1') return null;
+ return { agentId: null, id, metadata: { ...metaState } };
+ });
+ h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
+ Object.assign(metaState, patch);
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const step1Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ )!;
+
+ h.messages.set('tool-a-backfilled', {
+ agentId: null,
+ content: 'tool A result',
+ id: 'tool-a-backfilled',
+ parentId: step1Asst.id,
+ role: 'tool',
+ threadId: null,
+ tool_call_id: 'tc-a',
+ topicId: 'topic-1',
+ });
+ h.messages.set('tool-b-row-only', {
+ agentId: null,
+ content: 'tool B result',
+ id: 'tool-b-row-only',
+ parentId: step1Asst.id,
+ role: 'tool',
+ threadId: null,
+ tool_call_id: 'tc-b',
+ topicId: 'topic-1',
+ });
+ h.messages.set(step1Asst.id, {
+ ...h.messages.get(step1Asst.id)!,
+ tools: [
+ {
+ apiName: 'Read',
+ arguments: '{}',
+ id: 'tc-a',
+ identifier: 'read',
+ result_msg_id: 'tool-a-backfilled',
+ type: 'default',
+ },
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-b',
+ identifier: 'bash',
+ type: 'default',
+ },
+ ],
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 2, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step2Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
+ );
+ expect(step2Asst).toBeDefined();
+ // Spine-anchored: parallel-tool backfill state is irrelevant to the chain.
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
+ });
+
+ it('ignores subagent tool rows (threadId set) when resolving the step anchor', async () => {
+ // A subagent tool row lives on its own thread and must never anchor the
+ // main-agent wire. If the only `role:'tool'` child carries a threadId,
+ // the fallback must skip it and chain off the previous assistant.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const metaState: FakeTopicMetadata = {
+ runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
+ };
+ h.topicModel.findById.mockImplementation(async (id: string) => {
+ if (id !== 'topic-1') return null;
+ return { agentId: null, id, metadata: { ...metaState } };
+ });
+ h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
+ Object.assign(metaState, patch);
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const step1Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ )!;
+
+ h.messages.set('subagent-tool', {
+ agentId: null,
+ content: 'sub result',
+ id: 'subagent-tool',
+ parentId: step1Asst.id,
+ role: 'tool',
+ threadId: 'thread-sub',
+ tool_call_id: 'tc-sub',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 2, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step2Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
+ );
+ expect(step2Asst).toBeDefined();
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
+ });
+
+ it('handleTurnMetadata persists model/provider to DB so other replicas can recover lastModel/lastProvider', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('step_complete', 0, {
+ model: 'claude-sonnet-4-6',
+ phase: 'turn_metadata',
+ provider: 'claude-code',
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Was previously `{ metadata: { usage } }` only β€” now extended to also
+ // carry model/provider so a replica picking up the next step boundary
+ // can read them back from DB even if it never drained this event.
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-init', {
+ metadata: { usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 } },
+ model: 'claude-sonnet-4-6',
+ provider: 'claude-code',
+ });
+ });
+
+ it('retry recovers an unresolved tool that another replica only Phase-1 registered (no false-positive persistedIds)', async () => {
+ // Race: another replica wrote `assistant.tools[]` (Phase 1) but its
+ // Phase 2 β€” creating the `role:'tool'` row + backfilling
+ // `result_msg_id` β€” hasn't landed yet (or threw). The BatchIngester
+ // then retries the SAME tools_calling event onto THIS replica.
+ //
+ // If `persistedIds` includes the unresolved id, `persistToolBatch`
+ // filters it out of `freshForCreate`, skips the create, and rewrites
+ // `tools[]` unchanged β†’ the tool is orphaned (never gets a tool
+ // message, never gets `result_msg_id`). Fix: only mark ids whose
+ // `result_msg_id` is filled in as persisted.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Pre-populate the initial assistant with a Phase-1-only tool entry
+ // (no `result_msg_id`), simulating the other replica's mid-flight write.
+ h.messages.set('asst-init', {
+ ...h.messages.get('asst-init')!,
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-unresolved',
+ identifier: 'bash',
+ type: 'default',
+ // NOTE: no result_msg_id β€” Phase 2 has not run yet.
+ },
+ ],
+ });
+
+ // Retry of the same tools_calling event lands on this replica.
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-unresolved',
+ identifier: 'bash',
+ type: 'default',
+ },
+ ],
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // The tool message must have been created (Phase 2 completed via retry)
+ // and assistant.tools[0].result_msg_id must point at it.
+ const toolMsgs = [...h.messages.values()].filter((m) => m.role === 'tool');
+ expect(toolMsgs).toHaveLength(1);
+ expect(toolMsgs[0].tool_call_id).toBe('tc-unresolved');
+
+ const asst = h.messages.get('asst-init')!;
+ expect(asst.tools).toHaveLength(1);
+ expect(asst.tools![0].result_msg_id).toBe(toolMsgs[0].id);
+ });
+ });
+
+ describe('subagent threads', () => {
+ it('lazy-creates the thread + user + first assistant on first subagent chunk', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn-1',
+ spawnMetadata: {
+ description: 'Explore CC stream chain',
+ prompt: 'Investigate adapter logic',
+ subagentType: 'Explore',
+ },
+ subagentMessageId: 'sub-msg-1',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'subagent thinking',
+ subagent: subagentCtx,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(h.threads.size).toBe(1);
+ const thread = [...h.threads.values()][0];
+ expect(thread.title).toBe('Explore CC stream chain');
+ expect(thread.metadata?.sourceToolCallId).toBe('tc-spawn-1');
+ expect(thread.metadata?.subagentType).toBe('Explore');
+ expect(thread.sourceMessageId).toBe('asst-1');
+
+ const threadMessages = [...h.messages.values()].filter((m) => m.threadId === thread.id);
+ expect(threadMessages.map((m) => m.role)).toEqual(['user', 'assistant']);
+ expect(threadMessages[0].content).toBe('Investigate adapter logic');
+ expect(threadMessages[1].parentId).toBe(threadMessages[0].id);
+ });
+
+ it('cuts a new in-thread assistant when subagentMessageId advances', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const ctxBase = {
+ parentToolCallId: 'tc-spawn-1',
+ spawnMetadata: { prompt: 'do work', subagentType: 'Worker' },
+ };
+
+ const tool = {
+ apiName: 'Read',
+ arguments: '{}',
+ id: 'inner-tc-1',
+ identifier: 'read',
+ type: 'default',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ subagent: { ...ctxBase, subagentMessageId: 'sub-1' },
+ toolsCalling: [tool],
+ }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'text',
+ content: 'turn-2 thinking',
+ subagent: { ...ctxBase, subagentMessageId: 'sub-2' },
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const threadId = [...h.threads.keys()][0];
+ const threadAssts = [...h.messages.values()].filter(
+ (m) => m.threadId === threadId && m.role === 'assistant',
+ );
+ // Initial assistant + new turn assistant after subagentMessageId change
+ expect(threadAssts.length).toBeGreaterThanOrEqual(2);
+
+ // Tool message exists in the thread
+ const threadTool = [...h.messages.values()].find(
+ (m) => m.threadId === threadId && m.role === 'tool',
+ );
+ expect(threadTool?.tool_call_id).toBe('inner-tc-1');
+ expect(threadTool?.parentId).toBe(threadAssts[0].id);
+
+ // Second-turn assistant chains off the prior in-thread assistant (spine),
+ // with the tool as an inline child (phase 2 rule).
+ const secondTurn = threadAssts[1];
+ expect(secondTurn.parentId).toBe(threadAssts[0].id);
+ });
+
+ it('finalizes the run with terminal assistant carrying tool_result content', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn-1',
+ spawnMetadata: { prompt: 'p', subagentType: 'X' },
+ subagentMessageId: 'sub-1',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'thinking',
+ subagent: subagentCtx,
+ }),
+ buildEvent('tool_result', 1, {
+ content: 'final summary from subagent',
+ toolCallId: 'tc-spawn-1',
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const threadId = [...h.threads.keys()][0];
+ const threadAssts = [...h.messages.values()].filter(
+ (m) => m.threadId === threadId && m.role === 'assistant',
+ );
+ const terminal = threadAssts.at(-1);
+ expect(terminal?.content).toBe('final summary from subagent');
+
+ // Thread status updated
+ const thread = h.threads.get(threadId)!;
+ expect(thread.status).toBeDefined();
+ });
+
+ it('writes subagent usage + model onto the in-thread assistant, and finalize only flips status', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const subagentCtx = {
+ parentToolCallId: 'tc-spawn-1',
+ spawnMetadata: { prompt: 'p', subagentType: 'Explore' },
+ subagentMessageId: 'sub-1',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'working',
+ subagent: subagentCtx,
+ }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'tools_calling',
+ subagent: subagentCtx,
+ toolsCalling: [
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-child',
+ identifier: 'bash',
+ type: 'default',
+ },
+ ],
+ }),
+ // Subagent turn_metadata carries the authoritative per-turn usage + model.
+ buildEvent('step_complete', 2, {
+ model: 'claude-opus-4-8',
+ phase: 'turn_metadata',
+ provider: 'claude-code',
+ subagent: subagentCtx,
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ }),
+ buildEvent('tool_result', 3, { content: 'final', toolCallId: 'tc-spawn-1' }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const threadId = [...h.threads.keys()][0];
+ const thread = h.threads.get(threadId)!;
+ // Metrics are NOT denormalized onto metadata β€” derived on read instead.
+ expect(thread.metadata?.totalTokens).toBeUndefined();
+ expect(thread.metadata?.totalToolCalls).toBeUndefined();
+ // Create-time peer fields untouched; finalize only flips status.
+ expect(thread.metadata?.sourceToolCallId).toBe('tc-spawn-1');
+ expect(thread.metadata?.subagentType).toBe('Explore');
+ expect(thread.status).toBe(ThreadStatus.Active);
+
+ // The in-thread assistant got usage + model written β€” the rows the
+ // read-time aggregation later sums over.
+ const threadAssts = [...h.messages.values()].filter(
+ (m) => m.threadId === threadId && m.role === 'assistant',
+ );
+ const withUsage = threadAssts.find((m) => m.metadata?.usage?.totalTokens === 15);
+ expect(withUsage?.model).toBe('claude-opus-4-8');
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts
similarity index 99%
rename from apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
rename to apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts
index d3930f80d42..61fcfbf796d 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts
@@ -2,10 +2,7 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
+import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } from '.';
/**
* Regression for the SERVER-ONLY "ε€§ι‡ζ— ζ„δΉ‰ηš„ SubAgent" bug.
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.terminal.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.terminal.test.ts
new file mode 100644
index 00000000000..8bed3e52056
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.terminal.test.ts
@@ -0,0 +1,477 @@
+// @vitest-environment node
+import { createAdapter } from '@lobechat/heterogeneous-agents';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness } from './testUtils';
+
+describe('HeterogeneousPersistenceHandler', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ afterEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ describe('terminal events and finish()', () => {
+ it('flushes accumulated content on agent_runtime_end', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'final answer' }),
+ buildEvent('agent_runtime_end', 1, { reason: 'success' }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.content).toBe('final answer');
+ });
+
+ /**
+ * @example A finish request on a stale replica preserves the final snapshot written elsewhere.
+ */
+ it('does not let a stale finish overwrite a newer assistant snapshot', async () => {
+ // ROOT CAUSE:
+ //
+ // A warm serverless replica can retain an older per-operation accumulator
+ // while another replica persists a newer text snapshot to the shared DB.
+ // Before the fix, heteroFinish flushed the stale accumulator and replaced
+ // the final answer with the preceding progress message.
+ //
+ // We fixed this by making heteroIngest the only content/reasoning writer;
+ // a successful finish now releases operation state without rewriting text.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'progress',
+ snapshotMode: 'replace',
+ snapshotSeq: 4,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Simulate a newer snapshot committed by another Lambda replica.
+ h.messages.set('asst-1', {
+ ...h.messages.get('asst-1')!,
+ content: 'progress\n\nfinal answer',
+ metadata: { heteroTextSnapshotSeq: 5 },
+ });
+
+ await h.handler.finish({
+ operationId: 'op-1',
+ result: 'success',
+ topicId: 'topic-1',
+ });
+
+ expect(h.messages.get('asst-1')).toMatchObject({
+ content: 'progress\n\nfinal answer',
+ metadata: { heteroTextSnapshotSeq: 5 },
+ });
+ });
+
+ it.each([false, true])(
+ 'does not persist a Codex reconnect on either side of a tool-created step (failed=%s)',
+ async (failed) => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const adapter = createAdapter('codex');
+ const rawEvents = [
+ { type: 'turn.started' },
+ { message: 'Reconnecting... 2/5 (request timed out)', type: 'error' },
+ {
+ item: { id: 'progress', text: 'Inspecting the workflow.', type: 'agent_message' },
+ type: 'item.completed',
+ },
+ {
+ item: { command: 'printf inspected', id: 'inspect', type: 'command_execution' },
+ type: 'item.started',
+ },
+ {
+ item: {
+ aggregated_output: 'inspected',
+ command: 'printf inspected',
+ exit_code: 0,
+ id: 'inspect',
+ status: 'completed',
+ type: 'command_execution',
+ },
+ type: 'item.completed',
+ },
+ {
+ item: {
+ id: 'answer',
+ text: 'Version checks do not publish releases.',
+ type: 'agent_message',
+ },
+ type: 'item.completed',
+ },
+ failed
+ ? { error: { message: 'stream closed before response.completed' }, type: 'turn.failed' }
+ : { type: 'turn.completed' },
+ ];
+ // Keep ingest batches separated across the error/tool/newStep boundaries.
+ // Mock only the database, not the adapter or persistence coordinator.
+ let timestamp = 1_700_000_000_000;
+ for (const raw of rawEvents) {
+ const events = adapter.adapt(raw);
+ if (events.length === 0) continue;
+ await h.handler.ingest({
+ events: events.map((event) =>
+ buildEvent(event.type, event.stepIndex, event.data, timestamp++),
+ ),
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ }
+ await h.handler.finish({
+ error: failed
+ ? { message: 'stream closed before response.completed', type: 'AgentRuntimeError' }
+ : undefined,
+ operationId: 'op-1',
+ result: failed ? 'error' : 'success',
+ topicId: 'topic-1',
+ });
+
+ const assistants = [...h.messages.values()].filter(
+ (message) => message.role === 'assistant',
+ );
+ expect(assistants).toHaveLength(2);
+ expect(assistants.map((message) => message.content)).toEqual([
+ 'Inspecting the workflow.',
+ 'Version checks do not publish releases.',
+ ]);
+ expect(assistants[0].error).toBeUndefined();
+ expect(assistants.filter((message) => message.error)).toHaveLength(failed ? 1 : 0);
+ if (failed) {
+ expect(assistants[1].error.message).toBe('stream closed before response.completed');
+ }
+ expect([...h.messages.values()].find((message) => message.role === 'tool')).toMatchObject({
+ content: 'inspected',
+ parentId: 'asst-1',
+ });
+ },
+ );
+
+ it('writes error onto the assistant when terminal event is error', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'partial' }),
+ buildEvent('error', 1, {
+ message: 'CLI auth required',
+ type: 'AuthRequired',
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error).toBeDefined();
+ expect(asst.error.message).toBe('CLI auth required');
+ expect(asst.content).toBe('partial');
+ });
+
+ it('finish() preserves a structured status-guide error body on the assistant', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Register op state without any in-stream error β€” the process-level
+ // failure (spawn ENOENT) only arrives via the finish payload.
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: '' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.finish({
+ error: {
+ body: {
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ },
+ message: 'Claude Code CLI was not found on the machine running this agent.',
+ type: 'stream_error',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error).toBeDefined();
+ // `body` must survive formatErrorForState untouched β€” the client's
+ // status-guide UI gates on `body.agentType` + `body.code`.
+ expect(asst.error.body).toMatchObject({
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ });
+ expect(asst.error.message).toContain('was not found');
+ });
+
+ it('finish() must not downgrade an in-stream status-guide error with a flat message', async () => {
+ // Remote CC relays an API failure (529 overloaded / rate limit) as an
+ // in-stream `error` event whose data the adapter already classified into
+ // the structured status-guide shape (`agentType` + `code`). Older CLIs
+ // then send a finish error flattened to a bare `{ message }` β€” writing
+ // that over the persisted structured error would demote the client from
+ // the dedicated guide card to the generic error alert.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const overloadedMessage = 'API Error: 529 Overloaded. This is a server-side issue.';
+ await h.handler.ingest({
+ events: [
+ buildEvent('error', 0, {
+ agentType: 'claude-code',
+ code: 'overloaded',
+ error: overloadedMessage,
+ message: overloadedMessage,
+ stderr: overloadedMessage,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.finish({
+ error: { message: overloadedMessage, type: 'AgentRuntimeError' },
+ operationId: 'op-1',
+ result: 'error',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error.body).toMatchObject({
+ agentType: 'claude-code',
+ code: 'overloaded',
+ });
+ });
+
+ it('finish() with NO prior ingest bootstraps state and writes the error (spawn-fail path)', async () => {
+ // The real process-level failure shape: spawn ENOENT produces ZERO
+ // stream events, so no ingest ever created an OperationState. finish()
+ // must bootstrap from topic.metadata.runningOperation and write the
+ // error itself β€” deferring it to CompletionLifecycle (which runs AFTER
+ // the agent_runtime_end publish) races the client's message refetch.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.finish({
+ error: {
+ body: {
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ },
+ message: 'Claude Code CLI was not found on the machine running this agent.',
+ type: 'AgentRuntimeError',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error).toBeDefined();
+ expect(asst.error.body).toMatchObject({
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ });
+ expect(asst.error.message).toContain('was not found');
+ });
+
+ it('finish() projects the terminal error by assistant id after runningOperation was cleared', async () => {
+ // Gateway session completion can clear runningOperation before the CLI's
+ // heteroFinish request arrives. The producer-carried assistant id must
+ // keep that race from leaving an empty assistant with error=null.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ // The CLI echoed the failure into the answer before reporting it β€” that
+ // echo is what `clearEchoedContent` drops.
+ h.messages.get('asst-1')!.content = "You've hit your session limit";
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {},
+ });
+
+ await h.handler.finish({
+ assistantMessageId: 'asst-1',
+ error: {
+ body: {
+ agentType: 'claude-code',
+ clearEchoedContent: true,
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ },
+ message: "You've hit your session limit",
+ type: 'AgentRuntimeError',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error).toMatchObject({
+ body: {
+ agentType: 'claude-code',
+ code: 'rate_limit',
+ },
+ message: "You've hit your session limit",
+ type: 'AgentRuntimeError',
+ });
+ expect(asst.content).toBe('');
+ });
+
+ it('finish() keeps real work when a quota error only marks an echo', async () => {
+ // Kimi Code can burn a full run and only then hit its weekly window. The
+ // finish error carries clearEchoedContent (every rate_limit does), but
+ // the streamed answer is not an echo of it and must survive.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.messages.get('asst-1')!.content = 'Refactored the adapter and ran the tests.';
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {},
+ });
+
+ await h.handler.finish({
+ assistantMessageId: 'asst-1',
+ error: {
+ body: {
+ agentType: 'kimi-code',
+ clearEchoedContent: true,
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ },
+ message: "You've reached your weekly (7-day) usage limit.",
+ type: 'AgentRuntimeError',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.content).toBe('Refactored the adapter and ran the tests.');
+ expect(asst.error).toMatchObject({ body: { agentType: 'kimi-code', code: 'rate_limit' } });
+ });
+
+ it('finish() with no state stays a no-op for a stale operation (mismatched runningOperation)', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ // The topic's runningOperation belongs to a DIFFERENT operation β€” a late
+ // finish from a superseded run must not touch the current turn.
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'asst-other',
+ operationId: 'op-OTHER',
+ },
+ },
+ });
+
+ await expect(
+ h.handler.finish({
+ error: { message: 'boom', type: 'AgentRuntimeError' },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(h.messages.get('asst-1')!.error).toBeUndefined();
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ });
+
+ it('finish() drops the per-operation state so a retry starts fresh', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'a' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ await h.handler.finish({ operationId: 'op-1', result: 'success' });
+
+ // Same operationId on a different topic should now succeed (state was dropped)
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic-2',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'asst-2',
+ operationId: 'op-1',
+ },
+ },
+ });
+ h.messages.set('asst-2', {
+ agentId: null,
+ content: '',
+ id: 'asst-2',
+ role: 'assistant',
+ topicId: 'topic-2',
+ });
+
+ await expect(
+ h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'b' })],
+ operationId: 'op-1',
+ topicId: 'topic-2',
+ }),
+ ).resolves.not.toThrow();
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.test.ts
new file mode 100644
index 00000000000..8e5af217830
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.test.ts
@@ -0,0 +1,606 @@
+// @vitest-environment node
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness } from './testUtils';
+
+describe('HeterogeneousPersistenceHandler', () => {
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ afterEach(() => {
+ __resetOperationStatesForTesting();
+ });
+
+ describe('state bootstrap', () => {
+ it('reads runningOperation from topic.metadata to find the seeded assistantMessageId', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-seeded',
+ operationId: 'op-1',
+ topicAgentId: 'agent-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hello ' }),
+ buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'world' }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(h.topicModel.findById).toHaveBeenCalledWith('topic-1');
+ // Text chunks accumulate; flushed to DB at end of each batch (multi-replica fix)
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-seeded', { content: 'hello world' });
+ });
+
+ it('throws when the topic has no matching runningOperation', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'asst-other',
+ operationId: 'op-OTHER',
+ },
+ },
+ });
+
+ await expect(
+ h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/Stale hetero operation/);
+ });
+
+ it('rejects seeded assistant ids once runningOperation has been cleared', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {} as any,
+ });
+
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/no active runningOperation/);
+ });
+
+ it('keeps persisting when the marker is gone but the operation is still running', async () => {
+ // The marker is a rendering pointer any client can settle β€” a transport
+ // signal (a raw session_complete, or one multiplexed socket failing auth
+ // for every operation on the tab) clears it while the CLI keeps
+ // streaming. Refusing here discards the rest of a live run's output.
+ const isOperationLiveOnTopic = vi.fn(async () => true);
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {} as any,
+ });
+
+ await h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'kept' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(isOperationLiveOnTopic).toHaveBeenCalledWith('op-1', 'topic-1');
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-1', { content: 'kept' });
+ });
+
+ it('recovers the assistant pointer from heteroCurrentMsgId when the marker is gone', async () => {
+ // Desktop / old-CLI callers forward no assistantMessageId, so once the
+ // marker is gone the operation-scoped `heteroCurrentMsgId` is the only
+ // pointer left to the turn in flight.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic: async () => true,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: { heteroCurrentMsgId: { msgId: 'asst-1', operationId: 'op-1' } } as any,
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'kept' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-1', { content: 'kept' });
+ });
+
+ it('still refuses a marker-less batch once the operation row is terminal', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic: async () => false,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {} as any,
+ });
+
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/no active runningOperation/);
+ });
+
+ it('refuses a superseded batch even while its own operation row is alive', async () => {
+ // Liveness must NOT override ownership: a marker naming another run means
+ // the topic has moved on, and writing here would mutate a newer turn.
+ const isOperationLiveOnTopic = vi.fn(async () => true);
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ runningOperation: { assistantMessageId: 'asst-other', operationId: 'op-OTHER' },
+ },
+ });
+
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/current operation is op-OTHER/);
+ expect(isOperationLiveOnTopic).not.toHaveBeenCalled();
+ });
+
+ it('validates seeded assistant ids belong to the current topic', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ h.messages.set('asst-other-topic', {
+ agentId: null,
+ content: '',
+ id: 'asst-other-topic',
+ role: 'assistant',
+ topicId: 'topic-2',
+ });
+
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: 'asst-other-topic',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/does not belong to topic topic-1/);
+ });
+
+ it('rejects mid-flight topic mismatch on the same operationId', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(
+ h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'y' })],
+ operationId: 'op-1',
+ topicId: 'topic-OTHER',
+ }),
+ ).rejects.toThrow(/already bound to topic/);
+ });
+ });
+
+ describe('idempotency', () => {
+ it('replaces text with the latest full snapshot and ignores older snapshot seq values', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'text',
+ content: 'hello world',
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent(
+ 'stream_chunk',
+ 0,
+ {
+ chunkType: 'text',
+ content: 'hello',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ },
+ 1_700_000_000_999,
+ ),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.content).toBe('hello world');
+ expect(asst.metadata?.heteroTextSnapshotSeq).toBe(2);
+ });
+
+ it('replaces reasoning snapshots idempotently instead of re-appending on redelivery', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'reasoning',
+ reasoning: 'thinking hard',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Redelivery reaching the reducer (a cold replica has an empty
+ // processedKeys map β€” simulated here with a different timestamp so the
+ // in-memory dedupe does not swallow the event first). A raw delta would
+ // re-append and durably double the reasoning; the snapshot must not.
+ await h.handler.ingest({
+ events: [
+ buildEvent(
+ 'stream_chunk',
+ 0,
+ {
+ chunkType: 'reasoning',
+ reasoning: 'thinking hard',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ },
+ 1_700_000_000_999,
+ ),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.reasoning?.content).toBe('thinking hard'); // NOT doubled
+ expect(asst.metadata?.heteroReasoningSnapshotSeq).toBe(1);
+ });
+
+ it('drops events with the same (stepIndex, type, timestamp, dataFingerprint) key', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const tools = [
+ {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-1',
+ identifier: 'bash',
+ type: 'default',
+ },
+ ];
+ const evt = buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: tools,
+ });
+
+ await h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' });
+ const createCallsAfterFirst = h.messageModel.create.mock.calls.length;
+
+ await h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' });
+
+ // Same event re-ingested β†’ idempotency skips it; no extra tool-message create
+ expect(h.messageModel.create.mock.calls.length).toBe(createCallsAfterFirst);
+ });
+
+ it('gates publishing per operation and releases the gate when the operation finishes', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const first = buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' });
+ const second = buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'y' });
+
+ // Without operation state (nothing ingested yet, or a cold replica):
+ // treat everything as unpublished and latch nothing β€” degraded
+ // republish-all rather than silently dropping events.
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
+ h.handler.markEventPublished('op-1', first);
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
+
+ await h.handler.ingest({ events: [first, second], operationId: 'op-1', topicId: 'topic-1' });
+
+ // Latch per event: only unlatched events remain.
+ h.handler.markEventPublished('op-1', first);
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([second]);
+ h.handler.markEventPublished('op-1', second);
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([]);
+
+ // finish() drops the per-operation state β€” the gate goes with it.
+ await h.handler.finish({ operationId: 'op-1', result: 'success' });
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
+ });
+
+ it('does NOT collide bursty events sharing (stepIndex, type, timestamp) when their data differs', async () => {
+ // Producer-side reality: CC adapters stamp every event with `Date.now()`,
+ // so multiple `stream_chunk` events within the same step burst through
+ // a single millisecond. Without a content fingerprint in the dedupe
+ // key, all but the first would be dropped β†’ truncated assistant text.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const sameTimestamp = 1_700_000_000_000;
+ const events: AgentStreamEvent[] = [
+ {
+ ...buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'one ' }),
+ timestamp: sameTimestamp,
+ },
+ {
+ ...buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'two ' }),
+ timestamp: sameTimestamp,
+ },
+ {
+ ...buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'three' }),
+ timestamp: sameTimestamp,
+ },
+ buildEvent('agent_runtime_end', 0, { reason: 'success' }),
+ ];
+
+ await h.handler.ingest({ events, operationId: 'op-1', topicId: 'topic-1' });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.content).toBe('one two three');
+ });
+
+ it('mark-processed-AFTER-success contract: a thrown handler leaves the event un-marked so retry replays it', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // First call to messageModel.update on asst-1 throws once.
+ let updateAttempts = 0;
+ const realUpdate = h.messageModel.update.getMockImplementation()!;
+ h.messageModel.update.mockImplementation(async (id: string, patch: any) => {
+ if (id === 'asst-1' && patch.metadata?.usage) {
+ updateAttempts += 1;
+ if (updateAttempts === 1) {
+ throw new Error('flaky');
+ }
+ }
+ return realUpdate(id, patch);
+ });
+
+ const evt = buildEvent('step_complete', 0, {
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 1, totalOutputTokens: 0, totalTokens: 1 },
+ });
+
+ // First attempt: handler throws.
+ await expect(
+ h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' }),
+ ).rejects.toThrow('flaky');
+
+ // Retry SAME event β€” the handler now succeeds because the flake is gone.
+ // Critical: the dedupe map didn't pre-mark the failed event, so this
+ // re-runs instead of skipping silently.
+ await h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.metadata).toEqual({
+ usage: { totalInputTokens: 1, totalOutputTokens: 0, totalTokens: 1 },
+ });
+ });
+ });
+
+ describe('3-phase tool persist (main agent)', () => {
+ it('keeps tool rows and post-tool assistants attributed to the direct target agent', async () => {
+ const h = createHarness({
+ assistantAgentId: 'agent-direct-target',
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicAgentId: 'agent-conversation-owner',
+ topicId: 'topic-1',
+ });
+
+ const tool = {
+ apiName: 'Read',
+ arguments: '{"file_path":"tool-proof.txt"}',
+ id: 'tc-1',
+ identifier: 'claude-code',
+ type: 'default' as const,
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('tool_result', 1, {
+ content: 'TOOL_CALL_MARKER',
+ isError: false,
+ toolCallId: 'tc-1',
+ }),
+ buildEvent('stream_start', 2, { newStep: true }),
+ buildEvent('stream_chunk', 3, {
+ chunkType: 'text',
+ content: 'TOOL_CALL_MARKER',
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const toolMessage = [...h.messages.values()].find((message) => message.role === 'tool');
+ const finalAssistant = [...h.messages.values()].find(
+ (message) => message.role === 'assistant' && message.id !== 'asst-1',
+ );
+
+ expect(toolMessage?.agentId).toBe('agent-direct-target');
+ expect(finalAssistant?.agentId).toBe('agent-direct-target');
+ expect(finalAssistant?.parentId).toBe('asst-1');
+ expect(finalAssistant?.content).toBe('TOOL_CALL_MARKER');
+ });
+
+ it('writes assistant.tools[] then tool message then backfilled result_msg_id in order', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Capture call order across both methods so we can assert phase
+ // sequence (renderer mutates the tools[] array in place across phases,
+ // so verifying post-mortem state on call args is unreliable; relative
+ // ordering of distinct mock invocations is the durable contract).
+ const order: string[] = [];
+ const origCreate = h.messageModel.create.getMockImplementation()!;
+ const origUpdate = h.messageModel.update.getMockImplementation()!;
+ h.messageModel.update.mockImplementation(async (id: string, patch: any) => {
+ if (id === 'asst-1') order.push('update-asst');
+ return origUpdate(id, patch);
+ });
+ h.messageModel.create.mockImplementation(async (input: any, id?: string) => {
+ order.push(input.role === 'tool' ? 'create-tool' : 'create-other');
+ return origCreate(input, id);
+ });
+
+ const tool = {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-1',
+ identifier: 'bash',
+ type: 'default' as const,
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'looking ' }),
+ buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('tool_result', 2, {
+ content: 'a.ts\nb.ts',
+ isError: false,
+ toolCallId: 'tc-1',
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Phase 1 (update-asst) β†’ Phase 2 (create-tool) β†’ Phase 3 (update-asst) β†’ batch flush (update-asst)
+ expect(order).toEqual(['update-asst', 'create-tool', 'update-asst', 'update-asst']);
+
+ // Tool message exists with content from tool_result + correct tool_call_id
+ const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
+ expect(toolMsg).toBeDefined();
+ expect(toolMsg?.tool_call_id).toBe('tc-1');
+ expect(toolMsg?.content).toBe('a.ts\nb.ts');
+
+ // Final assistant.tools[] carries the backfilled result_msg_id
+ const finalAsst = h.messages.get('asst-1')!;
+ expect(finalAsst.tools?.[0]).toMatchObject({
+ id: 'tc-1',
+ result_msg_id: toolMsg?.id,
+ });
+ expect(finalAsst.content).toBe('looking ');
+ });
+
+ it('skips tool_use that have already been persisted in the same turn', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const tool = {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-1',
+ identifier: 'bash',
+ type: 'default',
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const toolMessages = [...h.messages.values()].filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(1);
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
new file mode 100644
index 00000000000..b087dd170db
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
@@ -0,0 +1,368 @@
+import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type {
+ MainAgentIntent,
+ MainAgentReduceCtx,
+ SubagentIntent,
+} from '@lobechat/heterogeneous-agents';
+import { reduceMainAgent } from '@lobechat/heterogeneous-agents';
+import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';
+import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';
+import { createNanoId } from '@lobechat/utils';
+import debug from 'debug';
+
+import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
+
+import { persistCodexTurnProvenance } from '../heteroProvenance';
+import { applyMainIntent, applySubagentIntent } from './applyIntents';
+import { eventKey, operationStates } from './operationState';
+import {
+ loadOrCreateState,
+ refreshMainStateFromDb,
+ refreshSubagentRunsFromDb,
+ refreshToolMessageIndex,
+ syncAssistantPointerForAdvancedStep,
+} from './stateSync';
+import type { HeterogeneousPersistenceHandlerDeps, OperationState } from './types';
+
+export { __resetOperationStatesForTesting, StaleHeteroOperationError } from './operationState';
+export type { HeterogeneousPersistenceHandlerDeps } from './types';
+
+const log = debug('lobe-server:hetero-agent:persistence');
+
+const generateThreadId = () => `thd_${createNanoId(16)()}`;
+
+/** The raw text a CLI would have echoed into the answer for this failure. */
+const errorEchoText = (error: { body?: Record<string, unknown>; message?: string }): string => {
+ const body = error.body ?? {};
+ const candidate = [body.stderr, body.message, error.message].find(
+ (value): value is string => typeof value === 'string' && value.trim().length > 0,
+ );
+
+ return candidate ?? '';
+};
+
+/**
+ * Server-side persistence for `lh hetero exec` event streams. Mirrors the
+ * desktop renderer's `executeHeterogeneousAgent` (1.8k lines) for the DB
+ * concerns only β€” IPC, store dispatch, notifications, refresh hooks all
+ * live host-side and are intentionally absent here.
+ *
+ * Phase 2b scope:
+ *
+ * 1. 3-phase tool persist (assistant.tools[] pre-register β†’ tool message
+ * create β†’ backfill `result_msg_id`)
+ * 2. Subagent thread + per-turn assistant chaining + finalize on parent
+ * tool_result
+ * 3. Step boundary handling (new assistant per `stream_start { newStep }`)
+ * 4. Per-turn metadata persistence (`step_complete` w/ `phase=turn_metadata`)
+ * 5. Final content / reasoning flush on `agent_runtime_end` / `error`
+ *
+ * Failure semantics (differs from the renderer's optimistic UI posture):
+ *
+ * - DB writes propagate exceptions instead of swallowing them. A throw
+ * bubbles to `ingest`, leaving the offending event un-marked in
+ * `processedKeys` so the BatchIngester's outer retry replays it.
+ * Idempotent state updates (per-tool `persistedIds`, payload de-dup,
+ * `ThreadModel.onConflictDoNothing`) make replays safe.
+ * - Renderer-only "log + continue" no longer applies β€” the server is
+ * authoritative for cloud runs, so silent partial writes would diverge
+ * DB from what the WS subscribers see.
+ *
+ * Multi-replica caveat: state is per-Node-process. Cloud sandbox routing
+ * must be sticky to a single replica per operationId, otherwise turn
+ * boundaries on the second replica would lose the chain-parent and
+ * pre-existing tool map. (Phase 3 sandbox owns the endpoint per-instance,
+ * so this is not a problem in practice.)
+ */
+export class HeterogeneousPersistenceHandler {
+ private readonly deps: HeterogeneousPersistenceHandlerDeps;
+
+ constructor(deps: HeterogeneousPersistenceHandlerDeps) {
+ this.deps = deps;
+ }
+
+ /**
+ * Process a batch of events for an operation. Sequential within the batch.
+ *
+ * Idempotency contract: an event is marked `processed` ONLY after its
+ * handler resolves cleanly. If a handler throws, the event stays unmarked
+ * so a follow-up retry processes it again, and the throw bubbles to
+ * `heteroIngest` β†’ tRPC β†’ BatchIngester so the producer re-sends. Events
+ * that already succeeded earlier in the batch are skipped on retry via
+ * the dedupe map, so the retry only re-runs the failed event onward.
+ */
+ async ingest(params: {
+ assistantMessageId?: string;
+ events: AgentStreamEvent[];
+ operationId: string;
+ topicId: string;
+ }): Promise<void> {
+ const state = await loadOrCreateState(
+ this.deps,
+ params.operationId,
+ params.topicId,
+ params.assistantMessageId,
+ );
+ const batchMaxStepIndex = Math.max(...params.events.map((event) => event.stepIndex));
+
+ // A different Lambda may have already processed `stream_start { newStep }`
+ // and persisted `heteroCurrentMsgId` for this operation. Warm instances keep
+ // their operation state in memory, so without an explicit resync they would
+ // keep appending later-step chunks to the PREVIOUS assistant row. Only resync
+ // when the incoming batch advances beyond the step this instance has seen.
+ if (batchMaxStepIndex > state.lastStepIndex) {
+ await syncAssistantPointerForAdvancedStep(this.deps, state);
+ }
+
+ await refreshToolMessageIndex(this.deps, state);
+ await refreshMainStateFromDb(this.deps, state);
+ await refreshSubagentRunsFromDb(this.deps, state);
+
+ for (const event of params.events) {
+ const key = eventKey(event);
+ if (state.processedKeys.has(key)) {
+ log('skip duplicate event %s op=%s', key, state.operationId);
+ continue;
+ }
+
+ // NOTE: do NOT mark `processed` before the handler runs. Marking up
+ // front would silently swallow event-level failures β€” the BatchIngester
+ // would ack OK while DB state diverges from the renderer's view. Mark
+ // only on success so a retry can complete the lost write.
+ await this.handleEvent(state, event);
+ state.processedKeys.add(key);
+ state.lastStepIndex = Math.max(state.lastStepIndex, event.stepIndex);
+ }
+
+ // Flush accumulated content after every batch so a subsequent replica
+ // picking up this operation always sees the latest content in the DB,
+ // even if it never processes a step boundary or terminal event.
+ await this.flushBatchContent(state);
+ }
+
+ /**
+ * Events of the batch not yet successfully published to the live stream.
+ * See `OperationState.publishedKeys` for why this gate is separate from
+ * the persistence dedupe. Without state (already finished, or a retry on
+ * a cold replica) every event is treated as unpublished β€” degrading to
+ * republish-all. Main-agent text/reasoning survive that via their
+ * `replace`-snapshot seq guards; the accepted cross-replica residuals are
+ * subagent text (append semantics), tool lifecycle replays (benign client
+ * upserts), and a duplicate trace fold β€” closing those needs a durable
+ * publish identity (tracked follow-up), not a bigger in-memory map.
+ */
+ filterUnpublishedEvents(operationId: string, events: AgentStreamEvent[]): AgentStreamEvent[] {
+ const state = operationStates.get(operationId);
+ if (!state) return events;
+
+ return events.filter((event) => !state.publishedKeys.has(eventKey(event)));
+ }
+
+ /** Latch an event as published so a batch retry skips its XADD. */
+ markEventPublished(operationId: string, event: AgentStreamEvent): void {
+ operationStates.get(operationId)?.publishedKeys.add(eventKey(event));
+ }
+
+ /**
+ * Flush trailing accumulators and drop the per-operation state.
+ *
+ * Resume id source: CC's `--resume <sessionId>` token comes from the
+ * adapter's cached `system:init.session_id`. The heterogeneous-agent service
+ * settles topic-level resume ownership after this flush.
+ *
+ * Use when:
+ * - A heterogeneous operation reaches a terminal producer callback.
+ *
+ * Expects:
+ * - The operation state was created by ingest or can be bootstrapped from the topic marker.
+ *
+ * Returns:
+ * - A promise that resolves after any finish-only error is projected and state is released.
+ */
+ async finish(params: {
+ assistantMessageId?: string;
+ error?: { body?: Record<string, unknown>; message: string; type: string };
+ operationId: string;
+ result: 'success' | 'error' | 'cancelled';
+ /**
+ * Needed to bootstrap state for a failed run that never ingested: a
+ * process-level failure (spawn ENOENT, auth printed straight to stderr)
+ * produces ZERO stream events, so no ingest ever created an
+ * `OperationState` for this op.
+ */
+ topicId?: string;
+ }): Promise<void> {
+ let state = operationStates.get(params.operationId);
+
+ // A run that died before producing any stream event has no state β€” but its
+ // terminal error must still land on the assistant message HERE, before the
+ // caller publishes `agent_runtime_end`. The client refetches messages on
+ // that event, so deferring the write to CompletionLifecycle (which runs
+ // after the publish) races the refetch and the error card doesn't render
+ // live. Bootstrap from topic.metadata.runningOperation like ingest does;
+ // a stale/mismatched operation stays a no-op.
+ if (!state && params.result === 'error' && params.error && params.topicId) {
+ try {
+ state = await loadOrCreateState(
+ this.deps,
+ params.operationId,
+ params.topicId,
+ params.assistantMessageId,
+ true,
+ );
+ } catch (error) {
+ log(
+ 'finish bootstrap failed op=%s topic=%s err=%O',
+ params.operationId,
+ params.topicId,
+ error,
+ );
+ return;
+ }
+ }
+ if (!state) return;
+
+ try {
+ if (params.error) await this.persistFinishError(state, params.error);
+ } finally {
+ operationStates.delete(params.operationId);
+ }
+ }
+
+ /**
+ * Persist the CLI's native session id onto `topic.metadata.heteroSessionId`.
+ * `TopicModel.updateMetadata` merges into existing JSONB so this does NOT
+ * clobber `runningOperation` / `workingDirectory` / other peer fields.
+ */
+ private async persistSessionId(topicId: string, sessionId: string): Promise<void> {
+ try {
+ await this.deps.topicModel.updateMetadata(topicId, { heteroSessionId: sessionId });
+ log('persisted sessionId topic=%s sessionId=%s', topicId, sessionId);
+ } catch (err) {
+ log('persistSessionId failed topic=%s err=%O', topicId, err);
+ }
+ }
+
+ // ─── Event dispatch ──────────────────────────────────────────────────────
+
+ private async handleEvent(state: OperationState, event: AgentStreamEvent): Promise<void> {
+ await this.reduceAndApply(state, event);
+ }
+
+ // ─── Main-agent reducer interpreter ──────────────────────────────────────
+
+ private mainReduceCtx(state: OperationState): MainAgentReduceCtx {
+ return {
+ agentId: state.agentId,
+ newId: (kind) => (kind === 'thread' ? generateThreadId() : `msg_${createNanoId(18)()}`),
+ topicId: state.topicId,
+ };
+ }
+
+ /**
+ * Single reducer entry point for the server persistence path. The reducer owns
+ * both the main thread and nested subagent runs; this interpreter only applies
+ * declarative intents to DB models. State commits after every intent succeeds,
+ * so a failing DB write leaves the event unmarked and the BatchIngester retry
+ * replays it against the previous reducer state.
+ */
+ private async reduceAndApply(state: OperationState, event: AgentStreamEvent) {
+ // Capture the CC-native session id off the stream_start stream so every
+ // message persisted below carries the session it belongs to. Stable per
+ // run; the copy is what makes a mid-topic session fork detectable.
+ if (event.type === 'stream_start') {
+ const sid = (event.data as { sessionId?: string } | undefined)?.sessionId;
+ if (typeof sid === 'string' && sid.length > 0 && sid !== state.heteroSessionId) {
+ state.heteroSessionId = sid;
+ // Persist the resume token the moment CC reports it, not only on a clean
+ // `finish()`. A stuck run is abandoned by the inactivity watchdog via
+ // AbandonOperationService, which never calls finish() β€” so a run that
+ // produced a valid session id but got killed before finishing would
+ // otherwise leave `topic.metadata.heteroSessionId` empty, forcing the
+ // next turn to spawn a fresh CC session and drop all `--resume` history.
+ // Writing it here makes resume survive abandon. The terminal service
+ // path may still overwrite it after verifying topic ownership.
+ await this.persistSessionId(state.topicId, sid);
+ }
+ }
+
+ if (event.type === 'stream_start' && typeof event.data?.codexTurnId === 'string') {
+ state.codexTurnId = event.data.codexTurnId;
+ await persistCodexTurnProvenance(this.deps.messageModel, state);
+ }
+
+ const { intents, state: next } = reduceMainAgent(state.main, event, this.mainReduceCtx(state));
+
+ for (const intent of intents) {
+ if ('threadId' in intent) {
+ await applySubagentIntent(this.deps, state, intent as SubagentIntent);
+ } else {
+ await applyMainIntent(this.deps, state, intent as MainAgentIntent, event.stepIndex);
+ }
+ }
+
+ state.main = next;
+ }
+
+ /**
+ * Persist an error supplied only by `heteroFinish` without rewriting streamed content.
+ *
+ * `heteroIngest` is the single writer for content and reasoning. A finish request can
+ * reach a warm serverless replica whose accumulator predates a newer snapshot written
+ * by another replica; replaying that accumulator here would roll the final answer back.
+ */
+ private async persistFinishError(
+ state: OperationState,
+ error: { body?: Record<string, unknown>; message: string; type: string },
+ ) {
+ const updateValue: Record<string, any> = {};
+ const clearsEcho = error.body?.clearEchoedContent === true;
+ // One read serves both decisions below.
+ const persisted =
+ clearsEcho || !isHeteroStatusGuideErrorData(error.body)
+ ? await this.deps.messageModel.findById(state.main.currentAssistantId)
+ : undefined;
+ // `clearEchoedContent` marks an error the CLI may ALSO have printed into
+ // the answer β€” it does not mean the answer is disposable. Quota rejections
+ // carry the flag too, and a run that worked for ten minutes before its
+ // weekly window closed must keep what it wrote, so only an exact echo is
+ // dropped (same rule as the client and the coordinator reducer).
+ if (clearsEcho && isEchoedErrorText(persisted?.content, errorEchoText(error))) {
+ updateValue.content = '';
+ }
+ // Same canonical normalization as the in-stream `setError` path β€” the CLI's
+ // free-form `{ message, type }` runs through formatErrorForState so the
+ // finish-only write and the in-stream write produce one classified error shape.
+ // A structured `body` (status-guide error: agentType + code) passes
+ // through untouched β€” the client's guide UI gates on it.
+ //
+ // Never DOWNGRADE, though: the in-stream `setError` path may already have
+ // persisted the adapter's classified status-guide error on this assistant,
+ // while older CLIs flatten the finish error to a bare `{ message }`.
+ // Overwriting would demote the client from the dedicated guide card to
+ // the generic error alert β€” keep the richer persisted error instead.
+ const overwritesGuideError =
+ !isHeteroStatusGuideErrorData(error.body) &&
+ isHeteroStatusGuideErrorData(persisted?.error?.body);
+ if (!overwritesGuideError) updateValue.error = formatErrorForState(error);
+
+ if (Object.keys(updateValue).length > 0) {
+ await this.deps.messageModel.update(state.main.currentAssistantId, updateValue);
+ }
+ }
+
+ /**
+ * Write accumulated content/reasoning to DB after every ingest batch.
+ * This ensures a subsequent replica always finds the latest text in the DB
+ * even if the current replica never processes a step-boundary or terminal
+ * event (which are the normal flush triggers).
+ */
+ private async flushBatchContent(state: OperationState): Promise<void> {
+ if (!state.main.accContent && !state.main.accReasoning) return;
+ const update: Record<string, any> = {};
+ if (state.main.accContent) update.content = state.main.accContent;
+ if (state.main.accReasoning) update.reasoning = { content: state.main.accReasoning };
+ if (Object.keys(state.main.turnMetadata).length > 0) update.metadata = state.main.turnMetadata;
+ await this.deps.messageModel.update(state.main.currentAssistantId, update);
+ }
+}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
new file mode 100644
index 00000000000..69dbd514c7e
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
@@ -0,0 +1,302 @@
+import {
+ type AgentInterventionInteractionKind,
+ type AgentInterventionProvider,
+ type AgentInterventionRequestData,
+ sanitizeAgentInterventionRequestForReview,
+} from '@lobechat/agent-gateway-client';
+import type {
+ MainAgentIntent,
+ MainAgentInterventionTransition,
+} from '@lobechat/heterogeneous-agents';
+
+import {
+ deriveAgentInterventionActivityKey,
+ hashAgentInterventionRequestRevision,
+} from '@/business/server/agent-run/agentInterventionIdentity';
+import {
+ acknowledgeAgentInterventionProducerResolution,
+ type AgentInterventionAllowedAction,
+ type AgentInterventionReviewDetail,
+ notifyAgentInterventionRequired,
+ type NotifyAgentInterventionRequiredParams,
+} from '@/business/server/agent-run/agentInterventionReview';
+
+import type { HeterogeneousPersistenceHandlerDeps, OperationState } from './types';
+
+interface StoredHeterogeneousIntervention {
+ deadline?: number;
+ interactionKind?: AgentInterventionInteractionKind;
+ notificationTransition?: MainAgentInterventionTransition;
+ provider?: AgentInterventionProvider;
+ resolutionRequestId?: string;
+ summary?: string;
+ transition?: MainAgentInterventionTransition;
+}
+
+export const HETEROGENEOUS_INTERVENTION_STATE_KEY = 'heterogeneousIntervention';
+const MAX_INTERVENTION_SUMMARY_LENGTH = 160;
+
+const interventionSummary = (
+ request?: AgentInterventionRequestData,
+ reviewDetail?: Extract<
+ AgentInterventionReviewDetail,
+ { type: 'permission' | 'plan' | 'question' }
+ >,
+): string => {
+ if (reviewDetail?.type === 'question') {
+ const question = reviewDetail.questions[0]?.question.trim().replaceAll(/\s+/g, ' ');
+ if (question) {
+ const characters = [...question];
+ return characters.length > MAX_INTERVENTION_SUMMARY_LENGTH
+ ? `${characters.slice(0, MAX_INTERVENTION_SUMMARY_LENGTH - 1).join('')}…`
+ : question;
+ }
+ }
+
+ const provider = request?.provider ?? 'heterogeneous-agent';
+ const kind = request?.interactionKind ?? 'question';
+ const apiName = request?.apiName || 'interaction';
+ return `${provider} ${kind}: ${apiName}`.slice(0, MAX_INTERVENTION_SUMMARY_LENGTH);
+};
+
+const buildHeterogeneousReviewDetail = (
+ request: AgentInterventionRequestData,
+): Extract<AgentInterventionReviewDetail, { type: 'permission' | 'plan' | 'question' }> => {
+ const parsed = JSON.parse(request.arguments) as {
+ questions: Array<{
+ header: string;
+ multiSelect: boolean;
+ options: Array<{ description?: string; id?: string; label: string }>;
+ question: string;
+ }>;
+ };
+ const questions = parsed.questions.map((question, questionIndex) => ({
+ header: question.header || undefined,
+ id: `question_${questionIndex + 1}`,
+ multiple: question.multiSelect,
+ options: question.options.map((option) => ({
+ description: option.description,
+ id: option.id ?? option.label,
+ label: option.label,
+ })),
+ question: question.question,
+ }));
+ const first = questions[0];
+
+ switch (request.interactionKind) {
+ case 'permission': {
+ return {
+ description: first.header,
+ options: first.options,
+ title: first.question,
+ type: 'permission',
+ };
+ }
+ case 'plan': {
+ return {
+ content: first.question,
+ options: first.options,
+ title: first.header ?? 'Review plan',
+ type: 'plan',
+ };
+ }
+ case 'question': {
+ return {
+ // The shared AskUser form offers "write your own" on every question,
+ // plus whole-form freeform and a supplement note, and the producer's
+ // bridge formats all three. Declare them so the claim accepts typed
+ // answers instead of treating them as off-list selections.
+ answerPolicy: { allowFreeform: true, allowSupplement: true },
+ questions: questions.map((question) => ({ ...question, allowCustomAnswer: true })),
+ title: first.header,
+ type: 'question',
+ };
+ }
+ default: {
+ throw new Error('Unsupported heterogeneous intervention kind');
+ }
+ }
+};
+
+const heterogeneousActionsFor = (
+ interactionKind: AgentInterventionInteractionKind,
+): AgentInterventionAllowedAction[] =>
+ interactionKind === 'question'
+ ? ['submit_answers', 'skip_interaction']
+ : ['select_provider_option', 'skip_interaction'];
+
+export const INTERVENTION_TRANSITIONS = new Set<MainAgentInterventionTransition>([
+ 'cancelled',
+ 'pending',
+ 'resolved',
+ 'session_ended',
+ 'timed_out',
+]);
+
+export const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([
+ 'permission',
+ 'plan',
+ 'question',
+]);
+
+export const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>([
+ 'claude-code',
+ 'cursor',
+ 'devin',
+ 'droid',
+ 'qoder',
+]);
+
+export async function applyToolIntervention(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+ intent: Extract<MainAgentIntent, { kind: 'setToolIntervention' }>,
+ stepIndex: number,
+): Promise<void> {
+ const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);
+ if (!toolMsgId) {
+ throw new Error(
+ `intervention for unknown toolCallId=${intent.toolCallId} op=${state.operationId}`,
+ );
+ }
+
+ const reviewRequest = sanitizeAgentInterventionRequestForReview(intent.request);
+ const reviewDetail = reviewRequest ? buildHeterogeneousReviewDetail(reviewRequest) : undefined;
+ const summary = interventionSummary(intent.request, reviewDetail);
+ const transitionKey = `${state.operationId}:${intent.toolCallId}:${intent.transition}`;
+ const pendingTransitionKey = `${state.operationId}:${intent.toolCallId}:pending`;
+ const requiresPendingReviewNotification =
+ !!deps.userId &&
+ !state.notifiedInterventionTransitions.has(transitionKey) &&
+ !state.notifiedInterventionTransitions.has(pendingTransitionKey);
+ if (
+ requiresPendingReviewNotification &&
+ (!reviewRequest?.interactionKind || !reviewRequest.provider || !reviewDetail)
+ ) {
+ throw new Error(
+ `Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,
+ );
+ }
+ const durableState: StoredHeterogeneousIntervention = {
+ deadline: intent.request?.deadline,
+ interactionKind: intent.request?.interactionKind,
+ provider: intent.request?.provider,
+ resolutionRequestId: intent.resolutionRequestId,
+ summary,
+ transition: intent.transition,
+ };
+
+ // Persist before any business side effect. The existing JSON plugin-state
+ // column carries only correlation metadata; no schema/migration is needed.
+ await deps.messageModel.updateMessagePlugin(toolMsgId, {
+ intervention: intent.intervention,
+ });
+ await deps.messageModel.updatePluginState(toolMsgId, {
+ [HETEROGENEOUS_INTERVENTION_STATE_KEY]: durableState,
+ });
+
+ if (!deps.userId || state.notifiedInterventionTransitions.has(transitionKey)) return;
+
+ if (!state.notifiedInterventionTransitions.has(pendingTransitionKey)) {
+ if (!reviewRequest?.interactionKind || !reviewRequest.provider || !reviewDetail) {
+ throw new Error(
+ `Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,
+ );
+ }
+ const assistantMessageId = state.main.currentAssistantId;
+ if (!assistantMessageId) {
+ throw new Error(
+ `Missing assistant owner for heterogeneous intervention toolCallId=${intent.toolCallId}`,
+ );
+ }
+ // Heterogeneous callbacks are individually sealed. Include the tool call
+ // so two concurrent interventions emitted by one assistant step never
+ // claim the same batch identity with conflicting item-0 contents.
+ const batchId = `${state.operationId}:${stepIndex}:${assistantMessageId}:${intent.toolCallId}`;
+ // The generic Web source bridge reads the same authoritative correlation
+ // from the tool row. Stamp it before notify so a card can never appear
+ // actionable while its operation/batch locator is still absent.
+ await deps.messageModel.updateMessagePlugin(toolMsgId, {
+ intervention: {
+ ...intent.intervention,
+ batchId,
+ itemIndex: 0,
+ operationId: state.operationId,
+ stepIndex,
+ },
+ });
+ const allowedActions = heterogeneousActionsFor(reviewRequest.interactionKind);
+ const notification: NotifyAgentInterventionRequiredParams = {
+ agentId: state.agentId ?? undefined,
+ approvalMode: 'manual',
+ batch: {
+ activityKey: deriveAgentInterventionActivityKey({
+ batchId,
+ operationId: state.operationId,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ }),
+ allowedActions: [],
+ id: batchId,
+ kind: 'single',
+ sealed: true,
+ stepIndex,
+ },
+ context: {
+ agentId: state.agentId ?? undefined,
+ assistantMessageId,
+ operationId: state.operationId,
+ topicId: state.topicId,
+ workspaceId: deps.workspaceId,
+ },
+ deadline: reviewRequest.deadline,
+ items: [
+ {
+ allowedActions,
+ detail: reviewDetail,
+ interactionKind: reviewRequest.interactionKind,
+ provider: reviewRequest.provider,
+ requestRevision: {
+ hash: hashAgentInterventionRequestRevision(intent.request?.arguments ?? ''),
+ version: 1,
+ },
+ sourceRef: {
+ operationId: state.operationId,
+ toolCallId: intent.toolCallId,
+ type: 'heterogeneous',
+ },
+ summary,
+ surface: 'form',
+ },
+ ],
+ summary,
+ systemActionEligibility: 'review_only',
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ };
+ await notifyAgentInterventionRequired(notification);
+ state.notifiedInterventionTransitions.add(pendingTransitionKey);
+ }
+
+ if (intent.transition !== 'pending') {
+ await acknowledgeAgentInterventionProducerResolution({
+ operationId: state.operationId,
+ ownerUserId: deps.userId,
+ resolutionRequestId: intent.resolutionRequestId,
+ status: intent.transition,
+ toolCallId: intent.toolCallId,
+ workspaceId: deps.workspaceId,
+ });
+ }
+ state.notifiedInterventionTransitions.add(transitionKey);
+
+ // Cold-replica dedupe marker. Cloud's override must still use the same
+ // `(operationId, toolCallId, transition)` idempotency key because a process
+ // can die after the external side effect but before this best-effort stamp.
+ await deps.messageModel.updatePluginState(toolMsgId, {
+ [HETEROGENEOUS_INTERVENTION_STATE_KEY]: {
+ ...durableState,
+ notificationTransition: intent.transition,
+ },
+ });
+}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/operationState.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/operationState.ts
new file mode 100644
index 00000000000..dbf7eb589f6
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/operationState.ts
@@ -0,0 +1,72 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import type { OperationState } from './types';
+
+/**
+ * Stable 32-bit FNV-1a hash of a string. Cheap to compute, collision odds are
+ * negligible at this scope (a few thousand events per operation), and the
+ * output is short enough to keep the per-operation `processedKeys` set small.
+ */
+const fnv1a = (input: string): string => {
+ let hash = 0x81_1c_9d_c5;
+ for (let i = 0; i < input.length; i += 1) {
+ hash ^= input.charCodeAt(i);
+ // FNV prime 0x01000193, applied via bit shifts to stay in 32-bit math.
+ hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0;
+ }
+ return hash.toString(36);
+};
+
+/**
+ * Per-event idempotency key. CLI BatchIngester retries the SAME event objects
+ * on transient failures, so the same `(stepIndex, type, data)` triple is
+ * stable across retries β€” and distinct between back-to-back events even when
+ * they share a millisecond timestamp.
+ *
+ * Why not just `(stepIndex, type, timestamp)`: producers stamp events with
+ * `Date.now()` (see `claudeCode.ts` / `codex.ts` adapters), and CC bursts
+ * multiple `stream_chunk` events through the same step within a single
+ * millisecond. Without a content fingerprint, later chunks would collide with
+ * earlier ones, get treated as duplicates, and be dropped β€” silently
+ * truncating assistant output.
+ *
+ * Why not hash full `data`: tools_calling payloads can carry large argument
+ * strings; a stable JSON.stringify on every event is cheap enough but the
+ * resulting key would balloon the `processedKeys` set. Hashing keeps the key
+ * bounded.
+ */
+export const eventKey = (event: AgentStreamEvent): string => {
+ // Fingerprint the data via stable JSON. Order is irrelevant β€” adapters
+ // produce events with consistent key order, and even if they didn't, the
+ // important property is "same event input β†’ same output", which holds.
+ const dataJson = (() => {
+ try {
+ return JSON.stringify(event.data ?? null);
+ } catch {
+ // Cyclic / unstringifiable payload: fall back to a coarse fingerprint.
+ // Real wire data is always JSON-serializable, so this branch only fires
+ // on bad test inputs.
+ return String(typeof event.data);
+ }
+ })();
+ return `${event.stepIndex}:${event.type}:${event.timestamp}:${fnv1a(dataJson)}`;
+};
+
+/**
+ * Module-level singleton: `Map<operationId, OperationState>`. Service
+ * instances are constructed per-request via the tRPC procedure middleware,
+ * so per-instance state would not survive across requests. Keying off the
+ * shared map lets two ingest batches for the same operationId share their
+ * tool map / accumulated content / subagent runs.
+ */
+export const operationStates = new Map<string, OperationState>();
+
+/** Test-only reset hook to clear the singleton between specs. */
+export const __resetOperationStatesForTesting = () => operationStates.clear();
+
+export class StaleHeteroOperationError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'StaleHeteroOperationError';
+ }
+}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
new file mode 100644
index 00000000000..d1ef69d0a00
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -0,0 +1,608 @@
+import {
+ type AgentInterventionInteractionKind,
+ type AgentInterventionProvider,
+} from '@lobechat/agent-gateway-client';
+import { LOADING_FLAT } from '@lobechat/const';
+import type {
+ MainAgentInterventionTransition,
+ MainAgentTurnToolState,
+ SubagentRunSnapshot,
+ ToolCallPayload,
+} from '@lobechat/heterogeneous-agents';
+import {
+ createMainAgentRunState,
+ rehydrateSubagentRunsState,
+} from '@lobechat/heterogeneous-agents';
+import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types';
+import debug from 'debug';
+
+import { restoreHeteroProvenance } from '../heteroProvenance';
+import {
+ HETEROGENEOUS_INTERVENTION_STATE_KEY,
+ INTERVENTION_KINDS,
+ INTERVENTION_PROVIDERS,
+ INTERVENTION_TRANSITIONS,
+} from './intervention';
+import { operationStates, StaleHeteroOperationError } from './operationState';
+import type { HeterogeneousPersistenceHandlerDeps, OperationState } from './types';
+
+const log = debug('lobe-server:hetero-agent:persistence');
+
+interface AssistantDbSnapshot {
+ content: string;
+ metadata: Record<string, any>;
+ model: string | undefined;
+ parentId: string | null | undefined;
+ provider: string | undefined;
+ reasoning: string;
+ reasoningSnapshotSeq: number;
+ textSnapshotSeq: number;
+ tools: ChatToolPayload[];
+}
+
+interface AssistantMessageDbLike {
+ content?: unknown;
+ metadata?: Record<string, any> | null;
+ model?: string;
+ parentId?: string | null;
+ provider?: string;
+ reasoning?: { content?: string } | null;
+ tools?: ChatToolPayload[] | null;
+}
+
+export async function loadOrCreateState(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ operationId: string,
+ topicId: string,
+ seedAssistantMessageId?: string,
+ allowMissingRunningOperation = false,
+): Promise<OperationState> {
+ let state = operationStates.get(operationId);
+ if (state) {
+ // Defensive: caller mismatch on topicId would corrupt persistence β€”
+ // assert and throw rather than silently writing to the wrong topic.
+ if (state.topicId !== topicId) {
+ throw new Error(
+ `Operation ${operationId} is already bound to topic ${state.topicId}, not ${topicId}`,
+ );
+ }
+ return state;
+ }
+
+ const topic = await deps.topicModel.findById(topicId);
+ const marker = topic?.metadata?.runningOperation;
+ const running =
+ marker?.operationId === operationId
+ ? marker
+ : marker?.childOperations?.find((child) => child.operationId === operationId);
+
+ if (!running) {
+ // Two different fates were collapsed into one refusal here.
+ //
+ // A marker naming ANOTHER operation means a newer run owns the topic:
+ // this batch is genuinely late and has to be dropped, or it would keep
+ // mutating a turn the conversation has already moved past.
+ //
+ // NO marker at all is a different story. The marker is a best-effort
+ // rendering pointer that a client can settle on nothing more than a
+ // transport signal β€” a raw `session_complete`, or one multiplexed socket
+ // failing auth for every operation on the tab β€” while the producer is
+ // still running and streaming. Refusing there throws away the whole
+ // remaining output of a live CLI, which then burns minutes of work
+ // nobody stores. The operation row is the authority on liveness, so ask
+ // it: still `running`, still bound to THIS topic β‡’ keep persisting
+ // without a marker. The turn's own pointers (`heteroCurrentMsgId`, the
+ // seeded assistant message) carry the rest.
+ const producerStillOwnsTopic =
+ !marker && (await deps.isOperationLiveOnTopic?.(operationId, topicId));
+
+ if (producerStillOwnsTopic) {
+ log('marker missing but operation still running op=%s topic=%s', operationId, topicId);
+ } else if (!(allowMissingRunningOperation && seedAssistantMessageId)) {
+ throw new StaleHeteroOperationError(
+ marker
+ ? `Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${marker.operationId}`
+ : `Stale hetero operation ${operationId} on topic ${topicId}; no active runningOperation`,
+ );
+ }
+ }
+
+ // Prefer the assistantMessageId forwarded in the ingest payload (sandbox path).
+ // The orchestrator already has it in-memory and passes it through env β†’ CLI β†’ tRPC,
+ // so this path avoids depending on `runningOperation.assistantMessageId`
+ // itself being readable on this replica. We still require the topic's
+ // runningOperation binding to match `operationId`, otherwise late/retried
+ // batches after finish could keep mutating a completed turn.
+ // Fall back to topic.metadata for desktop / old-CLI callers that lack the field.
+ // `heteroCurrentMsgId` is the last resort and is scoped to this operation:
+ // it is the only pointer left once a marker has been cleared out from under
+ // a still-running producer (see the liveness check above).
+ const currentMsgIdForOperation =
+ topic?.metadata?.heteroCurrentMsgId?.operationId === operationId
+ ? topic?.metadata?.heteroCurrentMsgId?.msgId
+ : undefined;
+ const baseAssistantMessageId =
+ seedAssistantMessageId ?? running?.assistantMessageId ?? currentMsgIdForOperation;
+
+ if (!baseAssistantMessageId) {
+ throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);
+ }
+
+ const baseAssistantMessage = await deps.messageModel.findById(baseAssistantMessageId);
+
+ if (seedAssistantMessageId) {
+ if (!baseAssistantMessage) {
+ throw new Error(
+ `Seeded assistantMessageId ${seedAssistantMessageId} was not found for topic ${topicId}`,
+ );
+ }
+ if (baseAssistantMessage.topicId !== topicId) {
+ throw new Error(
+ `Seeded assistantMessageId ${seedAssistantMessageId} does not belong to topic ${topicId}`,
+ );
+ }
+ }
+
+ // Prefer the latest step's assistant message id (written by handleStepStart)
+ // over the initial placeholder β€” so a new replica after a step boundary uses
+ // the correct message rather than the stale initial one.
+ // Guard: only use heteroCurrentMsgId when it belongs to THIS operation.
+ // A stale value from a previous run must not override the new operation's
+ // seeded assistantMessageId (P1 fix).
+ const stored = topic?.metadata?.heteroCurrentMsgId;
+ const currentAssistantMessageId =
+ stored?.operationId === operationId
+ ? (stored.msgId ?? baseAssistantMessageId)
+ : baseAssistantMessageId;
+
+ state = {
+ // A direct @Agent run keeps the topic under the conversation owner while
+ // the seeded assistant belongs to the executing target Agent. Every
+ // follow-up step and tool row must inherit the assistant author, not the
+ // topic owner, or the post-tool answer appears to switch back to Lobe AI.
+ // Legacy/finish-only callers may not have a readable assistant row; keep
+ // the historical topic-owner fallback for those paths.
+ agentId: baseAssistantMessage?.agentId ?? topic?.agentId ?? null,
+ // Left undefined until the run's own stream_start reports it (or a cold
+ // replica recovers it from a stamped message). NOT seeded from
+ // topic.metadata.heteroSessionId: that holds the id we ASKED CC to resume,
+ // which differs from the actual id when a fork/new session occurred.
+ heteroSessionId: undefined,
+ sourceUserMessageId: baseAssistantMessage?.parentId ?? undefined,
+ lastStepIndex: 0,
+ lastAppliedToolStateSeqByCallId: new Map(),
+ main: createMainAgentRunState(currentAssistantMessageId),
+ operationId,
+ notifiedInterventionTransitions: new Set(),
+ processedKeys: new Set(),
+ publishedKeys: new Set(),
+ toolMsgIdByCallId: new Map(),
+ threadId: running?.threadId ?? undefined,
+ topicId,
+ };
+ await refreshToolMessageIndex(deps, state);
+ await refreshMainStateFromDb(deps, state);
+ operationStates.set(operationId, state);
+ log(
+ 'created state for operation %s on topic %s msgId=%s tools=%d restored(content=%d tools=%d)',
+ operationId,
+ topicId,
+ currentAssistantMessageId,
+ state.toolMsgIdByCallId.size,
+ state.main.accContent.length,
+ state.main.toolState.payloads.length,
+ );
+ return state;
+}
+
+function createEmptyMainToolState(): MainAgentTurnToolState {
+ return { payloads: [], persistedIds: new Set(), toolMsgIdByCallId: new Map() };
+}
+
+function toAssistantSnapshot(
+ message: AssistantMessageDbLike | null | undefined,
+): AssistantDbSnapshot {
+ const rawContent = (message?.content ?? '') as string;
+ const metadata = ((message?.metadata as Record<string, any> | null) ?? {}) as Record<string, any>;
+ const textSnapshotSeq = Number(metadata.heteroTextSnapshotSeq ?? 0);
+ const reasoningSnapshotSeq = Number(metadata.heteroReasoningSnapshotSeq ?? 0);
+ return {
+ content: rawContent === LOADING_FLAT ? '' : rawContent,
+ metadata,
+ model: message?.model,
+ parentId: message?.parentId,
+ provider: message?.provider,
+ reasoning: (message?.reasoning as { content?: string } | null)?.content ?? '',
+ reasoningSnapshotSeq: Number.isFinite(reasoningSnapshotSeq) ? reasoningSnapshotSeq : 0,
+ textSnapshotSeq: Number.isFinite(textSnapshotSeq) ? textSnapshotSeq : 0,
+ tools: (message?.tools ?? []) as ChatToolPayload[],
+ };
+}
+
+function toToolPayload(tool: ChatToolPayload): ToolCallPayload {
+ return {
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ id: tool.id,
+ identifier: tool.identifier,
+ type: tool.type,
+ };
+}
+
+function buildMainToolStateFromSnapshot(
+ snapshot: AssistantDbSnapshot,
+ toolMsgIdByCallId: Map<string, string>,
+): MainAgentTurnToolState {
+ const toolState = createEmptyMainToolState();
+ const seen = new Set<string>();
+
+ for (const tool of snapshot.tools) {
+ if (!tool.id || seen.has(tool.id)) continue;
+ const toolMessageId = tool.result_msg_id ?? toolMsgIdByCallId.get(tool.id);
+ if (!toolMessageId) continue;
+
+ seen.add(tool.id);
+ toolState.payloads.push(toToolPayload(tool));
+ toolState.persistedIds.add(tool.id);
+ toolState.toolMsgIdByCallId.set(tool.id, toolMessageId);
+ }
+
+ return toolState;
+}
+
+export async function refreshToolMessageIndex(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+): Promise<void> {
+ const toolPlugins = await deps.messageModel.listMessagePluginsByTopic(state.topicId);
+ for (const plugin of toolPlugins) {
+ if (plugin.toolCallId) state.toolMsgIdByCallId.set(plugin.toolCallId, plugin.id);
+ if (plugin.toolCallId && plugin.state && typeof plugin.state === 'object') {
+ const stored = (plugin.state as Record<string, unknown>)[
+ HETEROGENEOUS_INTERVENTION_STATE_KEY
+ ];
+ if (stored && typeof stored === 'object') {
+ const metadata = stored as Record<string, unknown>;
+ const transition = INTERVENTION_TRANSITIONS.has(
+ metadata.transition as MainAgentInterventionTransition,
+ )
+ ? (metadata.transition as MainAgentInterventionTransition)
+ : undefined;
+ const interactionKind = INTERVENTION_KINDS.has(
+ metadata.interactionKind as AgentInterventionInteractionKind,
+ )
+ ? (metadata.interactionKind as AgentInterventionInteractionKind)
+ : undefined;
+ const provider = INTERVENTION_PROVIDERS.has(metadata.provider as AgentInterventionProvider)
+ ? (metadata.provider as AgentInterventionProvider)
+ : undefined;
+
+ if (transition) {
+ const request =
+ typeof plugin.apiName === 'string' &&
+ typeof plugin.arguments === 'string' &&
+ typeof plugin.identifier === 'string' &&
+ typeof metadata.deadline === 'number'
+ ? {
+ apiName: plugin.apiName,
+ arguments: plugin.arguments,
+ deadline: metadata.deadline,
+ identifier: plugin.identifier,
+ interactionKind,
+ provider,
+ toolCallId: plugin.toolCallId,
+ }
+ : undefined;
+ state.main.interventionsByCallId.set(plugin.toolCallId, {
+ intervention:
+ plugin.intervention ??
+ (transition === 'pending'
+ ? { status: 'pending' }
+ : transition === 'resolved'
+ ? { status: 'approved' }
+ : { rejectedReason: transition, status: 'rejected' }),
+ request,
+ resolutionRequestId:
+ typeof metadata.resolutionRequestId === 'string'
+ ? metadata.resolutionRequestId
+ : undefined,
+ transition,
+ });
+
+ if (metadata.notificationTransition === transition) {
+ state.notifiedInterventionTransitions.add(
+ `${state.operationId}:${plugin.toolCallId}:${transition}`,
+ );
+ }
+ }
+ }
+ }
+ if (
+ plugin.toolCallId &&
+ plugin.metadata?.heterogeneousToolStateOperationId === state.operationId &&
+ typeof plugin.metadata.heterogeneousToolStateSeq === 'number'
+ ) {
+ state.lastAppliedToolStateSeqByCallId.set(
+ plugin.toolCallId,
+ Math.max(
+ state.lastAppliedToolStateSeqByCallId.get(plugin.toolCallId) ?? 0,
+ plugin.metadata.heterogeneousToolStateSeq,
+ ),
+ );
+ }
+ }
+}
+
+/**
+ * Rehydrate reducer state from the DB projection of the current assistant.
+ * This preserves the shared pure reducer as the single state machine while
+ * keeping the serverless-specific "another replica already wrote this"
+ * recovery outside the package.
+ */
+export async function refreshMainStateFromDb(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+): Promise<void> {
+ const currentMsg = await deps.messageModel.findById(state.main.currentAssistantId);
+ const snapshot = toAssistantSnapshot(currentMsg);
+
+ // Recover the in-flight turn's CC message.id so a replayed `newStep` (cold
+ // replica retry) is recognized as the SAME turn β€” no duplicate assistant,
+ // no usage-only empty shell. Mirrors the subagent path's recovery of
+ // `currentSubagentMessageId` from `metadata.subagentMessageId`.
+ if (typeof snapshot.metadata.mainMessageId === 'string') {
+ state.main.currentMainMessageId = snapshot.metadata.mainMessageId;
+ }
+
+ // Recover the run's CC session id from a previously-stamped message so a
+ // cold replica that never saw this run's stream_start still stamps the
+ // right session id on the messages it persists.
+ restoreHeteroProvenance(state, snapshot.metadata);
+
+ if (snapshot.textSnapshotSeq > state.main.lastTextSnapshotSeq) {
+ state.main.accContent = snapshot.content;
+ state.main.lastTextSnapshotSeq = snapshot.textSnapshotSeq;
+ state.main.turnMetadata = snapshot.metadata;
+ } else {
+ if (snapshot.content.length > state.main.accContent.length) {
+ state.main.accContent = snapshot.content;
+ }
+ if (
+ Object.keys(state.main.turnMetadata).length === 0 &&
+ Object.keys(snapshot.metadata).length > 0
+ ) {
+ state.main.turnMetadata = snapshot.metadata;
+ }
+ }
+
+ // Seq-guarded reasoning restore mirrors the text path above; the length
+ // heuristic stays as the fallback for legacy rows without a stamped seq.
+ if (snapshot.reasoningSnapshotSeq > state.main.lastReasoningSnapshotSeq) {
+ state.main.accReasoning = snapshot.reasoning;
+ state.main.lastReasoningSnapshotSeq = snapshot.reasoningSnapshotSeq;
+ } else if (snapshot.reasoning.length > state.main.accReasoning.length) {
+ state.main.accReasoning = snapshot.reasoning;
+ }
+
+ const dbToolState = buildMainToolStateFromSnapshot(snapshot, state.toolMsgIdByCallId);
+ for (const [toolCallId, toolMessageId] of dbToolState.toolMsgIdByCallId) {
+ state.toolMsgIdByCallId.set(toolCallId, toolMessageId);
+ }
+ if (
+ dbToolState.payloads.length > state.main.toolState.payloads.length ||
+ dbToolState.persistedIds.size > state.main.toolState.persistedIds.size
+ ) {
+ state.main.toolState = dbToolState;
+ }
+
+ if (snapshot.model) state.main.turnModel = snapshot.model;
+ if (snapshot.provider) state.main.turnProvider = snapshot.provider;
+
+ // Recover the chain spine from the DB. The next normal
+ // turn parents off the run's latest main-thread message that is neither a
+ // tool nor a TOOLLESS signal callback (a tools-bearing signal turn is
+ // main-chain β€” see `getLatestSpineMessageId`); reading it straight
+ // from the DB (independent of
+ // `currentAssistantId`, which can regress to the seed placeholder on a cold
+ // / non-sticky replica β€” see the multi-replica caveat on the class) keeps
+ // consecutive cold-replica steps chained linearly instead of forking onto a
+ // stale node. Signal turns still anchor off `lastToolMsgIdEver`, which is
+ // maintained in-memory across the run's tool batches.
+ const spineId = await deps.messageModel.getLatestSpineMessageId({
+ threadId: state.threadId ?? null,
+ topicId: state.topicId,
+ });
+ if (spineId) state.main.lastSpineMessageId = spineId;
+}
+
+/**
+ * Rebuild the in-flight subagent runs (`state.main.subagents`) from DB.
+ *
+ * The shared reducer keys runs by `parentToolCallId` and only lazy-creates a
+ * thread when the run is ABSENT from this map. On a cold serverless replica
+ * `createMainAgentRunState` seeds an empty map, so a subagent event whose
+ * thread already exists (created by an earlier batch / another replica) would
+ * fork a brand-new thread β€” the "ε€§ι‡ζ— ζ„δΉ‰ηš„ Subagent" bug. `refreshMainStateFromDb`
+ * rebuilds the main-agent half; this rebuilds the subagent half the same way.
+ *
+ * Merge semantics: only runs MISSING from the in-memory map are rehydrated, so
+ * a warm replica's live per-turn accumulators (`accContent`, current
+ * `toolState`) are never clobbered by the DB projection.
+ *
+ * Finalized (`Active`) spawns are NOT rehydrated as live runs (a completed
+ * spawn is never resurrected β€” that would mint spurious empty assistants and
+ * re-finalize churn), but their `sourceToolCallId` IS recorded in
+ * `finalizedParents` so a REPLAYED first-event on a cold replica can't fork a
+ * duplicate thread for a spawn that already finished (the "δΈ€ζ¨‘δΈ€ζ ·ηš„δΈ€δΈͺ
+ * thread" bug). This mirrors #15838's main-turn idempotency for the subagent
+ * thread-create step: dedup keyed by the DB-homed `sourceToolCallId`,
+ * independent of in-memory state and of thread status.
+ *
+ * Best-effort: any DB hiccup (or a partial test mock without the query
+ * methods) leaves `state.main.subagents` untouched rather than aborting the
+ * whole ingest.
+ */
+export async function refreshSubagentRunsFromDb(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+): Promise<void> {
+ try {
+ const threads = await deps.threadModel.queryByTopicId(state.topicId);
+ const existing = state.main.subagents.runs;
+ const snapshots: SubagentRunSnapshot[] = [];
+ // Union with any parents finalized in-memory on a warm replica.
+ const finalizedParents = new Set(state.main.subagents.finalizedParents);
+
+ for (const thread of threads ?? []) {
+ if (thread.type !== ThreadType.Isolation) continue;
+ const meta = thread.metadata as { operationId?: string; sourceToolCallId?: string } | null;
+ // Operation-scoped: only attend to threads THIS operation created.
+ // Topics are reused across turns, so a prior run that crashed / was
+ // cancelled without an ingested terminal event can leave its subagent
+ // thread stuck in `Processing`. Without this guard the next operation
+ // would merge that unrelated thread into its reducer state and then
+ // finalize/mutate it on its own terminal drain. Threads written before
+ // this field existed have no `operationId` and are skipped (safe β€” we
+ // can't attribute them, and the live run re-creates what it needs).
+ if (meta?.operationId !== state.operationId) continue;
+ const parentToolCallId = meta?.sourceToolCallId;
+ if (!parentToolCallId || existing.has(parentToolCallId)) continue;
+
+ // Finalized spawn β†’ remember the key (blocks duplicate create), don't
+ // rehydrate it as a live run.
+ if (thread.status !== ThreadStatus.Processing) {
+ finalizedParents.add(parentToolCallId);
+ continue;
+ }
+
+ const messages = await deps.messageModel.query({
+ threadId: thread.id,
+ topicId: state.topicId,
+ });
+ const snapshot = buildSubagentSnapshot(parentToolCallId, thread.id, messages);
+ if (snapshot) snapshots.push(snapshot);
+ }
+
+ // Nothing new to project: no rehydratable runs AND no finalized keys
+ // beyond what memory already tracked (the set started as a copy of it and
+ // only grows, so an unchanged size means no new Active threads were found).
+ if (
+ snapshots.length === 0 &&
+ finalizedParents.size === state.main.subagents.finalizedParents.size
+ ) {
+ return;
+ }
+
+ // Union: rehydrated (missing) runs + the in-memory ones (which win, since
+ // they carry live accumulators the DB hasn't caught up to yet) + the
+ // finalized-parent guard set.
+ const merged = rehydrateSubagentRunsState(snapshots, [...finalizedParents]);
+ for (const [parentToolCallId, run] of existing) merged.runs.set(parentToolCallId, run);
+ state.main = { ...state.main, subagents: merged };
+ } catch (err) {
+ log('refreshSubagentRunsFromDb failed op=%s err=%O', state.operationId, err);
+ }
+}
+
+/**
+ * Reconstruct one {@link SubagentRunSnapshot} from a thread's persisted
+ * messages (ordered `createdAt` asc by the query). Returns undefined when the
+ * thread has no assistant yet β€” without one there is nothing to attach a
+ * continuation turn to, and the first-event path will (correctly) seed it.
+ */
+function buildSubagentSnapshot(
+ parentToolCallId: string,
+ threadId: string,
+ messages: Array<{
+ id: string;
+ metadata?: Record<string, any> | null;
+ parentId?: string | null;
+ role: string;
+ tool_call_id?: string;
+ }>,
+): SubagentRunSnapshot | undefined {
+ const assistants = messages.filter((m) => m.role === 'assistant');
+ const currentAssistant = assistants.at(-1);
+ if (!currentAssistant) return undefined;
+
+ const toolRows = messages.filter((m) => m.role === 'tool' && m.tool_call_id);
+ // Chain rule: the next turn's assistant parents off the
+ // prior assistant (the spine), not its last child tool β€” recover the anchor
+ // as the current assistant itself (matches the subagent reducer, and is
+ // fork-resistant since it reads the thread's real latest assistant from DB).
+ const lastChainParentId = currentAssistant.id;
+ // Recover the in-flight turn's CC message.id so a continuation event is
+ // recognized as the SAME turn (no spurious boundary β†’ no fragmentation).
+ const currentSubagentMessageId =
+ typeof currentAssistant.metadata?.subagentMessageId === 'string'
+ ? currentAssistant.metadata.subagentMessageId
+ : undefined;
+
+ return {
+ currentAssistantId: currentAssistant.id,
+ currentSubagentMessageId,
+ lastChainParentId,
+ lifetimeToolCallIds: toolRows.map((m) => m.tool_call_id!),
+ parentToolCallId,
+ threadId,
+ };
+}
+
+export async function syncAssistantPointerForAdvancedStep(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+): Promise<void> {
+ const topic = await deps.topicModel.findById(state.topicId);
+ const marker = topic?.metadata?.runningOperation;
+ const running =
+ marker?.operationId === state.operationId
+ ? marker
+ : marker?.childOperations?.find((child) => child.operationId === state.operationId);
+
+ // Same split as `loadOrCreateState`: another operation on the marker means
+ // this run has been superseded and must stop writing, while a marker that
+ // is simply gone can be a live producer whose topic was settled by a
+ // transport signal. In the latter case `heteroCurrentMsgId` β€” repointed by
+ // this operation's own ingest β€” is a complete substitute for the pointer
+ // this sync would have read off the marker.
+ if (
+ !running &&
+ (marker || !(await deps.isOperationLiveOnTopic?.(state.operationId, state.topicId)))
+ ) {
+ throw new StaleHeteroOperationError(
+ `Stale hetero operation ${state.operationId} on topic ${state.topicId}; current operation is ${marker?.operationId ?? 'unknown'}`,
+ );
+ }
+
+ const stored = topic?.metadata?.heteroCurrentMsgId;
+ const authoritativeAssistantMessageId =
+ stored?.operationId === state.operationId
+ ? (stored.msgId ?? running?.assistantMessageId)
+ : running?.assistantMessageId;
+
+ if (
+ !authoritativeAssistantMessageId ||
+ authoritativeAssistantMessageId === state.main.currentAssistantId
+ ) {
+ return;
+ }
+
+ state.main = {
+ ...state.main,
+ accContent: '',
+ accReasoning: '',
+ currentAssistantId: authoritativeAssistantMessageId,
+ lastReasoningSnapshotSeq: 0,
+ lastTextSnapshotSeq: 0,
+ toolState: createEmptyMainToolState(),
+ turnMetadata: {},
+ };
+ await refreshToolMessageIndex(deps, state);
+ await refreshMainStateFromDb(deps, state);
+
+ log(
+ 'synced warm state op=%s to assistant=%s after step advance',
+ state.operationId,
+ authoritativeAssistantMessageId,
+ );
+}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts
new file mode 100644
index 00000000000..39b98b4422e
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts
@@ -0,0 +1,196 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { vi } from 'vitest';
+
+import { HeterogeneousPersistenceHandler } from '.';
+
+interface FakeMessage {
+ agentId: string | null;
+ content: string;
+ error?: any;
+ id: string;
+ metadata?: any;
+ model?: string;
+ parentId?: string | null;
+ plugin?: any;
+ pluginError?: any;
+ pluginState?: any;
+ provider?: string;
+ reasoning?: any;
+ role: 'user' | 'assistant' | 'tool' | 'task' | 'system';
+ threadId?: string | null;
+ tool_call_id?: string;
+ tools?: any[];
+ topicId: string | null;
+}
+
+interface FakeThread {
+ id: string;
+ metadata?: any;
+ sourceMessageId?: string | null;
+ status: string;
+ title: string;
+ topicId: string;
+ type: string;
+}
+
+export interface FakeTopicMetadata {
+ heteroCurrentMsgId?: { msgId: string; operationId: string };
+ runningOperation?: {
+ assistantMessageId: string;
+ operationId: string;
+ threadId?: string;
+ };
+}
+
+interface FakeTopic {
+ agentId: string | null;
+ id: string;
+ metadata: FakeTopicMetadata;
+}
+
+export const createHarness = (params: {
+ assistantAgentId?: string | null;
+ assistantMessageId: string;
+ /** Stands in for the operation row: is this run still live on this topic? */
+ isOperationLiveOnTopic?: (operationId: string, topicId: string) => Promise<boolean>;
+ operationId: string;
+ topicAgentId?: string | null;
+ topicId: string;
+ threadId?: string;
+}) => {
+ let nextMsgIdSeq = 0;
+ const messages = new Map<string, FakeMessage>();
+ const threads = new Map<string, FakeThread>();
+
+ // Seed the initial assistant message that the orchestrator would have
+ // created before triggering the CLI ingest.
+ messages.set(params.assistantMessageId, {
+ agentId: params.assistantAgentId ?? params.topicAgentId ?? null,
+ content: '',
+ id: params.assistantMessageId,
+ role: 'assistant',
+ threadId: params.threadId ?? null,
+ topicId: params.topicId,
+ });
+
+ const messageModel = {
+ create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {
+ nextMsgIdSeq += 1;
+ const msgId = id ?? `msg_${nextMsgIdSeq}`;
+ const msg: FakeMessage = {
+ agentId: input.agentId ?? null,
+ content: input.content ?? '',
+ id: msgId,
+ metadata: input.metadata,
+ model: input.model,
+ parentId: input.parentId ?? null,
+ plugin: input.plugin,
+ provider: input.provider,
+ role: input.role!,
+ threadId: input.threadId ?? null,
+ tool_call_id: input.tool_call_id,
+ topicId: input.topicId ?? null,
+ };
+ messages.set(msgId, msg);
+ return msg;
+ }),
+ update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ messages.set(id, { ...existing, ...patch });
+ return { success: true };
+ }),
+ updateToolMessage: vi.fn(
+ async (
+ id: string,
+ patch: { content?: string; metadata?: any; pluginError?: any; pluginState?: any },
+ ) => {
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ messages.set(id, {
+ ...existing,
+ content: patch.content ?? existing.content,
+ metadata: patch.metadata ?? existing.metadata,
+ pluginError: patch.pluginError,
+ pluginState: patch.pluginState ?? existing.pluginState,
+ });
+ return { success: true };
+ },
+ ),
+ findById: vi.fn(async (id: string) => messages.get(id) ?? null),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (m) =>
+ m.role !== 'tool' &&
+ (m.threadId ?? null) === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
+ listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
+ };
+
+ const threadModel = {
+ create: vi.fn(async (input: Partial<FakeThread>) => {
+ const thread: FakeThread = {
+ id: input.id!,
+ metadata: input.metadata,
+ sourceMessageId: input.sourceMessageId,
+ status: input.status ?? 'active',
+ title: input.title ?? '',
+ topicId: input.topicId ?? params.topicId,
+ type: input.type ?? 'isolation',
+ };
+ threads.set(thread.id, thread);
+ return thread;
+ }),
+ findById: vi.fn(async (id: string) => threads.get(id) ?? null),
+ update: vi.fn(async (id: string, patch: Partial<FakeThread>) => {
+ const existing = threads.get(id);
+ if (!existing) return;
+ threads.set(id, { ...existing, ...patch });
+ }),
+ };
+
+ const topicModel = {
+ findById: vi.fn(async (id: string): Promise<FakeTopic | null> => {
+ if (id !== params.topicId) return null;
+ return {
+ agentId: params.topicAgentId ?? null,
+ id,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: params.assistantMessageId,
+ operationId: params.operationId,
+ threadId: params.threadId,
+ },
+ } satisfies FakeTopicMetadata,
+ };
+ }),
+ updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
+ };
+
+ const handler = new HeterogeneousPersistenceHandler({
+ isOperationLiveOnTopic: params.isOperationLiveOnTopic,
+ messageModel: messageModel as any,
+ threadModel: threadModel as any,
+ topicModel: topicModel as any,
+ });
+
+ return { handler, messageModel, messages, threadModel, threads, topicModel };
+};
+
+export const buildEvent = (
+ type: AgentStreamEvent['type'],
+ stepIndex: number,
+ data: Record<string, unknown>,
+ timestamp = 1_700_000_000_000 + stepIndex,
+): AgentStreamEvent => ({
+ data,
+ operationId: 'op-test',
+ stepIndex,
+ timestamp,
+ type,
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts
new file mode 100644
index 00000000000..087b80e560b
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts
@@ -0,0 +1,71 @@
+import type { MainAgentRunState } from '@lobechat/heterogeneous-agents';
+
+import type { MessageModel } from '@/database/models/message';
+import type { ThreadModel } from '@/database/models/thread';
+import type { TopicModel } from '@/database/models/topic';
+
+/**
+ * Per-operation in-memory state. Lifetime spans the whole CLI run from first
+ * `heteroIngest` batch through `heteroFinish`. Main-agent state is projected
+ * back from DB at each ingest boundary; active subagent run state is still the
+ * in-memory part of the operation.
+ */
+export interface OperationState {
+ agentId: string | null;
+ /** Native turn boundary shared by the user prompt and every assistant/tool step. */
+ codexTurnId?: string;
+ /**
+ * CC-native session id this run is producing, captured off the stream_start
+ * event stream and stamped on every persisted message's
+ * `metadata.heteroSessionId`. Run-global and stable; a change ACROSS a topic
+ * (visible only because it's copied per-message) means CC forked a new
+ * session β€” the forensic signal for a lost-`--resume` "session break".
+ * Recovered on a cold replica from the current assistant's stamped metadata.
+ */
+ heteroSessionId: string | undefined;
+ /** Last DB-confirmed tool-state seq, scoped to this operation. */
+ lastAppliedToolStateSeqByCallId: Map<string, number>;
+ lastStepIndex: number;
+ main: MainAgentRunState;
+ /** `(operationId, toolCallId, transition)` notification dedupe ledger. */
+ notifiedInterventionTransitions: Set<string>;
+ operationId: string;
+ processedKeys: Set<string>;
+ /**
+ * Publish gate, peer of `processedKeys` but for the live-stream sink.
+ * Persistence and publish fail independently: a batch can persist fully
+ * yet die inside the publish loop β€” its retry must republish ONLY the
+ * unpublished tail β€” while a batch whose tRPC response was lost after
+ * full success must republish nothing. Keyed by `eventKey`, latched only
+ * after the event's XADD succeeds.
+ */
+ publishedKeys: Set<string>;
+ /** User message answered by this operation, checked against its topic/thread before stamping. */
+ sourceUserMessageId?: string;
+ /** Isolation thread that owns this heterogeneous run, when applicable. */
+ threadId: string | undefined;
+ /**
+ * Run-global DB index for every tool message in the topic, keyed by
+ * `tool_call_id`. Main and subagent reducers keep only their per-turn maps;
+ * this map lets a `tool_result` land even when its `tools_calling` was
+ * reduced by another serverless replica.
+ */
+ toolMsgIdByCallId: Map<string, string>;
+ topicId: string;
+}
+
+export interface HeterogeneousPersistenceHandlerDeps {
+ /**
+ * Liveness probe against the operation row, used only when the topic has lost
+ * its `runningOperation` marker: it answers whether this operation is still
+ * `running` and still owns this topic, i.e. whether the producer behind the
+ * batch is alive. Optional so standalone/test callers keep the marker-only
+ * behaviour.
+ */
+ isOperationLiveOnTopic?: (operationId: string, topicId: string) => Promise<boolean>;
+ messageModel: MessageModel;
+ threadModel: ThreadModel;
+ topicModel: TopicModel;
+ userId?: string;
+ workspaceId?: string;
+}
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
deleted file mode 100644
index e9f4dcb10e2..00000000000
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
+++ /dev/null
@@ -1,1433 +0,0 @@
-// @vitest-environment node
-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
-
-const { acknowledgeAgentInterventionProducerResolution, notifyAgentInterventionRequired } =
- vi.hoisted(() => ({
- acknowledgeAgentInterventionProducerResolution: vi.fn(),
- notifyAgentInterventionRequired: vi.fn(),
- }));
-vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({
- acknowledgeAgentInterventionProducerResolution,
- notifyAgentInterventionRequired,
-}));
-
-/**
- * Branch-coverage tests against every event type / sub-type the renderer
- * (`heterogeneousAgentExecutor.ts:1314–1632`) dispatches on. Each describe
- * block names the event variant; each `it` covers one observable behavior
- * the renderer encodes for that variant. See `cc-stream-chain-reference.md`
- * for the source-of-truth table the renderer is keyed off of.
- *
- * Sibling specs:
- * - `HeterogeneousPersistenceHandler.test.ts`: state bootstrap +
- * idempotency + 3-phase persist + subagent lifecycle (the structural
- * contract).
- * - `HeterogeneousPersistenceHandler.fixture.test.ts`: end-to-end replay
- * of a real CC trace.
- */
-
-interface FakeMessage {
- agentId: string | null;
- content: string;
- error?: any;
- id: string;
- metadata?: any;
- model?: string;
- parentId?: string | null;
- plugin?: any;
- pluginError?: any;
- pluginState?: any;
- provider?: string;
- reasoning?: any;
- role: 'assistant' | 'user' | 'tool' | 'task' | 'system';
- threadId?: string | null;
- tool_call_id?: string;
- tools?: any[];
- topicId: string | null;
-}
-
-interface FakeThread {
- id: string;
- metadata?: any;
- sourceMessageId?: string | null;
- status: string;
- title: string;
- topicId: string;
- type: string;
-}
-
-const createHarness = (
- params: {
- assistantMessageId?: string;
- operationId?: string;
- topicAgentId?: string | null;
- topicId?: string;
- userId?: string | null;
- } = {},
-) => {
- const operationId = params.operationId ?? 'op-test';
- const topicId = params.topicId ?? 'topic-test';
- const assistantMessageId = params.assistantMessageId ?? 'asst-seeded';
- const topicAgentId = params.topicAgentId ?? null;
-
- let nextSeq = 0;
- const messages = new Map<string, FakeMessage>();
- const threads = new Map<string, FakeThread>();
-
- messages.set(assistantMessageId, {
- agentId: topicAgentId,
- content: '',
- id: assistantMessageId,
- role: 'assistant',
- topicId,
- });
-
- const messageModel = {
- create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {
- nextSeq += 1;
- const msgId = id ?? `msg_${nextSeq}`;
- const msg: FakeMessage = {
- agentId: input.agentId ?? null,
- content: input.content ?? '',
- id: msgId,
- metadata: input.metadata,
- model: input.model,
- parentId: input.parentId ?? null,
- plugin: input.plugin,
- provider: input.provider,
- role: input.role!,
- threadId: input.threadId ?? null,
- tool_call_id: input.tool_call_id,
- topicId: input.topicId ?? null,
- };
- messages.set(msgId, msg);
- return msg;
- }),
- update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
- const existing = messages.get(id);
- if (!existing) return { success: false };
- messages.set(id, { ...existing, ...patch });
- return { success: true };
- }),
- updateToolMessage: vi.fn(
- async (
- id: string,
- patch: {
- content?: string;
- heterogeneousToolState?: { operationId: string; snapshotSeq: number };
- metadata?: any;
- pluginError?: any;
- pluginState?: any;
- },
- ) => {
- const existing = messages.get(id);
- if (!existing) return { success: false };
- const snapshot = patch.heterogeneousToolState;
- const currentSeq =
- snapshot && existing.metadata?.heterogeneousToolStateOperationId === snapshot.operationId
- ? (existing.metadata.heterogeneousToolStateSeq ?? 0)
- : 0;
- if (snapshot && snapshot.snapshotSeq <= currentSeq) {
- return { applied: false, snapshotSeq: currentSeq, success: true };
- }
- messages.set(id, {
- ...existing,
- content: patch.content ?? existing.content,
- metadata: snapshot
- ? {
- ...existing.metadata,
- ...patch.metadata,
- heterogeneousToolStateOperationId: snapshot.operationId,
- heterogeneousToolStateSeq: snapshot.snapshotSeq,
- }
- : (patch.metadata ?? existing.metadata),
- pluginError: patch.pluginError,
- pluginState: patch.pluginState ?? existing.pluginState,
- });
- return {
- applied: true,
- snapshotSeq: snapshot?.snapshotSeq,
- success: true,
- };
- },
- ),
- findById: vi.fn(async (id: string) => messages.get(id) ?? null),
- getLatestSpineMessageId: vi.fn(
- async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
- const match = [...messages.values()].findLast(
- (m) =>
- m.topicId === topicId &&
- m.role !== 'tool' &&
- m.threadId === (threadId ?? null) &&
- !(m as any).metadata?.signal,
- );
- return match?.id;
- },
- ),
- listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
- updateMessagePlugin: vi.fn(async (id: string, patch: Record<string, unknown>) => {
- const existing = messages.get(id);
- if (existing) messages.set(id, { ...existing, plugin: { ...existing.plugin, ...patch } });
- }),
- updatePluginState: vi.fn(async (id: string, patch: Record<string, unknown>) => {
- const existing = messages.get(id);
- if (existing) {
- messages.set(id, { ...existing, pluginState: { ...existing.pluginState, ...patch } });
- }
- }),
- };
-
- const threadModel = {
- create: vi.fn(async (input: Partial<FakeThread>) => {
- const thread: FakeThread = {
- id: input.id!,
- metadata: input.metadata,
- sourceMessageId: input.sourceMessageId,
- status: input.status ?? 'active',
- title: input.title ?? '',
- topicId: input.topicId ?? topicId,
- type: input.type ?? 'isolation',
- };
- threads.set(thread.id, thread);
- return thread;
- }),
- update: vi.fn(async (id: string, patch: Partial<FakeThread>) => {
- const existing = threads.get(id);
- if (existing) threads.set(id, { ...existing, ...patch });
- }),
- };
-
- const topicModel = {
- findById: vi.fn(async () => ({
- agentId: topicAgentId,
- id: topicId,
- metadata: { runningOperation: { assistantMessageId, operationId } },
- })),
- updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
- };
-
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: messageModel as any,
- threadModel: threadModel as any,
- topicModel: topicModel as any,
- userId: params.userId === null ? undefined : (params.userId ?? 'user-test'),
- });
-
- return {
- assistantMessageId,
- handler,
- messageModel,
- messages,
- operationId,
- threadModel,
- threads,
- topicId,
- topicModel,
- };
-};
-
-const buildEvent = (
- type: AgentStreamEvent['type'],
- stepIndex: number,
- data: Record<string, unknown>,
- timestamp = 1_700_000_000_000 + stepIndex,
-): AgentStreamEvent => ({
- data,
- operationId: 'op-test',
- stepIndex,
- timestamp,
- type,
-});
-
-const ingest = async (h: ReturnType<typeof createHarness>, events: AgentStreamEvent[]) =>
- h.handler.ingest({ events, operationId: h.operationId, topicId: h.topicId });
-
-describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
- beforeEach(() => {
- __resetOperationStatesForTesting();
- acknowledgeAgentInterventionProducerResolution.mockReset();
- notifyAgentInterventionRequired.mockReset();
- });
- afterEach(() => __resetOperationStatesForTesting());
-
- // ─── step_complete ────────────────────────────────────────────────────────
-
- describe('step_complete', () => {
- it('phase=turn_metadata with usage writes assistant.metadata.usage and caches model/provider', async () => {
- const h = createHarness();
- const usage = { totalInputTokens: 100, totalOutputTokens: 50, totalTokens: 150 };
-
- await ingest(h, [
- buildEvent('step_complete', 0, {
- model: 'claude-opus-4-7',
- phase: 'turn_metadata',
- provider: 'claude-code',
- usage,
- }),
- ]);
-
- expect(h.messageModel.update).toHaveBeenCalledWith(
- h.assistantMessageId,
- expect.objectContaining({ metadata: { usage } }),
- );
- });
-
- it('phase=turn_metadata WITHOUT usage only caches model/provider for the next step', async () => {
- const h = createHarness();
-
- // turn_metadata with no usage β†’ no DB write yet, but lastModel/lastProvider
- // should propagate to the NEXT step's create assistant call.
- await ingest(h, [
- buildEvent('step_complete', 0, {
- model: 'claude-opus-4-7',
- phase: 'turn_metadata',
- provider: 'claude-code',
- }),
- buildEvent('stream_start', 1, { newStep: true }),
- ]);
-
- // First update would be the prev-step flush of nothing β€” no model/provider
- // because pre-cache occurred AFTER turn_metadata. But the new assistant
- // create should carry both.
- const newAssistantCall = h.messageModel.create.mock.calls.find(
- (call) => call[0]?.role === 'assistant',
- );
- expect(newAssistantCall?.[0]).toMatchObject({
- model: 'claude-opus-4-7',
- provider: 'claude-code',
- });
- });
-
- it('phase=result_usage is ignored (renderer line 1399–1402: would clobber per-step usage)', async () => {
- const h = createHarness();
-
- await ingest(h, [
- buildEvent('step_complete', 0, {
- phase: 'result_usage',
- usage: { totalInputTokens: 9999 },
- }),
- ]);
-
- // No update on assistant for result_usage
- expect(h.messageModel.update).not.toHaveBeenCalled();
- });
-
- it('unknown phase is dropped silently', async () => {
- const h = createHarness();
- await ingest(h, [buildEvent('step_complete', 0, { phase: 'something_new' })]);
- expect(h.messageModel.update).not.toHaveBeenCalled();
- });
- });
-
- // ─── stream_start ─────────────────────────────────────────────────────────
-
- describe('stream_start', () => {
- it('without newStep (CLI init) backfills the placeholder with the CLI model/provider', async () => {
- const h = createHarness();
- const beforeCreates = h.messageModel.create.mock.calls.length;
-
- await ingest(h, [
- buildEvent('stream_start', 0, {
- model: 'claude-sonnet-4-5',
- provider: 'claude-code',
- }),
- ]);
-
- // The init event carries the CLI's authoritative model/provider β€” it must
- // backfill the placeholder (which was created with only `provider`, no
- // model) so the model tag shows the real CLI model from the first turn,
- // even without any usage-bearing turn_metadata.
- const asst = h.messages.get(h.assistantMessageId);
- expect(asst?.model).toBe('claude-sonnet-4-5');
- expect(asst?.provider).toBe('claude-code');
- // No new assistant row is created β€” only the placeholder is patched.
- expect(h.messageModel.create.mock.calls.length).toBe(beforeCreates);
- });
-
- it('without newStep and no model/provider is a no-op', async () => {
- const h = createHarness();
- const beforeUpdates = h.messageModel.update.mock.calls.length;
- const beforeCreates = h.messageModel.create.mock.calls.length;
-
- await ingest(h, [buildEvent('stream_start', 0, {})]);
-
- expect(h.messageModel.update.mock.calls.length).toBe(beforeUpdates);
- expect(h.messageModel.create.mock.calls.length).toBe(beforeCreates);
- });
-
- it('with newStep but no prior tools chains the new assistant off the previous assistant', async () => {
- const h = createHarness();
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'plain step' }),
- buildEvent('stream_start', 1, { newStep: true }),
- ]);
-
- const newAsst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== h.assistantMessageId,
- );
- // No tool messages β†’ falls back to prev assistant id
- expect(newAsst?.parentId).toBe(h.assistantMessageId);
- });
- });
-
- // ─── stream_chunk ─────────────────────────────────────────────────────────
-
- describe('stream_chunk', () => {
- it('main-side text accumulates without writing to DB until step boundary', async () => {
- const h = createHarness();
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hi ' }),
- buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'there' }),
- ]);
-
- // Text is flushed to DB at end of each batch (multi-replica fix)
- expect(h.messageModel.update).toHaveBeenCalledWith(h.assistantMessageId, {
- content: 'hi there',
- });
- });
-
- it('main-side reasoning accumulates separately from text', async () => {
- const h = createHarness();
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, { chunkType: 'reasoning', reasoning: 'thinking ' }),
- buildEvent('stream_chunk', 1, { chunkType: 'reasoning', reasoning: 'more' }),
- buildEvent('agent_runtime_end', 2, { reason: 'success' }),
- ]);
-
- const asst = h.messages.get(h.assistantMessageId)!;
- expect(asst.reasoning).toEqual({ content: 'thinking more' });
- });
-
- it('subagent-tagged text routes to the run accumulator, NOT the main one', async () => {
- const h = createHarness();
- const subagentCtx = {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- };
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'subagent thought',
- subagent: subagentCtx,
- }),
- buildEvent('agent_runtime_end', 1, { reason: 'success' }),
- ]);
-
- const main = h.messages.get(h.assistantMessageId)!;
- expect(main.content).toBe(''); // Main untouched
-
- const threadId = [...h.threads.keys()][0];
- const subAssts = [...h.messages.values()].filter(
- (m) => m.threadId === threadId && m.role === 'assistant',
- );
- // After agent_runtime_end β†’ finalize without resultContent β†’ flush
- // accumulated content onto the in-thread assistant
- expect(subAssts.some((m) => m.content === 'subagent thought')).toBe(true);
- });
-
- it('subagent-tagged reasoning routes to the run reasoning accumulator', async () => {
- const h = createHarness();
- const subagentCtx = {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- };
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'reasoning',
- reasoning: 'subagent thinks hard',
- subagent: subagentCtx,
- }),
- buildEvent('agent_runtime_end', 1, { reason: 'success' }),
- ]);
-
- const threadId = [...h.threads.keys()][0];
- const flushed = [...h.messages.values()].find(
- (m) =>
- m.threadId === threadId &&
- m.role === 'assistant' &&
- m.reasoning?.content === 'subagent thinks hard',
- );
- expect(flushed).toBeDefined();
- });
-
- it('persists tool_state DB-first and drops stale in-operation snapshots', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- toolsCalling: [
- {
- apiName: 'todo_list',
- arguments: '{}',
- id: 'todo-1',
- identifier: 'codex',
- type: 'default',
- },
- ],
- }),
- buildEvent('stream_chunk', 1, {
- chunkType: 'tool_state',
- pluginState: { todos: { items: [{ status: 'processing', text: 'Implement' }] } },
- snapshotMode: 'replace',
- snapshotSeq: 2,
- toolCallId: 'todo-1',
- }),
- buildEvent('stream_chunk', 2, {
- chunkType: 'tool_state',
- pluginState: { stale: true },
- snapshotMode: 'replace',
- snapshotSeq: 1,
- toolCallId: 'todo-1',
- }),
- ]);
-
- const stateWrites = h.messageModel.updateToolMessage.mock.calls.filter(
- ([, patch]) => patch.heterogeneousToolState,
- );
- expect(stateWrites).toHaveLength(1);
- expect(stateWrites[0][1]).toMatchObject({
- heterogeneousToolState: { operationId: h.operationId, snapshotSeq: 2 },
- pluginState: {
- todos: { items: [{ status: 'processing', text: 'Implement' }] },
- },
- });
- const toolMessage = [...h.messages.values()].find(
- (message) => message.tool_call_id === 'todo-1',
- );
- expect(toolMessage?.metadata).toMatchObject({
- heterogeneousToolStateOperationId: h.operationId,
- heterogeneousToolStateSeq: 2,
- });
- expect(toolMessage?.pluginState).not.toEqual({ stale: true });
- });
-
- it('restores the tool-state watermark from DB after a cold operation-state reset', async () => {
- const h = createHarness();
- h.messages.set('tool-existing', {
- agentId: null,
- content: '',
- id: 'tool-existing',
- metadata: {
- heterogeneousToolStateOperationId: h.operationId,
- heterogeneousToolStateSeq: 4,
- },
- pluginState: { current: true },
- role: 'tool',
- tool_call_id: 'todo-existing',
- topicId: h.topicId,
- });
- h.messageModel.listMessagePluginsByTopic.mockResolvedValue([
- {
- id: 'tool-existing',
- metadata: h.messages.get('tool-existing')?.metadata,
- toolCallId: 'todo-existing',
- },
- ] as any);
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tool_state',
- pluginState: { stale: true },
- snapshotMode: 'replace',
- snapshotSeq: 3,
- toolCallId: 'todo-existing',
- }),
- ]);
-
- expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
- expect(h.messages.get('tool-existing')?.pluginState).toEqual({ current: true });
- });
-
- it('tools_calling with empty array is a no-op', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [] }),
- ]);
- expect(h.messageModel.update).not.toHaveBeenCalled();
- expect(h.messageModel.create).not.toHaveBeenCalled();
- });
-
- it('unknown chunkType is dropped silently', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, { chunkType: 'mystery_chunk', payload: 42 } as any),
- ]);
- expect(h.messageModel.update).not.toHaveBeenCalled();
- expect(h.messageModel.create).not.toHaveBeenCalled();
- });
- });
-
- // ─── tool_result ──────────────────────────────────────────────────────────
-
- describe('tool_result', () => {
- const buildToolFlow = (
- h: ReturnType<typeof createHarness>,
- toolResultData: Record<string, unknown>,
- ) =>
- ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- toolsCalling: [
- {
- apiName: 'TodoWrite',
- arguments: '{"todos":[]}',
- id: 'tc-1',
- identifier: 'todo-write',
- type: 'default',
- },
- ],
- }),
- buildEvent('tool_result', 1, { ...toolResultData, toolCallId: 'tc-1' }),
- ]);
-
- it('writes content + pluginState (TodoWrite synth) atomically through updateToolMessage', async () => {
- const h = createHarness();
- const todos = [
- { content: 'Read code', id: 't1', status: 'pending' },
- { content: 'Write tests', id: 't2', status: 'in_progress' },
- ];
-
- await buildToolFlow(h, {
- content: 'todos updated',
- pluginState: { todos },
- });
-
- const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
- expect(toolMsg?.content).toBe('todos updated');
- expect(toolMsg?.pluginState).toEqual({ todos });
- // Critical: the renderer's TodoWrite synth (adapter line 546–553) puts
- // todos on `pluginState` β€” we transparently persist them through
- // updateToolMessage, so selectTodosFromMessages reads them.
- expect(h.messageModel.updateToolMessage).toHaveBeenCalledWith(
- toolMsg?.id,
- expect.objectContaining({ pluginState: { todos } }),
- );
- });
-
- it('isError=true sets pluginError', async () => {
- const h = createHarness();
- await buildToolFlow(h, {
- content: 'ENOENT no such file',
- isError: true,
- });
-
- const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
- expect(toolMsg?.pluginError).toEqual({ message: 'ENOENT no such file' });
- });
-
- it('unknown toolCallId logs and drops without throwing', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('tool_result', 0, {
- content: 'orphan',
- toolCallId: 'tc-never-seen',
- }),
- ]);
- // Handler swallows unknown ids β€” no crash, no DB write
- expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
- });
-
- it('tool_result without toolCallId is dropped (defensive)', async () => {
- const h = createHarness();
- await ingest(h, [buildEvent('tool_result', 0, { content: 'x' })]);
- expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();
- });
- });
-
- // ─── agent_runtime_end / error ────────────────────────────────────────────
-
- describe('terminal events', () => {
- it('agent_runtime_end flushes content + reasoning + model/provider', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('step_complete', 0, {
- model: 'claude-opus-4-7',
- phase: 'turn_metadata',
- provider: 'claude-code',
- }),
- buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'final text' }),
- buildEvent('stream_chunk', 2, { chunkType: 'reasoning', reasoning: 'final reasoning' }),
- buildEvent('agent_runtime_end', 3, { reason: 'success' }),
- ]);
-
- const asst = h.messages.get(h.assistantMessageId)!;
- expect(asst.content).toBe('final text');
- expect(asst.reasoning).toEqual({ content: 'final reasoning' });
- expect(asst.model).toBe('claude-opus-4-7');
- expect(asst.provider).toBe('claude-code');
- });
-
- it('error event writes a ChatMessageError onto the assistant', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('error', 0, {
- message: 'connection timeout',
- type: 'AgentRuntimeError',
- }),
- ]);
- const asst = h.messages.get(h.assistantMessageId)!;
- expect(asst.error).toMatchObject({
- message: 'connection timeout',
- type: 'AgentRuntimeError',
- });
- });
-
- it('error with AuthRequired code + matching content suppresses the echoed content', async () => {
- const h = createHarness();
- // CC streams the auth error into the text stream BEFORE emitting the
- // structured error. Without echo suppression, the assistant ends up
- // with both the raw stderr AND the structured error β€” duplicates.
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'auth required - sign in again',
- }),
- buildEvent('error', 1, {
- code: 'AuthRequired',
- message: 'auth required - sign in again',
- type: 'AgentRuntimeError',
- }),
- ]);
- const asst = h.messages.get(h.assistantMessageId)!;
- expect(asst.content).toBe('');
- expect(asst.error).toBeDefined();
- });
-
- it('error with non-AuthRequired code preserves the streamed content', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'partial answer',
- }),
- buildEvent('error', 1, {
- message: 'partial answer',
- type: 'AgentRuntimeError',
- }),
- ]);
- const asst = h.messages.get(h.assistantMessageId)!;
- expect(asst.content).toBe('partial answer');
- expect(asst.error).toBeDefined();
- });
-
- it('error with explicit clearEchoedContent flag suppresses echoed content', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'oops timeout',
- }),
- buildEvent('error', 1, {
- clearEchoedContent: true,
- message: 'oops timeout',
- type: 'AgentRuntimeError',
- }),
- ]);
- const asst = h.messages.get(h.assistantMessageId)!;
- expect(asst.content).toBe('');
- });
-
- it('terminal event drains orphan subagent runs (no resultContent)', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'partial subagent thought',
- subagent: {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- },
- }),
- // No tool_result for tc-spawn β€” CLI crashed mid-spawn
- buildEvent('agent_runtime_end', 1, { reason: 'cancelled' }),
- ]);
-
- const threadId = [...h.threads.keys()][0];
- // Orphan flush wrote the accumulated content onto the in-thread assistant
- const flushed = [...h.messages.values()].find(
- (m) =>
- m.threadId === threadId &&
- m.role === 'assistant' &&
- m.content === 'partial subagent thought',
- );
- expect(flushed).toBeDefined();
- // Subagent run cleaned up on terminal
- expect([...h.threads.keys()]).toHaveLength(1);
- });
- });
-
- // ─── No-op event types ────────────────────────────────────────────────────
-
- describe('no-op event types', () => {
- it.each([
- ['tool_start', { parentMessageId: 'asst-seeded', toolCalling: { id: 'tc-1' } }],
- ['tool_end', { isSuccess: true, toolCallId: 'tc-1' }],
- ['stream_end', {}],
- ['agent_runtime_init', { state: 'idle' }],
- ['step_complete', { phase: 'operation_heartbeat' }],
- ['tool_execute', { apiName: 'Read', toolCallId: 'tc-1' }],
- ['stream_retry', { attempt: 1 }],
- ])('drops %s without DB writes', async (type, data) => {
- const h = createHarness();
- const beforeCreates = h.messageModel.create.mock.calls.length;
- const beforeUpdates = h.messageModel.update.mock.calls.length;
- const beforeToolUpdates = h.messageModel.updateToolMessage.mock.calls.length;
- const beforeThreads = h.threadModel.create.mock.calls.length;
-
- await ingest(h, [buildEvent(type as AgentStreamEvent['type'], 0, data)]);
-
- expect(h.messageModel.create.mock.calls.length).toBe(beforeCreates);
- expect(h.messageModel.update.mock.calls.length).toBe(beforeUpdates);
- expect(h.messageModel.updateToolMessage.mock.calls.length).toBe(beforeToolUpdates);
- expect(h.threadModel.create.mock.calls.length).toBe(beforeThreads);
- });
- });
-
- // ─── Subagent-specific edge cases ─────────────────────────────────────────
-
- describe('subagent edge cases', () => {
- it('subagent tool_result updates the in-thread tool message via the global toolMsgIdByCallId', async () => {
- const h = createHarness();
- const subagentCtx = {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- };
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- subagent: subagentCtx,
- toolsCalling: [
- {
- apiName: 'Read',
- arguments: '{}',
- id: 'inner-tc',
- identifier: 'read',
- type: 'default',
- },
- ],
- }),
- // tool_result for the SUBAGENT's inner tool β€” NOT the spawn parent
- buildEvent('tool_result', 1, {
- content: 'file contents',
- toolCallId: 'inner-tc',
- }),
- ]);
-
- const threadId = [...h.threads.keys()][0];
- const innerTool = [...h.messages.values()].find(
- (m) => m.threadId === threadId && m.role === 'tool',
- );
- expect(innerTool?.content).toBe('file contents');
- });
-
- it('multiple subagent spawns coexist independently (each with its own thread)', async () => {
- const h = createHarness();
-
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'first',
- subagent: {
- parentToolCallId: 'tc-spawn-A',
- spawnMetadata: { prompt: 'task A', subagentType: 'Explore' },
- subagentMessageId: 'sub-A-1',
- },
- }),
- buildEvent('stream_chunk', 1, {
- chunkType: 'text',
- content: 'second',
- subagent: {
- parentToolCallId: 'tc-spawn-B',
- spawnMetadata: { prompt: 'task B', subagentType: 'Plan' },
- subagentMessageId: 'sub-B-1',
- },
- }),
- buildEvent('agent_runtime_end', 2, { reason: 'success' }),
- ]);
-
- expect(h.threads.size).toBe(2);
- const titles = [...h.threads.values()].map((t) => t.title);
- expect(titles).toContain('Explore');
- expect(titles).toContain('Plan');
- });
-
- it('subagent first-event uses description for title, falls back to subagentType', async () => {
- const h = createHarness();
- // No description β†’ fallback to subagentType
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'x',
- subagent: {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'Worker' },
- subagentMessageId: 'sub-1',
- },
- }),
- ]);
- expect([...h.threads.values()][0].title).toBe('Worker');
- });
-
- it('subagent description longer than 80 chars is truncated for the thread title', async () => {
- const h = createHarness();
- const longDesc = 'a'.repeat(120);
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'x',
- subagent: {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { description: longDesc, prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- },
- }),
- ]);
- expect([...h.threads.values()][0].title).toHaveLength(80);
- });
-
- it('subagent with NO subagentMessageId still creates the thread (treated as a single turn)', async () => {
- const h = createHarness();
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'no-turn-id text',
- subagent: {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- // subagentMessageId omitted
- },
- }),
- buildEvent('agent_runtime_end', 1, { reason: 'success' }),
- ]);
-
- expect(h.threads.size).toBe(1);
- const flushed = [...h.messages.values()].find((m) => m.content === 'no-turn-id text');
- expect(flushed).toBeDefined();
- });
-
- it('finalize on parent tool_result creates the terminal in-thread assistant carrying resultContent', async () => {
- const h = createHarness();
- const subagentCtx = {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- };
- await ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'thinking',
- subagent: subagentCtx,
- }),
- buildEvent('tool_result', 1, {
- content: 'final summary',
- toolCallId: 'tc-spawn',
- }),
- ]);
-
- const threadId = [...h.threads.keys()][0];
- const threadAssts = [...h.messages.values()].filter(
- (m) => m.threadId === threadId && m.role === 'assistant',
- );
- // Terminal assistant has the authoritative summary
- expect(threadAssts.at(-1)?.content).toBe('final summary');
- // Run state cleaned up after finalize
- });
- });
-
- describe('agent_intervention producer ACK', () => {
- const materializeAskUserTool = async (
- h: ReturnType<typeof createHarness>,
- toolCallId: string,
- ) =>
- ingest(h, [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- toolsCalling: [
- {
- apiName: 'askUserQuestion',
- arguments: '{}',
- id: toolCallId,
- identifier: 'claude-code',
- type: 'default',
- },
- ],
- }),
- ]);
-
- const missingProviderRequest = (toolCallId: string) =>
- buildEvent('agent_intervention_request', 1, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Question',
- options: [{ label: 'Continue' }, { label: 'Stop' }],
- question: 'Proceed?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- toolCallId,
- });
-
- it('rejects an invalid first Cloud review before any intervention side effect', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
- const toolCallId = 'invalid-cloud-question';
- await materializeAskUserTool(h, toolCallId);
- h.messageModel.updateMessagePlugin.mockClear();
- h.messageModel.updatePluginState.mockClear();
-
- await expect(ingest(h, [missingProviderRequest(toolCallId)])).rejects.toThrow(
- `Unsafe heterogeneous intervention review payload toolCallId=${toolCallId}`,
- );
-
- expect(h.messageModel.updateMessagePlugin).not.toHaveBeenCalled();
- expect(h.messageModel.updatePluginState).not.toHaveBeenCalled();
- expect(notifyAgentInterventionRequired).not.toHaveBeenCalled();
- expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
- const toolMessage = [...h.messages.values()].find(
- (message) => message.tool_call_id === toolCallId,
- );
- expect(toolMessage?.plugin).not.toHaveProperty('intervention');
- expect(toolMessage?.pluginState).toBeUndefined();
- });
-
- it('preserves legacy intervention persistence without a userId', async () => {
- const h = createHarness({ topicAgentId: 'agent-test', userId: null });
- const toolCallId = 'legacy-question';
- await materializeAskUserTool(h, toolCallId);
- h.messageModel.updateMessagePlugin.mockClear();
- h.messageModel.updatePluginState.mockClear();
-
- await expect(ingest(h, [missingProviderRequest(toolCallId)])).resolves.toBeUndefined();
-
- expect(h.messageModel.updateMessagePlugin).toHaveBeenCalledTimes(1);
- expect(h.messageModel.updatePluginState).toHaveBeenCalledTimes(1);
- expect(notifyAgentInterventionRequired).not.toHaveBeenCalled();
- expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
- const toolMessage = [...h.messages.values()].find(
- (message) => message.tool_call_id === toolCallId,
- );
- expect(toolMessage?.plugin?.intervention).toEqual({ status: 'pending' });
- expect(toolMessage?.pluginState?.heterogeneousIntervention).toMatchObject({
- transition: 'pending',
- });
- });
-
- it('canonicalizes an omitted Claude multiSelect before durable review notification', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
-
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Producer ACK E2E',
- options: [
- { description: 'Proceed with validation.', label: 'Continue' },
- { description: 'Halt validation.', label: 'Stop' },
- ],
- question: 'Continue read only validation?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId: 'claude-question-1',
- }),
- ]);
-
- expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
- expect(notifyAgentInterventionRequired.mock.calls[0][0]).toMatchObject({
- items: [
- {
- detail: {
- questions: [
- {
- header: 'Producer ACK E2E',
- id: 'question_1',
- multiple: false,
- options: [
- {
- description: 'Proceed with validation.',
- id: 'Continue',
- label: 'Continue',
- },
- {
- description: 'Halt validation.',
- id: 'Stop',
- label: 'Stop',
- },
- ],
- question: 'Continue read only validation?',
- },
- ],
- title: 'Producer ACK E2E',
- type: 'question',
- },
- interactionKind: 'question',
- provider: 'claude-code',
- summary: 'Continue read only validation?',
- },
- ],
- summary: 'Continue read only validation?',
- });
- expect(h.messageModel.updatePluginState).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({
- heterogeneousIntervention: expect.objectContaining({
- interactionKind: 'question',
- provider: 'claude-code',
- }),
- }),
- );
- });
-
- it('lets the user type their own answer to a heterogeneous question', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
-
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Stack',
- multiSelect: false,
- options: [{ label: 'React' }, { label: 'Vue' }],
- question: 'Which framework?',
- },
- {
- header: 'Targets',
- multiSelect: true,
- options: [{ label: 'Web' }, { label: 'Desktop' }],
- question: 'Which targets?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId: 'claude-question-custom',
- }),
- ]);
-
- // The shared AskUser form always offers "write your own", "type
- // directly" and a supplement note; without these capabilities the claim
- // rejects every typed answer as not matching the request.
- const detail = notifyAgentInterventionRequired.mock.calls[0][0].items[0].detail;
- expect(detail).toMatchObject({
- answerPolicy: { allowFreeform: true, allowSupplement: true },
- questions: [
- { allowCustomAnswer: true, question: 'Which framework?' },
- { allowCustomAnswer: true, question: 'Which targets?' },
- ],
- type: 'question',
- });
- });
-
- it('uses only the sanitized first question for a multi-question summary', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
-
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- privateRawArgument: 'must not appear in the summary',
- questions: [
- {
- header: 'Validation',
- multiSelect: false,
- options: [
- {
- description: 'Sensitive option detail',
- label: 'Continue',
- },
- ],
- question: 'Which validation path should I use?',
- },
- {
- header: 'Follow-up',
- multiSelect: false,
- options: [{ label: 'Production' }],
- question: 'Which environment should I target?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId: 'claude-question-summary',
- }),
- ]);
-
- const notification = notifyAgentInterventionRequired.mock.calls[0][0];
- expect(notification.summary).toBe('Which validation path should I use?');
- expect(notification.items[0].summary).toBe('Which validation path should I use?');
- });
-
- it('normalizes and safely truncates a long question summary', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
- const longQuestion = ` Confirm\n\t${'πŸ˜€'.repeat(170)} now? `;
-
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Long question',
- multiSelect: false,
- options: [{ label: 'Continue' }],
- question: longQuestion,
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId: 'claude-long-question-summary',
- }),
- ]);
-
- const summary = notifyAgentInterventionRequired.mock.calls[0][0].summary;
- expect(summary).toBe(`Confirm ${'πŸ˜€'.repeat(151)}…`);
- expect([...summary]).toHaveLength(160);
- });
-
- it('keeps the technical fallback when the sanitized question has no visible text', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
-
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Blank question',
- multiSelect: false,
- options: [{ label: 'Continue' }],
- question: ' \n\t ',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId: 'claude-blank-question-summary',
- }),
- ]);
-
- const notification = notifyAgentInterventionRequired.mock.calls[0][0];
- expect(notification.summary).toBe('claude-code question: askUserQuestion');
- expect(notification.items[0].summary).toBe('claude-code question: askUserQuestion');
- });
-
- it('notifies pending once, ignores the publish leg, and notifies terminal only on ACK', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
- const requestId = '018fbd8e-7baf-7c6d-8000-000000000001';
- const request = buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- privateRawArgument: 'must be stripped',
- questions: [
- {
- header: 'Permission',
- multiSelect: false,
- options: [
- { id: 'allow', label: 'Allow', raw: 'strip me' },
- { id: 'deny', label: 'Deny' },
- ],
- question: 'Run command?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'devin',
- interactionKind: 'permission',
- provider: 'devin',
- toolCallId: 'permission-1',
- });
-
- await ingest(h, [request]);
- await ingest(h, [{ ...request, timestamp: request.timestamp + 1 }]);
-
- expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
- const pending = notifyAgentInterventionRequired.mock.calls[0][0];
- expect(pending).toMatchObject({
- agentId: 'agent-test',
- approvalMode: 'manual',
- batch: {
- allowedActions: [],
- id: 'op-test:0:asst-seeded:permission-1',
- kind: 'single',
- sealed: true,
- stepIndex: 0,
- },
- context: {
- assistantMessageId: 'asst-seeded',
- operationId: 'op-test',
- topicId: 'topic-test',
- },
- items: [
- {
- allowedActions: ['select_provider_option', 'skip_interaction'],
- detail: {
- description: 'Permission',
- options: [
- { description: undefined, id: 'allow', label: 'Allow' },
- { description: undefined, id: 'deny', label: 'Deny' },
- ],
- title: 'Run command?',
- type: 'permission',
- },
- interactionKind: 'permission',
- provider: 'devin',
- sourceRef: {
- operationId: 'op-test',
- toolCallId: 'permission-1',
- type: 'heterogeneous',
- },
- surface: 'form',
- },
- ],
- systemActionEligibility: 'review_only',
- });
- expect(pending.batch.activityKey).toMatch(
- /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
- );
- expect(pending.items[0].requestRevision).toEqual({
- hash: expect.stringMatching(/^[0-9a-f]{64}$/),
- version: 1,
- });
- expect(JSON.stringify(pending)).not.toContain('privateRawArgument');
-
- await ingest(h, [
- buildEvent('agent_intervention_response', 1, {
- producerAck: false,
- resolutionRequestId: requestId,
- result: { 'Run command?': 'allow' },
- toolCallId: 'permission-1',
- }),
- ]);
- expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
- expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
-
- const producerAck = buildEvent('agent_intervention_response', 2, {
- producerAck: true,
- resolutionRequestId: requestId,
- result: { 'Run command?': 'allow' },
- toolCallId: 'permission-1',
- });
- await ingest(h, [producerAck]);
- await ingest(h, [{ ...producerAck, timestamp: producerAck.timestamp + 1 }]);
-
- expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
- expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledTimes(1);
- expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledWith({
- operationId: 'op-test',
- ownerUserId: 'user-test',
- resolutionRequestId: requestId,
- status: 'resolved',
- toolCallId: 'permission-1',
- workspaceId: undefined,
- });
- });
-
- it('gives concurrent callbacks in one assistant step distinct sealed batch identities', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
- const intervention = (toolCallId: string) =>
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Question',
- multiSelect: false,
- options: [{ label: 'Continue' }],
- question: `Continue ${toolCallId}?`,
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'claude-code',
- interactionKind: 'question',
- provider: 'claude-code',
- toolCallId,
- });
-
- await ingest(h, [intervention('question-1'), intervention('question-2')]);
-
- expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(2);
- const notifications = notifyAgentInterventionRequired.mock.calls.map(([params]) => params);
- expect(notifications.map(({ batch }) => batch.id)).toEqual([
- 'op-test:0:asst-seeded:question-1',
- 'op-test:0:asst-seeded:question-2',
- ]);
- expect(new Set(notifications.map(({ batch }) => batch.activityKey)).size).toBe(2);
- expect(notifications.every(({ batch }) => batch.allowedActions.length === 0)).toBe(true);
- for (const notification of notifications) {
- expect(notification.items[0].allowedActions).toEqual([
- 'submit_answers',
- 'skip_interaction',
- ]);
- }
- });
-
- it('matches Web plan actions without advertising reserved cancel', async () => {
- const h = createHarness({ topicAgentId: 'agent-test' });
- await ingest(h, [
- buildEvent('agent_intervention_request', 0, {
- apiName: 'askUserQuestion',
- arguments: JSON.stringify({
- questions: [
- {
- header: 'Plan',
- multiSelect: false,
- options: [{ id: 'accept', label: 'Accept plan' }],
- question: 'Proceed with this plan?',
- },
- ],
- }),
- deadline: 1_900_000_000_000,
- identifier: 'cursor',
- interactionKind: 'plan',
- provider: 'cursor',
- toolCallId: 'plan-1',
- }),
- ]);
-
- const pending = notifyAgentInterventionRequired.mock.calls[0][0];
- expect(pending.items[0]).toMatchObject({
- allowedActions: ['select_provider_option', 'skip_interaction'],
- interactionKind: 'plan',
- });
- expect(pending.items[0].allowedActions).not.toContain('cancel_interaction');
- });
- });
-});
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
deleted file mode 100644
index a8aa6f2620e..00000000000
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ /dev/null
@@ -1,2328 +0,0 @@
-// @vitest-environment node
-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import { createAdapter } from '@lobechat/heterogeneous-agents';
-import { ThreadStatus } from '@lobechat/types';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- __resetOperationStatesForTesting,
- HeterogeneousPersistenceHandler,
-} from '../HeterogeneousPersistenceHandler';
-
-interface FakeMessage {
- agentId: string | null;
- content: string;
- error?: any;
- id: string;
- metadata?: any;
- model?: string;
- parentId?: string | null;
- plugin?: any;
- pluginError?: any;
- pluginState?: any;
- provider?: string;
- reasoning?: any;
- role: 'user' | 'assistant' | 'tool' | 'task' | 'system';
- threadId?: string | null;
- tool_call_id?: string;
- tools?: any[];
- topicId: string | null;
-}
-
-interface FakeThread {
- id: string;
- metadata?: any;
- sourceMessageId?: string | null;
- status: string;
- title: string;
- topicId: string;
- type: string;
-}
-
-interface FakeTopicMetadata {
- heteroCurrentMsgId?: { msgId: string; operationId: string };
- runningOperation?: {
- assistantMessageId: string;
- operationId: string;
- threadId?: string;
- };
-}
-
-interface FakeTopic {
- agentId: string | null;
- id: string;
- metadata: FakeTopicMetadata;
-}
-
-const createHarness = (params: {
- assistantAgentId?: string | null;
- assistantMessageId: string;
- /** Stands in for the operation row: is this run still live on this topic? */
- isOperationLiveOnTopic?: (operationId: string, topicId: string) => Promise<boolean>;
- operationId: string;
- topicAgentId?: string | null;
- topicId: string;
- threadId?: string;
-}) => {
- let nextMsgIdSeq = 0;
- const messages = new Map<string, FakeMessage>();
- const threads = new Map<string, FakeThread>();
-
- // Seed the initial assistant message that the orchestrator would have
- // created before triggering the CLI ingest.
- messages.set(params.assistantMessageId, {
- agentId: params.assistantAgentId ?? params.topicAgentId ?? null,
- content: '',
- id: params.assistantMessageId,
- role: 'assistant',
- threadId: params.threadId ?? null,
- topicId: params.topicId,
- });
-
- const messageModel = {
- create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {
- nextMsgIdSeq += 1;
- const msgId = id ?? `msg_${nextMsgIdSeq}`;
- const msg: FakeMessage = {
- agentId: input.agentId ?? null,
- content: input.content ?? '',
- id: msgId,
- metadata: input.metadata,
- model: input.model,
- parentId: input.parentId ?? null,
- plugin: input.plugin,
- provider: input.provider,
- role: input.role!,
- threadId: input.threadId ?? null,
- tool_call_id: input.tool_call_id,
- topicId: input.topicId ?? null,
- };
- messages.set(msgId, msg);
- return msg;
- }),
- update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
- const existing = messages.get(id);
- if (!existing) return { success: false };
- messages.set(id, { ...existing, ...patch });
- return { success: true };
- }),
- updateToolMessage: vi.fn(
- async (
- id: string,
- patch: { content?: string; metadata?: any; pluginError?: any; pluginState?: any },
- ) => {
- const existing = messages.get(id);
- if (!existing) return { success: false };
- messages.set(id, {
- ...existing,
- content: patch.content ?? existing.content,
- metadata: patch.metadata ?? existing.metadata,
- pluginError: patch.pluginError,
- pluginState: patch.pluginState ?? existing.pluginState,
- });
- return { success: true };
- },
- ),
- findById: vi.fn(async (id: string) => messages.get(id) ?? null),
- getLatestSpineMessageId: vi.fn(
- async ({ threadId }: { threadId?: string | null; topicId: string }) => {
- const match = [...messages.values()].findLast(
- (m) =>
- m.role !== 'tool' &&
- (m.threadId ?? null) === (threadId ?? null) &&
- !(m as any).metadata?.signal,
- );
- return match?.id;
- },
- ),
- listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
- };
-
- const threadModel = {
- create: vi.fn(async (input: Partial<FakeThread>) => {
- const thread: FakeThread = {
- id: input.id!,
- metadata: input.metadata,
- sourceMessageId: input.sourceMessageId,
- status: input.status ?? 'active',
- title: input.title ?? '',
- topicId: input.topicId ?? params.topicId,
- type: input.type ?? 'isolation',
- };
- threads.set(thread.id, thread);
- return thread;
- }),
- findById: vi.fn(async (id: string) => threads.get(id) ?? null),
- update: vi.fn(async (id: string, patch: Partial<FakeThread>) => {
- const existing = threads.get(id);
- if (!existing) return;
- threads.set(id, { ...existing, ...patch });
- }),
- };
-
- const topicModel = {
- findById: vi.fn(async (id: string): Promise<FakeTopic | null> => {
- if (id !== params.topicId) return null;
- return {
- agentId: params.topicAgentId ?? null,
- id,
- metadata: {
- runningOperation: {
- assistantMessageId: params.assistantMessageId,
- operationId: params.operationId,
- threadId: params.threadId,
- },
- } satisfies FakeTopicMetadata,
- };
- }),
- updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
- };
-
- const handler = new HeterogeneousPersistenceHandler({
- isOperationLiveOnTopic: params.isOperationLiveOnTopic,
- messageModel: messageModel as any,
- threadModel: threadModel as any,
- topicModel: topicModel as any,
- });
-
- return { handler, messageModel, messages, threadModel, threads, topicModel };
-};
-
-const buildEvent = (
- type: AgentStreamEvent['type'],
- stepIndex: number,
- data: Record<string, unknown>,
- timestamp = 1_700_000_000_000 + stepIndex,
-): AgentStreamEvent => ({
- data,
- operationId: 'op-test',
- stepIndex,
- timestamp,
- type,
-});
-
-describe('HeterogeneousPersistenceHandler', () => {
- beforeEach(() => {
- __resetOperationStatesForTesting();
- });
-
- afterEach(() => {
- __resetOperationStatesForTesting();
- });
-
- describe('state bootstrap', () => {
- it('reads runningOperation from topic.metadata to find the seeded assistantMessageId', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-seeded',
- operationId: 'op-1',
- topicAgentId: 'agent-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hello ' }),
- buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'world' }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- expect(h.topicModel.findById).toHaveBeenCalledWith('topic-1');
- // Text chunks accumulate; flushed to DB at end of each batch (multi-replica fix)
- expect(h.messageModel.update).toHaveBeenCalledWith('asst-seeded', { content: 'hello world' });
- });
-
- it('throws when the topic has no matching runningOperation', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: {
- runningOperation: {
- assistantMessageId: 'asst-other',
- operationId: 'op-OTHER',
- },
- },
- });
-
- await expect(
- h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow(/Stale hetero operation/);
- });
-
- it('rejects seeded assistant ids once runningOperation has been cleared', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: {} as any,
- });
-
- await expect(
- h.handler.ingest({
- assistantMessageId: 'asst-1',
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow(/no active runningOperation/);
- });
-
- it('keeps persisting when the marker is gone but the operation is still running', async () => {
- // The marker is a rendering pointer any client can settle β€” a transport
- // signal (a raw session_complete, or one multiplexed socket failing auth
- // for every operation on the tab) clears it while the CLI keeps
- // streaming. Refusing here discards the rest of a live run's output.
- const isOperationLiveOnTopic = vi.fn(async () => true);
- const h = createHarness({
- assistantMessageId: 'asst-1',
- isOperationLiveOnTopic,
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: {} as any,
- });
-
- await h.handler.ingest({
- assistantMessageId: 'asst-1',
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'kept' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- expect(isOperationLiveOnTopic).toHaveBeenCalledWith('op-1', 'topic-1');
- expect(h.messageModel.update).toHaveBeenCalledWith('asst-1', { content: 'kept' });
- });
-
- it('recovers the assistant pointer from heteroCurrentMsgId when the marker is gone', async () => {
- // Desktop / old-CLI callers forward no assistantMessageId, so once the
- // marker is gone the operation-scoped `heteroCurrentMsgId` is the only
- // pointer left to the turn in flight.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- isOperationLiveOnTopic: async () => true,
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: { heteroCurrentMsgId: { msgId: 'asst-1', operationId: 'op-1' } } as any,
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'kept' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- expect(h.messageModel.update).toHaveBeenCalledWith('asst-1', { content: 'kept' });
- });
-
- it('still refuses a marker-less batch once the operation row is terminal', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- isOperationLiveOnTopic: async () => false,
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: {} as any,
- });
-
- await expect(
- h.handler.ingest({
- assistantMessageId: 'asst-1',
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow(/no active runningOperation/);
- });
-
- it('refuses a superseded batch even while its own operation row is alive', async () => {
- // Liveness must NOT override ownership: a marker naming another run means
- // the topic has moved on, and writing here would mutate a newer turn.
- const isOperationLiveOnTopic = vi.fn(async () => true);
- const h = createHarness({
- assistantMessageId: 'asst-1',
- isOperationLiveOnTopic,
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: {
- runningOperation: { assistantMessageId: 'asst-other', operationId: 'op-OTHER' },
- },
- });
-
- await expect(
- h.handler.ingest({
- assistantMessageId: 'asst-1',
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow(/current operation is op-OTHER/);
- expect(isOperationLiveOnTopic).not.toHaveBeenCalled();
- });
-
- it('validates seeded assistant ids belong to the current topic', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- h.messages.set('asst-other-topic', {
- agentId: null,
- content: '',
- id: 'asst-other-topic',
- role: 'assistant',
- topicId: 'topic-2',
- });
-
- await expect(
- h.handler.ingest({
- assistantMessageId: 'asst-other-topic',
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow(/does not belong to topic topic-1/);
- });
-
- it('rejects mid-flight topic mismatch on the same operationId', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await expect(
- h.handler.ingest({
- events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'y' })],
- operationId: 'op-1',
- topicId: 'topic-OTHER',
- }),
- ).rejects.toThrow(/already bound to topic/);
- });
- });
-
- describe('idempotency', () => {
- it('replaces text with the latest full snapshot and ignores older snapshot seq values', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'hello world',
- snapshotMode: 'replace',
- snapshotSeq: 2,
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent(
- 'stream_chunk',
- 0,
- {
- chunkType: 'text',
- content: 'hello',
- snapshotMode: 'replace',
- snapshotSeq: 1,
- },
- 1_700_000_000_999,
- ),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.content).toBe('hello world');
- expect(asst.metadata?.heteroTextSnapshotSeq).toBe(2);
- });
-
- it('replaces reasoning snapshots idempotently instead of re-appending on redelivery', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'reasoning',
- reasoning: 'thinking hard',
- snapshotMode: 'replace',
- snapshotSeq: 1,
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Redelivery reaching the reducer (a cold replica has an empty
- // processedKeys map β€” simulated here with a different timestamp so the
- // in-memory dedupe does not swallow the event first). A raw delta would
- // re-append and durably double the reasoning; the snapshot must not.
- await h.handler.ingest({
- events: [
- buildEvent(
- 'stream_chunk',
- 0,
- {
- chunkType: 'reasoning',
- reasoning: 'thinking hard',
- snapshotMode: 'replace',
- snapshotSeq: 1,
- },
- 1_700_000_000_999,
- ),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.reasoning?.content).toBe('thinking hard'); // NOT doubled
- expect(asst.metadata?.heteroReasoningSnapshotSeq).toBe(1);
- });
-
- it('drops events with the same (stepIndex, type, timestamp, dataFingerprint) key', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const tools = [
- {
- apiName: 'Bash',
- arguments: '{"cmd":"ls"}',
- id: 'tc-1',
- identifier: 'bash',
- type: 'default',
- },
- ];
- const evt = buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- toolsCalling: tools,
- });
-
- await h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' });
- const createCallsAfterFirst = h.messageModel.create.mock.calls.length;
-
- await h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' });
-
- // Same event re-ingested β†’ idempotency skips it; no extra tool-message create
- expect(h.messageModel.create.mock.calls.length).toBe(createCallsAfterFirst);
- });
-
- it('gates publishing per operation and releases the gate when the operation finishes', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- const first = buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' });
- const second = buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'y' });
-
- // Without operation state (nothing ingested yet, or a cold replica):
- // treat everything as unpublished and latch nothing β€” degraded
- // republish-all rather than silently dropping events.
- expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
- h.handler.markEventPublished('op-1', first);
- expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
-
- await h.handler.ingest({ events: [first, second], operationId: 'op-1', topicId: 'topic-1' });
-
- // Latch per event: only unlatched events remain.
- h.handler.markEventPublished('op-1', first);
- expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([second]);
- h.handler.markEventPublished('op-1', second);
- expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([]);
-
- // finish() drops the per-operation state β€” the gate goes with it.
- await h.handler.finish({ operationId: 'op-1', result: 'success' });
- expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
- });
-
- it('does NOT collide bursty events sharing (stepIndex, type, timestamp) when their data differs', async () => {
- // Producer-side reality: CC adapters stamp every event with `Date.now()`,
- // so multiple `stream_chunk` events within the same step burst through
- // a single millisecond. Without a content fingerprint in the dedupe
- // key, all but the first would be dropped β†’ truncated assistant text.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const sameTimestamp = 1_700_000_000_000;
- const events: AgentStreamEvent[] = [
- {
- ...buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'one ' }),
- timestamp: sameTimestamp,
- },
- {
- ...buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'two ' }),
- timestamp: sameTimestamp,
- },
- {
- ...buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'three' }),
- timestamp: sameTimestamp,
- },
- buildEvent('agent_runtime_end', 0, { reason: 'success' }),
- ];
-
- await h.handler.ingest({ events, operationId: 'op-1', topicId: 'topic-1' });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.content).toBe('one two three');
- });
-
- it('mark-processed-AFTER-success contract: a thrown handler leaves the event un-marked so retry replays it', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // First call to messageModel.update on asst-1 throws once.
- let updateAttempts = 0;
- const realUpdate = h.messageModel.update.getMockImplementation()!;
- h.messageModel.update.mockImplementation(async (id: string, patch: any) => {
- if (id === 'asst-1' && patch.metadata?.usage) {
- updateAttempts += 1;
- if (updateAttempts === 1) {
- throw new Error('flaky');
- }
- }
- return realUpdate(id, patch);
- });
-
- const evt = buildEvent('step_complete', 0, {
- phase: 'turn_metadata',
- usage: { totalInputTokens: 1, totalOutputTokens: 0, totalTokens: 1 },
- });
-
- // First attempt: handler throws.
- await expect(
- h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' }),
- ).rejects.toThrow('flaky');
-
- // Retry SAME event β€” the handler now succeeds because the flake is gone.
- // Critical: the dedupe map didn't pre-mark the failed event, so this
- // re-runs instead of skipping silently.
- await h.handler.ingest({ events: [evt], operationId: 'op-1', topicId: 'topic-1' });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.metadata).toEqual({
- usage: { totalInputTokens: 1, totalOutputTokens: 0, totalTokens: 1 },
- });
- });
- });
-
- describe('3-phase tool persist (main agent)', () => {
- it('keeps tool rows and post-tool assistants attributed to the direct target agent', async () => {
- const h = createHarness({
- assistantAgentId: 'agent-direct-target',
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicAgentId: 'agent-conversation-owner',
- topicId: 'topic-1',
- });
-
- const tool = {
- apiName: 'Read',
- arguments: '{"file_path":"tool-proof.txt"}',
- id: 'tc-1',
- identifier: 'claude-code',
- type: 'default' as const,
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- buildEvent('tool_result', 1, {
- content: 'TOOL_CALL_MARKER',
- isError: false,
- toolCallId: 'tc-1',
- }),
- buildEvent('stream_start', 2, { newStep: true }),
- buildEvent('stream_chunk', 3, {
- chunkType: 'text',
- content: 'TOOL_CALL_MARKER',
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const toolMessage = [...h.messages.values()].find((message) => message.role === 'tool');
- const finalAssistant = [...h.messages.values()].find(
- (message) => message.role === 'assistant' && message.id !== 'asst-1',
- );
-
- expect(toolMessage?.agentId).toBe('agent-direct-target');
- expect(finalAssistant?.agentId).toBe('agent-direct-target');
- expect(finalAssistant?.parentId).toBe('asst-1');
- expect(finalAssistant?.content).toBe('TOOL_CALL_MARKER');
- });
-
- it('writes assistant.tools[] then tool message then backfilled result_msg_id in order', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Capture call order across both methods so we can assert phase
- // sequence (renderer mutates the tools[] array in place across phases,
- // so verifying post-mortem state on call args is unreliable; relative
- // ordering of distinct mock invocations is the durable contract).
- const order: string[] = [];
- const origCreate = h.messageModel.create.getMockImplementation()!;
- const origUpdate = h.messageModel.update.getMockImplementation()!;
- h.messageModel.update.mockImplementation(async (id: string, patch: any) => {
- if (id === 'asst-1') order.push('update-asst');
- return origUpdate(id, patch);
- });
- h.messageModel.create.mockImplementation(async (input: any, id?: string) => {
- order.push(input.role === 'tool' ? 'create-tool' : 'create-other');
- return origCreate(input, id);
- });
-
- const tool = {
- apiName: 'Bash',
- arguments: '{"cmd":"ls"}',
- id: 'tc-1',
- identifier: 'bash',
- type: 'default' as const,
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'looking ' }),
- buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- buildEvent('tool_result', 2, {
- content: 'a.ts\nb.ts',
- isError: false,
- toolCallId: 'tc-1',
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Phase 1 (update-asst) β†’ Phase 2 (create-tool) β†’ Phase 3 (update-asst) β†’ batch flush (update-asst)
- expect(order).toEqual(['update-asst', 'create-tool', 'update-asst', 'update-asst']);
-
- // Tool message exists with content from tool_result + correct tool_call_id
- const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
- expect(toolMsg).toBeDefined();
- expect(toolMsg?.tool_call_id).toBe('tc-1');
- expect(toolMsg?.content).toBe('a.ts\nb.ts');
-
- // Final assistant.tools[] carries the backfilled result_msg_id
- const finalAsst = h.messages.get('asst-1')!;
- expect(finalAsst.tools?.[0]).toMatchObject({
- id: 'tc-1',
- result_msg_id: toolMsg?.id,
- });
- expect(finalAsst.content).toBe('looking ');
- });
-
- it('skips tool_use that have already been persisted in the same turn', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const tool = {
- apiName: 'Bash',
- arguments: '{"cmd":"ls"}',
- id: 'tc-1',
- identifier: 'bash',
- type: 'default',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const toolMessages = [...h.messages.values()].filter((m) => m.role === 'tool');
- expect(toolMessages).toHaveLength(1);
- });
- });
-
- describe('step boundaries (stream_start newStep)', () => {
- it('recovers an isolation run from the thread spine instead of the projected topic reply', async () => {
- const h = createHarness({
- assistantMessageId: 'thread-asst-1',
- operationId: 'op-1',
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
- h.messages.set('projected-topic-reply', {
- agentId: 'target-agent',
- content: 'projected answer',
- id: 'projected-topic-reply',
- role: 'assistant',
- threadId: null,
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_start', 1, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const nextThreadAssistant = [...h.messages.values()].find(
- (message) =>
- message.role === 'assistant' &&
- message.threadId === 'thread-1' &&
- message.id !== 'thread-asst-1',
- );
- expect(nextThreadAssistant?.parentId).toBe('thread-asst-1');
- expect(h.messageModel.getLatestSpineMessageId).toHaveBeenCalledWith({
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
- });
-
- it('flushes prior content, opens a new assistant chained off the prior assistant (spine)', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const tool = {
- apiName: 'Bash',
- arguments: '{}',
- id: 'tc-1',
- identifier: 'bash',
- type: 'default',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1 ' }),
- buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- buildEvent('tool_result', 2, {
- content: 'ok',
- toolCallId: 'tc-1',
- }),
- buildEvent('stream_start', 3, { newStep: true }),
- buildEvent('stream_chunk', 4, { chunkType: 'text', content: 'step2' }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // First step: asst-1 got content + tools.
- // After step boundary (phase 2 spine rule): a NEW assistant is created
- // chained off the prior assistant (asst-1), with the tool as an inline
- // child β€” the read side reconstructs the zigzag.
- const newAssistants = [...h.messages.values()].filter(
- (m) => m.role === 'assistant' && m.id !== 'asst-1',
- );
- expect(newAssistants).toHaveLength(1);
- expect(newAssistants[0].parentId).toBe('asst-1');
- });
-
- it('chains off the prior assistant (spine) across a multi-replica boundary, recovered from DB', async () => {
- // Phase 2: the chain parent is the run's latest non-tool / non-signal
- // scoped message, recovered from the DB (`getLatestSpineMessageId`)
- // independent of the in-memory current-assistant pointer. So even when the
- // prior step's tools_calling drained on a DIFFERENT replica (this replica's
- // toolState stays empty), step 2 still chains off step 1's assistant β€” a
- // linear spine, not a fork.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Track topic.metadata so updateMetadata({heteroCurrentMsgId}) becomes
- // observable to subsequent findById calls β€” the default harness mock is
- // a no-op which would mask the bug behind a sync-rollback artifact.
- const metaState: FakeTopicMetadata = {
- runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
- };
- h.topicModel.findById.mockImplementation(async (id: string) => {
- if (id !== 'topic-1') return null;
- return { agentId: null, id, metadata: { ...metaState } };
- });
- h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
- Object.assign(metaState, patch);
- });
-
- // ── Batch 1: this replica drains step 1's stream_start ──
- // No tools yet on this asst β†’ handleStepStart chains step 1 off
- // 'asst-init' (correct, since asst-init had no tools).
- await h.handler.ingest({
- events: [buildEvent('stream_start', 1, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const step1Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init',
- )!;
- expect(step1Asst).toBeDefined();
- expect(step1Asst.parentId).toBe('asst-init');
-
- // ── Simulate "another replica drained step 1's tools_calling + result" ──
- // The other replica would have:
- // 1. Created a tool message
- // 2. Rewritten step1Asst.tools[] with result_msg_id pointing at it
- // Both writes hit DB. THIS replica's in-memory state.toolState stays []
- // (reset by handleStepStart) and has no idea this happened.
- h.messages.set('tool-other-replica', {
- agentId: null,
- content: 'result body',
- id: 'tool-other-replica',
- parentId: step1Asst.id,
- role: 'tool',
- tool_call_id: 'tc-1',
- topicId: 'topic-1',
- });
- h.messages.set(step1Asst.id, {
- ...h.messages.get(step1Asst.id)!,
- model: 'claude-sonnet-4-6',
- provider: 'claude-code',
- tools: [
- {
- apiName: 'Bash',
- arguments: '{}',
- id: 'tc-1',
- identifier: 'bash',
- result_msg_id: 'tool-other-replica',
- type: 'default',
- },
- ],
- });
-
- // ── Batch 2: step 2 stream_start lands back on THIS replica ──
- // The DB spine query returns step1Asst (the latest non-tool main message),
- // so step 2 chains off it regardless of this replica's empty toolState.
- await h.handler.ingest({
- events: [buildEvent('stream_start', 2, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const step2Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
- );
- expect(step2Asst).toBeDefined();
- expect(step2Asst!.parentId).toBe(step1Asst.id);
- // And the new assistant should inherit model/provider that the other
- // replica wrote β€” refresh also restores lastModel/lastProvider so we
- // no longer create assistants with model=null/provider=null on the
- // replica that didn't drain step_complete.
- expect(step2Asst!.model).toBe('claude-sonnet-4-6');
- expect(step2Asst!.provider).toBe('claude-code');
- });
-
- it('chains off the spine regardless of the prior step tool backfill state', async () => {
- // Phase 2: the chain anchors to the spine (latest non-tool main message),
- // so the prior step's tool-row / result_msg_id backfill timing β€” which
- // used to matter for the tool anchor β€” no longer affects the chain. Even
- // with a tool row present but no tools[] backfill, step 2 chains off the
- // prior assistant.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const metaState: FakeTopicMetadata = {
- runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
- };
- h.topicModel.findById.mockImplementation(async (id: string) => {
- if (id !== 'topic-1') return null;
- return { agentId: null, id, metadata: { ...metaState } };
- });
- h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
- Object.assign(metaState, patch);
- });
-
- // ── Batch 1: this replica drains step 1's stream_start (no tools yet) ──
- await h.handler.ingest({
- events: [buildEvent('stream_start', 1, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- const step1Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init',
- )!;
-
- // ── Other replica created the tool ROW but NOT the tools[] backfill ──
- // Note: step1Asst.tools[] is intentionally left WITHOUT result_msg_id,
- // so the ingest refresh cannot recover the anchor.
- h.messages.set('tool-row-only', {
- agentId: null,
- content: 'result body',
- id: 'tool-row-only',
- parentId: step1Asst.id,
- role: 'tool',
- threadId: null,
- tool_call_id: 'tc-1',
- topicId: 'topic-1',
- });
-
- // ── Batch 2: step 2 stream_start lands on THIS (empty-state) replica ──
- await h.handler.ingest({
- events: [buildEvent('stream_start', 2, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const step2Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
- );
- expect(step2Asst).toBeDefined();
- // Chains off the prior assistant (spine) β†’ wire stays linear; the tool is inline.
- expect(step2Asst!.parentId).toBe(step1Asst.id);
- });
-
- it('chains off the spine when parallel tools are only partially backfilled', async () => {
- // Regression for main-chain breaks with parallel/multi tool calls:
- // tool A is visible in assistant.tools[].result_msg_id, while tool B's
- // row exists but Phase 3 has not backfilled assistant.tools[] yet. The
- // step anchor must be tool B, not the earlier resolved tool A.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const metaState: FakeTopicMetadata = {
- runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
- };
- h.topicModel.findById.mockImplementation(async (id: string) => {
- if (id !== 'topic-1') return null;
- return { agentId: null, id, metadata: { ...metaState } };
- });
- h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
- Object.assign(metaState, patch);
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_start', 1, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- const step1Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init',
- )!;
-
- h.messages.set('tool-a-backfilled', {
- agentId: null,
- content: 'tool A result',
- id: 'tool-a-backfilled',
- parentId: step1Asst.id,
- role: 'tool',
- threadId: null,
- tool_call_id: 'tc-a',
- topicId: 'topic-1',
- });
- h.messages.set('tool-b-row-only', {
- agentId: null,
- content: 'tool B result',
- id: 'tool-b-row-only',
- parentId: step1Asst.id,
- role: 'tool',
- threadId: null,
- tool_call_id: 'tc-b',
- topicId: 'topic-1',
- });
- h.messages.set(step1Asst.id, {
- ...h.messages.get(step1Asst.id)!,
- tools: [
- {
- apiName: 'Read',
- arguments: '{}',
- id: 'tc-a',
- identifier: 'read',
- result_msg_id: 'tool-a-backfilled',
- type: 'default',
- },
- {
- apiName: 'Bash',
- arguments: '{}',
- id: 'tc-b',
- identifier: 'bash',
- type: 'default',
- },
- ],
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_start', 2, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const step2Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
- );
- expect(step2Asst).toBeDefined();
- // Spine-anchored: parallel-tool backfill state is irrelevant to the chain.
- expect(step2Asst!.parentId).toBe(step1Asst.id);
- });
-
- it('ignores subagent tool rows (threadId set) when resolving the step anchor', async () => {
- // A subagent tool row lives on its own thread and must never anchor the
- // main-agent wire. If the only `role:'tool'` child carries a threadId,
- // the fallback must skip it and chain off the previous assistant.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const metaState: FakeTopicMetadata = {
- runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
- };
- h.topicModel.findById.mockImplementation(async (id: string) => {
- if (id !== 'topic-1') return null;
- return { agentId: null, id, metadata: { ...metaState } };
- });
- h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
- Object.assign(metaState, patch);
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_start', 1, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- const step1Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init',
- )!;
-
- h.messages.set('subagent-tool', {
- agentId: null,
- content: 'sub result',
- id: 'subagent-tool',
- parentId: step1Asst.id,
- role: 'tool',
- threadId: 'thread-sub',
- tool_call_id: 'tc-sub',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_start', 2, { newStep: true })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const step2Asst = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
- );
- expect(step2Asst).toBeDefined();
- expect(step2Asst!.parentId).toBe(step1Asst.id);
- });
-
- it('handleTurnMetadata persists model/provider to DB so other replicas can recover lastModel/lastProvider', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('step_complete', 0, {
- model: 'claude-sonnet-4-6',
- phase: 'turn_metadata',
- provider: 'claude-code',
- usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Was previously `{ metadata: { usage } }` only β€” now extended to also
- // carry model/provider so a replica picking up the next step boundary
- // can read them back from DB even if it never drained this event.
- expect(h.messageModel.update).toHaveBeenCalledWith('asst-init', {
- metadata: { usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 } },
- model: 'claude-sonnet-4-6',
- provider: 'claude-code',
- });
- });
-
- it('retry recovers an unresolved tool that another replica only Phase-1 registered (no false-positive persistedIds)', async () => {
- // Race: another replica wrote `assistant.tools[]` (Phase 1) but its
- // Phase 2 β€” creating the `role:'tool'` row + backfilling
- // `result_msg_id` β€” hasn't landed yet (or threw). The BatchIngester
- // then retries the SAME tools_calling event onto THIS replica.
- //
- // If `persistedIds` includes the unresolved id, `persistToolBatch`
- // filters it out of `freshForCreate`, skips the create, and rewrites
- // `tools[]` unchanged β†’ the tool is orphaned (never gets a tool
- // message, never gets `result_msg_id`). Fix: only mark ids whose
- // `result_msg_id` is filled in as persisted.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Pre-populate the initial assistant with a Phase-1-only tool entry
- // (no `result_msg_id`), simulating the other replica's mid-flight write.
- h.messages.set('asst-init', {
- ...h.messages.get('asst-init')!,
- tools: [
- {
- apiName: 'Bash',
- arguments: '{"cmd":"ls"}',
- id: 'tc-unresolved',
- identifier: 'bash',
- type: 'default',
- // NOTE: no result_msg_id β€” Phase 2 has not run yet.
- },
- ],
- });
-
- // Retry of the same tools_calling event lands on this replica.
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- toolsCalling: [
- {
- apiName: 'Bash',
- arguments: '{"cmd":"ls"}',
- id: 'tc-unresolved',
- identifier: 'bash',
- type: 'default',
- },
- ],
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // The tool message must have been created (Phase 2 completed via retry)
- // and assistant.tools[0].result_msg_id must point at it.
- const toolMsgs = [...h.messages.values()].filter((m) => m.role === 'tool');
- expect(toolMsgs).toHaveLength(1);
- expect(toolMsgs[0].tool_call_id).toBe('tc-unresolved');
-
- const asst = h.messages.get('asst-init')!;
- expect(asst.tools).toHaveLength(1);
- expect(asst.tools![0].result_msg_id).toBe(toolMsgs[0].id);
- });
- });
-
- describe('subagent threads', () => {
- it('lazy-creates the thread + user + first assistant on first subagent chunk', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const subagentCtx = {
- parentToolCallId: 'tc-spawn-1',
- spawnMetadata: {
- description: 'Explore CC stream chain',
- prompt: 'Investigate adapter logic',
- subagentType: 'Explore',
- },
- subagentMessageId: 'sub-msg-1',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'subagent thinking',
- subagent: subagentCtx,
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- expect(h.threads.size).toBe(1);
- const thread = [...h.threads.values()][0];
- expect(thread.title).toBe('Explore CC stream chain');
- expect(thread.metadata?.sourceToolCallId).toBe('tc-spawn-1');
- expect(thread.metadata?.subagentType).toBe('Explore');
- expect(thread.sourceMessageId).toBe('asst-1');
-
- const threadMessages = [...h.messages.values()].filter((m) => m.threadId === thread.id);
- expect(threadMessages.map((m) => m.role)).toEqual(['user', 'assistant']);
- expect(threadMessages[0].content).toBe('Investigate adapter logic');
- expect(threadMessages[1].parentId).toBe(threadMessages[0].id);
- });
-
- it('cuts a new in-thread assistant when subagentMessageId advances', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const ctxBase = {
- parentToolCallId: 'tc-spawn-1',
- spawnMetadata: { prompt: 'do work', subagentType: 'Worker' },
- };
-
- const tool = {
- apiName: 'Read',
- arguments: '{}',
- id: 'inner-tc-1',
- identifier: 'read',
- type: 'default',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'tools_calling',
- subagent: { ...ctxBase, subagentMessageId: 'sub-1' },
- toolsCalling: [tool],
- }),
- buildEvent('stream_chunk', 1, {
- chunkType: 'text',
- content: 'turn-2 thinking',
- subagent: { ...ctxBase, subagentMessageId: 'sub-2' },
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const threadId = [...h.threads.keys()][0];
- const threadAssts = [...h.messages.values()].filter(
- (m) => m.threadId === threadId && m.role === 'assistant',
- );
- // Initial assistant + new turn assistant after subagentMessageId change
- expect(threadAssts.length).toBeGreaterThanOrEqual(2);
-
- // Tool message exists in the thread
- const threadTool = [...h.messages.values()].find(
- (m) => m.threadId === threadId && m.role === 'tool',
- );
- expect(threadTool?.tool_call_id).toBe('inner-tc-1');
- expect(threadTool?.parentId).toBe(threadAssts[0].id);
-
- // Second-turn assistant chains off the prior in-thread assistant (spine),
- // with the tool as an inline child (phase 2 rule).
- const secondTurn = threadAssts[1];
- expect(secondTurn.parentId).toBe(threadAssts[0].id);
- });
-
- it('finalizes the run with terminal assistant carrying tool_result content', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const subagentCtx = {
- parentToolCallId: 'tc-spawn-1',
- spawnMetadata: { prompt: 'p', subagentType: 'X' },
- subagentMessageId: 'sub-1',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'thinking',
- subagent: subagentCtx,
- }),
- buildEvent('tool_result', 1, {
- content: 'final summary from subagent',
- toolCallId: 'tc-spawn-1',
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const threadId = [...h.threads.keys()][0];
- const threadAssts = [...h.messages.values()].filter(
- (m) => m.threadId === threadId && m.role === 'assistant',
- );
- const terminal = threadAssts.at(-1);
- expect(terminal?.content).toBe('final summary from subagent');
-
- // Thread status updated
- const thread = h.threads.get(threadId)!;
- expect(thread.status).toBeDefined();
- });
-
- it('writes subagent usage + model onto the in-thread assistant, and finalize only flips status', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const subagentCtx = {
- parentToolCallId: 'tc-spawn-1',
- spawnMetadata: { prompt: 'p', subagentType: 'Explore' },
- subagentMessageId: 'sub-1',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'working',
- subagent: subagentCtx,
- }),
- buildEvent('stream_chunk', 1, {
- chunkType: 'tools_calling',
- subagent: subagentCtx,
- toolsCalling: [
- {
- apiName: 'Bash',
- arguments: '{}',
- id: 'tc-child',
- identifier: 'bash',
- type: 'default',
- },
- ],
- }),
- // Subagent turn_metadata carries the authoritative per-turn usage + model.
- buildEvent('step_complete', 2, {
- model: 'claude-opus-4-8',
- phase: 'turn_metadata',
- provider: 'claude-code',
- subagent: subagentCtx,
- usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
- }),
- buildEvent('tool_result', 3, { content: 'final', toolCallId: 'tc-spawn-1' }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const threadId = [...h.threads.keys()][0];
- const thread = h.threads.get(threadId)!;
- // Metrics are NOT denormalized onto metadata β€” derived on read instead.
- expect(thread.metadata?.totalTokens).toBeUndefined();
- expect(thread.metadata?.totalToolCalls).toBeUndefined();
- // Create-time peer fields untouched; finalize only flips status.
- expect(thread.metadata?.sourceToolCallId).toBe('tc-spawn-1');
- expect(thread.metadata?.subagentType).toBe('Explore');
- expect(thread.status).toBe(ThreadStatus.Active);
-
- // The in-thread assistant got usage + model written β€” the rows the
- // read-time aggregation later sums over.
- const threadAssts = [...h.messages.values()].filter(
- (m) => m.threadId === threadId && m.role === 'assistant',
- );
- const withUsage = threadAssts.find((m) => m.metadata?.usage?.totalTokens === 15);
- expect(withUsage?.model).toBe('claude-opus-4-8');
- });
- });
-
- describe('terminal events and finish()', () => {
- it('flushes accumulated content on agent_runtime_end', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'final answer' }),
- buildEvent('agent_runtime_end', 1, { reason: 'success' }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.content).toBe('final answer');
- });
-
- /**
- * @example A finish request on a stale replica preserves the final snapshot written elsewhere.
- */
- it('does not let a stale finish overwrite a newer assistant snapshot', async () => {
- // ROOT CAUSE:
- //
- // A warm serverless replica can retain an older per-operation accumulator
- // while another replica persists a newer text snapshot to the shared DB.
- // Before the fix, heteroFinish flushed the stale accumulator and replaced
- // the final answer with the preceding progress message.
- //
- // We fixed this by making heteroIngest the only content/reasoning writer;
- // a successful finish now releases operation state without rewriting text.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, {
- chunkType: 'text',
- content: 'progress',
- snapshotMode: 'replace',
- snapshotSeq: 4,
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Simulate a newer snapshot committed by another Lambda replica.
- h.messages.set('asst-1', {
- ...h.messages.get('asst-1')!,
- content: 'progress\n\nfinal answer',
- metadata: { heteroTextSnapshotSeq: 5 },
- });
-
- await h.handler.finish({
- operationId: 'op-1',
- result: 'success',
- topicId: 'topic-1',
- });
-
- expect(h.messages.get('asst-1')).toMatchObject({
- content: 'progress\n\nfinal answer',
- metadata: { heteroTextSnapshotSeq: 5 },
- });
- });
-
- it.each([false, true])(
- 'does not persist a Codex reconnect on either side of a tool-created step (failed=%s)',
- async (failed) => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- const adapter = createAdapter('codex');
- const rawEvents = [
- { type: 'turn.started' },
- { message: 'Reconnecting... 2/5 (request timed out)', type: 'error' },
- {
- item: { id: 'progress', text: 'Inspecting the workflow.', type: 'agent_message' },
- type: 'item.completed',
- },
- {
- item: { command: 'printf inspected', id: 'inspect', type: 'command_execution' },
- type: 'item.started',
- },
- {
- item: {
- aggregated_output: 'inspected',
- command: 'printf inspected',
- exit_code: 0,
- id: 'inspect',
- status: 'completed',
- type: 'command_execution',
- },
- type: 'item.completed',
- },
- {
- item: {
- id: 'answer',
- text: 'Version checks do not publish releases.',
- type: 'agent_message',
- },
- type: 'item.completed',
- },
- failed
- ? { error: { message: 'stream closed before response.completed' }, type: 'turn.failed' }
- : { type: 'turn.completed' },
- ];
- // Keep ingest batches separated across the error/tool/newStep boundaries.
- // Mock only the database, not the adapter or persistence coordinator.
- let timestamp = 1_700_000_000_000;
- for (const raw of rawEvents) {
- const events = adapter.adapt(raw);
- if (events.length === 0) continue;
- await h.handler.ingest({
- events: events.map((event) =>
- buildEvent(event.type, event.stepIndex, event.data, timestamp++),
- ),
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- }
- await h.handler.finish({
- error: failed
- ? { message: 'stream closed before response.completed', type: 'AgentRuntimeError' }
- : undefined,
- operationId: 'op-1',
- result: failed ? 'error' : 'success',
- topicId: 'topic-1',
- });
-
- const assistants = [...h.messages.values()].filter(
- (message) => message.role === 'assistant',
- );
- expect(assistants).toHaveLength(2);
- expect(assistants.map((message) => message.content)).toEqual([
- 'Inspecting the workflow.',
- 'Version checks do not publish releases.',
- ]);
- expect(assistants[0].error).toBeUndefined();
- expect(assistants.filter((message) => message.error)).toHaveLength(failed ? 1 : 0);
- if (failed) {
- expect(assistants[1].error.message).toBe('stream closed before response.completed');
- }
- expect([...h.messages.values()].find((message) => message.role === 'tool')).toMatchObject({
- content: 'inspected',
- parentId: 'asst-1',
- });
- },
- );
-
- it('writes error onto the assistant when terminal event is error', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'partial' }),
- buildEvent('error', 1, {
- message: 'CLI auth required',
- type: 'AuthRequired',
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.error).toBeDefined();
- expect(asst.error.message).toBe('CLI auth required');
- expect(asst.content).toBe('partial');
- });
-
- it('finish() preserves a structured status-guide error body on the assistant', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Register op state without any in-stream error β€” the process-level
- // failure (spawn ENOENT) only arrives via the finish payload.
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: '' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.finish({
- error: {
- body: {
- agentType: 'claude-code',
- code: 'cli_not_found',
- stderr: 'Error: spawn claude ENOENT',
- },
- message: 'Claude Code CLI was not found on the machine running this agent.',
- type: 'stream_error',
- },
- operationId: 'op-1',
- result: 'error',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.error).toBeDefined();
- // `body` must survive formatErrorForState untouched β€” the client's
- // status-guide UI gates on `body.agentType` + `body.code`.
- expect(asst.error.body).toMatchObject({
- agentType: 'claude-code',
- code: 'cli_not_found',
- stderr: 'Error: spawn claude ENOENT',
- });
- expect(asst.error.message).toContain('was not found');
- });
-
- it('finish() must not downgrade an in-stream status-guide error with a flat message', async () => {
- // Remote CC relays an API failure (529 overloaded / rate limit) as an
- // in-stream `error` event whose data the adapter already classified into
- // the structured status-guide shape (`agentType` + `code`). Older CLIs
- // then send a finish error flattened to a bare `{ message }` β€” writing
- // that over the persisted structured error would demote the client from
- // the dedicated guide card to the generic error alert.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const overloadedMessage = 'API Error: 529 Overloaded. This is a server-side issue.';
- await h.handler.ingest({
- events: [
- buildEvent('error', 0, {
- agentType: 'claude-code',
- code: 'overloaded',
- error: overloadedMessage,
- message: overloadedMessage,
- stderr: overloadedMessage,
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.finish({
- error: { message: overloadedMessage, type: 'AgentRuntimeError' },
- operationId: 'op-1',
- result: 'error',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.error.body).toMatchObject({
- agentType: 'claude-code',
- code: 'overloaded',
- });
- });
-
- it('finish() with NO prior ingest bootstraps state and writes the error (spawn-fail path)', async () => {
- // The real process-level failure shape: spawn ENOENT produces ZERO
- // stream events, so no ingest ever created an OperationState. finish()
- // must bootstrap from topic.metadata.runningOperation and write the
- // error itself β€” deferring it to CompletionLifecycle (which runs AFTER
- // the agent_runtime_end publish) races the client's message refetch.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.finish({
- error: {
- body: {
- agentType: 'claude-code',
- code: 'cli_not_found',
- stderr: 'Error: spawn claude ENOENT',
- },
- message: 'Claude Code CLI was not found on the machine running this agent.',
- type: 'AgentRuntimeError',
- },
- operationId: 'op-1',
- result: 'error',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.error).toBeDefined();
- expect(asst.error.body).toMatchObject({
- agentType: 'claude-code',
- code: 'cli_not_found',
- });
- expect(asst.error.message).toContain('was not found');
- });
-
- it('finish() projects the terminal error by assistant id after runningOperation was cleared', async () => {
- // Gateway session completion can clear runningOperation before the CLI's
- // heteroFinish request arrives. The producer-carried assistant id must
- // keep that race from leaving an empty assistant with error=null.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- // The CLI echoed the failure into the answer before reporting it β€” that
- // echo is what `clearEchoedContent` drops.
- h.messages.get('asst-1')!.content = "You've hit your session limit";
- h.topicModel.findById.mockResolvedValue({
- agentId: null,
- id: 'topic-1',
- metadata: {},
- });
-
- await h.handler.finish({
- assistantMessageId: 'asst-1',
- error: {
- body: {
- agentType: 'claude-code',
- clearEchoedContent: true,
- code: 'rate_limit',
- details: { kind: 'usage_limit' },
- },
- message: "You've hit your session limit",
- type: 'AgentRuntimeError',
- },
- operationId: 'op-1',
- result: 'error',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.error).toMatchObject({
- body: {
- agentType: 'claude-code',
- code: 'rate_limit',
- },
- message: "You've hit your session limit",
- type: 'AgentRuntimeError',
- });
- expect(asst.content).toBe('');
- });
-
- it('finish() keeps real work when a quota error only marks an echo', async () => {
- // Kimi Code can burn a full run and only then hit its weekly window. The
- // finish error carries clearEchoedContent (every rate_limit does), but
- // the streamed answer is not an echo of it and must survive.
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.messages.get('asst-1')!.content = 'Refactored the adapter and ran the tests.';
- h.topicModel.findById.mockResolvedValue({
- agentId: null,
- id: 'topic-1',
- metadata: {},
- });
-
- await h.handler.finish({
- assistantMessageId: 'asst-1',
- error: {
- body: {
- agentType: 'kimi-code',
- clearEchoedContent: true,
- code: 'rate_limit',
- details: { kind: 'usage_limit' },
- },
- message: "You've reached your weekly (7-day) usage limit.",
- type: 'AgentRuntimeError',
- },
- operationId: 'op-1',
- result: 'error',
- topicId: 'topic-1',
- });
-
- const asst = h.messages.get('asst-1')!;
- expect(asst.content).toBe('Refactored the adapter and ran the tests.');
- expect(asst.error).toMatchObject({ body: { agentType: 'kimi-code', code: 'rate_limit' } });
- });
-
- it('finish() with no state stays a no-op for a stale operation (mismatched runningOperation)', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- // The topic's runningOperation belongs to a DIFFERENT operation β€” a late
- // finish from a superseded run must not touch the current turn.
- h.topicModel.findById.mockResolvedValueOnce({
- agentId: null,
- id: 'topic-1',
- metadata: {
- runningOperation: {
- assistantMessageId: 'asst-other',
- operationId: 'op-OTHER',
- },
- },
- });
-
- await expect(
- h.handler.finish({
- error: { message: 'boom', type: 'AgentRuntimeError' },
- operationId: 'op-1',
- result: 'error',
- topicId: 'topic-1',
- }),
- ).resolves.toBeUndefined();
-
- expect(h.messages.get('asst-1')!.error).toBeUndefined();
- expect(h.messageModel.update).not.toHaveBeenCalled();
- });
-
- it('finish() drops the per-operation state so a retry starts fresh', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'a' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- await h.handler.finish({ operationId: 'op-1', result: 'success' });
-
- // Same operationId on a different topic should now succeed (state was dropped)
- h.topicModel.findById.mockResolvedValue({
- agentId: null,
- id: 'topic-2',
- metadata: {
- runningOperation: {
- assistantMessageId: 'asst-2',
- operationId: 'op-1',
- },
- },
- });
- h.messages.set('asst-2', {
- agentId: null,
- content: '',
- id: 'asst-2',
- role: 'assistant',
- topicId: 'topic-2',
- });
-
- await expect(
- h.handler.ingest({
- events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'b' })],
- operationId: 'op-1',
- topicId: 'topic-2',
- }),
- ).resolves.not.toThrow();
- });
- });
-
- describe('cold replica state restoration (Vercel serverless)', () => {
- it('restores accumulatedContent from DB so a cold instance does not truncate previous text', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Batch 1 (warm instance): stream two text chunks, flush happens via flushBatchContent
- await h.handler.ingest({
- events: [
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hello ' }, 1000),
- buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'world' }, 1001),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // DB should have the partial content written by flushBatchContent
- expect(h.messages.get('asst-1')?.content).toBe('hello world');
-
- // Simulate cold replica: drop the in-memory operation state
- __resetOperationStatesForTesting();
-
- // Batch 2 (cold instance): receives more text.
- // Without restoration the new instance would start with accumulatedContent='' and
- // write only " more" β€” truncating "hello world".
- await h.handler.ingest({
- events: [buildEvent('agent_runtime_end', 0, { reason: 'success' }, 2000)],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // The terminal flush should preserve the previously accumulated content.
- expect(h.messages.get('asst-1')?.content).toBe('hello world');
- });
-
- it('restores toolState.payloads and persistedIds so cold replica does not duplicate tools or overwrite tools[]', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // Batch 1 (warm): persist tool1
- const tool1: any = {
- apiName: 'tool1',
- arguments: '{}',
- id: 'tc-1',
- identifier: 'tool1',
- type: 'default',
- };
- await h.handler.ingest({
- events: [
- buildEvent(
- 'stream_chunk',
- 0,
- { chunkType: 'tools_calling', toolsCalling: [tool1] },
- 1000,
- ),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // assistant.tools[] should have tool1
- const asstAfterBatch1 = h.messages.get('asst-1')!;
- expect(asstAfterBatch1.tools).toHaveLength(1);
- expect(asstAfterBatch1.tools![0].id).toBe('tc-1');
- // tool message created for tool1
- const toolMsgsBatch1 = [...h.messages.values()].filter((m) => m.role === 'tool');
- expect(toolMsgsBatch1).toHaveLength(1);
-
- // Simulate cold replica: drop in-memory state
- __resetOperationStatesForTesting();
-
- // Batch 2 (cold): receives tool2 β€” should ADD to tools[], not overwrite
- const tool2: any = {
- apiName: 'tool2',
- arguments: '{}',
- id: 'tc-2',
- identifier: 'tool2',
- type: 'default',
- };
- await h.handler.ingest({
- events: [
- buildEvent(
- 'stream_chunk',
- 1,
- { chunkType: 'tools_calling', toolsCalling: [tool2] },
- 2000,
- ),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const asstAfterBatch2 = h.messages.get('asst-1')!;
- // Both tools should be present β€” cold restore kept tool1 in payloads
- expect(asstAfterBatch2.tools).toHaveLength(2);
-
- // tool1 should NOT be duplicated β€” persistedIds was restored
- const allToolMsgs = [...h.messages.values()].filter((m) => m.role === 'tool');
- const tool1Msgs = allToolMsgs.filter((m) => m.tool_call_id === 'tc-1');
- expect(tool1Msgs).toHaveLength(1);
- });
- });
-
- describe('warm replica step resync', () => {
- it('reports a late advanced batch as stale after its operation was removed', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
- h.topicModel.findById.mockResolvedValue({ agentId: null, id: 'topic-1', metadata: {} });
-
- await expect(
- h.handler.ingest({
- events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'late' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow('Stale hetero operation op-1');
- });
-
- it('switches to the DB-persisted step assistant when a later-step batch lands on a stale warm replica', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- h.messages.set('asst-2', {
- agentId: null,
- content: '',
- id: 'asst-2',
- parentId: 'asst-1',
- role: 'assistant',
- topicId: 'topic-1',
- });
-
- h.topicModel.findById.mockResolvedValue({
- agentId: null,
- id: 'topic-1',
- metadata: {
- heteroCurrentMsgId: { msgId: 'asst-2', operationId: 'op-1' },
- runningOperation: {
- assistantMessageId: 'asst-1',
- operationId: 'op-1',
- },
- } satisfies FakeTopicMetadata,
- });
-
- await h.handler.ingest({
- events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'step2' })],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- expect(h.messages.get('asst-1')?.content).toBe('step1');
- expect(h.messages.get('asst-2')?.content).toBe('step2');
- });
- });
-
- describe('per-message session provenance (heteroSessionId / heteroMessageId)', () => {
- it('stamps the CC session id + turn message id on the assistant, its tools, and its usage', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const tool = {
- apiName: 'Bash',
- arguments: '{}',
- id: 'tc-1',
- identifier: 'bash',
- type: 'default',
- };
-
- await h.handler.ingest({
- events: [
- // system.init: carries the CC session id but opens no new assistant.
- buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
- // A real turn boundary: opens a new assistant for CC message cc-1.
- buildEvent('stream_start', 1, {
- messageId: 'cc-1',
- newStep: true,
- sessionId: 'sess-A',
- }),
- buildEvent('stream_chunk', 2, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- buildEvent('step_complete', 3, {
- phase: 'turn_metadata',
- usage: { totalInputTokens: 1, totalOutputTokens: 1, totalTokens: 2 },
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const assistant = [...h.messages.values()].find(
- (m) => m.role === 'assistant' && m.id !== 'asst-init',
- )!;
- expect(assistant.metadata).toMatchObject({
- heteroMessageId: 'cc-1',
- heteroSessionId: 'sess-A',
- });
-
- const toolRow = [...h.messages.values()].find((m) => m.role === 'tool')!;
- expect(toolRow.metadata).toMatchObject({
- heteroMessageId: 'cc-1',
- heteroSessionId: 'sess-A',
- });
-
- // recordUsage overwrites the row's metadata wholesale β€” provenance must survive.
- const usageWrite = h.messageModel.update.mock.calls.find(
- ([, patch]: [string, any]) => patch?.metadata?.usage,
- )!;
- expect(usageWrite[1].metadata).toMatchObject({
- heteroMessageId: 'cc-1',
- heteroSessionId: 'sess-A',
- usage: { totalTokens: 2 },
- });
- });
-
- it('records a mid-topic session fork per-message so a diff pinpoints the break', async () => {
- // The tpc_PZAmvtpkfHE1 scenario: `--resume` failed, CC opened a fresh
- // session mid-conversation, and the topic-level single heteroSessionId
- // could not show WHERE the history was lost. Per-message stamping does.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
- buildEvent('stream_start', 1, { messageId: 'cc-1', newStep: true, sessionId: 'sess-A' }),
- buildEvent('stream_chunk', 2, { chunkType: 'text', content: 'turn 1' }),
- // Next turn resumes into a DIFFERENT session β€” the fork.
- buildEvent('stream_start', 3, { messageId: 'cc-2', newStep: true, sessionId: 'sess-B' }),
- buildEvent('stream_chunk', 4, { chunkType: 'text', content: 'turn 2' }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const newAssistants = [...h.messages.values()].filter(
- (m) => m.role === 'assistant' && m.id !== 'asst-init',
- );
- const sessById = new Map(
- newAssistants.map((m) => [m.metadata?.heteroMessageId, m.metadata?.heteroSessionId]),
- );
- expect(sessById.get('cc-1')).toBe('sess-A');
- expect(sessById.get('cc-2')).toBe('sess-B');
- });
-
- it('stamps heteroMessageId on the FIRST (seeded) turn, not just later newStep turns', async () => {
- // The first CC assistant follows system:init with NO newStep β€” it lands on
- // the pre-seeded assistant. The adapter now carries the turn's message.id on
- // that non-newStep stream_start so the seed assistant + its first-turn tool
- // and usage rows get heteroMessageId β€” the common first turn of a
- // resumed/forked operation this forensic data exists to diagnose.
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const tool = {
- apiName: 'Bash',
- arguments: '{}',
- id: 'tc-1',
- identifier: 'bash',
- type: 'default',
- };
-
- await h.handler.ingest({
- events: [
- // system:init carries the session id but opens no new assistant.
- buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
- // First assistant after init: non-newStep stream_start carrying the
- // seed turn's CC message.id (what the adapter now emits).
- buildEvent('stream_start', 1, { messageId: 'cc-seed', sessionId: 'sess-A' }),
- buildEvent('stream_chunk', 2, { chunkType: 'tools_calling', toolsCalling: [tool] }),
- buildEvent('step_complete', 3, {
- phase: 'turn_metadata',
- usage: { totalInputTokens: 1, totalOutputTokens: 1, totalTokens: 2 },
- }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- // The seeded assistant's usage write re-stamps the provenance.
- const seedUsageWrite = h.messageModel.update.mock.calls.find(
- ([id, patch]: [string, any]) => id === 'asst-init' && patch?.metadata?.usage,
- )!;
- expect(seedUsageWrite[1].metadata).toMatchObject({
- heteroMessageId: 'cc-seed',
- heteroSessionId: 'sess-A',
- });
-
- const toolRow = [...h.messages.values()].find((m) => m.role === 'tool')!;
- expect(toolRow.metadata).toMatchObject({
- heteroMessageId: 'cc-seed',
- heteroSessionId: 'sess-A',
- });
- });
-
- it('stamps the subagent turn message id on subagent tool + usage rows', async () => {
- const h = createHarness({
- assistantMessageId: 'asst-init',
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const subagentCtx = {
- parentToolCallId: 'tc-spawn',
- spawnMetadata: { prompt: 'p', subagentType: 'Explore' },
- subagentMessageId: 'sub-1',
- };
-
- await h.handler.ingest({
- events: [
- buildEvent('stream_start', 0, { sessionId: 'sess-A' }),
- buildEvent('stream_chunk', 1, {
- chunkType: 'tools_calling',
- subagent: subagentCtx,
- toolsCalling: [
- {
- apiName: 'Read',
- arguments: '{}',
- id: 'inner-tc',
- identifier: 'read',
- type: 'default',
- },
- ],
- }),
- buildEvent('step_complete', 2, {
- phase: 'turn_metadata',
- subagent: subagentCtx,
- usage: { totalInputTokens: 1, totalOutputTokens: 1, totalTokens: 2 },
- }),
- buildEvent('agent_runtime_end', 3, { reason: 'success' }),
- ],
- operationId: 'op-1',
- topicId: 'topic-1',
- });
-
- const threadId = [...h.threads.keys()][0];
-
- // The subagent's inner tool row carries the subagent turn's message id.
- const innerTool = [...h.messages.values()].find(
- (m) => m.threadId === threadId && m.role === 'tool',
- )!;
- expect(innerTool.metadata).toMatchObject({
- heteroMessageId: 'sub-1',
- heteroSessionId: 'sess-A',
- });
-
- // recordUsage overwrites the subagent assistant's metadata wholesale β€” the
- // heteroMessageId createMessage stamped must survive it.
- const subUsageWrite = h.messageModel.update.mock.calls.find(
- ([, patch]: [string, any]) => patch?.metadata?.usage,
- )!;
- expect(subUsageWrite[1].metadata).toMatchObject({
- heteroMessageId: 'sub-1',
- heteroSessionId: 'sess-A',
- usage: { totalTokens: 2 },
- });
- });
- });
-});