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.

26.8 KB
Raw Blame
import { ThrownResultError } from '@core/util/result';
import type { ChannelEntity } from '@entity/types/entity';
import type { Notification } from '@entity/types/notification';
import {
  cleanup,
  fireEvent,
  render,
  screen,
  waitFor,
} from '@solidjs/testing-library';
import { CombinedError } from '@urql/core';
import {
  batch,
  createSignal,
  For,
  type JSX,
  type ParentProps,
  Show,
} from 'solid-js';
import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import type { ChannelsDataSource } from './queries';
import type { ChannelsTab } from './types';

type FullChannel = ChannelEntity & { notifications: Notification[] };
const mocks = vi.hoisted(() => ({
  pass: (props: { children?: JSX.Element }) => props.children,
  selectedId: (): string | undefined => undefined,
  rows: (): ChannelEntity[] => [],
  mobileLayout: (): boolean => false,
  sectionsEnabled: (): boolean => true,
  sectionsLoading: (): boolean => false,
  tab: (): ChannelsTab => 'browse',
  active: (): boolean => true,
  searchOpen: (): boolean => false,
  searchText: (): string => '',
  authenticated: (): boolean | undefined => true,
  target: (): { messageId: string; threadId?: string } | undefined => undefined,
  sourceEnabled: (_scope: string): boolean => false,
  selectedQuery: vi.fn(),
  markRead: vi.fn(),
  resolveTarget: vi.fn(() => ({ kind: 'message', messageId: 'unread' })),
  refresh: vi.fn(async () => {}),
  prefetchTarget: vi.fn(async () => {}),
  favoriteIds: (): string[] => [],
}));

