Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

27.7 KB
Raw Blame
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

// The row's siblings reach the renderer IPC bridge at import time, which only
// exists inside Electron. Hoisted so it is in place before those modules are
// evaluated. Nothing asserted here calls through it.
vi.hoisted(() => {
  window.electronAPI ??= {
    invoke: () => Promise.resolve(undefined),
    eventOn: () => () => {},
    eventSend: () => {},
  } as unknown as typeof window.electronAPI;
});

const beginMessagingAppInstall = vi.hoisted(() => vi.fn());
const releaseBridgeIdentity = vi.hoisted(() => vi.fn());
const cancelIdentityLinkRequest = vi.hoisted(() => vi.fn());
const openExternalUrl = vi.hoisted(() => vi.fn());
const showModal = vi.hoisted(() => vi.fn());

vi.mock('@renderer/lib/ipc', () => ({
  rpc: {
    workspaces: { beginMessagingAppInstall, releaseBridgeIdentity, cancelIdentityLinkRequest },
  },
  events: { on: () => () => {}, emit: () => {} },
}));
vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl, reportOpenAttempt: vi.fn() }));
vi.mock('@renderer/lib/modal/modal-provider', () => ({
  useShowModal: (id: string) => (args: unknown) => showModal(id, args),
}));

/**
 * One messaging app, one line (CHOO-2137).
 *
 * The card used to answer "which account is you here" in two different shapes:
 * a linked app showed bare text plus a stray cross, an unlinked one showed a
 * button. Same column, same question, two visual languages — and the cross put
 * an irreversible unlink one mis-click from the control you press to *change*
 * an account. These pin the shape down: one control in the column either way,
 * the badges tied to the app name, and everything rare or destructive behind
 * the row menu.
 */
import { MessagingAppRow } from '@renderer/features/switch-servers/MessagingAppsCard';
import type {
  LinkedIdentity,
  PendingIdentity,
  RemoteBridge,
} from '@shared/core/switch-servers/switch-servers';

let container: HTMLDivElement | null = null;
let root: Root | null = null;

afterEach(async () => {
  if (root) await act(async () => root!.unmount());
  container?.remove();
  container = null;
  root = null;
});

async function render(node: React.ReactNode): Promise<HTMLDivElement> {
  container = document.createElement('div');
  document.body.appendChild(container);
  root = createRoot(container);
  await act(async () => root!.render(node));
  return container;
}

function bridge(patch: Partial<RemoteBridge> = {}): RemoteBridge {
  return {
    id: 'b-slack',
    type: 'slack',
    displayName: 'Slack Test',
    status: 'active',
    isDefault: false,
    homeUrl: null,
    channelCreationSupported: true,
    canCreateChannels: true,
    directorySearchSupported: true,
    attention: null,
    teamPlacementSupported: false,
    channelIdsRefused: null,
    receivesWebhooks: false,
    webhookUrl: null,
    ...patch,
  };
}

const IDENTITY: LinkedIdentity = {
  id: 'eu-1',
  bridgeId: 'b-slack',
  bridgeDisplayName: 'Slack Test',
  bridgeType: 'slack',
  externalUserId: 'U1',
  externalUsername: 'amaudruz.louis',
  verified: true,
};

const PENDING: PendingIdentity = {
  id: 'eu-1',
  bridgeId: 'b-slack',
  bridgeDisplayName: 'Slack Test',
  bridgeType: 'slack',
  externalUserId: 'U1',
  externalUsername: 'amaudruz.louis',
  requestedByName: null,
  codeExpiresAt: '2026-10-27T12:30:00Z',
};

function row(
  overrides: {
    workspaceId?: string | null;
    bridge?: RemoteBridge;
    identities?: LinkedIdentity[] | null;
    pending?: PendingIdentity[] | null;
    onReleased?: () => void;
    olderLinks?: { count: number; onRequireConfirmation: () => void } | null;
    isAdmin?: boolean;
    personal?: boolean;
    onConnectChat?: (() => void) | null;
    onDisconnect?: () => void;
  } = {}
) {
  return (
    <MessagingAppRow
      workspaceId={overrides.workspaceId === undefined ? 'ws-1' : overrides.workspaceId}
      serverId="srv-1"
      bridge={overrides.bridge ?? bridge()}
      identities={overrides.identities === undefined ? [] : overrides.identities}
      pending={overrides.pending === undefined ? [] : overrides.pending}
      currentUserId="u1"
      onReleased={overrides.onReleased ?? (() => {})}
      olderLinks={overrides.olderLinks ?? null}
      showBundledSignIn={false}
      isAdmin={overrides.isAdmin ?? false}
      personal={overrides.personal ?? false}
      savingChannelCreation={false}
      onToggleChannelCreation={() => {}}
      onConnectChat={overrides.onConnectChat ?? null}
      onReplaceToken={() => {}}
      onDisconnect={overrides.onDisconnect ?? (() => {})}
    />
  );
}

