Skip to content

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

15.9 KB
Raw Blame
/**
 * Choosing a workspace on a server you have just signed in to.
 *
 * The interesting behaviour is not the list — it is what the pages do with the
 * three answers the server can give. None, one and several each lead somewhere
 * different, being asked and failing is not the same as being asked and told
 * "none", and the sections the server cannot answer for at all are absent
 * rather than drawn empty.
 */
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const resolveWorkspaces = vi.hoisted(() => vi.fn());
const createWorkspace = vi.hoisted(() => vi.fn());
const setActiveWorkspace = vi.hoisted(() => vi.fn());
const listPendingInvitations = vi.hoisted(() => vi.fn());
const acceptPendingInvitation = vi.hoisted(() => vi.fn());
const listJoinableWorkspaces = vi.hoisted(() => vi.fn());
const joinByDomain = vi.hoisted(() => vi.fn());

vi.hoisted(() => {
  window.electronAPI ??= {
    invoke: () => Promise.resolve(undefined),
    eventOn: () => () => {},
    eventSend: () => {},
  } as unknown as typeof window.electronAPI;
});

vi.mock('@renderer/lib/ipc', () => ({
  rpc: {
    switchServers: {
      resolveWorkspaces,
      listPendingInvitations,
      listJoinableWorkspaces,
      switchCloud: () => Promise.resolve(null),
    },
    embeddedController: { precheckProviders: () => {} },
  },
  events: { on: () => () => {}, emit: () => {} },
}));

vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
  workspacesStore: {
    setActive: setActiveWorkspace,
    create: createWorkspace,
    acceptPendingInvitation,
    joinByDomain,
    idOnServerInScope: () => 'ws-1',
  },
}));

const SERVER = vi.hoisted(() => ({
  id: 'srv-1',
  name: 'switch.example.com',
  url: 'https://switch.example.com:8000',
  dashboardUrl: 'https://switch.example.com',
}));

vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
  switchServersStore: {
    setActive: vi.fn(),
    errorText: null,
    serverById: (id: string | null) => (id === SERVER.id ? SERVER : null),
    // Stepping back off the picker draws the sign-in page, which reads these.
    ensureAuthConfig: () => Promise.resolve(),
    authConfigFor: () => ({
      passwordLoginEnabled: true,
      oidcEnabled: false,
      oidcProviderLabel: null,
      oidcLoginOptions: [],
      oidcBrowserHandoff: false,
    }),
    authConfigCheckFailed: () => false,
    authConfigChecking: () => false,
    passwordLogin: () => Promise.resolve(true),
    oidcLogin: () => Promise.resolve(true),
  },
}));

// The page after the workspace, and not what these tests are about — stubbed
// so reaching it is a fact the test can assert without dragging in this
// computer's setup behind it.
vi.mock('@renderer/features/switch-buddy/buddy-step', () => ({
  BuddyStep: () => <div>Meet switch-buddy</div>,
}));

vi.mock('@renderer/lib/layout/navigation-provider', () => ({
  useNavigate: () => ({ navigate: vi.fn() }),
}));

vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));

import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';
import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';

function workspace(id: string, name: string) {
  return {
    id,
    serverId: 'srv-1',
    name,
    tenantId: `tenant-${id}`,
    slug: name.toLowerCase(),
    role: 'member' as const,
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
  };
}

function invitation(id: string, workspaceName: string) {
  return {
    id,
    tenantId: `tenant-${id}`,
    workspaceName,
    role: 'member' as const,
    expiresAt: '2026-12-01T00:00:00Z',
    invitedBy: 'Ada Lovelace',
  };
}

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

beforeEach(() => {
  resolveWorkspaces.mockReset();
  createWorkspace.mockReset();
  setActiveWorkspace.mockReset().mockResolvedValue(undefined);
  listPendingInvitations.mockReset().mockResolvedValue({ kind: 'listed', invitations: [] });
  acceptPendingInvitation.mockReset();
  listJoinableWorkspaces.mockReset().mockResolvedValue({ kind: 'listed', workspaces: [] });
  joinByDomain.mockReset();
  onboardingStore.reset();
});

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

/** The flow, opened at the page that follows a successful sign-in. */
async function renderAtPickWorkspace(): Promise<HTMLDivElement> {
  onboardingStore.connected(SERVER as never, 'external', false);
  onboardingStore.goTo('pickWorkspace');

  container = document.createElement('div');
  document.body.appendChild(container);
  root = createRoot(container);
  const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
  await act(async () =>
    root!.render(
      <QueryClientProvider client={client}>
        <OnboardingFlow />
      </QueryClientProvider>
    )
  );
  await settle();
  return container;
}

function deferred<T>() {
  let resolve!: (value: T) => void;
  const promise = new Promise<T>((res) => {
    resolve = res;
  });
  return { promise, resolve };
}

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

