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 { type SendMessageParams, type UploadFileItem } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';

import { sendVoiceMessage } from './sendVoiceMessage';

const voiceFile = {
  id: 'voice-file',
  status: 'success',
} as UploadFileItem;

describe('sendVoiceMessage', () => {
  it('forwards the optimistic user message id to the formal send lifecycle', async () => {
    const context = { agentId: 'agent-1', topicId: 'topic-created' };
    const sendMessage = vi.fn(async (params: SendMessageParams) => {
      params.onMessageAccepted?.();
    });

    await expect(
      sendVoiceMessage(sendMessage, voiceFile, {
        context,
        optimisticUserMessageId: 'tmp-voice-message',
      }),
    ).resolves.toBeUndefined();

    expect(sendMessage).toHaveBeenCalledWith(
      expect.objectContaining({
        conversationContext: context,
        optimisticUserMessageId: 'tmp-voice-message',
      }),
    );
  });

  it('releases the recording after acceptance without waiting for generation to finish', async () => {
    let params: SendMessageParams | undefined;
    let resolveSend!: () => void;
    let sendFinished = false;
    const sendMessage = vi.fn((nextParams: SendMessageParams) => {
      params = nextParams;
      return new Promise<void>((resolve) => {
        resolveSend = () => {
          sendFinished = true;
          resolve();
        };
      });
    });

    const result = sendVoiceMessage(sendMessage, voiceFile);
    params?.onMessageAccepted?.();

    await expect(result).resolves.toBeUndefined();
    expect(sendFinished).toBe(false);
    expect(sendMessage).toHaveBeenCalledWith({
      files: [voiceFile],
      message: '',
      onMessageAccepted: expect.any(Function),
      preserveComposer: true,
    });

    resolveSend();
  });

  it('lets acceptance win when cancellation races with the underlying send completion', async () => {
    const controller = new AbortController();
    const abortError = new DOMException('cancelled', 'AbortError');
    let params: SendMessageParams | undefined;
    let rejectSend!: (reason: unknown) => void;
    const sendMessage = vi.fn((nextParams: SendMessageParams) => {
      params = nextParams;
      return new Promise<void>((_, reject) => {
        rejectSend = reject;
      });
    });

    const result = sendVoiceMessage(sendMessage, voiceFile, { signal: controller.signal });
    expect(params?.signal).toBe(controller.signal);

    params?.onMessageAccepted?.();
    controller.abort(abortError);
    rejectSend(abortError);

    await expect(result).resolves.toBeUndefined();
  });

  it('waits for an unaccepted send to settle before reporting cancellation', async () => {
    const controller = new AbortController();
    const abortError = new DOMException('cancelled', 'AbortError');
    let resolveSend!: () => void;
    const sendMessage = vi.fn(
      () =>
        new Promise<void>((resolve) => {
          resolveSend = resolve;
        }),
    );
    const settled = vi.fn();

    const result = sendVoiceMessage(sendMessage, voiceFile, { signal: controller.signal });
    void result.then(settled, settled);
    controller.abort(abortError);
    await Promise.resolve();

    expect(settled).not.toHaveBeenCalled();

    resolveSend();
    await expect(result).rejects.toBe(abortError);
  });

  it('does not dispatch a pre-cancelled recording', async () => {
    const controller = new AbortController();
    const abortError = new DOMException('cancelled', 'AbortError');
    const sendMessage = vi.fn();
    controller.abort(abortError);

    await expect(
      sendVoiceMessage(sendMessage, voiceFile, { signal: controller.signal }),
    ).rejects.toBe(abortError);
    expect(sendMessage).not.toHaveBeenCalled();
  });

  it('keeps the recording available for retry when acceptance is not acknowledged', async () => {
    const sendMessage = vi.fn().mockResolvedValue(undefined);

    await expect(sendVoiceMessage(sendMessage, voiceFile)).rejects.toThrow(
      'Voice message was not accepted',
    );
  });

  it('sends the transcript as the message content while keeping the recording attached', async () => {
    const sendMessage = vi.fn(async (params: SendMessageParams) => {
      params.onMessageAccepted?.();
    });
    const transcribe = vi.fn(async () => 'list the files here');

    await expect(sendVoiceMessage(sendMessage, voiceFile, { transcribe })).resolves.toBeUndefined();

    expect(transcribe).toHaveBeenCalledWith(voiceFile, undefined);
    expect(sendMessage).toHaveBeenCalledWith(
      expect.objectContaining({ files: [voiceFile], message: 'list the files here' }),
    );
  });

  it('does not send when transcription fails', async () => {
    const sendMessage = vi.fn();
    const transcribe = vi.fn(async () => {
      throw new Error('Voice message transcript is empty');
    });

    await expect(sendVoiceMessage(sendMessage, voiceFile, { transcribe })).rejects.toThrow(
      'Voice message transcript is empty',
    );
    expect(sendMessage).not.toHaveBeenCalled();
  });

  it('does not send when cancelled while transcribing', async () => {
    const sendMessage = vi.fn();
    const abortController = new AbortController();
    const transcribe = vi.fn(async () => {
      abortController.abort();
      return 'too late';
    });

    await expect(
      sendVoiceMessage(sendMessage, voiceFile, { signal: abortController.signal, transcribe }),
    ).rejects.toMatchObject({ name: 'AbortError' });
    expect(sendMessage).not.toHaveBeenCalled();
  });

  // A new topic's first turn runs the composer's git step first, like a typed send.
  it('sends into the worktree the git step prepared', async () => {
    const firstSendWorktree = {
      deviceId: 'dev-1',
      path: '/repo',
      repoType: 'git' as const,
      sourcePath: '/repo',
    };
    const sendMessage = vi.fn(async (params: SendMessageParams) => {
      params.onMessageAccepted?.();
    });

    await sendVoiceMessage(sendMessage, voiceFile, {
      prepare: async () => ({ firstSendWorktree, ok: true }),
    });

    expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ firstSendWorktree }));
  });

  it('passes a prepared Desktop checkout to the first voice send', async () => {
    const checkout = { path: '/repo', sessionPath: '/checkout' };
    const sendMessage = vi.fn(async (params: SendMessageParams) => {
      params.onMessageAccepted?.();
    });

    await sendVoiceMessage(sendMessage, voiceFile, {
      prepare: async () => ({ newTopicWorkingDirectory: checkout, ok: true }),
    });

    expect(sendMessage).toHaveBeenCalledWith(
      expect.objectContaining({ newTopicWorkingDirectory: checkout }),
    );
  });

  it('sends nothing, and keeps the recording retryable, when the git step stops', async () => {
    const sendMessage = vi.fn();

    await expect(
      sendVoiceMessage(sendMessage, voiceFile, {
        prepare: async () => ({ ok: false }),
        transcribe: async () => 'hello',
      }),
    ).rejects.toThrow();
    expect(sendMessage).not.toHaveBeenCalled();
  });

  // A failed transcript is retried; the git step must not have run for it.
  it('transcribes before the git step, so a failed transcript spends no branch pick', async () => {
    const prepare = vi.fn(async () => ({ ok: true as const }));

    await expect(
      sendVoiceMessage(vi.fn(), voiceFile, {
        prepare,
        transcribe: async () => {
          throw new Error('asr down');
        },
      }),
    ).rejects.toThrow('asr down');
    expect(prepare).not.toHaveBeenCalled();
  });
});