function buttonLabels(el: HTMLElement): string[] {
  return [...el.querySelectorAll('button')].map((b) => b.textContent?.trim() ?? '');
}

/** Opens the row's overflow menu and returns the menu item labels. Base UI
 * portals the menu outside the row, so this reads the whole document. */
async function openMenu(el: HTMLElement): Promise<string[]> {
  const trigger = el.querySelector<HTMLButtonElement>('button[aria-label$="actions"]');
  expect(trigger).not.toBeNull();
  await act(async () => trigger!.click());
  return [...document.querySelectorAll('[role="menuitem"], [role="menuitemcheckbox"]')].map(
    (i) => i.textContent?.trim() ?? ''
  );
}

describe('the identity column', () => {
  it('states the handle without hanging a control off it', async () => {
    // The control that was removed is the unlink cross, and its absence is
    // still the point. The handle now reads as a fact about the app; both
    // things you can do to it — change it, drop it — are in the menu, where
    // neither sits a mis-click from the other.
    const el = await render(row({ identities: [IDENTITY] }));

    expect(el.textContent).toContain('@amaudruz.louis');
    expect(buttonLabels(el).filter((l) => l.includes('amaudruz.louis'))).toEqual([]);
  });

  it('cannot unlink straight from the row', async () => {
    const el = await render(row({ identities: [IDENTITY] }));

    const unlinkOnRow = [...el.querySelectorAll('button')].filter((b) =>
      (b.getAttribute('aria-label') ?? '').startsWith('Unlink')
    );
    expect(unlinkOnRow).toEqual([]);
  });

  it('asks for the account when there is none', async () => {
    const el = await render(row({ identities: [] }));

    expect(buttonLabels(el)).toContain('Link');
  });

  it('says nothing at all until the claimed accounts have loaded', async () => {
    // "Not linked" and "not known yet" look identical, and inviting someone to
    // link an account they already have is the more confusing of the two.
    const el = await render(row({ identities: null }));

    expect(buttonLabels(el)).not.toContain('Link');
  });

  it('adds the sigil only when the platform has not already', async () => {
    const el = await render(
      row({ identities: [{ ...IDENTITY, externalUsername: '@already.sigilled' }] })
    );

    expect(el.textContent).toContain('@already.sigilled');
    expect(el.textContent).not.toContain('@@already.sigilled');
  });
});

/**
 * Links have to be confirmed with a code posted from the account (CHOO-3881).
 * One still waiting counts for nothing and must never read as linked; one made
 * before confirming works, and asks to be confirmed.
 */
