Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

39.5 KB
Raw Blame
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import * as composioApi from '../../lib/composio/composioApi';
import * as openUrlModule from '../../utils/openUrl';
import { authorize } from '../../lib/composio/composioApi';
import { type ComposioConnection } from '../../lib/composio/types';
import ComposioConnectModal, {
  isMissingRequiredFieldsError,
  isValidAtlassianSubdomain,
  sanitizeAuthError,
} from './ComposioConnectModal';
import { composioToolkitMeta } from './toolkitMeta';

vi.mock('../../lib/composio/composioApi', () => ({
  authorize: vi.fn(),
  deleteConnection: vi.fn(),
  getUserScopes: vi.fn(() => Promise.resolve({ read: true, write: true, admin: false })),
  listConnections: vi.fn(),
  setUserScopes: vi.fn(),
}));

vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() }));

// Mock TriggerToggles because it does its own API calls
vi.mock('./TriggerToggles', () => ({ default: () => <div data-testid="trigger-toggles" /> }));

const mockToolkit = composioToolkitMeta('gmail');
const jiraToolkit = composioToolkitMeta('jira');

// ── Pure helper unit tests ────────────────────────────────────────────

describe('isValidAtlassianSubdomain', () => {
  it('accepts typical lowercase subdomain', () => {
    expect(isValidAtlassianSubdomain('acme')).toBe(true);
    expect(isValidAtlassianSubdomain('my-company')).toBe(true);
    expect(isValidAtlassianSubdomain('org123')).toBe(true);
  });

  it('accepts mixed-case subdomain (case-insensitive check)', () => {
    expect(isValidAtlassianSubdomain('MyCompany')).toBe(true);
  });

  it('accepts single-character subdomain', () => {
    expect(isValidAtlassianSubdomain('a')).toBe(true);
    expect(isValidAtlassianSubdomain('z')).toBe(true);
    expect(isValidAtlassianSubdomain('5')).toBe(true);
  });

  it('rejects full URLs', () => {
    expect(isValidAtlassianSubdomain('https://acme.atlassian.net')).toBe(false);
    expect(isValidAtlassianSubdomain('acme.atlassian.net')).toBe(false);
  });

  it('rejects leading/trailing hyphens', () => {
    expect(isValidAtlassianSubdomain('-acme')).toBe(false);
    expect(isValidAtlassianSubdomain('acme-')).toBe(false);
  });

  it('rejects empty string', () => {
    expect(isValidAtlassianSubdomain('')).toBe(false);
    expect(isValidAtlassianSubdomain('   ')).toBe(false);
  });

  it('rejects strings with spaces', () => {
    expect(isValidAtlassianSubdomain('my company')).toBe(false);
  });

  it('trims whitespace before validation', () => {
    expect(isValidAtlassianSubdomain('  acme  ')).toBe(true);
  });
});

describe('isMissingRequiredFieldsError', () => {
  it('matches the Composio error slug', () => {
    const err = new Error(
      'Authorization failed: [composio] authorize failed: Backend returned 400 Bad Request: Composio authorization failed: 400 {"error":{"message":"Missing required fields","code":612,"slug":"ConnectedAccount_MissingRequiredFields"}}'
    );
    expect(isMissingRequiredFieldsError(err)).toBe(true);
  });

  it('does NOT match on the numeric code alone — avoids false positives from port/resource numbers', () => {
    // The slug-only check prevents unrelated "612" occurrences (e.g. port numbers, IDs)
    // from being misidentified as the Composio missing-fields error.
    const err = new Error('error code 612 from server');
    expect(isMissingRequiredFieldsError(err)).toBe(false);
  });

  it('returns false for unrelated errors', () => {
    expect(isMissingRequiredFieldsError(new Error('Network timeout'))).toBe(false);
    expect(isMissingRequiredFieldsError(new Error('401 Unauthorized'))).toBe(false);
  });

  it('returns false for null / undefined', () => {
    expect(isMissingRequiredFieldsError(null)).toBe(false);
    expect(isMissingRequiredFieldsError(undefined)).toBe(false);
  });

  it('accepts non-Error objects with the slug in stringified form', () => {
    expect(isMissingRequiredFieldsError('ConnectedAccount_MissingRequiredFields')).toBe(true);
  });
});

