Skip to content

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

fix(settings): correct device pairing modal validation

Steven Enamakelecedb7918d7b
diff --git a/app/src/components/settings/panels/DevicesPanel.tsx b/app/src/components/settings/panels/DevicesPanel.tsx
deleted file mode 100644
index 96ac52b98f..0000000000
--- a/app/src/components/settings/panels/DevicesPanel.tsx
+++ /dev/null
@@ -1,389 +0,0 @@
-import createDebug from 'debug';
-import { useCallback, useEffect, useId, useRef, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { callCoreRpc } from '../../../services/coreRpcClient';
-import type { ToastNotification } from '../../../types/intelligence';
-import { ToastContainer } from '../../intelligence/Toast';
-import Button from '../../ui/Button';
-import { ModalShell } from '../../ui/ModalShell';
-import {
- SettingsBadge,
- SettingsEmptyState,
- SettingsListItem,
- SettingsSection,
- SettingsStatusLine,
-} from '../controls';
-import SettingsPanel from '../layout/SettingsPanel';
-import PairPhoneModal from './devices/PairPhoneModal';
-
-const log = createDebug('app:devices-ui');
-
-// ---------------------------------------------------------------------------
-// Types (mirror the Rust types.rs)
-// ---------------------------------------------------------------------------
-
-interface PairedDevice {
- channel_id: string;
- label: string;
- device_pubkey: string;
- created_at: string;
- last_seen_at: string | null;
- peer_online: boolean | null;
- revoked: boolean;
-}
-
-interface ListDevicesResponse {
- devices: PairedDevice[];
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function truncateId(id: string): string {
- if (id.length <= 10) return id;
- return `${id.slice(0, 4)}…${id.slice(-4)}`;
-}
-
-function relativeTime(iso: string | null): string {
- if (!iso) return 'Never';
- const delta = Date.now() - new Date(iso).getTime();
- const minutes = Math.floor(delta / 60_000);
- if (minutes < 1) return 'Just now';
- if (minutes < 60) return `${minutes}m ago`;
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return `${hours}h ago`;
- return `${Math.floor(hours / 24)}d ago`;
-}
-
-function formatRelativeTime(value: string, t: (key: string) => string): string {
- if (value === 'Never') return t('devices.lastSeenNever');
- if (value === 'Just now') return t('devices.lastSeenNow');
-
- const match = value.match(/^(\d+)([mhd]) ago$/);
- if (!match) return value;
-
- const [, count, unit] = match;
- const key =
- unit === 'm'
- ? 'devices.lastSeenMinutes'
- : unit === 'h'
- ? 'devices.lastSeenHours'
- : 'devices.lastSeenDays';
-
- return t(key).replace('{count}', count);
-}
-
-// ---------------------------------------------------------------------------
-// Sub-components
-// ---------------------------------------------------------------------------
-
-function PeerDot({ online }: { online: boolean | null }) {
- const { t } = useT();
- const isOnline = online === true;
- return (
- <span
- title={isOnline ? t('devices.online') : t('devices.offline')}
- data-testid={isOnline ? 'peer-status-online' : 'peer-status-offline'}
- className={`inline-block w-2 h-2 rounded-full shrink-0 ${isOnline ? 'bg-sage-500' : 'bg-content-faint'}`}
- />
- );
-}
-
-function DeviceRow({
- device,
- onRevoke,
-}: {
- device: PairedDevice;
- onRevoke: (device: PairedDevice) => void;
-}) {
- const { t } = useT();
- const statusBadge = (
- <div className="flex items-center gap-1.5">
- <PeerDot online={device.peer_online} />
- <span className="font-mono text-xs text-content-faint">{truncateId(device.channel_id)}</span>
- <span className="text-xs text-content-faint">
- {formatRelativeTime(relativeTime(device.last_seen_at), t)}
- </span>
- </div>
- );
-
- return (
- <SettingsListItem
- label={device.label}
- badge={statusBadge}
- onRemove={() => onRevoke(device)}
- removeLabel={t('devices.revoke')}
- />
- );
-}
-
-function ConfirmRevokeDialog({
- device,
- onConfirm,
- onCancel,
-}: {
- device: PairedDevice;
- onConfirm: () => void;
- onCancel: () => void;
-}) {
- const { t } = useT();
- const titleId = useId();
-
- return (
- <ModalShell
- title={t('devices.confirmRevokeTitle')}
- titleId={titleId}
- onClose={onCancel}
- maxWidthClassName="max-w-sm"
- contentClassName="px-6 py-5"
- footer={
- <div className="flex gap-3">
- <Button type="button" variant="secondary" size="md" onClick={onCancel} className="flex-1">
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- variant="primary"
- tone="danger"
- size="md"
- onClick={onConfirm}
- className="flex-1"
- data-testid="confirm-revoke-btn">
- {t('devices.revoke')}
- </Button>
- </div>
- }>
- <p className="text-sm text-content-secondary">
- {t('devices.confirmRevokeBody').replace('{label}', device.label)}
- </p>
- </ModalShell>
- );
-}
-
-// ---------------------------------------------------------------------------
-// Main panel
-// ---------------------------------------------------------------------------
-
-const DevicesPanel = () => {
- const { t } = useT();
-
- const [devices, setDevices] = useState<PairedDevice[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [revokeTarget, setRevokeTarget] = useState<PairedDevice | null>(null);
- const [revoking, setRevoking] = useState(false);
- const [showPairModal, setShowPairModal] = useState(false);
- const [toasts, setToasts] = useState<ToastNotification[]>([]);
-
- const addToast = useCallback((toast: Omit<ToastNotification, 'id'>) => {
- const newToast: ToastNotification = { ...toast, id: `toast-${Date.now()}-${Math.random()}` };
- setToasts(prev => [...prev, newToast]);
- }, []);
-
- const removeToast = useCallback((id: string) => {
- setToasts(prev => prev.filter(t => t.id !== id));
- }, []);
-
- // Import callCoreRpc lazily via module-level reference to avoid circular deps.
- const loadDevices = useCallback(async () => {
- log('[devices-ui] loadDevices start');
- setError(null);
- try {
- const res = await callCoreRpc<ListDevicesResponse>({
- method: 'openhuman.devices_list',
- params: {},
- });
- const active = res.devices.filter(d => !d.revoked);
- log('[devices-ui] loadDevices got %d device(s)', active.length);
- setDevices(active);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log('[devices-ui] loadDevices error: %s', msg);
- setError(t('devices.loadFailed').replace('{message}', msg));
- } finally {
- setLoading(false);
- }
- }, [t]);
-
- // intervalRef keeps the poll alive when the pair modal is open.
- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
-
- const startPolling = useCallback(() => {
- if (pollRef.current) return;
- pollRef.current = setInterval(() => {
- void loadDevices();
- }, 2_000);
- log('[devices-ui] started 2s poll for device updates');
- }, [loadDevices]);
-
- const stopPolling = useCallback(() => {
- if (pollRef.current) {
- clearInterval(pollRef.current);
- pollRef.current = null;
- log('[devices-ui] stopped poll');
- }
- }, []);
-
- useEffect(() => {
- void loadDevices();
- return stopPolling;
- }, [loadDevices, stopPolling]);
-
- const handleOpenPairModal = () => {
- log('[devices-ui] opening pair modal');
- setShowPairModal(true);
- startPolling();
- };
-
- const handleClosePairModal = () => {
- log('[devices-ui] closing pair modal');
- setShowPairModal(false);
- stopPolling();
- void loadDevices();
- };
-
- const handlePaired = (channelId: string) => {
- log('[devices-ui] DevicePaired event channelId=%s', channelId);
- addToast({
- type: 'success',
- title: t('devices.devicePairedTitle'),
- message: t('devices.devicePairedMessage'),
- });
- stopPolling();
- setShowPairModal(false);
- void loadDevices();
- };
-
- const confirmRevoke = async () => {
- if (!revokeTarget) return;
- const target = revokeTarget;
- setRevoking(true);
- log('[devices-ui] revoking channel_id=%s', target.channel_id);
- try {
- await callCoreRpc({
- method: 'openhuman.devices_revoke',
- params: { channel_id: target.channel_id },
- });
- log('[devices-ui] revoke ok channel_id=%s', target.channel_id);
- addToast({
- type: 'success',
- title: t('devices.deviceRevokedTitle'),
- message: t('devices.deviceRevokedMessage').replace('{label}', target.label),
- });
- setRevokeTarget(null);
- await loadDevices();
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log('[devices-ui] revoke error: %s', msg);
- addToast({ type: 'error', title: t('devices.revokeFailedTitle'), message: msg });
- } finally {
- setRevoking(false);
- }
- };
-
- return (
- <SettingsPanel
- description={t('settings.account.devicesDesc')}
- action={
- <Button type="button" variant="primary" size="xs" onClick={handleOpenPairModal}>
- {t('devices.pairIphone')}
- </Button>
- }>
- <div className="pb-3 flex items-center gap-2">
- {/* Bespoke beta badge — intentional marketing chip */}
- <SettingsBadge variant="warning">{t('devices.betaBadge')}</SettingsBadge>
- <p className="text-xs text-content-muted">{t('devices.betaText')}</p>
- </div>
-
- <div className="pb-5 space-y-3">
- {loading && (
- <div className="flex items-center justify-center py-12">
- <svg
- className="w-5 h-5 animate-spin text-content-faint"
- fill="none"
- viewBox="0 0 24 24">
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- />
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
- />
- </svg>
- </div>
- )}
-
- {!loading && error && <SettingsStatusLine saving={false} error={error} savingLabel="" />}
-
- {!loading && !error && devices.length === 0 && (
- <SettingsSection>
- <div className="flex flex-col items-center justify-center py-12 text-center">
- <div className="w-12 h-12 rounded-xl bg-primary-50 dark:bg-primary-500/10 flex items-center justify-center mb-3">
- <svg
- className="w-6 h-6 text-primary-400"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"
- />
- </svg>
- </div>
- <SettingsEmptyState label={t('devices.noPaired')} />
- <p className="text-xs text-content-faint mb-4 max-w-xs">{t('devices.emptyState')}</p>
- <Button type="button" variant="primary" size="sm" onClick={handleOpenPairModal}>
- {t('devices.pairIphone')}
- </Button>
- </div>
- </SettingsSection>
- )}
-
- {!loading && !error && devices.length > 0 && (
- <SettingsSection>
- <ul>
- {devices.map(device => (
- <DeviceRow
- key={device.channel_id}
- device={device}
- onRevoke={d => {
- log('[devices-ui] revoke requested channel_id=%s', d.channel_id);
- setRevokeTarget(d);
- }}
- />
- ))}
- </ul>
- </SettingsSection>
- )}
- </div>
-
- {revokeTarget && (
- <ConfirmRevokeDialog
- device={revokeTarget}
- onConfirm={() => {
- void confirmRevoke();
- }}
- onCancel={() => {
- if (!revoking) setRevokeTarget(null);
- }}
- />
- )}
-
- {showPairModal && <PairPhoneModal onClose={handleClosePairModal} onPaired={handlePaired} />}
-
- <ToastContainer notifications={toasts} onRemove={removeToast} />
- </SettingsPanel>
- );
-};
-
-export default DevicesPanel;
diff --git a/app/src/components/settings/panels/LanguagePanel.tsx b/app/src/components/settings/panels/LanguagePanel.tsx
deleted file mode 100644
index a6e7942c67..0000000000
--- a/app/src/components/settings/panels/LanguagePanel.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { useT } from '../../../lib/i18n/I18nContext';
-import LanguageSelect from '../../LanguageSelect';
-import { Card, Field } from '../../ui';
-import SettingsPanel from '../layout/SettingsPanel';
-
-/**
- * Settings → Language. The display-language picker, promoted to its own page
- * from a card at the bottom of Appearance.
- */
-const LanguagePanel = () => {
- const { t } = useT();
-
- return (
- <SettingsPanel testId="language-panel" description={t('settings.languageDesc')}>
- <Card>
- <Field
- label={t('settings.language')}
- description={t('settings.languageDesc')}
- control={<LanguageSelect ariaLabel={t('settings.language')} />}
- />
- </Card>
- </SettingsPanel>
- );
-};
-
-export default LanguagePanel;
diff --git a/app/src/components/settings/panels/__tests__/DevicesPanel.formatting.test.tsx b/app/src/components/settings/panels/__tests__/DevicesPanel.formatting.test.tsx
deleted file mode 100644
index 18bd08b8c0..0000000000
--- a/app/src/components/settings/panels/__tests__/DevicesPanel.formatting.test.tsx
+++ /dev/null
@@ -1,191 +0,0 @@
-import { fireEvent, screen, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../../../../services/coreRpcClient';
-import { renderWithProviders } from '../../../../test/test-utils';
-import DevicesPanel from '../DevicesPanel';
-
-/**
- * `DevicesPanel` was the weakest panel on the settings surface by branch
- * coverage — 79.8% lines / 58.2% branches. The existing suite covers the device
- * list, revoke, the pair modal and the online/offline indicator; what it never
- * reaches is the formatting layer every row is rendered through, and the 2s
- * poll the pair modal turns on.
- *
- * - `relativeTime` (panel :49-58) — five buckets, one of which every row hits.
- * - `formatRelativeTime` (:60-76) — maps those onto i18n keys and interpolates
- * `{count}`; a wrong bucket shows a device as last seen minutes ago when it
- * was days.
- * - `truncateId` (:44-47) — the boundary.
- * - `startPolling` / `stopPolling` (:213-...) — a poll left running after the
- * modal closes keeps hitting the core every 2s for the life of the session.
- */
-
-vi.mock('../../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-vi.mock('../devices/PairPhoneModal', () => ({
- default: ({ onClose, onPaired }: { onClose: () => void; onPaired: (id: string) => void }) => (
- <div data-testid="pair-modal">
- <button onClick={onClose}>close-modal</button>
- <button onClick={() => onPaired('CHAN123')}>simulate-paired</button>
- </div>
- ),
-}));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-/** A fixed clock so the relative-time buckets are deterministic. */
-const NOW = new Date('2026-08-31T12:00:00.000Z').getTime();
-
-const MINUTE = 60_000;
-const HOUR = 60 * MINUTE;
-const DAY = 24 * HOUR;
-
-function makeDevice(overrides: Record<string, unknown> = {}) {
- return {
- channel_id: 'CHAN_AAABBBCCC',
- label: "Alice's iPhone",
- device_pubkey: 'pubkey_base64url',
- created_at: new Date(NOW).toISOString(),
- last_seen_at: null,
- peer_online: false,
- revoked: false,
- ...overrides,
- };
-}
-
-/** Render a single device whose `last_seen_at` is `agoMs` in the past. */
-async function renderWithLastSeen(agoMs: number | null) {
- mockCall.mockResolvedValue({
- devices: [
- makeDevice({ last_seen_at: agoMs === null ? null : new Date(NOW - agoMs).toISOString() }),
- ],
- });
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
- await waitFor(() => expect(screen.getByText("Alice's iPhone")).toBeInTheDocument());
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- vi.useFakeTimers({ shouldAdvanceTime: true });
- vi.setSystemTime(NOW);
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe('DevicesPanel — last-seen bucketing', () => {
- it('renders a never-seen device as Never, not as 0 minutes ago', async () => {
- await renderWithLastSeen(null);
- expect(screen.getByText(/never/i)).toBeInTheDocument();
- expect(screen.queryByText(/ago/)).not.toBeInTheDocument();
- });
-
- it('renders a sighting under a minute as "just now"', async () => {
- await renderWithLastSeen(30_000);
- expect(screen.getByText(/just now/i)).toBeInTheDocument();
- });
-
- it('renders a sighting in the minutes bucket with its count', async () => {
- await renderWithLastSeen(42 * MINUTE);
- expect(screen.getByText(/42m ago/)).toBeInTheDocument();
- expect(screen.queryByText(/just now/i)).not.toBeInTheDocument();
- });
-
- it('renders a sighting in the hours bucket with its count', async () => {
- await renderWithLastSeen(5 * HOUR);
- expect(screen.getByText(/5h ago/)).toBeInTheDocument();
- });
-
- it('renders a sighting in the days bucket with its count', async () => {
- await renderWithLastSeen(3 * DAY);
- expect(screen.getByText(/3d ago/)).toBeInTheDocument();
- });
-
- it('does not spill a 90-minute sighting into the minutes bucket', async () => {
- // 90 minutes is 1h — reading it as "90m ago" is the classic off-by-a-bucket.
- await renderWithLastSeen(90 * MINUTE);
- expect(screen.queryByText(/90m ago/)).not.toBeInTheDocument();
- expect(screen.getByText(/1h ago/)).toBeInTheDocument();
- });
-
- it('does not spill a 25-hour sighting into the hours bucket', async () => {
- await renderWithLastSeen(25 * HOUR);
- expect(screen.queryByText(/25h ago/)).not.toBeInTheDocument();
- expect(screen.getByText(/1d ago/)).toBeInTheDocument();
- });
-
- it('treats exactly 60 minutes as the hours bucket', async () => {
- await renderWithLastSeen(60 * MINUTE);
- expect(screen.queryByText(/60m ago/)).not.toBeInTheDocument();
- expect(screen.getByText(/1h ago/)).toBeInTheDocument();
- });
-});
-
-describe('DevicesPanel — channel id truncation', () => {
- it('truncates a long channel id to first 4 + last 4', async () => {
- mockCall.mockResolvedValue({ devices: [makeDevice({ channel_id: 'ABCDEFGHIJKLMNOP' })] });
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- expect(await screen.findByText('ABCD…MNOP')).toBeInTheDocument();
- expect(screen.queryByText('ABCDEFGHIJKLMNOP')).not.toBeInTheDocument();
- });
-
- it('leaves a 10-character id intact rather than shortening it', async () => {
- mockCall.mockResolvedValue({ devices: [makeDevice({ channel_id: 'ABCDEFGHIJ' })] });
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- expect(await screen.findByText('ABCDEFGHIJ')).toBeInTheDocument();
- });
-});
-
-describe('DevicesPanel — the pair-modal poll', () => {
- async function openPairModal() {
- mockCall.mockResolvedValue({ devices: [] });
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
- await waitFor(() => expect(mockCall).toHaveBeenCalledTimes(1));
- fireEvent.click(screen.getAllByRole('button', { name: 'Pair iPhone' })[0]);
- await waitFor(() => expect(screen.getByTestId('pair-modal')).toBeInTheDocument());
- }
-
- it('polls the device list every 2s while the modal is open', async () => {
- await openPairModal();
- const afterOpen = mockCall.mock.calls.length;
-
- await vi.advanceTimersByTimeAsync(2100);
- await waitFor(() => expect(mockCall.mock.calls.length).toBeGreaterThan(afterOpen));
-
- const afterFirstTick = mockCall.mock.calls.length;
- await vi.advanceTimersByTimeAsync(2100);
- await waitFor(() => expect(mockCall.mock.calls.length).toBeGreaterThan(afterFirstTick));
- });
-
- it('stops polling once the modal closes', async () => {
- await openPairModal();
- fireEvent.click(screen.getByText('close-modal'));
- await waitFor(() => expect(screen.queryByTestId('pair-modal')).not.toBeInTheDocument());
-
- // Closing triggers one final reload; let it settle, then hold still.
- await waitFor(() => expect(mockCall.mock.calls.length).toBeGreaterThan(0));
- const settled = mockCall.mock.calls.length;
-
- await vi.advanceTimersByTimeAsync(6000);
- expect(mockCall.mock.calls.length).toBe(settled);
- });
-
- it('does not start a second interval when the modal is reopened', async () => {
- await openPairModal();
- fireEvent.click(screen.getByText('close-modal'));
- await waitFor(() => expect(screen.queryByTestId('pair-modal')).not.toBeInTheDocument());
-
- fireEvent.click(screen.getAllByRole('button', { name: 'Pair iPhone' })[0]);
- await waitFor(() => expect(screen.getByTestId('pair-modal')).toBeInTheDocument());
-
- const before = mockCall.mock.calls.length;
- await vi.advanceTimersByTimeAsync(2100);
- await waitFor(() => expect(mockCall.mock.calls.length).toBeGreaterThan(before));
- // One interval, so one extra call per tick — not two.
- expect(mockCall.mock.calls.length - before).toBeLessThanOrEqual(1);
- });
-});
diff --git a/app/src/components/settings/panels/__tests__/DevicesPanel.test.tsx b/app/src/components/settings/panels/__tests__/DevicesPanel.test.tsx
deleted file mode 100644
index 114ddb48eb..0000000000
--- a/app/src/components/settings/panels/__tests__/DevicesPanel.test.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import { fireEvent, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../../../../services/coreRpcClient';
-import { renderWithProviders } from '../../../../test/test-utils';
-import DevicesPanel from '../DevicesPanel';
-
-// ---------------------------------------------------------------------------
-// Mocks
-// ---------------------------------------------------------------------------
-
-vi.mock('../../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-// qrcode.react is not needed in panel tests.
-vi.mock('../devices/PairPhoneModal', () => ({
- default: ({ onClose, onPaired }: { onClose: () => void; onPaired: (id: string) => void }) => (
- <div data-testid="pair-modal">
- <button onClick={onClose}>close-modal</button>
- <button onClick={() => onPaired('CHAN123')}>simulate-paired</button>
- </div>
- ),
-}));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-function makeDevice(overrides = {}) {
- return {
- channel_id: 'CHAN_AAABBBCCC',
- label: "Alice's iPhone",
- device_pubkey: 'pubkey_base64url',
- created_at: new Date().toISOString(),
- last_seen_at: null,
- peer_online: false,
- revoked: false,
- ...overrides,
- };
-}
-
-function listResponse(devices: ReturnType<typeof makeDevice>[]) {
- return { devices };
-}
-
-describe('DevicesPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('shows empty state when no devices are paired', async () => {
- mockCall.mockResolvedValue(listResponse([]));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- expect(await screen.findByText('No paired devices')).toBeInTheDocument();
- // Two "Pair iPhone" buttons exist: header + empty-state CTA.
- expect(screen.getAllByRole('button', { name: /Pair iPhone/i })).toHaveLength(2);
- });
-
- it('renders a paired device row with label, truncated id, and revoke button', async () => {
- const device = makeDevice({ channel_id: 'ABCDEFGHIJ12345678', label: "Bob's iPhone" });
- mockCall.mockResolvedValue(listResponse([device]));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- expect(await screen.findByText("Bob's iPhone")).toBeInTheDocument();
- // Truncated: first 4 + last 4 chars
- expect(screen.getByText('ABCD…5678')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Revoke/i })).toBeInTheDocument();
- });
-
- it('filters out revoked devices', async () => {
- const devices = [
- makeDevice({ label: 'Active', revoked: false }),
- makeDevice({ channel_id: 'REVOKED_CHAN', label: 'Revoked', revoked: true }),
- ];
- mockCall.mockResolvedValue(listResponse(devices));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- expect(await screen.findByText('Active')).toBeInTheDocument();
- expect(screen.queryByText('Revoked')).not.toBeInTheDocument();
- });
-
- it('shows a confirm dialog on revoke click, then calls devices_revoke on confirm', async () => {
- const device = makeDevice({ label: "Charlie's iPhone", channel_id: 'CHAN_CHARLIE' });
- // First call: list. Second call: revoke. Third call: refresh after revoke.
- mockCall
- .mockResolvedValueOnce(listResponse([device]))
- .mockResolvedValueOnce({ success: true })
- .mockResolvedValueOnce(listResponse([]));
-
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- await screen.findByText("Charlie's iPhone");
- // Click the per-row revoke button (may be many; pick the first one)
- fireEvent.click(screen.getAllByRole('button', { name: /Revoke/i })[0]);
-
- // Confirmation dialog
- expect(await screen.findByText('Revoke device?')).toBeInTheDocument();
- // Use testid to unambiguously target the dialog confirm button
- fireEvent.click(screen.getByTestId('confirm-revoke-btn'));
-
- await waitFor(() => {
- expect(mockCall).toHaveBeenCalledWith(
- expect.objectContaining({ method: 'openhuman.devices_revoke' })
- );
- });
-
- // After revoke the list should be refreshed (empty state)
- expect(await screen.findByText('No paired devices')).toBeInTheDocument();
- });
-
- it('cancels revoke when the cancel button is pressed', async () => {
- const device = makeDevice({ label: "Dave's iPhone" });
- mockCall.mockResolvedValue(listResponse([device]));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- await screen.findByText("Dave's iPhone");
- fireEvent.click(screen.getByRole('button', { name: /Revoke/i }));
- expect(screen.getByText('Revoke device?')).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: /Cancel/i }));
- await waitFor(() => {
- expect(screen.queryByText('Revoke device?')).not.toBeInTheDocument();
- });
- // No revoke call made
- expect(mockCall).toHaveBeenCalledTimes(1);
- });
-
- it('opens the pair modal when Pair iPhone is clicked', async () => {
- mockCall.mockResolvedValue(listResponse([]));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- await screen.findByText('No paired devices');
- // Click the header-level button (first one).
- fireEvent.click(screen.getAllByRole('button', { name: /Pair iPhone/i })[0]);
-
- expect(await screen.findByTestId('pair-modal')).toBeInTheDocument();
- });
-
- it('closes the pair modal and reloads devices after pairing', async () => {
- const device = makeDevice({ label: 'New iPhone' });
- mockCall.mockResolvedValueOnce(listResponse([])).mockResolvedValueOnce(listResponse([device]));
-
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
- await screen.findByText('No paired devices');
- fireEvent.click(screen.getAllByRole('button', { name: /Pair iPhone/i })[0]);
-
- await screen.findByTestId('pair-modal');
- fireEvent.click(screen.getByText('simulate-paired'));
-
- await waitFor(() => {
- expect(screen.queryByTestId('pair-modal')).not.toBeInTheDocument();
- });
- });
-
- it('shows an error message when devices_list fails', async () => {
- mockCall.mockRejectedValue(new Error('Core offline'));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- expect(await screen.findByText(/Failed to load devices/)).toBeInTheDocument();
- });
-
- it('shows the online status indicator when a peer is online', async () => {
- const device = makeDevice({ label: 'Online iPhone', peer_online: true });
- mockCall.mockResolvedValue(listResponse([device]));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- await screen.findByText('Online iPhone');
-
- expect(screen.getByTestId('peer-status-online')).toBeInTheDocument();
- expect(screen.queryByTestId('peer-status-offline')).not.toBeInTheDocument();
- });
-
- it('shows the offline status indicator when a peer is offline', async () => {
- const device = makeDevice({ label: 'Offline iPhone', peer_online: false });
- mockCall.mockResolvedValue(listResponse([device]));
- renderWithProviders(<DevicesPanel />, { initialEntries: ['/settings/devices'] });
-
- await screen.findByText('Offline iPhone');
-
- expect(screen.getByTestId('peer-status-offline')).toBeInTheDocument();
- expect(screen.queryByTestId('peer-status-online')).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/components/settings/panels/devices/PairPhoneModal.test.tsx b/app/src/components/settings/panels/devices/PairPhoneModal.test.tsx
deleted file mode 100644
index f2e65ad7ce..0000000000
--- a/app/src/components/settings/panels/devices/PairPhoneModal.test.tsx
+++ /dev/null
@@ -1,289 +0,0 @@
-/**
- * Tests for PairPhoneModal.
- *
- * Timer strategy: most tests use real timers + mocked callCoreRpc.
- * Tests that validate timer-driven state (expiry, poll, auto-close) use
- * vi.useFakeTimers scoped per-test and flush promises with act()+Promise.resolve().
- */
-import { act, fireEvent, screen } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../../../../services/coreRpcClient';
-import { renderWithProviders } from '../../../../test/test-utils';
-import PairPhoneModal from './PairPhoneModal';
-
-// ---------------------------------------------------------------------------
-// Mocks
-// ---------------------------------------------------------------------------
-
-vi.mock('../../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-vi.mock('qrcode.react', () => ({
- QRCodeSVG: ({ value }: { value: string }) => <div data-testid="qr-code" data-value={value} />,
-}));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-const CHANNEL_ID = 'ABCDEFGHIJ1234567890AB';
-const PAIRING_TOKEN = 'tok_abc123';
-const CORE_PUBKEY = 'pubkey_base64url_value';
-
-function makePairingSession(overrides = {}) {
- return {
- channel_id: CHANNEL_ID,
- pairing_token: PAIRING_TOKEN,
- core_pubkey: CORE_PUBKEY,
- rpc_url: null,
- expires_at: new Date(Date.now() + 600_000).toISOString(),
- ...overrides,
- };
-}
-
-function makeDevice(overrides = {}) {
- return {
- channel_id: CHANNEL_ID,
- label: "Alice's iPhone",
- peer_online: true,
- revoked: false,
- ...overrides,
- };
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function setupRealTimers() {
- vi.useRealTimers();
-}
-
-function setupFakeTimers() {
- vi.useFakeTimers({ shouldAdvanceTime: false });
-}
-
-/** Advance fake timers + flush promise microtasks. */
-async function advanceAndFlush(ms: number) {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(ms);
- });
-}
-
-const onClose = vi.fn();
-const onPaired = vi.fn();
-
-describe('PairPhoneModal', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- setupRealTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- // ---------------------------------------------------------------------------
- // QR render + URL validation (no timer tricks needed)
- // ---------------------------------------------------------------------------
-
- it('shows loading then renders a QR code after create_pairing resolves', async () => {
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return makePairingSession();
- return { devices: [] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- expect(screen.getByText(/Generating pairing code/i)).toBeInTheDocument();
- expect(await screen.findByTestId('qr-code')).toBeInTheDocument();
- });
-
- it('QR code value contains all required URL params', async () => {
- const session = makePairingSession({ rpc_url: 'http://192.168.1.5:7788/rpc' });
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return session;
- return { devices: [] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- const qr = await screen.findByTestId('qr-code');
- const value = qr.getAttribute('data-value') ?? '';
- const url = new URL(value);
- expect(url.protocol).toBe('openhuman:');
- expect(url.searchParams.get('cid')).toBe(CHANNEL_ID);
- expect(url.searchParams.get('pt')).toBe(PAIRING_TOKEN);
- expect(url.searchParams.get('cpk')).toBe(CORE_PUBKEY);
- expect(url.searchParams.get('rpc')).toBe('http://192.168.1.5:7788/rpc');
- expect(url.searchParams.get('exp')).toBeTruthy();
- });
-
- // ---------------------------------------------------------------------------
- // Poll-based pairing detection
- // ---------------------------------------------------------------------------
-
- it('transitions to success state when device appears on poll', async () => {
- setupFakeTimers();
-
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return makePairingSession();
- return { devices: [makeDevice()] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- // Flush the create_pairing promise so the QR renders.
- await advanceAndFlush(0);
- // Advance past the 2s poll interval and flush the list call.
- await advanceAndFlush(2_100);
-
- expect(screen.getByText(/Paired with iPhone/i)).toBeInTheDocument();
- expect(screen.getByText("Alice's iPhone")).toBeInTheDocument();
- });
-
- it('calls onPaired after 3 s auto-close on success', async () => {
- setupFakeTimers();
-
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return makePairingSession();
- return { devices: [makeDevice()] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- // create_pairing + 2s poll.
- await advanceAndFlush(0);
- await advanceAndFlush(2_100);
- expect(screen.getByText(/Paired with iPhone/i)).toBeInTheDocument();
-
- // 3 s auto-close timer.
- await advanceAndFlush(3_100);
-
- expect(onPaired).toHaveBeenCalledWith(CHANNEL_ID);
- });
-
- // ---------------------------------------------------------------------------
- // Expiry
- // ---------------------------------------------------------------------------
-
- it('shows QR expired when the session deadline passes', async () => {
- setupFakeTimers();
-
- const session = makePairingSession({ expires_at: new Date(Date.now() + 50).toISOString() });
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return session;
- return { devices: [] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- await advanceAndFlush(0);
- expect(screen.getByTestId('qr-code')).toBeInTheDocument();
-
- // Advance past the 50 ms expiry.
- await advanceAndFlush(200);
-
- expect(screen.getByText(/QR code expired/i)).toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Generate new code/i })).toBeInTheDocument();
- });
-
- it('re-issues create_pairing when "Generate new code" is clicked', async () => {
- setupFakeTimers();
-
- const expiredSession = makePairingSession({
- expires_at: new Date(Date.now() + 50).toISOString(),
- });
- const freshSession = makePairingSession({ channel_id: 'NEW_CHANNEL_XYZ' });
-
- let createCount = 0;
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') {
- return createCount++ === 0 ? expiredSession : freshSession;
- }
- return { devices: [] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- await advanceAndFlush(0);
- expect(screen.getByTestId('qr-code')).toBeInTheDocument();
-
- await advanceAndFlush(200);
- expect(screen.getByText(/QR code expired/i)).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: /Generate new code/i }));
- // Loading + fresh QR
- await advanceAndFlush(0);
- expect(screen.getByTestId('qr-code')).toBeInTheDocument();
- expect(createCount).toBe(2);
- });
-
- // ---------------------------------------------------------------------------
- // Error state
- // ---------------------------------------------------------------------------
-
- it('shows error state when devices_create_pairing fails', async () => {
- mockCall.mockRejectedValue(new Error('tunnel unavailable'));
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- expect(await screen.findByText(/Something went wrong/i)).toBeInTheDocument();
- expect(screen.getByText(/tunnel unavailable/i)).toBeInTheDocument();
- });
-
- // ---------------------------------------------------------------------------
- // Close + details toggle (no timer tricks needed)
- // ---------------------------------------------------------------------------
-
- it('calls onClose when the X button is pressed', async () => {
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return makePairingSession();
- return { devices: [] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- await screen.findByTestId('qr-code');
- fireEvent.click(screen.getByRole('button', { name: /Close/i }));
-
- expect(onClose).toHaveBeenCalledTimes(1);
- expect(onPaired).not.toHaveBeenCalled();
- });
-
- it('toggles details section when "Show details" / "Hide details" is clicked', async () => {
- mockCall.mockImplementation(async ({ method }: { method: string }) => {
- if (method === 'openhuman.devices_create_pairing') return makePairingSession();
- return { devices: [] };
- });
-
- renderWithProviders(<PairPhoneModal onClose={onClose} onPaired={onPaired} />, {
- initialEntries: ['/settings/devices'],
- });
-
- await screen.findByTestId('qr-code');
- expect(screen.queryByText('Channel ID')).not.toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: /Show details/i }));
- expect(screen.getByText('Channel ID')).toBeInTheDocument();
- expect(screen.getByText(CHANNEL_ID)).toBeInTheDocument();
-
- // Toggle state is synchronous.
- fireEvent.click(screen.getByRole('button', { name: /Hide details/i }));
- expect(screen.queryByText('Channel ID')).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/components/settings/panels/devices/PairPhoneModal.tsx b/app/src/components/settings/panels/devices/PairPhoneModal.tsx
deleted file mode 100644
index e2b4a4d896..0000000000
--- a/app/src/components/settings/panels/devices/PairPhoneModal.tsx
+++ /dev/null
@@ -1,419 +0,0 @@
-/**
- * PairPhoneModal
- *
- * Opens a pairing session via `devices_create_pairing`, shows a QR code the
- * iPhone user scans, then polls `devices_list` every 2 s to detect when the
- * device has completed the handshake (DevicePaired). Handles expiry and lets
- * the user regenerate the code.
- *
- * TODO(future): replace the 2-second poll with a real socket event bridge when
- * the Rust core forwards DomainEvent::DevicePaired over Socket.IO to the UI.
- */
-import createDebug from 'debug';
-import { QRCodeSVG } from 'qrcode.react';
-import { useCallback, useEffect, useId, useRef, useState } from 'react';
-
-import { useT } from '../../../../lib/i18n/I18nContext';
-import { callCoreRpc } from '../../../../services/coreRpcClient';
-import Button from '../../../ui/Button';
-import { ModalShell } from '../../../ui/ModalShell';
-
-const log = createDebug('app:devices-ui:pair-modal');
-
-// ---------------------------------------------------------------------------
-// Types
-// ---------------------------------------------------------------------------
-
-interface CreatePairingResponse {
- channel_id: string;
- pairing_token: string;
- core_pubkey: string;
- rpc_url: string | null;
- expires_at: string;
-}
-
-interface PairedDevice {
- channel_id: string;
- label: string;
- peer_online: boolean | null;
- revoked: boolean;
-}
-
-interface ListDevicesResponse {
- devices: PairedDevice[];
-}
-
-type ModalState =
- | { kind: 'loading' }
- | { kind: 'qr'; session: CreatePairingResponse; qrUrl: string; expired: boolean }
- | { kind: 'success'; channelId: string; label: string }
- | { kind: 'error'; message: string };
-
-interface PairPhoneModalProps {
- onClose: () => void;
- /** Called when a device successfully completes pairing. */
- onPaired: (channelId: string) => void;
-}
-
-// ---------------------------------------------------------------------------
-// QR URL builder
-// ---------------------------------------------------------------------------
-
-function buildPairUrl(session: CreatePairingResponse): string {
- const params = new URLSearchParams();
- params.set('cid', session.channel_id);
- params.set('pt', session.pairing_token);
- params.set('cpk', session.core_pubkey);
- if (session.rpc_url) params.set('rpc', session.rpc_url);
- // expires_at is ISO 8601 — convert to unix timestamp for compact QR.
- const expUnix = Math.floor(new Date(session.expires_at).getTime() / 1_000);
- params.set('exp', String(expUnix));
- return `openhuman://pair?${params.toString()}`;
-}
-
-// ---------------------------------------------------------------------------
-// Component
-// ---------------------------------------------------------------------------
-
-const PairPhoneModal = ({ onClose, onPaired }: PairPhoneModalProps) => {
- const { t } = useT();
- const titleId = useId();
- const [state, setState] = useState<ModalState>({ kind: 'loading' });
- const [showDetails, setShowDetails] = useState(false);
- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const expireTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const pairedRef = useRef(false);
-
- const clearTimers = () => {
- if (pollRef.current) {
- clearInterval(pollRef.current);
- pollRef.current = null;
- }
- if (expireTimerRef.current) {
- clearTimeout(expireTimerRef.current);
- expireTimerRef.current = null;
- }
- };
-
- // Watch the paired-device list to detect handshake completion.
- const startPollForPaired = useCallback(
- (channelId: string) => {
- if (pollRef.current) return;
- log('[devices-ui] [pair-modal] starting poll for channel_id=%s', channelId);
- pollRef.current = setInterval(async () => {
- if (pairedRef.current) return;
- try {
- const res = await callCoreRpc<ListDevicesResponse>({
- method: 'openhuman.devices_list',
- params: {},
- });
- const matched = res.devices.find(d => d.channel_id === channelId && !d.revoked);
- if (matched) {
- pairedRef.current = true;
- clearTimers();
- log(
- '[devices-ui] [pair-modal] device paired! channel_id=%s label=%s',
- channelId,
- matched.label
- );
- setState({ kind: 'success', channelId, label: matched.label });
- // Auto-close after 3 s to let the user read the success message.
- setTimeout(() => {
- onPaired(channelId);
- }, 3_000);
- }
- } catch (err) {
- // Non-fatal poll failure — the modal stays open.
- log('[devices-ui] [pair-modal] poll error: %s', String(err));
- }
- }, 2_000);
- },
- [onPaired]
- );
-
- const createSession = useCallback(async () => {
- clearTimers();
- pairedRef.current = false;
- setState({ kind: 'loading' });
- log('[devices-ui] [pair-modal] calling devices_create_pairing');
- try {
- const session = await callCoreRpc<CreatePairingResponse>({
- method: 'openhuman.devices_create_pairing',
- params: {},
- });
- log(
- '[devices-ui] [pair-modal] session created channel_id=%s token_len=%d expires_at=%s',
- session.channel_id,
- session.pairing_token.length,
- session.expires_at
- );
- const qrUrl = buildPairUrl(session);
- setState({ kind: 'qr', session, qrUrl, expired: false });
-
- // Schedule expiry transition.
- const msUntilExpiry = new Date(session.expires_at).getTime() - Date.now();
- if (msUntilExpiry > 0) {
- expireTimerRef.current = setTimeout(() => {
- log('[devices-ui] [pair-modal] QR expired channel_id=%s', session.channel_id);
- setState(prev =>
- prev.kind === 'qr' && prev.session.channel_id === session.channel_id
- ? { ...prev, expired: true }
- : prev
- );
- }, msUntilExpiry);
- }
-
- startPollForPaired(session.channel_id);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log('[devices-ui] [pair-modal] create pairing error: %s', msg);
- setState({
- kind: 'error',
- message: t('devices.pairModal.errorPrefix').replace('{message}', msg),
- });
- }
- }, [startPollForPaired, t]);
-
- useEffect(() => {
- void createSession();
- return clearTimers;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // ---------------------------------------------------------------------------
- // Render
- // ---------------------------------------------------------------------------
-
- return (
- <ModalShell
- title={t('devices.pairModal.title')}
- titleId={titleId}
- onClose={onClose}
- maxWidthClassName="max-w-sm"
- contentClassName="p-5"
- footer={
- state.kind === 'qr' || state.kind === 'error' ? (
- <Button type="button" variant="tertiary" size="md" onClick={onClose} className="w-full">
- {t('common.cancel')}
- </Button>
- ) : undefined
- }>
- {state.kind === 'loading' && <LoadingBody />}
- {state.kind === 'error' && (
- <ErrorBody
- message={state.message}
- onRetry={() => {
- void createSession();
- }}
- />
- )}
- {state.kind === 'qr' && !state.expired && (
- <QrBody
- session={state.session}
- qrUrl={state.qrUrl}
- showDetails={showDetails}
- onToggleDetails={() => setShowDetails(v => !v)}
- />
- )}
- {state.kind === 'qr' && state.expired && (
- <ExpiredBody
- onRegenerate={() => {
- void createSession();
- }}
- />
- )}
- {state.kind === 'success' && <SuccessBody label={state.label} channelId={state.channelId} />}
- </ModalShell>
- );
-};
-
-// ---------------------------------------------------------------------------
-// State-specific sub-components
-// ---------------------------------------------------------------------------
-
-function LoadingBody() {
- const { t } = useT();
- return (
- <div className="flex flex-col items-center justify-center py-10 gap-3">
- <svg className="w-6 h-6 animate-spin text-primary-400" fill="none" viewBox="0 0 24 24">
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- />
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
- />
- </svg>
- <p className="text-sm text-content-muted">{t('devices.pairModal.loading')}</p>
- </div>
- );
-}
-
-function QrBody({
- session,
- qrUrl,
- showDetails,
- onToggleDetails,
-}: {
- session: CreatePairingResponse;
- qrUrl: string;
- showDetails: boolean;
- onToggleDetails: () => void;
-}) {
- const { t } = useT();
- const expiresAt = new Date(session.expires_at);
- const minutesLeft = Math.max(0, Math.floor((expiresAt.getTime() - Date.now()) / 60_000));
-
- return (
- <div className="flex flex-col items-center gap-4">
- <p className="text-sm text-content-secondary text-center">
- {t('devices.pairModal.instructions')}
- </p>
-
- {/* QR code */}
- <div className="p-3 bg-surface rounded-xl border border-line shadow-xs">
- <QRCodeSVG value={qrUrl} size={200} level="M" bgColor="#ffffff" fgColor="#1c1917" />
- </div>
-
- <p className="text-xs text-content-faint">
- {t(
- minutesLeft === 1 ? 'devices.pairModal.expiresIn' : 'devices.pairModal.expiresInPlural'
- ).replace('{count}', String(minutesLeft))}
- </p>
-
- {/* Details toggle */}
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={onToggleDetails}
- className="text-primary-500 hover:text-primary-600">
- {showDetails ? t('devices.pairModal.hideDetails') : t('devices.pairModal.showDetails')}
- </Button>
-
- {showDetails && (
- <div className="w-full space-y-2">
- <div>
- <p className="text-xs font-medium text-content-muted mb-1">
- {t('devices.pairModal.channelId')}
- </p>
- <p className="text-xs font-mono text-content-secondary bg-surface-muted rounded px-2 py-1 break-all select-all">
- {session.channel_id}
- </p>
- </div>
- <div>
- <p className="text-xs font-medium text-content-muted mb-1">
- {t('devices.pairModal.pairingUrl')}
- </p>
- <div className="relative">
- <p className="text-xs font-mono text-content-secondary bg-surface-muted rounded px-2 py-1 break-all select-all pr-16">
- {qrUrl}
- </p>
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={() => {
- void navigator.clipboard.writeText(qrUrl);
- }}
- className="absolute top-1 right-1 bg-surface border border-line dark:border-line-strong">
- {t('devices.pairModal.copyUrl')}
- </Button>
- </div>
- </div>
- </div>
- )}
- </div>
- );
-}
-
-function ExpiredBody({ onRegenerate }: { onRegenerate: () => void }) {
- const { t } = useT();
- return (
- <div className="flex flex-col items-center gap-4 py-4">
- <div className="w-12 h-12 rounded-xl bg-amber-50 flex items-center justify-center">
- <svg
- className="w-6 h-6 text-amber-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
- />
- </svg>
- </div>
- <p className="text-sm font-medium text-content-secondary">
- {t('devices.pairModal.expiredTitle')}
- </p>
- <p className="text-xs text-content-muted text-center">{t('devices.pairModal.expiredBody')}</p>
- <Button type="button" variant="primary" size="md" onClick={onRegenerate}>
- {t('devices.pairModal.generateNewCode')}
- </Button>
- </div>
- );
-}
-
-function SuccessBody({ label, channelId }: { label: string; channelId: string }) {
- const { t } = useT();
- return (
- <div className="flex flex-col items-center gap-4 py-4">
- <div className="w-12 h-12 rounded-xl bg-sage-50 flex items-center justify-center">
- <svg
- className="w-6 h-6 text-sage-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
- </svg>
- </div>
- <div className="text-center">
- <p className="text-sm font-medium text-content">{t('devices.pairModal.successTitle')}</p>
- <p className="text-xs text-content-muted mt-1">{label}</p>
- <p className="text-xs font-mono text-content-faint mt-0.5">
- {channelId.slice(0, 8)}…{channelId.slice(-6)}
- </p>
- </div>
- <p className="text-xs text-content-faint">{t('devices.pairModal.autoClose')}</p>
- </div>
- );
-}
-
-function ErrorBody({ message, onRetry }: { message: string; onRetry: () => void }) {
- const { t } = useT();
- return (
- <div className="flex flex-col items-center gap-4 py-4">
- <div className="w-12 h-12 rounded-xl bg-coral-50 flex items-center justify-center">
- <svg
- className="w-6 h-6 text-coral-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M6 18L18 6M6 6l12 12"
- />
- </svg>
- </div>
- <p className="text-sm font-medium text-content-secondary">
- {t('devices.pairModal.errorTitle')}
- </p>
- <p className="text-xs text-content-muted text-center break-all">{message}</p>
- <Button type="button" variant="primary" size="md" onClick={onRetry}>
- {t('common.retry')}
- </Button>
- </div>
- );
-}
-
-export default PairPhoneModal;