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.

14.7 KB
Raw Blame
import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { AuthIntent } from '../context/auth-context';
import type { FakeAuthWorld } from '../tests/fake-auth-context';
import { renderWithFakeAuth } from '../tests/render';
import { AuthView, type SignupJourneySlots } from './auth-view';

afterEach(() => {
  cleanup();
  vi.useRealTimers();
});

function setup(
  options: {
    intent?: AuthIntent;
    world?: Partial<FakeAuthWorld>;
    initialEmail?: string;
    autoStart?: boolean;
    token?: string;
    signupJourney?: (slots: SignupJourneySlots) => ReturnType<typeof Journey>;
  } = {}
) {
  const verified = vi.fn();
  const signIn = vi.fn();
  const { fake } = renderWithFakeAuth(
    () => (
      <AuthView
        intent={options.intent ?? 'login'}
        showApple={false}
        compact={false}
        initialEmail={options.initialEmail}
        autoStart={options.autoStart}
        token={options.token}
        onVerified={verified}
        onSignIn={signIn}
        signupJourney={options.signupJourney}
        signedIn={(user) => (
          <p data-testid="signed-in">
            {user().email} {user().tutorialComplete ? 'returning' : 'new'}
          </p>
        )}
      />
    ),
    options.world
  );
  return { fake, verified, signIn };
}

/** As `setup`, but the session code can arrive after the view has mounted. */
function setupWithTokenSignal(
  options: {
    world?: Partial<FakeAuthWorld>;
    /** Replaces the fake backend's redemption, e.g. to make it reject. */
    redeem?: (token: string) => Promise<boolean>;
  } = {}
) {
  const [token, setToken] = createSignal<string | undefined>(undefined);
  const { fake } = renderWithFakeAuth(
    () => (
      <AuthView
        intent="login"
        showApple={false}
        compact={false}
        token={token()}
        signedIn={(user) => (
          <p data-testid="signed-in">
            {user().email} {user().tutorialComplete ? 'returning' : 'new'}
          </p>
        )}
      />
    ),
    options.world
  );
  // Safe after render: the effect's first run sees no code and returns early,
  // so nothing redeems until setToken.
  if (options.redeem) fake.context.redeemSessionToken = options.redeem;
  return { fake, setToken };
}

const click = (name: string | RegExp) =>
  fireEvent.click(screen.getByRole('button', { name }));
// Stepper swaps steps on the next frame, so each step is awaited.
const typeEmail = async (value: string) =>
  fireEvent.input(await screen.findByPlaceholderText('[email protected]'), {
    target: { value },
  });
const typeCode = async (value: string) =>
  fireEvent.input(await screen.findByLabelText(/code/i), {
    target: { value },
  });

describe('agent signup', () => {
  it('asks for an agent account by email', async () => {
    const { fake } = setup({ intent: 'agent-signup' });

    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');

    expect(fake.calls()).toContain('sendAgentCode:[email protected]');
  });

  it('asks for an agent account through Google', async () => {
    const { fake } = setup({ intent: 'agent-signup' });

    click('Continue with Google');

    await waitFor(() =>
      expect(fake.calls()).toContain('sso:google:agent-signup')
    );
  });
});