describe('sanitizeAuthError', () => {
  it('returns a generic message for missing-required-fields errors', () => {
    const err = new Error(
      'Authorization failed: [composio] authorize failed: Backend returned 400 Bad Request for POST https://api.tinyhumans.ai/agent-integrations/composio/authorize: Composio authorization failed: 400 {"error":{"slug":"ConnectedAccount_MissingRequiredFields","code":612}}'
    );
    const result = sanitizeAuthError(err);
    expect(result).not.toContain('ConnectedAccount_MissingRequiredFields');
    expect(result).not.toContain('api.tinyhumans.ai');
    expect(result).not.toContain('612');
    expect(result).toContain('required field');
  });

  it('strips backend URLs from plain authorization errors', () => {
    const err = new Error(
      'Authorization failed: Backend returned 500 Internal Server Error for POST https://api.tinyhumans.ai/agent-integrations/composio/authorize: internal error'
    );
    const result = sanitizeAuthError(err);
    expect(result).not.toContain('api.tinyhumans.ai');
    expect(result).not.toContain('https://');
  });

  it('strips raw JSON payloads', () => {
    const err = new Error(
      'Authorization failed: something happened: {"error":{"code":500,"message":"internal"}}'
    );
    const result = sanitizeAuthError(err);
    expect(result).not.toContain('"code"');
    expect(result).not.toContain('"message"');
  });

  it('returns a safe fallback for null/undefined', () => {
    expect(sanitizeAuthError(null)).toBe('Something went wrong.');
    expect(sanitizeAuthError(undefined)).toBe('Something went wrong.');
  });

  it('handles non-Error thrown values', () => {
    const result = sanitizeAuthError('plain string error');
    expect(typeof result).toBe('string');
    expect(result.length).toBeGreaterThan(0);
  });
});

// ── Component render tests ────────────────────────────────────────────

