Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

8.5 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

class MockBroadcastChannel {
  static instance: MockBroadcastChannel | undefined;

  readonly postMessage = vi.fn();
  private messageHandler: ((event: { data: unknown }) => void) | undefined;

  constructor(readonly name: string) {
    MockBroadcastChannel.instance = this;
  }

  addEventListener(_type: string, handler: (event: { data: unknown }) => void) {
    this.messageHandler = handler;
  }

  emit(data: unknown) {
    this.messageHandler?.({ data });
  }
}

describe('call resolution signaling', () => {
  beforeEach(() => {
    localStorage.clear();
    MockBroadcastChannel.instance = undefined;
    vi.resetModules();
    vi.stubGlobal('BroadcastChannel', MockBroadcastChannel);
  });

  afterEach(() => {
    vi.unstubAllGlobals();
  });

  it('publishes to this tab and both cross-tab transports', async () => {
    const { publishCallResolution, subscribeToCallResolutions } = await import(
      '../call-resolution'
    );
    const handler = vi.fn();
    const unsubscribe = subscribeToCallResolutions(handler);
    const resolution = {
      type: 'answered' as const,
      callId: 'call-1',
      answeredBy: 'macro|[email protected]',
    };

    publishCallResolution(resolution);

    expect(handler).toHaveBeenCalledWith(resolution);
    expect(MockBroadcastChannel.instance?.name).toBe('macro-call-resolution');
    expect(MockBroadcastChannel.instance?.postMessage).toHaveBeenCalledWith(
      resolution
    );
    expect(
      JSON.parse(localStorage.getItem('macro.call-resolution') ?? '')
    ).toEqual(resolution);

    // Both transports can deliver the same cross-tab message.
    MockBroadcastChannel.instance?.emit(resolution);
    window.dispatchEvent(
      new StorageEvent('storage', {
        key: 'macro.call-resolution',
        newValue: JSON.stringify(resolution),
      })
    );
    expect(handler).toHaveBeenCalledTimes(1);
    unsubscribe();
  });

  it('receives valid BroadcastChannel and storage fallback messages', async () => {
    const { subscribeToCallResolutions } = await import('../call-resolution');
    const handler = vi.fn();
    const unsubscribe = subscribeToCallResolutions(handler);
    const answered = {
      type: 'answered',
      callId: 'call-1',
      answeredBy: 'macro|[email protected]',
    };
    const ended = {
      type: 'ended',
      channelId: 'channel-1',
      callId: 'call-2',
    };
    const declined = {
      type: 'declined',
      callId: 'call-3',
      declinedBy: 'macro|[email protected]',
    };

    MockBroadcastChannel.instance?.emit(answered);
    MockBroadcastChannel.instance?.emit({ type: 'answered' });
    MockBroadcastChannel.instance?.emit({ type: 'declined', callId: 'call-3' });
    window.dispatchEvent(
      new StorageEvent('storage', {
        key: 'macro.call-resolution',
        newValue: JSON.stringify(ended),
      })
    );
    MockBroadcastChannel.instance?.emit(declined);

    expect(handler).toHaveBeenNthCalledWith(1, answered);
    expect(handler).toHaveBeenNthCalledWith(2, ended);
    expect(handler).toHaveBeenNthCalledWith(3, declined);
    expect(handler).toHaveBeenCalledTimes(3);
    unsubscribe();
  });

  it('createCallResolutionsEffect unsubscribes when its owner is disposed', async () => {
    const { createRoot } = await import('solid-js');
    const { createCallResolutionsEffect, publishCallResolution } = await import(
      '../call-resolution'
    );
    const handler = vi.fn();
    const whileMounted = {
      type: 'ended' as const,
      channelId: 'channel-1',
      callId: 'call-1',
    };

    createRoot((dispose) => {
      createCallResolutionsEffect(handler);
      publishCallResolution(whileMounted);
      dispose();
    });
    publishCallResolution({ ...whileMounted, callId: 'call-2' });

    expect(handler).toHaveBeenCalledTimes(1);
    expect(handler).toHaveBeenCalledWith(whileMounted);
  });
});