describe('a link that needs its code', () => {
  it('shows a waiting link as waiting, with the code one click away', async () => {
    const el = await render(row({ identities: [], pending: [PENDING] }));

    expect(el.textContent).toContain('Waiting for confirmation');
    expect(el.textContent).not.toContain('No account linked');
    expect(buttonLabels(el)).not.toContain('Link');

    const show = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Show code');
    await act(async () => show!.click());
    expect(showModal).toHaveBeenCalledWith('claimIdentityModal', {
      workspaceId: 'ws-1',
      bridgeId: 'b-slack',
      confirm: { identityId: 'eu-1', externalUsername: 'amaudruz.louis', kind: 'pending' },
    });
  });

  it('cancels a waiting link from the menu, withdrawing only the request', async () => {
    releaseBridgeIdentity.mockReset();
    cancelIdentityLinkRequest.mockReset().mockResolvedValue({ kind: 'cancelled' });
    const onReleased = vi.fn();
    const el = await render(row({ identities: [], pending: [PENDING], onReleased }));

    expect(await openMenu(el)).toContain('Cancel link to @amaudruz.louis');
    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Cancel link to @amaudruz.louis'
    );
    await act(async () => item!.click());
    await settle();

    expect(cancelIdentityLinkRequest).toHaveBeenCalledWith({
      workspaceId: 'ws-1',
      bridgeId: 'b-slack',
      identityId: 'eu-1',
    });
    expect(releaseBridgeIdentity).not.toHaveBeenCalled();
    expect(onReleased).toHaveBeenCalledTimes(1);
  });

  it('says why a cancel did nothing, in the server’s words', async () => {
    cancelIdentityLinkRequest.mockReset().mockResolvedValue({
      kind: 'refused',
      message: 'Nothing is waiting to be confirmed.',
    });
    const el = await render(row({ identities: [], pending: [PENDING] }));

    await openMenu(el);
    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Cancel link to @amaudruz.louis'
    );
    await act(async () => item!.click());
    await settle();

    expect(el.textContent).toContain('Nothing is waiting to be confirmed.');
  });

  it('names the confirmed account when several are linked on the app', async () => {
    const el = await render(
      row({
        identities: [
          { ...IDENTITY, id: 'eu-old', externalUsername: 'old.handle', verified: false },
          IDENTITY,
        ],
      })
    );

    expect(el.textContent).toContain('@amaudruz.louis');
    expect(el.textContent).not.toContain('@old.handle');
    expect(el.textContent).not.toContain('Not confirmed');
    expect(buttonLabels(el)).not.toContain('Confirm');
  });

  it('marks a link made before confirming as not confirmed, and offers to confirm it', async () => {
    const el = await render(row({ identities: [{ ...IDENTITY, verified: false }] }));

    expect(el.textContent).toContain('@amaudruz.louis');
    expect(el.textContent).toContain('Not confirmed');

    const confirm = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Confirm');
    await act(async () => confirm!.click());
    expect(showModal).toHaveBeenCalledWith('claimIdentityModal', {
      workspaceId: 'ws-1',
      bridgeId: 'b-slack',
      confirm: { identityId: 'eu-1', externalUsername: 'amaudruz.louis', kind: 'unverified' },
    });
  });

  it('keeps Unlink, not Cancel, for a link made before confirming', async () => {
    // Cancelling drops the link outright, and this one works today.
    const el = await render(row({ identities: [{ ...IDENTITY, verified: false }] }));

    const labels = await openMenu(el);
    expect(labels).toContain('Unlink @amaudruz.louis');
    expect(labels.some((l) => l.startsWith('Cancel link'))).toBe(false);
  });

  it('shows a confirmed link as before, with nothing to confirm', async () => {
    const el = await render(row({ identities: [IDENTITY], pending: [PENDING] }));

    expect(el.textContent).not.toContain('Not confirmed');
    expect(el.textContent).not.toContain('Waiting for confirmation');
    expect(buttonLabels(el)).not.toContain('Confirm');
  });
});

describe('the app name and its badges', () => {
  it('keeps Default beside the name rather than adrift in the row', async () => {
    // With the name set to grow, the badge was pushed away from what it
    // qualifies and ended up floating mid-row against the identity column.
    const el = await render(row({ bridge: bridge({ isDefault: true }) }));

    const label = [...el.querySelectorAll('span')].find(
      (s) => s.textContent?.trim() === 'Slack Test'
    );
    expect(label).toBeDefined();
    expect(label!.parentElement!.textContent).toContain('Default');
  });

  it('shows a bridge that is down, since a new room cannot use it', async () => {
    const el = await render(row({ bridge: bridge({ status: 'error' }) }));

    expect(el.textContent).toContain('error');
  });
});

describe('requiring confirmation for older links', () => {
  it('is offered with how many there are, and opens the confirmation', async () => {
    const onRequireConfirmation = vi.fn();
    const el = await render(
      row({ isAdmin: true, olderLinks: { count: 3, onRequireConfirmation } })
    );

    expect(await openMenu(el)).toContain('Require confirmation for older links (3)…');
    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Require confirmation for older links (3)…'
    );
    await act(async () => item!.click());

    expect(onRequireConfirmation).toHaveBeenCalledTimes(1);
  });

  it('is not offered when the card has nothing to offer', async () => {
    const el = await render(row({ isAdmin: true, olderLinks: null }));

    const labels = await openMenu(el);
    expect(labels.some((l) => l.startsWith('Require confirmation'))).toBe(false);
  });
});