describe('<ComposioConnectModal>', () => {
  it('hides raw connection ID and "id:" label in connected phase', () => {
    const connection: ComposioConnection = { id: 'ca_xyz', toolkit: 'gmail', status: 'ACTIVE' };

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    // Should be in 'connected' phase because connection.status is 'ACTIVE'
    expect(screen.getByText(/Gmail is connected/)).toBeInTheDocument();
    expect(screen.queryByText(/ca_xyz/)).not.toBeInTheDocument();
    expect(screen.queryByText(/id:/)).not.toBeInTheDocument();
  });

  it('renders accountEmail when provided', () => {
    const connection: ComposioConnection = {
      id: 'ca_xyz',
      toolkit: 'gmail',
      status: 'ACTIVE',
      accountEmail: '[email protected]',
    };

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    expect(screen.getByText('([email protected])')).toBeInTheDocument();
  });

  it('renders workspace when accountEmail is missing', () => {
    const connection: ComposioConnection = {
      id: 'ca_xyz',
      toolkit: 'gmail',
      status: 'ACTIVE',
      workspace: 'Acme',
    };

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    expect(screen.getByText('(Acme)')).toBeInTheDocument();
  });

  it('renders username when email and workspace are missing', () => {
    const connection: ComposioConnection = {
      id: 'ca_xyz',
      toolkit: 'gmail',
      status: 'ACTIVE',
      username: 'oxox',
    };

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    expect(screen.getByText('(oxox)')).toBeInTheDocument();
  });

  it('prioritizes accountEmail over workspace and username', () => {
    const connection: ComposioConnection = {
      id: 'ca_xyz',
      toolkit: 'gmail',
      status: 'ACTIVE',
      accountEmail: '[email protected]',
      workspace: 'Acme',
      username: 'oxox',
    };

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    expect(screen.getByText('([email protected])')).toBeInTheDocument();
    expect(screen.queryByText('(Acme)')).not.toBeInTheDocument();
    expect(screen.queryByText('(oxox)')).not.toBeInTheDocument();
  });

  it('renders multi-connection list when multiple active connections exist', () => {
    const connections: ComposioConnection[] = [
      { id: 'ca_1', toolkit: 'gmail', status: 'ACTIVE', accountEmail: '[email protected]' },
      { id: 'ca_2', toolkit: 'gmail', status: 'ACTIVE', accountEmail: '[email protected]' },
    ];

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={connections} onClose={() => {}} />
    );

    expect(screen.getByText('[email protected]')).toBeInTheDocument();
    expect(screen.getByText('[email protected]')).toBeInTheDocument();
    expect(screen.getByText(/Add another account/i)).toBeInTheDocument();
  });

  it('stays in connected phase after disconnecting one of multiple connections', async () => {
    const connections: ComposioConnection[] = [
      { id: 'ca_1', toolkit: 'gmail', status: 'ACTIVE', accountEmail: '[email protected]' },
      { id: 'ca_2', toolkit: 'gmail', status: 'ACTIVE', accountEmail: '[email protected]' },
    ];
    vi.mocked(composioApi.deleteConnection).mockResolvedValue({ deleted: true });

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={connections} onClose={() => {}} />
    );

    const personalEl = screen.getByText('[email protected]');
    const row = personalEl.closest('.rounded-lg')!;
    const disconnectBtn = within(row as HTMLElement).getByText(/Remove/i);
    fireEvent.click(disconnectBtn);

    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_2');
    });
  });

  it('shows default label on first connection in multi-connection list', () => {
    const connections: ComposioConnection[] = [
      { id: 'ca_1', toolkit: 'gmail', status: 'ACTIVE', accountEmail: '[email protected]' },
      { id: 'ca_2', toolkit: 'gmail', status: 'ACTIVE', accountEmail: '[email protected]' },
    ];

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={connections} onClose={() => {}} />
    );

    expect(screen.getByText(/^default$/i)).toBeInTheDocument();
  });

  it('falls back to toolkit name when connection has no label', () => {
    const connections: ComposioConnection[] = [
      { id: 'ca_1', toolkit: 'gmail', status: 'ACTIVE' },
      { id: 'ca_2', toolkit: 'gmail', status: 'ACTIVE' },
    ];

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={connections} onClose={() => {}} />
    );

    const gmailTexts = screen.getAllByText('Gmail');
    expect(gmailTexts.length).toBeGreaterThanOrEqual(2);
  });

  it('disconnects with just the connection id and offers no clear-memory option', async () => {
    const connection: ComposioConnection = { id: 'ca_xyz', toolkit: 'gmail', status: 'ACTIVE' };
    vi.mocked(composioApi.deleteConnection).mockResolvedValue({ deleted: true });

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    expect(screen.queryByLabelText(/also delete memory/i)).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: /^Disconnect$/i }));

    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_xyz');
    });
  });

  it('shows the failure and returns to the connected view when it is dismissed', async () => {
    const connection: ComposioConnection = { id: 'ca_xyz', toolkit: 'gmail', status: 'ACTIVE' };
    vi.mocked(composioApi.deleteConnection).mockRejectedValueOnce(new Error('backend down'));

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    fireEvent.click(screen.getByRole('button', { name: /^Disconnect$/i }));

    expect(await screen.findByText(/backend down/i)).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: /dismiss/i }));

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /^Disconnect$/i })).toBeInTheDocument();
    });
  });

  it('shows an expired-auth recovery state with a reconnect CTA', () => {
    const connection: ComposioConnection = {
      id: 'ca_expired',
      toolkit: 'gmail',
      status: 'EXPIRED',
    };

    render(
      <ComposioConnectModal toolkit={mockToolkit} connections={[connection]} onClose={() => {}} />
    );

    expect(screen.getByText(/Gmail authorization expired/i)).toBeInTheDocument();
    expect(screen.getByText(/Reconnect to re-enable Gmail tools/i)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Reconnect Gmail/i })).toBeInTheDocument();
    expect(screen.queryByText(/ca_expired/)).not.toBeInTheDocument();
  });

  // ── Connect flow → openUrl(connectUrl) ───────────────────────────
  //
  // Verifies the end-to-end OAuth handoff plumbing for #1710:
  //   Connect click → authorize RPC → openUrl(connectUrl).
  //
  // The frontend doesn't care whether the URL is the backend's
  // `/agent-integrations/composio/authorize` redirect or Composio's
  // hosted `https://hosted.composio.dev/<token>` — both come back via
  // the same `connectUrl` field on `ComposioAuthorizeResponse`, so this
  // single assertion covers both modes. After this commit the
  // mechanically-wired direct-mode flow is: ops.rs `composio_authorize`
  // → factory routes to Direct → `direct_authorize` returns a Composio
  // hosted URL → frontend opens it in the system browser via this
  // path → `list_connections` polling detects the new ACTIVE row.
  describe('Connect flow (covers backend + direct mode #1710)', () => {
    beforeEach(() => {
      vi.mocked(composioApi.authorize).mockReset();
      vi.mocked(composioApi.listConnections).mockReset();
      vi.mocked(openUrlModule.openUrl).mockReset();
    });

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

    it('opens the connectUrl from the authorize response in the system browser', async () => {
      // Direct mode emits an empty connectionId; backend mode emits a
      // populated one. The frontend treats both the same — only the
      // URL is the source of truth for opening the browser.
      vi.mocked(composioApi.authorize).mockResolvedValue({
        connectUrl: 'https://hosted.composio.dev/test-token',
        connectionId: '',
      });
      // Polling won't fire during this test — we don't advance timers
      // past the connect click, so listConnections only needs to be
      // mockable to avoid throwing.
      vi.mocked(composioApi.listConnections).mockResolvedValue({ connections: [] });

      render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);

      const connectBtn = screen.getByRole('button', { name: /Connect Gmail/ });
      fireEvent.click(connectBtn);

      await waitFor(() => {
        expect(composioApi.authorize).toHaveBeenCalledWith('gmail', undefined);
      });
      await waitFor(() => {
        expect(openUrlModule.openUrl).toHaveBeenCalledWith(
          'https://hosted.composio.dev/test-token'
        );
      });
    });

    it('shows the waiting state even when the OS browser opener rejects', async () => {
      vi.mocked(composioApi.authorize).mockResolvedValue({
        connectUrl: 'https://hosted.composio.dev/test-token',
        connectionId: '',
      });
      vi.mocked(composioApi.listConnections).mockResolvedValue({ connections: [] });
      vi.mocked(openUrlModule.openUrl).mockRejectedValueOnce(new Error('opener unavailable'));

      render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);

      fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/ }));

      expect(await screen.findByRole('button', { name: /Reopen browser/i })).toBeInTheDocument();
      expect(screen.getByText(/Waiting for Gmail/i)).toBeInTheDocument();
      expect(screen.queryByText(/Something went wrong/i)).not.toBeInTheDocument();
    });
  });
});

