import { useCallback, useEffect, useRef, useState } from 'react' import { AlertCircle, Loader2, QrCode, RefreshCw } from 'lucide-react' import { DEVICE_PAIRING_CODE_TTL_SECONDS, type DevicePairingLinkWarning, type DevicePairingLinksResponse, } from '@opencode-manager/shared/schemas' import { useCreateDevicePairingLinks, useInvalidatePairedDevices } from '@/hooks/useDevicePairing' import { Alert, AlertDescription } from '@/components/ui/alert' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from '@/components/ui/dialog' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { PairingQrCode } from './PairingQrCode' const WARNING_MESSAGES: Record = { 'plain-http': 'This address uses plain HTTP, so the sign-in code travels unencrypted.', loopback: 'This address is localhost; other devices cannot reach it.', 'headers-unreadable': 'Stored remote access headers could not be decrypted and are not included.', } const INSECURE_ORIGIN_EXPLANATION = "The mobile app QR code needs HTTPS. Use an HTTPS address, or turn on 'Allow plain-HTTP app links on private networks' if this Manager uses a private IP address." const SCREEN_SHARING_WARNING = "This QR code contains your remote access headers. Don't show it while screen sharing or recording." const BROWSER_HINT = "Scan with your phone camera to sign in the browser or installed app. In an iPhone home-screen app, use 'Sign in with QR code' on its sign-in screen." const LINKS_FAILED_MESSAGE = 'Failed to create pairing links' interface ConnectDeviceDialogProps { open: boolean onOpenChange: (open: boolean) => void } function formatCountdown(localExpiresAt: number, now: number): string { const remainingSeconds = Math.max(0, Math.ceil((localExpiresAt - now) / 1000)) const minutes = Math.floor(remainingSeconds / 60) return `${minutes}:${String(remainingSeconds % 60).padStart(2, '0')}` } export function ConnectDeviceDialog({ open, onOpenChange }: ConnectDeviceDialogProps) { const invalidatePairedDevices = useInvalidatePairedDevices() const { mutate, isPending } = useCreateDevicePairingLinks() const [links, setLinks] = useState(null) const [localExpiresAt, setLocalExpiresAt] = useState(null) const [error, setError] = useState(null) const [revealed, setRevealed] = useState(false) const [now, setNow] = useState(() => Date.now()) const wasOpenRef = useRef(false) const requestLinks = useCallback(() => { setError(null) mutate( {}, { onSuccess: (response) => { const receivedAt = Date.now() setLinks(response) setLocalExpiresAt(receivedAt + DEVICE_PAIRING_CODE_TTL_SECONDS * 1000) setNow(receivedAt) }, onError: (requestError) => { setLinks(null) setLocalExpiresAt(null) setError( requestError instanceof Error && requestError.message ? requestError.message : LINKS_FAILED_MESSAGE, ) }, }, ) }, [mutate]) useEffect(() => { if (open && !wasOpenRef.current) { wasOpenRef.current = true setLinks(null) setLocalExpiresAt(null) setRevealed(false) requestLinks() return } if (!open && wasOpenRef.current) { wasOpenRef.current = false setLinks(null) setLocalExpiresAt(null) setError(null) setRevealed(false) void invalidatePairedDevices() } }, [invalidatePairedDevices, open, requestLinks]) useEffect(() => { if (!open || !links) return undefined const interval = setInterval(() => setNow(Date.now()), 1000) return () => clearInterval(interval) }, [links, open]) useEffect(() => { if (!open || !links || localExpiresAt === null || isPending) return if (now < localExpiresAt) return requestLinks() }, [isPending, links, localExpiresAt, now, open, requestLinks]) return ( Connect a device Scan a code with the mobile app or your phone camera to sign in. {error ? (
{error}
) : !links ? (

Creating a pairing code…

) : (
{localExpiresAt !== null && (

Expires in {formatCountdown(localExpiresAt, now)}

)} Mobile app Browser / PWA {links.appLink ? ( <>

{SCREEN_SHARING_WARNING}

{links.headerNames.length > 0 ? `Includes headers: ${links.headerNames.join(', ')}` : 'No remote access headers are included.'}

) : (

{INSECURE_ORIGIN_EXPLANATION}

)}

{BROWSER_HINT}

{links.warnings.map((warning) => (

{WARNING_MESSAGES[warning]}

))}
)}
) }