vi.mock('@core/context/user', () => ({
  useIsAuthenticated: () => () => mocks.authenticated(),
}));
vi.mock('@channel/queries/prefetch-channel-target', () => ({
  prefetchChannelTarget: mocks.prefetchTarget,
}));
vi.mock('@channel/ChannelAccessDenied', () => ({
  ChannelAccessDenied: (props: {
    channelId: string;
    onRefreshChannel: () => void;
  }) => (
    <div data-testid="channel-access-denied" data-channel-id={props.channelId}>
      <button type="button" onClick={props.onRefreshChannel}>
        Complete approval
      </button>
    </div>
  ),
}));
vi.mock('./queries/channel-list-search-pool', () => ({
  useChannelListSearchPool: () => () => [],
}));
vi.mock('@queries/favorites/favorites', () => ({
  useFavoritesData: () => () => ({
    favorites: mocks.favoriteIds().map((entityId) => ({
      entityId,
      entityType: 'channel',
    })),
  }),
}));
vi.mock('@app/features/command/mobile/mobileSearchState', () => ({
  SearchState: {
    isOpen: () => mocks.searchOpen(),
    query: () => mocks.searchText(),
  },
}));
vi.mock('@queries/soup/search', () => ({
  useSearchSoupQuery: () => ({ isSuccess: false, isLoading: false }),
  validateSearchServiceText: (text: string) => text.length >= 3,
}));
vi.mock('@app/lib/split-router', () => ({
  SplitRouter: {
    Outlet: (props: { fallback: () => JSX.Element }) => (
      <Show when={mocks.selectedId()} fallback={props.fallback()}>
        <ChannelDetailRouteView />
      </Show>
    ),
  },
}));
vi.mock('@app/features/tours/ViewTour', () => ({ ViewTour: () => null }));
vi.mock('@app/components/view-shell', () => ({
  ViewShell: {
    Root: mocks.pass,
    Aside: mocks.pass,
    Main: mocks.pass,
    TopBar: mocks.pass,
  },
  ViewSidebar: { Title: (props: ParentProps) => <h1>{props.children}</h1> },
}));
vi.mock('@app/features/next-soup/utils', () => ({
  getChannelEntityTarget: mocks.resolveTarget,
  markChannelNotificationsSeenOnOpen: mocks.markRead,
}));
vi.mock('@app/features/soup', () => ({
  MaybeSoupEntityActionDrawerManager: mocks.pass,
}));
vi.mock('@app/features/soup/entity-notifications', () => ({
  withEntityNotifications: (entity: FullChannel) => ({
    ...entity,
    notifications:
      typeof entity.notifications === 'function'
        ? entity.notifications
        : () => entity.notifications,
  }),
}));
vi.mock('@components/app/GlobalAppState', () => ({
  useGlobalBlockOrchestrator: () => ({}),
  useGlobalNotificationSource: () => ({}),
}));
vi.mock('@components/app/PreviewPanel', () => ({
  PreviewPanel: (props: { target: { blockId: string } }) => (
    <div data-testid="legacy-preview">
      {props.target.blockId}
      <textarea aria-label="Composer" />
    </div>
  ),
}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
  useSplitPanelOrThrow: () => ({
    handle: { setDisplayName: vi.fn(), isActive: () => mocks.active() },
  }),
}));
vi.mock('@components/app/split-panel', () => ({
  SplitPanel: { Root: mocks.pass, Body: mocks.pass },
}));
vi.mock(
  '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
  () => ({ StaticMarkdownContext: mocks.pass })
);
vi.mock('@entity', async () => ({
  ...(await import('@entity/types/entity')),
  ListEntityMetadataQueryProvider: mocks.pass,
}));
vi.mock('./components/ChannelDetailView', () => ({
  ChannelDetailView: (props: { channel: ChannelEntity; target?: unknown }) => (
    <div
      data-testid="channel-detail"
      data-target={JSON.stringify(props.target)}
    >
      {props.channel.id}
      <textarea aria-label="Composer" />
    </div>
  ),
}));
vi.mock('./components/PendingDirectMessageDetail', () => ({
  PendingDirectMessageDetail: () => null,
}));
vi.mock('./components/ChannelThreadsView', () => ({
  ChannelThreadsView: () => <div data-testid="channel-threads" />,
}));
vi.mock('./components/ChannelsMobileView', () => ({
  ChannelsMobileView: (props: {
    source: ChannelsDataSource;
    pinned: readonly ChannelEntity[];
    searchQuery: string;
  }) => (
    <div
      data-testid="mobile-channels"
      data-query={props.searchQuery}
      data-pinned={props.pinned.map((channel) => channel.id).join(',')}
    >
      <For each={props.source.items()}>
        {(channel) => <div>{channel.name}</div>}
      </For>
    </div>
  ),
}));
vi.mock('./components/rail/ChannelsRail', () => ({ ChannelsRail: () => null }));
vi.mock('@channel/Channel/channel-entity', () => ({
  useChannelByIdQuery: mocks.selectedQuery,
}));
vi.mock('@core/mobile/isTouchDevice', () => ({
  isTouchDevice: () => mocks.mobileLayout(),
}));
vi.mock('@app/features/soup/search/context', () => ({
  useOptionalSearchContext: () => undefined,
}));
vi.mock('./channels-view-context', () => ({
  ChannelsViewProvider: mocks.pass,
  useChannelsView: () => ({
    state: {
      tab: 'browse',
      sortBy: { channels: 'updated_at', direct_messages: 'updated_at' },
    },
    tab: () => (mocks.sectionsEnabled() ? 'browse' : mocks.tab()),
    sectionsEnabled: () => mocks.sectionsEnabled(),
    sectionsLoading: () => mocks.sectionsLoading(),
    threadsChannelId: () => undefined,
    setTab: vi.fn(),
    setSelectedChannel: vi.fn(),
    mobileLayout: () => mocks.mobileLayout(),
    selectedChannel: () =>
      mocks.selectedId()
        ? {
            type: 'channel',
            id: mocks.selectedId(),
            target: mocks.target(),
          }
        : undefined,
  }),
}));
vi.mock('./queries', () => ({
  filterChannelsForScope: (_scope: string, channels: ChannelEntity[]) =>
    channels,
  deduplicateChannels: (collections: ChannelEntity[][]) => [
    ...new Map(
      collections.flat().map((channel) => [channel.id, channel])
    ).values(),
  ],
  resolveSelectedChannel: (
    id: string | undefined,
    loaded: ChannelEntity[],
    fallback: ChannelEntity[] = []
  ) => [...loaded, ...fallback].find((channel) => channel.id === id),
  useChannelsSources: (enabled: (scope: string) => boolean) => {
    mocks.sourceEnabled = enabled;
    return {
      team_channels: { items: () => mocks.rows() },
      channels: { items: () => mocks.rows() },
      direct_messages: { items: () => mocks.rows() },
      recents: { items: () => mocks.rows() },
      search: { items: () => [] },
      threads: { items: () => mocks.rows() },
    };
  },
}));