// ── Jira-specific flow tests ──────────────────────────────────────────

describe('<ComposioConnectModal> — Jira subdomain collection', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('shows the Atlassian subdomain input in the idle phase for Jira', () => {
    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    expect(screen.getByLabelText(/Atlassian subdomain/i)).toBeInTheDocument();
    expect(screen.getByPlaceholderText('your-subdomain')).toBeInTheDocument();
  });

  it('does NOT show the Atlassian subdomain input for non-Jira toolkits', () => {
    render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);

    expect(screen.queryByLabelText(/Atlassian subdomain/i)).not.toBeInTheDocument();
    expect(screen.queryByPlaceholderText('your-subdomain')).not.toBeInTheDocument();
  });

  it('shows a validation error when connect is clicked with an empty subdomain', async () => {
    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    const connectButton = screen.getByRole('button', { name: /Connect Jira/i });
    fireEvent.click(connectButton);

    await waitFor(() => {
      expect(screen.getByText(/This field is required/i)).toBeInTheDocument();
    });
  });

  it('shows a validation error when the subdomain looks like a full URL', async () => {
    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    const input = screen.getByPlaceholderText('your-subdomain');
    fireEvent.change(input, { target: { value: 'https://acme.atlassian.net' } });

    const connectButton = screen.getByRole('button', { name: /Connect Jira/i });
    fireEvent.click(connectButton);

    await waitFor(() => {
      expect(screen.getByText(/short subdomain only/i)).toBeInTheDocument();
    });
  });

  it('clears subdomain validation error when the user types', async () => {
    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    // Trigger validation error
    const connectButton = screen.getByRole('button', { name: /Connect Jira/i });
    fireEvent.click(connectButton);

    await waitFor(() => {
      expect(screen.getByText(/This field is required/i)).toBeInTheDocument();
    });

    // Type to clear the error
    const input = screen.getByPlaceholderText('your-subdomain');
    fireEvent.change(input, { target: { value: 'a' } });

    await waitFor(() => {
      expect(screen.queryByText(/Please enter your Atlassian subdomain/i)).not.toBeInTheDocument();
    });
  });
});

// ── needs-subdomain phase tests ───────────────────────────────────────