async function click(el: HTMLElement, text: string): Promise<void> {
  const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
    b.textContent?.includes(text)
  );
  expect(found, `nothing to click named ${text}`).toBeDefined();
  await act(async () => found!.click());
  await settle();
}

async function typeName(el: HTMLElement, value: string): Promise<void> {
  const input = el.querySelector('input');
  expect(input, 'no name field').not.toBeNull();
  const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
  await act(async () => {
    setter.call(input, value);
    input!.dispatchEvent(new Event('input', { bubbles: true }));
  });
}

describe('picking a workspace after signing in', () => {
  it('lists the workspaces the account is a member of', async () => {
    resolveWorkspaces.mockResolvedValue([
      workspace('ws-1', 'Acme'),
      workspace('ws-2', 'Skunkworks'),
    ]);

    const el = await renderAtPickWorkspace();

    expect(resolveWorkspaces).toHaveBeenCalledWith('srv-1');
    expect(el.textContent).toContain('Choose your workspace');
    expect(el.textContent).toContain('Acme');
    expect(el.textContent).toContain('Skunkworks');
    expect(el.textContent).toContain('Create your own workspace');
  });

  it('leaves out the invite and join rows on a server too old to list them', async () => {
    // It cannot say whether anyone invited you or which workspaces are open to
    // your domain, so an empty section would be a claim it never made.
    resolveWorkspaces.mockResolvedValue([
      workspace('ws-1', 'Acme'),
      workspace('ws-2', 'Skunkworks'),
    ]);
    listPendingInvitations.mockResolvedValue({ kind: 'unsupported' });
    listJoinableWorkspaces.mockResolvedValue({ kind: 'unsupported' });

    const el = await renderAtPickWorkspace();

    expect(el.textContent).not.toContain('Join');
    expect(el.textContent).not.toContain('Accept');
    expect(el.textContent).not.toContain('invited you');
    expect(el.textContent).not.toContain('domain');
  });

  it('offers invitations to your address beside your memberships', async () => {
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);
    listPendingInvitations.mockResolvedValue({
      kind: 'listed',
      invitations: [invitation('inv-1', 'Skunkworks')],
    });

    const el = await renderAtPickWorkspace();

    // One membership is no longer the only way forward, so nothing is chosen.
    expect(setActiveWorkspace).not.toHaveBeenCalled();
    expect(onboardingStore.page).toBe('pickWorkspace');
    const rows = el.querySelectorAll('[data-testid="pending-invitation-row"]');
    expect(rows).toHaveLength(1);
    expect(rows[0]!.textContent).toContain('Skunkworks');
    expect(rows[0]!.textContent).toContain('Ada Lovelace invited you as member');
    expect(rows[0]!.textContent).toContain('Invited');
    expect(el.textContent).toContain('You’re a member of these, or can join them.');
  });

  it('joins the workspace an invitation is for and opens it', async () => {
    resolveWorkspaces.mockResolvedValue([]);
    listPendingInvitations.mockResolvedValue({
      kind: 'listed',
      invitations: [invitation('inv-1', 'Skunkworks')],
    });
    acceptPendingInvitation.mockResolvedValue(workspace('ws-9', 'Skunkworks'));

    const el = await renderAtPickWorkspace();
    // With an invitation waiting, having no memberships is not a reason to
    // skip ahead to creating one.
    expect(onboardingStore.page).toBe('pickWorkspace');
    await click(el, 'Accept');

    expect(acceptPendingInvitation).toHaveBeenCalledWith(
      'srv-1',
      expect.objectContaining({ id: 'inv-1' })
    );
    expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');
    expect(onboardingStore.page).toBe('meetBuddy');
  });

  it('stays on the picker with the error when accepting fails', async () => {
    resolveWorkspaces.mockResolvedValue([]);
    listPendingInvitations.mockResolvedValue({
      kind: 'listed',
      invitations: [invitation('inv-1', 'Skunkworks')],
    });
    acceptPendingInvitation.mockRejectedValue(new Error('This invitation has been revoked'));

    const el = await renderAtPickWorkspace();
    await click(el, 'Accept');

    expect(onboardingStore.page).toBe('pickWorkspace');
    expect(el.textContent).toContain('This invitation has been revoked');
    expect(setActiveWorkspace).not.toHaveBeenCalled();
  });

  it('does not choose for you when the invitation check failed', async () => {
    // Skipping ahead on one membership would hide an invitation the page could
    // not rule out.
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);
    listPendingInvitations.mockRejectedValue(new Error('gateway unreachable'));

    const el = await renderAtPickWorkspace();

    expect(setActiveWorkspace).not.toHaveBeenCalled();
    expect(el.textContent).toContain('gateway unreachable');
    expect([...el.querySelectorAll('button')].map((b) => b.textContent)).toContain('Retry');
  });

  it('offers workspaces open to your e-mail domain, and joins one', async () => {
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);
    listJoinableWorkspaces.mockResolvedValue({
      kind: 'listed',
      workspaces: [{ tenantId: 't-9', workspaceName: 'Skunkworks', domain: 'acme.example' }],
    });
    joinByDomain.mockResolvedValue(workspace('ws-9', 'Skunkworks'));

    const el = await renderAtPickWorkspace();

    expect(setActiveWorkspace).not.toHaveBeenCalled();
    const rows = el.querySelectorAll('[data-testid="joinable-workspace-row"]');
    expect(rows).toHaveLength(1);
    expect(rows[0]!.textContent).toContain('Open to anyone at acme.example');
    await click(el, 'Join');

    expect(joinByDomain).toHaveBeenCalledWith(
      'srv-1',
      expect.objectContaining({ tenantId: 't-9' })
    );
    expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');
    expect(onboardingStore.page).toBe('meetBuddy');
  });

  it('does not choose for you when the domain check failed', async () => {
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);
    listJoinableWorkspaces.mockRejectedValue(new Error('gateway unreachable'));

    const el = await renderAtPickWorkspace();

    expect(setActiveWorkspace).not.toHaveBeenCalled();
    expect(el.textContent).toContain('gateway unreachable');
  });

  it('does not ask a question with one answer', async () => {
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);

    const el = await renderAtPickWorkspace();

    expect(setActiveWorkspace).toHaveBeenCalledWith('ws-1');
    expect(onboardingStore.page).toBe('meetBuddy');
    expect(el.textContent).toContain('Meet switch-buddy');
  });

  it('goes straight to creating one when the account is in none', async () => {
    resolveWorkspaces.mockResolvedValue([]);

    const el = await renderAtPickWorkspace();

    expect(onboardingStore.page).toBe('createWorkspace');
    expect(el.textContent).toContain('Create your workspace');
    // Nothing behind it: the picker had no list to return to.
    expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain('Back');
  });

  it('goes back by a button and not only by a chevron', async () => {
    // The full-window pages have no step pager: Back is the way back.
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);

    const el = await renderAtPickWorkspace();
    await click(el, 'Back');

    expect(onboardingStore.page).toBe('signIn');
  });

  /**
   * Leaving while a workspace is being entered lands the user two pages on when
   * it resolves — back on the sign-in, and then thrown forward out of it.
   */
  it('holds the way back shut while a workspace is being opened', async () => {
    resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);
    const opening = deferred<void>();
    setActiveWorkspace.mockReturnValue(opening.promise);

    const el = await renderAtPickWorkspace();
    await click(el, 'Acme');

    const back = [...el.querySelectorAll<HTMLButtonElement>('button')].find(
      (b) => b.textContent?.trim() === 'Back'
    )!;
    expect(back.disabled).toBe(true);

    opening.resolve();
    await settle();
  });

  it('says the server could not be asked, rather than treating it as no workspaces', async () => {
    // Conflating the two would offer to create a second workspace to someone
    // who already has one.
    resolveWorkspaces.mockRejectedValue(new Error('gateway unreachable'));

    const el = await renderAtPickWorkspace();

    expect(el.textContent).toContain('switch.example.com');
    expect(el.textContent).toContain('Retry');
    expect(onboardingStore.page).toBe('pickWorkspace');
    expect(el.textContent).not.toContain('Create your workspace');
  });

  it('creates a workspace and carries on into it', async () => {
    resolveWorkspaces.mockResolvedValue([]);
    createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));

    const el = await renderAtPickWorkspace();
    await typeName(el, '  Acme  ');
    await click(el, 'Create workspace');

    expect(createWorkspace).toHaveBeenCalledWith('srv-1', 'Acme');
    expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');
    expect(onboardingStore.page).toBe('meetBuddy');
  });

  /**
   * The workspace exists on the server from the moment Create returns. Asking
   * again would send back a name it has just taken and earn a conflict that
   * reads as the name being refused — and on this page, reached because the
   * account is in no workspace at all, there is no Back either.
   */
  it('offers to open the workspace it already made rather than creating it twice', async () => {
    resolveWorkspaces.mockResolvedValue([]);
    createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));
    setActiveWorkspace.mockRejectedValueOnce(new Error('could not switch'));

    const el = await renderAtPickWorkspace();
    await typeName(el, 'Acme');
    await click(el, 'Create workspace');

    expect(el.textContent).toContain('could not be moved into it');

    setActiveWorkspace.mockResolvedValue(undefined);
    await click(el, 'Open workspace');

    expect(createWorkspace).toHaveBeenCalledTimes(1);
    expect(onboardingStore.page).toBe('meetBuddy');
  });

  it('keeps the form and says why when the name is refused', async () => {
    resolveWorkspaces.mockResolvedValue([]);
    createWorkspace.mockRejectedValue(new Error('That name is already taken.'));

    const el = await renderAtPickWorkspace();
    await typeName(el, 'Acme');
    await click(el, 'Create workspace');

    expect(el.textContent).toContain('already taken');
    expect(onboardingStore.page).toBe('createWorkspace');
  });
});