describe('email sign-in', () => {
  it('updates a signed-in viewer without remounting their workspace on session refresh', () => {
    const { fake } = setup({
      world: {
        user: {
          id: 'macro|[email protected]',
          email: '[email protected]',
          tutorialComplete: false,
          isAgent: false,
        },
      },
    });
    const workspace = screen.getByTestId('signed-in');

    fake.update((draft) => {
      if (draft.user) draft.user.tutorialComplete = true;
    });

    expect(screen.getByTestId('signed-in')).toBe(workspace);
    expect(workspace.textContent).toBe('[email protected] returning');

    fake.update((draft) => {
      draft.user = {
        id: 'macro|[email protected]',
        email: '[email protected]',
        tutorialComplete: false,
        isAgent: false,
      };
    });
    expect(screen.getByTestId('signed-in')).not.toBe(workspace);
    expect(screen.getByTestId('signed-in').textContent).toBe(
      '[email protected] new'
    );
  });

  it('sends a code, verifies it, and hands off to the signed-in view', async () => {
    const { fake, verified } = setup();
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');
    await typeCode('424242');
    await screen.findByTestId('signed-in');
    expect(screen.getByTestId('signed-in').textContent).toBe(
      '[email protected] returning'
    );
    expect(fake.calls()).toEqual(
      expect.arrayContaining([
        'pageView:login',
        'sendCode:[email protected]',
        'verify:[email protected]:424242',
        'completeLogin',
        'identify:macro|[email protected]',
      ])
    );
    expect(fake.events()).toContainEqual({
      event: 'login',
      data: { method: 'email' },
    });
    expect(verified).toHaveBeenCalledOnce();
  });

  it('keeps the verify step open on a wrong code', async () => {
    setup();
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');
    await typeCode('000000');
    await screen.findByText('Invalid code.');
    await typeCode('424242');
    await screen.findByTestId('signed-in');
  });

  // Every check counts against the auth service's per-address attempt limit.
  it('checks each entered code once, even when Verify is tapped after a miss', async () => {
    const { fake } = setup();
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');
    for (const wrong of ['000000', '111111', '222222']) {
      await typeCode(wrong);
      await screen.findByText('Invalid code.');
      expect(screen.getByLabelText(/code/i)).toHaveProperty('value', '');
      click(/^Verify/);
    }
    await typeCode('424242');
    await screen.findByTestId('signed-in');
    expect(fake.calls().filter((call) => call.startsWith('verify:'))).toEqual([
      'verify:[email protected]:000000',
      'verify:[email protected]:111111',
      'verify:[email protected]:222222',
      'verify:[email protected]:424242',
    ]);
  });

  it('says to wait when code checks are rate-limited, and keeps the code to retry', async () => {
    const { fake } = setup({
      world: { codeAttempts: { '[email protected]': 5 } },
    });
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');
    await typeCode('424242');
    await screen.findByText(
      'Too many attempts. Wait a minute, then try again.'
    );
    expect(screen.queryByText('Invalid code.')).toBeNull();
    expect(screen.getByLabelText(/code/i)).toHaveProperty('value', '424242');

    fake.update((draft) => {
      draft.codeAttempts = {};
    });
    click(/^Verify/);
    await screen.findByTestId('signed-in');
  });

  it('asks for a password only for password accounts', async () => {
    setup({ world: { passwordAccounts: { '[email protected]': 'hunter2' } } });
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    const password = await screen.findByPlaceholderText('Password');
    fireEvent.input(password, { target: { value: 'wrong' } });
    click('Continue');
    await screen.findByText(/Check your email and password/);
    fireEvent.input(password, { target: { value: 'hunter2' } });
    click('Continue');
    await screen.findByTestId('signed-in');
  });

  it('lets the user resend after the countdown', async () => {
    vi.useFakeTimers({ shouldAdvanceTime: true });
    const { fake } = setup();
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');
    expect(
      screen.getByRole('button', { name: /Resend \(45\)/ })
    ).toHaveProperty('disabled', true);
    await vi.advanceTimersByTimeAsync(45_000);
    click('Resend');
    await waitFor(() =>
      expect(
        fake.calls().filter((c) => c === 'sendCode:[email protected]')
      ).toHaveLength(2)
    );
  });

  it('goes back from verify to the email step, and from there to the picker', async () => {
    setup();
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('[email protected]');
    click('Change email');
    await screen.findByPlaceholderText('[email protected]');
    click('Back to sign in');
    await screen.findByRole('button', { name: 'Continue with Google' });
  });

  it('signs straight in from a dev persona link when the backend returns the code', async () => {
    setup({
      initialEmail: '[email protected]',
      autoStart: true,
      world: { autoCode: true },
    });
    await screen.findByTestId('signed-in');
  });

  it('shows the server’s reason when sending fails', async () => {
    setup({ world: { failures: { sendCode: 'Email is not allowed.' } } });
    click('Continue with email');
    await typeEmail('[email protected]');
    click('Continue');
    await screen.findByText('Email is not allowed.');
  });
});

