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.

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

import type { IdNode, Message } from '../../types';
import { BranchResolver } from '../BranchResolver';

const createUserMessage = (): Message => ({
  content: 'test',
  createdAt: 0,
  id: 'msg-1',
  role: 'user',
  updatedAt: 0,
});

const createBranchNode = (): IdNode => ({
  children: [
    { children: [], id: 'msg-2' },
    { children: [], id: 'msg-3' },
  ],
  id: 'msg-1',
});

const createMessageWithActiveBranch = (activeBranchIndex: number): Message => ({
  content: 'test',
  createdAt: 0,
  id: 'msg-1',
  metadata: { activeBranchIndex },
  role: 'user',
  updatedAt: 0,
});

describe('BranchResolver', () => {
  const resolver = new BranchResolver();

  describe('getActiveBranchId', () => {
    it('should return branch by activeBranchIndex from metadata when present', () => {
      const message: Message = createMessageWithActiveBranch(1);

      const idNode: IdNode = createBranchNode();

      expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-3');
    });

    it('should infer active branch from which branch has children', () => {
      const message: Message = createUserMessage();

      const idNode: IdNode = {
        children: [
          { children: [], id: 'msg-2' },
          { children: [{ children: [], id: 'msg-4' }], id: 'msg-3' },
        ],
        id: 'msg-1',
      };

      expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-3');
    });

    it('should default to first branch when no hints available', () => {
      const message: Message = createUserMessage();

      const idNode: IdNode = createBranchNode();

      expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-2');
    });

    it('should return undefined for optimistic update (activeBranchIndex === children.length)', () => {
      const message: Message = {
        content: 'test',
        createdAt: 0,
        id: 'msg-1',
        metadata: { activeBranchIndex: 2 }, // index = children.length (optimistic update)
        role: 'user',
        updatedAt: 0,
      };

      const idNode: IdNode = createBranchNode();

      // When activeBranchIndex === children.length, it's an optimistic update
      // The branch hasn't been created yet, so return undefined
      expect(resolver.getActiveBranchId(message, idNode)).toBeUndefined();
    });

    it('should ignore activeBranchIndex when it exceeds optimistic update range', () => {
      const message: Message = {
        content: 'test',
        createdAt: 0,
        id: 'msg-1',
        metadata: { activeBranchIndex: 5 }, // > children.length (invalid)
        role: 'user',
        updatedAt: 0,
      };

      const idNode: IdNode = createBranchNode();

      // activeBranchIndex > children.length should be ignored, fallback to default
      expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-2');
    });
  });

  describe('getActiveBranchIdFromMetadata', () => {
    it('should return branch by activeBranchIndex from metadata', () => {
      const message: Message = createMessageWithActiveBranch(1);

      const childIds = ['msg-2', 'msg-3'];
      const childrenMap = new Map<string | null, string[]>();

      expect(resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap)).toBe('msg-3');
    });

    it('should infer active branch from which child has descendants', () => {
      const message: Message = createUserMessage();

      const childIds = ['msg-2', 'msg-3'];
      const childrenMap = new Map<string | null, string[]>([
        ['msg-2', []],
        ['msg-3', ['msg-4']],
      ]);

      expect(resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap)).toBe('msg-3');
    });

    it('should ignore newer user descendants from threads when selecting the active branch', () => {
      const messages: Message[] = [
        createUserMessage(),
        {
          content: 'old branch',
          createdAt: 1,
          id: 'msg-2',
          parentId: 'msg-1',
          role: 'assistant',
          updatedAt: 1,
        },
        {
          content: 'current branch',
          createdAt: 2,
          id: 'msg-3',
          parentId: 'msg-1',
          role: 'assistant',
          updatedAt: 2,
        },
        {
          content: 'continued main flow',
          createdAt: 3,
          id: 'msg-4',
          parentId: 'msg-3',
          role: 'user',
          updatedAt: 3,
        },
        {
          content: 'newer threaded reply',
          createdAt: 4,
          id: 'msg-5',
          parentId: 'msg-2',
          role: 'user',
          threadId: 'thread-1',
          updatedAt: 4,
        },
      ];
      const resolverWithMessages = new BranchResolver(
        new Map(messages.map((item) => [item.id, item])),
      );
      const childrenMap = new Map<string | null, string[]>([
        ['msg-2', ['msg-5']],
        ['msg-3', ['msg-4']],
      ]);

      expect(
        resolverWithMessages.getActiveBranchIdFromMetadata(
          messages[0],
          ['msg-2', 'msg-3'],
          childrenMap,
        ),
      ).toBe('msg-3');
    });

    it('should default to first child when no hints available', () => {
      const message: Message = createUserMessage();

      const childIds = ['msg-2', 'msg-3'];
      const childrenMap = new Map<string | null, string[]>();

      expect(resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap)).toBe('msg-2');
    });

    it('should return undefined for optimistic update (activeBranchIndex === childIds.length)', () => {
      const message: Message = {
        content: 'test',
        createdAt: 0,
        id: 'msg-1',
        metadata: { activeBranchIndex: 2 }, // index = childIds.length (optimistic update)
        role: 'user',
        updatedAt: 0,
      };

      const childIds = ['msg-2', 'msg-3'];
      const childrenMap = new Map<string | null, string[]>();

      // When activeBranchIndex === childIds.length, it's an optimistic update
      // The branch hasn't been created yet, so return undefined
      expect(
        resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap),
      ).toBeUndefined();
    });

    it('should ignore activeBranchIndex when it exceeds optimistic update range', () => {
      const message: Message = {
        content: 'test',
        createdAt: 0,
        id: 'msg-1',
        metadata: { activeBranchIndex: 5 }, // > childIds.length (invalid)
        role: 'user',
        updatedAt: 0,
      };

      const childIds = ['msg-2', 'msg-3'];
      const childrenMap = new Map<string | null, string[]>();

      // activeBranchIndex > childIds.length should be ignored, fallback to default
      expect(resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap)).toBe('msg-2');
    });

    it('returns a lone child without walking its subtree', () => {
      // Every step of a long single-path chain resolves its one continuation
      // here; walking the subtree each time made parse quadratic.
      const message: Message = {
        content: '',
        createdAt: 0,
        id: 'tool-1',
        role: 'tool',
        updatedAt: 0,
      };
      const childrenMap = new Map<string | null, string[]>([['ast-2', ['tool-2']]]);
      const lookup = vi.spyOn(childrenMap, 'get');
      const resolverWithMessages = new BranchResolver(new Map([['tool-1', message]]));

      expect(
        resolverWithMessages.getActiveBranchIdFromMetadata(message, ['ast-2'], childrenMap),
      ).toBe('ast-2');
      expect(lookup).not.toHaveBeenCalled();
    });
  });
});