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.

27.9 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';

import {
  compareStreamIds,
  getDefaultReasonDetail,
  StreamEventManager,
  stripFinalStateInEventData,
} from '../StreamEventManager';

// Mock Redis clients. Blocking reads (`XREAD BLOCK`) must run on a dedicated
// short-lived duplicated connection: ioredis executes commands on one
// connection strictly in order, so a blocking read on the shared client would
// stall every concurrent XADD/EXPIRE behind the block timeout. The duplicate
// is scoped to the read (managers are constructed per request and rarely
// disconnected, so an instance-held duplicate would leak a socket).
const mockBlockingRedis = {
  disconnect: vi.fn(),
  quit: vi.fn(),
  xread: vi.fn(),
};

const mockRedis = {
  del: vi.fn(),
  duplicate: vi.fn(() => mockBlockingRedis),
  expire: vi.fn(),
  keys: vi.fn(),
  quit: vi.fn(),
  xadd: vi.fn(),
  xdel: vi.fn(),
  xread: vi.fn(),
  xrevrange: vi.fn(),
  xrange: vi.fn(),
};

vi.mock('../redis', () => ({
  getAgentRuntimeRedisClient: () => mockRedis,
}));

describe('StreamEventManager', () => {
  let streamManager: StreamEventManager;

  beforeEach(() => {
    vi.clearAllMocks();
    streamManager = new StreamEventManager();
  });

  describe('compareStreamIds', () => {
    it('orders by milliseconds, then sequence', () => {
      expect(compareStreamIds('9-5', '10-0')).toBeLessThan(0);
      expect(compareStreamIds('10-2', '10-10')).toBeLessThan(0);
      expect(compareStreamIds('10-1', '10-1')).toBe(0);
      expect(compareStreamIds('11', '10-99')).toBeGreaterThan(0);
    });

    it('fails closed for a cursor that is not a stream id', () => {
      expect(compareStreamIds('missing', '1-0')).toBeNaN();
      expect(compareStreamIds('1-0', '1-x')).toBeNaN();
    });
  });

  describe('deleteStreamEvents', () => {
    it('removes the given entries from the operation stream', async () => {
      await streamManager.deleteStreamEvents('op-1', ['1-0', '2-0']);

      expect(mockRedis.xdel).toHaveBeenCalledWith('agent_runtime_stream:op-1', '1-0', '2-0');
    });

    it('skips the round trip when there is nothing to delete', async () => {
      await streamManager.deleteStreamEvents('op-1', []);

      expect(mockRedis.xdel).not.toHaveBeenCalled();
    });
  });

  describe('publishAgentRuntimeInit', () => {
    it('should publish agent runtime init event with correct data', async () => {
      const operationId = 'test-operation-id';
      const metadata = {
        agentConfig: { test: true },
        createdAt: '2024-01-01T00:00:00.000Z',
        modelRuntimeConfig: { model: 'gpt-4' },
        status: 'idle',
        totalCost: 0,
        totalSteps: 0,
        userId: 'user-123',
      };

      mockRedis.xadd.mockResolvedValue('event-id-123');

      const result = await streamManager.publishAgentRuntimeInit(operationId, metadata);

      expect(result).toBe('event-id-123');
      expect(mockRedis.xadd).toHaveBeenCalledWith(
        `agent_runtime_stream:${operationId}`,
        '*',
        'type',
        'agent_runtime_init',
        'stepIndex',
        '0',
        'operationId',
        operationId,
        'data',
        JSON.stringify(metadata),
        'timestamp',
        expect.any(String),
      );
    });
  });

  describe('getStreamHistoryPage', () => {
    const row = (id: string, type: string) => [
      id,
      ['type', type, 'stepIndex', '0', 'operationId', 'op-1', 'data', '{}', 'timestamp', '1'],
    ];

    it('returns forward pages with an exclusive cursor and typed event fields', async () => {
      mockRedis.xrange.mockResolvedValueOnce([
        row('1-0', 'agent_runtime_init'),
        row('2-0', 'stream_chunk'),
        row('3-0', 'stream_chunk'),
      ]);
      const page = await streamManager.getStreamHistoryPage('op-1', '0', 2);
      expect(page).toMatchObject({ available: true, hasMore: true, nextCursor: '2-0' });
      expect(page.events.map((event) => event.id)).toEqual(['1-0', '2-0']);
      expect(page.events[0]).toMatchObject({ data: {}, stepIndex: 0, timestamp: 1 });
      mockRedis.xrange
        .mockResolvedValueOnce([row('2-0', 'stream_chunk')])
        .mockResolvedValueOnce([row('3-0', 'stream_chunk')]);
      expect((await streamManager.getStreamHistoryPage('op-1', '2-0', 2)).events[0].id).toBe('3-0');
      expect(mockRedis.xrange).toHaveBeenLastCalledWith(
        'agent_runtime_stream:op-1',
        '(2-0',
        '+',
        'COUNT',
        3,
      );
    });

    it('fails closed for a legacy truncated prefix, an expired stream, or a missing cursor', async () => {
      mockRedis.xrange.mockResolvedValueOnce([row('100-0', 'stream_chunk')]);
      expect((await streamManager.getStreamHistoryPage('op-1')).available).toBe(false);
      mockRedis.xrange.mockResolvedValueOnce([]);
      expect((await streamManager.getStreamHistoryPage('op-1')).available).toBe(false);
      // Missing cursor on an expired stream: no entry, and no init to anchor it.
      mockRedis.xrange.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
      expect((await streamManager.getStreamHistoryPage('op-1', '1-0')).available).toBe(false);
    });

    // A superseded `tools_calling` snapshot is removed after a newer entry lands,
    // so a follower whose cursor was that snapshot must keep paging, not fail.
    it('continues after a cursor whose snapshot was removed mid-stream', async () => {
      mockRedis.xrange
        .mockResolvedValueOnce([])
        .mockResolvedValueOnce([row('1-0', 'agent_runtime_init')])
        .mockResolvedValueOnce([row('4-0', 'stream_chunk')]);

      const page = await streamManager.getStreamHistoryPage('op-1', '3-0', 2);

      expect(page).toMatchObject({ available: true, hasMore: false, nextCursor: '4-0' });
      expect(page.events.map((event) => event.id)).toEqual(['4-0']);
    });

    it('fails closed for a missing cursor with nothing after it or no init before it', async () => {
      mockRedis.xrange
        .mockResolvedValueOnce([])
        .mockResolvedValueOnce([row('1-0', 'agent_runtime_init')])
        .mockResolvedValueOnce([]);
      expect((await streamManager.getStreamHistoryPage('op-1', '3-0')).available).toBe(false);

      mockRedis.xrange
        .mockResolvedValueOnce([])
        .mockResolvedValueOnce([row('5-0', 'agent_runtime_init')]);
      expect((await streamManager.getStreamHistoryPage('op-1', '3-0')).available).toBe(false);

      mockRedis.xrange
        .mockResolvedValueOnce([])
        .mockResolvedValueOnce([row('1-0', 'stream_chunk')]);
      expect((await streamManager.getStreamHistoryPage('op-1', '3-0')).available).toBe(false);
    });

    it('propagates Redis errors instead of reporting an empty successful history', async () => {
      mockRedis.xrange.mockRejectedValueOnce(new Error('Redis unavailable'));
      await expect(streamManager.getStreamHistoryPage('op-1')).rejects.toThrow('Redis unavailable');
    });
  });

  describe('publishAgentRuntimeEnd', () => {
    it('should publish agent runtime end event with correct data', async () => {
      const operationId = 'test-operation-id';
      const stepIndex = 5;
      const finalState = {
        cost: { total: 100 },
        status: 'done',
        stepCount: 5,
      };

      mockRedis.xadd.mockResolvedValue('event-id-456');

      const result = await streamManager.publishAgentRuntimeEnd({
        finalState,
        operationId,
        stepIndex,
      });

      expect(result).toBe('event-id-456');
      expect(mockRedis.xadd).toHaveBeenCalledWith(
        `agent_runtime_stream:${operationId}`,
        '*',
        'type',
        'agent_runtime_end',
        'stepIndex',
        '5',
        'operationId',
        operationId,
        'data',
        JSON.stringify({
          finalState,
          operationId,
          phase: 'execution_complete',
          reason: 'completed',
          reasonDetail: 'Agent runtime completed successfully',
        }),
        'timestamp',
        expect.any(String),
      );
    });

    // agent_runtime_end optionally carries the canonical UIChatMessage[]
    // snapshot so the client can use the pushed payload as Source of Truth
    // instead of refetching from DB.
    it('should include uiMessages in serialized data when provided', async () => {
      const operationId = 'test-operation-id';
      const stepIndex = 5;
      const finalState = { status: 'done', stepCount: 5 };
      const uiMessages = [{ id: 'msg_a', role: 'assistantGroup' }] as any;

      mockRedis.xadd.mockResolvedValue('event-id-ui');

      await streamManager.publishAgentRuntimeEnd({
        finalState,
        operationId,
        reason: 'done',
        stepIndex,
        uiMessages,
      });

      // Find the serialized `data` argument inline so this test stays robust
      // if other positional args shift around.
      const dataArg = mockRedis.xadd.mock.calls[0]?.find(
        (a: any) => typeof a === 'string' && a.startsWith('{'),
      );
      const parsed = JSON.parse(dataArg);
      expect(parsed.uiMessages).toEqual(uiMessages);
      expect(parsed.finalState).toEqual(finalState);
    });

    it('should omit uiMessages from serialized data when not provided', async () => {
      const operationId = 'test-operation-id';
      const finalState = { status: 'done', stepCount: 3 };

      mockRedis.xadd.mockResolvedValue('event-id-noui');

      await streamManager.publishAgentRuntimeEnd({ finalState, operationId, stepIndex: 3 });

      const dataArg = mockRedis.xadd.mock.calls[0]?.find(
        (a: any) => typeof a === 'string' && a.startsWith('{'),
      );
      const parsed = JSON.parse(dataArg);
      expect(parsed).not.toHaveProperty('uiMessages');
    });

    it('should accept custom reason and reasonDetail', async () => {
      const operationId = 'test-operation-id';
      const stepIndex = 3;
      const finalState = { status: 'error' };
      const reason = 'error';
      const reasonDetail = 'Agent failed due to timeout';

      mockRedis.xadd.mockResolvedValue('event-id-789');

      await streamManager.publishAgentRuntimeEnd({
        finalState,
        operationId,
        reason,
        reasonDetail,
        stepIndex,
      });

      expect(mockRedis.xadd).toHaveBeenCalledWith(
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        operationId,
        'data',
        JSON.stringify({
          finalState,
          operationId,
          phase: 'execution_complete',
          reason,
          reasonDetail,
        }),
        expect.any(String),
        expect.any(String),
      );
    });

    it('should derive error reasonDetail from finalState when omitted', async () => {
      const operationId = 'test-operation-id';
      const stepIndex = 3;
      const finalState = {
        error: {
          message: 'Invalid provider API key',
          type: 'InvalidProviderAPIKey',
        },
        status: 'error',
      };

      mockRedis.xadd.mockResolvedValue('event-id-790');

      await streamManager.publishAgentRuntimeEnd({
        finalState,
        operationId,
        reason: 'error',
        stepIndex,
      });

      expect(mockRedis.xadd).toHaveBeenCalledWith(
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        expect.any(String),
        operationId,
        'data',
        JSON.stringify({
          finalState,
          operationId,
          phase: 'execution_complete',
          reason: 'error',
          reasonDetail: 'Invalid provider API key',
        }),
        expect.any(String),
        expect.any(String),
      );
    });

    // Heavy reconstructible fields (notably `messages` with
    // compressedGroup envelopes) must be stripped before xadd so a
    // single event can't blow past Upstash's 10 MB request limit.
    it('strips messages + tool-set fields from finalState before xadd', async () => {
      const operationId = 'test-operation-id';
      const messages = [
        { content: 'msg', role: 'user' },
        { content: 'reply', role: 'assistant' },
      ];
      const finalState = {
        cost: { total: 42 },
        error: { message: 'boom', type: 'BoomError' },
        expertise: {
          contentHash: 'hash',
          domains: [{ id: 'product-design', lessonIds: ['lesson-1'] }],
          renderedContext: '<expertise>heavy learned context</expertise>',
          schemaVersion: 1,
        },
        messages,
        operationToolSet: { enabledToolIds: ['x'] },
        status: 'error',
        stepCount: 4,
        toolManifestMap: { x: { name: 'x' } },
        toolSourceMap: { x: 'plugin' },
        tools: [{ name: 'x' }],
        usage: { llm: { tokens: { total: 100 } } },
        world: {
          agent: { systemRole: 'you are a helpful agent' },
          expertise: {
            contentHash: 'hash',
            domains: [{ id: 'product-design', lessonIds: ['lesson-1'] }],
            renderedContext: '<expertise>heavy learned context</expertise>',
            schemaVersion: 1,
          },
        },
      };

      mockRedis.xadd.mockResolvedValue('event-id-strip');

      await streamManager.publishAgentRuntimeEnd({
        finalState,
        operationId,
        reason: 'error',
        stepIndex: 4,
      });

      const dataArg = mockRedis.xadd.mock.calls[0]?.find(
        (a: any) => typeof a === 'string' && a.startsWith('{'),
      );
      const parsed = JSON.parse(dataArg);

      // Stripped: heavy / reconstructible fields gone
      expect(parsed.finalState.expertise).toBeUndefined();
      // The expertise snapshot moved into `world`; the rest of the world, which
      // the client renders from, must survive the strip.
      expect(parsed.finalState.world.expertise).toBeUndefined();
      expect(parsed.finalState.world.agent).toEqual({
        systemRole: 'you are a helpful agent',
      });
      expect(parsed.finalState.messages).toBeUndefined();
      expect(parsed.finalState.operationToolSet).toBeUndefined();
      expect(parsed.finalState.toolManifestMap).toBeUndefined();
      expect(parsed.finalState.toolSourceMap).toBeUndefined();
      expect(parsed.finalState.tools).toBeUndefined();

      // Preserved: lightweight observability fields downstream consumers use
      expect(parsed.finalState.status).toBe('error');
      expect(parsed.finalState.cost).toEqual({ total: 42 });
      expect(parsed.finalState.error).toEqual({ message: 'boom', type: 'BoomError' });
      expect(parsed.finalState.stepCount).toBe(4);
      expect(parsed.finalState.usage).toEqual({ llm: { tokens: { total: 100 } } });

      // reasonDetail derivation runs against the un-stripped in-process
      // finalState passed as a param, so the error message survives.
      expect(parsed.reasonDetail).toBe('boom');
    });

    // Reaching `world.expertise` means destructuring `world`; a run without an
    // expertise snapshot β€” the common case β€” must still ship its world.
    it('keeps the world snapshot when it carries no expertise', async () => {
      const world = {
        agent: { systemRole: 'you are a helpful agent' },
        group: { agentMap: {} },
        userTimezone: 'Asia/Shanghai',
      };
      mockRedis.xadd.mockResolvedValue('event-id-world');

      await streamManager.publishAgentRuntimeEnd({
        finalState: { cost: { total: 1 }, messages: [], status: 'done', stepCount: 1, world },
        operationId: 'test-operation-id',
        reason: 'done',
        stepIndex: 1,
      });

      const dataArg = mockRedis.xadd.mock.calls[0]?.find(
        (a: any) => typeof a === 'string' && a.startsWith('{'),
      );

      expect(JSON.parse(dataArg).finalState.world).toEqual(world);
    });
  });

  it.each([undefined, 'execution_complete'])(
    'omits finalState from persisted step_complete events (phase=%s)',
    async (phase) => {
      const finalState = { initialContext: { prompt: 'context' }, status: 'done' };
      const data = { finalState, ...(phase && { phase, reason: 'done' }) };
      mockRedis.xadd.mockResolvedValue('event-1');

      await streamManager.publishStreamEvent('op-1', {
        data,
        stepIndex: 1,
        type: 'step_complete',
      });

      const args = mockRedis.xadd.mock.calls[0];
      const stored = JSON.parse(args[args.indexOf('data') + 1]);
      expect(stored).toEqual(phase ? { phase, reason: 'done' } : {});
      expect(data.finalState).toBe(finalState);
    },
  );

  it('persists an opted-in state snapshot while omitting reconstructible message bodies', async () => {
    const finalState = {
      host: { includeFinalState: true },
      initialContext: { prompt: 'context' },
      messages: [{ content: 'large history' }],
      status: 'done',
    };
    mockRedis.xadd.mockResolvedValue('event-1');
    await streamManager.publishStreamEvent('op-1', {
      data: { finalState, phase: 'execution_complete', reason: 'done' },
      stepIndex: 1,
      type: 'step_complete',
    });
    const args = mockRedis.xadd.mock.calls[0];
    const stored = JSON.parse(args[args.indexOf('data') + 1]);
    expect(stored.finalState).toEqual({
      host: { includeFinalState: true },
      initialContext: { prompt: 'context' },
      status: 'done',
    });
    expect(finalState.messages).toHaveLength(1);
  });

  describe('readEventsOnce', () => {
    it("resolves '$' to the current tail and returns it (not '$') on timeout", async () => {
      // Stream has a tail entry; xread then times out (no newer events).
      mockRedis.xrevrange.mockResolvedValue([['7-0', ['type', 'stream_chunk']]]);
      mockBlockingRedis.xread.mockResolvedValue(null);

      const res = await streamManager.readEventsOnce('op-1', '$', 25_000);

      // '$' was resolved to the concrete tail before blocking…
      expect(mockRedis.xrevrange).toHaveBeenCalledWith(
        'agent_runtime_stream:op-1',
        '+',
        '-',
        'COUNT',
        1,
      );
      expect(mockBlockingRedis.xread).toHaveBeenCalledWith(
        'BLOCK',
        25_000,
        'STREAMS',
        'agent_runtime_stream:op-1',
        '7-0',
      );
      // …so the timeout hands back the concrete id, keeping the next poll gap-free.
      expect(res).toEqual({ events: [], lastEventId: '7-0' });
    });

    it("resolves '$' on an empty stream to '0'", async () => {
      mockRedis.xrevrange.mockResolvedValue([]);
      mockBlockingRedis.xread.mockResolvedValue(null);

      const res = await streamManager.readEventsOnce('op-1', '$');

      expect(mockBlockingRedis.xread).toHaveBeenCalledWith(
        'BLOCK',
        expect.any(Number),
        'STREAMS',
        'agent_runtime_stream:op-1',
        '0',
      );
      expect(res).toEqual({ events: [], lastEventId: '0' });
    });

    it('does not resolve an explicit cursor and blocks from it directly', async () => {
      mockBlockingRedis.xread.mockResolvedValue(null);

      const res = await streamManager.readEventsOnce('op-1', '5-0');

      expect(mockRedis.xrevrange).not.toHaveBeenCalled();
      expect(mockBlockingRedis.xread).toHaveBeenCalledWith(
        'BLOCK',
        expect.any(Number),
        'STREAMS',
        'agent_runtime_stream:op-1',
        '5-0',
      );
      expect(res).toEqual({ events: [], lastEventId: '5-0' });
    });

    it('parses events and advances the cursor to the last id', async () => {
      mockBlockingRedis.xread.mockResolvedValue([
        [
          'agent_runtime_stream:op-1',
          [
            [
              '8-0',
              [
                'type',
                'agent_intervention_response',
                'stepIndex',
                '2',
                'operationId',
                'op-1',
                'data',
                JSON.stringify({ toolCallId: 't1' }),
                'timestamp',
                '123',
              ],
            ],
          ],
        ],
      ]);

      const res = await streamManager.readEventsOnce('op-1', '5-0');

      expect(res.lastEventId).toBe('8-0');
      expect(res.events).toHaveLength(1);
      expect(res.events[0]).toMatchObject({
        id: '8-0',
        type: 'agent_intervention_response',
        stepIndex: 2,
        data: { toolCallId: 't1' },
      });
    });
  });

  // Regression: publishes used to share one connection with `XREAD BLOCK`
  // subscribers, so every XADD/EXPIRE queued behind the 1s block timeout and
  // streaming degraded to one chunk per second while any SSE client was
  // attached.
  describe('blocking reads use a dedicated scoped connection', () => {
    it('does not open extra connections at construction (managers are per-request)', () => {
      expect(mockRedis.duplicate).not.toHaveBeenCalled();
    });

    it('keeps writes on the shared client and blocking reads on a scoped duplicate', async () => {
      mockRedis.xadd.mockResolvedValue('event-id-1');
      mockBlockingRedis.xread.mockResolvedValue(null);

      await streamManager.publishStreamChunk('op-1', 0, { chunkType: 'text', content: 'hi' });
      await streamManager.readEventsOnce('op-1', '5-0');

      expect(mockRedis.xadd).toHaveBeenCalledTimes(1);
      expect(mockRedis.duplicate).toHaveBeenCalledTimes(1);
      expect(mockBlockingRedis.xread).toHaveBeenCalledTimes(1);
      expect(mockRedis.xread).not.toHaveBeenCalled();
    });

    it('closes the scoped connection after the read completes', async () => {
      mockBlockingRedis.xread.mockResolvedValue(null);

      await streamManager.readEventsOnce('op-1', '5-0');

      expect(mockBlockingRedis.disconnect).toHaveBeenCalledTimes(1);
    });

    it('closes the scoped connection when the read throws', async () => {
      mockBlockingRedis.xread.mockRejectedValue(new Error('boom'));

      await expect(streamManager.readEventsOnce('op-1', '5-0')).rejects.toThrow('boom');

      expect(mockBlockingRedis.disconnect).toHaveBeenCalledTimes(1);
    });

    it('runs a whole subscription loop on one scoped connection and closes it', async () => {
      const abort = new AbortController();
      mockBlockingRedis.xread.mockImplementation(async () => {
        abort.abort();
        return null;
      });

      await streamManager.subscribeStreamEvents('op-1', '0', () => {}, abort.signal);

      expect(mockRedis.duplicate).toHaveBeenCalledTimes(1);
      expect(mockBlockingRedis.xread).toHaveBeenCalledTimes(1);
      expect(mockRedis.xread).not.toHaveBeenCalled();
      expect(mockBlockingRedis.disconnect).toHaveBeenCalledTimes(1);
    });
  });

  describe('publishStreamEvent step_start', () => {
    const storedData = () => {
      const dataArg = mockRedis.xadd.mock.calls[0]?.find(
        (a: any) => typeof a === 'string' && a.startsWith('{'),
      );
      return JSON.parse(dataArg);
    };

    // The snapshot is a whole message list per step (megabytes on a long topic).
    // Its consumers get it from the gateway push; nothing reads it back from the
    // stream, so keeping a copy per step only grew the stream and every replay.
    it('keeps the uiMessages snapshot out of the stored stream entry', async () => {
      mockRedis.xadd.mockResolvedValue('event-id-step');

      await streamManager.publishStreamEvent('op-step', {
        data: { llmCalls: 3, uiMessages: [{ content: 'x'.repeat(64), id: 'msg_1' }] },
        stepIndex: 4,
        type: 'step_start',
      });

      expect(storedData()).toEqual({ llmCalls: 3 });
    });

    it('stores a protocol-2 step_start unchanged', async () => {
      mockRedis.xadd.mockResolvedValue('event-id-step');

      await streamManager.publishStreamEvent('op-step', {
        data: { llmCalls: 1, messageRevision: 4 },
        stepIndex: 4,
        type: 'step_start',
      });

      expect(storedData()).toEqual({ llmCalls: 1, messageRevision: 4 });
    });
  });

  describe('stripFinalStateInEventData', () => {
    it('returns data unchanged when finalState is absent', () => {
      const data = { phase: 'execution_complete', reason: 'done' };
      expect(stripFinalStateInEventData(data)).toBe(data);
    });

    it('returns data unchanged when finalState is falsy', () => {
      const data = { finalState: null, reason: 'done' };
      expect(stripFinalStateInEventData(data)).toBe(data);
    });

    it('strips reconstructible fields off finalState while preserving others', () => {
      const result = stripFinalStateInEventData({
        finalState: {
          cost: { total: 1 },
          expertise: {
            contentHash: 'hash',
            domains: [],
            renderedContext: '<expertise>heavy learned context</expertise>',
            schemaVersion: 1,
          },
          messages: [{ role: 'user' }],
          operationToolSet: {},
          status: 'done',
          toolManifestMap: {},
          toolSourceMap: {},
          tools: [],
        },
        reason: 'done',
      });

      expect(result).toEqual({
        finalState: { cost: { total: 1 }, status: 'done' },
        reason: 'done',
      });
    });

    it('handles non-object data defensively', () => {
      expect(stripFinalStateInEventData(undefined)).toBeUndefined();
      expect(stripFinalStateInEventData(null)).toBeNull();
      expect(stripFinalStateInEventData('chunk')).toBe('chunk');
      expect(stripFinalStateInEventData(123)).toBe(123);
    });
  });

  describe('getDefaultReasonDetail', () => {
    it('should return success message for non-error reasons', () => {
      expect(getDefaultReasonDetail({}, 'completed')).toBe('Agent runtime completed successfully');
      expect(getDefaultReasonDetail({}, undefined)).toBe('Agent runtime completed successfully');
    });

    it('should extract from ChatMessageError format (body.error.message)', () => {
      const state = {
        error: {
          body: { error: { message: 'Rate limit exceeded' } },
          message: 'ProviderBizError',
          type: 'ProviderBizError',
        },
      };
      expect(getDefaultReasonDetail(state, 'error')).toBe('Rate limit exceeded');
    });

    it('should extract from ChatMessageError format (body.message)', () => {
      const state = {
        error: {
          body: { message: 'Service unavailable' },
          message: 'error',
          type: 'InternalServerError',
        },
      };
      expect(getDefaultReasonDetail(state, 'error')).toBe('Service unavailable');
    });

    it('should extract from ChatCompletionErrorPayload format (error.message)', () => {
      const state = {
        error: {
          error: { message: 'Budget exceeded' },
          errorType: 'InsufficientBudgetForModel',
          provider: 'lobehub',
        },
      };
      expect(getDefaultReasonDetail(state, 'error')).toBe('Budget exceeded');
    });

    it('should extract from nested ChatCompletionErrorPayload (error.error.message)', () => {
      const state = {
        error: {
          error: {
            error: { message: 'ζ— ζ•ˆηš„δ»€η‰Œ' },
            message: 'ζ— ζ•ˆηš„δ»€η‰Œ',
            status: 401,
          },
          errorType: 'InvalidProviderAPIKey',
        },
      };
      expect(getDefaultReasonDetail(state, 'error')).toBe('ζ— ζ•ˆηš„δ»€η‰Œ');
    });

    it('should skip [object Object] and fallback to type', () => {
      const state = {
        error: {
          message: '[object Object]',
          type: 'ProviderBizError',
        },
      };
      expect(getDefaultReasonDetail(state, 'error')).toBe('ProviderBizError');
    });

    it('should use direct message when it is a real string', () => {
      const state = {
        error: { message: 'Connection timeout', type: 'NetworkError' },
      };
      expect(getDefaultReasonDetail(state, 'error')).toBe('Connection timeout');
    });

    it('should fallback to default message when error is empty', () => {
      expect(getDefaultReasonDetail({}, 'error')).toBe('Agent runtime failed');
      expect(getDefaultReasonDetail({ error: {} }, 'error')).toBe('Agent runtime failed');
      expect(getDefaultReasonDetail(null, 'error')).toBe('Agent runtime failed');
    });

    it('should handle interrupted reason', () => {
      const state = { error: { message: 'User cancelled' } };
      expect(getDefaultReasonDetail(state, 'interrupted')).toBe('User cancelled');
    });

    it('should fallback for interrupted without error', () => {
      expect(getDefaultReasonDetail({}, 'interrupted')).toBe('Agent runtime interrupted');
    });
  });
});