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.

10.6 KB
Raw Blame
import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { NewMeetingCapabilities } from '../context/new-meeting';
import { createMeetingSession } from './meeting-session';
import { createMeetingSessionLifecycle } from './meeting-session-lifecycle';
import { createNewMeeting } from './new-meeting';

const alice = {
  id: 'macro|[email protected]',
  name: 'Alice',
  email: '[email protected]',
};
const bob = {
  id: 'macro|[email protected]',
  name: 'Bob',
  email: '[email protected]',
};
const meeting = {
  id: 'meeting-1',
  shareToken: 'meeting-secret',
  title: 'Quick Call',
};
const credentials = {
  callId: 'call-1',
  channelId: null,
  roomName: 'room',
  serverUrl: 'wss://example.com',
  token: 'rtc-token',
  participantId: 'host',
  started: false,
  shareToken: meeting.shareToken,
};
const preferences = { microphoneEnabled: false, cameraEnabled: false };
const disposers: (() => void)[] = [];
// The session enters the call while invitations ring, so tests settle them last.
const rings: Promise<void>[] = [];
afterEach(async () => {
  await Promise.all(rings.splice(0));
  for (const dispose of disposers.splice(0)) dispose();
});

function setup(overrides: Partial<NewMeetingCapabilities> = {}) {
  return createRoot((dispose) => {
    disposers.push(dispose);
    const events: string[] = [];
    const [people, setPeople] = createSignal([alice, bob]);
    const [activeCallId, setActiveCallId] = createSignal<string | null>(null);
    const create = vi.fn(async () => {
      events.push('create');
      return meeting;
    });
    const invite = vi.fn(async () => {
      events.push('ring');
    });
    const prepareRoom = vi.fn(async () => ({
      id: 'prepared-room',
      expiresAt: new Date(Date.now() + 300_000).toISOString(),
    }));
    const cancelRoom = vi.fn(async () => undefined);
    const draft = createNewMeeting({
      people,
      create,
      invite,
      prepareRoom,
      cancelRoom,
      ...overrides,
    });
    const join = vi.fn(async () => {
      events.push('join');
      return credentials;
    });
    const connect = vi.fn(async () => {
      events.push('connect');
      setActiveCallId(credentials.callId);
    });
    const release = vi.fn(async () => undefined);
    const session = createMeetingSession({
      lifecycle: createMeetingSessionLifecycle(),
      prepare: draft.prepare,
      shareToken: () => draft.meeting()?.shareToken ?? '',
      isInCall: () => activeCallId() !== null,
      activeCallId,
      join,
      connect: async () => {
        await connect();
        rings.push(draft.ring());
      },
      disconnect: async () => {
        setActiveCallId(null);
      },
      release,
    });
    return {
      draft,
      session,
      create,
      invite,
      join,
      connect,
      release,
      events,
      prepareRoom,
      cancelRoom,
      dispose,
      setPeople,
    };
  });
}