describe('the row menu', () => {
  it('offers the webhook address of a connection that receives events on one', async () => {
    const el = await render(
      row({
        bridge: bridge({
          receivesWebhooks: true,
          webhookUrl: 'https://switch.example/messaging/bridges/b-1/events',
        }),
      })
    );

    expect(await openMenu(el)).toContain('Copy webhook address');
  });

  it('says what is missing when the server has no public address to give', async () => {
    const el = await render(row({ bridge: bridge({ receivesWebhooks: true, webhookUrl: null }) }));

    await openMenu(el);
    expect(document.body.textContent).toContain('MESSAGING_PUBLIC_URL');
  });

  it('offers no webhook address for a connection that dials out', async () => {
    const el = await render(row());

    expect(await openMenu(el)).not.toContain('Copy webhook address');
  });

  it('is where unlinking lives, and only when there is a link to undo', async () => {
    const el = await render(row({ identities: [IDENTITY] }));

    expect(await openMenu(el)).toContain('Unlink @amaudruz.louis');
  });

  it('offers no unlink when nothing is linked', async () => {
    const el = await render(row({ identities: [] }));

    expect(await openMenu(el)).not.toContain('Unlink @amaudruz.louis');
  });

  it('offers disconnecting the app to an admin', async () => {
    const el = await render(row({ isAdmin: true }));

    expect(await openMenu(el)).toContain('Disconnect app…');
  });

  it('does not offer it to anyone else — the endpoint would refuse them', async () => {
    const el = await render(row({ isAdmin: false }));

    expect(await openMenu(el)).not.toContain('Disconnect app…');
  });

  it('keeps the workspace’s settings out of Settings, where only your own account is shown', async () => {
    const el = await render(
      row({
        personal: true,
        identities: [IDENTITY],
        bridge: bridge({
          receivesWebhooks: true,
          webhookUrl: 'https://switch.example/messaging/bridges/b-1/events',
        }),
      })
    );

    const items = await openMenu(el);
    expect(items).toContain('Unlink @amaudruz.louis');
    expect(items.some((item) => item.startsWith('Create channels'))).toBe(false);
    expect(items).not.toContain('Copy webhook address');
    expect(items).not.toContain('Disconnect app…');
  });

  it('opens on a platform that cannot create channels at all', async () => {
    // Telegram. The explanation used to be a menu *label*, which Base UI
    // requires to sit inside a group — so opening this menu threw and took the
    // page down with it. Every other case here has a platform that supports
    // channel creation, which is how it got through. The toggle has since moved
    // out to a column of its own; the menu must still open.
    const el = await render(
      row({ bridge: bridge({ channelCreationSupported: false, canCreateChannels: false }) })
    );

    expect(await openMenu(el)).toContain('Link my account…');
  });

  it('asks before disconnecting rather than doing it on the click', async () => {
    // The server deletes every room on the bridge first, so the menu item may
    // only ever open a confirmation.
    const onDisconnect = vi.fn();
    const el = await render(row({ isAdmin: true, onDisconnect }));
    await openMenu(el);

    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Disconnect app…'
    );
    await act(async () => item!.click());

    expect(onDisconnect).toHaveBeenCalledTimes(1);
  });

  it('offers connecting a chat, to a member too, where the card allows it', async () => {
    const onConnectChat = vi.fn();
    const telegram = bridge({ id: 'b-tg', type: 'telegram', displayName: 'Telegram' });
    const el = await render(row({ bridge: telegram, isAdmin: false, onConnectChat }));
    expect(await openMenu(el)).toContain('Add to Telegram…');

    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Add to Telegram…'
    );
    await act(async () => item!.click());

    expect(onConnectChat).toHaveBeenCalledTimes(1);
  });

  it('offers no chat to connect otherwise', async () => {
    const el = await render(row({ isAdmin: true }));

    expect(await openMenu(el)).not.toContain('Add to Slack…');
  });
});

/**
 * Whether Switch may open channels on an app.
 *
 * It has been in both places. CHOO-2158 pulled it onto the row as a column, so
 * it could be read down the page; the card is a list rather than a table of
 * controls now, and it is back in the menu — read far less often than the app
 * name and the account under it, and a switch in a list of names reads as the
 * loudest thing there.
 *
 * What it has to say did not change with either move, and that is what these
 * are for.
 */