describe('<ComposioConnectModal> — needs-subdomain recovery phase', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('transitions to needs-subdomain phase for Jira when Composio returns the missing-required-fields error', async () => {
    // needs-subdomain phase is only shown for Atlassian toolkits (jira).
    vi.mocked(authorize).mockRejectedValueOnce(
      new Error(
        'Authorization failed: Backend returned 400: {"error":{"slug":"ConnectedAccount_MissingRequiredFields","code":612}}'
      )
    );

    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    const input = screen.getByPlaceholderText('your-subdomain');
    fireEvent.change(input, { target: { value: 'acme' } });
    fireEvent.click(screen.getByRole('button', { name: /Connect Jira/i }));

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Retry connection/i })).toBeInTheDocument();
      expect(screen.getByText(/To connect Jira/i)).toBeInTheDocument();
    });
  });

  it('routes non-Jira missing-required-fields errors to the error phase (not needs-subdomain)', async () => {
    // Gmail does not have an Atlassian subdomain — showing the Atlassian subdomain
    // form for it would be misleading and the retry would loop forever.
    vi.mocked(authorize).mockRejectedValueOnce(
      new Error(
        'Authorization failed: Backend returned 400: {"error":{"slug":"ConnectedAccount_MissingRequiredFields","code":612}}'
      )
    );

    render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);
    fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/i }));

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Dismiss/i })).toBeInTheDocument();
      expect(screen.queryByRole('button', { name: /Retry connection/i })).not.toBeInTheDocument();
    });
  });

  it('does NOT show raw backend payload in the needs-subdomain phase', async () => {
    vi.mocked(authorize).mockRejectedValueOnce(
      new Error(
        'Authorization failed: Backend returned 400: {"error":{"slug":"ConnectedAccount_MissingRequiredFields","code":612,"message":"very sensitive backend payload"}}'
      )
    );

    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    const input = screen.getByPlaceholderText('your-subdomain');
    fireEvent.change(input, { target: { value: 'acme' } });
    fireEvent.click(screen.getByRole('button', { name: /Connect Jira/i }));

    await waitFor(() => {
      expect(screen.queryByText(/very sensitive backend payload/i)).not.toBeInTheDocument();
      expect(screen.queryByText(/ConnectedAccount_MissingRequiredFields/i)).not.toBeInTheDocument();
    });
  });

  it('clicking Cancel in needs-subdomain goes back to idle', async () => {
    vi.mocked(authorize).mockRejectedValueOnce(new Error('ConnectedAccount_MissingRequiredFields'));

    render(<ComposioConnectModal toolkit={jiraToolkit} onClose={() => {}} />);

    const input = screen.getByPlaceholderText('your-subdomain');
    fireEvent.change(input, { target: { value: 'acme' } });
    fireEvent.click(screen.getByRole('button', { name: /Connect Jira/i }));

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Retry connection/i })).toBeInTheDocument();
    });

    fireEvent.click(screen.getByRole('button', { name: /Cancel/i }));

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Connect Jira/i })).toBeInTheDocument();
    });
  });

  it('surfaces Meta rate-limit guidance for Instagram authorize failures', async () => {
    const instagramToolkit = composioToolkitMeta('instagram');
    vi.mocked(authorize).mockRejectedValueOnce(
      new Error('Authorization failed: Backend returned 429 Too Many Requests')
    );

    render(<ComposioConnectModal toolkit={instagramToolkit} onClose={() => {}} />);
    fireEvent.click(screen.getByRole('button', { name: /Connect Instagram/i }));

    await waitFor(() => {
      expect(screen.getByText(/Business or Creator account/i)).toBeInTheDocument();
      expect(screen.getByText(/HTTP 429/i)).toBeInTheDocument();
      expect(screen.queryByText(/api.tinyhumans.ai/i)).not.toBeInTheDocument();
    });
  });

  it('surfaces a sanitized (non-raw) error for unrelated authorization failures', async () => {
    vi.mocked(authorize).mockRejectedValueOnce(
      new Error(
        'Authorization failed: Backend returned 500 Internal Server Error for POST https://api.tinyhumans.ai/agent-integrations/composio/authorize: {"error":{"message":"internal server error payload","code":500}}'
      )
    );

    render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);

    fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/i }));

    await waitFor(() => {
      // Should be in error phase, not needs-subdomain
      expect(screen.getByRole('button', { name: /Dismiss/i })).toBeInTheDocument();
      // Raw URL should not be shown
      expect(screen.queryByText(/api.tinyhumans.ai/i)).not.toBeInTheDocument();
      // Raw JSON payload should not be shown
      expect(screen.queryByText(/internal server error payload/i)).not.toBeInTheDocument();
    });
  });
});

// ── Dynamics 365 org_name required-field flow (#2127) ──────────────────

