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.

9.7 KB
Raw Blame
import {
  useEntitySubscription,
  useRefreshTrackedEntitiesOnFocus,
  useReopenTrackedEntitiesOnReconnect,
} from '@service-connection/client';
import type { MessageParent } from '@service-storage/messages';
import { createRoot, createSignal } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { useMessageThreadQuery } from '../thread-replies';

const mocks = await vi.hoisted(async () => {
  const { createSignal } = await import('solid-js');
  const [visible, setVisible] = createSignal(true);
  return {
    send: vi.fn(),
    clearStream: vi.fn(),
    visible,
    setVisible,
    invalidate: vi.fn().mockResolvedValue(undefined),
    updates: new Set<(event: unknown) => void>(),
    reconnects: new Set<() => void>(),
    warn: vi.fn(),
  };
});
vi.mock('@macro-inc/observability', () => ({
  Telemetry: { info: vi.fn(), warn: mocks.warn, error: vi.fn() },
}));
// Focus is elsewhere throughout: presence follows visibility alone.
vi.mock('@core/signal/tabFocus', () => ({
  isTabFocused: () => false,
  isTabVisible: mocks.visible,
}));
vi.mock('@service-connection/stream', () => ({
  clearStream: mocks.clearStream,
}));
vi.mock('@service-connection/websocket', async () => {
  const { onCleanup } = await import('solid-js');
  return {
    ws: { send: mocks.send },
    createConnectionWebsocketEffect: (callback: (event: unknown) => void) => {
      mocks.updates.add(callback);
      onCleanup(() => mocks.updates.delete(callback));
    },
  };
});
vi.mock('@macro-inc/collaboration/websocket', async () => {
  const { onCleanup } = await import('solid-js');
  return {
    createReconnectEffect: (_ws: unknown, callback: () => void) => {
      mocks.reconnects.add(callback);
      onCleanup(() => mocks.reconnects.delete(callback));
    },
  };
});
vi.mock('@service-storage/messages', () => ({ entityMessagesClient: {} }));
vi.mock('@tanstack/solid-query', () => ({
  useQuery: (options: () => unknown) => options(),
}));
vi.mock('../../client', () => ({
  queryClient: {
    invalidateQueries: mocks.invalidate,
    getQueryState: () => undefined,
    getQueriesData: () => [],
  },
}));

const parent: MessageParent = { type: 'document', id: 'source-document' };
const disposers: (() => void)[] = [];
function mount(view: () => void) {
  return createRoot((dispose) => {
    disposers.push(dispose);
    view();
    return dispose;
  });
}
function mountBlock() {
  return mount(() =>
    useEntitySubscription(() => ({
      entity_type: parent.type,
      entity_id: parent.id,
    }))
  );
}
function sent(action: string, id = parent.id) {
  return mocks.send.mock.calls.filter(
    ([message]) => message.action === action && message.entity_id === id
  );
}
beforeEach(() => {
  vi.useFakeTimers();
  vi.clearAllMocks();
  mocks.setVisible(true);
});
afterEach(() => {
  for (const dispose of disposers.splice(0)) dispose();
  vi.useRealTimers();
});

it('subscribes and heartbeats a linked document drawer without a document block', () => {
  const close = mount(() =>
    useMessageThreadQuery(
      () => parent,
      () => 'root'
    )
  );
  expect(sent('open')).toHaveLength(1);
  vi.advanceTimersByTime(20_000);
  expect(sent('ping')).toHaveLength(1);
  close();
  expect(sent('close')).toHaveLength(1);
  vi.advanceTimersByTime(20_000);
  expect(sent('ping')).toHaveLength(1);
  expect(mocks.updates.size).toBe(0);
});

it('tracks and refreshes a call thread independently from its channel', () => {
  const call: MessageParent = { type: 'call', id: 'call-id' };
  const channel: MessageParent = { type: 'channel', id: 'channel-id' };
  mount(() => {
    useReopenTrackedEntitiesOnReconnect();
    useMessageThreadQuery(
      () => call,
      () => call.id
    );
    useMessageThreadQuery(
      () => channel,
      () => 'root'
    );
  });
  expect(sent('open', call.id)[0][0].entity_type).toBe('call');
  expect(sent('open', channel.id)[0][0].entity_type).toBe('channel');
  mocks.invalidate.mockClear();
  for (const reconnect of mocks.reconnects) reconnect();
  expect(mocks.invalidate).toHaveBeenCalledWith({
    queryKey: ['messages', 'threadReplies', call],
  });
  expect(mocks.invalidate).toHaveBeenCalledWith({
    queryKey: ['messages', 'threadReplies', channel],
  });
});

it.each(['drawer', 'block'] as const)(
  'keeps the source subscription alive when the %s closes first',
  (first) => {
    const closeBlock = mountBlock();
    const closeDrawer = mount(() =>
      useMessageThreadQuery(
        () => parent,
        () => 'root'
      )
    );
    expect(sent('open')).toHaveLength(1);
    const closeFirst = first === 'drawer' ? closeDrawer : closeBlock;
    const closeLast = first === 'drawer' ? closeBlock : closeDrawer;
    closeFirst();
    expect(sent('close')).toHaveLength(0);
    expect(mocks.clearStream).not.toHaveBeenCalled();
    vi.advanceTimersByTime(20_000);
    expect(sent('ping')).toHaveLength(1);
    closeLast();
    expect(sent('close')).toHaveLength(1);
    expect(mocks.clearStream).toHaveBeenCalledWith(parent.id);
  }
);

