Skip to content

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

45.6 KB
Raw Blame
// @vitest-environment node
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { AgentOperationModel } from '@/database/models/agentOperation';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
import type { AgentHook, SerializedHook } from '@/server/services/agentRuntime/hooks/types';
import * as verifyService from '@/server/services/verify';

import type { HeterogeneousPersistenceHandler } from '..';
import {
  HeterogeneousAgentService,
  normalizeHeterogeneousFinishError,
  StaleHeteroOperationError,
} from '..';
import { HeteroTraceRecorder } from '../HeteroTraceRecorder';

// Force queue/production mode so the terminal funnel takes the serialized-webhook
// delivery path (the hetero cross-process path), not the in-memory handler path.
// Default to local (false) so the existing in-memory-handler tests are unaffected.
vi.mock('@/server/services/queue/impls', () => ({
  isQueueAgentRuntimeEnabled: vi.fn(() => false),
}));

const mockPublishJSON = vi.hoisted(() => vi.fn());
vi.mock('@upstash/qstash', () => ({
  Client: class {
    publishJSON = mockPublishJSON;
  },
}));

const { isQueueAgentRuntimeEnabled } = await import('@/server/services/queue/impls');

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 = () => {
  // Faithful publish-gate fake (filter by event identity, latch per event) so batch-retry
  // tests exercise the real skip/resume behavior; `publishData` passes data through.
  const publishedKeys = new Set<string>();
  const gateKey = (event: AgentStreamEvent) =>
    `${event.stepIndex}:${event.type}:${event.timestamp}`;
  const handler = {
    filterUnpublishedEvents: vi.fn((_operationId: string, events: AgentStreamEvent[]) =>
      events.filter((event) => !publishedKeys.has(gateKey(event))),
    ),
    finish: vi.fn(async () => {}),
    ingest: vi.fn(async () => {}),
    markEventPublished: vi.fn((_operationId: string, event: AgentStreamEvent) => {
      publishedKeys.add(gateKey(event));
    }),
    publishData: vi.fn((_operationId: string, event: AgentStreamEvent) => event.data),
  };
  return handler as unknown as HeterogeneousPersistenceHandler & typeof handler;
};

const createFakeAgentOperationModel = () => ({
  findById: vi.fn(async (): Promise<any> => null),
  recordHeteroIngestRejection: vi.fn(async () => true),
  settleRunning: vi.fn(async () => true),
  touchRunning: vi.fn(async () => true),
});

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: { operationId?: string; streamEventManager?: IStreamEventManager } = {},
) => {
  const { manager, published } = createFakeStreamManager();
  const persistenceHandler = createFakePersistenceHandler();
  const agentOperationModel = createFakeAgentOperationModel();
  const topicModel = {
    settleRunningOperation: vi.fn(async (_topicId: string, operationId: string): Promise<any> => ({
      assistantMessageId: 'asst-1',
      operationId,
      status: 'settled',
    })),
    updateMetadata: vi.fn(async () => undefined),
  };
  const service = new HeterogeneousAgentService({} as any, 'user-test', {
    agentOperationModel: agentOperationModel as any,
    persistenceHandler,
    streamEventManager: overrides.streamEventManager ?? manager,
    topicModel: topicModel as any,
  });
  return { agentOperationModel, manager, persistenceHandler, published, service, topicModel };
};

const codexIngestInput = (
  events: AgentStreamEvent[],
): Parameters<HeterogeneousAgentService['heteroIngest']>[0] => ({
  agentType: 'codex',
  events,
  operationId: 'op-test',
  topicId: 'topic-1',
});

const queuedFinishInput = (): Parameters<HeterogeneousAgentService['heteroFinish']>[0] => ({
  agentType: 'claude-code',
  operationId: 'op-q',
  result: 'success',
  topicId: 'topic-q',
});