describe('resolvesRingFor', () => {
  it('scopes answered and declined to the acting user and ended to everyone', async () => {
    const { resolvesRingFor } = await import('../call-resolution');
    const me = 'macro|[email protected]';
    const other = 'macro|[email protected]';

    expect(
      resolvesRingFor({ type: 'answered', callId: 'c', answeredBy: me }, me)
    ).toBe(true);
    expect(
      resolvesRingFor({ type: 'answered', callId: 'c', answeredBy: other }, me)
    ).toBe(false);
    expect(
      resolvesRingFor({ type: 'declined', callId: 'c', declinedBy: me }, me)
    ).toBe(true);
    expect(
      resolvesRingFor({ type: 'declined', callId: 'c', declinedBy: other }, me)
    ).toBe(false);
    expect(
      resolvesRingFor({ type: 'declined', callId: 'c', declinedBy: me }, null)
    ).toBe(false);
    expect(
      resolvesRingFor({ type: 'ended', callId: 'c', channelId: 'ch' }, me)
    ).toBe(true);
  });
});

describe('getCallRecordResolution', () => {
  it('does not publish a channel ring resolution for a standalone meeting', async () => {
    const { getCallRecordResolution } = await import('../call-resolution');
    expect(
      getCallRecordResolution(
        {
          callId: 'standalone-call',
          channelId: null,
          isActive: false,
          participants: [],
          viewerHasDeclined: false,
        },
        'macro|[email protected]'
      )
    ).toBeNull();
  });
  it('resolves an active call after the user has joined, even if they left', async () => {
    const { getCallRecordResolution } = await import('../call-resolution');

    expect(
      getCallRecordResolution(
        {
          callId: 'call-1',
          channelId: 'channel-1',
          isActive: true,
          participants: [
            {
              userId: 'macro|[email protected]',
              joinedAt: '2026-08-10T10:00:00.000Z',
              leftAt: '2026-08-10T10:01:00.000Z',
            },
          ],
          viewerHasDeclined: false,
        },
        'macro|[email protected]'
      )
    ).toEqual({
      type: 'answered',
      callId: 'call-1',
      answeredBy: 'macro|[email protected]',
    });
  });

  it('keeps ringing when a different user answered', async () => {
    const { getCallRecordResolution } = await import('../call-resolution');

    expect(
      getCallRecordResolution(
        {
          callId: 'call-1',
          channelId: 'channel-1',
          isActive: true,
          participants: [
            {
              userId: 'macro|[email protected]',
              joinedAt: '2026-08-10T10:00:00.000Z',
              leftAt: '2026-08-10T10:01:00.000Z',
            },
          ],
          viewerHasDeclined: false,
        },
        'macro|[email protected]'
      )
    ).toBeNull();
  });

  it('resolves a viewer decline when the websocket event was missed', async () => {
    const { getCallRecordResolution } = await import('../call-resolution');

    expect(
      getCallRecordResolution(
        {
          callId: 'call-1',
          channelId: 'channel-1',
          isActive: true,
          participants: [],
          viewerHasDeclined: true,
        },
        'macro|[email protected]'
      )
    ).toEqual({
      type: 'declined',
      callId: 'call-1',
      declinedBy: 'macro|[email protected]',
    });
  });

  it('prefers answered over an earlier viewer decline', async () => {
    const { getCallRecordResolution } = await import('../call-resolution');

    expect(
      getCallRecordResolution(
        {
          callId: 'call-1',
          channelId: 'channel-1',
          isActive: true,
          participants: [
            {
              userId: 'macro|[email protected]',
              joinedAt: '2026-08-10T10:00:00.000Z',
              leftAt: null,
            },
          ],
          viewerHasDeclined: true,
        },
        'macro|[email protected]'
      )
    ).toEqual({
      type: 'answered',
      callId: 'call-1',
      answeredBy: 'macro|[email protected]',
    });
  });

  it('resolves an inactive call as ended and leaves an unanswered call alone', async () => {
    const { getCallRecordResolution } = await import('../call-resolution');
    const unansweredRecord = {
      callId: 'call-1',
      channelId: 'channel-1',
      isActive: true,
      participants: [],
      viewerHasDeclined: false,
    };

    expect(
      getCallRecordResolution(unansweredRecord, 'macro|[email protected]')
    ).toBeNull();
    expect(
      getCallRecordResolution(
        { ...unansweredRecord, isActive: false },
        'macro|[email protected]'
      )
    ).toEqual({
      type: 'ended',
      callId: 'call-1',
      channelId: 'channel-1',
    });
  });
});