describe('<ComposioConnectModal> — Dynamics 365 org_name collection (#2127)', () => {
  const dynamicsToolkit = composioToolkitMeta('dynamics365');

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders the Dynamics 365 Organization Name input in the idle phase', () => {
    render(<ComposioConnectModal toolkit={dynamicsToolkit} onClose={() => {}} />);

    expect(screen.getByLabelText(/Dynamics 365 Organization Name/i)).toBeInTheDocument();
    expect(screen.getByPlaceholderText('myorg')).toBeInTheDocument();
    // Suffix renders inside the input wrapper so users see the .crm.dynamics.com tail.
    expect(screen.getByText('.crm.dynamics.com')).toBeInTheDocument();
  });

  it('blocks submission when org name is empty and surfaces the generic required-field error', async () => {
    render(<ComposioConnectModal toolkit={dynamicsToolkit} onClose={() => {}} />);

    fireEvent.click(screen.getByRole('button', { name: /Connect Dynamics 365/i }));

    await waitFor(() => {
      expect(screen.getByText(/This field is required/i)).toBeInTheDocument();
    });
    expect(authorize).not.toHaveBeenCalled();
  });

  it('rejects a full URL with the subdomain-invalid message', async () => {
    render(<ComposioConnectModal toolkit={dynamicsToolkit} onClose={() => {}} />);

    const input = screen.getByPlaceholderText('myorg');
    fireEvent.change(input, { target: { value: 'https://myorg.crm.dynamics.com' } });
    fireEvent.click(screen.getByRole('button', { name: /Connect Dynamics 365/i }));

    await waitFor(() => {
      expect(screen.getByText(/short subdomain only/i)).toBeInTheDocument();
    });
    expect(authorize).not.toHaveBeenCalled();
  });

  it('forwards the trimmed org_name as extra_params on successful submit', async () => {
    vi.mocked(authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/dynamics-token',
      connectionId: 'ca_dyn_1',
    });
    vi.mocked(composioApi.listConnections).mockResolvedValue({ connections: [] });

    render(<ComposioConnectModal toolkit={dynamicsToolkit} onClose={() => {}} />);

    fireEvent.change(screen.getByPlaceholderText('myorg'), { target: { value: '  myorg  ' } });
    fireEvent.click(screen.getByRole('button', { name: /Connect Dynamics 365/i }));

    await waitFor(() => {
      expect(authorize).toHaveBeenCalledWith('dynamics365', { org_name: 'myorg' });
    });
  });

  it('transitions to the needs-fields recovery phase when Composio returns 612', async () => {
    vi.mocked(authorize).mockRejectedValueOnce(
      new Error(
        'Authorization failed: Backend returned 400: {"error":{"slug":"ConnectedAccount_MissingRequiredFields","code":612}}'
      )
    );

    render(<ComposioConnectModal toolkit={dynamicsToolkit} onClose={() => {}} />);

    fireEvent.change(screen.getByPlaceholderText('myorg'), { target: { value: 'myorg' } });
    fireEvent.click(screen.getByRole('button', { name: /Connect Dynamics 365/i }));

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Retry connection/i })).toBeInTheDocument();
      expect(screen.getByText(/we need a bit more information/i)).toBeInTheDocument();
    });
    expect(screen.queryByText(/ConnectedAccount_MissingRequiredFields/i)).not.toBeInTheDocument();
  });
});

// ── WhatsApp WABA id parity check — registry refactor must not regress (#2127) ─

describe('<ComposioConnectModal> — WhatsApp WABA id parity (#2127)', () => {
  const whatsappToolkit = composioToolkitMeta('whatsapp');

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('still renders the WABA id input and forwards waba_id as extra_params', async () => {
    vi.mocked(authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/wa-token',
      connectionId: 'ca_wa_1',
    });
    vi.mocked(composioApi.listConnections).mockResolvedValue({ connections: [] });

    render(<ComposioConnectModal toolkit={whatsappToolkit} onClose={() => {}} />);

    expect(screen.getByLabelText(/WhatsApp Business Account ID/i)).toBeInTheDocument();
    fireEvent.change(screen.getByPlaceholderText(/123456789012345/), {
      target: { value: '999000111222333' },
    });
    fireEvent.click(screen.getByRole('button', { name: /Connect WhatsApp/i }));

    await waitFor(() => {
      expect(authorize).toHaveBeenCalledWith('whatsapp', { waba_id: '999000111222333' });
    });
  });
});

describe('ComposioConnectModal — connection-failed copy (issue #3759)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('substitutes the status into the failure message when polling sees a FAILED connection', async () => {
    // A PENDING connection resumes polling on mount; the first poll observes a
    // FAILED connection and must SUBSTITUTE {status} into the error copy
    // (issue #3759) — not concatenate/leak the literal placeholder.
    vi.mocked(composioApi.listConnections).mockResolvedValue({
      connections: [{ id: 'ca_err', toolkit: 'gmail', status: 'FAILED' }],
    });

    render(
      <ComposioConnectModal
        toolkit={mockToolkit}
        connections={[{ id: 'ca_pending', toolkit: 'gmail', status: 'PENDING' }]}
        onClose={() => {}}
      />
    );

    expect(await screen.findByText('Connection failed (status: FAILED).')).toBeInTheDocument();
    // Regression guard: the raw placeholder must never reach the screen.
    expect(screen.queryByText(/\{status\}/)).not.toBeInTheDocument();
  });
});

