Skip to content

Self-improving AI Employees for everyone

refactor(credentials): unify normal and dev panels

trohitgcd0b1c2488a2
diff --git a/client/package.json b/client/package.json
index 3b6c78e0..4f53579f 100644
--- a/client/package.json
+++ b/client/package.json
@@ -13,7 +13,7 @@
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
- "test:credentials": "vitest run src/hooks/__tests__/useApiKeys.test.ts src/components/__tests__/CredentialsModal.test.tsx",
+ "test:credentials": "vitest run src/hooks/__tests__/useApiKeys.test.ts src/components/__tests__/CredentialsModal.test.tsx src/components/credentials src/features/home/__tests__/connectorsTab.test.tsx src/stores/__tests__/shellDialogsStore.test.ts",
"test:nodepanels": "vitest run src/hooks/__tests__/useDragVariable.test.ts src/hooks/__tests__/useParameterPanel.test.ts src/components/parameterPanel/__tests__ src/components/__tests__/OutputPanel.test.tsx"
},
"dependencies": {
diff --git a/client/src/components/__tests__/CredentialsModal.test.tsx b/client/src/components/__tests__/CredentialsModal.test.tsx
index 64814eec..95a58acf 100644
--- a/client/src/components/__tests__/CredentialsModal.test.tsx
+++ b/client/src/components/__tests__/CredentialsModal.test.tsx
@@ -1,234 +1,195 @@
-/**
- * Smoke + behavioural tests for CredentialsModal.
- *
- * The hook contract is exhaustively tested in
- * client/src/hooks/__tests__/useApiKeys.test.ts (which locks in invariants 1 and 6).
- *
- * This suite locks in invariants 2 and 5:
- * - Modal renders without crashing for representative panel types
- * - Status objects (twitter/google/whatsapp/android/telegram) are read from
- * WebSocketContext, NOT fetched on mount
- * - OAuth login click triggers the matching `*_oauth_login` request
- *
- * Heavy mocking strategy: useApiKeys + useWebSocket + status hooks all stubbed
- * so the modal can mount in jsdom without real WS connection / antd transitions.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+/** Real catalogue, shell state and provider forms with only transport mocked. */
+import { act, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { renderWithProviders } from '../../test/providers';
-
-// Scaling-v2 wraps the credentials modal in TanStack Query (useCatalogueQuery)
-// and ThemeProvider. `renderWithProviders` wraps every render in both.
-const render = renderWithProviders;
-
-// --- Mocks (declared BEFORE importing the modal -- vi.mock is hoisted) ------
-
-const apiHookMock = {
- validateApiKey: vi.fn().mockResolvedValue({ isValid: true, models: ['gpt-4'] }),
- saveApiKey: vi.fn().mockResolvedValue({ isValid: true }),
- getStoredApiKey: vi.fn().mockResolvedValue(null),
- hasStoredKey: vi.fn().mockResolvedValue(false),
- getStoredModels: vi.fn().mockResolvedValue(null),
- removeApiKey: vi.fn().mockResolvedValue(undefined),
- validateGoogleMapsKey: vi.fn().mockResolvedValue({ isValid: true }),
- validateApifyKey: vi.fn().mockResolvedValue({ isValid: true }),
- getAiModels: vi.fn().mockResolvedValue([]),
- getProviderDefaults: vi.fn().mockResolvedValue({
- default_model: '',
- temperature: 0.7,
- max_tokens: 4096,
- thinking_enabled: false,
- thinking_budget: 2048,
- reasoning_effort: 'medium',
- reasoning_format: 'parsed',
- }),
- saveProviderDefaults: vi.fn().mockResolvedValue(true),
- getProviderUsageSummary: vi.fn().mockResolvedValue([]),
- getAPIUsageSummary: vi.fn().mockResolvedValue([]),
- getModelConstraints: vi.fn().mockResolvedValue({
- found: false,
- model: '',
- provider: '',
- max_output_tokens: 4096,
- context_length: 128_000,
- temperature_range: [0, 2],
- supports_thinking: false,
- thinking_type: 'none',
- is_reasoning_model: false,
- }),
- getValidatedAiProviders: vi.fn().mockResolvedValue({
- providers: [],
- global_provider: null,
- global_model: null,
- }),
- saveGlobalModel: vi.fn().mockResolvedValue(true),
- isValidating: false,
- validationError: null,
- isConnected: true,
-};
-
-vi.mock('../../hooks/useApiKeys', () => ({
- useApiKeys: () => apiHookMock,
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { toast } from 'sonner';
+import { makeTestQueryClient, renderWithProviders } from '../../test/providers';
+import { CATALOGUE_QUERY_KEY, type CatalogueResponse } from '@/hooks/useCatalogueQuery';
+import { useShellDialogsStore, type CredentialsOptions } from '@/stores/shellDialogsStore';
+import { useAppStore } from '@/store/useAppStore';
+const featureFlags = vi.hoisted(() => ({ normalMode: true }));
+vi.mock('@/lib/featureFlags', () => ({ featureFlags }));
+
+const ws = vi.hoisted(() => ({
+ isConnected: true, isReady: true, apiKeyStatuses: {},
+ sendRequest: vi.fn(), validateApiKey: vi.fn(),
+}));
+vi.mock('@/contexts/WebSocketContext', () => ({
+ useWebSocket: () => ws, useWebSocketActions: () => ws,
+ CREDENTIAL_PROBE_REQUEST_TIMEOUT: 180_000,
}));
+vi.mock('idb-keyval', () => ({ get: vi.fn().mockResolvedValue(undefined), set: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('@/assets/icons', () => ({ NodeIcon: () => null }));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));
+import CredentialsModal from '../CredentialsModal';
-const wsMock = {
- isConnected: true,
- sendRequest: vi.fn().mockResolvedValue({}),
- // status getters aren't actually used here -- they're consumed via the dedicated hooks below
-};
+let catalogue: CatalogueResponse;
+let disabled: string[];
+function Harness({ options }: { options?: CredentialsOptions }) {
+ const open = useShellDialogsStore((s) => s.openCredentials);
+ const close = useShellDialogsStore((s) => s.closeCredentials);
+ const visible = useShellDialogsStore((s) => s.credentialsOpen);
+ return <><button onClick={() => open(options)}>Open credentials</button><CredentialsModal visible={visible} onClose={close} /></>;
+}
+function mount(options?: CredentialsOptions) {
+ const queryClient = makeTestQueryClient();
+ renderWithProviders(<Harness options={options} />, { queryClient });
+ return queryClient;
+}
+async function open() { await userEvent.click(screen.getByRole('button', { name: 'Open credentials' })); }
+const keyInput = () => screen.findByPlaceholderText('Enter API key...');
-// Replace the entire WebSocketContext module with stub exports. The
-// `vi.importActual` + spread pattern was previously used here but failed
-// to override `useWebSocket` reliably under React 19 — the real
-// implementation's `useContext(WebSocketContext)` check fired against the
-// undefined provider, throwing the "must be used within a WebSocketProvider"
-// error before the mocked override could intercept. The full-replace style
-// matches what useApiKeys.test.ts does and works in both vitest 1 and 2.
-vi.mock('../../contexts/WebSocketContext', () => ({
- useWebSocket: () => wsMock,
- useWhatsAppStatus: () => ({
- connected: false,
- has_session: false,
- running: false,
- pairing: false,
- device_id: null,
- connected_phone: null,
- qr: null,
- }),
- useAndroidStatus: () => ({
- connected: false,
- paired: false,
- device_id: null,
- device_name: null,
- connected_devices: [],
- qr_data: null,
- }),
- useTwitterStatus: () => ({
- connected: false,
- username: null,
- user_id: null,
- name: null,
- profile_image_url: null,
- }),
- useGoogleStatus: () => ({
- connected: false,
- email: null,
- name: null,
- profile_image_url: null,
- }),
- useTelegramStatus: () => ({
- connected: false,
- bot_username: null,
- bot_name: null,
- bot_id: null,
- owner_chat_id: null,
- }),
- useNodeStatus: () => ({ status: 'idle', data: {} }),
-}));
+beforeEach(() => {
+ vi.clearAllMocks();
+ featureFlags.normalMode = true;
+ useAppStore.setState({ shellMode: 'normal' });
+ useShellDialogsStore.setState({ credentialsOpen: false, credentialsOptions: { intent: 'manage' }, credentialsRequestId: 0 });
+ disabled = [];
+ catalogue = {
+ version: 'test', categories: [{ key: 'ai', label: 'AI', order: 0 }, { key: 'messaging', label: 'Messaging', order: 1 }],
+ consumer_categories: [{ key: 'messages', label: 'Messages', order: 0 }, { key: 'ai', label: 'AI', order: 1 }],
+ providers: [
+ { id: 'openai', name: 'OpenAI', category: 'ai', category_label: 'AI', color: '', kind: 'apiKey',
+ consumer_category: 'ai', description: 'GPT models', publisher: 'OpenAI', verified: true,
+ fields: [{ key: 'apiKey', label: 'API key', secret: true }], has_defaults: true, stored: false, connected: false },
+ { id: 'telegram', name: 'Telegram', category: 'messaging', category_label: 'Messaging', color: '', kind: 'apiKey',
+ consumer_category: 'messages', fields: [{ key: 'apiKey', label: 'Bot token', secret: true }], stored: true, connected: true },
+ ],
+ };
+ ws.sendRequest.mockImplementation(async (type: string) => {
+ if (type === 'get_credential_catalogue') return catalogue;
+ if (type === 'get_node_allowlist') return { disabled_credential_categories: disabled };
+ if (type === 'get_stored_api_key') return { hasKey: false };
+ if (type === 'get_provider_defaults') return { defaults: { default_model: '', temperature: 0.5, max_tokens: 2048 } };
+ if (type === 'get_validated_ai_providers') return { providers: [], global_provider: null, global_model: null };
+ if (type === 'get_provider_usage_summary') return { providers: [] };
+ return { success: true };
+ });
+ ws.validateApiKey.mockResolvedValue({ valid: false, message: 'That key was rejected.' });
+});
-vi.mock('../../hooks/useWhatsApp', () => ({
- useWhatsApp: () => ({
- getStatus: vi.fn().mockResolvedValue({}),
- getQRCode: vi.fn().mockResolvedValue(null),
- sendMessage: vi.fn().mockResolvedValue(true),
- startConnection: vi.fn().mockResolvedValue(undefined),
- restartConnection: vi.fn().mockResolvedValue(undefined),
- isLoading: false,
- lastError: null,
- connectionStatus: { connected: false },
- }),
-}));
+describe('shared credentials host', () => {
+ it('browses the same cards in either mode and offers Manage for connected providers', async () => {
+ mount(); await open();
+ expect(await screen.findByRole('button', { name: 'Connect OpenAI' })).toBeVisible();
+ await userEvent.click(screen.getByRole('button', { name: 'Manage Telegram' }));
+ expect(await screen.findByRole('dialog', { name: 'Manage Telegram' })).toBeVisible();
+ expect(toast.success).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole('button', { name: 'All connectors' }));
+ act(() => useAppStore.setState({ shellMode: 'dev' }));
+ expect(screen.getByRole('button', { name: 'Manage Telegram' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Connect OpenAI' })).toBeVisible();
+ expect(ws.sendRequest.mock.calls.some(([type]) => /oauth_status|telegram_status/.test(type))).toBe(false);
+ });
-vi.mock('../../hooks/useAppTheme', () => ({
- useAppTheme: () => ({
- isDarkMode: false,
- colors: {
- background: '#fff',
- backgroundAlt: '#fafafa',
- backgroundPanel: '#f5f5f5',
- text: '#000',
- textSecondary: '#666',
- primary: '#1890ff',
- border: '#d9d9d9',
- secondary: '#666',
- },
- dracula: {
- purple: '#bd93f9',
- cyan: '#8be9fd',
- green: '#50fa7b',
- pink: '#ff79c6',
- orange: '#ffb86c',
- yellow: '#f1fa8c',
- red: '#ff5555',
- },
- accent: { blue: '#268bd2', cyan: '#2aa198', green: '#859900' },
- fontSize: { xs: 10, sm: 12, md: 14, lg: 16, xl: 18 },
- fontWeight: { normal: 400, medium: 500, semibold: 600, bold: 700 },
- spacing: { xs: 4, sm: 8, md: 12, lg: 16, xl: 24 },
- borderRadius: { sm: 4, md: 6, lg: 8 },
- transitions: { fast: '0.15s ease', medium: '0.3s ease' },
- }),
-}));
+ it('adds technical sections on mode change without remounting or clearing the connection draft', async () => {
+ mount({ providerId: 'openai' }); await open();
+ const input = await keyInput();
+ await userEvent.type(input, 'draft-secret');
+ expect(screen.queryByText('Usage & Costs')).not.toBeInTheDocument();
+ expect(ws.sendRequest.mock.calls.some(([type]) => type === 'get_provider_defaults')).toBe(false);
+ act(() => useAppStore.setState({ shellMode: 'dev' }));
+ expect(await screen.findByText('Usage & Costs')).toBeVisible();
+ await waitFor(() => expect(ws.sendRequest).toHaveBeenCalledWith('get_provider_defaults', { provider: 'openai' }));
+ expect(await keyInput()).toBe(input);
+ expect(input).toHaveValue('draft-secret');
+ act(() => useAppStore.setState({ shellMode: 'normal' }));
+ expect(screen.queryByText('Usage & Costs')).not.toBeInTheDocument();
+ expect(input).toHaveValue('draft-secret');
+ expect(ws.sendRequest.mock.calls.some(([type]) => type === 'save_provider_defaults')).toBe(false);
+ });
-// Now import the component
-import CredentialsModal from '../CredentialsModal';
+ it('shows Dev sections when Home is disabled', async () => {
+ featureFlags.normalMode = false;
+ mount({ providerId: 'openai' }); await open();
+ expect(await screen.findByText('Usage & Costs')).toBeVisible();
+ });
-beforeEach(() => {
- Object.values(apiHookMock).forEach((v) => {
- if (typeof v === 'function' && 'mockClear' in v) {
- (v as ReturnType<typeof vi.fn>).mockClear();
- }
+ it('waits for a directly requested provider instead of selecting a different one', async () => {
+ let resolve!: (value: CatalogueResponse) => void;
+ const pending = new Promise<CatalogueResponse>((done) => { resolve = done; });
+ const original = ws.sendRequest.getMockImplementation()!;
+ ws.sendRequest.mockImplementation((type: string, ...args: unknown[]) => type === 'get_credential_catalogue' ? pending : original(type, ...args));
+ mount({ providerId: 'openai', intent: 'connect' }); await open();
+ expect(screen.getByRole('status', { name: 'Loading connector' })).toBeVisible();
+ expect(screen.queryByText('Connector unavailable')).not.toBeInTheDocument();
+ await act(async () => resolve(catalogue));
+ expect(await screen.findByRole('dialog', { name: 'Connect OpenAI' })).toBeVisible();
+ expect(await keyInput()).toBeVisible();
});
- wsMock.sendRequest.mockClear();
- wsMock.sendRequest.mockResolvedValue({});
-});
+ it.each(['missing', 'disabled'])('explains a %s direct target without mounting its credential form', async (kind) => {
+ if (kind === 'disabled') disabled = ['ai'];
+ mount({ providerId: kind === 'missing' ? 'unknown' : 'openai' }); await open();
+ expect(await screen.findByText('Connector unavailable')).toBeVisible();
+ expect(screen.queryByPlaceholderText('Enter API key...')).not.toBeInTheDocument();
+ });
-describe('CredentialsModal smoke', () => {
- it('renders when visible=true without crashing', () => {
- render(<CredentialsModal visible={true} onClose={vi.fn()} />);
- // Scaling-v2 fetches the provider catalogue async via useCatalogueQuery,
- // so a freshly-mounted modal may show "loading" before any provider names.
- // What we really assert is that the modal DOES mount (no exception) and a
- // dialog or credentials surface lands in the DOM.
- expect(document.body.textContent).toMatch(
- /credentials|providers|loading|OpenAI|Twitter|Gmail|WhatsApp|Android/i,
- );
+ it.each(['connect', 'manage'] as const)('only auto-closes successful guided connections (%s)', async (intent) => {
+ const queryClient = mount({ providerId: 'openai', intent }); await open();
+ await keyInput();
+ act(() => queryClient.setQueryData(CATALOGUE_QUERY_KEY, {
+ ...catalogue, providers: catalogue.providers.map((p) => p.id === 'openai' ? { ...p, connected: true, stored: true } : p),
+ }));
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('OpenAI is connected'));
+ expect(useShellDialogsStore.getState().credentialsOpen).toBe(intent === 'manage');
+ expect(toast.success).toHaveBeenCalledTimes(1);
});
- it('renders nothing visible when visible=false', () => {
- const { container } = render(
- <CredentialsModal visible={false} onClose={vi.fn()} />,
- );
- // Modal hidden; no major content in our render tree
- expect(container.querySelector('[role="dialog"]')).toBeNull();
+ it('waits for category restrictions before mounting a direct target from cached data', async () => {
+ let resolve!: (value: unknown) => void;
+ const pending = new Promise((done) => { resolve = done; });
+ const original = ws.sendRequest.getMockImplementation()!;
+ ws.sendRequest.mockImplementation((type: string, ...args: unknown[]) => type === 'get_node_allowlist' ? pending : original(type, ...args));
+ const queryClient = mount({ providerId: 'openai' });
+ act(() => queryClient.setQueryData(CATALOGUE_QUERY_KEY, catalogue));
+ await open();
+ expect(screen.getByRole('status', { name: 'Loading connector' })).toBeVisible();
+ expect(ws.sendRequest.mock.calls.some(([type]) => type === 'get_stored_api_key')).toBe(false);
+ await act(async () => resolve({ disabled_credential_categories: ['ai'] }));
+ expect(await screen.findByText('Connector unavailable')).toBeVisible();
+ expect(ws.sendRequest.mock.calls.some(([type]) => type === 'get_stored_api_key')).toBe(false);
});
- it('does NOT eagerly fetch status objects on mount (invariant 5)', () => {
- render(<CredentialsModal visible={true} onClose={vi.fn()} />);
- // Status comes from useWebSocket subscriptions, not from explicit *_status requests.
- const statusFetches = wsMock.sendRequest.mock.calls.filter(([type]: any[]) =>
- ['twitter_oauth_status', 'google_oauth_status', 'telegram_status'].includes(type),
- );
- expect(statusFetches).toHaveLength(0);
+ it('keeps AI guidance and key links, and a refused save preserves the input and shows its reason', async () => {
+ mount({ categoryId: 'ai', intent: 'connect' }); await open();
+ expect(await screen.findByText(/Your employees need an AI model/)).toBeVisible();
+ expect(screen.queryByRole('button', { name: 'Manage Telegram' })).not.toBeInTheDocument();
+ await userEvent.click(await screen.findByRole('button', { name: 'Connect OpenAI' }));
+ expect(screen.getByRole('link', { name: 'Get a key from OpenAI' })).toHaveAttribute('href', 'https://platform.openai.com/api-keys');
+ await userEvent.type(await keyInput(), 'rejected-key');
+ await userEvent.click(screen.getByRole('button', { name: 'Validate' }));
+ expect(await screen.findByText('That key was rejected.')).toBeVisible();
+ expect(await keyInput()).toHaveValue('rejected-key');
+ expect(useShellDialogsStore.getState().credentialsOpen).toBe(true);
});
-});
+ it('closes with Escape and restores focus to the original entry point', async () => {
+ mount({ providerId: 'openai' }); await open(); await keyInput();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Open credentials' })).toHaveFocus());
+ });
+
+ it('closes the provider before the browser and supports the real close button', async () => {
+ mount(); await open();
+ await userEvent.click(await screen.findByRole('button', { name: 'Manage Telegram' }));
+ const detail = await screen.findByRole('dialog', { name: 'Manage Telegram' });
+ await userEvent.click(within(detail).getByRole('button', { name: 'Close' }));
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Manage Telegram' })).not.toBeInTheDocument());
+ expect(screen.getByRole('dialog', { name: 'Connectors' })).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Open credentials' })).toHaveFocus());
+ });
-describe('CredentialsModal -- close handling', () => {
- it('invokes onClose when antd Modal close is requested', async () => {
- const onClose = vi.fn();
- render(<CredentialsModal visible={true} onClose={onClose} />);
- // antd Modal renders a close button with aria-label "Close"
- const closeBtn = document.querySelector('.ant-modal-close') as HTMLElement | null;
- if (closeBtn) {
- await userEvent.click(closeBtn);
- expect(onClose).toHaveBeenCalled();
- } else {
- // If antd structure changes, this is a soft pass -- the smoke test above
- // already validated the modal mounts. Document the assumption for refactor.
- expect(true).toBe(true);
- }
+ it('retains the original focus target when a direct provider opens the browser', async () => {
+ mount({ providerId: 'openai' }); await open(); await keyInput();
+ await userEvent.click(screen.getByRole('button', { name: 'All connectors' }));
+ const browser = await screen.findByRole('dialog', { name: 'Connectors' });
+ await waitFor(() => expect(browser.contains(document.activeElement)).toBe(true));
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Open credentials' })).toHaveFocus());
});
});
diff --git a/client/src/components/catalog/CatalogLayout.tsx b/client/src/components/catalog/CatalogLayout.tsx
new file mode 100644
index 00000000..e812460a
--- /dev/null
+++ b/client/src/components/catalog/CatalogLayout.tsx
@@ -0,0 +1,418 @@
+/**
+ * The shared catalog page behind Settings > Skills, Connectors and Plugins
+ * (design handoff "Settings: Billing, Skills, Plugins"): a title with Yours /
+ * Discover, search, an optional category filter and primary action, and a
+ * grid of cards.
+ *
+ * Every rule follows from the props and the item data, never from which
+ * page is showing:
+ * - the page supplies both lists, and Yours counts its own;
+ * - the category filter exists when there are categories, and starts open
+ * when the page is opened on one;
+ * - Discover shows DISCOVER_LIMIT cards until "Show all";
+ * - a card offers remove only with `onRemove`, and a switch only with
+ * `onToggle`;
+ * - a card glows when its item turns 'added' while it is on screen, then
+ * `onItemAdded` runs (never on first render).
+ *
+ * The view, search and filter live here, so they start fresh each time the
+ * page mounts (the Settings tabs unmount when hidden).
+ */
+
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
+import { ArrowRight, BadgeCheck, Check, LoaderCircle, Plus, SlidersHorizontal } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Switch } from '@/components/ui/switch';
+import { Toggle } from '@/components/ui/toggle';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { animate } from '@/lib/motion';
+import { cn } from '@/lib/utils';
+import { AppMark, SearchField } from './primitives';
+import { DISCOVER_LIMIT, catalogSlice, type CatalogItem, type CatalogView } from './catalog';
+import { staggerSettings } from './stagger';
+
+export interface CatalogLayoutProps {
+ title: string;
+ /** Also the search box's accessible name. */
+ searchPlaceholder: string;
+ yours: { items: CatalogItem[]; sectionTitle: string; empty: { title: string; detail: string } };
+ discover: { items: CatalogItem[]; sectionTitle: string };
+ loading?: boolean;
+ categories?: { key: string; label: string }[];
+ initialCategory?: string;
+ verbs: { add: string; remove?: string; busy?: string };
+ onAdd: (item: CatalogItem) => void;
+ onRemove?: (item: CatalogItem) => void;
+ /** Opens the settings of an already-added item, without removing it. */
+ onManage?: (item: CatalogItem) => void;
+ onToggle?: (item: CatalogItem, on: boolean) => void;
+ onItemAdded?: (item: CatalogItem) => void;
+ /** A header button that opens an inline form above the list. */
+ primaryAction?: { label: string; form: (close: () => void) => ReactNode };
+}
+
+const GRID = '-mt-2 grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-3';
+
+export function CatalogLayout({
+ title,
+ searchPlaceholder,
+ yours,
+ discover,
+ loading = false,
+ categories = [],
+ initialCategory = 'all',
+ verbs,
+ onAdd,
+ onRemove,
+ onManage,
+ onToggle,
+ onItemAdded,
+ primaryAction,
+}: CatalogLayoutProps) {
+ const [view, setView] = useState<CatalogView>('discover');
+ const [category, setCategory] = useState(initialCategory);
+ const [filterOpen, setFilterOpen] = useState(initialCategory !== 'all');
+ const [query, setQuery] = useState('');
+ const [showAll, setShowAll] = useState(false);
+ const [formOpen, setFormOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const shownKey = useRef(`${view}|${category}`);
+
+ // The blocks rise in again on a new view or category. The first render is
+ // the dialog's to stagger.
+ useLayoutEffect(() => {
+ const key = `${view}|${category}`;
+ if (shownKey.current === key) return;
+ shownKey.current = key;
+ staggerSettings(rootRef.current);
+ }, [view, category]);
+
+ const list = view === 'yours' ? yours.items : discover.items;
+ const { shown, total } = catalogSlice(list, { category, query, cap: view === 'discover' && !showAll ? DISCOVER_LIMIT : null });
+ const canShowAll = view === 'discover' && total > DISCOVER_LIMIT;
+ const q = query.trim();
+
+ const changeView = (next: CatalogView) => {
+ setView(next);
+ setShowAll(false);
+ };
+ const toggleFilter = (open: boolean) => {
+ setFilterOpen(open);
+ if (!open) setCategory('all');
+ };
+
+ const filtered = q !== '' || category !== 'all';
+ const empty = filtered
+ ? {
+ title: q ? `Nothing matches “${q}”` : 'Nothing in this category',
+ detail: q ? 'Try another word.' : 'Try another category.',
+ discover: false,
+ }
+ : view === 'yours'
+ ? { ...yours.empty, discover: true }
+ : { title: 'Nothing here yet', detail: 'Check back soon.', discover: false };
+
+ return (
+ <div ref={rootRef} className="flex flex-col gap-5.5 px-4 pt-6.5 pb-8 sm:px-8">
+ <div data-stagger className="flex flex-wrap items-center gap-3.5 pr-10">
+ <h2 className="text-xl font-semibold tracking-[-0.02em] text-fg-default">{title}</h2>
+ <ToggleGroup
+ type="single"
+ variant="segmented"
+ aria-label={`${title} to show`}
+ value={view}
+ onValueChange={(next) => next && changeView(next as CatalogView)}
+ >
+ <ToggleGroupItem value="yours" className="px-3 text-sm">
+ Yours
+ <span className="font-mono text-2xs font-normal text-fg-faint">{yours.items.length}</span>
+ </ToggleGroupItem>
+ <ToggleGroupItem value="discover" className="px-3 text-sm">
+ Discover
+ </ToggleGroupItem>
+ </ToggleGroup>
+ <div className="ml-auto flex flex-[1_1_280px] items-center justify-end gap-2">
+ <SearchField value={query} onChange={setQuery} placeholder={searchPlaceholder} className="max-w-75 flex-1" />
+ {categories.length > 0 && (
+ <Toggle
+ variant="chips"
+ pressed={filterOpen}
+ onPressedChange={toggleFilter}
+ aria-label="Filter by category"
+ title="Filter"
+ className="size-9 rounded-row px-0 [&_svg:not([class*='size-'])]:size-4"
+ >
+ <SlidersHorizontal strokeWidth={1.75} />
+ </Toggle>
+ )}
+ {primaryAction && (
+ <Button
+ variant="invert"
+ size="lg"
+ aria-expanded={formOpen}
+ onClick={() => setFormOpen((open) => !open)}
+ className="rounded-row pr-3.5 pl-3 font-semibold active:scale-97"
+ >
+ <Plus strokeWidth={2.2} />
+ {primaryAction.label}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {categories.length > 0 && filterOpen && (
+ <ToggleGroup
+ data-stagger
+ type="single"
+ variant="chips"
+ size="lg"
+ className="-mt-2 gap-2"
+ aria-label="Category"
+ value={category}
+ onValueChange={(next) => next && setCategory(next)}
+ >
+ <ToggleGroupItem value="all">All</ToggleGroupItem>
+ {categories.map((c) => (
+ <ToggleGroupItem key={c.key} value={c.key}>
+ {c.label}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ )}
+
+ {primaryAction && formOpen && (
+ <div data-stagger className="flex flex-col gap-2.5 rounded-card border border-border-strong bg-bg-elevated p-4">
+ {primaryAction.form(() => setFormOpen(false))}
+ </div>
+ )}
+
+ <div data-stagger className="flex items-center gap-2.5">
+ <span className="text-lead font-semibold whitespace-nowrap text-fg-default">
+ {view === 'yours' ? yours.sectionTitle : discover.sectionTitle}
+ </span>
+ <Badge variant="outline" className="rounded-md border-border-default bg-bg-app px-1.75 font-mono text-2xs text-fg-muted">
+ {total}
+ </Badge>
+ {canShowAll && (
+ <Button variant="quiet" size="sm" onClick={() => setShowAll((all) => !all)} className="ml-auto text-row text-fg-default">
+ {showAll ? 'Show less' : 'Show all'}
+ <ArrowRight />
+ </Button>
+ )}
+ </div>
+
+ {loading && list.length === 0 ? (
+ <div className={GRID}>
+ {[0, 1, 2, 3].map((i) => (
+ <Skeleton key={i} className="h-30 rounded-card" />
+ ))}
+ </div>
+ ) : total > 0 ? (
+ <div className={GRID}>
+ {shown.map((item) => (
+ <CatalogCard
+ key={item.id}
+ item={item}
+ view={view}
+ verbs={verbs}
+ onAdd={onAdd}
+ onRemove={onRemove}
+ onManage={onManage}
+ onToggle={onToggle}
+ onItemAdded={onItemAdded}
+ />
+ ))}
+ </div>
+ ) : (
+ <div
+ data-stagger
+ className="flex flex-col items-center gap-2.5 rounded-panel border border-dashed border-border-strong px-5 py-10 text-center"
+ >
+ <span className="text-base font-medium text-fg-default">{empty.title}</span>
+ <span className="text-sm text-fg-muted">{empty.detail}</span>
+ {empty.discover && (
+ <Button
+ variant="quiet"
+ size="sm"
+ onClick={() => changeView('discover')}
+ className="mt-1 h-8 border-border-strong px-3.5 font-semibold text-fg-default"
+ >
+ Discover
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function CatalogCard({
+ item,
+ view,
+ verbs,
+ onAdd,
+ onRemove,
+ onManage,
+ onToggle,
+ onItemAdded,
+}: {
+ item: CatalogItem;
+ view: CatalogView;
+ verbs: CatalogLayoutProps['verbs'];
+ onAdd: CatalogLayoutProps['onAdd'];
+ onRemove?: CatalogLayoutProps['onRemove'];
+ onManage?: CatalogLayoutProps['onManage'];
+ onToggle?: CatalogLayoutProps['onToggle'];
+ onItemAdded?: CatalogLayoutProps['onItemAdded'];
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const lastState = useRef(item.state);
+ const added = item.state === 'added';
+
+ useEffect(() => {
+ const before = lastState.current;
+ lastState.current = item.state;
+ if (item.state !== 'added' || before === 'added') return;
+ animate(ref.current, [{ boxShadow: 'var(--glow-connect)' }, { boxShadow: '0 0 0 0 transparent' }], {
+ duration: 1200,
+ easing: 'default',
+ fill: 'none',
+ });
+ onItemAdded?.(item);
+ }, [item, onItemAdded]);
+
+ return (
+ <div
+ ref={ref}
+ data-catalog-item={item.id}
+ data-stagger
+ className={cn(
+ 'flex gap-3.5 rounded-card border bg-bg-elevated p-4.5 transition-[border-color,translate,box-shadow] duration-(--dur-default) ease-(--ease-default) hover:-translate-y-0.5 hover:border-border-strong hover:shadow-popover motion-reduce:hover:translate-y-0',
+ added ? 'border-status-working-border' : 'border-border-default',
+ )}
+ >
+ <AppMark name={item.name} iconRef={item.tile.iconRef} tone={item.tile.tone} size="xl" />
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-lead font-semibold text-fg-default">{item.name}</span>
+ {item.verified && (
+ <BadgeCheck role="img" aria-label="Verified" strokeWidth={1.75} className="size-3.75 shrink-0 text-fg-faint" />
+ )}
+ </div>
+ {item.description && <p className="line-clamp-2 text-row leading-snug text-fg-muted">{item.description}</p>}
+ {item.byline && <span className="mt-0.5 text-sm text-fg-faint">{item.byline}</span>}
+ {item.meta && <span className="mt-0.5 font-mono text-2xs text-fg-faint">{item.meta}</span>}
+ </div>
+ <div className="flex shrink-0 flex-col items-end gap-2">
+ <CardAction item={item} view={view} verbs={verbs} onAdd={onAdd} onRemove={onRemove} onManage={onManage} onToggle={onToggle} />
+ </div>
+ </div>
+ );
+}
+
+const DONE = 'size-8.5 rounded-lg border border-action-run-border bg-action-run-soft text-action-run-ink';
+
+function CardAction({
+ item,
+ view,
+ verbs,
+ onAdd,
+ onRemove,
+ onManage,
+ onToggle,
+}: {
+ item: CatalogItem;
+ view: CatalogView;
+ verbs: CatalogLayoutProps['verbs'];
+ onAdd: CatalogLayoutProps['onAdd'];
+ onRemove?: CatalogLayoutProps['onRemove'];
+ onManage?: CatalogLayoutProps['onManage'];
+ onToggle?: CatalogLayoutProps['onToggle'];
+}) {
+ const removeVerb = verbs.remove ?? 'Remove';
+ if (item.state === 'busy') {
+ return (
+ <span
+ role="status"
+ aria-label={`${item.name}: ${verbs.busy ?? 'Working…'}`}
+ className="grid size-8.5 place-items-center rounded-lg border border-status-ready-border bg-status-ready-fill"
+ >
+ <LoaderCircle aria-hidden className="size-3.5 animate-spin text-status-ready-ink" />
+ </span>
+ );
+ }
+ if (item.state === 'added' && onManage) {
+ return (
+ <>
+ <Button variant="quiet" size="sm" aria-label={`Manage ${item.name}`} onClick={() => onManage(item)}>
+ Manage
+ </Button>
+ {onRemove && (
+ <Button
+ variant="quiet"
+ size="xs"
+ aria-label={`${removeVerb} ${item.name}`}
+ onClick={() => onRemove(item)}
+ className="text-fg-faint hover:bg-action-stop-soft hover:text-action-stop-ink"
+ >
+ {removeVerb}
+ </Button>
+ )}
+ </>
+ );
+ }
+ if (view === 'discover') {
+ if (item.state === 'available') {
+ return (
+ <Button
+ variant="quiet"
+ size="icon"
+ aria-label={`${verbs.add} ${item.name}`}
+ title={`${verbs.add} ${item.name}`}
+ onClick={() => onAdd(item)}
+ className="size-8.5 border-border-strong bg-bg-app text-fg-default hover:border-action-run-border hover:bg-action-run-soft hover:text-action-run-ink active:scale-92"
+ >
+ <Plus />
+ </Button>
+ );
+ }
+ return onRemove ? (
+ <Button
+ variant="quiet"
+ size="icon"
+ aria-label={`${removeVerb} ${item.name}`}
+ title={`${removeVerb} ${item.name}`}
+ onClick={() => onRemove(item)}
+ className={cn(DONE, 'hover:border-action-stop-border hover:bg-action-stop-soft hover:text-action-stop-ink')}
+ >
+ <Check strokeWidth={2.2} />
+ </Button>
+ ) : (
+ <span role="img" aria-label={`${item.name} added`} className={cn('grid place-items-center', DONE)}>
+ <Check aria-hidden strokeWidth={2.2} className="size-4" />
+ </span>
+ );
+ }
+ return (
+ <>
+ {onToggle && (
+ <Switch size="md" tone="run" checked={item.enabled ?? false} onCheckedChange={(on) => onToggle(item, on)} aria-label={item.name} />
+ )}
+ {onRemove && (
+ <Button
+ variant="quiet"
+ size="xs"
+ aria-label={`${removeVerb} ${item.name}`}
+ onClick={() => onRemove(item)}
+ className="mt-auto h-6.5 px-2 text-xs text-fg-faint hover:bg-action-stop-soft hover:text-action-stop-ink"
+ >
+ {removeVerb}
+ </Button>
+ )}
+ </>
+ );
+}
+
+export default CatalogLayout;
diff --git a/client/src/components/catalog/catalog.ts b/client/src/components/catalog/catalog.ts
new file mode 100644
index 00000000..4ab0ce88
--- /dev/null
+++ b/client/src/components/catalog/catalog.ts
@@ -0,0 +1,46 @@
+/**
+ * The shared catalog behind Settings > Skills, Connectors and Plugins
+ * (design handoff "Settings: Billing, Skills, Plugins"): what one card
+ * shows, and how a list is narrowed for display. Each page maps its own
+ * records to `CatalogItem`s; nothing here knows which page it is on.
+ */
+
+import type { ColorRole } from './presentation';
+
+export type CatalogView = 'yours' | 'discover';
+
+export interface CatalogItem {
+ id: string;
+ name: string;
+ description?: string;
+ /** "by Google", "by you". Searched along with the name and description. */
+ byline?: string;
+ verified?: boolean;
+ /** A category key, for the filter chips. */
+ category?: string;
+ /** One short mono line under the byline. */
+ meta?: string;
+ /** A brand icon, or tinted initials when there is none. */
+ tile: { iconRef?: string | null; tone?: ColorRole };
+ state: 'available' | 'busy' | 'added';
+ /** The switch in Yours, shown only when the page can toggle items. */
+ enabled?: boolean;
+}
+
+/** Discover shows this many cards until "Show all". */
+export const DISCOVER_LIMIT = 8;
+
+/** Items in `category` ('all' for every one) matching `query`, the first
+ * `cap` of them when a cap is given. `total` counts every match. */
+export function catalogSlice(
+ items: CatalogItem[],
+ { category, query, cap }: { category: string; query: string; cap: number | null },
+): { shown: CatalogItem[]; total: number } {
+ const q = query.trim().toLowerCase();
+ const matched = items.filter((item) => {
+ if (category !== 'all' && item.category !== category) return false;
+ if (!q) return true;
+ return [item.name, item.description, item.byline].some((text) => text?.toLowerCase().includes(q));
+ });
+ return { shown: cap === null ? matched : matched.slice(0, cap), total: matched.length };
+}
diff --git a/client/src/components/catalog/presentation.ts b/client/src/components/catalog/presentation.ts
new file mode 100644
index 00000000..e53d0cd0
--- /dev/null
+++ b/client/src/components/catalog/presentation.ts
@@ -0,0 +1,11 @@
+/** Shared role colours for catalogue tiles and employee avatars. */
+export const COLOR_ROLES = ['agent', 'model', 'tool', 'trigger', 'workflow'] as const;
+export type ColorRole = (typeof COLOR_ROLES)[number];
+
+export const AVATAR_CLASS: Record<ColorRole, string> = {
+ agent: 'bg-node-agent-fill border-node-agent-edge text-node-agent-ink',
+ model: 'bg-node-model-fill border-node-model-edge text-node-model-ink',
+ tool: 'bg-node-tool-fill border-node-tool-edge text-node-tool-ink',
+ trigger: 'bg-node-trigger-fill border-node-trigger-edge text-node-trigger-ink',
+ workflow: 'bg-node-workflow-fill border-node-workflow-edge text-node-workflow-ink',
+};
diff --git a/client/src/components/catalog/primitives.tsx b/client/src/components/catalog/primitives.tsx
new file mode 100644
index 00000000..c5e5e5a2
--- /dev/null
+++ b/client/src/components/catalog/primitives.tsx
@@ -0,0 +1,76 @@
+/** Shared catalogue brand marks and search fields. */
+import { Search } from 'lucide-react';
+import { NodeIcon } from '@/assets/icons';
+import { Input } from '@/components/ui/input';
+import { cn } from '@/lib/utils';
+import { theme } from '@/styles/theme';
+import { AVATAR_CLASS, type ColorRole } from './presentation';
+
+const MARK_SIZE = {
+ xs: { box: 'size-5', icon: theme.iconSize.xs },
+ sm: { box: 'size-5.5', icon: theme.iconSize.xs },
+ lg: { box: 'size-9.5 rounded-row', icon: theme.iconSize.md },
+ xl: { box: 'size-12.5 rounded-card text-sm', icon: theme.iconSize.lg },
+} as const;
+
+/** An app's brand mark (the credential catalogue's icon), in a disc. Falls
+ * back to the app's first two letters, tinted in `tone` when given (a
+ * skill or starter tile). */
+export function AppMark({
+ name,
+ iconRef,
+ size = 'sm',
+ tone,
+ className,
+}: {
+ name: string;
+ iconRef?: string | null;
+ size?: keyof typeof MARK_SIZE;
+ tone?: ColorRole;
+ className?: string;
+}) {
+ const spec = MARK_SIZE[size];
+ const letters = name.replace(/[^\p{L}\p{N}]/gu, '').slice(0, 2).toUpperCase();
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ 'grid shrink-0 place-items-center rounded-full border font-mono text-2xs font-semibold',
+ tone ? AVATAR_CLASS[tone] : 'border-border-default bg-bg-panel text-fg-muted',
+ spec.box,
+ className,
+ )}
+ >
+ <NodeIcon icon={iconRef} size={spec.icon} fallback={<span>{letters}</span>} />
+ </span>
+ );
+}
+
+/** A search box for settings and catalogue surfaces. The
+ * placeholder doubles as its accessible name unless `label` says otherwise. */
+export function SearchField({
+ value,
+ onChange,
+ placeholder,
+ label,
+ className,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder: string;
+ label?: string;
+ className?: string;
+}) {
+ return (
+ <div className={cn('relative min-w-0', className)}>
+ <Search aria-hidden className="pointer-events-none absolute top-1/2 left-3 size-3.75 -translate-y-1/2 text-fg-faint" />
+ <Input
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ placeholder={placeholder}
+ aria-label={label ?? placeholder}
+ className="h-9 rounded-row bg-bg-app pl-8.5 text-row font-normal md:text-row dark:bg-bg-app"
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/catalog/stagger.ts b/client/src/components/catalog/stagger.ts
new file mode 100644
index 00000000..96044e70
--- /dev/null
+++ b/client/src/components/catalog/stagger.ts
@@ -0,0 +1,20 @@
+/**
+ * Settings blocks rise in, 30ms apart (design handoff "Settings modal"):
+ * every `[data-stagger]` under `root`. HomeSettings plays it when the dialog
+ * opens or the tab changes; a catalog page plays it again when its view or
+ * category changes.
+ */
+
+import { stagger } from '@/lib/motion';
+
+export function staggerSettings(root: ParentNode | null | undefined): void {
+ if (!root) return;
+ stagger(
+ root.querySelectorAll('[data-stagger]'),
+ [
+ { opacity: 0, transform: 'translateY(10px)' },
+ { opacity: 1, transform: 'none' },
+ ],
+ { base: 40, step: 30, cap: 14, duration: 420, easing: 'spring' },
+ );
+}
diff --git a/client/src/components/credentials/CredentialsBrowser.tsx b/client/src/components/credentials/CredentialsBrowser.tsx
new file mode 100644
index 00000000..ff19878b
--- /dev/null
+++ b/client/src/components/credentials/CredentialsBrowser.tsx
@@ -0,0 +1,168 @@
+/**
+ * The shared credentials browser in Home and Dev. Discover lists every
+ * visible provider, apps before AI models; Yours lists connected ones.
+ *
+ * Connect and Manage open the shared host with the corresponding intent.
+ * Disconnect removes what the panel would remove for API-key and signed-in
+ * providers, after a confirmation; for the rest (a paired phone, an email
+ * account) it opens the panel, which owns those steps. A card glows when
+ * it turns connected. Connection-success feedback belongs to the host.
+ * There is no custom connector:
+ * nothing serves one yet, so the page has no Add button.
+ */
+
+import { useMemo, useState } from 'react';
+import { toast } from 'sonner';
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@/components/ui/alert-dialog';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import { isConnected, useCredentialsCatalogue, type ConsumerProvider, type CredentialsCatalogue } from './catalogue';
+import type { CatalogItem } from '@/components/catalog/catalog';
+import { CatalogLayout } from '@/components/catalog/CatalogLayout';
+
+/** Remove a provider's credential the way its panel would. False when the
+ * panel has to do it (QR pairing, the IMAP/SMTP account). */
+async function disconnect(
+ provider: ConsumerProvider,
+ sendRequest: <T = unknown>(type: string, data?: Record<string, unknown>) => Promise<T>,
+): Promise<boolean> {
+ if (provider.kind === 'apiKey') {
+ // A named-endpoint provider owns several rows. Its panel removes each
+ // by reference; deleting the family id would leave those rows intact.
+ if (provider.endpoints) return false;
+ await sendRequest('delete_api_key', { provider: provider.id });
+ // Local model servers also keep their base URL under the field key.
+ const fieldKey = provider.fields?.[0]?.key;
+ if (fieldKey && fieldKey !== 'apiKey') await sendRequest('delete_api_key', { provider: fieldKey });
+ return true;
+ }
+ if (provider.kind === 'oauth' && provider.ws?.logout) {
+ await sendRequest(provider.ws.logout, {});
+ return true;
+ }
+ return false;
+}
+
+function toItem(provider: ConsumerProvider): CatalogItem {
+ const connected = isConnected(provider);
+ const meta = [
+ connected && provider.account_label ? `Connected as ${provider.account_label}` : null,
+ provider.runs_locally ? 'Runs on this computer' : null,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+ return {
+ id: provider.id,
+ name: provider.name,
+ description: provider.description,
+ byline: provider.publisher ? `by ${provider.publisher}` : undefined,
+ verified: provider.verified,
+ category: provider.consumer_category,
+ meta: meta || undefined,
+ tile: { iconRef: provider.icon_ref },
+ state: connected ? 'added' : 'available',
+ };
+}
+
+export interface CredentialsBrowserProps {
+ onConnect: (providerId: string, intent?: 'connect' | 'manage') => void;
+ initialCategory?: string;
+ /** The host can share its query/visibility result without another hook. */
+ catalogue?: CredentialsCatalogue;
+}
+
+export function CredentialsBrowser(props: CredentialsBrowserProps) {
+ return props.catalogue
+ ? <CredentialsBrowserContent {...props} catalogue={props.catalogue} />
+ : <ConnectedCredentialsBrowser {...props} />;
+}
+
+function ConnectedCredentialsBrowser(props: CredentialsBrowserProps) {
+ const catalogue = useCredentialsCatalogue();
+ return <CredentialsBrowserContent {...props} catalogue={catalogue} />;
+}
+
+function CredentialsBrowserContent({
+ onConnect,
+ initialCategory = 'all',
+ catalogue,
+}: CredentialsBrowserProps & { catalogue: CredentialsCatalogue }) {
+ const { providers, categories, isLoading, isError, refetch } = catalogue;
+ const { sendRequest } = useWebSocketActions();
+ const [confirming, setConfirming] = useState<ConsumerProvider | null>(null);
+ const byId = useMemo(() => new Map(providers.map((provider) => [provider.id, provider])), [providers]);
+ const items = useMemo(() => providers.map(toItem), [providers]);
+ const connected = useMemo(() => items.filter((item) => item.state === 'added'), [items]);
+
+ const confirmDisconnect = async () => {
+ const provider = confirming;
+ setConfirming(null);
+ if (!provider) return;
+ try {
+ const done = await disconnect(provider, sendRequest);
+ if (done) toast.info(`${provider.name} disconnected`);
+ else onConnect(provider.id, 'manage');
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : `Couldn't disconnect ${provider.name}`);
+ }
+ };
+
+ if (isError && !catalogue.catalogue.data) {
+ return (
+ <Alert variant="destructive" className="m-8 w-auto">
+ <AlertTitle>Couldn't load connectors</AlertTitle>
+ <AlertDescription>Check your connection and try again.</AlertDescription>
+ <Button variant="outline" onClick={() => void refetch()}>Try again</Button>
+ </Alert>
+ );
+ }
+
+ return (
+ <>
+ <CatalogLayout
+ title="Connectors"
+ searchPlaceholder="Search connectors"
+ loading={isLoading}
+ categories={categories}
+ initialCategory={initialCategory}
+ yours={{
+ items: connected,
+ sectionTitle: 'Connected',
+ empty: { title: 'No apps connected yet', detail: 'Connect the apps your employees should work in.' },
+ }}
+ discover={{ items, sectionTitle: 'Top connectors' }}
+ verbs={{ add: 'Connect', remove: 'Disconnect' }}
+ onAdd={(item) => onConnect(item.id, 'connect')}
+ onManage={(item) => onConnect(item.id, 'manage')}
+ onRemove={(item) => setConfirming(byId.get(item.id) ?? null)}
+ />
+
+ <AlertDialog open={confirming !== null} onOpenChange={(open) => !open && setConfirming(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Disconnect {confirming?.name}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Employees that use {confirming?.name} stop using it until you connect it again.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep it</AlertDialogCancel>
+ <AlertDialogAction onClick={() => void confirmDisconnect()}>Disconnect</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+export default CredentialsBrowser;
diff --git a/client/src/components/credentials/CredentialsModal.tsx b/client/src/components/credentials/CredentialsModal.tsx
index 3bdb2fa2..b132f1bc 100644
--- a/client/src/components/credentials/CredentialsModal.tsx
+++ b/client/src/components/credentials/CredentialsModal.tsx
@@ -1,186 +1,171 @@
-/**
- * CredentialsModal — thin shell.
- *
- * Post-Wave-12: the server-owned catalogue (`get_credential_catalogue`
- * → `useCatalogueQuery`) is the SINGLE source of truth for the
- * provider list. The retired `providers.tsx` static fallback no longer
- * exists — adding a new provider is a backend-only change.
- *
- * Cold-boot UX:
- * - With IDB hit (return visit): catalogue populated within ~50 ms
- * via the warm-start path in `useCatalogueQuery`.
- * - With IDB miss (first visit / cleared storage): a Skeleton
- * palette renders while the WS catalogue arrives (~200-500 ms).
- * - Server unreachable: explicit "couldn't reach server" error
- * state — never a stale fallback list (would mislead the user
- * about which providers they have configured).
- */
-
-import React, { useMemo } from 'react';
-import { Loader2, ShieldCheck, AlertTriangle } from 'lucide-react';
-
-import Modal from '../ui/Modal';
-import { Badge } from '@/components/ui/badge';
+/** One app-level host for browsing, connecting and managing credentials. */
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { ArrowLeft, ExternalLink, ShieldCheck } from 'lucide-react';
+import { toast } from 'sonner';
+import { useShellMode } from '@/app/ShellModeSwitch';
+import { FEATURED_AI_PROVIDERS } from '@/components/onboarding/aiProviderLinks';
+import Modal from '@/components/ui/Modal';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
+import { useShellDialogsStore, type CredentialsIntent, type CredentialsOptions } from '@/stores/shellDialogsStore';
+import CredentialsBrowser from './CredentialsBrowser';
+import { isConnected, useCredentialsCatalogue } from './catalogue';
+import { rehydrateProvider } from './catalogueAdapter';
import PanelRenderer from './PanelRenderer';
-import CredentialsPalette from './CredentialsPalette';
-import { rehydrateCatalogue } from './catalogueAdapter';
-import { useCatalogueQuery } from '../../hooks/useCatalogueQuery';
-import { useCredentialRegistry } from '../../store/useCredentialRegistry';
-import { useNodeAllowlist } from '../../hooks/useNodeAllowlist';
-
-interface Props {
- visible: boolean;
- onClose: () => void;
-}
-const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
- // UI state lives in the Zustand store (no catalogue data ever).
- const selectedId = useCredentialRegistry((s) => s.selectedId);
- const setSelectedId = useCredentialRegistry((s) => s.setSelectedId);
+interface Props { visible: boolean; onClose: () => void }
- // Server-owned catalogue with IDB warm-start. Single source of truth.
- const catalogue = useCatalogueQuery();
-
- // Rehydrate server JSON → runtime ProviderConfig shape. No client
- // fallback — if the data isn't here yet we render Skeleton, and if
- // the fetch errored we render an explicit error state.
- const rehydrated = useMemo(() => {
- if (!catalogue.data) return null;
- return rehydrateCatalogue(catalogue.data);
- }, [catalogue.data]);
+/** Each explicit open starts fresh navigation; switching mode does not. */
+export default function CredentialsModal(props: Props) {
+ const options = useShellDialogsStore((s) => s.credentialsOptions);
+ const requestId = useShellDialogsStore((s) => s.credentialsRequestId);
+ return <CredentialsSession key={requestId} {...props} options={options} />;
+}
- // Apply the absolute blocklist from server/config/node_allowlist.json
- // (`disabled_credential_categories`). Hides the entire category +
- // every provider belonging to it. Mode-independent; complements the
- // node-side `disabled_groups` so disabling Android removes both the
- // canvas nodes AND the credentials panel in one config edit.
- const { isCredentialCategoryDisabled } = useNodeAllowlist();
- const providers = useMemo(
- () =>
- (rehydrated?.providers ?? []).filter(
- (p) => !isCredentialCategoryDisabled(p.category),
- ),
- [rehydrated?.providers, isCredentialCategoryDisabled],
- );
- const categories = useMemo(
- () =>
- (rehydrated?.categories ?? []).filter(
- (c) => !isCredentialCategoryDisabled(c.key),
- ),
- [rehydrated?.categories, isCredentialCategoryDisabled],
+function CredentialsSession({ visible, onClose, options }: Props & { options: CredentialsOptions }) {
+ const view = useCredentialsCatalogue();
+ const showTechnicalSections = useShellMode() === 'dev';
+ const [browsing, setBrowsing] = useState(!options.providerId);
+ const [selection, setSelection] = useState<{ id: string; intent: CredentialsIntent } | null>(
+ options.providerId ? { id: options.providerId, intent: options.intent ?? 'manage' } : null,
);
+ const browserOpener = useRef<HTMLElement | null>(null);
+ const providerOpener = useRef<HTMLElement | null>(null);
+ const sessionOpener = useRef<HTMLElement | null>(null);
+ const provider = view.providers.find((p) => p.id === selection?.id) ?? null;
+ const config = useMemo(() => provider ? rehydrateProvider(provider) : null, [provider]);
+ const featured = FEATURED_AI_PROVIDERS.find((p) => p.id === provider?.id);
+ const connected = provider ? isConnected(provider) : false;
+ const seen = useRef({ id: selection?.id, known: false, connected: false });
- // Default selection: if nothing is selected yet (or the previous
- // selection isn't in the current catalogue), pick the first provider.
- const effectiveSelectedId = useMemo(() => {
- if (selectedId && providers.some((p) => p.id === selectedId)) return selectedId;
- return providers[0]?.id ?? null;
- }, [selectedId, providers]);
+ const closeProvider = useCallback(() => {
+ if (browsing) setSelection(null);
+ else onClose();
+ }, [browsing, onClose]);
- // Keep the store in sync without causing a render loop — only update
- // when the effective id diverges from the stored one.
- React.useEffect(() => {
- if (effectiveSelectedId && effectiveSelectedId !== selectedId) {
- setSelectedId(effectiveSelectedId);
+ useEffect(() => {
+ const before = seen.current;
+ seen.current = { id: selection?.id, known: visible && provider !== null, connected };
+ if (!visible || !provider || before.id !== selection?.id || !before.known || before.connected || !connected) return;
+ toast.success(`${provider.name} is connected`);
+ if (selection?.intent === 'connect') {
+ if (options.intent === 'connect') onClose();
+ else closeProvider();
}
- }, [effectiveSelectedId, selectedId, setSelectedId]);
-
- const selected = useMemo(
- () => providers.find((p) => p.id === effectiveSelectedId) ?? null,
- [providers, effectiveSelectedId],
- );
+ }, [visible, provider, selection, connected, options.intent, onClose, closeProvider]);
- const isLoadingServer = catalogue.isLoading && !catalogue.data;
- const hasServerError = catalogue.isError && !catalogue.data;
+ const allProviders = () => { setBrowsing(true); setSelection(null); };
+ const aiSetup = options.categoryId === 'ai' && options.intent === 'connect';
+ const hasData = Boolean(view.catalogue.data) && !view.isLoading;
- const headerActions = (
- <div className="flex items-center gap-3">
- <div className="flex items-center gap-2 text-base font-semibold">
- <ShieldCheck className="h-4 w-4 text-warning" />
- <span>API Credentials</span>
- </div>
- {rehydrated && (
- <Badge variant="success">{providers.length} providers</Badge>
- )}
- {isLoadingServer && (
- <Badge variant="info" className="gap-1">
- <Loader2 className="h-3 w-3 animate-spin" />
- loading
- </Badge>
- )}
- {hasServerError && (
- <Badge variant="destructive" className="gap-1" title="Server unreachable">
- <AlertTriangle className="h-3 w-3" />
- offline
- </Badge>
- )}
- </div>
- );
+ return (
+ <>
+ <Modal
+ isOpen={visible && browsing}
+ onClose={onClose}
+ title={aiSetup ? 'Connect an AI model' : 'Connectors'}
+ titleIcon={<ShieldCheck className="size-4" />}
+ motion="spring"
+ maxWidth="min(1040px, calc(100vw - 2rem))"
+ maxHeight="min(760px, calc(100dvh - 2rem))"
+ onOpenAutoFocus={() => {
+ browserOpener.current = document.activeElement as HTMLElement | null;
+ sessionOpener.current ??= browserOpener.current;
+ }}
+ onCloseAutoFocus={(event) => {
+ if (sessionOpener.current?.isConnected) {
+ event.preventDefault();
+ sessionOpener.current.focus();
+ }
+ }}
+ >
+ {aiSetup && (
+ <div className="px-5 pt-5 sm:px-8">
+ <p className="text-sm text-fg-muted">
+ Your employees need an AI model to think. Pick a provider, then connect with its API key,
+ or choose a model that runs on this computer.
+ </p>
+ </div>
+ )}
+ <CredentialsBrowser catalogue={view} initialCategory={options.categoryId}
+ onConnect={(id, intent = 'connect') => setSelection({ id, intent })} />
+ </Modal>
- // Body dispatch:
- // 1. Server error + no cached data → error state, no providers shown.
- // 2. Loading + no cached data → Skeleton palette + empty detail.
- // 3. Catalogue available (cached or fresh) → normal UI.
- let body: React.ReactNode;
- if (hasServerError) {
- body = (
- <div className="flex flex-1 flex-col items-center justify-center p-8">
- <Alert variant="destructive" className="max-w-md">
- <AlertTriangle className="h-4 w-4" />
- <AlertTitle>Couldn't reach the credentials server</AlertTitle>
- <AlertDescription>
- The provider list comes from the backend. Check your connection
- and try again — refreshing the page will retry the fetch.
- </AlertDescription>
- </Alert>
- </div>
- );
- } else if (!rehydrated) {
- body = (
- <div className="flex h-full overflow-hidden">
- <div className="flex w-[280px] shrink-0 flex-col gap-2 border-r border-border p-4">
- {Array.from({ length: 6 }).map((_, i) => (
- <Skeleton key={i} className="h-9 w-full" />
- ))}
- </div>
- <div className="flex flex-1 flex-col gap-3 bg-background p-6">
- <Skeleton className="h-6 w-48" />
- <Skeleton className="h-4 w-72" />
- <Skeleton className="mt-4 h-32 w-full" />
- </div>
- </div>
- );
- } else {
- body = (
- <div className="flex h-full overflow-hidden">
- <div className="flex w-[280px] shrink-0 flex-col border-r border-border">
- <CredentialsPalette
- providers={providers}
- categories={categories}
- selectedId={effectiveSelectedId}
- onSelect={setSelectedId}
- />
- </div>
- <div className="flex flex-1 flex-col overflow-auto bg-background">
- <PanelRenderer config={selected} visible={visible} />
+ <Modal
+ isOpen={visible && selection !== null}
+ onClose={closeProvider}
+ title={provider ? `${selection?.intent === 'manage' ? 'Manage' : 'Connect'} ${provider.name}` : 'Connector'}
+ titleIcon={null}
+ motion="spring"
+ maxWidth="min(640px, calc(100vw - 2rem))"
+ maxHeight="min(800px, calc(100dvh - 2rem))"
+ autoHeight
+ onOpenAutoFocus={() => {
+ providerOpener.current = document.activeElement as HTMLElement | null;
+ sessionOpener.current ??= providerOpener.current;
+ }}
+ onCloseAutoFocus={(event) => {
+ // Closing both layers returns to the screen, not to a disappearing card.
+ event.preventDefault();
+ if ((!visible && browsing) || (browsing && providerOpener.current === sessionOpener.current)) return;
+ if (providerOpener.current?.isConnected) providerOpener.current.focus();
+ }}
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-5 pt-4">
+ <Button variant="quiet" size="sm" onClick={allProviders} className="-ml-2 gap-1">
+ <ArrowLeft aria-hidden className="size-4" />
+ {options.categoryId === 'ai' ? 'All AI models' : 'All connectors'}
+ </Button>
+ {featured && (
+ <a href={featured.keyUrl} target="_blank" rel="noopener noreferrer"
+ className="ml-auto inline-flex items-center gap-1 text-sm text-fg-default underline-offset-4 hover:underline">
+ Get a key from {provider?.name}<ExternalLink aria-hidden className="size-3.5" />
+ </a>
+ )}
</div>
- </div>
- );
- }
+ {!hasData ? (
+ view.isError ? <CatalogueError onRetry={() => void view.refetch()} /> : (
+ <div className="space-y-3 p-5" role="status" aria-label="Loading connector">
+ <Skeleton className="h-6 w-48" /><Skeleton className="h-24 w-full" />
+ </div>
+ )
+ ) : !provider ? (
+ <div className="p-5">
+ <Alert>
+ <AlertTitle>Connector unavailable</AlertTitle>
+ <AlertDescription>This connector is missing or disabled. Choose another connector from the catalogue.</AlertDescription>
+ </Alert>
+ </div>
+ ) : (
+ <>
+ <div className="space-y-2 px-5 pt-3 text-sm text-fg-muted">
+ {(provider.description || featured?.hint) && <p>{provider.description || featured?.hint}</p>}
+ <div className="flex flex-wrap items-center gap-2">
+ {provider.publisher && <span>by {provider.publisher}</span>}
+ {provider.verified && <Badge variant="outline">Verified</Badge>}
+ <Badge variant={connected ? 'success' : 'secondary'}>{connected ? 'Connected' : 'Not connected'}</Badge>
+ {connected && provider.account_label && <span>{provider.account_label}</span>}
+ {provider.runs_locally && <span>Runs on this computer</span>}
+ </div>
+ </div>
+ <PanelRenderer config={config} visible={visible} showTechnicalSections={showTechnicalSections} />
+ </>
+ )}
+ </Modal>
+ </>
+ );
+}
+function CatalogueError({ onRetry }: { onRetry: () => void }) {
return (
- <Modal
- isOpen={visible}
- onClose={onClose}
- maxWidth="95vw"
- maxHeight="95vh"
- headerActions={headerActions}
- >
- {body}
- </Modal>
+ <div className="p-5">
+ <Alert variant="destructive">
+ <AlertTitle>Couldn't reach the credentials server</AlertTitle>
+ <AlertDescription>Check your connection and try again.</AlertDescription>
+ </Alert>
+ <Button variant="outline" onClick={onRetry} className="mt-3">Try again</Button>
+ </div>
);
-};
-
-export default CredentialsModal;
+}
diff --git a/client/src/components/credentials/CredentialsPalette.tsx b/client/src/components/credentials/CredentialsPalette.tsx
deleted file mode 100644
index 0e05915c..00000000
--- a/client/src/components/credentials/CredentialsPalette.tsx
+++ /dev/null
@@ -1,375 +0,0 @@
-/**
- * CredentialsPalette — virtualized, searchable provider picker.
- *
- * Drop-in replacement for the antd `Menu` sidebar in `CredentialsModal`.
- * Scales from 20 → 5000 providers at 60 fps with < 200 ms INP during
- * rapid typing, per the runtime/memory targets in
- * `docs-internal/credentials_scaling/architecture.md`.
- *
- * Stack:
- * - `cmdk` for the Command shell + keyboard navigation + a11y.
- * - `fuzzysort` for pre-indexed fuzzy search (~1–2 ms per query on
- * 5000 entries).
- * - `react-virtuoso` `GroupedVirtuoso` for a DOM pool of ~10–50 nodes
- * regardless of item count, with sticky category headers.
- * - `startTransition` wrapping the filter update so the input stays
- * synchronous and typing never stalls (measured ~30–70 ms shorter
- * long task vs `useDeferredValue`).
- *
- * Store-shape rule: all derived data (prepared index, byId map,
- * filtered result, groupCounts) lives in `useMemo` inside this
- * component. Nothing touches Zustand. The store only holds UI state
- * (`selectedId`, `query`), which is how we avoid the #1 runtime/memory
- * trap (selector closures retaining the whole catalogue).
- */
-
-import React, {
- memo,
- startTransition,
- useCallback,
- useDeferredValue,
- useMemo,
- useState,
-} from 'react';
-import { Command } from 'cmdk';
-import { GroupedVirtuoso } from 'react-virtuoso';
-import fuzzysort from 'fuzzysort';
-import { Search, X } from 'lucide-react';
-
-import { Input } from '@/components/ui/input';
-import { cn } from '@/lib/utils';
-import { NodeIcon } from '../../assets/icons';
-import { theme } from '../../styles/theme';
-import { useWebSocket } from '../../contexts/WebSocketContext';
-import type { ProviderConfig, CategoryGroup } from './types';
-
-// ============================================================================
-// Props
-// ============================================================================
-
-export interface CredentialsPaletteProps {
- providers: ProviderConfig[];
- categories: CategoryGroup[];
- selectedId: string | null;
- onSelect: (id: string) => void;
- /** Height of the scrollable list area. */
- height?: number | string;
- /** Optional placeholder for the search input. */
- placeholder?: string;
-}
-
-// ============================================================================
-// Pre-indexed search
-// ============================================================================
-
-interface PreparedEntry {
- provider: ProviderConfig;
- _name: Fuzzysort.Prepared;
- _category: Fuzzysort.Prepared;
-}
-
-function buildPrepared(providers: ProviderConfig[]): PreparedEntry[] {
- return providers.map((p) => ({
- provider: p,
- _name: fuzzysort.prepare(p.name),
- _category: fuzzysort.prepare(p.categoryLabel),
- }));
-}
-
-function filterProviders(query: string, prepared: PreparedEntry[]): ProviderConfig[] {
- if (!query.trim()) return prepared.map((e) => e.provider);
- const results = fuzzysort.go(query, prepared, {
- keys: ['_name', '_category'],
- threshold: -10_000,
- limit: 500,
- });
- return results.map((r) => r.obj.provider);
-}
-
-// ============================================================================
-// Grouping (derived; never stored)
-// ============================================================================
-
-interface GroupedView {
- groups: CategoryGroup[];
- groupCounts: number[];
- flatItems: ProviderConfig[];
-}
-
-function groupFiltered(filtered: ProviderConfig[], categoryOrder: CategoryGroup[]): GroupedView {
- // Preserve the canonical category order from the server payload; for
- // each category, emit only those filtered providers that belong to it.
- const byCat = new Map<string, ProviderConfig[]>();
- for (const p of filtered) {
- const arr = byCat.get(p.category);
- if (arr) arr.push(p);
- else byCat.set(p.category, [p]);
- }
-
- const groups: CategoryGroup[] = [];
- const groupCounts: number[] = [];
- const flatItems: ProviderConfig[] = [];
-
- for (const cat of categoryOrder) {
- const items = byCat.get(cat.key);
- if (!items || items.length === 0) continue;
- groups.push({ key: cat.key, label: cat.label, items });
- groupCounts.push(items.length);
- flatItems.push(...items);
- }
-
- // Any provider whose category isn't in `categoryOrder` (server may
- // send a new category mid-session) still needs to render — bucket them
- // under a synthetic "Other" group at the end.
- const known = new Set(categoryOrder.map((c) => c.key));
- const orphans: ProviderConfig[] = [];
- for (const [catKey, items] of byCat.entries()) {
- if (!known.has(catKey)) orphans.push(...items);
- }
- if (orphans.length > 0) {
- groups.push({ key: '_other', label: 'Other', items: orphans });
- groupCounts.push(orphans.length);
- flatItems.push(...orphans);
- }
-
- return { groups, groupCounts, flatItems };
-}
-
-// ============================================================================
-// Status indicator — three states: configured + validated, configured but
-// validation failed, not configured. "Validated" is meaningful only for
-// providers that go through `validate_api_key` (AI providers + the special
-// google_maps / apify validators); for OAuth + QR-pairing flows the
-// validation cache is empty and a stored credential renders as success.
-// ============================================================================
-
-type CredStatus = 'unconfigured' | 'stored' | 'failed';
-
-const STATUS_CLASSES: Record<CredStatus, string> = {
- unconfigured: 'bg-muted-foreground/30',
- stored: 'bg-success',
- failed: 'bg-destructive',
-};
-
-const STATUS_LABEL: Record<CredStatus, string> = {
- unconfigured: 'Not configured',
- stored: 'Configured',
- failed: 'Validation failed',
-};
-
-interface ProviderStatusDotProps {
- providerId: string;
- stored: boolean;
-}
-
-/** Memo'd indicator. Reads `apiKeyStatuses[id]` only when it exists, so
- * providers without a validation flow (OAuth, QR pairing) don't pay
- * for the lookup, and any future state (failed validation, etc.)
- * renders without touching the row's click / selection logic. */
-const ProviderStatusDot = memo<ProviderStatusDotProps>(function ProviderStatusDot({
- providerId,
- stored,
-}) {
- const { apiKeyStatuses } = useWebSocket();
- const validation = apiKeyStatuses[providerId];
-
- // Treat the broadcast that fires on delete (`message === 'deleted'`)
- // as unconfigured for the brief window before the catalogue refetch
- // lands and flips `stored` to false. Without this the dot flashes red
- // for ~300 ms (the invalidateCatalogue debounce) every time a key is
- // removed, even though the user's intent was deletion, not failure.
- const justDeleted = validation?.message === 'deleted';
-
- let status: CredStatus;
- let title = STATUS_LABEL.unconfigured;
- if (!stored || justDeleted) {
- status = 'unconfigured';
- } else if (validation && validation.valid === false) {
- status = 'failed';
- title = validation.message
- ? `${STATUS_LABEL.failed}: ${validation.message}`
- : STATUS_LABEL.failed;
- } else {
- status = 'stored';
- title = STATUS_LABEL.stored;
- }
-
- return (
- <span
- aria-label={STATUS_LABEL[status]}
- title={title}
- className={cn(
- 'h-2 w-2 shrink-0 rounded-full transition-colors',
- STATUS_CLASSES[status],
- )}
- />
- );
-});
-
-// ============================================================================
-// Row renderer — memoized to stop upstream re-renders from cascading
-// ============================================================================
-
-interface RowProps {
- provider: ProviderConfig;
- selected: boolean;
- onSelect: (id: string) => void;
-}
-
-const ProviderRow = memo<RowProps>(function ProviderRow({ provider, selected, onSelect }) {
- const handleClick = useCallback(() => onSelect(provider.id), [onSelect, provider.id]);
-
- return (
- <Command.Item
- value={provider.id}
- onSelect={handleClick}
- className={cn(
- 'opencompany-palette-row flex cursor-pointer items-center gap-3 rounded-sm border px-3 py-2 text-sm text-foreground',
- selected
- ? 'border-node-agent-border bg-node-agent-soft'
- : 'border-transparent bg-transparent'
- )}
- >
- <NodeIcon
- icon={provider.iconRef}
- size={theme.iconSize.xs}
- className="shrink-0"
- />
- <span className="flex-1 truncate">{provider.name}</span>
- <ProviderStatusDot providerId={provider.id} stored={!!provider.stored} />
- </Command.Item>
- );
-});
-
-// ============================================================================
-// Group header renderer
-// ============================================================================
-
-interface HeaderProps {
- label: string;
- count: number;
-}
-
-const GroupHeader = memo<HeaderProps>(function GroupHeader({ label, count }) {
- return (
- <div className="sticky top-0 z-[1] flex justify-between border-b border-border bg-background px-3 py-1 text-xs font-semibold tracking-wider text-muted-foreground uppercase">
- <span>{label}</span>
- <span className="text-muted-foreground/60">{count}</span>
- </div>
- );
-});
-
-// ============================================================================
-// The palette component
-// ============================================================================
-
-const CredentialsPalette: React.FC<CredentialsPaletteProps> = ({
- providers,
- categories,
- selectedId,
- onSelect,
- height = '100%',
- placeholder = 'Search providers…',
-}) => {
- // Pre-indexed fuzzysort entries — rebuilt only when `providers` reference changes.
- const prepared = useMemo(() => buildPrepared(providers), [providers]);
-
- // Input value is synchronous; filter is deferred via startTransition.
- const [query, setQuery] = useState('');
- const [filtered, setFiltered] = useState<ProviderConfig[]>(() => providers);
-
- // If the providers array changes (e.g. after a server revalidate
- // replaces the TanStack Query cache), reset the filtered set.
- const prevProvidersRef = React.useRef(providers);
- if (prevProvidersRef.current !== providers) {
- prevProvidersRef.current = providers;
- // Synchronous update here is fine: happens at most once per catalogue change.
- setFiltered(filterProviders(query, prepared));
- }
-
- const handleQueryChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const v = e.target.value;
- setQuery(v);
- startTransition(() => {
- setFiltered(filterProviders(v, prepared));
- });
- },
- [prepared],
- );
-
- // Deferred query for group derivation (avoid recomputing on every keystroke
- // if React batches filter updates slower than the input).
- const deferredFiltered = useDeferredValue(filtered);
-
- const grouped = useMemo<GroupedView>(
- () => groupFiltered(deferredFiltered, categories),
- [deferredFiltered, categories],
- );
-
- return (
- <Command
- // cmdk disables built-in filtering so we can use fuzzysort instead.
- shouldFilter={false}
- label="Credential providers"
- className="flex h-full w-full flex-col"
- >
- <div className="border-b border-border p-2">
- <div className="relative">
- <Search className="pointer-events-none absolute top-1/2 left-2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- value={query}
- onChange={handleQueryChange}
- placeholder={placeholder}
- className="h-9 pl-8 pr-8"
- autoFocus
- />
- {query && (
- <button
- type="button"
- onClick={() => {
- setQuery('');
- startTransition(() => setFiltered(filterProviders('', prepared)));
- }}
- className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- aria-label="Clear search"
- >
- <X className="h-4 w-4" />
- </button>
- )}
- </div>
- </div>
- <div className="min-h-0 flex-1">
- {grouped.flatItems.length === 0 ? (
- <div className="flex h-full items-center justify-center text-sm text-muted-foreground opacity-70">
- No providers match &ldquo;{query}&rdquo;
- </div>
- ) : (
- <GroupedVirtuoso
- style={{ height }}
- groupCounts={grouped.groupCounts}
- groupContent={(idx) => (
- <GroupHeader
- label={grouped.groups[idx].label}
- count={grouped.groupCounts[idx]}
- />
- )}
- itemContent={(idx) => {
- const p = grouped.flatItems[idx];
- if (!p) return null;
- return (
- <ProviderRow
- provider={p}
- selected={p.id === selectedId}
- onSelect={onSelect}
- />
- );
- }}
- />
- )}
- </div>
- </Command>
- );
-};
-
-export default memo(CredentialsPalette);
diff --git a/client/src/components/credentials/PanelRenderer.tsx b/client/src/components/credentials/PanelRenderer.tsx
index 0f58ce0d..09b0dab5 100644
--- a/client/src/components/credentials/PanelRenderer.tsx
+++ b/client/src/components/credentials/PanelRenderer.tsx
@@ -18,7 +18,7 @@ import type { ProviderConfig, PanelKind } from './types';
// Vite will emit one chunk per panel under dist/assets/ApiKeyPanel-*.js,
// OAuthPanel-*.js, etc. Keep the import paths inside the arrow fns so
// code splitting is preserved.
-const PANEL_LOADERS: Record<PanelKind, () => Promise<{ default: React.ComponentType<PanelProps> }>> = {
+const PANEL_LOADERS: Record<PanelKind, () => Promise<{ default: React.ComponentType<CredentialPanelProps> }>> = {
apiKey: () => import('./panels/ApiKeyPanel'),
oauth: () => import('./panels/OAuthPanel'),
qrPairing: () => import('./panels/QrPairingPanel'),
@@ -30,7 +30,7 @@ const PANEL_LOADERS: Record<PanelKind, () => Promise<{ default: React.ComponentT
// the same kind doesn't re-trigger Suspense. React.lazy memoizes too
// internally, but declaring them once makes the intent explicit and
// avoids any HMR edge cases.
-const LAZY_PANELS: Record<PanelKind, React.LazyExoticComponent<React.ComponentType<PanelProps>>> = {
+const LAZY_PANELS: Record<PanelKind, React.LazyExoticComponent<React.ComponentType<CredentialPanelProps>>> = {
apiKey: React.lazy(PANEL_LOADERS.apiKey),
oauth: React.lazy(PANEL_LOADERS.oauth),
qrPairing: React.lazy(PANEL_LOADERS.qrPairing),
@@ -38,21 +38,15 @@ const LAZY_PANELS: Record<PanelKind, React.LazyExoticComponent<React.ComponentTy
browserProfiles: React.lazy(PANEL_LOADERS.browserProfiles),
};
-/** `full`: the editor's Credentials modal (usage, provider defaults, rate
- * limits). `compact`: only what it takes to connect, for Normal mode's
- * Connect dialog. */
-export type PanelVariant = 'full' | 'compact';
-
-interface PanelProps {
+export interface CredentialPanelProps {
config: ProviderConfig;
visible: boolean;
- variant?: PanelVariant;
+ /** Set by the shared host from shell mode; connection inputs stay available in both modes. */
+ showTechnicalSections?: boolean;
}
-interface Props {
+interface Props extends Omit<CredentialPanelProps, 'config'> {
config: ProviderConfig | null;
- visible: boolean;
- variant?: PanelVariant;
}
const PanelFallback: React.FC = () => (
@@ -68,7 +62,7 @@ const EmptyState: React.FC<{ icon: React.ReactNode; message: string }> = ({ icon
</div>
);
-const PanelRenderer: React.FC<Props> = ({ config, visible, variant = 'full' }) => {
+const PanelRenderer: React.FC<Props> = ({ config, visible, showTechnicalSections = false }) => {
const Lazy = useMemo(() => {
if (!config) return null;
return LAZY_PANELS[config.kind] ?? null;
@@ -93,7 +87,9 @@ const PanelRenderer: React.FC<Props> = ({ config, visible, variant = 'full' }) =
return (
<Suspense fallback={<PanelFallback />}>
- <Lazy config={config} visible={visible} variant={variant} />
+ {/* Provider identity resets transient errors/reveal state. Mode changes
+ keep the same panel mounted and preserve the active connection draft. */}
+ <Lazy key={config.id} config={config} visible={visible} showTechnicalSections={showTechnicalSections} />
</Suspense>
);
};
diff --git a/client/src/components/credentials/__tests__/ConnectionKinds.test.tsx b/client/src/components/credentials/__tests__/ConnectionKinds.test.tsx
new file mode 100644
index 00000000..8bc07d4a
--- /dev/null
+++ b/client/src/components/credentials/__tests__/ConnectionKinds.test.tsx
@@ -0,0 +1,150 @@
+/** Connection essentials stay usable in both presentations through the real renderer. */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const mocks = vi.hoisted(() => ({
+ sendRequest: vi.fn(), validateApiKey: vi.fn(), saveApiKey: vi.fn(), removeApiKey: vi.fn(),
+ getStoredApiKey: vi.fn(), hasStoredKey: vi.fn(),
+}));
+vi.mock('@/hooks/useApiKeys', () => ({ useApiKeys: () => ({ ...mocks, isConnected: true }) }));
+vi.mock('@/contexts/WebSocketContext', () => ({
+ useWebSocket: () => ({ ...mocks, isConnected: true, isReady: true }),
+ useWebSocketActions: () => ({ sendRequest: mocks.sendRequest, isReady: true }),
+ CREDENTIAL_PROBE_REQUEST_TIMEOUT: 60_000,
+}));
+vi.mock('../hooks', () => ({ useProviderStatus: () => null }));
+vi.mock('@/assets/icons', () => ({ NodeIcon: () => null }));
+
+import PanelRenderer from '../PanelRenderer';
+import type { ProviderConfig } from '../types';
+import { queryKeys } from '@/lib/queryConfig';
+
+const BASE: ProviderConfig = {
+ id: 'connection', name: 'Connection', category: 'apps', categoryLabel: 'Apps',
+ color: '', iconRef: '', kind: 'oauth',
+ ws: { login: 'provider_login', logout: 'provider_logout', status: 'provider_status' },
+};
+
+function mount(config: ProviderConfig, showTechnicalSections: boolean) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const element = (provider: ProviderConfig) => (
+ <QueryClientProvider client={client}>
+ <PanelRenderer config={provider} visible showTechnicalSections={showTechnicalSections} />
+ </QueryClientProvider>
+ );
+ const view = render(element(config));
+ return {
+ change: (provider: ProviderConfig) => view.rerender(element(provider)),
+ loaded: () => waitFor(() => expect(client.getQueryData(queryKeys.credentialValues.byProvider(config.id).queryKey)).toBeDefined()),
+ };
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.sendRequest.mockResolvedValue({ success: true, hasKey: false });
+ mocks.saveApiKey.mockResolvedValue({ isValid: true });
+ mocks.validateApiKey.mockResolvedValue({ isValid: true });
+ mocks.removeApiKey.mockResolvedValue(undefined);
+ mocks.getStoredApiKey.mockResolvedValue(null);
+ mocks.hasStoredKey.mockResolvedValue(false);
+});
+
+describe.each([false, true])('connection forms with technical sections %s', (showTechnicalSections) => {
+ it('shows custom IMAP/SMTP and saves the same complete email configuration', async () => {
+ const user = userEvent.setup();
+ const saved: Record<string, string> = {
+ email_provider: 'custom', email_imap_port: '1993', email_imap_encryption: 'tls',
+ email_smtp_port: '1587', email_smtp_encryption: 'start-tls',
+ };
+ mocks.getStoredApiKey.mockImplementation(async (key: string) => saved[key] ?? null);
+ mount({ ...BASE, id: 'email', name: 'Email', kind: 'email' }, showTechnicalSections);
+
+ await user.type(await screen.findByLabelText('IMAP Host'), 'imap.example.com');
+ await user.type(screen.getByLabelText('SMTP Host'), 'smtp.example.com');
+ await user.type(screen.getByLabelText('Email Address'), '[email protected]');
+ await user.type(screen.getByLabelText('Password', { exact: true }), 'app-password');
+ await user.type(screen.getByLabelText(/Display Name/), 'Alice');
+ expect(screen.getByLabelText('IMAP Port')).toHaveValue(1993);
+ expect(screen.getByLabelText('SMTP Port')).toHaveValue(1587);
+ expect(screen.getByLabelText('IMAP Security')).toHaveTextContent('TLS / SSL');
+ expect(screen.getByLabelText('SMTP Security')).toHaveTextContent('STARTTLS');
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(mocks.saveApiKey).toHaveBeenCalledTimes(10));
+ expect(mocks.saveApiKey.mock.calls).toEqual([
+ ['email_provider', 'custom'], ['email_address', '[email protected]'],
+ ['email_password', 'app-password'], ['email_display_name', 'Alice'],
+ ['email_imap_host', 'imap.example.com'], ['email_imap_port', '1993'], ['email_imap_encryption', 'tls'],
+ ['email_smtp_host', 'smtp.example.com'], ['email_smtp_port', '1587'], ['email_smtp_encryption', 'start-tls'],
+ ]);
+ expect(mocks.removeApiKey).not.toHaveBeenCalled();
+ expect(screen.getByLabelText(/Password/)).toHaveValue('');
+ });
+
+ it('keeps browser profile creation, import and confirmed deletion available', async () => {
+ const user = userEvent.setup();
+ mocks.sendRequest.mockImplementation(async (command: string) => command === 'browser_profiles_list' ? {
+ success: true,
+ profiles: [
+ { id: 'work', name: 'Work', kind: 'shared', sites: [{ domain: 'example.com', cookie_count: 2 }], in_use: null },
+ { id: 'busy', name: 'Employee', kind: 'employee', sites: [], in_use: { label: 'Assistant' } },
+ ],
+ } : { success: true });
+ mount({ ...BASE, id: 'browser', name: 'Web browser', kind: 'browserProfiles' }, showTechnicalSections);
+
+ expect(await screen.findByText('Work')).toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: 'Import logins' })).toHaveLength(2);
+ expect(screen.getByRole('button', { name: 'Delete Employee' })).toBeDisabled();
+ await user.type(screen.getByRole('textbox', { name: 'New profile name' }), ' Personal ');
+ await user.click(screen.getByRole('button', { name: 'Add profile' }));
+ await waitFor(() => expect(mocks.sendRequest).toHaveBeenCalledWith('browser_profile_create', { name: 'Personal' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Delete Work' })).toBeEnabled());
+ await user.click(screen.getByRole('button', { name: 'Delete Work' }));
+ expect(mocks.sendRequest.mock.calls.some(([command]) => command === 'browser_profile_delete')).toBe(false);
+ const confirmation = screen.getByRole('alertdialog');
+ await user.click(within(confirmation).getByRole('button', { name: 'Delete' }));
+ await waitFor(() => expect(mocks.sendRequest).toHaveBeenCalledWith('browser_profile_delete', { profile_id: 'work' }));
+ });
+
+ it('starts fieldless CLI OAuth without stored fields and displays its one-time code', async () => {
+ const user = userEvent.setup();
+ const openWindow = vi.spyOn(window, 'open').mockReturnValue(null);
+ mocks.sendRequest.mockResolvedValue({ success: true, url: 'https://example.com/device', verification_code: 'ABCD-1234' });
+ mount({ ...BASE, id: 'cli', name: 'CLI provider' }, showTechnicalSections);
+
+ const login = await screen.findByRole('button', { name: 'Login with CLI provider' });
+ expect(login).toBeEnabled();
+ expect(mocks.sendRequest).not.toHaveBeenCalled();
+ await user.click(login);
+ expect(mocks.sendRequest).toHaveBeenCalledWith('provider_login', {});
+ expect(openWindow).toHaveBeenCalledWith('https://example.com/device', '_blank');
+ expect(await screen.findByText('ABCD-1234')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Save Credentials' })).not.toBeInTheDocument();
+ openWindow.mockRestore();
+ });
+
+ it('keeps optional tokens usable alongside OAuth without making them a login prerequisite', async () => {
+ const user = userEvent.setup();
+ const provider: ProviderConfig = {
+ ...BASE, id: 'dual', name: 'Dual provider',
+ fields: [
+ { key: 'apiKey', label: 'Access token', secret: true, required: false, placeholder: 'Optional access token' },
+ { key: 'account_email', label: 'Account email', required: false },
+ ],
+ };
+ const view = mount(provider, showTechnicalSections);
+ await view.loaded();
+ expect(await screen.findByRole('button', { name: 'Login with Dual provider' })).toBeEnabled();
+ await user.type(screen.getByPlaceholderText('Optional access token'), 'optional-token');
+ await user.click(screen.getByRole('button', { name: 'Validate' }));
+ expect(mocks.validateApiKey).toHaveBeenCalledWith('dual', 'optional-token');
+ view.change({ ...provider, stored: true, account_label: 'Alice' });
+ expect(screen.getByRole('button', { name: 'Disconnect' })).toBeEnabled();
+ expect(screen.getByPlaceholderText('Optional access token')).toBeInTheDocument();
+ expect(screen.getByLabelText('Account email')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Disconnect' }));
+ expect(mocks.sendRequest).toHaveBeenCalledWith('provider_logout', {});
+ });
+});
diff --git a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx
new file mode 100644
index 00000000..89d34caa
--- /dev/null
+++ b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { ThemeProvider } from '@/contexts/ThemeContext';
+import type { CredentialsCatalogue, ConsumerProvider } from '../catalogue';
+
+const sendRequest = vi.fn();
+const useCatalogue = vi.fn();
+vi.mock('@/contexts/WebSocketContext', () => ({
+ useWebSocketActions: () => ({ sendRequest, isReady: true }),
+}));
+vi.mock('../catalogue', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../catalogue')>()),
+ useCredentialsCatalogue: () => useCatalogue(),
+}));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));
+
+import { CredentialsBrowser } from '../CredentialsBrowser';
+
+const ENDPOINT: ConsumerProvider = {
+ id: 'openai_compatible', name: 'Model server', category: 'ai', category_label: 'AI',
+ consumer_category: 'ai', color: '', kind: 'apiKey', connected: true,
+ endpoints: [{ ref: 'openai_compatible:lab', label: 'Lab', base_url: 'http://gpu:8000', kind: 'generic', model_count: 1 }],
+};
+
+function catalogue(providers: ConsumerProvider[] = [ENDPOINT]): CredentialsCatalogue {
+ return {
+ catalogue: { data: { providers } }, providers, categories: [],
+ isLoading: false, isError: false, error: null, refetch: vi.fn(),
+ } as unknown as CredentialsCatalogue;
+}
+
+beforeEach(() => {
+ sendRequest.mockReset().mockResolvedValue({ success: true });
+ useCatalogue.mockReset();
+});
+
+describe('CredentialsBrowser', () => {
+ it('uses its host catalogue without fetching another copy and can manage in Yours', () => {
+ const onConnect = vi.fn();
+ render(<ThemeProvider><CredentialsBrowser catalogue={catalogue()} onConnect={onConnect} /></ThemeProvider>);
+ expect(useCatalogue).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('radio', { name: /Yours/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Manage Model server' }));
+ expect(onConnect).toHaveBeenCalledWith('openai_compatible', 'manage');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('hands named-endpoint removal to the panel instead of deleting the family id', async () => {
+ const onConnect = vi.fn();
+ render(<ThemeProvider><CredentialsBrowser catalogue={catalogue()} onConnect={onConnect} /></ThemeProvider>);
+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect Model server' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));
+ await waitFor(() => expect(onConnect).toHaveBeenCalledWith('openai_compatible', 'manage'));
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('offers a retry when no catalogue could be loaded', () => {
+ const state = catalogue([]);
+ state.catalogue = { ...state.catalogue, data: undefined } as CredentialsCatalogue['catalogue'];
+ state.isError = true;
+ render(<ThemeProvider><CredentialsBrowser catalogue={state} onConnect={vi.fn()} /></ThemeProvider>);
+ expect(screen.getByText("Couldn't load connectors")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
+ expect(state.refetch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/credentials/__tests__/PanelRenderer.test.tsx b/client/src/components/credentials/__tests__/PanelRenderer.test.tsx
new file mode 100644
index 00000000..fd1eb932
--- /dev/null
+++ b/client/src/components/credentials/__tests__/PanelRenderer.test.tsx
@@ -0,0 +1,171 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const mocks = vi.hoisted(() => ({
+ sendRequest: vi.fn(),
+ validateApiKey: vi.fn(),
+ saveApiKey: vi.fn(),
+ removeApiKey: vi.fn(),
+ getProviderDefaults: vi.fn(),
+ getValidatedAiProviders: vi.fn(),
+ getProviderUsageSummary: vi.fn(),
+ getAPIUsageSummary: vi.fn(),
+ getWhatsAppRateLimitConfig: vi.fn(),
+ apiKeyStatuses: {},
+}));
+
+vi.mock('@/hooks/useApiKeys', () => ({
+ useApiKeys: () => ({ ...mocks, isConnected: true }),
+}));
+vi.mock('@/contexts/WebSocketContext', () => ({
+ useWebSocket: () => ({ ...mocks, isConnected: true, isReady: true }),
+ CREDENTIAL_PROBE_REQUEST_TIMEOUT: 60_000,
+}));
+vi.mock('../hooks', () => ({ useProviderStatus: () => null }));
+vi.mock('@/assets/icons', () => ({ NodeIcon: () => null }));
+
+import PanelRenderer from '../PanelRenderer';
+import type { ProviderConfig } from '../types';
+import { queryKeys } from '@/lib/queryConfig';
+
+const API: ProviderConfig = {
+ id: 'first', name: 'First provider', category: 'ai', categoryLabel: 'AI',
+ color: '', kind: 'apiKey', iconRef: '', hasDefaults: true, usageService: 'first-api',
+ fields: [{ key: 'apiKey', label: 'API key', placeholder: 'Provider key', required: true, help: 'Create a key in your account.' }],
+};
+
+const OAUTH: ProviderConfig = {
+ ...API, id: 'oauth', name: 'OAuth provider', kind: 'oauth', hasDefaults: false,
+ fields: [
+ { key: 'client_id', label: 'Client ID', required: true },
+ { key: 'client_secret', label: 'Client secret', secret: true, required: true },
+ ],
+ ws: { login: 'provider_login', logout: 'provider_logout', status: 'provider_status' },
+ instructions: 'Register an application before signing in.',
+ callbackUrl: 'http://localhost/callback',
+};
+
+function renderPanel(config: ProviderConfig, showTechnicalSections?: boolean) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const element = (nextConfig: ProviderConfig, technical?: boolean) => (
+ <QueryClientProvider client={client}>
+ <PanelRenderer config={nextConfig} visible showTechnicalSections={technical} />
+ </QueryClientProvider>
+ );
+ const view = render(element(config, showTechnicalSections));
+ return {
+ ...view,
+ change: (nextConfig: ProviderConfig, technical?: boolean) => view.rerender(element(nextConfig, technical)),
+ loaded: (id: string) => waitFor(() => expect(client.getQueryData(queryKeys.credentialValues.byProvider(id).queryKey)).toBeDefined()),
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.sendRequest.mockResolvedValue({ hasKey: false });
+ mocks.validateApiKey.mockResolvedValue({ isValid: false, success: false, error: 'Key rejected' });
+ mocks.getProviderDefaults.mockResolvedValue({});
+ mocks.getValidatedAiProviders.mockResolvedValue({ providers: [] });
+ mocks.getProviderUsageSummary.mockResolvedValue([]);
+ mocks.getAPIUsageSummary.mockResolvedValue([]);
+ mocks.getWhatsAppRateLimitConfig.mockResolvedValue({ success: true, config: { enabled: false } });
+});
+
+describe('shared credential panel policy', () => {
+ it('mounts technical sections only in dev and keeps the connection draft across mode changes', async () => {
+ const user = userEvent.setup();
+ const view = renderPanel(API);
+ await view.loaded(API.id);
+ const field = await screen.findByPlaceholderText('Provider key');
+ await user.type(field, 'draft-key');
+
+ expect(screen.getByText('Create a key in your account.')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Default Parameters' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Usage.*Costs/i })).not.toBeInTheDocument();
+ expect(mocks.getProviderDefaults).not.toHaveBeenCalled();
+ expect(mocks.getAPIUsageSummary).not.toHaveBeenCalled();
+ expect(mocks.getProviderUsageSummary).not.toHaveBeenCalled();
+
+ view.change(API, true);
+ await waitFor(() => expect(mocks.getProviderDefaults).toHaveBeenCalledWith(API.id));
+ expect(mocks.getAPIUsageSummary).toHaveBeenCalledWith('first-api');
+ expect(screen.getByRole('button', { name: 'Default Parameters' })).toBeInTheDocument();
+ expect(screen.getByPlaceholderText('Provider key')).toBe(field);
+ expect(field).toHaveValue('draft-key');
+
+ await user.click(screen.getByRole('button', { name: 'Usage & Costs' }));
+ await waitFor(() => expect(mocks.getProviderUsageSummary).toHaveBeenCalledOnce());
+ view.change(API, false);
+ expect(screen.queryByRole('button', { name: 'Default Parameters' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Usage.*Costs/i })).not.toBeInTheDocument();
+ expect(field).toHaveValue('draft-key');
+ expect(mocks.getProviderDefaults).toHaveBeenCalledOnce();
+ expect(mocks.getAPIUsageSummary).toHaveBeenCalledOnce();
+ });
+
+ it('isolates drafts by provider and clears reveal and error state on a provider switch', async () => {
+ const user = userEvent.setup();
+ const view = renderPanel(API);
+ await view.loaded(API.id);
+ await user.type(await screen.findByPlaceholderText('Provider key'), 'first-draft');
+ await user.click(screen.getByRole('button', { name: 'Show key' }));
+ await user.click(screen.getByRole('button', { name: 'Validate' }));
+ expect(await screen.findByText('Key rejected')).toBeInTheDocument();
+
+ const second = { ...API, id: 'second', name: 'Second provider' };
+ view.change(second);
+ await view.loaded(second.id);
+ expect(screen.getByPlaceholderText('Provider key')).toHaveValue('');
+ expect(screen.getByPlaceholderText('Provider key')).toHaveAttribute('type', 'password');
+ expect(screen.queryByText('Key rejected')).not.toBeInTheDocument();
+ await user.type(screen.getByPlaceholderText('Provider key'), 'second-draft');
+
+ view.change(API);
+ expect(screen.getByPlaceholderText('Provider key')).toHaveValue('first-draft');
+ expect(screen.getByPlaceholderText('Provider key')).toHaveAttribute('type', 'password');
+ expect(screen.queryByText('Key rejected')).not.toBeInTheDocument();
+ });
+
+ it('keeps required OAuth setup and callbacks in both modes without normal-mode usage requests', async () => {
+ const user = userEvent.setup();
+ const view = renderPanel(OAUTH);
+ await view.loaded(OAUTH.id);
+ const secret = await screen.findByLabelText('Client secret', { exact: false });
+ await user.type(secret, 'oauth-draft');
+ expect(screen.getByLabelText('Client ID', { exact: false })).toBeInTheDocument();
+ expect(screen.getByText('Register an application before signing in.', { exact: false })).toBeInTheDocument();
+ expect(screen.getByText('http://localhost/callback')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Save Credentials' })).toBeInTheDocument();
+ expect(mocks.getAPIUsageSummary).not.toHaveBeenCalled();
+ expect(mocks.sendRequest.mock.calls.every(([command]) => command === 'get_stored_api_key')).toBe(true);
+
+ view.change(OAUTH, true);
+ await waitFor(() => expect(mocks.getAPIUsageSummary).toHaveBeenCalledOnce());
+ expect(screen.getByLabelText('Client secret', { exact: false })).toBe(secret);
+ expect(secret).toHaveValue('oauth-draft');
+ expect(secret).toHaveAttribute('type', 'password');
+ expect(screen.getByText('http://localhost/callback')).toBeInTheDocument();
+ });
+
+ it('keeps pairing available while mounting rate-limit requests only in dev', async () => {
+ const qr: ProviderConfig = {
+ ...API, id: 'whatsapp', name: 'WhatsApp', kind: 'qrPairing', fields: undefined,
+ hasRateLimits: true,
+ qr: {
+ qrField: 'qr', isConnected: () => true, connectedTitle: 'Phone connected',
+ connectedSubtitle: () => 'Your phone is ready', isLoading: () => false,
+ emptyText: () => 'Scan to connect', scanText: 'Scan with your phone',
+ },
+ };
+ const view = renderPanel(qr);
+ expect(await screen.findByText('Phone connected')).toBeInTheDocument();
+ expect(mocks.getWhatsAppRateLimitConfig).not.toHaveBeenCalled();
+ view.change(qr, true);
+ await waitFor(() => expect(mocks.getWhatsAppRateLimitConfig).toHaveBeenCalledOnce());
+ view.change(qr, false);
+ expect(screen.getByText('Phone connected')).toBeInTheDocument();
+ expect(mocks.getWhatsAppRateLimitConfig).toHaveBeenCalledOnce();
+ });
+});
diff --git a/client/src/components/credentials/__tests__/catalogue.test.tsx b/client/src/components/credentials/__tests__/catalogue.test.tsx
new file mode 100644
index 00000000..59b7decf
--- /dev/null
+++ b/client/src/components/credentials/__tests__/catalogue.test.tsx
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { renderHook } from '@testing-library/react';
+import type { CatalogueResponse, ServerProviderConfig } from '@/hooks/useCatalogueQuery';
+
+let data: CatalogueResponse | undefined;
+let disabled: string[] = [];
+const sendRequest = vi.fn();
+const refetch = vi.fn();
+
+vi.mock('@/contexts/WebSocketContext', () => ({
+ useWebSocketActions: () => ({ sendRequest, isReady: true }),
+}));
+vi.mock('@/hooks/useCatalogueQuery', () => ({
+ useCatalogueQueryCore: () => ({ data, isLoading: !data, isError: false, error: null, refetch }),
+}));
+vi.mock('@/hooks/useNodeAllowlist', () => ({
+ useNodeAllowlist: () => ({ isCredentialCategoryDisabled: (category: string) => disabled.includes(category) }),
+}));
+
+import { isConnected, useCredentialsCatalogue } from '../catalogue';
+
+function provider(id: string, category: string, consumerCategory: string): ServerProviderConfig {
+ return { id, name: id, category, category_label: category, consumer_category: consumerCategory, color: '', kind: 'apiKey' };
+}
+
+beforeEach(() => {
+ disabled = [];
+ data = {
+ providers: [provider('openai', 'ai', 'ai'), provider('phone', 'android', 'devices'), provider('github', 'vcs', 'developer')],
+ categories: [],
+ consumer_categories: [
+ { key: 'developer', label: 'Developer', order: 0 },
+ { key: 'devices', label: 'Devices', order: 1 },
+ { key: 'ai', label: 'AI', order: 2 },
+ ],
+ version: '1',
+ };
+});
+
+describe('shared credentials catalogue', () => {
+ it('uses the same category blocklist for providers and visible category chips', () => {
+ const { result, rerender } = renderHook(useCredentialsCatalogue);
+ expect(result.current.providers.map((p) => p.id)).toEqual(['github', 'phone', 'openai']);
+ disabled = ['android'];
+ rerender();
+ expect(result.current.providers.map((p) => p.id)).toEqual(['github', 'openai']);
+ expect(result.current.categories.map((c) => c.key)).toEqual(['developer', 'ai']);
+ expect(result.current.catalogue.data).toBe(data);
+ });
+
+ it('keeps query state and retry available with an empty cold catalogue', () => {
+ data = undefined;
+ const { result } = renderHook(useCredentialsCatalogue);
+ expect(result.current.providers).toEqual([]);
+ expect(result.current.categories).toEqual([]);
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.refetch).toBe(refetch);
+ });
+
+ it('uses live connection state before stored credentials', () => {
+ const item = provider('phone', 'android', 'devices');
+ expect(isConnected({ ...item, stored: true, connected: false })).toBe(false);
+ expect(isConnected({ ...item, stored: true })).toBe(true);
+ });
+});
diff --git a/client/src/components/credentials/catalogue.ts b/client/src/components/credentials/catalogue.ts
new file mode 100644
index 00000000..2c9d3565
--- /dev/null
+++ b/client/src/components/credentials/catalogue.ts
@@ -0,0 +1,89 @@
+/**
+ * Normal mode's view of the credential catalogue: every provider, in the
+ * order of its `consumer_category` (apps before AI models). The server
+ * gives every provider one; the filter only drops a malformed entry. Same
+ * cache as the editor's Credentials modal, read through the stable
+ * actions context.
+ */
+
+import { useMemo } from 'react';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { useNodeAllowlist } from '@/hooks/useNodeAllowlist';
+import {
+ useCatalogueQueryCore,
+ type CatalogueResponse,
+ type ServerCategory,
+ type ServerProviderConfig,
+} from '@/hooks/useCatalogueQuery';
+
+export type ConsumerProvider = ServerProviderConfig & { consumer_category: string };
+
+export function useCredentialsQuery() {
+ const { sendRequest, isReady } = useWebSocketActions();
+ return useCatalogueQueryCore(sendRequest, isReady);
+}
+
+/** Kept for existing Home readers of the raw catalogue query. */
+export const useHomeCatalogue = useCredentialsQuery;
+
+/** Consumer providers, sorted by their category's place in `consumer_categories`
+ * (a stable sort, so the catalogue's own order holds within a category). */
+export function consumerProviders(catalogue: CatalogueResponse | undefined): ConsumerProvider[] {
+ const order = new Map((catalogue?.consumer_categories ?? []).map((category, index) => [category.key, index]));
+ const rank = (provider: ConsumerProvider) => order.get(provider.consumer_category) ?? order.size;
+ return (catalogue?.providers ?? [])
+ .filter((provider): provider is ConsumerProvider => Boolean(provider.consumer_category))
+ .sort((a, b) => rank(a) - rank(b));
+}
+
+export function isConnected(provider: ServerProviderConfig): boolean {
+ return Boolean(provider.connected ?? provider.stored);
+}
+
+/** One visibility policy for the browser and its selected-provider host. */
+export function useCredentialsCatalogue() {
+ const catalogue = useCredentialsQuery();
+ const { isCredentialCategoryDisabled, isLoading: allowlistIsLoading } = useNodeAllowlist();
+ const waitingForAllowlist = Boolean(allowlistIsLoading);
+ const providers = useMemo(
+ () => waitingForAllowlist ? [] : consumerProviders(catalogue.data).filter((provider) => !isCredentialCategoryDisabled(provider.category)),
+ [catalogue.data, isCredentialCategoryDisabled, waitingForAllowlist],
+ );
+ const categories = useMemo(() => {
+ const visible = new Set(providers.map((provider) => provider.consumer_category));
+ return (catalogue.data?.consumer_categories ?? []).filter((category) => visible.has(category.key));
+ }, [catalogue.data, providers]);
+ return {
+ catalogue,
+ providers,
+ categories,
+ isLoading: catalogue.isLoading || waitingForAllowlist,
+ isError: catalogue.isError,
+ error: catalogue.error,
+ refetch: catalogue.refetch,
+ };
+}
+
+export type CredentialsCatalogue = ReturnType<typeof useCredentialsCatalogue>;
+
+export interface ConnectorsView {
+ categories: ServerCategory[];
+ providers: ConsumerProvider[];
+ /** Connected apps (not AI providers), for the composer's apps pill. */
+ connectedApps: ConsumerProvider[];
+ hasAi: boolean;
+}
+
+export function useConnectors(): ConnectorsView & { isLoading: boolean } {
+ const { providers, categories, isLoading } = useCredentialsCatalogue();
+ const view = useMemo<ConnectorsView>(() => {
+ const connected = providers.filter(isConnected);
+ return {
+ categories,
+ providers,
+ connectedApps: connected.filter((p) => p.consumer_category !== 'ai'),
+ hasAi: connected.some((p) => p.consumer_category === 'ai'),
+ };
+ }, [providers, categories]);
+ return { ...view, isLoading };
+}
diff --git a/client/src/components/credentials/panels/ApiKeyPanel.tsx b/client/src/components/credentials/panels/ApiKeyPanel.tsx
index 48c3a358..9029f15f 100644
--- a/client/src/components/credentials/panels/ApiKeyPanel.tsx
+++ b/client/src/components/credentials/panels/ApiKeyPanel.tsx
@@ -19,14 +19,13 @@ import { NodeIcon } from '../../../assets/icons';
import { theme } from '../../../styles/theme';
import { CREDENTIAL_PROBE_REQUEST_TIMEOUT } from '@/contexts/WebSocketContext';
import type { ServerEndpointSummary } from '@/hooks/useCatalogueQuery';
-import type { ProviderConfig } from '../types';
-import type { PanelVariant } from '../PanelRenderer';
+import type { CredentialPanelProps } from '../PanelRenderer';
import EndpointList from './EndpointList';
-const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean; variant?: PanelVariant }> = ({
+const ApiKeyPanel: React.FC<CredentialPanelProps> = ({
config,
visible,
- variant = 'full',
+ showTechnicalSections = false,
}) => {
const panel = useCredentialPanel(config, visible);
// Primary credential field (validate / connect target — bot token,
@@ -186,9 +185,9 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean; variant?
</>
)}
- {variant === 'full' && config.hasDefaults && <ProviderDefaultsSection providerId={config.id} />}
- {variant === 'full' && config.hasDefaults && <LlmUsageSection providerId={config.id} providerName={config.name} />}
- {variant === 'full' && config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />}
+ {showTechnicalSections && config.hasDefaults && <ProviderDefaultsSection providerId={config.id} />}
+ {showTechnicalSections && config.hasDefaults && <LlmUsageSection providerId={config.id} providerName={config.name} />}
+ {showTechnicalSections && config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />}
</div>
);
};
diff --git a/client/src/components/credentials/panels/EmailPanel.tsx b/client/src/components/credentials/panels/EmailPanel.tsx
index 42f0f6cf..96550404 100644
--- a/client/src/components/credentials/panels/EmailPanel.tsx
+++ b/client/src/components/credentials/panels/EmailPanel.tsx
@@ -273,24 +273,24 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ co
</span>
)}
</FormLabel>
- <FormControl>
- <div className="relative">
+ <div className="relative">
+ <FormControl>
<Input
type={revealPassword ? 'text' : 'password'}
placeholder={stored ? '••••••••' : 'App password or account password'}
className="font-mono pr-9"
{...field}
/>
- <button
- type="button"
- onClick={() => setRevealPassword((v) => !v)}
- className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- aria-label={revealPassword ? 'Hide password' : 'Show password'}
- >
- {revealPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
- </button>
- </div>
- </FormControl>
+ </FormControl>
+ <button
+ type="button"
+ onClick={() => setRevealPassword((v) => !v)}
+ className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ aria-label={revealPassword ? 'Hide password' : 'Show password'}
+ >
+ {revealPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
+ </button>
+ </div>
<FormDescription>{AUTH_NOTES[provider]}</FormDescription>
<FormMessage />
</FormItem>
diff --git a/client/src/components/credentials/panels/OAuthPanel.tsx b/client/src/components/credentials/panels/OAuthPanel.tsx
index cf9bfac5..47b0e2d5 100644
--- a/client/src/components/credentials/panels/OAuthPanel.tsx
+++ b/client/src/components/credentials/panels/OAuthPanel.tsx
@@ -10,13 +10,12 @@ import { OAuthConnect } from '../primitives';
import { ApiUsageSection } from '../sections';
import { NodeIcon } from '../../../assets/icons';
import { theme } from '../../../styles/theme';
-import type { ProviderConfig } from '../types';
-import type { PanelVariant } from '../PanelRenderer';
+import type { CredentialPanelProps } from '../PanelRenderer';
-const OAuthPanel: React.FC<{ config: ProviderConfig; visible: boolean; variant?: PanelVariant }> = ({
+const OAuthPanel: React.FC<CredentialPanelProps> = ({
config,
visible,
- variant = 'full',
+ showTechnicalSections = false,
}) => {
const panel = useCredentialPanel(config, visible);
const status = useProviderStatus(config.statusHook);
@@ -60,7 +59,7 @@ const OAuthPanel: React.FC<{ config: ProviderConfig; visible: boolean; variant?:
onLogout={() => panel.actions.oauthLogout()}
onRefresh={() => panel.actions.oauthRefresh()}
extraSection={
- variant === 'full' && config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />
+ showTechnicalSections && config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />
}
/>
</div>
diff --git a/client/src/components/credentials/panels/QrPairingPanel.tsx b/client/src/components/credentials/panels/QrPairingPanel.tsx
index 83646227..408401c9 100644
--- a/client/src/components/credentials/panels/QrPairingPanel.tsx
+++ b/client/src/components/credentials/panels/QrPairingPanel.tsx
@@ -17,13 +17,12 @@ import { RateLimitSection } from '../sections';
import { NodeIcon } from '../../../assets/icons';
import { theme } from '../../../styles/theme';
import type { ActionDef } from '../primitives/ActionBar';
-import type { ProviderConfig } from '../types';
-import type { PanelVariant } from '../PanelRenderer';
+import type { CredentialPanelProps } from '../PanelRenderer';
-const QrPairingPanel: React.FC<{ config: ProviderConfig; visible: boolean; variant?: PanelVariant }> = ({
+const QrPairingPanel: React.FC<CredentialPanelProps> = ({
config,
visible,
- variant = 'full',
+ showTechnicalSections = false,
}) => {
const panel = useCredentialPanel(config, visible);
const status = useProviderStatus(config.statusHook);
@@ -81,7 +80,7 @@ const QrPairingPanel: React.FC<{ config: ProviderConfig; visible: boolean; varia
loading={qr.isLoading(status)} emptyText={qr.emptyText(status, panel.stored)} />
{!connected && qrData && <div className="mt-3 text-sm text-muted-foreground">{qr.scanText}</div>}
</div>
- {variant === 'full' && config.hasRateLimits && connected && <RateLimitSection />}
+ {showTechnicalSections && config.hasRateLimits && connected && <RateLimitSection />}
{panel.error && (
<Alert variant="destructive">
<AlertDescription>{panel.error}</AlertDescription>
diff --git a/client/src/components/ui/CommandPalette.tsx b/client/src/components/ui/CommandPalette.tsx
index cdeb8fec..45af2920 100644
--- a/client/src/components/ui/CommandPalette.tsx
+++ b/client/src/components/ui/CommandPalette.tsx
@@ -5,7 +5,7 @@
* `.cmdk` panel. Keeps a small registered command set in state; the
* Dashboard wires the actual handlers (`onOpenSettings`, etc.) via the
* `commands` prop. Composes on top of the cmdk library that ships with
- * the codebase (CredentialsPalette uses the same dependency).
+ * the codebase.
*
* Token-driven: chrome reads bg-bg-elevated + border-border-strong;
* active row reads bg-bg-active + text-accent. Under Renaissance the
diff --git a/client/src/components/ui/Modal.tsx b/client/src/components/ui/Modal.tsx
index c05300f2..fc567fef 100644
--- a/client/src/components/ui/Modal.tsx
+++ b/client/src/components/ui/Modal.tsx
@@ -64,6 +64,9 @@ interface ModalProps {
* specific than a bare `motion-reduce:` utility).
*/
motion?: 'default' | 'spring';
+ /** Focus lifecycle for programmatically opened dialogs without a DialogTrigger. */
+ onOpenAutoFocus?: React.ComponentProps<typeof DialogPrimitive.Content>['onOpenAutoFocus'];
+ onCloseAutoFocus?: React.ComponentProps<typeof DialogPrimitive.Content>['onCloseAutoFocus'];
}
const DEFAULT_TITLE_ICON = <Settings className="h-4 w-4 opacity-70" />;
@@ -95,6 +98,8 @@ const Modal: React.FC<ModalProps> = ({
hideHeader = false,
titleIcon = DEFAULT_TITLE_ICON,
motion = 'default',
+ onOpenAutoFocus,
+ onCloseAutoFocus,
}) => {
const showHeader = !hideHeader && Boolean(title || headerActions);
@@ -118,6 +123,8 @@ const Modal: React.FC<ModalProps> = ({
void-near-black, light/dark use plain blacks). */}
<DialogOverlay className={cn('bg-bg-overlay supports-backdrop-filter:backdrop-blur-xs', OVERLAY_MOTION[motion])} />
<DialogPrimitive.Content
+ onOpenAutoFocus={onOpenAutoFocus}
+ onCloseAutoFocus={onCloseAutoFocus}
data-slot="dialog-content"
className={cn(
// bg-bg-app + border-border-default consume the new-contract
@@ -151,10 +158,10 @@ const Modal: React.FC<ModalProps> = ({
// + text-transform are theme-driven so titles read as Cinzel
// uppercase under Renaissance and Space Mono under
// Cyber, while staying clean sans-serif under light/dark.
- <div className="modal-head relative flex w-full items-center border-b border-border-default bg-bg-panel px-5 py-3">
- <DialogTitle className="absolute left-5 flex items-center gap-2 font-display text-base font-semibold tracking-[var(--type-tracking-display)] text-fg-default [text-transform:var(--type-uppercase)]">
+ <div className="modal-head relative flex min-h-14 w-full shrink-0 items-center border-b border-border-default bg-bg-panel px-5 py-3">
+ <DialogTitle className="absolute left-5 flex max-w-[calc(100%_-_5rem)] items-center gap-2 font-display text-base font-semibold tracking-[var(--type-tracking-display)] text-fg-default [text-transform:var(--type-uppercase)]">
{titleIcon}
- {title}
+ <span className="truncate">{title}</span>
</DialogTitle>
<div className="flex flex-1 items-center justify-center">{headerActions}</div>
{/* No onClick: DialogClose already routes through onOpenChange,
diff --git a/client/src/features/home/HomeShell.tsx b/client/src/features/home/HomeShell.tsx
index e9319fe8..cd48fe3c 100644
--- a/client/src/features/home/HomeShell.tsx
+++ b/client/src/features/home/HomeShell.tsx
@@ -6,9 +6,9 @@
*
* The shell owns what spans views: the employee broadcasts that keep the
* team current, the orb behind the content, the Workspace dock on the
- * right, the Settings dialog, and the connect dialogs any view can open (an
- * app's, and "Connect an AI model"). Switching views scrolls to the top and
- * plays the view swap.
+ * right, and the Settings dialog. Connection actions open the app shell's
+ * shared credentials dialog. Switching views scrolls to the top and plays
+ * the view swap.
*
* The scrolling area is a column the view fills at least, so an employee's
* page can pin its message box to the bottom however short the conversation.
@@ -17,15 +17,14 @@
import { useLayoutEffect, useRef, useState } from 'react';
import { animate } from '@/lib/motion';
import { cn } from '@/lib/utils';
+import { useShellDialogsStore, type CredentialsIntent } from '@/stores/shellDialogsStore';
import { useApprovalLifecycle } from './approvals/data';
-import { ConnectAIDialog } from './connectAI/ConnectAIDialog';
import { useEmployeeLifecycle, useEmployeesQuery } from './data/employees';
import { EmployeeView } from './employee/EmployeeView';
import { HomeHeader } from './header/HomeHeader';
import { HireView } from './hire/HireView';
import { SPIKE, spikeOrb } from './orb/orb';
import { OrbStage } from './orb/OrbStage';
-import { ConnectDialog } from './settings/ConnectDialog';
import { HomeSettings } from './settings/HomeSettings';
import { HomeSidebar } from './sidebar/HomeSidebar';
import { useHomeStore } from './state/homeStore';
@@ -60,10 +59,10 @@ export default function HomeShell() {
useApprovalLifecycle();
const view = useHomeStore((s) => s.view);
const title = useViewTitle();
- const [connectId, setConnectId] = useState<string | null>(null);
- const openConnect = (providerId: string) => {
+ const openCredentials = useShellDialogsStore((s) => s.openCredentials);
+ const openConnect = (providerId: string, intent: CredentialsIntent = 'connect') => {
spikeOrb(SPIKE.connect);
- setConnectId(providerId);
+ openCredentials({ providerId, intent });
};
const [scrolled, setScrolled] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -117,8 +116,6 @@ export default function HomeShell() {
</main>
<WorkspaceDock onConnect={openConnect} />
<HomeSettings onConnect={openConnect} />
- <ConnectDialog providerId={connectId} onClose={() => setConnectId(null)} />
- <ConnectAIDialog />
</div>
);
}
diff --git a/client/src/features/home/__tests__/connectAI.test.ts b/client/src/features/home/__tests__/connectAI.test.ts
new file mode 100644
index 00000000..0fe71c57
--- /dev/null
+++ b/client/src/features/home/__tests__/connectAI.test.ts
@@ -0,0 +1,49 @@
+/** Home's AI prompts target the shared credentials browser without losing
+ * the employee, hire draft, or Settings page underneath. */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../orb/orb', () => ({ SPIKE: { connect: 1, settings: 1 }, spikeOrb: vi.fn() }));
+
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
+import { useHomeStore } from '../state/homeStore';
+
+beforeEach(() => {
+ useShellDialogsStore.setState({
+ credentialsOpen: false,
+ credentialsOptions: { intent: 'manage' },
+ credentialsRequestId: 0,
+ });
+ useHomeStore.setState({ view: { kind: 'hire' }, settingsOpen: false, settingsTab: 'profile', settingsCategory: 'all' });
+});
+
+describe('Home AI connection navigation', () => {
+ it('opens the shared AI category with connection intent', () => {
+ useHomeStore.getState().openConnectAI();
+
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { categoryId: 'ai', intent: 'connect' },
+ });
+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });
+ });
+
+ it('replaces an old provider target while keeping the employee and Settings location', () => {
+ useHomeStore.setState({
+ view: { kind: 'employee', workflowId: '4' },
+ settingsOpen: true,
+ settingsTab: 'connectors',
+ settingsCategory: 'messages',
+ });
+ useShellDialogsStore.getState().openCredentials({ providerId: 'telegram', intent: 'manage' });
+
+ useHomeStore.getState().openConnectAI();
+
+ expect(useShellDialogsStore.getState().credentialsOptions).toEqual({ categoryId: 'ai', intent: 'connect' });
+ expect(useHomeStore.getState()).toMatchObject({
+ view: { kind: 'employee', workflowId: '4' },
+ settingsOpen: true,
+ settingsTab: 'connectors',
+ settingsCategory: 'messages',
+ });
+ });
+});
diff --git a/client/src/features/home/__tests__/connectAI.test.tsx b/client/src/features/home/__tests__/connectAI.test.tsx
deleted file mode 100644
index 62081406..00000000
--- a/client/src/features/home/__tests__/connectAI.test.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * The guided "Connect an AI model" dialog: the featured providers with
- * their hint and whether each is connected; picking one opens its own panel
- * with the link to where its key is made; the dialog closes once that
- * provider connects; and every other model is one click away in Settings.
- */
-
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen } from '@testing-library/react';
-import type { CatalogueResponse, ServerProviderConfig } from '@/hooks/useCatalogueQuery';
-
-let catalogue: CatalogueResponse | undefined;
-
-vi.mock('../data/connectors', async (importOriginal) => ({
- ...(await importOriginal<typeof import('../data/connectors')>()),
- useHomeCatalogue: () => ({ data: catalogue, isLoading: !catalogue }),
-}));
-vi.mock('@/components/credentials/PanelRenderer', () => ({
- default: ({ config }: { config: { name: string } | null }) => <div>Panel for {config?.name}</div>,
-}));
-vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
-
-import { FEATURED_AI_PROVIDERS } from '@/components/onboarding/aiProviderLinks';
-import { ThemeProvider } from '@/contexts/ThemeContext';
-import { ConnectAIDialog } from '../connectAI/ConnectAIDialog';
-import { useHomeStore } from '../state/homeStore';
-import { pillToast } from '../ui/pillToast';
-
-function provider(id: string, name: string, connected = false): ServerProviderConfig {
- return {
- id,
- name,
- category: 'ai',
- category_label: 'AI',
- color: '',
- kind: 'apiKey',
- consumer_category: 'ai',
- stored: connected,
- connected,
- };
-}
-
-function withProviders(...providers: ServerProviderConfig[]): CatalogueResponse {
- return { providers, categories: [], version: 'v1' };
-}
-
-// A fresh element each time, so a rerender reads the catalogue again.
-const ui = () => (
- <ThemeProvider>
- <ConnectAIDialog />
- </ThemeProvider>
-);
-
-beforeEach(() => {
- vi.mocked(pillToast).mockClear();
- catalogue = withProviders(provider('openai', 'OpenAI'), provider('anthropic', 'Anthropic', true), provider('gemini', 'Gemini'));
- useHomeStore.setState({ connectAIOpen: true, settingsOpen: false });
-});
-
-describe('ConnectAIDialog', () => {
- it('lists the featured providers with a hint, and which are connected', () => {
- render(ui());
- expect(screen.getByRole('dialog', { name: 'Connect an AI model' })).toBeInTheDocument();
- for (const entry of FEATURED_AI_PROVIDERS) expect(screen.getByText(entry.hint)).toBeInTheDocument();
- const anthropic = screen.getByRole('button', { name: /Anthropic/ });
- expect(anthropic).toHaveTextContent('Connected');
- expect(screen.getByRole('button', { name: /OpenAI/ })).not.toHaveTextContent('Connected');
- });
-
- it('opens a provider’s own panel with the page where its key is made, and goes back', () => {
- render(ui());
- fireEvent.click(screen.getByRole('button', { name: /OpenAI/ }));
- expect(screen.getByText('Panel for OpenAI')).toBeInTheDocument();
- const openai = FEATURED_AI_PROVIDERS.find((entry) => entry.id === 'openai')!;
- expect(screen.getByRole('link', { name: /Get one from OpenAI/ })).toHaveAttribute('href', openai.keyUrl);
- fireEvent.click(screen.getByRole('button', { name: 'All AI models' }));
- expect(screen.queryByText('Panel for OpenAI')).not.toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Gemini/ })).toBeInTheDocument();
- });
-
- it('closes once the picked provider connects', () => {
- const { rerender } = render(ui());
- fireEvent.click(screen.getByRole('button', { name: /OpenAI/ }));
- expect(pillToast).not.toHaveBeenCalled();
- catalogue = withProviders(provider('openai', 'OpenAI', true), provider('anthropic', 'Anthropic', true));
- rerender(ui());
- expect(pillToast).toHaveBeenCalledWith('OpenAI is connected');
- expect(useHomeStore.getState().connectAIOpen).toBe(false);
- });
-
- it('stays open on a provider that was connected already', () => {
- const { rerender } = render(ui());
- fireEvent.click(screen.getByRole('button', { name: /Anthropic/ }));
- rerender(ui());
- expect(useHomeStore.getState().connectAIOpen).toBe(true);
- expect(pillToast).not.toHaveBeenCalled();
- });
-
- it('sends the owner to every AI model in Settings', () => {
- render(ui());
- fireEvent.click(screen.getByRole('button', { name: 'See all AI models' }));
- const home = useHomeStore.getState();
- expect(home.connectAIOpen).toBe(false);
- expect(home).toMatchObject({ settingsOpen: true, settingsTab: 'connectors', settingsCategory: 'ai' });
- });
-});
diff --git a/client/src/features/home/__tests__/connectorsTab.test.tsx b/client/src/features/home/__tests__/connectorsTab.test.tsx
index 9652872b..f5464d67 100644
--- a/client/src/features/home/__tests__/connectorsTab.test.tsx
+++ b/client/src/features/home/__tests__/connectorsTab.test.tsx
@@ -1,8 +1,7 @@
/**
* Settings > Connectors: Disconnect removes what the provider's own panel
* would (an API key, a sign-in), and hands QR and email accounts to their
- * panel; a card glows and confirms only when a provider flips to connected
- * while the page is open; the page opens on the category it was asked for,
+ * panel; connection feedback belongs to the shared host; the page opens on the category it was asked for,
* and search also matches who makes the app.
*/
@@ -18,11 +17,11 @@ vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
useWebSocketActions: () => ({ sendRequest, isReady: true }),
}));
-vi.mock('../data/connectors', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../data/connectors')>();
+vi.mock('@/components/credentials/catalogue', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/components/credentials/catalogue')>();
return {
...actual,
- useConnectors: () => ({
+ useCredentialsCatalogue: () => ({
providers,
categories: [{ key: 'ai', label: 'AI' }, { key: 'messages', label: 'Messages' }],
connectedApps: providers.filter(actual.isConnected).filter((p) => p.consumer_category !== 'ai'),
@@ -32,7 +31,7 @@ vi.mock('../data/connectors', async (importOriginal) => {
};
});
-vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));
import { ThemeProvider } from '@/contexts/ThemeContext';
import { ConnectorsTab } from '../settings/ConnectorsTab';
@@ -44,7 +43,7 @@ function ui(onConnect = vi.fn(), initialCategory?: string) {
</ThemeProvider>
);
}
-import { pillToast } from '../ui/pillToast';
+import { toast } from 'sonner';
function provider(patch: Partial<ServerProviderConfig> & { id: string; kind: ServerProviderConfig['kind'] }) {
return {
@@ -58,14 +57,15 @@ function provider(patch: Partial<ServerProviderConfig> & { id: string; kind: Ser
}
async function disconnect(name: string) {
- const card = screen.getByText(name).closest('[data-catalog-item]') as HTMLElement;
- fireEvent.click(card.querySelector('button')!);
+ fireEvent.click(screen.getByRole('button', { name: `Disconnect ${name}` }));
fireEvent.click(await screen.findByRole('button', { name: 'Disconnect' }));
}
beforeEach(() => {
sendRequest.mockReset().mockResolvedValue({ success: true });
- vi.mocked(pillToast).mockClear();
+ vi.mocked(toast.success).mockClear();
+ vi.mocked(toast.info).mockClear();
+ vi.mocked(toast.error).mockClear();
providers = [
provider({ id: 'openai', name: 'OpenAI', kind: 'apiKey', connected: true, fields: [{ key: 'apiKey' }] }),
provider({ id: 'ollama', name: 'Ollama', kind: 'apiKey', connected: true, fields: [{ key: 'ollama_proxy' }], runs_locally: true }),
@@ -99,21 +99,32 @@ describe('ConnectorsTab', () => {
const onConnect = vi.fn();
render(ui(onConnect));
await disconnect('WhatsApp');
- await waitFor(() => expect(onConnect).toHaveBeenCalledWith('whatsapp'));
+ await waitFor(() => expect(onConnect).toHaveBeenCalledWith('whatsapp', 'manage'));
expect(sendRequest).not.toHaveBeenCalled();
});
- it('confirms a connection only when it happens while the tab is open', () => {
+ it('leaves connection-success feedback to the shared host', () => {
providers = [provider({ id: 'openai', name: 'OpenAI', kind: 'apiKey', connected: true })];
const { rerender } = render(ui());
- expect(pillToast).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
providers = [provider({ id: 'openai', name: 'OpenAI', kind: 'apiKey', connected: false })];
rerender(ui());
providers = [provider({ id: 'openai', name: 'OpenAI', kind: 'apiKey', connected: true })];
rerender(ui());
- expect(pillToast).toHaveBeenCalledTimes(1);
- expect(pillToast).toHaveBeenCalledWith('OpenAI is connected');
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'Manage OpenAI' })).toBeInTheDocument();
+ });
+
+ it('opens existing connections for management and new providers for connection', () => {
+ providers.push(provider({ id: 'gemini', name: 'Gemini', kind: 'apiKey', connected: false }));
+ const onConnect = vi.fn();
+ render(ui(onConnect));
+ fireEvent.click(screen.getByRole('button', { name: 'Manage OpenAI' }));
+ expect(onConnect).toHaveBeenLastCalledWith('openai', 'manage');
+ fireEvent.click(screen.getByRole('button', { name: 'Connect Gemini' }));
+ expect(onConnect).toHaveBeenLastCalledWith('gemini', 'connect');
+ expect(sendRequest).not.toHaveBeenCalled();
});
it('filters by category and search', () => {
diff --git a/client/src/features/home/__tests__/employeeView.test.tsx b/client/src/features/home/__tests__/employeeView.test.tsx
index dd5ff824..fb9f5980 100644
--- a/client/src/features/home/__tests__/employeeView.test.tsx
+++ b/client/src/features/home/__tests__/employeeView.test.tsx
@@ -36,6 +36,7 @@ import { parseEmployee, type EmployeeSummary } from '../data/schemas';
import { ThemeProvider } from '@/contexts/ThemeContext';
import { EmployeeView } from '../employee/EmployeeView';
import { useHomeStore } from '../state/homeStore';
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
import { pillToast } from '../ui/pillToast';
const TALK_ON = { state: 'on', agent_node_id: 'w1:talk' };
@@ -138,25 +139,32 @@ describe('EmployeeView', () => {
});
it('says to connect an AI model, and opens that dialog, when Start is refused for want of one', async () => {
- useHomeStore.setState({ connectAIOpen: false });
+ useShellDialogsStore.setState({ credentialsOpen: false });
actions.startEmployee.mockRejectedValue(new Error('needs_ai'));
renderPage(summary({ status: 'ready', talk: TALK_ON }, { state: 'never_started' }));
fireEvent.click(screen.getByRole('button', { name: 'Start' }));
await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Connect an AI model first.', { tone: 'error' }));
- expect(useHomeStore.getState().connectAIOpen).toBe(true);
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { categoryId: 'ai', intent: 'connect' },
+ });
});
it('opens the "Connect an AI model" dialog from the conversation', () => {
- useHomeStore.setState({ connectAIOpen: false });
+ useShellDialogsStore.setState({ credentialsOpen: false });
renderPage(summary({ status: 'ready', talk: TALK_ON, needs_ai: true }, { state: 'never_started' }));
fireEvent.click(screen.getByRole('button', { name: 'Connect an AI model' }));
- expect(useHomeStore.getState().connectAIOpen).toBe(true);
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { categoryId: 'ai', intent: 'connect' },
+ });
});
- it('makes Open in Dev mode the main button when nothing else is possible', () => {
+ it('keeps the stopped notice without offering Open in Dev mode when no normal action is available', () => {
renderPage(summary({ status: 'attention', talk: TALK_ON }, { state: 'failed', can_resume: false }));
- fireEvent.click(screen.getByRole('button', { name: 'Open in Dev mode' }));
- expect(enterDev).toHaveBeenCalledWith({ workflowId: 'w1' });
+ expect(screen.queryByRole('button', { name: 'Open in Dev mode' })).not.toBeInTheDocument();
+ expect(screen.getByText('Maya isn’t running, so they can’t read messages right now.')).toBeInTheDocument();
+ expect(enterDev).not.toHaveBeenCalled();
});
it('offers Start above the message box while the employee is not running', async () => {
diff --git a/client/src/features/home/__tests__/homeSettings.test.tsx b/client/src/features/home/__tests__/homeSettings.test.tsx
index 86913cdf..fff9a49f 100644
--- a/client/src/features/home/__tests__/homeSettings.test.tsx
+++ b/client/src/features/home/__tests__/homeSettings.test.tsx
@@ -17,8 +17,8 @@ vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
}));
vi.mock('../settings/ProfileTab', () => ({ ProfileTab: () => <p>Profile page</p> }));
-vi.mock('../settings/ConnectorsTab', () => ({
- ConnectorsTab: ({ initialCategory }: { initialCategory?: string }) => <p>Connectors page ({initialCategory})</p>,
+vi.mock('@/components/credentials/CredentialsBrowser', () => ({
+ CredentialsBrowser: ({ initialCategory }: { initialCategory?: string }) => <p>Connectors page ({initialCategory})</p>,
}));
vi.mock('../data/employees', () => ({ useEmployeesQuery: () => ({ data: [{}, {}, {}], isPending: false }) }));
diff --git a/client/src/features/home/connectAI/ConnectAIDialog.tsx b/client/src/features/home/connectAI/ConnectAIDialog.tsx
deleted file mode 100644
index d63d02c0..00000000
--- a/client/src/features/home/connectAI/ConnectAIDialog.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * "Connect an AI model", for an owner who has never made an API key (after
- * onboarding's Connect your AI step). It lists the featured AI providers
- * (components/onboarding/aiProviderLinks.ts: a hint and the page where the
- * key is made), each with its name, mark and whether it is connected from
- * the credential catalogue. Picking one opens that provider's own panel,
- * compact, as the Connect dialog does, with the link to its key page; the
- * dialog closes once that provider connects. Every other AI model (one on
- * this computer, another company) is in Settings > Connectors > AI.
- *
- * Opened through homeStore's openConnectAI: when a setup finds no AI model,
- * after a hire that cannot start without one, and from an employee's main
- * action (on their page, or in the Workspace header).
- */
-
-import { ArrowLeft, Check, ExternalLink, ShieldCheck } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { FEATURED_AI_PROVIDERS } from '@/components/onboarding/aiProviderLinks';
-import PanelRenderer from '@/components/credentials/PanelRenderer';
-import { rehydrateProvider } from '@/components/credentials/catalogueAdapter';
-import { Button } from '@/components/ui/button';
-import Modal from '@/components/ui/Modal';
-import { Skeleton } from '@/components/ui/skeleton';
-import { isConnected, useHomeCatalogue } from '../data/connectors';
-import { useHomeStore } from '../state/homeStore';
-import { pillToast } from '../ui/pillToast';
-import { AppMark } from '../ui/primitives';
-
-export function ConnectAIDialog() {
- const open = useHomeStore((s) => s.connectAIOpen);
- const closeConnectAI = useHomeStore((s) => s.closeConnectAI);
- const openSettings = useHomeStore((s) => s.openSettings);
- const { data } = useHomeCatalogue();
- const [pickedId, setPickedId] = useState<string | null>(null);
-
- const featured = useMemo(
- () =>
- FEATURED_AI_PROVIDERS.flatMap((entry) => {
- const provider = data?.providers.find((candidate) => candidate.id === entry.id);
- return provider ? [{ ...entry, provider }] : [];
- }),
- [data],
- );
- const picked = featured.find((entry) => entry.id === pickedId) ?? null;
- const pickedProvider = picked?.provider ?? null;
- const config = useMemo(() => (pickedProvider ? rehydrateProvider(pickedProvider) : null), [pickedProvider]);
-
- const close = useCallback(() => {
- setPickedId(null);
- closeConnectAI();
- }, [closeConnectAI]);
-
- // Only the picked provider going from not connected to connected counts.
- const connected = pickedProvider ? isConnected(pickedProvider) : false;
- const name = pickedProvider?.name ?? '';
- const seen = useRef({ id: pickedId, connected });
- useEffect(() => {
- const before = seen.current;
- seen.current = { id: pickedId, connected };
- if (!pickedId || before.id !== pickedId || before.connected || !connected) return;
- pillToast(`${name} is connected`);
- close();
- }, [pickedId, connected, name, close]);
-
- const seeAll = () => {
- close();
- openSettings('connectors', 'ai');
- };
-
- return (
- <Modal
- isOpen={open}
- onClose={close}
- title={picked ? `Connect ${picked.provider.name}` : 'Connect an AI model'}
- titleIcon={null}
- motion="spring"
- maxWidth="min(560px, calc(100vw - 2rem))"
- maxHeight="min(720px, calc(100vh - 2rem))"
- autoHeight
- className="rounded-panel bg-bg-panel shadow-dialog"
- >
- {picked ? (
- <div className="flex flex-col">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-5 pt-4">
- <Button
- variant="quiet"
- size="sm"
- onClick={() => setPickedId(null)}
- className="-ml-2 gap-1 text-row text-fg-muted"
- >
- <ArrowLeft aria-hidden />
- All AI models
- </Button>
- <span className="ml-auto text-sm text-fg-muted">
- No key yet?{' '}
- <a
- href={picked.keyUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center gap-1 font-medium text-fg-default underline-offset-4 hover:underline"
- >
- Get one from {picked.provider.name}
- <ExternalLink aria-hidden className="size-3.5" />
- </a>
- </span>
- </div>
- <PanelRenderer config={config} visible variant="compact" />
- </div>
- ) : (
- <div className="flex flex-col gap-4 px-6 pt-5 pb-6">
- <p className="m-0 text-base text-pretty text-fg-muted">
- Your employees need an AI model to think. Pick one, then paste the key they give you. It takes about a
- minute.
- </p>
- {data ? (
- <div className="grid grid-cols-[repeat(auto-fit,minmax(140px,1fr))] gap-2.5">
- {featured.map(({ id, hint, provider }) => (
- <Button
- key={id}
- variant="quiet"
- onClick={() => setPickedId(id)}
- className="h-auto flex-col gap-1.5 rounded-card border-border-default bg-bg-elevated px-3 py-4 whitespace-normal hover:border-border-strong"
- >
- <AppMark name={provider.name} iconRef={provider.icon_ref} size="lg" />
- <span className="text-base font-semibold text-fg-default">{provider.name}</span>
- <span className="text-xs font-normal text-fg-muted">{hint}</span>
- {isConnected(provider) && (
- <span className="flex items-center gap-1 text-xs font-medium text-status-working-ink">
- <Check aria-hidden className="size-3" strokeWidth={2.5} />
- Connected
- </span>
- )}
- </Button>
- ))}
- </div>
- ) : (
- <div className="grid grid-cols-3 gap-2.5">
- {FEATURED_AI_PROVIDERS.map((entry) => (
- <Skeleton key={entry.id} className="h-30 rounded-card" />
- ))}
- </div>
- )}
- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-border-default pt-4">
- <span className="text-sm text-fg-muted">A model that runs on this computer, or another company?</span>
- <Button
- variant="quiet"
- size="sm"
- onClick={seeAll}
- className="ml-auto h-8 border-border-strong px-3.5 font-semibold text-fg-default"
- >
- See all AI models
- </Button>
- </div>
- <p className="m-0 flex items-center gap-1.5 text-xs text-fg-faint">
- <ShieldCheck aria-hidden className="size-3.5 shrink-0" />
- Your key is stored encrypted, and is only sent to the company you pick.
- </p>
- </div>
- )}
- </Modal>
- );
-}
-
-export default ConnectAIDialog;
diff --git a/client/src/features/home/data/connectors.ts b/client/src/features/home/data/connectors.ts
index c987780b..a0c6f8ec 100644
--- a/client/src/features/home/data/connectors.ts
+++ b/client/src/features/home/data/connectors.ts
@@ -1,60 +1,2 @@
-/**
- * Normal mode's view of the credential catalogue: every provider, in the
- * order of its `consumer_category` (apps before AI models). The server
- * gives every provider one; the filter only drops a malformed entry. Same
- * cache as the editor's Credentials modal, read through the stable
- * actions context.
- */
-
-import { useMemo } from 'react';
-import { useWebSocketActions } from '@/contexts/WebSocketContext';
-import {
- useCatalogueQueryCore,
- type CatalogueResponse,
- type ServerCategory,
- type ServerProviderConfig,
-} from '@/hooks/useCatalogueQuery';
-
-export type ConsumerProvider = ServerProviderConfig & { consumer_category: string };
-
-export function useHomeCatalogue() {
- const { sendRequest, isReady } = useWebSocketActions();
- return useCatalogueQueryCore(sendRequest, isReady);
-}
-
-/** Consumer providers, sorted by their category's place in `consumer_categories`
- * (a stable sort, so the catalogue's own order holds within a category). */
-export function consumerProviders(catalogue: CatalogueResponse | undefined): ConsumerProvider[] {
- const order = new Map((catalogue?.consumer_categories ?? []).map((category, index) => [category.key, index]));
- const rank = (provider: ConsumerProvider) => order.get(provider.consumer_category) ?? order.size;
- return (catalogue?.providers ?? [])
- .filter((provider): provider is ConsumerProvider => Boolean(provider.consumer_category))
- .sort((a, b) => rank(a) - rank(b));
-}
-
-export function isConnected(provider: ServerProviderConfig): boolean {
- return Boolean(provider.connected ?? provider.stored);
-}
-
-export interface ConnectorsView {
- categories: ServerCategory[];
- providers: ConsumerProvider[];
- /** Connected apps (not AI providers), for the composer's apps pill. */
- connectedApps: ConsumerProvider[];
- hasAi: boolean;
-}
-
-export function useConnectors(): ConnectorsView & { isLoading: boolean } {
- const { data, isLoading } = useHomeCatalogue();
- const view = useMemo<ConnectorsView>(() => {
- const providers = consumerProviders(data);
- const connected = providers.filter(isConnected);
- return {
- categories: data?.consumer_categories ?? [],
- providers,
- connectedApps: connected.filter((p) => p.consumer_category !== 'ai'),
- hasAi: connected.some((p) => p.consumer_category === 'ai'),
- };
- }, [data]);
- return { ...view, isLoading };
-}
+/** Compatibility exports for Home's connector consumers. */
+export * from '@/components/credentials/catalogue';
diff --git a/client/src/features/home/data/presentation.ts b/client/src/features/home/data/presentation.ts
index 119d3624..1ffecacc 100644
--- a/client/src/features/home/data/presentation.ts
+++ b/client/src/features/home/data/presentation.ts
@@ -21,7 +21,7 @@
* and cannot be sent otherwise.
*/
-import type { AppRef, ColorRole, EmployeeSummary } from './schemas';
+import type { AppRef, EmployeeSummary } from './schemas';
import type {
WorkflowControlPendingMutation,
WorkflowControlState,
@@ -186,14 +186,7 @@ export const STATUS_DOT_CLASS: Record<StatusTone, string> = {
live: 'bg-node-trigger opencompany-pip-pulse',
};
-/** Avatar: the employee's role colour at the soft-button tint. */
-export const AVATAR_CLASS: Record<ColorRole, string> = {
- agent: 'bg-node-agent-fill border-node-agent-edge text-node-agent-ink',
- model: 'bg-node-model-fill border-node-model-edge text-node-model-ink',
- tool: 'bg-node-tool-fill border-node-tool-edge text-node-tool-ink',
- trigger: 'bg-node-trigger-fill border-node-trigger-edge text-node-trigger-ink',
- workflow: 'bg-node-workflow-fill border-node-workflow-edge text-node-workflow-ink',
-};
+export { AVATAR_CLASS } from '@/components/catalog/presentation';
/** The avatar's letter: the first letter of the name, "?" when empty. */
export function initialOf(name: string): string {
diff --git a/client/src/features/home/data/schemas.ts b/client/src/features/home/data/schemas.ts
index 6962e7a0..12047b10 100644
--- a/client/src/features/home/data/schemas.ts
+++ b/client/src/features/home/data/schemas.ts
@@ -11,8 +11,8 @@
import { z } from 'zod';
import { normalizeWorkflowControlStatus, type WorkflowControlStatus } from '@/contexts/WebSocketContext';
-export const COLOR_ROLES = ['agent', 'model', 'tool', 'trigger', 'workflow'] as const;
-export type ColorRole = (typeof COLOR_ROLES)[number];
+import { COLOR_ROLES } from '@/components/catalog/presentation';
+export { COLOR_ROLES, type ColorRole } from '@/components/catalog/presentation';
export const EMPLOYEE_STATUSES = ['working', 'ready', 'paused', 'attention'] as const;
export type EmployeeStatus = (typeof EMPLOYEE_STATUSES)[number];
diff --git a/client/src/features/home/employee/PrimaryActionButton.tsx b/client/src/features/home/employee/PrimaryActionButton.tsx
index 951d2646..fdeb4339 100644
--- a/client/src/features/home/employee/PrimaryActionButton.tsx
+++ b/client/src/features/home/employee/PrimaryActionButton.tsx
@@ -1,11 +1,10 @@
/**
* The button for an employee's main action (see useEmployeeControl): the
- * green run button for Start, Resume and connecting, a quiet one for Pause
- * and Open in Dev mode. `className` sizes it for a smaller host (the
- * Workspace header).
+ * green run button for Start, Resume and connecting, a quiet one for Pause.
+ * Normal mode omits the developer-workflow fallback. `className` sizes it
+ * for a smaller host (the Workspace header).
*/
-import { Code } from 'lucide-react';
import { ActionButton } from '@/components/ui/action-button';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
@@ -13,6 +12,9 @@ import type { EmployeeControl } from './useEmployeeControl';
export function PrimaryActionButton({ control, className }: { control: EmployeeControl; className?: string }) {
const { primary } = control.view;
+ // Keep an in-flight lifecycle label until it settles, but never offer
+ // the developer-workflow fallback from normal-mode employee controls.
+ if (primary.kind === 'open_workflow' && !control.busy) return null;
if (primary.kind === 'pause' || primary.kind === 'open_workflow') {
return (
<Button
@@ -21,7 +23,6 @@ export function PrimaryActionButton({ control, className }: { control: EmployeeC
onClick={control.act}
className={cn('h-9 gap-2 rounded-row border-border-strong px-4 font-semibold text-fg-default', className)}
>
- {primary.kind === 'open_workflow' && !control.busy && <Code aria-hidden className="size-3.25" />}
{control.label}
</Button>
);
diff --git a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
index c29aaa44..ce27f405 100644
--- a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
+++ b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { setReducedMotion } from '@/test/waapi';
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
const sendRequest = vi.fn();
@@ -90,7 +91,8 @@ beforeEach(() => {
vi.mocked(pillToast).mockClear();
resetDraftForTests();
seedReadyDraft();
- useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null, connectAIOpen: false });
+ useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null });
+ useShellDialogsStore.setState({ credentialsOpen: false });
});
afterEach(() => {
@@ -142,7 +144,10 @@ describe('HireDraftPanel', () => {
const home = useHomeStore.getState();
expect(home.view).toEqual({ kind: 'employee', workflowId: 'w1' });
expect(home.hireNotice).toEqual({ workflowId: 'w1', name: 'Maya', warnings });
- expect(home.connectAIOpen).toBe(true);
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { categoryId: 'ai', intent: 'connect' },
+ });
});
it('tells the owner in plain words when the same hire is still going through', async () => {
@@ -190,7 +195,10 @@ describe('HireDraftPanel', () => {
useDraftStore.setState({ status: 'failed', failure: { code: 'no_ai_provider', text: 'Answer WhatsApp', refine: false } });
renderPanel();
fireEvent.click(screen.getByRole('button', { name: 'Connect an AI model' }));
- expect(useHomeStore.getState().connectAIOpen).toBe(true);
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { categoryId: 'ai', intent: 'connect' },
+ });
});
it('shows how long the setup has taken, and Cancel hands the words back', () => {
diff --git a/client/src/features/home/genui/__tests__/useHireComposer.test.tsx b/client/src/features/home/genui/__tests__/useHireComposer.test.tsx
index 30c3cb43..6e3c25cb 100644
--- a/client/src/features/home/genui/__tests__/useHireComposer.test.tsx
+++ b/client/src/features/home/genui/__tests__/useHireComposer.test.tsx
@@ -22,6 +22,7 @@ vi.mock('../../data/connectors', () => ({
import corpus from '../__fixtures__/replies.json';
import { useHomeStore } from '../../state/homeStore';
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
import { resetDraftForTests, useDraftStore } from '../draftStore';
import { useHireComposer } from '../useHireComposer';
@@ -32,7 +33,8 @@ beforeEach(() => {
resetDraftForTests();
connectors.hasAi = false;
connectors.isLoading = false;
- useHomeStore.setState({ connectAIOpen: false, composerFocus: 0, view: { kind: 'hire' } });
+ useHomeStore.setState({ composerFocus: 0, view: { kind: 'hire' } });
+ useShellDialogsStore.setState({ credentialsOpen: false });
});
async function submit(result: { current: ReturnType<typeof useHireComposer> }, job: string) {
@@ -54,7 +56,10 @@ describe('useHireComposer', () => {
const { result, rerender } = renderHook(() => useHireComposer());
await submit(result, 'Answer my WhatsApp');
expect(useDraftStore.getState().failure?.code).toBe('no_ai_provider');
- expect(useHomeStore.getState().connectAIOpen).toBe(true);
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { categoryId: 'ai', intent: 'connect' },
+ });
sendRequest.mockResolvedValue({ success: true, reply: GOOD_REPLY });
connectors.hasAi = true;
diff --git a/client/src/features/home/genui/__tests__/useStarterHire.test.tsx b/client/src/features/home/genui/__tests__/useStarterHire.test.tsx
index 78c76788..d3c61dd2 100644
--- a/client/src/features/home/genui/__tests__/useStarterHire.test.tsx
+++ b/client/src/features/home/genui/__tests__/useStarterHire.test.tsx
@@ -80,7 +80,7 @@ beforeEach(() => {
sendRequest.mockClear();
vi.mocked(pillToast).mockClear();
resetDraftForTests();
- useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null, connectAIOpen: false });
+ useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null });
library = [row('write-like-a-person', { is_active: false })];
builtIns = receptionist.skills.map((name) => ({ name, description: `Use for ${name}.`, metadata: { title: name } }));
hireResponse = {
diff --git a/client/src/features/home/settings/CatalogLayout.tsx b/client/src/features/home/settings/CatalogLayout.tsx
index 7c0e8b35..4ee9b5e1 100644
--- a/client/src/features/home/settings/CatalogLayout.tsx
+++ b/client/src/features/home/settings/CatalogLayout.tsx
@@ -1,390 +1,2 @@
-/**
- * The shared catalog page behind Settings > Skills, Connectors and Plugins
- * (design handoff "Settings: Billing, Skills, Plugins"): a title with Yours /
- * Discover, search, an optional category filter and primary action, and a
- * grid of cards.
- *
- * Every rule follows from the props and the item data, never from which
- * page is showing:
- * - the page supplies both lists, and Yours counts its own;
- * - the category filter exists when there are categories, and starts open
- * when the page is opened on one;
- * - Discover shows DISCOVER_LIMIT cards until "Show all";
- * - a card offers remove only with `onRemove`, and a switch only with
- * `onToggle`;
- * - a card glows when its item turns 'added' while it is on screen, then
- * `onItemAdded` runs (never on first render).
- *
- * The view, search and filter live here, so they start fresh each time the
- * page mounts (the Settings tabs unmount when hidden).
- */
-
-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
-import { ArrowRight, BadgeCheck, Check, LoaderCircle, Plus, SlidersHorizontal } from 'lucide-react';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import { Skeleton } from '@/components/ui/skeleton';
-import { Switch } from '@/components/ui/switch';
-import { Toggle } from '@/components/ui/toggle';
-import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
-import { animate } from '@/lib/motion';
-import { cn } from '@/lib/utils';
-import { AppMark, SearchField } from '../ui/primitives';
-import { DISCOVER_LIMIT, catalogSlice, type CatalogItem, type CatalogView } from './catalog';
-import { staggerSettings } from './stagger';
-
-export interface CatalogLayoutProps {
- title: string;
- /** Also the search box's accessible name. */
- searchPlaceholder: string;
- yours: { items: CatalogItem[]; sectionTitle: string; empty: { title: string; detail: string } };
- discover: { items: CatalogItem[]; sectionTitle: string };
- loading?: boolean;
- categories?: { key: string; label: string }[];
- initialCategory?: string;
- verbs: { add: string; remove?: string; busy?: string };
- onAdd: (item: CatalogItem) => void;
- onRemove?: (item: CatalogItem) => void;
- onToggle?: (item: CatalogItem, on: boolean) => void;
- onItemAdded?: (item: CatalogItem) => void;
- /** A header button that opens an inline form above the list. */
- primaryAction?: { label: string; form: (close: () => void) => ReactNode };
-}
-
-const GRID = '-mt-2 grid grid-cols-[repeat(auto-fill,minmax(300px,1fr))] gap-3';
-
-export function CatalogLayout({
- title,
- searchPlaceholder,
- yours,
- discover,
- loading = false,
- categories = [],
- initialCategory = 'all',
- verbs,
- onAdd,
- onRemove,
- onToggle,
- onItemAdded,
- primaryAction,
-}: CatalogLayoutProps) {
- const [view, setView] = useState<CatalogView>('discover');
- const [category, setCategory] = useState(initialCategory);
- const [filterOpen, setFilterOpen] = useState(initialCategory !== 'all');
- const [query, setQuery] = useState('');
- const [showAll, setShowAll] = useState(false);
- const [formOpen, setFormOpen] = useState(false);
- const rootRef = useRef<HTMLDivElement>(null);
- const shownKey = useRef(`${view}|${category}`);
-
- // The blocks rise in again on a new view or category. The first render is
- // the dialog's to stagger.
- useLayoutEffect(() => {
- const key = `${view}|${category}`;
- if (shownKey.current === key) return;
- shownKey.current = key;
- staggerSettings(rootRef.current);
- }, [view, category]);
-
- const list = view === 'yours' ? yours.items : discover.items;
- const { shown, total } = catalogSlice(list, { category, query, cap: view === 'discover' && !showAll ? DISCOVER_LIMIT : null });
- const canShowAll = view === 'discover' && total > DISCOVER_LIMIT;
- const q = query.trim();
-
- const changeView = (next: CatalogView) => {
- setView(next);
- setShowAll(false);
- };
- const toggleFilter = (open: boolean) => {
- setFilterOpen(open);
- if (!open) setCategory('all');
- };
-
- const filtered = q !== '' || category !== 'all';
- const empty = filtered
- ? {
- title: q ? `Nothing matches “${q}”` : 'Nothing in this category',
- detail: q ? 'Try another word.' : 'Try another category.',
- discover: false,
- }
- : view === 'yours'
- ? { ...yours.empty, discover: true }
- : { title: 'Nothing here yet', detail: 'Check back soon.', discover: false };
-
- return (
- <div ref={rootRef} className="flex flex-col gap-5.5 px-8 pt-6.5 pb-8">
- <div data-stagger className="flex flex-wrap items-center gap-3.5 pr-10">
- <h2 className="text-xl font-semibold tracking-[-0.02em] text-fg-default">{title}</h2>
- <ToggleGroup
- type="single"
- variant="segmented"
- aria-label={`${title} to show`}
- value={view}
- onValueChange={(next) => next && changeView(next as CatalogView)}
- >
- <ToggleGroupItem value="yours" className="px-3 text-sm">
- Yours
- <span className="font-mono text-2xs font-normal text-fg-faint">{yours.items.length}</span>
- </ToggleGroupItem>
- <ToggleGroupItem value="discover" className="px-3 text-sm">
- Discover
- </ToggleGroupItem>
- </ToggleGroup>
- <div className="ml-auto flex flex-[1_1_280px] items-center justify-end gap-2">
- <SearchField value={query} onChange={setQuery} placeholder={searchPlaceholder} className="max-w-75 flex-1" />
- {categories.length > 0 && (
- <Toggle
- variant="chips"
- pressed={filterOpen}
- onPressedChange={toggleFilter}
- aria-label="Filter by category"
- title="Filter"
- className="size-9 rounded-row px-0 [&_svg:not([class*='size-'])]:size-4"
- >
- <SlidersHorizontal strokeWidth={1.75} />
- </Toggle>
- )}
- {primaryAction && (
- <Button
- variant="invert"
- size="lg"
- aria-expanded={formOpen}
- onClick={() => setFormOpen((open) => !open)}
- className="rounded-row pr-3.5 pl-3 font-semibold active:scale-97"
- >
- <Plus strokeWidth={2.2} />
- {primaryAction.label}
- </Button>
- )}
- </div>
- </div>
-
- {categories.length > 0 && filterOpen && (
- <ToggleGroup
- data-stagger
- type="single"
- variant="chips"
- size="lg"
- className="-mt-2 gap-2"
- aria-label="Category"
- value={category}
- onValueChange={(next) => next && setCategory(next)}
- >
- <ToggleGroupItem value="all">All</ToggleGroupItem>
- {categories.map((c) => (
- <ToggleGroupItem key={c.key} value={c.key}>
- {c.label}
- </ToggleGroupItem>
- ))}
- </ToggleGroup>
- )}
-
- {primaryAction && formOpen && (
- <div data-stagger className="flex flex-col gap-2.5 rounded-card border border-border-strong bg-bg-elevated p-4">
- {primaryAction.form(() => setFormOpen(false))}
- </div>
- )}
-
- <div data-stagger className="flex items-center gap-2.5">
- <span className="text-lead font-semibold whitespace-nowrap text-fg-default">
- {view === 'yours' ? yours.sectionTitle : discover.sectionTitle}
- </span>
- <Badge variant="outline" className="rounded-md border-border-default bg-bg-app px-1.75 font-mono text-2xs text-fg-muted">
- {total}
- </Badge>
- {canShowAll && (
- <Button variant="quiet" size="sm" onClick={() => setShowAll((all) => !all)} className="ml-auto text-row text-fg-default">
- {showAll ? 'Show less' : 'Show all'}
- <ArrowRight />
- </Button>
- )}
- </div>
-
- {loading && list.length === 0 ? (
- <div className={GRID}>
- {[0, 1, 2, 3].map((i) => (
- <Skeleton key={i} className="h-30 rounded-card" />
- ))}
- </div>
- ) : total > 0 ? (
- <div className={GRID}>
- {shown.map((item) => (
- <CatalogCard
- key={item.id}
- item={item}
- view={view}
- verbs={verbs}
- onAdd={onAdd}
- onRemove={onRemove}
- onToggle={onToggle}
- onItemAdded={onItemAdded}
- />
- ))}
- </div>
- ) : (
- <div
- data-stagger
- className="flex flex-col items-center gap-2.5 rounded-panel border border-dashed border-border-strong px-5 py-10 text-center"
- >
- <span className="text-base font-medium text-fg-default">{empty.title}</span>
- <span className="text-sm text-fg-muted">{empty.detail}</span>
- {empty.discover && (
- <Button
- variant="quiet"
- size="sm"
- onClick={() => changeView('discover')}
- className="mt-1 h-8 border-border-strong px-3.5 font-semibold text-fg-default"
- >
- Discover
- </Button>
- )}
- </div>
- )}
- </div>
- );
-}
-
-function CatalogCard({
- item,
- view,
- verbs,
- onAdd,
- onRemove,
- onToggle,
- onItemAdded,
-}: {
- item: CatalogItem;
- view: CatalogView;
- verbs: CatalogLayoutProps['verbs'];
- onAdd: CatalogLayoutProps['onAdd'];
- onRemove?: CatalogLayoutProps['onRemove'];
- onToggle?: CatalogLayoutProps['onToggle'];
- onItemAdded?: CatalogLayoutProps['onItemAdded'];
-}) {
- const ref = useRef<HTMLDivElement>(null);
- const lastState = useRef(item.state);
- const added = item.state === 'added';
-
- useEffect(() => {
- const before = lastState.current;
- lastState.current = item.state;
- if (item.state !== 'added' || before === 'added') return;
- animate(ref.current, [{ boxShadow: 'var(--glow-connect)' }, { boxShadow: '0 0 0 0 transparent' }], {
- duration: 1200,
- easing: 'default',
- fill: 'none',
- });
- onItemAdded?.(item);
- }, [item, onItemAdded]);
-
- return (
- <div
- ref={ref}
- data-catalog-item={item.id}
- data-stagger
- className={cn(
- 'flex gap-3.5 rounded-card border bg-bg-elevated p-4.5 transition-[border-color,translate,box-shadow] duration-(--dur-default) ease-(--ease-default) hover:-translate-y-0.5 hover:border-border-strong hover:shadow-popover motion-reduce:hover:translate-y-0',
- added ? 'border-status-working-border' : 'border-border-default',
- )}
- >
- <AppMark name={item.name} iconRef={item.tile.iconRef} tone={item.tile.tone} size="xl" />
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <div className="flex min-w-0 items-center gap-1.5">
- <span className="truncate text-lead font-semibold text-fg-default">{item.name}</span>
- {item.verified && (
- <BadgeCheck role="img" aria-label="Verified" strokeWidth={1.75} className="size-3.75 shrink-0 text-fg-faint" />
- )}
- </div>
- {item.description && <p className="line-clamp-2 text-row leading-snug text-fg-muted">{item.description}</p>}
- {item.byline && <span className="mt-0.5 text-sm text-fg-faint">{item.byline}</span>}
- {item.meta && <span className="mt-0.5 font-mono text-2xs text-fg-faint">{item.meta}</span>}
- </div>
- <div className="flex shrink-0 flex-col items-end gap-2">
- <CardAction item={item} view={view} verbs={verbs} onAdd={onAdd} onRemove={onRemove} onToggle={onToggle} />
- </div>
- </div>
- );
-}
-
-const DONE = 'size-8.5 rounded-lg border border-action-run-border bg-action-run-soft text-action-run-ink';
-
-function CardAction({
- item,
- view,
- verbs,
- onAdd,
- onRemove,
- onToggle,
-}: {
- item: CatalogItem;
- view: CatalogView;
- verbs: CatalogLayoutProps['verbs'];
- onAdd: CatalogLayoutProps['onAdd'];
- onRemove?: CatalogLayoutProps['onRemove'];
- onToggle?: CatalogLayoutProps['onToggle'];
-}) {
- const removeVerb = verbs.remove ?? 'Remove';
- if (item.state === 'busy') {
- return (
- <span
- role="status"
- aria-label={`${item.name}: ${verbs.busy ?? 'Working…'}`}
- className="grid size-8.5 place-items-center rounded-lg border border-status-ready-border bg-status-ready-fill"
- >
- <LoaderCircle aria-hidden className="size-3.5 animate-spin text-status-ready-ink" />
- </span>
- );
- }
- if (view === 'discover') {
- if (item.state === 'available') {
- return (
- <Button
- variant="quiet"
- size="icon"
- aria-label={`${verbs.add} ${item.name}`}
- title={`${verbs.add} ${item.name}`}
- onClick={() => onAdd(item)}
- className="size-8.5 border-border-strong bg-bg-app text-fg-default hover:border-action-run-border hover:bg-action-run-soft hover:text-action-run-ink active:scale-92"
- >
- <Plus />
- </Button>
- );
- }
- return onRemove ? (
- <Button
- variant="quiet"
- size="icon"
- aria-label={`${removeVerb} ${item.name}`}
- title={`${removeVerb} ${item.name}`}
- onClick={() => onRemove(item)}
- className={cn(DONE, 'hover:border-action-stop-border hover:bg-action-stop-soft hover:text-action-stop-ink')}
- >
- <Check strokeWidth={2.2} />
- </Button>
- ) : (
- <span role="img" aria-label={`${item.name} added`} className={cn('grid place-items-center', DONE)}>
- <Check aria-hidden strokeWidth={2.2} className="size-4" />
- </span>
- );
- }
- return (
- <>
- {onToggle && (
- <Switch size="md" tone="run" checked={item.enabled ?? false} onCheckedChange={(on) => onToggle(item, on)} aria-label={item.name} />
- )}
- {onRemove && (
- <Button
- variant="quiet"
- size="xs"
- aria-label={`${removeVerb} ${item.name}`}
- onClick={() => onRemove(item)}
- className="mt-auto h-6.5 px-2 text-xs text-fg-faint hover:bg-action-stop-soft hover:text-action-stop-ink"
- >
- {removeVerb}
- </Button>
- )}
- </>
- );
-}
-
-export default CatalogLayout;
+export * from '@/components/catalog/CatalogLayout';
+export { default } from '@/components/catalog/CatalogLayout';
diff --git a/client/src/features/home/settings/ConnectDialog.tsx b/client/src/features/home/settings/ConnectDialog.tsx
deleted file mode 100644
index d369642f..00000000
--- a/client/src/features/home/settings/ConnectDialog.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Connect one app from Normal mode: the editor's credential panel for the
- * provider's kind (API key, OAuth sign-in, QR pairing, email account), in
- * its compact variant (no usage or model-defaults sections). The panel owns
- * every connect / validate / sign-in rule; this is only its frame.
- *
- * Takes a provider id and reads the live catalogue entry, so the panel sees
- * `stored` / `connected` flip the moment the connection lands. When it does,
- * the dialog closes; from outside Settings (a draft's or an employee's
- * "Connect {App}") it also confirms with a toast, which Settings' own card
- * does there.
- */
-
-import { useEffect, useMemo, useRef } from 'react';
-import Modal from '@/components/ui/Modal';
-import PanelRenderer from '@/components/credentials/PanelRenderer';
-import { rehydrateProvider } from '@/components/credentials/catalogueAdapter';
-import { isConnected, useHomeCatalogue } from '../data/connectors';
-import { useHomeStore } from '../state/homeStore';
-import { pillToast } from '../ui/pillToast';
-
-export function ConnectDialog({ providerId, onClose }: { providerId: string | null; onClose: () => void }) {
- const { data } = useHomeCatalogue();
- const provider = useMemo(
- () => (providerId ? (data?.providers.find((p) => p.id === providerId) ?? null) : null),
- [data, providerId],
- );
- const config = useMemo(() => (provider ? rehydrateProvider(provider) : null), [provider]);
-
- // Only the same app going from not connected to connected counts.
- const connected = provider ? isConnected(provider) : false;
- const seen = useRef({ id: providerId, known: provider !== null, connected });
- useEffect(() => {
- const before = seen.current;
- seen.current = { id: providerId, known: provider !== null, connected };
- const flipped = before.id === providerId && before.known && !before.connected && connected;
- if (!flipped || !provider) return;
- if (!useHomeStore.getState().settingsOpen) pillToast(`${provider.name} is connected`);
- onClose();
- }, [providerId, provider, connected, onClose]);
-
- return (
- <Modal
- isOpen={providerId !== null}
- onClose={onClose}
- title={provider ? `Connect ${provider.name}` : 'Connect'}
- titleIcon={null}
- motion="spring"
- maxWidth="min(560px, calc(100vw - 2rem))"
- maxHeight="min(720px, calc(100vh - 2rem))"
- autoHeight
- className="rounded-panel bg-bg-panel shadow-dialog"
- >
- <PanelRenderer config={config} visible={providerId !== null} variant="compact" />
- </Modal>
- );
-}
-
-export default ConnectDialog;
diff --git a/client/src/features/home/settings/ConnectorsTab.tsx b/client/src/features/home/settings/ConnectorsTab.tsx
index 126f8693..4b96d1d2 100644
--- a/client/src/features/home/settings/ConnectorsTab.tsx
+++ b/client/src/features/home/settings/ConnectorsTab.tsx
@@ -1,138 +1,2 @@
-/**
- * Settings > Connectors (design handoff): every app the owner can connect,
- * on the shared catalog page. Discover lists them all, apps before AI
- * models; Yours lists the connected ones.
- *
- * "+" opens the provider's own credential panel (ConnectDialog).
- * Disconnect removes what the panel would remove for API-key and signed-in
- * providers, after a confirmation; for the rest (a paired phone, an email
- * account) it opens the panel, which owns those steps. A card glows and a
- * toast confirms only when a provider actually flips to connected while
- * the page is open, never on first render. There is no custom connector:
- * nothing serves one yet, so the page has no Add button.
- */
-
-import { useMemo, useState } from 'react';
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@/components/ui/alert-dialog';
-import { useWebSocketActions } from '@/contexts/WebSocketContext';
-import { isConnected, useConnectors, type ConsumerProvider } from '../data/connectors';
-import { pillToast } from '../ui/pillToast';
-import type { CatalogItem } from './catalog';
-import { CatalogLayout } from './CatalogLayout';
-
-/** Remove a provider's credential the way its panel would. False when the
- * panel has to do it (QR pairing, the IMAP/SMTP account). */
-async function disconnect(
- provider: ConsumerProvider,
- sendRequest: <T = unknown>(type: string, data?: Record<string, unknown>) => Promise<T>,
-): Promise<boolean> {
- if (provider.kind === 'apiKey') {
- await sendRequest('delete_api_key', { provider: provider.id });
- // Local model servers also keep their base URL under the field key.
- const fieldKey = provider.fields?.[0]?.key;
- if (fieldKey && fieldKey !== 'apiKey') await sendRequest('delete_api_key', { provider: fieldKey });
- return true;
- }
- if (provider.kind === 'oauth' && provider.ws?.logout) {
- await sendRequest(provider.ws.logout, {});
- return true;
- }
- return false;
-}
-
-function toItem(provider: ConsumerProvider): CatalogItem {
- const connected = isConnected(provider);
- const meta = [
- connected && provider.account_label ? `Connected as ${provider.account_label}` : null,
- provider.runs_locally ? 'Runs on this computer' : null,
- ]
- .filter(Boolean)
- .join(' · ');
- return {
- id: provider.id,
- name: provider.name,
- description: provider.description,
- byline: provider.publisher ? `by ${provider.publisher}` : undefined,
- verified: provider.verified,
- category: provider.consumer_category,
- meta: meta || undefined,
- tile: { iconRef: provider.icon_ref },
- state: connected ? 'added' : 'available',
- };
-}
-
-export function ConnectorsTab({
- onConnect,
- initialCategory = 'all',
-}: {
- onConnect: (providerId: string) => void;
- initialCategory?: string;
-}) {
- const { providers, categories, isLoading } = useConnectors();
- const { sendRequest } = useWebSocketActions();
- const [confirming, setConfirming] = useState<ConsumerProvider | null>(null);
- const byId = useMemo(() => new Map(providers.map((provider) => [provider.id, provider])), [providers]);
- const items = useMemo(() => providers.map(toItem), [providers]);
- const connected = useMemo(() => items.filter((item) => item.state === 'added'), [items]);
-
- const confirmDisconnect = async () => {
- const provider = confirming;
- setConfirming(null);
- if (!provider) return;
- try {
- const done = await disconnect(provider, sendRequest);
- if (done) pillToast(`${provider.name} disconnected`, { tone: 'info' });
- else onConnect(provider.id);
- } catch (error) {
- pillToast(error instanceof Error ? error.message : `Couldn't disconnect ${provider.name}`, { tone: 'error' });
- }
- };
-
- return (
- <>
- <CatalogLayout
- title="Connectors"
- searchPlaceholder="Search connectors"
- loading={isLoading}
- categories={categories}
- initialCategory={initialCategory}
- yours={{
- items: connected,
- sectionTitle: 'Connected',
- empty: { title: 'No apps connected yet', detail: 'Connect the apps your employees should work in.' },
- }}
- discover={{ items, sectionTitle: 'Top connectors' }}
- verbs={{ add: 'Connect', remove: 'Disconnect' }}
- onAdd={(item) => onConnect(item.id)}
- onRemove={(item) => setConfirming(byId.get(item.id) ?? null)}
- onItemAdded={(item) => pillToast(`${item.name} is connected`)}
- />
-
- <AlertDialog open={confirming !== null} onOpenChange={(open) => !open && setConfirming(null)}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Disconnect {confirming?.name}?</AlertDialogTitle>
- <AlertDialogDescription>
- Employees that use {confirming?.name} stop using it until you connect it again.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Keep it</AlertDialogCancel>
- <AlertDialogAction onClick={() => void confirmDisconnect()}>Disconnect</AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </>
- );
-}
-
-export default ConnectorsTab;
+/** Home and Dev use the same credentials browser. */
+export { CredentialsBrowser as ConnectorsTab, CredentialsBrowser as default } from '@/components/credentials/CredentialsBrowser';
diff --git a/client/src/features/home/settings/HomeSettings.tsx b/client/src/features/home/settings/HomeSettings.tsx
index 9d51001e..c7004ab7 100644
--- a/client/src/features/home/settings/HomeSettings.tsx
+++ b/client/src/features/home/settings/HomeSettings.tsx
@@ -3,8 +3,8 @@
* behind a left nav, in the shared Modal with its spring entrance. One
* `PAGES` list drives both the nav and the panels. The nav's search keeps
* the pages whose label or keywords match, and drops a group with none.
- * Connect dialogs open on top from Connectors (and from an employee's
- * "Connect {App}"); HomeShell owns them.
+ * Connectors opens the app shell's shared credentials dialog on top, so
+ * closing it returns to the same Settings page.
*/
import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
@@ -12,11 +12,12 @@ import { CircleUserRound, CreditCard, Grid2x2Plus, Plug, Star, X, type LucideIco
import { Tabs as TabsPrimitive } from 'radix-ui';
import { OcLogo } from '@/components/brand/Logo';
import { Button } from '@/components/ui/button';
+import { CredentialsBrowser } from '@/components/credentials/CredentialsBrowser';
import Modal from '@/components/ui/Modal';
+import type { CredentialsIntent } from '@/stores/shellDialogsStore';
import { useHomeStore, type SettingsTab } from '../state/homeStore';
import { MicroLabel, SearchField } from '../ui/primitives';
import { BillingTab } from './BillingTab';
-import { ConnectorsTab } from './ConnectorsTab';
import { PluginsTab } from './PluginsTab';
import { ProfileTab } from './ProfileTab';
import { SkillsTab } from './SkillsTab';
@@ -27,7 +28,7 @@ const NAV_ITEM =
interface PageContext {
close: () => void;
- onConnect: (providerId: string) => void;
+ onConnect: (providerId: string, intent?: CredentialsIntent) => void;
/** The category the page was opened on ('all' when none). */
initialCategory: string;
}
@@ -78,7 +79,7 @@ const PAGES: Page[] = [
label: 'Connectors',
icon: Grid2x2Plus,
keywords: 'apps',
- render: ({ onConnect, initialCategory }) => <ConnectorsTab onConnect={onConnect} initialCategory={initialCategory} />,
+ render: ({ onConnect, initialCategory }) => <CredentialsBrowser onConnect={onConnect} initialCategory={initialCategory} />,
},
{
tab: 'plugins',
@@ -128,7 +129,7 @@ function SettingsNav() {
);
}
-export function HomeSettings({ onConnect }: { onConnect: (providerId: string) => void }) {
+export function HomeSettings({ onConnect }: { onConnect: (providerId: string, intent?: CredentialsIntent) => void }) {
const open = useHomeStore((s) => s.settingsOpen);
const tab = useHomeStore((s) => s.settingsTab);
const category = useHomeStore((s) => s.settingsCategory);
diff --git a/client/src/features/home/settings/catalog.ts b/client/src/features/home/settings/catalog.ts
index 373874eb..6bf32f09 100644
--- a/client/src/features/home/settings/catalog.ts
+++ b/client/src/features/home/settings/catalog.ts
@@ -1,46 +1 @@
-/**
- * The shared catalog behind Settings > Skills, Connectors and Plugins
- * (design handoff "Settings: Billing, Skills, Plugins"): what one card
- * shows, and how a list is narrowed for display. Each page maps its own
- * records to `CatalogItem`s; nothing here knows which page it is on.
- */
-
-import type { ColorRole } from '../data/schemas';
-
-export type CatalogView = 'yours' | 'discover';
-
-export interface CatalogItem {
- id: string;
- name: string;
- description?: string;
- /** "by Google", "by you". Searched along with the name and description. */
- byline?: string;
- verified?: boolean;
- /** A category key, for the filter chips. */
- category?: string;
- /** One short mono line under the byline. */
- meta?: string;
- /** A brand icon, or tinted initials when there is none. */
- tile: { iconRef?: string | null; tone?: ColorRole };
- state: 'available' | 'busy' | 'added';
- /** The switch in Yours, shown only when the page can toggle items. */
- enabled?: boolean;
-}
-
-/** Discover shows this many cards until "Show all". */
-export const DISCOVER_LIMIT = 8;
-
-/** Items in `category` ('all' for every one) matching `query`, the first
- * `cap` of them when a cap is given. `total` counts every match. */
-export function catalogSlice(
- items: CatalogItem[],
- { category, query, cap }: { category: string; query: string; cap: number | null },
-): { shown: CatalogItem[]; total: number } {
- const q = query.trim().toLowerCase();
- const matched = items.filter((item) => {
- if (category !== 'all' && item.category !== category) return false;
- if (!q) return true;
- return [item.name, item.description, item.byline].some((text) => text?.toLowerCase().includes(q));
- });
- return { shown: cap === null ? matched : matched.slice(0, cap), total: matched.length };
-}
+export * from '@/components/catalog/catalog';
diff --git a/client/src/features/home/settings/stagger.ts b/client/src/features/home/settings/stagger.ts
index 96044e70..fb916688 100644
--- a/client/src/features/home/settings/stagger.ts
+++ b/client/src/features/home/settings/stagger.ts
@@ -1,20 +1 @@
-/**
- * Settings blocks rise in, 30ms apart (design handoff "Settings modal"):
- * every `[data-stagger]` under `root`. HomeSettings plays it when the dialog
- * opens or the tab changes; a catalog page plays it again when its view or
- * category changes.
- */
-
-import { stagger } from '@/lib/motion';
-
-export function staggerSettings(root: ParentNode | null | undefined): void {
- if (!root) return;
- stagger(
- root.querySelectorAll('[data-stagger]'),
- [
- { opacity: 0, transform: 'translateY(10px)' },
- { opacity: 1, transform: 'none' },
- ],
- { base: 40, step: 30, cap: 14, duration: 420, easing: 'spring' },
- );
-}
+export * from '@/components/catalog/stagger';
diff --git a/client/src/features/home/state/homeStore.ts b/client/src/features/home/state/homeStore.ts
index 17fdac7b..9badc8f7 100644
--- a/client/src/features/home/state/homeStore.ts
+++ b/client/src/features/home/state/homeStore.ts
@@ -1,6 +1,6 @@
/**
* Normal mode's UI state: which view is showing, the sidebar, the Settings
- * dialog, the guided "Connect an AI model" dialog, the Workspace dock, and
+ * dialog, the Workspace dock, and
* the one-shot signals the hire choreography fires (a sidebar row's glow,
* the logo pulse, what a hire could not set up as asked). Server data lives
* in TanStack Query (features/home/data), never here.
@@ -8,6 +8,7 @@
import { z } from 'zod';
import { create } from 'zustand';
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
import { SPIKE, spikeOrb } from '../orb/orb';
export type HomeView = { kind: 'hire' } | { kind: 'employee'; workflowId: string };
@@ -85,8 +86,6 @@ interface HomeState {
logoPulse: number;
/** Bumped to ask the composer to take focus. */
composerFocus: number;
- /** The guided "Connect an AI model" dialog (connectAI/ConnectAIDialog). */
- connectAIOpen: boolean;
/** What the last hire said, for its employee's page (hire/HireNotice). */
hireNotice: HireNotice | null;
/** The Workspace dock. Open, width and tab persist; the rest is this
@@ -107,7 +106,6 @@ interface HomeState {
glowRow: (workflowId: string) => void;
pulseLogo: () => void;
openConnectAI: () => void;
- closeConnectAI: () => void;
setHireNotice: (notice: HireNotice | null) => void;
/** The composer took the focus it was asked for; a remount must not
* take it again. */
@@ -131,7 +129,6 @@ export const useHomeStore = create<HomeState>((set, get) => ({
glow: null,
logoPulse: 0,
composerFocus: 0,
- connectAIOpen: false,
hireNotice: null,
workspaceOpen: workspace.open,
workspaceWidth: workspace.widthPx,
@@ -171,10 +168,9 @@ export const useHomeStore = create<HomeState>((set, get) => ({
set((state) => ({ glow: { workflowId, nonce: (state.glow?.nonce ?? 0) + 1 } })),
pulseLogo: () => set((state) => ({ logoPulse: state.logoPulse + 1 })),
openConnectAI: () => {
- if (!get().connectAIOpen) spikeOrb(SPIKE.connect);
- set({ connectAIOpen: true });
+ spikeOrb(SPIKE.connect);
+ useShellDialogsStore.getState().openCredentials({ categoryId: 'ai', intent: 'connect' });
},
- closeConnectAI: () => set({ connectAIOpen: false }),
setHireNotice: (notice) => set({ hireNotice: notice }),
consumeComposerFocus: () => set((state) => (state.composerFocus === 0 ? state : { composerFocus: 0 })),
openWorkspace: (workflowId) => {
diff --git a/client/src/features/home/ui/primitives.tsx b/client/src/features/home/ui/primitives.tsx
index a88dcffb..96f40511 100644
--- a/client/src/features/home/ui/primitives.tsx
+++ b/client/src/features/home/ui/primitives.tsx
@@ -5,11 +5,7 @@
*/
import type { ReactNode } from 'react';
-import { Search } from 'lucide-react';
-import { NodeIcon } from '@/assets/icons';
-import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
-import { theme } from '@/styles/theme';
import {
AVATAR_CLASS,
STATUS_DOT_CLASS,
@@ -110,71 +106,4 @@ export function MicroLabel({ children, className }: { children: ReactNode; class
);
}
-const MARK_SIZE = {
- xs: { box: 'size-5', icon: theme.iconSize.xs },
- sm: { box: 'size-5.5', icon: theme.iconSize.xs },
- lg: { box: 'size-9.5 rounded-row', icon: theme.iconSize.md },
- xl: { box: 'size-12.5 rounded-card text-sm', icon: theme.iconSize.lg },
-} as const;
-
-/** An app's brand mark (the credential catalogue's icon), in a disc. Falls
- * back to the app's first two letters, tinted in `tone` when given (a
- * skill or starter tile). */
-export function AppMark({
- name,
- iconRef,
- size = 'sm',
- tone,
- className,
-}: {
- name: string;
- iconRef?: string | null;
- size?: keyof typeof MARK_SIZE;
- tone?: ColorRole;
- className?: string;
-}) {
- const spec = MARK_SIZE[size];
- const letters = name.replace(/[^\p{L}\p{N}]/gu, '').slice(0, 2).toUpperCase();
- return (
- <span
- aria-hidden
- className={cn(
- 'grid shrink-0 place-items-center rounded-full border font-mono text-2xs font-semibold',
- tone ? AVATAR_CLASS[tone] : 'border-border-default bg-bg-panel text-fg-muted',
- spec.box,
- className,
- )}
- >
- <NodeIcon icon={iconRef} size={spec.icon} fallback={<span>{letters}</span>} />
- </span>
- );
-}
-
-/** A search box on a Home surface (Settings nav, the catalog pages). The
- * placeholder doubles as its accessible name unless `label` says otherwise. */
-export function SearchField({
- value,
- onChange,
- placeholder,
- label,
- className,
-}: {
- value: string;
- onChange: (value: string) => void;
- placeholder: string;
- label?: string;
- className?: string;
-}) {
- return (
- <div className={cn('relative min-w-0', className)}>
- <Search aria-hidden className="pointer-events-none absolute top-1/2 left-3 size-3.75 -translate-y-1/2 text-fg-faint" />
- <Input
- value={value}
- onChange={(event) => onChange(event.target.value)}
- placeholder={placeholder}
- aria-label={label ?? placeholder}
- className="h-9 rounded-row bg-bg-app pl-8.5 text-row font-normal md:text-row dark:bg-bg-app"
- />
- </div>
- );
-}
+export { AppMark, SearchField } from '@/components/catalog/primitives';
diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.ts
index d5b9673d..cc7cd904 100644
--- a/client/src/hooks/useCatalogueQuery.ts
+++ b/client/src/hooks/useCatalogueQuery.ts
@@ -13,9 +13,9 @@
* `since` fetches — if the catalogue is unchanged, the server returns
* `{unchanged: true}` and we keep using the cached data.
*
- * The store (`useCredentialRegistry`) holds only UI state. Derived data
- * like the `byId` Map, the fuzzysort-prepared index, and the filtered
- * result set all live in `useMemo` inside `CredentialsPalette.tsx`.
+ * The shell dialog store holds navigation intent only. The shared
+ * CredentialsBrowser derives its filtered provider list from this cache;
+ * search/category state stays local to its reusable CatalogLayout.
*
* See: `docs-internal/credentials_scaling/research_react_stack.md` for the
* store-shape decision and runtime/memory traps this design avoids.
@@ -136,7 +136,7 @@ export interface ServerProviderConfig {
* unless the provider declares a live check (WhatsApp's pairing, the
* IMAP/SMTP account's keys). */
connected?: boolean;
- /** Normal-mode Connectors category; providers without one are editor-only. */
+ /** Shared Connectors category; declared by every shipped provider. */
consumer_category?: string | null;
/** One short line for the Normal-mode Connectors card. */
description?: string;
diff --git a/client/src/hooks/useNodeAllowlist.ts b/client/src/hooks/useNodeAllowlist.ts
index 9c7655a6..c9f7d96a 100644
--- a/client/src/hooks/useNodeAllowlist.ts
+++ b/client/src/hooks/useNodeAllowlist.ts
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useRef } from 'react';
-import { useWebSocket } from '../contexts/WebSocketContext';
+import { useWebSocketActions } from '../contexts/WebSocketContext';
interface NodeAllowlistResponse {
show_all: boolean;
@@ -52,7 +52,7 @@ interface NodeAllowlistResponse {
* doesn't ship the fields (older deployments).
*/
export const useNodeAllowlist = () => {
- const { sendRequest, isConnected } = useWebSocket();
+ const { sendRequest, isConnected } = useWebSocketActions();
const [config, setConfig] = useState<NodeAllowlistResponse | null>(null);
const hasFetchedRef = useRef(false);
@@ -147,6 +147,8 @@ export const useNodeAllowlist = () => {
);
return {
+ /** Credentials wait for category visibility before mounting a provider form. */
+ isLoading: config === null,
isVisible,
isBlocked,
isAllowed,
diff --git a/client/src/store/useCredentialRegistry.ts b/client/src/store/useCredentialRegistry.ts
deleted file mode 100644
index ae68b28a..00000000
--- a/client/src/store/useCredentialRegistry.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Credentials panel UI store.
- *
- * Holds ONLY UI state — `selectedId`, `paletteOpen`, `query`. The catalogue
- * data itself lives in TanStack Query (see `hooks/useCatalogueQuery.ts`).
- * Derived data (filtered providers, prepared fuzzysort index, byId Map)
- * lives in `useMemo` inside the component that needs it.
- *
- * Why: a Zustand selector that closes over a 5000-entry catalogue retains
- * the whole array in the closure scope forever. The fix is to never put
- * the catalogue inside the store. See
- * `docs-internal/credentials_scaling/research_react_stack.md` — "Top 5
- * runtime/memory traps", trap #1.
- */
-
-import { create } from 'zustand';
-
-export interface CredentialRegistryUIState {
- selectedId: string | null;
- paletteOpen: boolean;
- query: string;
-
- setSelectedId: (id: string | null) => void;
- openPalette: () => void;
- closePalette: () => void;
- togglePalette: () => void;
- setQuery: (q: string) => void;
- reset: () => void;
-}
-
-const INITIAL: Pick<CredentialRegistryUIState, 'selectedId' | 'paletteOpen' | 'query'> = {
- selectedId: null,
- paletteOpen: false,
- query: '',
-};
-
-export const useCredentialRegistry = create<CredentialRegistryUIState>((set) => ({
- ...INITIAL,
- setSelectedId: (id) => set({ selectedId: id }),
- openPalette: () => set({ paletteOpen: true }),
- closePalette: () => set({ paletteOpen: false }),
- togglePalette: () => set((s) => ({ paletteOpen: !s.paletteOpen })),
- setQuery: (q) => set({ query: q }),
- reset: () => set(INITIAL),
-}));
diff --git a/client/src/stores/__tests__/shellDialogsStore.test.ts b/client/src/stores/__tests__/shellDialogsStore.test.ts
new file mode 100644
index 00000000..179cd665
--- /dev/null
+++ b/client/src/stores/__tests__/shellDialogsStore.test.ts
@@ -0,0 +1,38 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { useShellDialogsStore } from '../shellDialogsStore';
+
+beforeEach(() => {
+ useShellDialogsStore.setState({
+ credentialsOpen: false,
+ credentialsOptions: { intent: 'manage' },
+ credentialsRequestId: 0,
+ });
+});
+
+describe('credentials navigation requests', () => {
+ it('opens the manager without retaining the last contextual target', () => {
+ useShellDialogsStore.getState().openCredentials({ providerId: 'gemini', categoryId: 'ai', intent: 'connect' });
+ useShellDialogsStore.getState().closeCredentials();
+ useShellDialogsStore.getState().openCredentials();
+
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { intent: 'manage' },
+ credentialsRequestId: 2,
+ });
+ expect(useShellDialogsStore.getState().credentialsOptions).toEqual({ intent: 'manage' });
+ });
+
+ it('reopens the same target as a fresh request and defaults its intent to manage', () => {
+ const options = { providerId: 'google' };
+ useShellDialogsStore.getState().openCredentials(options);
+ useShellDialogsStore.getState().openCredentials(options);
+
+ expect(useShellDialogsStore.getState()).toMatchObject({
+ credentialsOpen: true,
+ credentialsOptions: { providerId: 'google', intent: 'manage' },
+ credentialsRequestId: 2,
+ });
+ expect(options).toEqual({ providerId: 'google' });
+ });
+});
diff --git a/client/src/stores/shellDialogsStore.ts b/client/src/stores/shellDialogsStore.ts
index 0ed5c1dc..1dacc1e2 100644
--- a/client/src/stores/shellDialogsStore.ts
+++ b/client/src/stores/shellDialogsStore.ts
@@ -7,14 +7,25 @@
import { create } from 'zustand';
+export type CredentialsIntent = 'connect' | 'manage';
+
+export interface CredentialsOptions {
+ providerId?: string;
+ categoryId?: string;
+ intent?: CredentialsIntent;
+}
+
interface ShellDialogsState {
settingsOpen: boolean;
credentialsOpen: boolean;
+ credentialsOptions: CredentialsOptions & { intent: CredentialsIntent };
+ /** Repeated opens are navigation requests, even when their target matches. */
+ credentialsRequestId: number;
/** Increments to ask the (editor-only) onboarding wizard to reopen. */
onboardingReplay: number;
openSettings: () => void;
closeSettings: () => void;
- openCredentials: () => void;
+ openCredentials: (options?: CredentialsOptions) => void;
closeCredentials: () => void;
replayOnboarding: () => void;
}
@@ -22,10 +33,16 @@ interface ShellDialogsState {
export const useShellDialogsStore = create<ShellDialogsState>((set) => ({
settingsOpen: false,
credentialsOpen: false,
+ credentialsOptions: { intent: 'manage' },
+ credentialsRequestId: 0,
onboardingReplay: 0,
openSettings: () => set({ settingsOpen: true }),
closeSettings: () => set({ settingsOpen: false }),
- openCredentials: () => set({ credentialsOpen: true }),
+ openCredentials: (options) => set((state) => ({
+ credentialsOpen: true,
+ credentialsOptions: { ...options, intent: options?.intent ?? 'manage' },
+ credentialsRequestId: state.credentialsRequestId + 1,
+ })),
closeCredentials: () => set({ credentialsOpen: false }),
replayOnboarding: () => set((state) => ({ settingsOpen: false, onboardingReplay: state.onboardingReplay + 1 })),
}));
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 3484a772..b20a3e5e 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -37,10 +37,9 @@ Post-migration (2026-04-14). Single source of truth for the current frontend.
| Forms | `react-hook-form@7` + `zod@4` + `@hookform/resolvers` | Credential panels + sections |
| Toasts | `sonner` | Direct imports; shadcn `<Toaster />` wrapper mounted in `App.tsx` |
| Server state | `@tanstack/react-query@5` | `useCatalogueQuery`, `useProviderStatus`, etc. |
-| UI state | `zustand@5` | `useAppStore`, `useCredentialRegistry` (UI-only, never holds catalogue data) |
+| UI state | `zustand@5` | `useAppStore`, `shellDialogsStore` (UI-only, never holds catalogue data) |
| Realtime | native WebSocket wrapped by `WebSocketContext` | `contexts/WebSocketContext.tsx` |
-| Search palette | `cmdk@1` + `fuzzysort@3` | `CredentialsPalette` |
-| Virtualization | `react-virtuoso@4` | `GroupedVirtuoso` in `CredentialsPalette` (grouped, variable-height) |
+| Search palette | `cmdk@1` | App command palette; credentials use shared searchable catalog cards |
| IndexedDB | `idb-keyval@6` | Warm-start cache for the credentials catalogue |
| Canvas | `reactflow@11` | Workflow editor |
| Code editor | `react-simple-code-editor` + `prismjs` | Python/JS/TS node editors |
@@ -97,8 +96,9 @@ client/src/
│ │ # headerActions) so call sites didn't churn.
│ │
│ ├── credentials/ # EXEMPLAR SUBSYSTEM — see "Credentials" section below
-│ │ ├── CredentialsModal.tsx # Shell — palette + PanelRenderer
-│ │ ├── CredentialsPalette.tsx # cmdk + fuzzysort + GroupedVirtuoso
+│ │ ├── CredentialsModal.tsx # Shared app-level browser + provider dialogs
+│ │ ├── CredentialsBrowser.tsx # Connector cards; also embedded in Home Settings
+│ │ ├── catalogue.ts # Shared catalogue ordering + category visibility
│ │ ├── PanelRenderer.tsx # Lazy-loads panel by kind
│ │ ├── catalogueAdapter.ts # Server JSON -> ProviderConfig
│ │ ├── types.ts # ProviderConfig, FieldDef, PanelKind, etc.
@@ -172,7 +172,6 @@ client/src/
│
├── store/
│ ├── useAppStore.ts # UI state (sidebar, palette, shellMode, pro mode, persisted)
-│ └── useCredentialRegistry.ts # UI-only: selectedId + paletteOpen + query
│
├── styles/
│ └── theme.ts # `lightColors` / `darkColors` base packs,
@@ -384,13 +383,13 @@ hooks/useCatalogueQuery.ts (TanStack Query + idb-keyval warm-start)
components/credentials/catalogueAdapter.ts (hydrate JSON -> ProviderConfig)
│
▼
-components/credentials/CredentialsModal.tsx
- ├─ CredentialsPalette.tsx (cmdk + fuzzysort + GroupedVirtuoso)
+components/credentials/CredentialsModal.tsx (one AppShell host)
+ ├─ CredentialsBrowser.tsx (shared cards, also embedded in Home Settings)
└─ PanelRenderer.tsx (lazy: ApiKey/OAuth/QrPairing/Email/BrowserProfiles)
```
**State rules:**
-- **Zustand** (`useCredentialRegistry`) holds ONLY UI state: `selectedId`, `paletteOpen`, `query`. Never catalogue data. Prevents the closure-retention bug where selectors keep the whole 5000-entry catalogue in memory.
+- **Zustand** (`shellDialogsStore`) holds only dialog navigation: optional provider/category target, `connect` or `manage` intent, and a request counter. Search/category state is local to shared `components/catalog/CatalogLayout`; neither owns catalogue or credential data.
- **TanStack Query** owns the server state (catalogue, usage summaries, etc).
- **idb-keyval** cache seeds first paint — opened modal renders from IndexedDB in <50 ms before the WS roundtrip completes.
- **`requestIdleCallback`** writes back to IDB so saves don't block first paint.
@@ -406,6 +405,9 @@ components/credentials/CredentialsModal.tsx
**Anchor cache contracts at the prefix root via `setQueryDefaults`, not per-call options.** `PersistQueryClientProvider` hydrates entries from localStorage with the QueryClient's *default* options, so per-call `staleTime: FOREVER` does not stop `gcTime: 5min` eviction on hydration. Every persisted prefix must have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in [client/src/lib/queryClient.ts](../client/src/lib/queryClient.ts). The persisted set is `['nodeSpec']`, `['nodeGroups']`; both carry `setQueryDefaults`. `['skillContent']` and `['credentialValues']` carry `setQueryDefaults` for in-memory longevity only and are intentionally absent from the persistor whitelist. The persistor whitelist in [client/src/lib/queryPersist.ts](../client/src/lib/queryPersist.ts) must mirror it; a string in the whitelist that doesn't match a real query key (the prior `'pluginCatalogue'` typo) is silently dead. `credentialCatalogue` is intentionally NOT in either list — it has its own `idb-keyval` warm-start. `credentialValues` keeps `gcTime: FOREVER` for the in-memory cache so the credentials form survives idle, but it is intentionally NOT persisted (OWASP — see "Persistence layers" above).
**Component rules:**
+- Normal and Dev use the same connector cards and provider dialogs. `openCredentials({ providerId?, categoryId?, intent? })` defaults to management; guided connection intent closes on a selected provider's disconnected-to-connected transition. Connected cards expose Manage and Disconnect. All entry points use the app-level host, including Home's AI setup action.
+- The host derives `showTechnicalSections` from effective `useShellMode()` (including the Home-disabled fallback). Provider defaults, usage and rate limits mount only in Dev. Required authentication fields, callback URLs and setup help remain available in both modes; normal-mode saves never clear advanced values.
+- The shared catalogue waits for credential-category visibility before mounting a provider form, including direct targets. Missing or disabled targets show an unavailable state. The credential panel is keyed by provider ID, never mode: switching mode preserves connection drafts, while switching providers resets transient errors and secret reveal state.
- `PanelRenderer` lazy-loads each panel type so the initial JS payload doesn't grow linearly with provider count.
- Panels are config-driven: `StatusCard`, `ActionBar`, `FieldRenderer`, `OAuthConnect` consume `ProviderConfig` fields rather than hand-coding per-provider JSX.
- Exception: EmailPanel has conditional `custom` IMAP/SMTP fields that the simple schema can't express — it gets a dedicated zod schema and RHF form. That's the boundary where config-driven hands off to hand-written.
@@ -528,7 +530,7 @@ This is the rule that keeps the data layer schema-driven instead of imperatively
| Owns | What goes here | Examples |
|---|---|---|
| **TanStack Query** | Anything the server has authoritative state for. List / single-record / settings reads. Mutations that change server state. | `useWorkflowsQuery`, `useNodeParamsQuery`, `useUserSettingsQuery`, `useCatalogueQuery`, `useSaveWorkflowMutation`, `useSaveNodeParamsMutation`, `useSaveUserSettingsMutation` |
-| **Zustand** | UI-only state that survives navigation. The active edit buffer for the current workflow. Sidebar/panel visibility flags. | `useAppStore.currentWorkflow` (mutable buffer), `sidebarVisible`, `shellMode`, `proMode`, `renamingNodeId`, `useCredentialRegistry.selectedId`, Home's `useHomeStore` |
+| **Zustand** | UI-only state that survives navigation. The active edit buffer for the current workflow. Sidebar/panel visibility flags. | `useAppStore.currentWorkflow` (mutable buffer), `sidebarVisible`, `shellMode`, `proMode`, `renamingNodeId`, `shellDialogsStore.credentialsOptions`, Home's `useHomeStore` |
| **`useState` / `useReducer`** | Per-component transient state. Form-field drafts. Hover/focus. | text-input drafts, dropdown-open, inline-edit toggles |
| **`WebSocketContext`** | Raw WS connection, `sendRequest`, push-only broadcast slices (workflow progress, android/whatsapp/twitter status, console/terminal logs). The provider value is `useMemo`'d so unrelated state changes do not re-render every consumer. Exposes `isConnected` (socket open) and `isReady` (open + pending-send queue drained); gate catalogue/spec queries on `isReady`. `drainPendingSends(ws)` runs synchronously, then `setIsReady(true)` fires immediately; terminal/chat/console history restore is fire-and-forget in the background (Wave 32 removed the init-burst gate and the hardcoded `probeApiKey` loop). Catalogue invalidation routes through `invalidateCatalogue(queryClient)` ([`hooks/useCatalogueQuery.ts`](../client/src/hooks/useCatalogueQuery.ts)) which debounces the refetch on a 300 ms trailing edge, so an oauth burst or multi-service reconnect collapses to one refetch instead of N. | `androidStatus`, `consoleLogs`, broadcast streams |
| **`stores/nodeStatusStore.ts`** (Zustand) | Per-workflow node-execution statuses -- moved out of WebSocketContext so a status tick does not cascade through the React tree. `useNodeStatus(id)` is a slice selector; only the affected node's consumers re-render. Mirror this pattern for any new high-frequency push state. | `allStatuses[workflowId][nodeId]`, `currentWorkflowId` |
diff --git a/docs-internal/node_allowlist.md b/docs-internal/node_allowlist.md
index 4a61bdc6..7c76486b 100644
--- a/docs-internal/node_allowlist.md
+++ b/docs-internal/node_allowlist.md
@@ -111,7 +111,7 @@ Read via `services.node_allowlist.get_node_allowlist_service().get_config()` —
| `client/src/components/ui/ComponentPalette.tsx` | `if (isBlocked(name, groups)) return false; if (!showAll && !isAllowed(name)) return false;` where `showAll = featureFlags.normalMode \|\| proMode` |
| `server/services/employees/builder.py` | every node Hire builds must pass `is_hire_allowed(node_type)` |
| `server/nodes/tool/agent_builder/__init__.py` | the blocklists in an editor-built workflow; `policy.check_tool` (`is_hire_allowed` and the rest of Hire's rule) on a hired employee |
-| `client/src/components/credentials/CredentialsModal.tsx` | `providers.filter(p => !isCredentialCategoryDisabled(p.category))` + same for `categories` |
+| `client/src/components/credentials/catalogue.ts` | Shared Normal/Dev browser and direct targets wait for category visibility, filter disabled provider categories, then derive visible consumer categories |
| `client/src/components/parameterPanel/MasterSkillEditor.tsx` | `(foldersQuery.data ?? []).filter(f => !isSkillFolderDisabled(f.name))` |
## Backend service
diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.md
index 8fc629eb..7b4ae8c0 100644
--- a/docs-internal/normal_mode.md
+++ b/docs-internal/normal_mode.md
@@ -71,7 +71,7 @@ is the reference.
| `employee/` | One employee's page, which is the conversation with them: only their name under a small orb, then Talk (below). What to act on shows in the conversation only while there is something to do: the drafts waiting for the owner after the messages, and above the message box their main action while they can't read messages (Resume, Start, or connect what is missing; `useEmployeeControl`, `PrimaryActionButton`) or Help in browser while they wait there. It never says why they stopped. Pausing them, and watching them work, is the Workspace's: the header's Workspace pill opens it on the employee on screen, and its header carries the same main action |
| `connectAI/` | The guided Connect an AI model dialog (below) |
| `workspace/` | The Workspace dock (below), its header pill, and its Canvas tab, which loads in its own chunk |
-| `settings/` | The Settings pages (Profile, Billing, Skills, Connectors, Plugins), the shared catalog page the last three build on, and `ConnectDialog` (the editor's credential panel for one provider, in its compact variant) |
+| `settings/` | Settings pages (Profile, Billing, Skills, Connectors, Plugins). Catalog primitives live in `components/catalog`; Connectors embeds the shared `components/credentials/CredentialsBrowser`. Provider dialogs belong to AppShell. |
| `approvals/` | The drafts query, the decide mutation (optimistic), the approval broadcast listener |
| `data/` | zod-parsed queries for employees, connectors and the profile; `talk.ts`, the thread and its mutations; `presentation.ts` maps server state to pills, actions and the message box's mode without deriving new rules |
| `orb/` | The 3D orb (below) |
@@ -337,18 +337,14 @@ that way and fails when one loses an app it names or the way it starts.
### Connecting an AI model
-[connectAI/ConnectAIDialog.tsx](../client/src/features/home/connectAI/ConnectAIDialog.tsx)
-is the guided dialog for an owner who has never made an API key. It lists the
-featured providers of onboarding's Connect your AI step
-(`components/onboarding/aiProviderLinks.ts`: a hint and the page where the key
-is made), with names, marks and connected state from the credential
-catalogue. Picking one opens that provider's own panel, compact, with a link
-to its key page, and the dialog closes once the provider connects; "See all
-AI models" opens Settings > Connectors on AI. `homeStore.openConnectAI()`
-opens it when a setup answers `no_ai_provider`, after a hire that answers
-`needs_ai`, from the page's Connect an AI model, and when Start is refused
-with `needs_ai`. The key-page links live in `aiProviderLinks.ts`, not in the
-credential catalogue.
+`homeStore.openConnectAI()` delegates to the shared app-level credentials
+host with `{ categoryId: 'ai', intent: 'connect' }`. The connector browser
+starts on AI with beginner guidance; selecting a provider opens the same
+connection form used in Dev. Featured providers retain the key-page links
+and hints from `components/onboarding/aiProviderLinks.ts`. Successful guided
+connection closes the flow; Manage stays open after saving. These actions
+serve setup's `no_ai_provider`, hire/start's `needs_ai`, and the employee's
+Connect an AI model action.
## Talk
@@ -637,6 +633,12 @@ changing page clears it.
browser, whose panel manages optional login profiles).
**The catalog page** ([settings/CatalogLayout.tsx](../client/src/features/home/settings/CatalogLayout.tsx)).
+The implementation is shared in `components/catalog/`; Home paths are compatibility exports.
+Connectors uses `components/credentials/CredentialsBrowser` in both modes.
+Connected cards offer Manage and Disconnect; connection dialogs are owned by
+AppShell. Normal mode omits provider defaults, detailed usage and rate limits,
+while preserving all setup fields. Disabled credential categories are filtered
+from both browsing and directly requested providers.
Skills, Connectors and Plugins are built on a shared page:
- a title with Yours / Discover, search, and a category filter behind a
button;