describe('channel creation', () => {
  /** Opens the row menu and returns the item with this label. Base UI portals
   * the menu, so this reads the whole document. */
  async function menuItem(el: HTMLElement, label: string): Promise<HTMLElement> {
    await openMenu(el);
    const found = [
      ...document.querySelectorAll<HTMLElement>('[role="menuitem"], [role="menuitemcheckbox"]'),
    ].find((i) => i.textContent?.trim() === label);
    expect(found, `no menu item labelled ${label}`).toBeDefined();
    return found!;
  }

  it('is in the menu, not on the row', async () => {
    const el = await render(row({ isAdmin: true }));

    expect(el.querySelector('[role="switch"]')).toBeNull();
    expect(await openMenu(el)).toContain('Create channels on Slack');
  });

  it('shows the current answer', async () => {
    const el = await render(row({ isAdmin: true }));

    expect((await menuItem(el, 'Create channels on Slack')).getAttribute('aria-checked')).toBe(
      'true'
    );
  });

  it('says a platform cannot create channels rather than just showing it off', async () => {
    // An unticked box reads as "switched off", which is a different claim from
    // "this platform has no such thing". Telegram is the case: it never gets a
    // box at all, only a line saying so.
    const el = await render(
      row({ bridge: bridge({ channelCreationSupported: false, canCreateChannels: false }) })
    );

    const labels = await openMenu(el);
    expect(labels).toContain('Channels not supported on Slack');
    expect(document.querySelector('[role="menuitemcheckbox"]')).toBeNull();
  });

  it('leaves it alone for a non-admin', async () => {
    const el = await render(row({ isAdmin: false }));

    expect(
      (await menuItem(el, 'Create channels on Slack')).getAttribute('data-disabled')
    ).not.toBeNull();
  });

  it('lets an admin move it', async () => {
    const el = await render(row({ isAdmin: true }));

    expect(
      (await menuItem(el, 'Create channels on Slack')).getAttribute('data-disabled')
    ).toBeNull();
  });
});

/** A promise the test resolves on its own schedule, to pin a request mid-flight. */
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
  let resolve!: (value: T) => void;
  const promise = new Promise<T>((r) => {
    resolve = r;
  });
  return { promise, resolve };
}

async function settle(): Promise<void> {
  for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());
}

/**
 * The generic attention warning, and "Approve again" on top of it for the
 * distributed Teams app alone.
 *
 * "Approve again" re-runs the same install flow a first approval does, which
 * only makes sense for a connection that came from it — gating it on
 * `teamPlacementSupported` is what keeps it off a Teams bridge registered with
 * pasted-in credentials, and off every other platform.
 */