describe('ComposioConnectModal — focus-triggered re-poll', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('polls immediately on window focus so the connected flip does not wait for the timer', async () => {
    // Resume-polling path: a PENDING connection starts the poller on mount.
    // The first poll still sees PENDING; then the connection goes ACTIVE and
    // the user returns to the app (window focus). The focus poke must fire an
    // immediate re-poll and flip to "connected" without waiting for the next
    // scheduled tick.
    vi.mocked(composioApi.listConnections)
      .mockResolvedValueOnce({ connections: [{ id: 'ca_1', toolkit: 'gmail', status: 'PENDING' }] })
      .mockResolvedValue({ connections: [{ id: 'ca_1', toolkit: 'gmail', status: 'ACTIVE' }] });

    render(
      <ComposioConnectModal
        toolkit={mockToolkit}
        connections={[{ id: 'ca_1', toolkit: 'gmail', status: 'PENDING' }]}
        onClose={() => {}}
      />
    );

    // First poll resolved to PENDING — still waiting, not connected yet.
    await waitFor(() => {
      expect(composioApi.listConnections).toHaveBeenCalledTimes(1);
    });
    expect(screen.queryByText(/Gmail is connected/)).not.toBeInTheDocument();

    // User switches back from the browser → immediate re-poll → ACTIVE.
    fireEvent(window, new Event('focus'));

    expect(await screen.findByText(/Gmail is connected/)).toBeInTheDocument();
  });
});

// ── Cancelling a stuck handoff ────────────────────────────────────────
// A connection that never comes back from the browser used to leave the
// toolkit pinned on "Connecting": the modal only polled, and closing it left
// the Composio connection in PENDING so reopening resumed the same wait.