import { ChannelDetailRouteView, ChannelsView } from './channels-view';

const row = (id: string, unreadId?: string): ChannelEntity => ({
  id,
  type: 'channel',
  name: id,
  ownerId: 'viewer',
  channelType: 'private',
  isParticipant: true,
  unreadNotifications: unreadId
    ? [{ id: unreadId, state: 'unseen', createdAt: '2026-01-01' }]
    : [],
});
const full = (id: string, notificationIds: string[]): FullChannel => ({
  ...row(id),
  unreadNotifications: undefined,
  notifications: notificationIds.map((notificationId) => ({
    id: notificationId,
    entity_id: id,
    entity_type: 'channel',
    notification_event_type: 'channel_message_send',
    notification_metadata: {
      tag: 'channel_message_send',
      content: { messageId: notificationId, channelType: 'private' },
    },
    sent: true,
    state: 'unseen',
    created_at: '2026-01-01',
    updated_at: '2026-01-01',
  })),
});

type QueryState = {
  isLoading: boolean;
  isFetching: boolean;
  error: Error | null;
  data: { entities: FullChannel[] } | undefined;
};
let setQuery: ReturnType<typeof createStore<QueryState>>[1];
let setSelectedId: ReturnType<typeof createSignal<string | undefined>>[1];
let setRows: ReturnType<typeof createSignal<ChannelEntity[]>>[1];

beforeEach(() => {
  vi.clearAllMocks();
  mocks.mobileLayout = () => false;
  mocks.sectionsEnabled = () => true;
  mocks.sectionsLoading = () => false;
  mocks.tab = () => 'browse';
  mocks.favoriteIds = () => [];
  mocks.active = () => true;
  mocks.searchOpen = () => false;
  mocks.searchText = () => '';
  mocks.authenticated = () => true;
  mocks.target = () => undefined;
  [mocks.selectedId, setSelectedId] = createSignal<string | undefined>('one');
  [mocks.rows, setRows] = createSignal([row('one', 'new'), row('two')]);
  const [query, update] = createStore<QueryState>({
    isLoading: false,
    isFetching: false,
    error: null,
    data: { entities: [full('two', [])] },
  });
  setQuery = update;
  mocks.selectedQuery.mockImplementation((_id, enabled: () => boolean) => ({
    get isEnabled() {
      return enabled();
    },
    get isPending() {
      return query.isLoading;
    },
    get isLoading() {
      return query.isLoading;
    },
    get isFetching() {
      return query.isFetching;
    },
    get error() {
      return query.error;
    },
    get data() {
      return query.data;
    },
    refresh: mocks.refresh,
  }));
});
afterEach(cleanup);