describe('new meeting setup', () => {
  it('can warm a restored setup without reusing its cancelled room', async () => {
    const { draft, prepareRoom, cancelRoom } = setup();
    await draft.warmup();
    draft.cancel();
    await draft.warmup();
    expect(cancelRoom).toHaveBeenCalledOnce();
    expect(prepareRoom).toHaveBeenCalledTimes(2);
  });

  it('prepares once without creating or inviting, then claims the room on Start', async () => {
    const { draft, create, invite, prepareRoom, cancelRoom, dispose } = setup();
    await Promise.all([draft.warmup(), draft.warmup()]);
    expect(prepareRoom).toHaveBeenCalledOnce();
    expect(create).not.toHaveBeenCalled();
    expect(invite).not.toHaveBeenCalled();
    await draft.prepare(new AbortController().signal);
    expect(create).toHaveBeenCalledExactlyOnceWith('prepared-room');
    dispose();
    expect(cancelRoom).not.toHaveBeenCalled();
  });

  it('cancels an unused room including a preparation that finishes after disposal', async () => {
    for (const late of [false, true]) {
      let finish!: (room: { id: string; expiresAt: string }) => void;
      const prepareRoom = () =>
        new Promise<{ id: string; expiresAt: string }>((resolve) => {
          finish = resolve;
        });
      const { draft, dispose, cancelRoom, create } = setup({ prepareRoom });
      const warming = draft.warmup();
      if (late) dispose();
      finish({
        id: 'unused',
        expiresAt: new Date(Date.now() + 300_000).toISOString(),
      });
      await warming;
      if (!late) dispose();
      expect(cancelRoom).toHaveBeenCalledExactlyOnceWith('unused');
      expect(create).not.toHaveBeenCalled();
    }
  });

  it('falls back to ordinary creation when preparation fails or expires', async () => {
    for (const failed of [false, true]) {
      const { draft, create } = setup({
        prepareRoom: async () => {
          if (failed) throw new Error('offline');
          return { id: 'expired', expiresAt: new Date(0).toISOString() };
        },
      });
      await draft.warmup();
      await draft.prepare(new AbortController().signal);
      expect(create).toHaveBeenCalledExactlyOnceWith(undefined);
    }
  });

  it('does not create a meeting when Start is cancelled during room preparation', async () => {
    let finish!: (room: { id: string; expiresAt: string }) => void;
    const { draft, create } = setup({
      prepareRoom: () =>
        new Promise((resolve) => {
          finish = resolve;
        }),
    });
    const warming = draft.warmup();
    const attempt = new AbortController();
    const starting = draft.prepare(attempt.signal);
    attempt.abort();
    finish({
      id: 'unused',
      expiresAt: new Date(Date.now() + 300_000).toISOString(),
    });
    await Promise.all([starting, warming]);
    expect(create).not.toHaveBeenCalled();
  });

  it('keeps selection local until Start, then creates, connects and rings once', async () => {
    const { draft, session, create, invite, events } = setup();
    draft.select(new Set([alice.id, bob.id]));
    expect(create).not.toHaveBeenCalled();
    expect(invite).not.toHaveBeenCalled();
    await Promise.all([
      session.join(undefined, preferences),
      session.join(undefined, preferences),
    ]);
    expect(events).toEqual(['create', 'join', 'connect', 'ring']);
    expect(invite).toHaveBeenCalledExactlyOnceWith(meeting.shareToken, [
      alice.id,
      bob.id,
    ]);
    expect(session.joinedCallId()).toBe(credentials.callId);
  });

  it('enters the connected call while invitations are still pending', async () => {
    let finish!: () => void;
    const invite = vi.fn(
      () =>
        new Promise<void>((resolve) => {
          finish = resolve;
        })
    );
    const { draft, session } = setup({ invite });
    draft.select(new Set([alice.id]));
    await session.join(undefined, preferences);
    expect(session.joining()).toBe(false);
    expect(session.joinedCallId()).toBe(credentials.callId);
    expect(draft.inviting()).toBe(true);
    finish();
    await vi.waitFor(() => expect(draft.inviting()).toBe(false));
  });

  it('starts without invitees and reuses its meeting without ringing again on rejoin', async () => {
    const { draft, session, create, invite } = setup();
    await session.join(undefined, preferences);
    expect(invite).not.toHaveBeenCalled();
    await session.leave();
    draft.select(new Set([alice.id]));
    await session.join(undefined, preferences);
    expect(create).toHaveBeenCalledOnce();
    expect(invite).toHaveBeenCalledOnce();
    await session.leave();
    await session.join(undefined, preferences);
    expect(invite).toHaveBeenCalledOnce();
  });

  it('keeps a successful creation on connection failure and rings only after retry connects', async () => {
    const { draft, session, create, invite, connect } = setup();
    draft.select(new Set([alice.id]));
    connect.mockRejectedValueOnce(new Error('offline'));
    await session.join(undefined, preferences);
    expect(invite).not.toHaveBeenCalled();
    expect(session.error()).toBeTruthy();
    await session.join(undefined, preferences);
    expect(create).toHaveBeenCalledOnce();
    expect(invite).toHaveBeenCalledOnce();
  });

  it('does not ring or join after cancelling a pending creation, and reuses that link on retry', async () => {
    let finish!: (value: typeof meeting) => void;
    const create = vi.fn(
      () =>
        new Promise<typeof meeting>((resolve) => {
          finish = resolve;
        })
    );
    const { draft, session, join, invite, release } = setup({ create });
    draft.select(new Set([alice.id]));
    const starting = session.join(undefined, preferences);
    await vi.waitFor(() => expect(create).toHaveBeenCalledOnce());
    await session.leave();
    finish(meeting);
    await starting;
    expect(join).not.toHaveBeenCalled();
    expect(invite).not.toHaveBeenCalled();
    await session.join(undefined, preferences);
    expect(create).toHaveBeenCalledOnce();
    expect(invite).toHaveBeenCalledOnce();
    await session.leave();
    expect(release).toHaveBeenCalledWith(meeting.shareToken, credentials.token);
  });

  it('keeps the connected call if invitations fail and retries only the invitations', async () => {
    const { draft, session, invite, create, join, connect } = setup();
    draft.select(new Set([bob.id]));
    invite.mockRejectedValueOnce(new Error('offline'));
    await session.join(undefined, preferences);
    expect(session.joinedCallId()).toBe(credentials.callId);
    expect(session.error()).toBeUndefined();
    expect(draft.inviteError()).toBeTruthy();
    await draft.ring();
    expect(draft.inviteError()).toBeUndefined();
    expect(create).toHaveBeenCalledOnce();
    expect(join).toHaveBeenCalledOnce();
    expect(connect).toHaveBeenCalledOnce();
    expect(invite).toHaveBeenCalledTimes(2);
  });

  it('validates selected IDs against the latest roster before starting', async () => {
    const { draft, session, invite, setPeople } = setup();
    draft.select(new Set([alice.id, bob.id, 'bot|not-a-person']));
    expect([...draft.selected()]).toEqual([alice.id, bob.id]);
    setPeople([alice]);
    await session.join(undefined, preferences);
    expect(invite).toHaveBeenCalledExactlyOnceWith(meeting.shareToken, [
      alice.id,
    ]);
  });

  it('bounds the batch without silently replacing the previous selection', () => {
    const people = Array.from({ length: 51 }, (_, index) => ({
      id: `macro|user${index}@example.com`,
      name: `User ${index}`,
      email: `user${index}@example.com`,
    }));
    const { draft } = setup({ people: () => people });
    draft.select(new Set([people[0].id]));
    draft.select(new Set(people.map((person) => person.id)));
    expect([...draft.selected()]).toEqual([people[0].id]);
    expect(draft.selectionError()).toContain('50');
  });
});