it('shares heartbeat and reconnect work across many threads in one parent', () => {
  mount(useReopenTrackedEntitiesOnReconnect);
  const closeBlock = mountBlock();
  const closeThreads = Array.from({ length: 50 }, (_, index) =>
    mount(() =>
      useMessageThreadQuery(
        () => parent,
        () => `root-${index}`
      )
    )
  );
  expect(sent('open')).toHaveLength(1);
  expect(mocks.invalidate).toHaveBeenCalledTimes(3);
  mocks.invalidate.mockClear();
  vi.advanceTimersByTime(20_000);
  expect(sent('ping')).toHaveLength(1);
  for (const reconnect of mocks.reconnects) reconnect();
  expect(sent('open')).toHaveLength(2);
  expect(mocks.invalidate).toHaveBeenCalledTimes(3);

  closeThreads[0]();
  mocks.invalidate.mockClear();
  for (const reconnect of mocks.reconnects) reconnect();
  expect(mocks.invalidate).toHaveBeenCalledTimes(3);
  for (const close of closeThreads.slice(1)) close();
  mocks.invalidate.mockClear();
  for (const reconnect of mocks.reconnects) reconnect();
  expect(mocks.invalidate).not.toHaveBeenCalled();
  expect(sent('close')).toHaveLength(0);
  vi.advanceTimersByTime(20_000);
  expect(sent('ping')).toHaveLength(2);
  closeBlock();
  expect(sent('close')).toHaveLength(1);
  vi.advanceTimersByTime(20_000);
  expect(sent('ping')).toHaveLength(2);
});

it('refreshes cached messages after all views close and the parent reopens', () => {
  const open = () =>
    mount(() =>
      useMessageThreadQuery(
        () => parent,
        () => 'root'
      )
    );
  const close = open();
  expect(mocks.invalidate).toHaveBeenCalledTimes(3);
  close();
  mocks.invalidate.mockClear();
  open();
  expect(sent('open')).toHaveLength(2);
  expect(mocks.invalidate).toHaveBeenCalledTimes(3);
});

it('keeps the heartbeat in a visible tab whose window is not focused', () => {
  mountBlock();
  vi.advanceTimersByTime(60_000);
  expect(sent('ping')).toHaveLength(3);
});

it('suspends the shared heartbeat in a background tab', () => {
  mountBlock();
  mocks.setVisible(false);
  vi.advanceTimersByTime(40_000);
  expect(sent('ping')).toHaveLength(0);
  mocks.setVisible(true);
  vi.advanceTimersByTime(20_000);
  expect(sent('ping')).toHaveLength(1);
});

it('reports a presence lapse once per hidden absence past the gateway window', () => {
  mount(useRefreshTrackedEntitiesOnFocus);
  mountBlock();
  const lapses = () =>
    mocks.warn.mock.calls.filter(
      ([name]) => name === 'presence.heartbeat_lapsed'
    );

  mocks.setVisible(false);
  vi.advanceTimersByTime(40_000);
  expect(lapses()).toHaveLength(0);
  vi.advanceTimersByTime(40_000);
  expect(lapses()).toHaveLength(1);
  expect(lapses()[0][1]).toMatchObject({
    'presence.entity_id': parent.id,
    'presence.lapsed_ms': 60_000,
  });
  vi.advanceTimersByTime(60_000);
  expect(lapses()).toHaveLength(1);

  mocks.setVisible(true);
  mocks.setVisible(false);
  vi.advanceTimersByTime(60_000);
  expect(lapses()).toHaveLength(2);
});

it('pings when visible again and refreshes only views left unseen past the gateway window', () => {
  mount(useRefreshTrackedEntitiesOnFocus);
  mount(() =>
    useMessageThreadQuery(
      () => parent,
      () => 'root'
    )
  );
  mocks.invalidate.mockClear();

  // Heartbeats keep the gateway's view fresh while visible, focused or not.
  vi.advanceTimersByTime(80_000);
  expect(sent('ping')).toHaveLength(4);
  mocks.setVisible(false);
  vi.advanceTimersByTime(30_000);
  mocks.setVisible(true);
  expect(sent('ping')).toHaveLength(5);
  expect(mocks.invalidate).not.toHaveBeenCalled();

  // Away past the window: the gateway stopped sending this parent's events.
  mocks.setVisible(false);
  vi.advanceTimersByTime(60_000);
  expect(sent('ping')).toHaveLength(5);
  mocks.setVisible(true);
  expect(sent('ping')).toHaveLength(6);
  expect(mocks.invalidate).toHaveBeenCalledTimes(3);
  expect(mocks.invalidate).toHaveBeenCalledWith({
    queryKey: ['messages', 'threadReplies', parent],
  });
});

it('moves the drawer subscription with its source and reopens all remaining owners on reconnect', () => {
  mountBlock();
  const [source, setSource] = createSignal(parent);
  mount(() => {
    useReopenTrackedEntitiesOnReconnect();
    useMessageThreadQuery(source, () => 'root');
  });
  // Refetched session metadata may replace the parent object without changing it.
  setSource({ ...parent });
  expect(sent('open')).toHaveLength(1);
  expect(sent('close')).toHaveLength(0);
  setSource({ type: 'document', id: 'next-document' });
  expect(sent('close')).toHaveLength(0);
  expect(sent('open', 'next-document')).toHaveLength(1);
  for (const reconnect of mocks.reconnects) reconnect();
  expect(sent('open')).toHaveLength(2);
  expect(sent('open', 'next-document')).toHaveLength(2);
  expect(mocks.invalidate).toHaveBeenLastCalledWith({
    queryKey: [
      'messages',
      'threadReplies',
      { type: 'document', id: 'next-document' },
    ],
  });
});