describe('Chat rollout source activation', () => {
  it('waits for the desktop flag before loading sources or mounting either experience', () => {
    const [loading, setLoading] = createSignal(true);
    mocks.sectionsLoading = loading;
    mocks.sectionsEnabled = () => false;
    mocks.tab = () => 'recents';
    render(() => <ChannelsView />);
    for (const scope of [
      'team_channels',
      'channels',
      'direct_messages',
      'recents',
      'threads',
      'search',
    ]) {
      expect(mocks.sourceEnabled(scope)).toBe(false);
    }
    expect(screen.queryByTestId('channel-detail')).toBeNull();
    setLoading(false);
    expect(mocks.sourceEnabled('recents')).toBe(true);
    expect(mocks.sourceEnabled('channels')).toBe(false);
  });

  it('restores a saved legacy tab without activating it while sections are enabled', () => {
    const [enabled, setEnabled] = createSignal(true);
    mocks.sectionsEnabled = enabled;
    mocks.tab = () => 'recents';
    render(() => <ChannelsView />);
    expect(mocks.sourceEnabled('channels')).toBe(true);
    expect(mocks.sourceEnabled('recents')).toBe(false);
    setEnabled(false);
    expect(mocks.sourceEnabled('channels')).toBe(false);
    expect(mocks.sourceEnabled('recents')).toBe(true);
  });

  it('restores the Threads surface only in the legacy layout', () => {
    const [enabled, setEnabled] = createSignal(false);
    mocks.sectionsEnabled = enabled;
    mocks.tab = () => 'threads';
    render(() => <ChannelsView />);
    expect(screen.getByTestId('channel-threads')).toBeTruthy();
    expect(mocks.sourceEnabled('threads')).toBe(true);
    setEnabled(true);
    expect(screen.queryByTestId('channel-threads')).toBeNull();
    expect(mocks.sourceEnabled('threads')).toBe(false);
    expect(mocks.sourceEnabled('channels')).toBe(true);
  });

  it('keeps the mobile recent feed active while the desktop rollout is unresolved', () => {
    mocks.mobileLayout = () => true;
    mocks.sectionsLoading = () => true;
    render(() => <ChannelsView />);
    expect(screen.getByTestId('mobile-channels')).toBeTruthy();
    expect(mocks.sourceEnabled('recents')).toBe(true);
    expect(mocks.sourceEnabled('channels')).toBe(false);
  });
});
describe('mobile dock search wiring', () => {
  it('shows only recent conversations independently of the dock search session', () => {
    mocks.mobileLayout = () => true;
    const [open, setOpen] = createSignal(true);
    const [text, setText] = createSignal('');
    const [active, setActive] = createSignal(true);
    mocks.searchOpen = open;
    mocks.searchText = text;
    mocks.active = active;
    setRows([
      {
        ...row('julia'),
        name: 'Julia Westphal',
        channelType: 'direct_message',
      },
      { ...row('hutch'), name: 'hutch', channelType: 'direct_message' },
    ]);
    render(() => <ChannelsView />);
    expect(screen.getByText('hutch')).toBeTruthy();
    expect(mocks.sourceEnabled('recents')).toBe(true);
    for (const scope of ['channels', 'direct_messages', 'threads', 'search']) {
      expect(mocks.sourceEnabled(scope)).toBe(false);
    }
    setText('Julia');
    expect(screen.getByText('Julia Westphal')).toBeTruthy();
    expect(screen.getByText('hutch')).toBeTruthy();
    setActive(false);
    expect(screen.getByText('hutch')).toBeTruthy();
    setActive(true);
    expect(screen.getByText('hutch')).toBeTruthy();
    setOpen(false);
    expect(screen.getByText('hutch')).toBeTruthy();
    expect(screen.getByTestId('mobile-channels').dataset.query).toBe('');
  });

  it('pins the first six loaded channel favorites in favorite order', () => {
    mocks.mobileLayout = () => true;
    setRows(['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((id) => row(id)));
    mocks.favoriteIds = () => ['g', 'missing', 'f', 'e', 'd', 'c', 'b', 'a'];
    render(() => <ChannelsView />);
    expect(screen.getByTestId('mobile-channels').dataset.pinned).toBe(
      'g,f,e,d,c,b'
    );
  });
});

describe('channel selection loading and recovery', () => {
  it('prefetches an explicit target while uncached channel metadata is loading', () => {
    const target = { messageId: 'reply', threadId: 'root' };
    mocks.target = () => target;
    setRows([]);
    setQuery({ isLoading: true, isFetching: true, data: undefined });
    render(() => <ChannelsView />);
    expect(mocks.prefetchTarget).toHaveBeenCalledExactlyOnceWith('one', target);
    expect(
      screen.getByRole('status', { name: 'Loading conversation' })
    ).toBeTruthy();
    expect(screen.queryByTestId('channel-detail')).toBeNull();
    setQuery({
      isLoading: false,
      isFetching: false,
      data: { entities: [full('one', [])] },
    });
    expect(screen.getByTestId('channel-detail').textContent).toBe('one');
    expect(mocks.prefetchTarget).toHaveBeenCalledOnce();
  });

  it.each([false, undefined])(
    'waits for confirmed authentication before prefetching a target from %s',
    (initial) => {
      const [authenticated, setAuthenticated] = createSignal<
        boolean | undefined
      >(initial);
      mocks.authenticated = authenticated;
      const target = { messageId: 'root', threadId: 'root' };
      mocks.target = () => target;
      render(() => <ChannelsView />);
      expect(mocks.prefetchTarget).not.toHaveBeenCalled();
      setAuthenticated(true);
      expect(mocks.prefetchTarget).toHaveBeenCalledExactlyOnceWith(
        'one',
        target
      );
    }
  );

  it.each(['pointerDown', 'keyDown', 'wheel'] as const)(
    'stays at latest after %s and notification hydration',
    (event) => {
      setQuery({ isFetching: true, data: undefined });
      render(() => <ChannelsView />);
      const composer = screen.getByRole('textbox', { name: 'Composer' });
      fireEvent[event](composer);
      batch(() =>
        setQuery({
          isFetching: false,
          data: { entities: [full('one', ['unread'])] },
        })
      );
      expect(mocks.resolveTarget).not.toHaveBeenCalled();
      expect(screen.getByTestId('channel-detail').dataset.target).toBe(
        JSON.stringify({ kind: 'latest' })
      );
      expect(mocks.markRead).toHaveBeenCalledOnce();
    }
  );

  it('stays at latest after mounting when notifications arrive', () => {
    setQuery({ isFetching: true, data: undefined });
    render(() => <ChannelsView />);
    const composer = screen.getByRole('textbox', { name: 'Composer' });
    batch(() =>
      setQuery({
        isFetching: false,
        data: { entities: [full('one', ['unread'])] },
      })
    );
    expect(screen.getByTestId('channel-detail').dataset.target).toBe(
      JSON.stringify({ kind: 'latest' })
    );
    expect(screen.getByRole('textbox', { name: 'Composer' })).toBe(composer);
  });

  it('preserves an already-loaded full notification edge on route open', () => {
    setRows([full('one', ['unread-message'])]);
    render(() => <ChannelsView />);
    expect(mocks.markRead).toHaveBeenCalledOnce();
    const marked = mocks.markRead.mock.calls[0][0];
    expect(
      marked
        .notifications()
        .map((notification: Notification) => notification.id)
    ).toEqual(['unread-message']);
  });

  it('keeps the composer mounted and focused across loading, failure, retry, and recovery', () => {
    setQuery({ isFetching: true, data: undefined });
    render(() => <ChannelsView />);
    const composer = screen.getByRole('textbox', { name: 'Composer' });
    composer.focus();
    batch(() => setQuery({ isFetching: false, error: new Error('Offline') }));
    expect(screen.getByRole('textbox', { name: 'Composer' })).toBe(composer);
    batch(() => setQuery({ isFetching: true, error: null }));
    expect(screen.getByRole('textbox', { name: 'Composer' })).toBe(composer);
    batch(() =>
      setQuery({
        isFetching: false,
        data: { entities: [full('one', ['new'])] },
      })
    );
    expect(screen.getByRole('textbox', { name: 'Composer' })).toBe(composer);
    expect(document.activeElement).toBe(composer);
    expect(mocks.markRead).toHaveBeenCalledOnce();
  });

  it.each([
    new Error('Connection interrupted'),
    new ThrownResultError([{ code: 'NETWORK_ERROR', message: 'Offline' }]),
    new ThrownResultError([{ code: 'SERVER_ERROR', message: 'Server failed' }]),
    new CombinedError({ networkError: new Error('Offline') }),
    new CombinedError({
      networkError: new Error('HTTP 503'),
      response: { status: 503 },
    }),
  ])(
    'renders an empty unread projection after a transient failure without marking read: %s',
    (error) => {
      setSelectedId('two');
      setQuery({ error, data: undefined });
      render(() => <ChannelsView />);
      expect(screen.getByTestId('channel-detail').textContent).toBe('two');
      expect(screen.queryByText('Conversation unavailable')).toBeNull();
      expect(mocks.markRead).not.toHaveBeenCalled();

      batch(() => {
        setQuery('data', { entities: [full('two', ['fresh'])] });
        setQuery('error', null);
      });
      expect(mocks.markRead).toHaveBeenCalledOnce();
      const marked = mocks.markRead.mock.calls[0][0] as {
        notifications: () => Notification[];
      };
      expect(
        marked.notifications().map((notification) => notification.id)
      ).toEqual(['fresh']);
    }
  );

  it('does not mark a cached nonempty unread projection on a transient failure', () => {
    setQuery({ error: new Error('Offline'), data: undefined });
    render(() => <ChannelsView />);
    expect(screen.getByTestId('channel-detail').textContent).toBe('one');
    expect(mocks.markRead).not.toHaveBeenCalled();
  });

  it.each([
    new ThrownResultError([{ code: 'UNAUTHORIZED', message: 'Unauthorized' }]),
    new ThrownResultError([{ code: 'FORBIDDEN', message: 'Forbidden' }]),
    new ThrownResultError([{ code: 'NOT_FOUND', message: 'Not found' }]),
    new CombinedError({
      networkError: new Error('HTTP 401'),
      response: { status: 401 },
    }),
    new CombinedError({
      networkError: new Error('HTTP 403'),
      response: { status: 403 },
    }),
    new CombinedError({
      graphQLErrors: [
        { message: 'Forbidden', extensions: { code: 'FORBIDDEN' } },
      ],
    }),
  ])(
    'keeps access failures unavailable even with cached or previously loaded data: %s',
    (error) => {
      setSelectedId('two');
      setQuery('error', error);
      render(() => <ChannelsView />);
      expect(screen.getByTestId('channel-access-denied')).toBeTruthy();
      expect(screen.queryByTestId('channel-detail')).toBeNull();
      expect(mocks.markRead).not.toHaveBeenCalled();

      setQuery('error', null);
      expect(screen.getByTestId('channel-detail').textContent).toBe('two');
      mocks.markRead.mockClear();
      setQuery('error', error);
      expect(screen.getByTestId('channel-access-denied')).toBeTruthy();
      expect(screen.queryByTestId('channel-detail')).toBeNull();
      expect(mocks.markRead).not.toHaveBeenCalled();
    }
  );

  it('loads an uncached private channel after its access request is approved', async () => {
    setRows([]);
    setSelectedId('private');
    setQuery({ error: null, data: { entities: [] } });
    render(() => <ChannelsView />);

    expect(screen.getByTestId('channel-access-denied').dataset.channelId).toBe(
      'private'
    );
    expect(screen.queryByTestId('channel-detail')).toBeNull();
    expect(mocks.markRead).not.toHaveBeenCalled();

    fireEvent.click(screen.getByRole('button', { name: 'Complete approval' }));
    await waitFor(() => expect(mocks.refresh).toHaveBeenCalledOnce());
    setQuery('data', { entities: [full('private', [])] });

    expect(screen.getByTestId('channel-detail').textContent).toBe('private');
    expect(screen.queryByTestId('channel-access-denied')).toBeNull();
    expect(mocks.markRead).toHaveBeenCalledOnce();
  });

  it('keeps an empty channel lookup on the same denied route during refresh', () => {
    setRows([]);
    setQuery({ error: null, data: { entities: [] } });
    render(() => <ChannelsView />);
    const denied = screen.getByTestId('channel-access-denied');

    setQuery('isFetching', true);
    expect(screen.getByTestId('channel-access-denied')).toBe(denied);
    setQuery('isFetching', false);
    expect(screen.getByTestId('channel-access-denied')).toBe(denied);
    expect(mocks.markRead).not.toHaveBeenCalled();
  });

  it('keeps an uncached channel unavailable after a transient failure', () => {
    setRows([]);
    setQuery({ error: new Error('Offline'), data: undefined });
    render(() => <ChannelsView />);
    expect(screen.getByText('Conversation unavailable')).toBeTruthy();
    expect(screen.queryByTestId('channel-detail')).toBeNull();
    expect(mocks.markRead).not.toHaveBeenCalled();
  });

  it('shows the selected channel while its notification data is still loading', () => {
    setSelectedId('two');
    render(() => <ChannelsView />);
    expect(screen.getByTestId('channel-detail').textContent).toBe('two');
    mocks.markRead.mockClear();

    batch(() => {
      setQuery('isFetching', true);
      setSelectedId('one');
    });
    expect(screen.getByTestId('channel-detail').textContent).toBe('one');
    expect(screen.queryByText('Loading conversation')).toBeNull();
    expect(mocks.markRead).not.toHaveBeenCalled();

    batch(() => {
      setQuery('data', { entities: [full('one', ['new'])] });
      setQuery('isFetching', false);
    });
    expect(screen.getByTestId('channel-detail').textContent).toBe('one');
    expect(mocks.markRead).toHaveBeenCalledOnce();
  });

  it('renders an empty unread projection while refreshing its notifications', () => {
    setSelectedId('two');
    setQuery('isFetching', true);
    render(() => <ChannelsView />);
    expect(screen.getByTestId('channel-detail')).toBeTruthy();
    expect(mocks.markRead).not.toHaveBeenCalled();
    batch(() => {
      setQuery('data', { entities: [full('two', ['arrived-after-list'])] });
      setQuery('isFetching', false);
    });
    expect(screen.getByTestId('channel-detail').textContent).toBe('two');
    expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(
      expect.objectContaining({ id: 'two' }),
      expect.anything(),
      { channelReadScope: 'top-level' }
    );
  });

  it('refreshes a previously listed channel after access approval', async () => {
    render(() => <ChannelsView />);
    const denied = screen.getByTestId('channel-access-denied');
    expect(screen.queryByText('Loading conversation')).toBeNull();
    await fireEvent.click(
      screen.getByRole('button', { name: 'Complete approval' })
    );
    expect(mocks.refresh).toHaveBeenCalledOnce();
    expect(mocks.markRead).not.toHaveBeenCalled();

    setQuery('isFetching', true);
    expect(screen.getByTestId('channel-access-denied')).toBe(denied);
    expect(screen.queryByTestId('channel-detail')).toBeNull();
    batch(() => {
      setQuery('data', { entities: [full('one', ['new'])] });
      setQuery('isFetching', false);
    });
    expect(screen.getByTestId('channel-detail').textContent).toBe('one');
    expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(
      expect.objectContaining({ id: 'one' }),
      expect.anything(),
      { channelReadScope: 'top-level' }
    );
  });

  it('never marks cached data while a reopened selection is refreshing', async () => {
    setQuery('data', { entities: [full('one', ['old']), full('two', [])] });
    render(() => <ChannelsView />);
    await waitFor(() => expect(mocks.markRead).toHaveBeenCalledOnce());
    setSelectedId('two');
    await waitFor(() => expect(mocks.markRead).toHaveBeenCalledTimes(2));
    mocks.markRead.mockClear();
    batch(() => {
      setSelectedId('one');
      setQuery('isFetching', true);
    });
    expect(screen.getByTestId('channel-detail')).toBeTruthy();
    expect(mocks.markRead).not.toHaveBeenCalled();
    batch(() => {
      setQuery('data', { entities: [full('one', ['old', 'new'])] });
      setQuery('isFetching', false);
    });
    expect(mocks.markRead).toHaveBeenCalledOnce();
    const marked = mocks.markRead.mock.calls[0][0] as {
      notifications: () => Notification[];
    };
    expect(
      marked.notifications().map((notification) => notification.id)
    ).toEqual(['old', 'new']);
  });

  it('keeps an already-open read conversation focused when its unread edge changes', async () => {
    setSelectedId('two');
    render(() => <ChannelsView />);
    await waitFor(() => expect(mocks.markRead).toHaveBeenCalledOnce());
    const composer = screen.getByRole('textbox', { name: 'Composer' });
    composer.focus();
    mocks.markRead.mockClear();
    setRows([row('one', 'new'), row('two', 'incoming')]);
    expect(screen.getByRole('textbox', { name: 'Composer' })).toBe(composer);
    expect(document.activeElement).toBe(composer);
    expect(mocks.markRead).not.toHaveBeenCalled();
  });

  it('keeps no selection distinct from an unavailable conversation', () => {
    setQuery('error', new Error('previous selection failed'));
    setSelectedId(undefined);
    render(() => <ChannelsView />);
    expect(screen.getByText('Select a conversation')).toBeTruthy();
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();
  });
});