π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(hetero-agent): server-side aiAgent.heteroIngest / heteroFinish + persistence handler (#14444)
Arvin Xu0e6eba61a965
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex b120bb2e640..5b92e918386 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -73,11 +73,20 @@ export interface ChatTopicMetadata {*/cronJobId?: string;/**- * Persistent session id for a heterogeneous agent (desktop only).+ * Persistent session id for a heterogeneous agent.* Saved after each turn so the next message in the same topic can resume* the conversation (e.g. Claude Code CLI uses `--resume <sessionId>`).- * CC CLI stores sessions per-cwd under `~/.claude/projects/<encoded-cwd>/`,- * so resume requires the current cwd to equal `workingDirectory`.+ *+ * Two write paths share this field:+ *+ * - **Desktop renderer** writes from `executeHeterogeneousAgent` after+ * the local CLI process finishes. Resume is gated on `workingDirectory`+ * equality because CC stores sessions per-cwd under+ * `~/.claude/projects/<encoded-cwd>/`.+ * - **Cloud server** writes from `aiAgent.heteroFinish` (and from in-stream+ * terminal events) when the sandbox CLI run completes. The sandbox+ * mounts a stable cwd, so server-side resume does not check+ * `workingDirectory`.*/heteroSessionId?: string;model?: string;diff --git a/src/server/modules/AgentRuntime/StreamEventManager.ts b/src/server/modules/AgentRuntime/StreamEventManager.tsindex d492b408980..1152ae17797 100644--- a/src/server/modules/AgentRuntime/StreamEventManager.ts+++ b/src/server/modules/AgentRuntime/StreamEventManager.ts@@ -1,3 +1,4 @@+import { type AgentStreamEventType } from '@lobechat/agent-gateway-client';import { type ChatToolPayload } from '@lobechat/types';import debug from 'debug';import { type Redis } from 'ioredis';@@ -38,24 +39,19 @@ export const getDefaultReasonDetail = (finalState: any, reason?: string): stringreturn 'Agent runtime completed successfully';};+/**+ * Server-side stream event shape. Wire-compatible with `AgentStreamEvent` in+ * `@lobechat/agent-gateway-client` (the type union is the single source of+ * truth) β heterogeneous CLI agents that ingest via `aiAgent.heteroIngest`+ * republish their events through this same manager unchanged.+ */export interface StreamEvent {data: any;id?: string; // Redis Stream event IDoperationId: string;stepIndex: number;timestamp: number;- type:- | 'agent_runtime_init'- | 'agent_runtime_end'- | 'stream_start'- | 'stream_chunk'- | 'stream_end'- | 'stream_retry'- | 'tool_start'- | 'tool_end'- | 'step_start'- | 'step_complete'- | 'error';+ type: AgentStreamEventType;}export interface StreamChunkData {diff --git a/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.tsnew file mode 100644index 00000000000..609eb502fc6--- /dev/null+++ b/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts@@ -0,0 +1,178 @@+// @vitest-environment node+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentRouter } from '../aiAgent';+import { cleanupTestUser, createTestUser } from './integration/setup';++// Mock getServerDB to return our test database instance+let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++const mockHeteroIngest = vi.fn();+const mockHeteroFinish = vi.fn();++// Stub the service so we can assert on procedure β service wiring without+// pulling in the real Redis-backed StreamEventManager.+vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(() => ({+ heteroFinish: mockHeteroFinish,+ heteroIngest: mockHeteroIngest,+ })),+}));++// AgentRuntimeService and AiChatService are constructed by the procedure+// middleware too β stub to keep the test isolated.+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({})),+}));+vi.mock('@/server/services/aiChat', () => ({+ AiChatService: vi.fn().mockImplementation(() => ({})),+}));++const buildEvent = (type: AgentStreamEvent['type'], stepIndex: number): AgentStreamEvent => ({+ data: {},+ operationId: 'op-1',+ stepIndex,+ timestamp: 1_700_000_000_000,+ type,+});++describe('aiAgentRouter.heteroIngest / heteroFinish', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;++ beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ userId = await createTestUser(serverDB);+ mockHeteroIngest.mockReset();+ mockHeteroFinish.mockReset();+ mockHeteroIngest.mockResolvedValue(undefined);+ mockHeteroFinish.mockResolvedValue(undefined);+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ vi.clearAllMocks();+ });++ const createCaller = () => aiAgentRouter.createCaller({ userId, jwtPayload: { userId } } as any);++ describe('heteroIngest', () => {+ it('delegates the batch to HeterogeneousAgentService and acks', async () => {+ const events = [+ buildEvent('stream_start', 0),+ buildEvent('stream_chunk', 1),+ buildEvent('agent_runtime_end', 2),+ ];++ const result = await createCaller().heteroIngest({+ agentType: 'claude-code',+ events,+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ expect(result).toEqual({ ack: true });+ expect(mockHeteroIngest).toHaveBeenCalledTimes(1);+ expect(mockHeteroIngest).toHaveBeenCalledWith({+ agentType: 'claude-code',+ events,+ operationId: 'op-1',+ topicId: 'topic-1',+ });+ });++ it('wraps service errors into INTERNAL_SERVER_ERROR so the CLI ingester retries', async () => {+ mockHeteroIngest.mockRejectedValueOnce(new Error('redis down'));++ await expect(+ createCaller().heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow(/redis down/);+ });++ it('rejects empty batches at the schema layer', async () => {+ await expect(+ createCaller().heteroIngest({+ agentType: 'claude-code',+ events: [],+ operationId: 'op-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow();+ });++ it('rejects unknown agent types at the schema layer', async () => {+ await expect(+ createCaller().heteroIngest({+ // @ts-expect-error β verifying schema validation+ agentType: 'gemini',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow();+ });+ });++ describe('heteroFinish', () => {+ it('forwards finish payload to the service and acks', async () => {+ const result = await createCaller().heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-1',+ result: 'success',+ sessionId: 'cc-session-abc',+ topicId: 'topic-1',+ });++ expect(result).toEqual({ ack: true });+ expect(mockHeteroFinish).toHaveBeenCalledWith({+ agentType: 'claude-code',+ error: undefined,+ operationId: 'op-1',+ result: 'success',+ sessionId: 'cc-session-abc',+ topicId: 'topic-1',+ });+ });++ it('passes through error classification', async () => {+ await createCaller().heteroFinish({+ agentType: 'codex',+ error: { message: 'auth required', type: 'AuthRequired' },+ operationId: 'op-2',+ result: 'error',+ topicId: 'topic-2',+ });++ expect(mockHeteroFinish).toHaveBeenCalledWith(+ expect.objectContaining({+ error: { message: 'auth required', type: 'AuthRequired' },+ result: 'error',+ }),+ );+ });++ it('rejects unknown result values at the schema layer', async () => {+ await expect(+ createCaller().heteroFinish({+ agentType: 'claude-code',+ // @ts-expect-error β verifying schema validation+ result: 'maybe',+ operationId: 'op-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow();+ });+ });+});diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex 4f50cc77501..0ba0a612770 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -1,3 +1,4 @@+import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';import { type AgentRuntimeContext } from '@lobechat/agent-runtime';import { parse } from '@lobechat/conversation-flow';import { type TaskCurrentActivity, type TaskStatusResult } from '@lobechat/types';@@ -15,6 +16,7 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { AiAgentService } from '@/server/services/aiAgent';import { AiChatService } from '@/server/services/aiChat';+import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import { nanoid } from '@/utils/uuid';const log = debug('lobe-server:ai-agent-router');@@ -326,6 +328,67 @@ const InterruptTaskSchema = zmessage: 'Either threadId or operationId must be provided',});+/**+ * Wire shape of an `AgentStreamEvent` produced by `lh hetero exec`. Mirrors+ * `AgentStreamEvent` in `@lobechat/agent-gateway-client` (kept here as a Zod+ * schema for tRPC input validation; tRPC's type inference takes care of the+ * client-side typing). Republished verbatim through `StreamEventManager` so+ * gateway WS subscribers see the same shape regardless of producer.+ */+const AgentStreamEventSchema = z.object({+ data: z.any(),+ operationId: z.string(),+ stepIndex: z.number().int().nonnegative(),+ timestamp: z.number().int().nonnegative(),+ type: z.enum([+ 'agent_runtime_init',+ 'agent_runtime_end',+ 'stream_start',+ 'stream_chunk',+ 'stream_end',+ 'stream_retry',+ 'tool_start',+ 'tool_end',+ 'tool_execute',+ 'tool_result',+ 'step_start',+ 'step_complete',+ 'error',+ ]),+});++/**+ * Schema for `aiAgent.heteroIngest` β accepts a batch of producer-side+ * `AgentStreamEvent`s from `lh hetero exec`. `topicId` is required (operationId+ * β topic reverse-lookup is unreliable per LOBE-8516 design decision).+ */+const HeteroIngestSchema = z.object({+ agentType: z.enum(['claude-code', 'codex']),+ events: z.array(AgentStreamEventSchema).min(1),+ operationId: z.string().min(1),+ topicId: z.string().min(1),+});++/**+ * Schema for `aiAgent.heteroFinish` β terminal call, mirrors the CLI process+ * exit. `result` is the high-level outcome; `error` carries CLI-classified+ * details when `result === 'error'`. `sessionId` is the native CLI session+ * (CC's per-cwd id), kept here so the server can resume next time.+ */+const HeteroFinishSchema = z.object({+ agentType: z.enum(['claude-code', 'codex']),+ error: z+ .object({+ message: z.string(),+ type: z.string(),+ })+ .optional(),+ operationId: z.string().min(1),+ result: z.enum(['success', 'error', 'cancelled']),+ sessionId: z.string().optional(),+ topicId: z.string().min(1),+});+const aiAgentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -334,6 +397,7 @@ const aiAgentProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>agentRuntimeService: new AgentRuntimeService(ctx.serverDB, ctx.userId),aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId),aiChatService: new AiChatService(ctx.serverDB, ctx.userId),+ heterogeneousAgentService: new HeterogeneousAgentService(ctx.serverDB, ctx.userId),messageModel: new MessageModel(ctx.serverDB, ctx.userId),threadModel: new ThreadModel(ctx.serverDB, ctx.userId),topicModel: new TopicModel(ctx.serverDB, ctx.userId),@@ -1150,6 +1214,75 @@ export const aiAgentRouter = router({}}),+ /**+ * Ingest a batch of `AgentStreamEvent`s from a `lh hetero exec` producer+ * (CLI standalone, sandboxed CC, etc.) and republish them through the+ * existing stream fanout so renderer-side gateway WS subscribers see them+ * unchanged. Phase 2a: pub/sub only β no DB persistence (phase 2b adds it).+ */+ heteroIngest: aiAgentProcedure.input(HeteroIngestSchema).mutation(async ({ input, ctx }) => {+ const { agentType, events, operationId, topicId } = input;++ log(+ 'heteroIngest: topic=%s op=%s type=%s count=%d',+ topicId,+ operationId,+ agentType,+ events.length,+ );++ try {+ // Zod's z.any() infers `data?: any`, but the wire shape always includes+ // a `data` field (may be null). Cast at the boundary instead of widening+ // the shared `AgentStreamEvent` type or the service signature.+ await ctx.heterogeneousAgentService.heteroIngest({+ agentType,+ events: events as AgentStreamEvent[],+ operationId,+ topicId,+ });+ return { ack: true as const };+ } catch (error: any) {+ log('heteroIngest failed: %s', error?.message);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: error?.message || 'Failed to ingest heterogeneous agent events',+ });+ }+ }),++ /**+ * Terminal handshake from a `lh hetero exec` producer: signals process exit+ * and carries the run's high-level outcome. Always emits a final+ * `agent_runtime_end` so renderer subscribers can shut down even when the+ * CLI's own end-event was lost mid-flight.+ */+ heteroFinish: aiAgentProcedure.input(HeteroFinishSchema).mutation(async ({ input, ctx }) => {+ const { agentType, error, operationId, result, sessionId, topicId } = input;++ log('heteroFinish: topic=%s op=%s type=%s result=%s', topicId, operationId, agentType, result);++ try {+ await ctx.heterogeneousAgentService.heteroFinish({+ agentType,+ error,+ operationId,+ result,+ sessionId,+ topicId,+ });+ return { ack: true as const };+ } catch (err: any) {+ log('heteroFinish failed: %s', err?.message);+ throw new TRPCError({+ cause: err,+ code: 'INTERNAL_SERVER_ERROR',+ message: err?.message || 'Failed to finalize heterogeneous agent run',+ });+ }+ }),+processHumanIntervention: aiAgentProcedure.input(ProcessHumanInterventionSchema).mutation(async ({ input, ctx }) => {diff --git a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsnew file mode 100644index 00000000000..5298a7af98c--- /dev/null+++ b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -0,0 +1,872 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import {+ AgentRuntimeErrorType,+ type ChatMessageError,+ type ChatToolPayload,+ ThreadStatus,+ ThreadType,+} from '@lobechat/types';+import { createNanoId } from '@lobechat/utils';+import debug from 'debug';++import type { MessageModel } from '@/database/models/message';+import type { ThreadModel } from '@/database/models/thread';+import type { TopicModel } from '@/database/models/topic';++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)}`;+};++const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').trim();++/**+ * CC sometimes streams the error string into `content` BEFORE emitting the+ * structured error event (e.g. AuthRequired echoes the stderr line). Mirrors+ * the renderer's `shouldSuppressTerminalErrorEcho` (lines 113β130 of+ * heterogeneousAgentExecutor.ts): only suppress when the body is explicitly+ * marked or matches the AuthRequired code, AND the trimmed strings are+ * equal. Anything else stays β accidental partial overlaps are not echo.+ */+const shouldSuppressTerminalErrorEcho = (+ content: string,+ error: ChatMessageError | undefined,+): boolean => {+ if (!error) return false;+ const errorBody = error.body as+ | {+ clearEchoedContent?: boolean;+ code?: string;+ message?: string;+ stderr?: string;+ }+ | undefined;+ // The renderer guards on either an explicit flag or AuthRequired (the most+ // common echo source). Other error codes might echo too, but we err on the+ // side of preserving content unless the producer asks for the cleanup.+ const ECHO_TRIGGER_CODES = new Set(['AuthRequired']);+ if (+ !errorBody?.clearEchoedContent &&+ (!errorBody?.code || !ECHO_TRIGGER_CODES.has(errorBody.code))+ ) {+ return false;+ }+ const normalizedContent = normalizeErrorText(content);+ const normalizedError = normalizeErrorText(+ errorBody?.stderr || errorBody?.message || error.message,+ );+ return !!normalizedContent && !!normalizedError && normalizedContent === normalizedError;+};++interface ToolCallPayload extends ChatToolPayload {}++/** Per-assistant-message tool persistence state (main or sub-agent scope). */+interface ToolPersistenceState {+ payloads: ChatToolPayload[];+ persistedIds: Set<string>;+}++interface SubagentEventContext {+ parentToolCallId: string;+ spawnMetadata?: {+ description?: string;+ prompt?: string;+ subagentType?: string;+ };+ subagentMessageId?: string;+}++/**+ * Per-spawn subagent run state. Mirrors `SubagentRunState` in the renderer+ * (`src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts`),+ * minus UI-only fields (`stream`, `subOperationId`, `pendingFlushTarget`).+ */+interface SubagentRunState {+ accumulatedContent: string;+ accumulatedReasoning: string;+ currentAssistantMsgId: string;+ currentSubagentMessageId: string;+ lastChainParentId: string;+ lifetimeToolCallIds: Set<string>;+ state: ToolPersistenceState;+ threadId: string;+}++/**+ * Per-operation in-memory state. Lifetime spans the whole CLI run from first+ * `heteroIngest` batch through `heteroFinish`. Multi-replica caveat: state is+ * per-Node-process; cloud sandbox routing must be sticky to a single replica+ * for one operationId, otherwise turn boundaries on the second replica will+ * 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.)+ */+interface OperationState {+ accumulatedContent: string;+ accumulatedReasoning: string;+ agentId: string | null;+ currentAssistantMessageId: string;+ lastModel: string | undefined;+ lastProvider: string | undefined;+ operationId: string;+ processedKeys: Set<string>;+ subagentRuns: Map<string, SubagentRunState>;+ toolMsgIdByCallId: Map<string, string>;+ toolState: ToolPersistenceState;+ 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 interface HeterogeneousPersistenceHandlerDeps {+ messageModel: MessageModel;+ threadModel: ThreadModel;+ topicModel: TopicModel;+}++/**+ * 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: {+ events: AgentStreamEvent[];+ operationId: string;+ topicId: string;+ }): Promise<void> {+ const state = await this.loadOrCreateState(params.operationId, params.topicId);++ 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);+ }+ }++ /**+ * Flush trailing accumulators, persist the CLI's native session id (when+ * present) for next-turn resume, 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 CLI surfaces it here as a+ * `heteroFinish` argument; we write it to `topic.metadata.heteroSessionId`+ * (the same field the desktop renderer uses), so the next CLI spawn for+ * this topic can include `--resume <id>`.+ */+ async finish(params: {+ error?: { message: string; type: string };+ operationId: string;+ result: 'success' | 'error' | 'cancelled';+ sessionId?: string;+ }): Promise<void> {+ const state = operationStates.get(params.operationId);+ if (!state) return;++ try {+ await this.flushFinalState(state, params.error, params.result);+ if (params.sessionId) {+ await this.persistSessionId(state.topicId, params.sessionId);+ }+ } 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): 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 running = topic?.metadata?.runningOperation;+ if (!running || running.operationId !== operationId) {+ throw new Error(+ `No matching runningOperation on topic ${topicId} for operation ${operationId} β orchestrator must seed topic.metadata.runningOperation before ingest`,+ );+ }+ if (!running.assistantMessageId) {+ throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);+ }++ state = {+ accumulatedContent: '',+ accumulatedReasoning: '',+ agentId: topic.agentId ?? null,+ currentAssistantMessageId: running.assistantMessageId,+ lastModel: undefined,+ lastProvider: undefined,+ operationId,+ processedKeys: new Set(),+ subagentRuns: new Map(),+ toolMsgIdByCallId: new Map(),+ toolState: { payloads: [], persistedIds: new Set() },+ topicId,+ };+ operationStates.set(operationId, state);+ log('created state for operation %s on topic %s', operationId, topicId);+ return state;+ }++ // βββ Event dispatch ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++ private async handleEvent(state: OperationState, event: AgentStreamEvent): Promise<void> {+ switch (event.type) {+ case 'tool_result': {+ await this.handleToolResult(state, event);+ return;+ }++ case 'step_complete': {+ if (event.data?.phase === 'turn_metadata') {+ await this.handleTurnMetadata(state, event);+ }+ return;+ }++ case 'stream_start': {+ if (event.data?.newStep) {+ await this.handleStepStart(state);+ }+ return;+ }++ case 'stream_chunk': {+ await this.handleStreamChunk(state, event);+ return;+ }++ case 'agent_runtime_end':+ case 'error': {+ await this.handleTerminal(state, event);+ return;+ }++ // tool_start / tool_end / step_start / stream_end / agent_runtime_init /+ // tool_execute / stream_retry: no-op β server only persists the+ // adapter-level events, lifecycle markers are renderer-side concerns.+ default: {+ return;+ }+ }+ }++ // βββ Per-event handlers ββββββββββββββββββββββββββββββββββββββββββββββββββ++ private async handleTurnMetadata(state: OperationState, event: AgentStreamEvent) {+ const { model, provider, usage } = event.data ?? {};+ if (model) state.lastModel = model;+ if (provider) state.lastProvider = provider;+ if (!usage) return;++ await this.deps.messageModel.update(state.currentAssistantMessageId, {+ metadata: { usage },+ });+ }++ /**+ * `stream_start { newStep: true }` opens a new assistant turn within the+ * same operation. Mirrors renderer logic:+ *+ * 1. Flush prior assistant's accumulated content / reasoning / model+ * 2. Create the new assistant β chained off the last main-agent tool+ * message (so the wire becomes `asst β tool β asst β tool β ...`),+ * falling back to the prev assistant when the prior step had no tools+ * 3. Reset main-agent tool state (NOT the global `toolMsgIdByCallId` β+ * late subagent tool_results from prior steps still resolve via it)+ */+ private async handleStepStart(state: OperationState) {+ const prevUpdate: Record<string, any> = {};+ if (state.accumulatedContent) prevUpdate.content = state.accumulatedContent;+ if (state.accumulatedReasoning) prevUpdate.reasoning = { content: state.accumulatedReasoning };+ if (state.lastModel) prevUpdate.model = state.lastModel;+ if (state.lastProvider) prevUpdate.provider = state.lastProvider;++ if (Object.keys(prevUpdate).length > 0) {+ await this.deps.messageModel.update(state.currentAssistantMessageId, prevUpdate);+ }++ const lastToolMsgId = [...state.toolState.payloads]+ .reverse()+ .find((p) => !!p.result_msg_id)?.result_msg_id;+ const stepParentId = lastToolMsgId || state.currentAssistantMessageId;++ const newMsg = await this.deps.messageModel.create({+ agentId: state.agentId ?? undefined,+ content: '',+ model: state.lastModel,+ parentId: stepParentId,+ provider: state.lastProvider,+ role: 'assistant',+ topicId: state.topicId,+ });+ state.currentAssistantMessageId = newMsg.id;++ state.accumulatedContent = '';+ state.accumulatedReasoning = '';+ state.toolState = { payloads: [], persistedIds: new Set() };+ }++ private async handleStreamChunk(state: OperationState, event: AgentStreamEvent) {+ const chunk = event.data ?? {};+ const subagentCtx = chunk.subagent as SubagentEventContext | undefined;++ if (chunk.chunkType === 'text' && typeof chunk.content === 'string') {+ if (subagentCtx) {+ await this.persistSubagentText(state, subagentCtx, 'text', chunk.content);+ } else {+ state.accumulatedContent += chunk.content;+ }+ return;+ }++ if (chunk.chunkType === 'reasoning' && typeof chunk.reasoning === 'string') {+ if (subagentCtx) {+ await this.persistSubagentText(state, subagentCtx, 'reasoning', chunk.reasoning);+ } else {+ state.accumulatedReasoning += chunk.reasoning;+ }+ return;+ }++ if (chunk.chunkType === 'tools_calling') {+ const tools = chunk.toolsCalling as ToolCallPayload[] | undefined;+ if (!tools?.length) return;++ if (subagentCtx) {+ await this.persistSubagentToolBatch(state, subagentCtx, tools);+ } else {+ await this.persistMainToolBatch(state, tools);+ }+ }+ }++ private async handleToolResult(state: OperationState, event: AgentStreamEvent) {+ const data = event.data ?? {};+ const toolCallId: string | undefined = data.toolCallId;+ if (!toolCallId) return;++ const content: string = data.content ?? '';+ const isError: boolean = !!data.isError;+ const pluginState: Record<string, any> | undefined = data.pluginState;++ const toolMsgId = state.toolMsgIdByCallId.get(toolCallId);+ if (toolMsgId) {+ await this.deps.messageModel.updateToolMessage(toolMsgId, {+ content,+ pluginError: isError ? { message: content } : undefined,+ pluginState,+ });+ } else {+ // Late-arriving result for a call we never saw the tool_use for is+ // recoverable on a follow-up batch (out-of-order delivery); log and+ // move on so the rest of the batch lands.+ log('tool_result for unknown toolCallId=%s op=%s', toolCallId, state.operationId);+ }++ // If this tool_result is for a subagent's spawning tool_use (parent+ // toolCallId matches a registered subagent run), the subagent ended β+ // finalize so its terminal assistant carries the authoritative result+ // before any subsequent step boundary swaps the main assistant.+ if (state.subagentRuns.has(toolCallId)) {+ await this.finalizeSubagentRun(state, toolCallId, content);+ }+ }++ private async handleTerminal(state: OperationState, event: AgentStreamEvent) {+ const isError = event.type === 'error';+ const messageError = isError ? this.toChatMessageError(event.data) : undefined;+ const suppressEcho =+ !!messageError && shouldSuppressTerminalErrorEcho(state.accumulatedContent, messageError);++ const updateValue: Record<string, any> = {};+ if (suppressEcho) {+ // CC sometimes streams the error string into `content` BEFORE emitting+ // the structured error event. When the two payloads echo each other,+ // surface only the structured error and clear the duplicate text.+ updateValue.content = '';+ } else if (state.accumulatedContent) {+ updateValue.content = state.accumulatedContent;+ }+ if (state.accumulatedReasoning) updateValue.reasoning = { content: state.accumulatedReasoning };+ if (state.lastModel) updateValue.model = state.lastModel;+ if (state.lastProvider) updateValue.provider = state.lastProvider;+ if (messageError) updateValue.error = messageError;++ if (Object.keys(updateValue).length > 0) {+ await this.deps.messageModel.update(state.currentAssistantMessageId, updateValue);+ }++ // Drain any subagent runs that never saw their parent tool_result (CLI+ // crashed mid-spawn, or main never closed the spawn). Flush only β no+ // terminal assistant since we don't have authoritative resultContent.+ for (const parentToolCallId of state.subagentRuns.keys()) {+ await this.finalizeSubagentRun(state, parentToolCallId, undefined);+ }++ // Reset accumulators so a `finish()` flush after a terminal event in the+ // stream is a no-op (idempotent finalize).+ state.accumulatedContent = '';+ state.accumulatedReasoning = '';+ }++ /** Final safety flush triggered by `heteroFinish`. */+ private async flushFinalState(+ state: OperationState,+ error: { message: string; type: string } | undefined,+ result: 'success' | 'error' | 'cancelled',+ ) {+ if (!state.accumulatedContent && !state.accumulatedReasoning && !error && result !== 'error') {+ // Nothing pending β terminal event already flushed in-stream.+ return;+ }++ const updateValue: Record<string, any> = {};+ if (state.accumulatedContent) updateValue.content = state.accumulatedContent;+ if (state.accumulatedReasoning) updateValue.reasoning = { content: state.accumulatedReasoning };+ if (error) {+ // `error.type` is a free-form string from the CLI; coerce to the+ // shared union via `as` since the runtime contract accepts arbitrary+ // values (renderer-side error classifier already does the same).+ const errType = (error.type ||+ AgentRuntimeErrorType.AgentRuntimeError) as ChatMessageError['type'];+ updateValue.error = {+ body: { message: error.message },+ message: error.message,+ type: errType,+ } satisfies ChatMessageError;+ }++ if (Object.keys(updateValue).length > 0) {+ await this.deps.messageModel.update(state.currentAssistantMessageId, updateValue);+ }+ }++ private toChatMessageError(data: unknown): ChatMessageError {+ if (typeof data === 'object' && data && 'message' in data) {+ const message =+ typeof (data as any).message === 'string' ? (data as any).message : 'Agent runtime error';+ return {+ body: data as Record<string, unknown>,+ message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+ }+ const message = typeof data === 'string' ? data : 'Agent runtime error';+ return {+ body: { message },+ message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+ }++ // βββ 3-phase tool persist (main agent) βββββββββββββββββββββββββββββββββββ++ /**+ * Same shape as renderer's `persistToolBatch` (lines 319β411 in+ * `heterogeneousAgentExecutor.ts`):+ *+ * 1. Append fresh tools to `state.payloads`, write them on the assistant+ * together with the latest streamed content / reasoning so DB stays+ * in sync (no orphan-tool window once the parser sees them).+ * 2. Create a `role:'tool'` message per fresh tool_use, capture its DB+ * id into the global `toolMsgIdByCallId` lookup, and write+ * `result_msg_id` onto the matching `state.payloads` entry.+ * 3. Re-write `state.payloads` so phase 2's backfilled `result_msg_id`+ * lands on the assistant row.+ *+ * Idempotent on retry: tool_use ids already in `state.persistedIds` are+ * skipped up front.+ */+ private async persistToolBatch(+ incoming: ToolCallPayload[],+ persistState: ToolPersistenceState,+ assistantMessageId: string,+ state: OperationState,+ snapshot: { content: string; reasoning: string },+ threadId?: string,+ ): Promise<{ newToolMsgIds: string[] }> {+ // Merge incoming tools into the payloads array, de-duped by id. On a+ // retry of the same event, payloads already has these entries β skip the+ // re-push to keep phase 1/3 writes idempotent.+ for (const tool of incoming) {+ if (!persistState.payloads.some((p) => p.id === tool.id)) {+ persistState.payloads.push({ ...tool });+ }+ }++ const buildUpdate = (): Record<string, any> => {+ const update: Record<string, any> = { tools: persistState.payloads };+ if (snapshot.content) update.content = snapshot.content;+ if (snapshot.reasoning) update.reasoning = { content: snapshot.reasoning };+ return update;+ };++ // βββ Phase 1: pre-register tools[] on the assistant βββ+ // Idempotent re-write of the tools[] JSONB column. Throws propagate so+ // the outer ingest loop leaves the event un-marked β retry replays.+ await this.deps.messageModel.update(assistantMessageId, buildUpdate());++ // βββ Phase 2: create tool messages, capture ids βββ+ // Only create rows for tools that haven't been persisted yet. On retry+ // after a phase 2 mid-batch failure, this skips the ones that already+ // landed (their ids are in `persistedIds`) and re-tries the rest.+ const newToolMsgIds: string[] = [];+ const freshForCreate = incoming.filter((t) => !persistState.persistedIds.has(t.id));+ for (const tool of freshForCreate) {+ const result = await this.deps.messageModel.create({+ agentId: state.agentId ?? undefined,+ content: '',+ parentId: assistantMessageId,+ plugin: {+ apiName: tool.apiName,+ arguments: tool.arguments,+ identifier: tool.identifier,+ type: tool.type,+ },+ role: 'tool',+ threadId: threadId ?? null,+ tool_call_id: tool.id,+ topicId: state.topicId,+ });+ // Mark persisted ONLY after the create resolves cleanly β a thrown+ // create leaves the id absent so retries re-attempt this tool.+ state.toolMsgIdByCallId.set(tool.id, result.id);+ persistState.persistedIds.add(tool.id);+ newToolMsgIds.push(result.id);+ const entry = persistState.payloads.find((p) => p.id === tool.id);+ if (entry) entry.result_msg_id = result.id;+ }++ // βββ Phase 3: backfill result_msg_id on assistant.tools[] βββ+ // Always runs: even if every tool was already persisted in a prior call,+ // a phase 3 retry after a partial-failure replay needs to land the+ // up-to-date payloads. The write is idempotent (same JSONB).+ await this.deps.messageModel.update(assistantMessageId, buildUpdate());++ return { newToolMsgIds };+ }++ private async persistMainToolBatch(state: OperationState, tools: ToolCallPayload[]) {+ await this.persistToolBatch(tools, state.toolState, state.currentAssistantMessageId, state, {+ content: state.accumulatedContent,+ reasoning: state.accumulatedReasoning,+ });+ }++ // βββ Subagent thread + turn tracking βββββββββββββββββββββββββββββββββββββ++ private async ensureSubagentRun(+ state: OperationState,+ subagentCtx: SubagentEventContext,+ ): Promise<SubagentRunState | undefined> {+ let run = state.subagentRuns.get(subagentCtx.parentToolCallId);++ // βββ First subagent event for this parent β lazy-create Thread βββ+ if (!run) {+ const { spawnMetadata } = subagentCtx;+ const threadId = generateThreadId();+ const title =+ spawnMetadata?.description?.slice(0, 80) || spawnMetadata?.subagentType || 'Subagent';++ // Failures here propagate so a retry replays the lazy-create. The+ // run isn't registered in `subagentRuns` until all three rows land,+ // so a partial-failure retry re-attempts the whole sequence; the+ // ThreadModel.create uses `onConflictDoNothing` on id so re-running+ // with the same generated id is safe.+ await this.deps.threadModel.create({+ id: threadId,+ metadata: {+ sourceToolCallId: subagentCtx.parentToolCallId,+ startedAt: new Date().toISOString(),+ subagentType: spawnMetadata?.subagentType,+ },+ sourceMessageId: state.currentAssistantMessageId,+ status: ThreadStatus.Processing,+ title,+ topicId: state.topicId,+ type: ThreadType.Isolation,+ } as any);++ const userMsg = await this.deps.messageModel.create({+ agentId: state.agentId ?? undefined,+ content: spawnMetadata?.prompt ?? '',+ parentId: state.currentAssistantMessageId,+ role: 'user',+ threadId,+ topicId: state.topicId,+ });++ const firstAssistant = await this.deps.messageModel.create({+ agentId: state.agentId ?? undefined,+ content: '',+ parentId: userMsg.id,+ role: 'assistant',+ threadId,+ topicId: state.topicId,+ });++ run = {+ accumulatedContent: '',+ accumulatedReasoning: '',+ currentAssistantMsgId: firstAssistant.id,+ currentSubagentMessageId: subagentCtx.subagentMessageId ?? '',+ lastChainParentId: firstAssistant.id,+ lifetimeToolCallIds: new Set(),+ state: { payloads: [], persistedIds: new Set() },+ threadId,+ };+ state.subagentRuns.set(subagentCtx.parentToolCallId, run);+ return run;+ }++ // βββ New subagent turn β flush old content, cut a new assistant βββ+ if (+ subagentCtx.subagentMessageId &&+ subagentCtx.subagentMessageId !== run.currentSubagentMessageId+ ) {+ if (run.accumulatedContent || run.accumulatedReasoning) {+ const update: Record<string, any> = {};+ if (run.accumulatedContent) update.content = run.accumulatedContent;+ if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };+ await this.deps.messageModel.update(run.currentAssistantMsgId, update);+ }++ const nextAssistant = await this.deps.messageModel.create({+ agentId: state.agentId ?? undefined,+ content: '',+ parentId: run.lastChainParentId,+ role: 'assistant',+ threadId: run.threadId,+ topicId: state.topicId,+ });+ run.currentAssistantMsgId = nextAssistant.id;+ run.currentSubagentMessageId = subagentCtx.subagentMessageId;+ run.lastChainParentId = nextAssistant.id;+ run.state = { payloads: [], persistedIds: new Set() };+ run.accumulatedContent = '';+ run.accumulatedReasoning = '';+ }++ return run;+ }++ private async persistSubagentText(+ state: OperationState,+ subagentCtx: SubagentEventContext,+ kind: 'text' | 'reasoning',+ chunk: string,+ ) {+ const run = await this.ensureSubagentRun(state, subagentCtx);+ if (!run) return;+ if (kind === 'text') run.accumulatedContent += chunk;+ else run.accumulatedReasoning += chunk;+ }++ private async persistSubagentToolBatch(+ state: OperationState,+ subagentCtx: SubagentEventContext,+ tools: ToolCallPayload[],+ ) {+ const run = await this.ensureSubagentRun(state, subagentCtx);+ if (!run) return;++ for (const tool of tools) run.lifetimeToolCallIds.add(tool.id);++ const { newToolMsgIds } = await this.persistToolBatch(+ tools,+ run.state,+ run.currentAssistantMsgId,+ state,+ { content: run.accumulatedContent, reasoning: run.accumulatedReasoning },+ run.threadId,+ );++ // Chain next turn's assistant off the LAST tool message of this batch β+ // mirrors main-agent step-boundary logic.+ const lastToolMsgId = newToolMsgIds.at(-1);+ if (lastToolMsgId) run.lastChainParentId = lastToolMsgId;+ }++ /**+ * Two-step finalization: flush trailing content on the current in-thread+ * assistant, then (when `resultContent` is provided) create a terminal+ * assistant carrying the authoritative summary so the thread always ends+ * with `... β tool β asst(result)`.+ *+ * `resultContent` is omitted when the spawn never closed (CLI crash);+ * called from `handleTerminal` to drain orphan runs without faking a+ * result.+ */+ private async finalizeSubagentRun(+ state: OperationState,+ parentToolCallId: string,+ resultContent: string | undefined,+ ) {+ const run = state.subagentRuns.get(parentToolCallId);+ if (!run) return;++ if (run.accumulatedContent || run.accumulatedReasoning) {+ const update: Record<string, any> = {};+ if (run.accumulatedContent) update.content = run.accumulatedContent;+ if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };+ await this.deps.messageModel.update(run.currentAssistantMsgId, update);+ run.accumulatedContent = '';+ run.accumulatedReasoning = '';+ }++ if (resultContent) {+ const terminal = await this.deps.messageModel.create({+ agentId: state.agentId ?? undefined,+ content: resultContent,+ parentId: run.lastChainParentId,+ role: 'assistant',+ threadId: run.threadId,+ topicId: state.topicId,+ });+ run.currentAssistantMsgId = terminal.id;+ run.lastChainParentId = terminal.id;+ }++ // Mark the thread completed. Idempotent β re-running on a retry just+ // re-writes the same status; downstream UI badges are derived state.+ await this.deps.threadModel.update(run.threadId, { status: ThreadStatus.Active });++ state.subagentRuns.delete(parentToolCallId);+ }+}diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.tsnew file mode 100644index 00000000000..d0aa8973cf9--- /dev/null+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts@@ -0,0 +1,779 @@+// @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';++/**+ * 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;+ } = {},+) => {+ 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; 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 };+ },+ ),+ };++ 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 } },+ })),+ };++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: messageModel as any,+ threadModel: threadModel as any,+ topicModel: topicModel as any,+ });++ 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());+ 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 = { inputTokens: 100, outputTokens: 50 };++ 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 is a no-op (orchestrator already seeded the assistant id)', 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, {+ assistantMessage: { id: 'asst-from-event' },+ model: 'foo',+ provider: 'bar',+ }),+ ]);++ 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' }),+ ]);++ // No update yet β text is held in accumulator+ expect(h.messageModel.update).not.toHaveBeenCalled();+ });++ 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('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' }],+ ['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/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.tsnew file mode 100644index 00000000000..0717f28d361--- /dev/null+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts@@ -0,0 +1,329 @@+// @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';++/**+ * Synthetic fixture mirroring the shape of a real CC run captured under+ * `.heerogeneous-tracing/cc-streaming.json` (gitignored, not available in+ * CI). Rather than read a real trace, we generate a stream that exercises+ * the same characteristics:+ *+ * - Multiple text chunks bursting within the same millisecond (verifies+ * the data-fingerprint dedupe key, not just timestamps)+ * - 30 tool_use β tool_result pairs across multiple steps+ * - Step boundaries (`stream_start { newStep: true }`) cutting new+ * assistants chained off the last tool message+ * - Per-turn metadata events (`step_complete` phase=turn_metadata) with+ * usage payloads+ * - Terminal `agent_runtime_end`+ *+ * If the real trace shape changes (new event variants, new chunk types),+ * regenerate the fixture below to match. The aim is "deterministic stand-in+ * for the broad real-trace flow", not "byte-equal capture".+ */++const TOOLS_PER_STEP = 10;+const STEP_COUNT = 3;+const TEXT_CHUNKS_PER_STEP = 5;++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;+}++const buildSyntheticStream = (): AgentStreamEvent[] => {+ const events: AgentStreamEvent[] = [];+ // Use a single anchor timestamp shared across many bursty chunks to verify+ // that the dedupe key fingerprints `data` (not just timestamp+stepIndex).+ const burstyTimestamp = 1_700_000_000_000;+ let sequence = 0;+ let stepIndex = 0;++ const push = (+ type: AgentStreamEvent['type'],+ data: Record<string, unknown>,+ overrides: { stepIndex?: number; timestamp?: number } = {},+ ) => {+ sequence += 1;+ events.push({+ data,+ operationId: 'op-fixture',+ stepIndex: overrides.stepIndex ?? stepIndex,+ // Default each event to a unique timestamp; bursty chunks override.+ timestamp: overrides.timestamp ?? burstyTimestamp + sequence,+ type,+ });+ };++ for (let step = 0; step < STEP_COUNT; step += 1) {+ if (step > 0) {+ // Cut a new step β the renderer parity test asserts the new assistant+ // chains off the last tool of the previous step.+ push('stream_start', { newStep: true });+ }++ // Burst N text chunks all sharing the same timestamp. With the old+ // (stepIndex, type, timestamp) key, all but the first would dedupe. The+ // fingerprinted key keeps each chunk distinct via its `content`.+ for (let t = 0; t < TEXT_CHUNKS_PER_STEP; t += 1) {+ push(+ 'stream_chunk',+ { chunkType: 'text', content: `step-${step}-chunk-${t} ` },+ { timestamp: burstyTimestamp + step * 1000 },+ );+ }++ // Tool calls in this step.+ const stepTools = Array.from({ length: TOOLS_PER_STEP }, (_, i) => ({+ apiName: 'Bash',+ arguments: JSON.stringify({ cmd: `cmd-${step}-${i}` }),+ id: `tc-${step}-${i}`,+ identifier: 'bash',+ type: 'default' as const,+ }));++ push('stream_chunk', {+ chunkType: 'tools_calling',+ toolsCalling: stepTools,+ });++ // Tool results β one per tool, with content varying by id.+ for (const tool of stepTools) {+ push('tool_result', {+ content: `result of ${tool.id}`,+ toolCallId: tool.id,+ });+ }++ // Per-turn usage.+ push('step_complete', {+ model: 'claude-opus-4-7',+ phase: 'turn_metadata',+ provider: 'claude-code',+ usage: { inputTokens: 100 + step, outputTokens: 50 + step },+ });++ stepIndex += 1;+ }++ push('agent_runtime_end', { reason: 'success' });+ return events;+};++const createHarness = () => {+ let nextSeq = 0;+ const messages = new Map<string, FakeMessage>();+ const threads = new Map<string, any>();++ messages.set('asst-fixture', {+ agentId: null,+ content: '',+ id: 'asst-fixture',+ role: 'assistant',+ topicId: 'topic-fixture',+ });++ 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: any) => {+ const existing = messages.get(id);+ if (!existing) return { success: false };+ messages.set(id, {+ ...existing,+ content: patch.content ?? existing.content,+ pluginError: patch.pluginError,+ pluginState: patch.pluginState ?? existing.pluginState,+ });+ return { success: true };+ }),+ };++ const threadModel = {+ create: vi.fn(async (input: any) => {+ threads.set(input.id, { ...input });+ return { ...input };+ }),+ update: vi.fn(async (id: string, patch: any) => {+ const existing = threads.get(id);+ if (existing) threads.set(id, { ...existing, ...patch });+ }),+ };++ const topicModel = {+ findById: vi.fn(async () => ({+ agentId: null,+ id: 'topic-fixture',+ metadata: {+ runningOperation: { assistantMessageId: 'asst-fixture', operationId: 'op-fixture' },+ },+ })),+ };++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: messageModel as any,+ threadModel: threadModel as any,+ topicModel: topicModel as any,+ });++ return { handler, messageModel, messages, threadModel, threads, topicModel };+};++const ingest = async (+ h: ReturnType<typeof createHarness>,+ events: AgentStreamEvent[],+ batchSize = 50,+) => {+ for (let i = 0; i < events.length; i += batchSize) {+ await h.handler.ingest({+ events: events.slice(i, i + batchSize),+ operationId: 'op-fixture',+ topicId: 'topic-fixture',+ });+ }+};++describe('HeterogeneousPersistenceHandler β synthetic CC trace fixture', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ it('replays a multi-step CC-shaped run end-to-end with correct counts and chain shape', async () => {+ const events = buildSyntheticStream();+ expect(events.length).toBeGreaterThan(50);++ const h = createHarness();+ await ingest(h, events);+ await h.handler.finish({ operationId: 'op-fixture', result: 'success' });++ // βββ Tool message invariants βββ+ const toolMessages = [...h.messages.values()].filter((m) => m.role === 'tool');+ const expectedTools = TOOLS_PER_STEP * STEP_COUNT;+ const uniqueToolCallIds = new Set(toolMessages.map((m) => m.tool_call_id).filter(Boolean));+ expect(uniqueToolCallIds.size).toBe(expectedTools);+ expect(toolMessages.length).toBe(expectedTools);++ // Every tool message has the result_msg content from `tool_result`.+ expect(toolMessages.every((m) => m.content.startsWith('result of '))).toBe(true);++ // βββ Step-boundary chain shape βββ+ const allAssistants = [...h.messages.values()]+ .filter((m) => m.role === 'assistant' && m.threadId == null)+ .sort((a, b) => (a.id === 'asst-fixture' ? -1 : 1));++ // STEP_COUNT-1 new assistants from `stream_start { newStep }` events.+ expect(allAssistants.length).toBe(STEP_COUNT);++ // Each new assistant chains off the LAST tool message of the prior step+ // (renderer parity: "the wire becomes asst β tool β asst β tool β ...").+ for (let i = 1; i < allAssistants.length; i += 1) {+ const parent = h.messages.get(allAssistants[i].parentId!);+ expect(parent?.role).toBe('tool');+ }++ // βββ Bursty-text dedupe key correctness βββ+ // The fixture deliberately emits TEXT_CHUNKS_PER_STEP text chunks with+ // identical (stepIndex, type, timestamp) keys but distinct `content`.+ // With the legacy 3-tuple key this would dedupe β truncated content;+ // the fingerprint key keeps each chunk distinct.+ const finalAssistantContent = allAssistants.at(-1)?.content ?? '';+ const lastStep = STEP_COUNT - 1;+ for (let t = 0; t < TEXT_CHUNKS_PER_STEP; t += 1) {+ expect(finalAssistantContent).toContain(`step-${lastStep}-chunk-${t}`);+ }+ });++ it('idempotent under whole-batch retry β no duplicates when the same events are re-ingested', async () => {+ const events = buildSyntheticStream();+ const h = createHarness();++ await ingest(h, events);+ const baselineToolCount = [...h.messages.values()].filter((m) => m.role === 'tool').length;+ const baselineCreateCalls = h.messageModel.create.mock.calls.length;++ // Re-ingest the SAME events without `finish()`. Every event keeps the+ // same fingerprint, so the dedupe map skips them all β no new writes.+ await ingest(h, events);+ const afterReplayToolCount = [...h.messages.values()].filter((m) => m.role === 'tool').length;+ const afterReplayCreateCalls = h.messageModel.create.mock.calls.length;++ expect(afterReplayToolCount).toBe(baselineToolCount);+ expect(afterReplayCreateCalls).toBe(baselineCreateCalls);+ });++ it('partial-batch retry resumes from the failed event without re-creating succeeded ones', async () => {+ const events = buildSyntheticStream();+ const h = createHarness();++ // Make the 7th `messageModel.create` (a tool message creation, mid-batch)+ // throw on its first attempt only.+ let toolCreateAttempts = 0;+ const realCreate = h.messageModel.create.getMockImplementation()!;+ h.messageModel.create.mockImplementation(async (input: any, id?: string) => {+ if (input.role === 'tool') {+ toolCreateAttempts += 1;+ if (toolCreateAttempts === 7) {+ throw new Error('transient db error');+ }+ }+ return realCreate(input, id);+ });++ // First attempt should throw because the 7th tool create fails.+ await expect(ingest(h, events)).rejects.toThrow('transient db error');++ // Retry the SAME batch β the failing tool create is no longer flaky.+ // Succeeded tools are skipped via persistedIds; the failed one + all+ // subsequent events get processed.+ await ingest(h, events);++ // Same final tool count as a clean run: TOOLS_PER_STEP * STEP_COUNT.+ const expected = TOOLS_PER_STEP * STEP_COUNT;+ const toolMessages = [...h.messages.values()].filter((m) => m.role === 'tool');+ expect(new Set(toolMessages.map((m) => m.tool_call_id)).size).toBe(expected);+ expect(toolMessages.length).toBe(expected);+ });+});diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.tsnew file mode 100644index 00000000000..94f7738f5a1--- /dev/null+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts@@ -0,0 +1,716 @@+// @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';++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;+}++const createHarness = (params: {+ assistantMessageId: string;+ operationId: string;+ topicAgentId?: string | null;+ topicId: 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.topicAgentId ?? null,+ content: '',+ id: params.assistantMessageId,+ role: 'assistant',+ 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 };+ },+ ),+ };++ 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;+ }),+ 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) => {+ if (id !== params.topicId) return null;+ return {+ agentId: params.topicAgentId ?? null,+ id,+ metadata: {+ runningOperation: {+ assistantMessageId: params.assistantMessageId,+ operationId: params.operationId,+ },+ },+ };+ }),+ };++ const handler = new HeterogeneousPersistenceHandler({+ 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; nothing flushed until step boundary or finish+ expect(h.messageModel.update).not.toHaveBeenCalled();+ });++ 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(/No matching runningOperation/);+ });++ 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('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('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: { inputTokens: 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: { inputTokens: 1 } });+ });+ });++ describe('3-phase tool persist (main agent)', () => {+ 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) => {+ order.push(input.role === 'tool' ? 'create-tool' : 'create-other');+ return origCreate(input);+ });++ 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)+ expect(order).toEqual(['update-asst', 'create-tool', '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('flushes prior content, opens a new assistant chained off the last tool message', 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: a NEW assistant created chained off the tool msg+ const newAssistants = [...h.messages.values()].filter(+ (m) => m.role === 'assistant' && m.id !== 'asst-1',+ );+ expect(newAssistants).toHaveLength(1);++ const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');+ expect(newAssistants[0].parentId).toBe(toolMsg?.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 tool message+ const secondTurn = threadAssts[1];+ expect(secondTurn.parentId).toBe(threadTool?.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();+ });+ });++ 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');+ });++ 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() 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.mockResolvedValueOnce({+ 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/src/server/services/heterogeneousAgent/__tests__/index.test.ts b/src/server/services/heterogeneousAgent/__tests__/index.test.tsnew file mode 100644index 00000000000..3d7ca70ff52--- /dev/null+++ b/src/server/services/heterogeneousAgent/__tests__/index.test.ts@@ -0,0 +1,240 @@+// @vitest-environment node+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { describe, expect, it, vi } from 'vitest';++import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';++import type { HeterogeneousPersistenceHandler } from '..';+import { HeterogeneousAgentService } from '..';++const createFakeStreamManager = () => {+ const published: Array<{ event: any; operationId: string }> = [];+ const manager: Partial<IStreamEventManager> = {+ publishStreamEvent: vi.fn(async (operationId, event) => {+ published.push({ event, operationId });+ return `${operationId}-${published.length}`;+ }),+ };+ return { manager: manager as IStreamEventManager, published };+};++const createFakePersistenceHandler = () => {+ const handler = {+ finish: vi.fn(async () => {}),+ ingest: vi.fn(async () => {}),+ };+ return handler as unknown as HeterogeneousPersistenceHandler & typeof handler;+};++const buildEvent = (+ type: AgentStreamEvent['type'],+ stepIndex: number,+ data: Record<string, unknown> = {},+): AgentStreamEvent => ({+ data,+ operationId: 'op-test',+ stepIndex,+ timestamp: 1_700_000_000_000 + stepIndex,+ type,+});++const createService = (overrides: { streamEventManager?: IStreamEventManager } = {}) => {+ const { manager, published } = createFakeStreamManager();+ const persistenceHandler = createFakePersistenceHandler();+ const service = new HeterogeneousAgentService({} as any, 'user-test', {+ persistenceHandler,+ streamEventManager: overrides.streamEventManager ?? manager,+ });+ return { manager, persistenceHandler, published, service };+};++describe('HeterogeneousAgentService', () => {+ describe('heteroIngest', () => {+ it('republishes every event through the stream manager preserving ordering', async () => {+ const { manager, published, service } = createService();++ const events: AgentStreamEvent[] = [+ buildEvent('stream_start', 0, { assistantMessage: { id: 'asst-1' } }),+ buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'hi' }),+ buildEvent('tool_start', 2, { parentMessageId: 'asst-1' }),+ buildEvent('tool_result', 3, { toolCallId: 'tc-1' }),+ buildEvent('agent_runtime_end', 4, { reason: 'success' }),+ ];++ await service.heteroIngest({+ agentType: 'claude-code',+ events,+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ expect(manager.publishStreamEvent).toHaveBeenCalledTimes(5);++ // Verify events arrive in submission order with correct payloads+ published.forEach((entry, idx) => {+ expect(entry.operationId).toBe('op-1');+ expect(entry.event.type).toBe(events[idx].type);+ expect(entry.event.stepIndex).toBe(events[idx].stepIndex);+ expect(entry.event.data).toEqual(events[idx].data);+ });+ });++ it('uses the operationId from the request, not from the event itself', async () => {+ const { manager, service } = createService();++ // Producer-side bug simulation: events tagged with stale op id+ const events: AgentStreamEvent[] = [+ { ...buildEvent('stream_chunk', 0), operationId: 'op-stale' },+ ];++ await service.heteroIngest({+ agentType: 'claude-code',+ events,+ operationId: 'op-current',+ topicId: 'topic-1',+ });++ expect(manager.publishStreamEvent).toHaveBeenCalledWith(+ 'op-current',+ expect.objectContaining({ stepIndex: 0, type: 'stream_chunk' }),+ );+ });++ it('propagates publish failures so the CLI ingester retries the batch', async () => {+ const manager: Partial<IStreamEventManager> = {+ publishStreamEvent: vi+ .fn()+ .mockResolvedValueOnce('ok-0')+ .mockRejectedValueOnce(new Error('redis down')),+ };+ const persistenceHandler = createFakePersistenceHandler();+ const service = new HeterogeneousAgentService({} as any, 'user-test', {+ persistenceHandler,+ streamEventManager: manager as IStreamEventManager,+ });++ await expect(+ service.heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0), buildEvent('stream_chunk', 1)],+ operationId: 'op-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow('redis down');+ });++ it('persists before publishing β DB is the source of truth fetchAndReplace reads', async () => {+ const callOrder: string[] = [];+ const manager: Partial<IStreamEventManager> = {+ publishStreamEvent: vi.fn(async () => {+ callOrder.push('publish');+ return 'ok';+ }),+ };+ const persistenceHandler = {+ finish: vi.fn(async () => {}),+ ingest: vi.fn(async () => {+ callOrder.push('persist');+ }),+ } as unknown as HeterogeneousPersistenceHandler;+ const service = new HeterogeneousAgentService({} as any, 'user-test', {+ persistenceHandler,+ streamEventManager: manager as IStreamEventManager,+ });++ await service.heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ expect(callOrder).toEqual(['persist', 'publish']);+ });++ it('throws on persistence failure without publishing β keep DB and stream consistent', async () => {+ const manager: Partial<IStreamEventManager> = {+ publishStreamEvent: vi.fn(),+ };+ const persistenceHandler = {+ finish: vi.fn(async () => {}),+ ingest: vi.fn(async () => {+ throw new Error('topic missing runningOperation');+ }),+ } as unknown as HeterogeneousPersistenceHandler;+ const service = new HeterogeneousAgentService({} as any, 'user-test', {+ persistenceHandler,+ streamEventManager: manager as IStreamEventManager,+ });++ await expect(+ service.heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow(/runningOperation/);+ expect(manager.publishStreamEvent).not.toHaveBeenCalled();+ });+ });++ describe('heteroFinish', () => {+ it('publishes a terminal agent_runtime_end with the high-level result', async () => {+ const { manager, published, service } = createService();++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-1',+ result: 'success',+ sessionId: 'cc-session-abc',+ topicId: 'topic-1',+ });++ expect(manager.publishStreamEvent).toHaveBeenCalledTimes(1);+ expect(published[0].operationId).toBe('op-1');+ expect(published[0].event.type).toBe('agent_runtime_end');+ expect(published[0].event.data).toMatchObject({+ agentType: 'claude-code',+ operationId: 'op-1',+ reason: 'success',+ sessionId: 'cc-session-abc',+ });+ });++ it('forwards classified error details when the run failed', async () => {+ const { published, service } = createService();++ await service.heteroFinish({+ agentType: 'codex',+ error: { message: 'auth required', type: 'AuthRequired' },+ operationId: 'op-2',+ result: 'error',+ topicId: 'topic-2',+ });++ expect(published[0].event.data).toMatchObject({+ agentType: 'codex',+ error: { message: 'auth required', type: 'AuthRequired' },+ reason: 'error',+ });+ expect(published[0].event.data.sessionId).toBeUndefined();+ });++ it('handles cancelled runs and runs without sessionId', async () => {+ const { published, service } = createService();++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-3',+ result: 'cancelled',+ topicId: 'topic-3',+ });++ expect(published[0].event.data).toMatchObject({+ operationId: 'op-3',+ reason: 'cancelled',+ });+ });+ });+});diff --git a/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.tsnew file mode 100644index 00000000000..4ff9258e058--- /dev/null+++ b/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts@@ -0,0 +1,338 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';++import { HeterogeneousAgentService, HeterogeneousPersistenceHandler } from '..';+import { __resetOperationStatesForTesting } from '../HeterogeneousPersistenceHandler';++const createSilentStreamManager = (): IStreamEventManager =>+ ({+ publishStreamEvent: vi.fn(async () => 'ok'),+ }) as unknown as IStreamEventManager;++describe('HeterogeneousAgentService β phase 2c session id persistence + resume', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ describe('heteroFinish persists sessionId via TopicModel.updateMetadata', () => {+ it('writes the CLI session id to topic.metadata.heteroSessionId', async () => {+ const updateMetadata = vi.fn(async () => undefined);+ const findById = vi.fn(async () => ({+ agentId: null,+ id: 'topic-1',+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-1',+ operationId: 'op-1',+ },+ },+ }));++ // Real handler so we exercise the persistSessionId path end-to-end+ const handler = new HeterogeneousPersistenceHandler({+ messageModel: { update: vi.fn(async () => ({ success: true })) } as any,+ threadModel: {} as any,+ topicModel: { findById, updateMetadata } as any,+ });++ // Seed in-memory state by ingesting one event so finish has something to drain+ await handler.ingest({+ events: [+ {+ data: { chunkType: 'text', content: 'hi' },+ operationId: 'op-1',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_chunk',+ },+ ],+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ persistenceHandler: handler,+ streamEventManager: createSilentStreamManager(),+ });++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-1',+ result: 'success',+ sessionId: 'cc-session-fresh',+ topicId: 'topic-1',+ });++ expect(updateMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: 'cc-session-fresh',+ });+ });++ it('skips the metadata write when no sessionId is provided', async () => {+ const updateMetadata = vi.fn(async () => undefined);+ const findById = vi.fn(async () => ({+ agentId: null,+ id: 'topic-2',+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-2',+ operationId: 'op-2',+ },+ },+ }));++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: { update: vi.fn(async () => ({ success: true })) } as any,+ threadModel: {} as any,+ topicModel: { findById, updateMetadata } as any,+ });+ await handler.ingest({+ events: [+ {+ data: {},+ operationId: 'op-2',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ },+ ],+ operationId: 'op-2',+ topicId: 'topic-2',+ });++ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ persistenceHandler: handler,+ streamEventManager: createSilentStreamManager(),+ });++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-2',+ result: 'success',+ // no sessionId β CLI run aborted before init landed, or codex without resume+ topicId: 'topic-2',+ });++ expect(updateMetadata).not.toHaveBeenCalled();+ });++ it('persists sessionId even when result=error (so the next run can still resume context)', async () => {+ const updateMetadata = vi.fn(async () => undefined);+ const findById = vi.fn(async () => ({+ agentId: null,+ id: 'topic-3',+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-3',+ operationId: 'op-3',+ },+ },+ }));++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: { update: vi.fn(async () => ({ success: true })) } as any,+ threadModel: {} as any,+ topicModel: { findById, updateMetadata } as any,+ });+ await handler.ingest({+ events: [+ {+ data: {},+ operationId: 'op-3',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_init',+ },+ ],+ operationId: 'op-3',+ topicId: 'topic-3',+ });++ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ persistenceHandler: handler,+ streamEventManager: createSilentStreamManager(),+ });++ await service.heteroFinish({+ agentType: 'claude-code',+ error: { message: 'rate limited', type: 'AgentRuntimeError' },+ operationId: 'op-3',+ result: 'error',+ sessionId: 'cc-session-partial',+ topicId: 'topic-3',+ });++ expect(updateMetadata).toHaveBeenCalledWith('topic-3', {+ heteroSessionId: 'cc-session-partial',+ });+ });++ it('topic.metadata.runningOperation is preserved (updateMetadata merges, does not replace)', async () => {+ // This contract is enforced by `TopicModel.updateMetadata` itself+ // (verified in packages/database tests). We just assert the handler+ // calls it with a partial β not the full metadata object.+ const updateMetadata = vi.fn(async () => undefined);+ const findById = vi.fn(async () => ({+ agentId: null,+ id: 'topic-4',+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-4',+ operationId: 'op-4',+ },+ workingDirectory: '/Users/dev/project',+ },+ }));++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: { update: vi.fn(async () => ({ success: true })) } as any,+ threadModel: {} as any,+ topicModel: { findById, updateMetadata } as any,+ });+ await handler.ingest({+ events: [+ {+ data: {},+ operationId: 'op-4',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_init',+ },+ ],+ operationId: 'op-4',+ topicId: 'topic-4',+ });++ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ persistenceHandler: handler,+ streamEventManager: createSilentStreamManager(),+ });++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-4',+ result: 'success',+ sessionId: 'cc-session-resume-target',+ topicId: 'topic-4',+ });++ // Critical: passes only the field we want to update; other peers+ // (runningOperation, workingDirectory) are untouched in the patch+ // and TopicModel.updateMetadata's merge semantics preserve them.+ expect(updateMetadata).toHaveBeenCalledTimes(1);+ const call = updateMetadata.mock.calls[0] as unknown as [string, Record<string, unknown>];+ const patch = call[1];+ expect(patch).toEqual({ heteroSessionId: 'cc-session-resume-target' });+ expect(patch).not.toHaveProperty('runningOperation');+ expect(patch).not.toHaveProperty('workingDirectory');+ });++ it('updateMetadata failure does not poison heteroFinish (terminal event still publishes)', async () => {+ const updateMetadata = vi.fn(async () => {+ throw new Error('connection lost');+ });+ const findById = vi.fn(async () => ({+ agentId: null,+ id: 'topic-5',+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-5',+ operationId: 'op-5',+ },+ },+ }));++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: { update: vi.fn(async () => ({ success: true })) } as any,+ threadModel: {} as any,+ topicModel: { findById, updateMetadata } as any,+ });+ await handler.ingest({+ events: [+ {+ data: {},+ operationId: 'op-5',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_init',+ },+ ],+ operationId: 'op-5',+ topicId: 'topic-5',+ });++ const stream = createSilentStreamManager();+ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ persistenceHandler: handler,+ streamEventManager: stream,+ });++ // Should not throw β sessionId persistence is best-effort+ await expect(+ service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-5',+ result: 'success',+ sessionId: 'cc-session-x',+ topicId: 'topic-5',+ }),+ ).resolves.not.toThrow();++ // Terminal agent_runtime_end still published+ expect(stream.publishStreamEvent).toHaveBeenCalled();+ });+ });++ describe('getHeterogeneousResumeSessionId', () => {+ const buildService = (findByIdImpl: (id: string) => Promise<any>) => {+ const findById = vi.fn(findByIdImpl);+ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ persistenceHandler: {+ finish: vi.fn(async () => {}),+ ingest: vi.fn(async () => {}),+ } as unknown as HeterogeneousPersistenceHandler,+ streamEventManager: createSilentStreamManager(),+ topicModel: { findById } as any,+ });+ return { findById, service };+ };++ it('returns the persisted heteroSessionId for the topic', async () => {+ const { findById, service } = buildService(async (id) => ({+ agentId: null,+ id,+ metadata: {+ heteroSessionId: 'cc-session-aaaa',+ runningOperation: { assistantMessageId: 'asst', operationId: 'op' },+ },+ }));++ const sessionId = await service.getHeterogeneousResumeSessionId('topic-resume');+ expect(sessionId).toBe('cc-session-aaaa');+ expect(findById).toHaveBeenCalledWith('topic-resume');+ });++ it('returns undefined when no prior run persisted a session id', async () => {+ const { service } = buildService(async (id) => ({+ agentId: null,+ id,+ metadata: {+ runningOperation: { assistantMessageId: 'asst', operationId: 'op' },+ // no heteroSessionId+ },+ }));+ expect(await service.getHeterogeneousResumeSessionId('topic-no-session')).toBeUndefined();+ });++ it('returns undefined for an unknown topic', async () => {+ const { service } = buildService(async () => null);+ expect(await service.getHeterogeneousResumeSessionId('topic-missing')).toBeUndefined();+ });++ it('returns undefined when topic has no metadata', async () => {+ const { service } = buildService(async (id) => ({ agentId: null, id, metadata: null }));+ expect(await service.getHeterogeneousResumeSessionId('topic-bare')).toBeUndefined();+ });+ });+});diff --git a/src/server/services/heterogeneousAgent/index.ts b/src/server/services/heterogeneousAgent/index.tsnew file mode 100644index 00000000000..c1caaaf5521--- /dev/null+++ b/src/server/services/heterogeneousAgent/index.ts@@ -0,0 +1,170 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { LobeChatDatabase } from '@lobechat/database';+import debug from 'debug';++import { MessageModel } from '@/database/models/message';+import { ThreadModel } from '@/database/models/thread';+import { TopicModel } from '@/database/models/topic';+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';+import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';++import { HeterogeneousPersistenceHandler } from './HeterogeneousPersistenceHandler';++const log = debug('lobe-server:hetero-agent-service');++export type HeterogeneousAgentType = 'claude-code' | 'codex';++export type HeterogeneousFinishResult = 'success' | 'error' | 'cancelled';++export interface HeterogeneousIngestParams {+ agentType: HeterogeneousAgentType;+ events: AgentStreamEvent[];+ operationId: string;+ topicId: string;+}++export interface HeterogeneousFinishParams {+ agentType: HeterogeneousAgentType;+ error?: { message: string; type: string };+ operationId: string;+ result: HeterogeneousFinishResult;+ /**+ * Native CLI session id (e.g. CC's per-cwd session). Used in phase 2c to+ * persist on `topic.metadata` so a subsequent `lh hetero exec` run can+ * resume context.+ */+ sessionId?: string;+ topicId: string;+}++export interface HeterogeneousAgentServiceOptions {+ /** Inject a pre-built persistence handler (used by tests). */+ persistenceHandler?: HeterogeneousPersistenceHandler;+ /** Inject a pre-built manager (used by tests). */+ streamEventManager?: IStreamEventManager;+ /** Inject a pre-built TopicModel (used by tests for the resume helper). */+ topicModel?: TopicModel;+}++/**+ * Server-side ingest handler for heterogeneous agent CLIs (`lh hetero exec`+ * for Claude Code / Codex). Receives `AgentStreamEvent` batches from the+ * producer and republishes them through the existing `StreamEventManager`+ * fanout, so renderer-side gateway WS subscribers see the same wire shape+ * regardless of whether the run came from the agent gateway or a CLI process.+ *+ * Phase 2a scope: pure pub/sub. Phase 2b adds DB persistence via+ * `HeterogeneousPersistenceHandler`. Phase 2c persists `sessionId` to+ * `topic.metadata.heterogeneousSessions`.+ */+export class HeterogeneousAgentService {+ private readonly db: LobeChatDatabase;+ private readonly persistenceHandler: HeterogeneousPersistenceHandler;+ private readonly streamEventManager: IStreamEventManager;+ private readonly topicModel: TopicModel;+ private readonly userId: string;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ options: HeterogeneousAgentServiceOptions = {},+ ) {+ this.db = db;+ this.userId = userId;+ this.streamEventManager = options.streamEventManager ?? createStreamEventManager();+ this.topicModel = options.topicModel ?? new TopicModel(db, userId);+ this.persistenceHandler =+ options.persistenceHandler ??+ new HeterogeneousPersistenceHandler({+ messageModel: new MessageModel(db, userId),+ threadModel: new ThreadModel(db, userId),+ topicModel: this.topicModel,+ });+ }++ async heteroIngest(params: HeterogeneousIngestParams): Promise<void> {+ const { agentType, events, operationId, topicId } = params;++ log(+ 'heteroIngest: user=%s topic=%s op=%s type=%s count=%d',+ this.userId,+ topicId,+ operationId,+ agentType,+ events.length,+ );++ // Persist FIRST, then publish β the renderer's gateway handler triggers+ // `fetchAndReplaceMessages` on stream_start / tool_end / step_complete,+ // so DB must already reflect the latest writes when the WS event lands.+ // Persistence failures throw so the CLI BatchIngester retries the batch;+ // events that already landed are skipped via the handler's idempotency+ // map keyed on (stepIndex, type, timestamp).+ await this.persistenceHandler.ingest({ events, operationId, topicId });++ // Sequential publish preserves stepIndex ordering β Redis XADD itself is+ // serialized but awaiting in-order avoids interleaving with concurrent+ // ingest batches sharing the same operationId.+ for (const event of events) {+ // Each event already carries operationId; pass through unchanged so the+ // wire shape on the WS side is identical to gateway-driven runs.+ await this.streamEventManager.publishStreamEvent(operationId, {+ data: event.data,+ stepIndex: event.stepIndex,+ type: event.type,+ });+ }+ }++ async heteroFinish(params: HeterogeneousFinishParams): Promise<void> {+ const { agentType, error, operationId, result, sessionId, topicId } = params;++ log(+ 'heteroFinish: user=%s topic=%s op=%s type=%s result=%s sessionId=%s',+ this.userId,+ topicId,+ operationId,+ agentType,+ result,+ sessionId ?? '<none>',+ );++ // Drain any pending state in the persistence handler β flushes trailing+ // accumulated content / reasoning that the in-stream `agent_runtime_end`+ // already wrote (no-op when state is clean), persists the CLI's native+ // session id for next-turn resume, and frees the per-operation memory.+ await this.persistenceHandler.finish({ error, operationId, result, sessionId });++ // Always emit a terminal `agent_runtime_end` so renderer subscribers shut+ // down even if the CLI stream missed it (process killed mid-flight,+ // network drop on last batch). Idempotent on the renderer side: the+ // gateway event handler latches `terminalState` on first end-event.+ await this.streamEventManager.publishStreamEvent(operationId, {+ data: {+ agentType,+ error,+ operationId,+ reason: result,+ sessionId,+ },+ stepIndex: 0,+ type: 'agent_runtime_end',+ });+ }++ /**+ * Look up the persisted CLI session id for a topic so the orchestrator+ * (phase 3 cloud sandbox) can pass `--resume <sessionId>` to the next+ * `lh hetero exec` spawn. Returns undefined when no prior run completed+ * on this topic β caller should spawn fresh.+ *+ * Reads the same `topic.metadata.heteroSessionId` the desktop renderer+ * writes, so resume state is shared between desktop and cloud paths.+ */+ async getHeterogeneousResumeSessionId(topicId: string): Promise<string | undefined> {+ const topic = await this.topicModel.findById(topicId);+ return topic?.metadata?.heteroSessionId;+ }+}++export { HeterogeneousPersistenceHandler } from './HeterogeneousPersistenceHandler';