describe('the attention warning', () => {
  beforeEach(() => {
    beginMessagingAppInstall.mockReset().mockResolvedValue('https://teams.example/consent');
    openExternalUrl.mockReset().mockResolvedValue(true);
  });

  it('shows the server’s own sentence when a bridge has something wrong with it', async () => {
    const el = await render(row({ bridge: bridge({ attention: 'Approval was withdrawn.' }) }));

    expect(el.textContent).toContain('Approval was withdrawn.');
  });

  it('shows nothing extra when there is nothing to warn about', async () => {
    const el = await render(row({ bridge: bridge({ attention: null }) }));

    expect(el.textContent).not.toContain('Approve again');
  });

  it('offers Approve again to an admin on a team-placement connection', async () => {
    const el = await render(
      row({
        isAdmin: true,
        bridge: bridge({ attention: 'Approval was withdrawn.', teamPlacementSupported: true }),
      })
    );

    expect(buttonLabels(el)).toContain('Approve again');
  });

  it('does not offer it to a non-admin, even on a team-placement connection', async () => {
    const el = await render(
      row({
        isAdmin: false,
        bridge: bridge({ attention: 'Approval was withdrawn.', teamPlacementSupported: true }),
      })
    );

    expect(buttonLabels(el)).not.toContain('Approve again');
  });

  it('does not offer it on a connection that does not support team placement', async () => {
    const el = await render(
      row({
        isAdmin: true,
        bridge: bridge({ attention: 'Approval was withdrawn.', teamPlacementSupported: false }),
      })
    );

    expect(buttonLabels(el)).not.toContain('Approve again');
  });

  it('starts the install and opens the consent page on click', async () => {
    const el = await render(
      row({
        isAdmin: true,
        bridge: bridge({
          type: 'teams',
          attention: 'Approval was withdrawn.',
          teamPlacementSupported: true,
        }),
      })
    );

    const approve = [...el.querySelectorAll('button')].find(
      (b) => b.textContent?.trim() === 'Approve again'
    );
    await act(async () => approve!.click());
    await settle();

    expect(beginMessagingAppInstall).toHaveBeenCalledWith({
      workspaceId: 'ws-1',
      platform: 'teams',
    });
    expect(openExternalUrl).toHaveBeenCalledWith(
      'https://teams.example/consent',
      'Could not open Microsoft Teams'
    );
    expect(el.textContent).toContain('Approve again in the browser window');
  });

  it('forgets an earlier re-approval once a different warning replaces it', async () => {
    const withdrawn = bridge({
      type: 'teams',
      attention: 'Approval was withdrawn.',
      teamPlacementSupported: true,
    });
    const el = await render(row({ isAdmin: true, bridge: withdrawn }));
    const approve = [...el.querySelectorAll('button')].find(
      (b) => b.textContent?.trim() === 'Approve again'
    );
    await act(async () => approve!.click());
    await settle();
    expect(el.textContent).toContain('Approve again in the browser window');

    await act(async () =>
      root!.render(
        row({
          isAdmin: true,
          bridge: { ...withdrawn, attention: 'The app was blocked by your Teams admin.' },
        })
      )
    );

    expect(el.textContent).toContain('The app was blocked by your Teams admin.');
    expect(el.textContent).not.toContain('Approve again in the browser window');
    expect(buttonLabels(el)).toContain('Approve again');
  });

  it('shows why re-approving could not start, rather than leaving it unexplained', async () => {
    beginMessagingAppInstall.mockRejectedValue(new Error('install refused'));
    const el = await render(
      row({
        isAdmin: true,
        bridge: bridge({
          type: 'teams',
          attention: 'Approval was withdrawn.',
          teamPlacementSupported: true,
        }),
      })
    );

    const approve = [...el.querySelectorAll('button')].find(
      (b) => b.textContent?.trim() === 'Approve again'
    );
    await act(async () => approve!.click());
    await settle();

    expect(el.textContent).toContain('Could not start re-approving Microsoft Teams');
    expect(openExternalUrl).not.toHaveBeenCalled();
  });

  it('disables the button while the install is starting', async () => {
    const { promise, resolve } = deferred<string>();
    beginMessagingAppInstall.mockReturnValue(promise);
    const el = await render(
      row({
        isAdmin: true,
        bridge: bridge({
          type: 'teams',
          attention: 'Approval was withdrawn.',
          teamPlacementSupported: true,
        }),
      })
    );

    const approve = [...el.querySelectorAll('button')].find(
      (b) => b.textContent?.trim() === 'Approve again'
    ) as HTMLButtonElement;
    await act(async () => approve.click());
    await settle();

    expect(
      [...el.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'Opening…')?.disabled
    ).toBe(true);

    await act(async () => resolve('https://teams.example/consent'));
    await settle();
  });
});

describe('the Teams placement button', () => {
  it('is offered to an admin on a connection that supports team placement', async () => {
    const el = await render(
      row({ isAdmin: true, bridge: bridge({ teamPlacementSupported: true }) })
    );

    expect(await openMenu(el)).toContain('Manage Microsoft Teams…');
  });

  it('is withheld from a non-admin', async () => {
    const el = await render(
      row({ isAdmin: false, bridge: bridge({ teamPlacementSupported: true }) })
    );

    expect(await openMenu(el)).not.toContain('Manage Microsoft Teams…');
  });

  it('is withheld on a connection that does not support team placement', async () => {
    const el = await render(
      row({ isAdmin: true, bridge: bridge({ teamPlacementSupported: false }) })
    );

    expect(await openMenu(el)).not.toContain('Manage Microsoft Teams…');
  });

  it('opens the Teams placement modal for this bridge', async () => {
    const el = await render(
      row({
        isAdmin: true,
        bridge: bridge({
          id: 'b-teams',
          displayName: 'Contoso Teams',
          teamPlacementSupported: true,
        }),
      })
    );
    await openMenu(el);

    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Manage Microsoft Teams…'
    );
    await act(async () => item!.click());

    expect(showModal).toHaveBeenCalledWith('teamsPlacementModal', {
      workspaceId: 'ws-1',
      bridgeId: 'b-teams',
      bridgeDisplayName: 'Contoso Teams',
    });
  });

  it('does nothing while the workspace has not resolved yet', async () => {
    const el = await render(
      row({ workspaceId: null, isAdmin: true, bridge: bridge({ teamPlacementSupported: true }) })
    );
    await openMenu(el);

    const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
      (i) => i.textContent?.trim() === 'Manage Microsoft Teams…'
    );
    await act(async () => item!.click());

    expect(showModal).not.toHaveBeenCalled();
  });
});