describe('single sign-on', () => {
  it('starts Google with the page’s intent', async () => {
    const { fake } = setup({ intent: 'login' });
    click('Continue with Google');
    await screen.findByTestId('signed-in');
    expect(fake.calls()).toContain('sso:google:login');
  });

  it('records the email choice as a sign-up click on /signup', () => {
    const { fake } = setup({ intent: 'signup' });
    click('Continue with email');
    expect(fake.events()).toContainEqual({
      event: 'sign_up_click',
      data: { method: 'email' },
    });
  });

  it('redeems the session code an SSO return put on the URL', async () => {
    setup({
      token: 'tok-1',
      world: { sessionTokens: { 'tok-1': '[email protected]' } },
    });
    await screen.findByText('[email protected] new');
  });

  // The desktop app is already parked on the signed-out route when the
  // `macro://` auth callback comes back, so the session code arrives as a
  // query-only navigation that never remounts this view.
  it('redeems a session code that arrives after mount', async () => {
    const { setToken } = setupWithTokenSignal({
      world: { sessionTokens: { 'tok-deep-link': '[email protected]' } },
    });
    await screen.findByRole('button', { name: 'Continue with Google' });

    setToken('tok-deep-link');

    await screen.findByText('[email protected] new');
  });

  it('redeems a late session code only once', async () => {
    const { fake, setToken } = setupWithTokenSignal({
      world: { sessionTokens: { 'tok-deep-link': '[email protected]' } },
    });
    setToken('tok-deep-link');
    await screen.findByText('[email protected] new');

    setToken('tok-deep-link');

    await waitFor(() =>
      expect(
        fake.calls().filter((call) => call === 'redeem:tok-deep-link')
      ).toHaveLength(1)
    );
  });

  // Redemption re-primes the session after the network call, so it can reject
  // rather than answer false — that must still tell the user.
  it('reports a session code whose redemption throws', async () => {
    const consoleError = vi
      .spyOn(console, 'error')
      .mockImplementation(() => {});
    const { fake, setToken } = setupWithTokenSignal({
      redeem: () => Promise.reject(new Error('network down')),
    });

    setToken('tok-deep-link');

    await waitFor(() =>
      expect(fake.notifications()).toEqual([
        'Sign-in failed. Please try again.',
      ])
    );
    consoleError.mockRestore();
  });

  it('reports a session code that cannot be redeemed', async () => {
    const { fake } = setup({ token: 'expired' });
    await waitFor(() =>
      expect(fake.notifications()).toEqual([
        'Sign-in failed. Please try again.',
      ])
    );
    expect(
      screen.getByRole('button', { name: 'Continue with Google' })
    ).toBeTruthy();
  });
});

let googleSignup: Promise<void> | undefined;

function Journey(props: SignupJourneySlots) {
  return (
    <section>
      <button
        type="button"
        onClick={() => {
          googleSignup = props.onGoogle();
        }}
      >
        Connect work email
      </button>
      <button type="button" onClick={props.onSignIn}>
        Sign in instead
      </button>
      <p data-testid="showing-email">{String(props.showingEmail)}</p>
      {props.emailForm}
    </section>
  );
}

describe('desktop sign-up', () => {
  it('hands onboarding’s slides a Google sign-up and no email form until chosen', async () => {
    const { fake } = setup({
      intent: 'signup',
      signupJourney: (slots) => <Journey {...slots} />,
    });
    expect(screen.getByTestId('showing-email').textContent).toBe('false');
    expect(screen.queryByPlaceholderText('[email protected]')).toBeNull();
    click('Connect work email');
    await screen.findByText('[email protected] new');
    expect(fake.calls()).toContain('sso:google:signup');
    await googleSignup;
  });

  it('shows the email form inside the slides for an emailed sign-up link', () => {
    setup({
      intent: 'signup',
      initialEmail: '[email protected]',
      signupJourney: (slots) => <Journey {...slots} />,
    });
    expect(screen.getByTestId('showing-email').textContent).toBe('true');
    expect(screen.getByDisplayValue('[email protected]')).toBeTruthy();
  });

  it('lets the slides send a returning visitor to sign in', () => {
    const { signIn } = setup({
      intent: 'signup',
      signupJourney: (slots) => <Journey {...slots} />,
    });
    fireEvent.click(screen.getByRole('button', { name: 'Sign in instead' }));
    expect(signIn).toHaveBeenCalledOnce();
  });

  it('holds a pending frame while the session resolves, then shows the signed-out slides', async () => {
    vi.useFakeTimers({ shouldAdvanceTime: true });
    renderWithFakeAuth(
      () => (
        <AuthView
          intent="signup"
          showApple={false}
          compact={false}
          signupJourney={(slots) => <Journey {...slots} />}
          pending={() => <p data-testid="pending">Loading</p>}
          signedIn={() => <p data-testid="signed-in" />}
        />
      ),
      {},
      { sessionLatencyMs: 300 }
    );
    expect(screen.getByTestId('pending')).toBeTruthy();
    expect(
      screen.queryByRole('button', { name: 'Connect work email' })
    ).toBeNull();
    await vi.advanceTimersByTimeAsync(300);
    await screen.findByRole('button', { name: 'Connect work email' });
    expect(screen.queryByTestId('pending')).toBeNull();
  });
});