describe('<ComposioConnectModal> — cancelling a pending connection', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(composioApi.listConnections).mockResolvedValue({ connections: [] });
    vi.mocked(composioApi.deleteConnection).mockResolvedValue({ deleted: true });
  });

  it('deletes the connection created by authorize and returns to idle', async () => {
    vi.mocked(composioApi.authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/test-token',
      connectionId: 'ca_new',
    });
    const onChanged = vi.fn();

    render(<ComposioConnectModal toolkit={mockToolkit} onChanged={onChanged} onClose={() => {}} />);
    fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/ }));

    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));

    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_new');
    });
    // Back to the idle phase — the Connect button is offered again and the
    // waiting spinner copy is gone.
    expect(await screen.findByRole('button', { name: /Connect Gmail/ })).toBeInTheDocument();
    expect(screen.queryByText(/Waiting for Gmail/i)).not.toBeInTheDocument();
    expect(onChanged).toHaveBeenCalled();
  });

  it('cancels a handoff resumed from an existing PENDING connection', async () => {
    vi.mocked(composioApi.listConnections).mockResolvedValue({
      connections: [{ id: 'ca_pending', toolkit: 'gmail', status: 'PENDING' }],
    });

    render(
      <ComposioConnectModal
        toolkit={mockToolkit}
        connections={[{ id: 'ca_pending', toolkit: 'gmail', status: 'PENDING' }]}
        onClose={() => {}}
      />
    );

    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));

    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_pending');
    });
    expect(await screen.findByRole('button', { name: /Connect Gmail/ })).toBeInTheDocument();
  });

  it('stops polling once the pending connection is cancelled', async () => {
    vi.useFakeTimers();
    try {
      vi.mocked(composioApi.listConnections).mockResolvedValue({
        connections: [{ id: 'ca_pending', toolkit: 'gmail', status: 'PENDING' }],
      });

      render(
        <ComposioConnectModal
          toolkit={mockToolkit}
          connections={[{ id: 'ca_pending', toolkit: 'gmail', status: 'PENDING' }]}
          onClose={() => {}}
        />
      );

      await vi.advanceTimersByTimeAsync(0);
      const pollsBeforeCancel = vi.mocked(composioApi.listConnections).mock.calls.length;

      fireEvent.click(screen.getByTestId('composio-cancel-connect'));
      await vi.advanceTimersByTimeAsync(0);
      await vi.advanceTimersByTimeAsync(30_000);

      expect(vi.mocked(composioApi.listConnections).mock.calls.length).toBe(pollsBeforeCancel);
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_pending');
    } finally {
      vi.useRealTimers();
    }
  });

  it('finds and deletes the pending row by toolkit when authorize returned no id', async () => {
    // Direct mode's authorize emits an empty connectionId. Releasing the UI
    // without deleting anything would leave the row Composio created behind —
    // the same stuck PENDING this button exists to clear — so cancel has to
    // look it up by toolkit first.
    vi.mocked(composioApi.authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/test-token',
      connectionId: '',
    });
    // The first call is the poll that `handleConnect` kicks off; it must come
    // back empty, otherwise the poller itself records the id and the cancel
    // path never reaches its lookup — the test would then pass without
    // exercising the branch it exists for. The rows only appear on the call
    // cancel makes.
    vi.mocked(composioApi.listConnections)
      .mockResolvedValueOnce({ connections: [] })
      .mockResolvedValue({
        connections: [
          { id: 'ca_other_toolkit', toolkit: 'slack', status: 'INITIATED' },
          { id: 'ca_direct', toolkit: 'gmail', status: 'INITIATED' },
        ],
      });

    render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);
    fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/ }));
    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));

    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_direct');
    });
    expect(await screen.findByRole('button', { name: /Connect Gmail/ })).toBeInTheDocument();
  });

  it('does not report success when the backend did not confirm the delete', async () => {
    // `deleted: false` means the row is still there. Flipping to idle would
    // tell the user the handoff is gone while Composio still holds it.
    vi.mocked(composioApi.authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/test-token',
      connectionId: 'ca_new',
    });
    vi.mocked(composioApi.deleteConnection).mockResolvedValue({ deleted: false });
    const onChanged = vi.fn();

    render(<ComposioConnectModal toolkit={mockToolkit} onChanged={onChanged} onClose={() => {}} />);
    fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/ }));
    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));

    expect(await screen.findByText(/did not confirm/i)).toBeInTheDocument();
    expect(onChanged).not.toHaveBeenCalled();
  });

  it('ignores a poll that was already in flight when cancel ran', async () => {
    // Clearing the timer cannot un-send a request. A tick that resolves after
    // the delete must not push the modal back to "connected" for a connection
    // that no longer exists.
    let resolvePoll: (value: { connections: ComposioConnection[] }) => void = () => {};
    const pending = new Promise<{ connections: ComposioConnection[] }>(resolve => {
      resolvePoll = resolve;
    });
    vi.mocked(composioApi.listConnections).mockReturnValue(pending);

    render(
      <ComposioConnectModal
        toolkit={mockToolkit}
        connections={[{ id: 'ca_pending', toolkit: 'gmail', status: 'PENDING' }]}
        onClose={() => {}}
      />
    );

    // The mount poll is now in flight and will not settle until we say so.
    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));
    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_pending');
    });

    // The stale response lands late, claiming the toolkit went ACTIVE.
    resolvePoll({ connections: [{ id: 'ca_pending', toolkit: 'gmail', status: 'ACTIVE' }] });
    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Connect Gmail/ })).toBeInTheDocument();
    });
    expect(screen.queryByText(/Gmail is connected/)).not.toBeInTheDocument();
  });

  it('returns to the connected view when a second-account handoff is cancelled', async () => {
    // Adding another account to an already-connected toolkit and then
    // cancelling must leave the existing account alone, not drop the user
    // onto the disconnected idle screen.
    vi.mocked(composioApi.authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/test-token',
      connectionId: 'ca_second',
    });

    render(
      <ComposioConnectModal
        toolkit={mockToolkit}
        connections={[{ id: 'ca_first', toolkit: 'gmail', status: 'ACTIVE' }]}
        onClose={() => {}}
      />
    );

    fireEvent.click(await screen.findByRole('button', { name: /Add another account/i }));
    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));

    await waitFor(() => {
      expect(composioApi.deleteConnection).toHaveBeenCalledWith('ca_second');
    });
    expect(await screen.findByText(/Gmail is connected/)).toBeInTheDocument();
  });

  it('surfaces a failure to cancel instead of silently staying stuck', async () => {
    vi.mocked(composioApi.authorize).mockResolvedValue({
      connectUrl: 'https://hosted.composio.dev/test-token',
      connectionId: 'ca_new',
    });
    vi.mocked(composioApi.deleteConnection).mockRejectedValue(new Error('backend down'));

    render(<ComposioConnectModal toolkit={mockToolkit} onClose={() => {}} />);
    fireEvent.click(screen.getByRole('button', { name: /Connect Gmail/ }));
    fireEvent.click(await screen.findByTestId('composio-cancel-connect'));

    expect(await screen.findByText(/backend down/)).toBeInTheDocument();
  });
});