describe('HeterogeneousAgentService', () => {
  describe('normalizeHeterogeneousFinishError', () => {
    it('enriches a flattened weekly limit with the stable quota fields', () => {
      expect(
        normalizeHeterogeneousFinishError('claude-code', {
          message: "You've hit your weekly limit Β· resets 10pm (Asia/Shanghai)",
          type: 'AgentRuntimeError',
        }),
      ).toMatchObject({
        errorRef: 'H2001',
        attribution: 'user',
        retryable: false,
        body: { agentType: 'claude-code', code: 'rate_limit', details: { kind: 'usage_limit' } },
      });
    });

    it('turns a Kimi Code quota exit into the rate-limit guide instead of a JSON card', () => {
      // Verbatim stderr from a real run: Kimi Code reports a spent weekly
      // window through `provider.auth_error`, and used to land as the generic
      // AgentRuntimeError catch-all with no reset / schedule / transfer action.
      expect(
        normalizeHeterogeneousFinishError('kimi-code', {
          message:
            "error: failed to run prompt: provider.auth_error: 403 You've reached your weekly (7-day) usage limit. Your quota will reset when the current 7-day window ends. To continue now, purchase extra usage or upgrade your plan: https://www.kimi.com/membership/subscription?tab=quota",
          type: 'AgentRuntimeError',
        }),
      ).toMatchObject({
        attribution: 'user',
        category: 'quota',
        countAsFailure: false,
        errorRef: 'H2001',
        body: {
          agentType: 'kimi-code',
          code: 'rate_limit',
          details: { kind: 'usage_limit' },
          rateLimitInfo: { rateLimitType: 'seven_day', status: 'rejected' },
        },
      });
    });

    it('classifies a flattened Claude Code login failure for the frontend status guide', () => {
      expect(
        normalizeHeterogeneousFinishError('claude-code', {
          message: 'Not logged in Β· Please run /login',
          type: 'AgentRuntimeError',
        }),
      ).toMatchObject({
        body: {
          agentType: 'claude-code',
          code: 'auth_required',
          stderr: 'Not logged in Β· Please run /login',
        },
        errorRef: 'H1001',
        type: 'AgentRuntimeError',
      });
    });

    it('classifies auth details nested in a flattened error body', () => {
      expect(
        normalizeHeterogeneousFinishError('claude-code', {
          body: { stderr: 'Not logged in. Please run /login' },
          message: 'Agent execution failed',
          type: 'AgentRuntimeError',
        }),
      ).toMatchObject({ body: { agentType: 'claude-code', code: 'auth_required' } });
    });

    it('preserves an existing structured status-guide error', () => {
      const error = {
        body: {
          agentType: 'claude-code',
          code: 'auth_required',
          message: 'existing',
        },
        message: 'existing',
        type: 'AgentRuntimeError',
      };

      expect(normalizeHeterogeneousFinishError('claude-code', error)).toMatchObject(error);
    });
  });

  describe('heteroIngest', () => {
    it('refreshes the durable operation lease before accepting a batch', async () => {
      const { agentOperationModel, persistenceHandler, service } = createService();

      await service.heteroIngest({
        agentType: 'codex',
        events: [buildEvent('stream_chunk', 0)],
        operationId: 'op-1',
        topicId: 'topic-1',
      });

      expect(agentOperationModel.touchRunning).toHaveBeenCalledWith('op-1');
      expect(persistenceHandler.ingest).toHaveBeenCalledOnce();
      expect(agentOperationModel.recordHeteroIngestRejection).not.toHaveBeenCalled();
    });

    it('acknowledges an accepted batch so the producer can tell it from a discarded one', async () => {
      const { service } = createService();

      await expect(
        service.heteroIngest({
          agentType: 'codex',
          events: [buildEvent('stream_chunk', 0)],
          operationId: 'op-1',
          topicId: 'topic-1',
        }),
      ).resolves.toEqual({ accepted: true });
    });

    it('reports and records a refusal when the operation lost its lease', async () => {
      const { agentOperationModel, manager, persistenceHandler, service } = createService();
      agentOperationModel.touchRunning.mockResolvedValue(false);

      // Discarding the batch is right β€” the operation is over. Doing it behind a
      // bare 200 was not: the producer read that as delivery and kept working.
      await expect(
        service.heteroIngest({
          agentType: 'claude-code',
          events: [buildEvent('stream_chunk', 0), buildEvent('stream_chunk', 1)],
          operationId: 'op-reclaimed',
          topicId: 'topic-1',
        }),
      ).resolves.toEqual({ accepted: false, reason: 'operation-not-running' });

      expect(persistenceHandler.ingest).not.toHaveBeenCalled();
      expect(manager.publishStreamEvent).not.toHaveBeenCalled();
      expect(agentOperationModel.recordHeteroIngestRejection).toHaveBeenCalledWith(
        'op-reclaimed',
        expect.objectContaining({ droppedEvents: 2, reason: 'operation-not-running' }),
      );
    });

    it('still refuses the batch when the rejection marker cannot be written', async () => {
      const { agentOperationModel, service } = createService();
      agentOperationModel.touchRunning.mockResolvedValue(false);
      agentOperationModel.recordHeteroIngestRejection.mockRejectedValue(new Error('db down'));

      await expect(
        service.heteroIngest({
          agentType: 'claude-code',
          events: [buildEvent('stream_chunk', 0)],
          operationId: 'op-reclaimed',
          topicId: 'topic-1',
        }),
      ).resolves.toEqual({ accepted: false, reason: 'operation-not-running' });
    });

    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: 'interrupted' }),
      ];

      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', {
        agentOperationModel: createFakeAgentOperationModel() as any,
        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('republishes nothing and skips the trace fold when an identical batch is redelivered', async () => {
      // Response lost after a fully successful attempt β†’ the CLI BatchIngester
      // redelivers the same batch. Live subscribers must not see duplicates,
      // and the execution-trace snapshot must not double-fold.
      const appendBatch = vi
        .spyOn(HeteroTraceRecorder.prototype, 'appendBatch')
        .mockResolvedValue();
      const { manager, published, service } = createService();
      const events: AgentStreamEvent[] = [
        buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hi' }),
        buildEvent('tool_start', 1, { toolCallId: 'tc-1' }),
      ];

      await service.heteroIngest(codexIngestInput(events));
      expect(published).toHaveLength(2);

      await service.heteroIngest(codexIngestInput(events));

      expect(manager.publishStreamEvent).toHaveBeenCalledTimes(2);
      expect(published).toHaveLength(2);
      expect(appendBatch).toHaveBeenCalledTimes(1);
      appendBatch.mockRestore();
    });

    it('a retried batch resumes publishing from the first unpublished event (no duplicates, no loss)', async () => {
      // Publish dies mid-loop on the first attempt: the head is delivered and
      // latched, the tail is not. The retry must publish ONLY the tail β€”
      // republishing the head would duplicate live events, skipping the tail
      // would lose them.
      const appendBatch = vi
        .spyOn(HeteroTraceRecorder.prototype, 'appendBatch')
        .mockResolvedValue();
      const published: any[] = [];
      let failOnSecondPublish = true;
      const manager: Partial<IStreamEventManager> = {
        publishStreamEvent: vi.fn(async (_operationId, event) => {
          if (failOnSecondPublish && published.length === 1) {
            failOnSecondPublish = false;
            throw new Error('redis down');
          }
          published.push(event);
          return `id-${published.length}`;
        }),
      };
      const persistenceHandler = createFakePersistenceHandler();
      const service = new HeterogeneousAgentService({} as any, 'user-test', {
        agentOperationModel: createFakeAgentOperationModel() as any,
        persistenceHandler,
        streamEventManager: manager as IStreamEventManager,
      });
      const events: AgentStreamEvent[] = [
        buildEvent('stream_start', 0, { assistantMessage: { id: 'asst-1' } }),
        buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'hello' }),
        buildEvent('agent_runtime_end', 2, { reason: 'interrupted' }),
      ];

      await expect(service.heteroIngest(codexIngestInput(events))).rejects.toThrow('redis down');
      expect(published.map((event) => event.type)).toEqual(['stream_start']);

      await service.heteroIngest(codexIngestInput(events));

      // Every event delivered exactly once across both attempts.
      expect(published.map((event) => event.type)).toEqual([
        'stream_start',
        'stream_chunk',
        'agent_runtime_end',
      ]);
      // The recorder folds once β€” on the attempt that delivered new events.
      expect(appendBatch).toHaveBeenCalledTimes(1);
      appendBatch.mockRestore();
    });

    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 = {
        ...createFakePersistenceHandler(),
        ingest: vi.fn(async () => {
          callOrder.push('persist');
        }),
      } as unknown as HeterogeneousPersistenceHandler;
      const service = new HeterogeneousAgentService({} as any, 'user-test', {
        agentOperationModel: createFakeAgentOperationModel() as any,
        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', {
        agentOperationModel: createFakeAgentOperationModel() as any,
        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();
    });

    it('refuses stale operation batches without publishing or throwing', async () => {
      const manager: Partial<IStreamEventManager> = {
        publishStreamEvent: vi.fn(),
      };
      const persistenceHandler = {
        finish: vi.fn(async () => {}),
        ingest: vi.fn(async () => {
          throw new StaleHeteroOperationError('stale old batch');
        }),
      } as unknown as HeterogeneousPersistenceHandler;
      const agentOperationModel = createFakeAgentOperationModel();
      const service = new HeterogeneousAgentService({} as any, 'user-test', {
        agentOperationModel: agentOperationModel as any,
        persistenceHandler,
        streamEventManager: manager as IStreamEventManager,
      });

      await expect(
        service.heteroIngest({
          agentType: 'claude-code',
          events: [buildEvent('stream_chunk', 0)],
          operationId: 'op-old',
          topicId: 'topic-1',
        }),
      ).resolves.toEqual({ accepted: false, reason: 'stale-operation' });
      expect(manager.publishStreamEvent).not.toHaveBeenCalled();
      expect(agentOperationModel.recordHeteroIngestRejection).toHaveBeenCalledWith(
        'op-old',
        expect.objectContaining({ reason: 'stale-operation' }),
      );
    });
  });

  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('settles a success whose output ingest discarded as a failed turn', async () => {
      // The producer's receipt is honest about its own process (the CLI did exit
      // 0) and blind to the only thing that matters here: none of its output was
      // persisted. Trusting it leaves the user on an assistant placeholder that
      // never fills in, with the topic/task retired as answered.
      const { agentOperationModel, persistenceHandler, published, service } = createService();
      agentOperationModel.findById.mockResolvedValue({
        metadata: {
          heteroIngestRejection: {
            at: '2026-09-18T04:44:38.923Z',
            droppedEvents: 12,
            reason: 'stale-operation',
          },
        },
      });

      await service.heteroFinish({
        agentType: 'claude-code',
        assistantMessageId: 'asst-1',
        operationId: 'op-dropped',
        result: 'success',
        topicId: 'topic-1',
      });

      expect(persistenceHandler.finish).toHaveBeenCalledWith(
        expect.objectContaining({
          error: expect.objectContaining({
            body: expect.objectContaining({ droppedEvents: 12, reason: 'stale-operation' }),
          }),
          result: 'error',
        }),
      );
      expect(published[0].event.data.reason).toBe('error');
      expect(published[0].event.data.error.message).toMatch(/not saved/);
    });

    it('leaves a clean success alone', async () => {
      const { persistenceHandler, published, service } = createService();

      await service.heteroFinish({
        agentType: 'claude-code',
        assistantMessageId: 'asst-1',
        operationId: 'op-clean',
        result: 'success',
        topicId: 'topic-1',
      });

      expect(persistenceHandler.finish).toHaveBeenCalledWith(
        expect.objectContaining({ error: undefined, result: 'success' }),
      );
      expect(published[0].event.data.reason).toBe('success');
    });

    it('keeps the producer verdict when the rejection marker cannot be read', async () => {
      const { agentOperationModel, published, service } = createService();
      agentOperationModel.findById.mockRejectedValue(new Error('db down'));

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-unreadable',
        result: 'success',
        topicId: 'topic-1',
      });

      expect(published[0].event.data.reason).toBe('success');
    });

    it('forwards classified error details when the run failed', async () => {
      const { published, service } = createService({ operationId: 'op-2' });

      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('persists and publishes a structured auth_required error from a flattened finish', async () => {
      const { persistenceHandler, published, service } = createService({ operationId: 'op-auth' });

      await service.heteroFinish({
        agentType: 'claude-code',
        error: { message: 'Not logged in Β· Please run /login', type: 'AgentRuntimeError' },
        operationId: 'op-auth',
        result: 'error',
        topicId: 'topic-auth',
      });

      expect(persistenceHandler.finish).toHaveBeenCalledWith(
        expect.objectContaining({
          error: expect.objectContaining({
            body: expect.objectContaining({
              agentType: 'claude-code',
              code: 'auth_required',
            }),
          }),
        }),
      );
      expect(published[0].event.data.error).toMatchObject({
        body: { agentType: 'claude-code', code: 'auth_required' },
      });
    });

    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',
      });
    });

    /**
     * @example Operation A finishes after operation B owns the topic; A still becomes terminal.
     */
    it('settles a delayed finish without touching the newer topic operation', async () => {
      // ROOT CAUSE:
      //
      // A delayed operation used to return on topic-owner conflict without
      // settling its durable row. Persisting its session id before that conflict
      // check could also overwrite the replacement operation's resume binding.
      //
      // Before: the old row remained running and its session binding could win.
      // After: its message state flushes without a binding update, then its own
      // row and terminal stream settle independently of the new topic owner.
      const { manager, published } = createFakeStreamManager();
      const persistenceHandler = createFakePersistenceHandler();
      const settleRunningSpy = vi
        .spyOn(AgentOperationModel.prototype, 'settleRunning')
        .mockResolvedValue(true);
      const topicModel = {
        settleRunningOperation: vi.fn(async () => ({
          activeOperationId: 'op-new',
          status: 'conflict' as const,
        })),
        updateMetadata: vi.fn(async () => undefined),
      } as any;
      const completeOperationSpy = vi
        .spyOn(CompletionLifecycle.prototype, 'completeOperation')
        .mockResolvedValue();
      const service = new HeterogeneousAgentService({} as any, 'user-test', {
        persistenceHandler,
        snapshotStore: null,
        streamEventManager: manager,
        topicModel,
      });

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-old',
        result: 'success',
        topicId: 'topic-1',
      });

      expect(topicModel.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-old');
      expect(topicModel.updateMetadata).not.toHaveBeenCalled();
      expect(settleRunningSpy).toHaveBeenCalledWith('op-old', 'done');
      expect(published).toHaveLength(1);
      expect(published[0].event).toMatchObject({
        data: { operationId: 'op-old', reason: 'success' },
        type: 'agent_runtime_end',
      });
      expect(completeOperationSpy).not.toHaveBeenCalled();

      completeOperationSpy.mockRestore();
    });

    // The unified terminal funnel: heteroFinish must drive the run's lifecycle
    // hooks through the shared hookDispatcher (the same mechanism the normal LLM
    // path uses), which is what marks the owning task done/failed and fires any
    // IM bot completion callback. These register a local-mode handler hook for
    // the operation and assert heteroFinish dispatches it.
    const registerHook = (operationId: string): { onComplete: any; onError: any } => {
      const onComplete = vi.fn(async () => {});
      const onError = vi.fn(async () => {});
      const hooks: AgentHook[] = [
        { handler: onComplete, id: 'task-on-complete', type: 'onComplete' },
        { handler: onError, id: 'task-on-error', type: 'onError' },
      ];
      hookDispatcher.register(operationId, hooks);
      return { onComplete, onError };
    };

    it('fires onComplete (reason=done) hooks on a successful run', async () => {
      const { service } = createService({ operationId: 'op-hook-success' });
      const { onComplete, onError } = registerHook('op-hook-success');

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-hook-success',
        result: 'success',
        topicId: 'topic-hook-1',
      });

      expect(onComplete).toHaveBeenCalledTimes(1);
      expect(onComplete.mock.calls[0][0]).toMatchObject({
        operationId: 'op-hook-success',
        reason: 'done',
      });
      expect(onError).not.toHaveBeenCalled();
      // Hooks are unregistered after dispatch so a replay can't double-fire.
      expect(hookDispatcher.hasHooks('op-hook-success')).toBe(false);
    });

    it('fires both onComplete and onError (reason=error) hooks on a failed run', async () => {
      const { service } = createService({ operationId: 'op-hook-error' });
      const { onComplete, onError } = registerHook('op-hook-error');

      await service.heteroFinish({
        agentType: 'codex',
        error: { message: 'auth required', type: 'AuthRequired' },
        operationId: 'op-hook-error',
        result: 'error',
        topicId: 'topic-hook-2',
      });

      expect(onComplete).toHaveBeenCalledTimes(1);
      expect(onError).toHaveBeenCalledTimes(1);
      expect(onError.mock.calls[0][0]).toMatchObject({
        errorMessage: 'auth required',
        errorType: 'AuthRequired',
        operationId: 'op-hook-error',
        reason: 'error',
      });
    });

    // Verify-lifecycle alignment: heteroFinish must route the terminal transition
    // through CompletionLifecycle (the SAME owner the in-process runtime uses), not
    // a stripped-down funnel. That single funnel is what runs the delivery-checker
    // gate on success β€” and the gate bails unless op.model/provider are set, so the
    // synthetic state MUST carry the model/provider backfilled from the CLI stream.
    it('routes the terminal transition through CompletionLifecycle with backfilled model/provider', async () => {
      const { service } = createService({ operationId: 'op-verify-align' });

      const finalizeSpy = vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue({
        llmCalls: 3,
        model: 'claude-opus-4-8',
        provider: 'anthropic',
        stepCount: 5,
        toolCalls: 2,
        totalCost: 0.12,
        totalInputTokens: 100,
        totalOutputTokens: 200,
        totalTokens: 300,
        traceS3Key: 'trace-key',
      } as any);
      const dispatchSpy = vi
        .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')
        .mockResolvedValue();

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-verify-align',
        result: 'success',
        topicId: 'topic-verify-align',
      });

      expect(dispatchSpy).toHaveBeenCalledTimes(1);
      const [opId, state, reason] = dispatchSpy.mock.calls[0] as [string, any, string];
      expect(opId).toBe('op-verify-align');
      expect(reason).toBe('done');
      // model/provider gate the verify run (lifecycle.ts bails when either is absent).
      expect(state).toMatchObject({ model: 'claude-opus-4-8', provider: 'anthropic' });
      // Trace aggregates flow into the shape persistCompletion reads.
      expect(state.usage?.llm?.tokens?.total).toBe(300);
      // Synthetic goal + deliverable messages drive the delivery checker.
      expect(state.messages).toEqual(
        expect.arrayContaining([
          expect.objectContaining({ role: 'user' }),
          expect.objectContaining({ role: 'assistant' }),
        ]),
      );

      finalizeSpy.mockRestore();
      dispatchSpy.mockRestore();
    });

    it('forwards a group member role to the completion lifecycle', async () => {
      const { service, topicModel } = createService({ operationId: 'op-member' });
      topicModel.settleRunningOperation.mockResolvedValue({
        assistantMessageId: 'asst-member',
        orchestrationRole: 'member',
        status: 'settled',
      });
      const completeOperationSpy = vi
        .spyOn(CompletionLifecycle.prototype, 'completeOperation')
        .mockResolvedValue(undefined);

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-member',
        result: 'success',
        topicId: 'topic-member',
      });

      expect(completeOperationSpy).toHaveBeenCalledWith(
        expect.objectContaining({ operationId: 'op-member', orchestrationRole: 'member' }),
        'done',
      );
      completeOperationSpy.mockRestore();
    });

    // Cross-instance race guard: recordStart's in-memory verify-plan promise lives
    // on a DIFFERENT CompletionLifecycle (execAgent), so heteroFinish can't await
    // it. A fast run could reach the gate before the plan persists. heteroFinish
    // must therefore re-run the idempotent durable instantiation and AWAIT it
    // before dispatching the gate.
    it('awaits durable verify-plan instantiation before the completion gate for a task-bound run', async () => {
      const { service } = createService({ operationId: 'op-race-guard' });

      const findByIdSpy = vi
        .spyOn(AgentOperationModel.prototype, 'findById')
        .mockResolvedValue({ parentOperationId: null, taskId: 'task-1' } as any);
      const instantiateSpy = vi
        .spyOn(verifyService, 'instantiateVerifyPlanOnStart')
        .mockResolvedValue();
      const dispatchSpy = vi
        .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')
        .mockResolvedValue();

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-race-guard',
        result: 'success',
        topicId: 'topic-race-guard',
      });

      expect(instantiateSpy).toHaveBeenCalledTimes(1);
      // Ensured with the run's own task id (3rd arg is the params object).
      expect(instantiateSpy.mock.calls[0][2]).toMatchObject({
        operationId: 'op-race-guard',
        taskId: 'task-1',
      });
      // The durable ensure is awaited BEFORE the gate β€” otherwise
      // runVerifyOnCompletion could read an empty plan and skip verify.
      expect(instantiateSpy.mock.invocationCallOrder[0]).toBeLessThan(
        dispatchSpy.mock.invocationCallOrder[0],
      );

      findByIdSpy.mockRestore();
      instantiateSpy.mockRestore();
      dispatchSpy.mockRestore();
    });

    it('skips verify-plan instantiation for a non-task hetero run', async () => {
      const { service } = createService({ operationId: 'op-no-task' });

      const findByIdSpy = vi
        .spyOn(AgentOperationModel.prototype, 'findById')
        .mockResolvedValue({ parentOperationId: null, taskId: null } as any);
      const instantiateSpy = vi
        .spyOn(verifyService, 'instantiateVerifyPlanOnStart')
        .mockResolvedValue();
      const dispatchSpy = vi
        .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')
        .mockResolvedValue();

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-no-task',
        result: 'success',
        topicId: 'topic-no-task',
      });

      expect(instantiateSpy).not.toHaveBeenCalled();
      // Still routes through the lifecycle β€” verify just has nothing to gate on.
      expect(dispatchSpy).toHaveBeenCalledTimes(1);

      findByIdSpy.mockRestore();
      instantiateSpy.mockRestore();
      dispatchSpy.mockRestore();
    });

    it('does NOT fire hooks on a cancelled run (the real result fires them)', async () => {
      const { service } = createService();
      const { onComplete, onError } = registerHook('op-hook-cancelled');

      await service.heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-hook-cancelled',
        result: 'cancelled',
        topicId: 'topic-hook-3',
      });

      expect(onComplete).not.toHaveBeenCalled();
      expect(onError).not.toHaveBeenCalled();
      // Still registered β€” the subsequent success/error call will dispatch them.
      expect(hookDispatcher.hasHooks('op-hook-cancelled')).toBe(true);
      hookDispatcher.unregister('op-hook-cancelled');
    });
  });

  // ───────────────────────────────────────────────────────────────────────────
  // The hetero terminal funnel in PRODUCTION (queue) mode. This is the path the
  // device/sandbox runs actually take: execAgent (process A) serializes the run's
  // lifecycle hooks onto `topic.metadata.runningOperation.hooks`; heteroFinish
  // (process B β€” the device callback / CLI exit, a different Lambda) reads them
  // back and must deliver each webhook. There is NO in-memory handler to fall
  // back on across that process boundary, so the in-memory-handler tests above
  // (which run in local mode) never exercise it. This guards the
  // read(runningOperation.hooks) β†’ dispatch β†’ deliverWebhook round-trip β€” the
  // link that, if broken, leaves a finished hetero task's `task_topics.status`
  // stuck at `running` because `onTopicComplete` never fires.
  describe('heteroFinish β€” queue-mode terminal webhook delivery (regression guard)', () => {
    const originalToken = process.env.QSTASH_TOKEN;
    const originalAppUrl = process.env.APP_URL;

    const taskHook: SerializedHook = {
      id: 'task-on-complete',
      type: 'onComplete',
      webhook: {
        body: { taskId: 'task_q', taskIdentifier: 'T-Q', userId: 'user-test' },
        delivery: 'qstash',
        url: '/api/workflows/task/on-topic-complete',
      },
    };

    const makeService = (
      hooks: SerializedHook[] | undefined,
      options: { operationHooks?: SerializedHook[]; topicStatus?: 'missing' | 'settled' } = {},
    ) => {
      const topicModel = {
        // Keep covering the legacy topic mirror used by partially upgraded runs.
        settleRunningOperation: vi.fn(async () => ({
          assistantMessageId: undefined,
          hooks,
          status: options.topicStatus ?? ('settled' as const),
          threadId: undefined,
        })),
      } as any;
      const { manager } = createFakeStreamManager();
      const agentOperationModel = createFakeAgentOperationModel();
      agentOperationModel.findById.mockResolvedValue({
        metadata: options.operationHooks
          ? { _hooks: options.operationHooks, assistantMessageId: 'asst-op' }
          : undefined,
      } as any);
      const service = new HeterogeneousAgentService({} as any, 'user-test', {
        agentOperationModel: agentOperationModel as any,
        persistenceHandler: createFakePersistenceHandler(),
        snapshotStore: null,
        streamEventManager: manager,
        topicModel,
      });
      return { service, topicModel };
    };

    beforeEach(() => {
      vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
      mockPublishJSON.mockReset();
      mockPublishJSON.mockResolvedValue(undefined);
      process.env.QSTASH_TOKEN = 'test-token';
      process.env.APP_URL = 'https://app.test';
    });

    afterEach(() => {
      vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(false);
      if (originalToken === undefined) delete process.env.QSTASH_TOKEN;
      else process.env.QSTASH_TOKEN = originalToken;
      if (originalAppUrl === undefined) delete process.env.APP_URL;
      else process.env.APP_URL = originalAppUrl;
    });

    it('delivers the task-on-complete webhook read from runningOperation.hooks (reason=done)', async () => {
      const { service } = makeService([taskHook]);

      await service.heteroFinish(queuedFinishInput());

      expect(mockPublishJSON).toHaveBeenCalledTimes(1);
      const arg = mockPublishJSON.mock.calls[0][0];
      expect(arg.url).toContain('/api/workflows/task/on-topic-complete');
      expect(arg.body).toMatchObject({
        hookId: 'task-on-complete',
        hookType: 'onComplete',
        reason: 'done',
        taskId: 'task_q',
        topicId: 'topic-q',
      });
    });

    it('delivers hooks from the operation when the stream terminal already cleared the topic', async () => {
      const { service } = makeService(undefined, {
        operationHooks: [taskHook],
        topicStatus: 'missing',
      });

      await service.heteroFinish(queuedFinishInput());

      expect(mockPublishJSON).toHaveBeenCalledTimes(1);
      expect(mockPublishJSON.mock.calls[0][0].body).toMatchObject({
        hookId: 'task-on-complete',
        topicId: 'topic-q',
      });
    });

    it('negative control: delivers nothing when runningOperation.hooks is empty', async () => {
      const { service } = makeService([]);

      await service.heteroFinish(queuedFinishInput());

      expect(mockPublishJSON).not.toHaveBeenCalled();
    });
  });

  // ───────────────────────────────────────────────────────────────────────────
  // Serialize hooks into the topic mirror, then finish after dropping the
  // in-memory registration. The topic store is a fake; this covers hook
  // serialization and dispatch, not ingest or database concurrency.
  describe('heteroFinish β€” serialized topic hook round-trip', () => {
    const originalToken = process.env.QSTASH_TOKEN;
    const originalAppUrl = process.env.APP_URL;
    const TOPIC = 'topic-int';

    // The exact hook taskRunner attaches: a handler (local) PLUS a qstash webhook.
    const taskHook: AgentHook = {
      handler: async () => {},
      id: 'task-on-complete',
      type: 'onComplete',
      webhook: {
        body: { taskId: 'task_x', taskIdentifier: 'T-X', userId: 'user-test' },
        delivery: 'qstash',
        url: '/api/workflows/task/on-topic-complete',
      },
    };

    // Fake topic store for seeding and settling this run's serialized hooks.
    const makeStore = () => {
      let meta: Record<string, any> = {};
      const topicModel = {
        settleRunningOperation: vi.fn(async (_id: string, operationId: string) => {
          const runningOperation = meta.runningOperation;
          if (!runningOperation) {
            const currentMessage = meta.heteroCurrentMsgId;
            return {
              assistantMessageId:
                currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,
              status: 'missing' as const,
            };
          }
          const isRoot = runningOperation.operationId === operationId;
          const operation = isRoot
            ? runningOperation
            : runningOperation.childOperations?.find(
                (candidate: any) => candidate.operationId === operationId,
              );
          if (!operation) {
            return {
              activeOperationId: runningOperation.operationId,
              status: 'conflict' as const,
            };
          }

          const currentMessage = meta.heteroCurrentMsgId;
          meta = {
            ...meta,
            runningOperation: isRoot
              ? null
              : {
                  ...runningOperation,
                  childOperations: runningOperation.childOperations.filter(
                    (candidate: any) => candidate.operationId !== operationId,
                  ),
                },
          };
          return {
            assistantMessageId:
              currentMessage?.operationId === operationId
                ? currentMessage.msgId
                : operation.assistantMessageId,
            hooks: operation.hooks,
            orchestrationRole: operation.orchestrationRole,
            status: 'settled' as const,
            threadId: operation.threadId,
          };
        }),
        updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>) => {
          meta = { ...meta, ...patch };
        }),
      } as any;
      return { get: () => meta, topicModel };
    };

    // Use the real hook serializer to seed the topic mirror.
    const seed = (store: ReturnType<typeof makeStore>, operationId: string) => {
      hookDispatcher.register(operationId, [taskHook]);
      const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
      return store.topicModel.updateMetadata(TOPIC, {
        runningOperation: { assistantMessageId: 'asst-1', hooks: serializedHooks, operationId },
      });
    };

    const makeService = (store: ReturnType<typeof makeStore>) =>
      new HeterogeneousAgentService({} as any, 'user-test', {
        persistenceHandler: createFakePersistenceHandler(),
        snapshotStore: null,
        streamEventManager: createFakeStreamManager().manager,
        topicModel: store.topicModel,
      });

    beforeEach(() => {
      vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
      mockPublishJSON.mockReset();
      mockPublishJSON.mockResolvedValue(undefined);
      process.env.QSTASH_TOKEN = 'test-token';
      process.env.APP_URL = 'https://app.test';
    });

    afterEach(() => {
      vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(false);
      hookDispatcher.unregister('op-int');
      if (originalToken === undefined) delete process.env.QSTASH_TOKEN;
      else process.env.QSTASH_TOKEN = originalToken;
      if (originalAppUrl === undefined) delete process.env.APP_URL;
      else process.env.APP_URL = originalAppUrl;
    });

    it('dispatches serialized topic hooks after the in-memory registration is gone', async () => {
      const store = makeStore();
      await seed(store, 'op-int');

      // An unrelated metadata update preserves the seeded hooks in this fake.
      await store.topicModel.updateMetadata(TOPIC, {
        heteroCurrentMsgId: { msgId: 'm1', operationId: 'op-int' },
      });
      expect(store.get().runningOperation?.hooks).toHaveLength(1);

      // heteroFinish runs in a DIFFERENT process/Lambda than execAgent, so the
      // in-memory hookDispatcher has nothing for this op β€” it relies purely on
      // the serialized hooks read from runningOperation. Drop the in-memory
      // registration to model that boundary faithfully.
      hookDispatcher.unregister('op-int');

      await makeService(store).heteroFinish({
        agentType: 'claude-code',
        operationId: 'op-int',
        result: 'success',
        topicId: TOPIC,
      });

      expect(mockPublishJSON).toHaveBeenCalledTimes(1);
      expect(mockPublishJSON.mock.calls[0][0].url).toContain(
        '/api/workflows/task/on-topic-complete',
      );
    });
  });
});