diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 610cefaf6..aa9d6bfb0 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -8,10 +8,10 @@ import { useState, type ReactNode, } from "react"; -import { ArrowRight, ChevronDown, Eye, EyeOff, ShieldCheck, X } from "lucide-react"; +import { ArrowRight, ChevronDown, Eye, EyeOff } from "lucide-react"; import { ThemeToggleIcon } from "@/components/icons/ThemeToggleIcon"; import { Trans, useTranslation } from "react-i18next"; -import { channelUiPresentation } from "@/channel-plugins/registry"; +import { ChannelPairing } from "@/components/pairing/ChannelPairing"; import { StarPrompt } from "@/components/StarPrompt"; import { Sidebar } from "@/components/Sidebar"; import { RemoteInstances } from "@/components/remote/RemoteInstances"; @@ -55,14 +55,11 @@ import { useReconnectRuns } from "@/hooks/useReconnectRuns"; import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh"; import { useSidebarState } from "@/hooks/useSidebarState"; import { useSkills } from "@/hooks/useSkills"; -import { useLogoFallback } from "@/hooks/useLogoFallback"; -import { usePageVisibility } from "@/hooks/usePageVisibility"; import { useMediaQuery } from "@/hooks/useMediaQuery"; import { useAppViewport } from "@/hooks/useAppViewport"; import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import { ThemeProvider, useTheme } from "@/hooks/useTheme"; import { useReadingTypography } from "@/hooks/useReadingTypography"; -import { logoFallbackUrls } from "@/lib/provider-brand"; import { cn } from "@/lib/utils"; import { BootstrapAuthRequiredError, @@ -86,7 +83,6 @@ import type { BootstrapResponse, ChatSummary, RuntimeSurface, - PairingRequestInfo, SessionAutomationJob, SettingsPayload, WorkspaceScopePayload, @@ -95,12 +91,7 @@ import type { import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Disclosure } from "@/components/ui/disclosure"; -import { - fetchPairingRequests, - fetchSettings, - fetchWorkspaces, - runPairingAction, -} from "@/lib/api"; +import { fetchSettings, fetchWorkspaces } from "@/lib/api"; import { createRuntimeHost, isNativeRuntime, @@ -144,9 +135,6 @@ const SIDEBAR_RAIL_WIDTH = 56; const MOBILE_SIDEBAR_WIDTH = `min(${SIDEBAR_WIDTH}px, calc(100vw - 0.75rem))`; const TOKEN_REFRESH_MARGIN_MS = 30_000; const TOKEN_REFRESH_MIN_DELAY_MS = 5_000; -const PAIRING_POLL_INTERVAL_MS = 5_000; -const PAIRING_IDLE_POLL_INTERVAL_MS = 15_000; -const PAIRING_DISMISS_SNOOZE_MS = 30_000; type ShellView = "chat" | "settings" | "apps" | "automations" | "skills" | "channels" | "remote"; type ShellRoute = { view: ShellView; @@ -602,343 +590,6 @@ function HostChrome({ ); } -function PairingCodePopup({ - requests, - total, - busyCode, - error, - onApprove, - onDismiss, -}: { - requests: PairingRequestInfo[]; - total: number; - busyCode: string | null; - error: string | null; - onApprove: (code: string) => void; - onDismiss: (request: PairingRequestInfo) => void; -}) { - const { t } = useTranslation(); - const [value, setValue] = useState(""); - const attemptedCode = useRef(null); - const normalizedCode = normalizePairingCode(value); - const matchedRequest = useMemo( - () => requests.find((request) => request.code === normalizedCode) ?? null, - [normalizedCode, requests], - ); - // Keep delivered and legacy requests usable even when another bot cannot reply. - const firstRequest = requests.find((request) => ( - !request.delivery_status || request.delivery_status === "sent" - )) ?? requests[0] ?? null; - const displayRequest = matchedRequest ?? firstRequest; - const deliveryBlocked = displayRequest?.delivery_status === "failed" - || displayRequest?.delivery_status === "sending"; - const expires = formatPairingExpiry(displayRequest?.expires_in_seconds); - const isCompleteCode = normalizedCode.length === 9; - const showNoMatch = isCompleteCode && !matchedRequest && !busyCode; - - useEffect(() => { - if (!matchedRequest || busyCode || attemptedCode.current === matchedRequest.code) return; - attemptedCode.current = matchedRequest.code; - onApprove(matchedRequest.code); - }, [busyCode, matchedRequest, onApprove]); - - useEffect(() => { - if (!requests.length) { - setValue(""); - attemptedCode.current = null; - } - }, [requests.length]); - - if (!firstRequest) return null; - - const codeInput = ( - { - attemptedCode.current = null; - setValue(formatPairingCodeInput(next)); - }} - /> - ); - - return ( -
-
- -
-
-
-

- {t("app.pairing.title", { defaultValue: "Pair a chat user" })} -

-

- {displayRequest.delivery_status === "failed" ? t("app.pairing.deliveryFailed", { - defaultValue: "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.", - }) : displayRequest.delivery_status === "sending" ? t("app.pairing.deliverySending", { - defaultValue: "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.", - }) : t("app.pairing.description", { - defaultValue: "Enter the pairing code shown in the chat.", - })} -

-
- -
- - {deliveryBlocked ? ( -
- - {t("app.pairing.haveCode", { defaultValue: "Already received a code?" })} - - {codeInput} -
- ) : ( - <> - - {codeInput} - - )} - - {!deliveryBlocked || total > 1 ? ( -
- - {matchedRequest && busyCode === matchedRequest.code - ? t("app.pairing.matched", { - defaultValue: "Matched {{channel}}. Connecting...", - channel: channelLabel(matchedRequest.channel), - }) - : deliveryBlocked ? null : t("app.pairing.expiresInline", { - defaultValue: "Code expires {{expires}}.", - expires, - })} - - {total > 1 ? ( - - {t("app.pairing.queueCount", { - defaultValue: "{{count}} pending", - count: total, - })} - - ) : null} -
- ) : null} - - {showNoMatch ? ( -

- {t("app.pairing.noMatch", { - defaultValue: "No pending request matches this code.", - })} -

- ) : null} - - {error ? ( -
-

{error}

- {matchedRequest ? ( - - ) : null} -
- ) : null} -
-
-
- ); -} - -function PairingChannelBadge({ channel }: { channel: string }) { - const presentation = pairingChannelPresentation(channel); - const initials = presentation.initials; - const color = presentation.color; - const logoUrls = useMemo( - () => logoFallbackUrls(presentation?.logoUrl), - [presentation?.logoUrl], - ); - const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls); - - return ( -
- {logoUrl ? ( - - ) : presentation ? ( - - {initials} - - ) : ( - - )} -
- ); -} - -function PairingCodeSlots({ - value, - disabled, - matched, - invalid, - ariaLabel, - onChange, -}: { - value: string; - disabled: boolean; - matched: boolean; - invalid: boolean; - ariaLabel: string; - onChange: (value: string) => void; -}) { - const inputRef = useRef(null); - const [focused, setFocused] = useState(false); - const compact = compactPairingCode(value); - const activeIndex = Math.min(compact.length, 7); - const slots = Array.from({ length: 8 }, (_, index) => compact[index] ?? ""); - const renderSlot = (char: string, index: number) => { - const highlighted = focused && index === activeIndex && !matched && !invalid; - return ( -
- {char || " "} -
- ); - }; - - return ( -
inputRef.current?.focus()} - > - setFocused(true)} - onBlur={() => setFocused(false)} - onChange={(event) => onChange(event.target.value)} - className="absolute inset-0 z-10 h-full w-full cursor-text opacity-0 disabled:cursor-default" - /> -
- {slots.slice(0, 4).map((char, index) => renderSlot(char, index))} -
- {slots.slice(4).map((char, index) => renderSlot(char, index + 4))} -
-
- ); -} - -function compactPairingCode(raw: string): string { - return raw.replace(/[^a-zA-Z0-9]/g, "").slice(0, 8).toUpperCase(); -} - -function formatPairingCodeInput(raw: string): string { - const compact = compactPairingCode(raw); - if (compact.length <= 4) return compact; - return `${compact.slice(0, 4)}-${compact.slice(4)}`; -} - -function normalizePairingCode(raw: string): string { - return formatPairingCodeInput(raw); -} - -function pairingChannelKey(channel: string): string { - const raw = channel.trim().toLowerCase(); - if (!raw) return ""; - return raw.split(/[.:]/)[0] ?? raw; -} - -function channelLabel(channel: string): string { - return pairingChannelPresentation(channel).label; -} - -function pairingChannelPresentation(channel: string) { - const key = pairingChannelKey(channel); - const plugin = channelUiPresentation(key); - return { - label: plugin?.displayName ?? channel, - initials: plugin?.initials ?? channel.slice(0, 2).toUpperCase(), - color: plugin?.color ?? "#10B981", - logoUrl: plugin?.logoUrl, - }; -} - -function formatPairingExpiry(seconds: number | null | undefined): string { - if (seconds == null) return "soon"; - if (seconds <= 0) return "expired"; - if (seconds < 60) return `${seconds}s`; - return `${Math.ceil(seconds / 60)} min`; -} - function resolveRuntimeSurface( surface: RuntimeSurface | null | undefined, fallback: RuntimeSurface, @@ -1279,22 +930,10 @@ function Shell({ const restartStartedAtRef = useRef(0); const [restartToast, setRestartToast] = useState(null); const [isRestarting, setIsRestarting] = useState(false); - const [pairingRequests, setPairingRequests] = useState([]); - const [pairingBusyCode, setPairingBusyCode] = useState(null); - const [pairingError, setPairingError] = useState(null); - const pairingRefreshRef = useRef | null>(null); - const pairingRefreshPendingRef = useRef(false); - const [snoozedPairingCodes, setSnoozedPairingCodes] = useState>( - () => new Map(), - ); const [runningChatIds, setRunningChatIds] = useState>(() => new Set()); const [updatedChatIds, setUpdatedChatIds] = useState>(readSessionUpdateChatIds); const [workspaces, setWorkspaces] = useState(null); const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken); - const pageVisible = usePageVisibility(); const [settingsSnapshot, setSettingsSnapshot] = useState(null); const [settingsLoading, setSettingsLoading] = useState(true); const settingsRefreshGenerationRef = useRef(0); @@ -1475,80 +1114,8 @@ function Shell({ writeSessionUpdateChatIds(updatedChatIds); }, [updatedChatIds]); - const refreshPairingRequests = useCallback((): Promise => { - if (pairingRefreshRef.current) { - // An earlier snapshot may predate the notice or completed mutation. - pairingRefreshPendingRef.current = true; - return pairingRefreshRef.current; - } - - const request = (async () => { - let requestCount: number; - do { - pairingRefreshPendingRef.current = false; - try { - const payload = await fetchPairingRequests(getToken()); - const requests = Array.isArray(payload.requests) ? payload.requests : []; - setPairingRequests(requests); - setSnoozedPairingCodes((current) => { - if (current.size === 0) return current; - const activeRequests = new Map(requests.map((request) => [request.code, request])); - const now = Date.now(); - const next = new Map( - Array.from(current).filter( - ([code, snooze]) => activeRequests.has(code) - && snooze.until > now - && activeRequests.get(code)?.delivery_status === snooze.deliveryStatus, - ), - ); - return next.size === current.size ? current : next; - }); - requestCount = requests.length; - } catch { - // Pairing is an opportunistic WebUI affordance. The slash command path - // remains available if this polling request fails. - requestCount = 0; - } - } while (pairingRefreshPendingRef.current); - return requestCount; - })(); - const clearRequest = () => { - if (pairingRefreshRef.current === request) pairingRefreshRef.current = null; - }; - pairingRefreshRef.current = request; - void request.then(clearRequest, clearRequest); - return request; - }, [getToken]); - useEffect(() => client.onReady(() => invalidateToolsCatalog(client)), [client]); - useEffect(() => { - if (!pageVisible) return undefined; - - let disposed = false; - let timer: number | null = null; - const poll = async () => { - const requestCount = await refreshPairingRequests(); - if (disposed) return; - if (timer !== null) window.clearTimeout(timer); - timer = window.setTimeout( - () => void poll(), - requestCount > 0 ? PAIRING_POLL_INTERVAL_MS : PAIRING_IDLE_POLL_INTERVAL_MS, - ); - }; - const requestRefresh = () => { void poll(); }; - const unsubscribePairing = client.onPairingChange(requestRefresh); - const unsubscribeReady = client.onReady(requestRefresh); - void poll(); - return () => { - disposed = true; - pairingRefreshPendingRef.current = false; - if (timer !== null) window.clearTimeout(timer); - unsubscribePairing(); - unsubscribeReady(); - }; - }, [client, pageVisible, refreshPairingRequests]); - const activeSession = useMemo(() => { if (!activeKey) return null; if (temporarySessions[activeKey]) return temporarySessions[activeKey]; @@ -2477,52 +2044,6 @@ function Shell({ void onRequestDeleteMany([{ key, label }], onDecision); }, [onRequestDeleteMany]); - const visiblePairingRequests = useMemo( - () => { - const now = Date.now(); - return pairingRequests.filter((request) => { - const snooze = snoozedPairingCodes.get(request.code); - return !snooze || snooze.until <= now; - }); - }, - [pairingRequests, snoozedPairingCodes], - ); - - const onPairingAction = useCallback( - async (action: "approve" | "deny", code: string) => { - setPairingBusyCode(code); - setPairingError(null); - try { - const payload = await runPairingAction(client, action, code); - setPairingRequests(Array.isArray(payload.requests) ? payload.requests : []); - setSnoozedPairingCodes((current) => { - if (!current.has(code)) return current; - const next = new Map(current); - next.delete(code); - return next; - }); - } catch (e) { - setPairingError((e as Error).message); - } finally { - setPairingBusyCode(null); - // A mutation reply can be older than an already-delivered notification. - void refreshPairingRequests(); - } - }, - [client, refreshPairingRequests], - ); - - const onDismissPairingRequest = useCallback((request: PairingRequestInfo) => { - setSnoozedPairingCodes((current) => { - const next = new Map(current); - next.set(request.code, { - until: Date.now() + PAIRING_DISMISS_SNOOZE_MS, - deliveryStatus: request.delivery_status, - }); - return next; - }); - }, []); - const titleForSession = useCallback((session: ChatSummary) => ( sidebarState.title_overrides[session.key] || session.title @@ -3248,14 +2769,7 @@ function Shell({
) : null} - void onPairingAction("approve", code)} - onDismiss={onDismissPairingRequest} - /> + ); diff --git a/webui/src/components/pairing/ChannelPairing.tsx b/webui/src/components/pairing/ChannelPairing.tsx new file mode 100644 index 000000000..cd2666ce1 --- /dev/null +++ b/webui/src/components/pairing/ChannelPairing.tsx @@ -0,0 +1,156 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +import { usePageVisibility } from "@/hooks/usePageVisibility"; +import { fetchPairingRequests, runPairingAction } from "@/lib/api"; +import type { PairingRequestInfo } from "@/lib/types"; +import { useClient } from "@/providers/ClientProvider"; +import { PairingCodePopup } from "./PairingCodePopup"; + +const PAIRING_POLL_INTERVAL_MS = 5_000; +const PAIRING_IDLE_POLL_INTERVAL_MS = 15_000; +const PAIRING_DISMISS_SNOOZE_MS = 30_000; + +export function ChannelPairing() { + const { client, getToken } = useClient(); + const pageVisible = usePageVisibility(); + const [pairingRequests, setPairingRequests] = useState([]); + const [pairingBusyCode, setPairingBusyCode] = useState(null); + const [pairingError, setPairingError] = useState(null); + const pairingRefreshRef = useRef | null>(null); + const pairingRefreshPendingRef = useRef(false); + const [snoozedPairingCodes, setSnoozedPairingCodes] = useState>( + () => new Map(), + ); + + const refreshPairingRequests = useCallback((): Promise => { + if (pairingRefreshRef.current) { + // An earlier snapshot may predate the notice or completed mutation. + pairingRefreshPendingRef.current = true; + return pairingRefreshRef.current; + } + + const request = (async () => { + let requestCount: number; + do { + pairingRefreshPendingRef.current = false; + try { + const payload = await fetchPairingRequests(getToken()); + const requests = Array.isArray(payload.requests) ? payload.requests : []; + setPairingRequests(requests); + setSnoozedPairingCodes((current) => { + if (current.size === 0) return current; + const activeRequests = new Map(requests.map((request) => [request.code, request])); + const now = Date.now(); + const next = new Map( + Array.from(current).filter( + ([code, snooze]) => activeRequests.has(code) + && snooze.until > now + && activeRequests.get(code)?.delivery_status === snooze.deliveryStatus, + ), + ); + return next.size === current.size ? current : next; + }); + requestCount = requests.length; + } catch { + // Pairing is an opportunistic WebUI affordance. The slash command path + // remains available if this polling request fails. + requestCount = 0; + } + } while (pairingRefreshPendingRef.current); + return requestCount; + })(); + const clearRequest = () => { + if (pairingRefreshRef.current === request) pairingRefreshRef.current = null; + }; + pairingRefreshRef.current = request; + void request.then(clearRequest, clearRequest); + return request; + }, [getToken]); + + useEffect(() => { + if (!pageVisible) return undefined; + + let disposed = false; + let timer: number | null = null; + const poll = async () => { + const requestCount = await refreshPairingRequests(); + if (disposed) return; + if (timer !== null) window.clearTimeout(timer); + timer = window.setTimeout( + () => void poll(), + requestCount > 0 ? PAIRING_POLL_INTERVAL_MS : PAIRING_IDLE_POLL_INTERVAL_MS, + ); + }; + const requestRefresh = () => { void poll(); }; + const unsubscribePairing = client.onPairingChange(requestRefresh); + const unsubscribeReady = client.onReady(requestRefresh); + void poll(); + return () => { + disposed = true; + pairingRefreshPendingRef.current = false; + if (timer !== null) window.clearTimeout(timer); + unsubscribePairing(); + unsubscribeReady(); + }; + }, [client, pageVisible, refreshPairingRequests]); + + const visiblePairingRequests = useMemo( + () => { + const now = Date.now(); + return pairingRequests.filter((request) => { + const snooze = snoozedPairingCodes.get(request.code); + return !snooze || snooze.until <= now; + }); + }, + [pairingRequests, snoozedPairingCodes], + ); + + const onPairingAction = useCallback( + async (action: "approve" | "deny", code: string) => { + setPairingBusyCode(code); + setPairingError(null); + try { + const payload = await runPairingAction(client, action, code); + setPairingRequests(Array.isArray(payload.requests) ? payload.requests : []); + setSnoozedPairingCodes((current) => { + if (!current.has(code)) return current; + const next = new Map(current); + next.delete(code); + return next; + }); + } catch (e) { + setPairingError((e as Error).message); + } finally { + setPairingBusyCode(null); + // A mutation reply can be older than an already-delivered notification. + void refreshPairingRequests(); + } + }, + [client, refreshPairingRequests], + ); + + const onDismissPairingRequest = useCallback((request: PairingRequestInfo) => { + setSnoozedPairingCodes((current) => { + const next = new Map(current); + next.set(request.code, { + until: Date.now() + PAIRING_DISMISS_SNOOZE_MS, + deliveryStatus: request.delivery_status, + }); + return next; + }); + }, []); + + return ( + void onPairingAction("approve", code)} + onDismiss={onDismissPairingRequest} + /> + ); +} diff --git a/webui/src/components/pairing/PairingCodePopup.tsx b/webui/src/components/pairing/PairingCodePopup.tsx new file mode 100644 index 000000000..fdd420a8c --- /dev/null +++ b/webui/src/components/pairing/PairingCodePopup.tsx @@ -0,0 +1,348 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { ShieldCheck, X } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { channelUiPresentation } from "@/channel-plugins/registry"; +import { Button } from "@/components/ui/button"; +import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; +import { useLogoFallback } from "@/hooks/useLogoFallback"; +import { logoFallbackUrls } from "@/lib/provider-brand"; +import type { PairingRequestInfo } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +export function PairingCodePopup({ + requests, + total, + busyCode, + error, + onApprove, + onDismiss, +}: { + requests: PairingRequestInfo[]; + total: number; + busyCode: string | null; + error: string | null; + onApprove: (code: string) => void; + onDismiss: (request: PairingRequestInfo) => void; +}) { + const { t } = useTranslation(); + const [value, setValue] = useState(""); + const attemptedCode = useRef(null); + const normalizedCode = normalizePairingCode(value); + const matchedRequest = useMemo( + () => requests.find((request) => request.code === normalizedCode) ?? null, + [normalizedCode, requests], + ); + // Keep delivered and legacy requests usable even when another bot cannot reply. + const firstRequest = requests.find((request) => ( + !request.delivery_status || request.delivery_status === "sent" + )) ?? requests[0] ?? null; + const displayRequest = matchedRequest ?? firstRequest; + const deliveryBlocked = displayRequest?.delivery_status === "failed" + || displayRequest?.delivery_status === "sending"; + const expires = formatPairingExpiry(displayRequest?.expires_in_seconds); + const isCompleteCode = normalizedCode.length === 9; + const showNoMatch = isCompleteCode && !matchedRequest && !busyCode; + + useEffect(() => { + if (!matchedRequest || busyCode || attemptedCode.current === matchedRequest.code) return; + attemptedCode.current = matchedRequest.code; + onApprove(matchedRequest.code); + }, [busyCode, matchedRequest, onApprove]); + + useEffect(() => { + if (!requests.length) { + setValue(""); + attemptedCode.current = null; + } + }, [requests.length]); + + if (!firstRequest) return null; + + const codeInput = ( + { + attemptedCode.current = null; + setValue(formatPairingCodeInput(next)); + }} + /> + ); + + return ( +
+
+ +
+
+
+

+ {t("app.pairing.title", { defaultValue: "Pair a chat user" })} +

+

+ {displayRequest.delivery_status === "failed" ? t("app.pairing.deliveryFailed", { + defaultValue: "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.", + }) : displayRequest.delivery_status === "sending" ? t("app.pairing.deliverySending", { + defaultValue: "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.", + }) : t("app.pairing.description", { + defaultValue: "Enter the pairing code shown in the chat.", + })} +

+
+ +
+ + {deliveryBlocked ? ( +
+ + {t("app.pairing.haveCode", { defaultValue: "Already received a code?" })} + + {codeInput} +
+ ) : ( + <> + + {codeInput} + + )} + + {!deliveryBlocked || total > 1 ? ( +
+ + {matchedRequest && busyCode === matchedRequest.code + ? t("app.pairing.matched", { + defaultValue: "Matched {{channel}}. Connecting...", + channel: channelLabel(matchedRequest.channel), + }) + : deliveryBlocked ? null : t("app.pairing.expiresInline", { + defaultValue: "Code expires {{expires}}.", + expires, + })} + + {total > 1 ? ( + + {t("app.pairing.queueCount", { + defaultValue: "{{count}} pending", + count: total, + })} + + ) : null} +
+ ) : null} + + {showNoMatch ? ( +

+ {t("app.pairing.noMatch", { + defaultValue: "No pending request matches this code.", + })} +

+ ) : null} + + {error ? ( +
+

{error}

+ {matchedRequest ? ( + + ) : null} +
+ ) : null} +
+
+
+ ); +} + +function PairingChannelBadge({ channel }: { channel: string }) { + const presentation = pairingChannelPresentation(channel); + const initials = presentation.initials; + const color = presentation.color; + const logoUrls = useMemo( + () => logoFallbackUrls(presentation?.logoUrl), + [presentation?.logoUrl], + ); + const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls); + + return ( +
+ {logoUrl ? ( + + ) : presentation ? ( + + {initials} + + ) : ( + + )} +
+ ); +} + +function PairingCodeSlots({ + value, + disabled, + matched, + invalid, + ariaLabel, + onChange, +}: { + value: string; + disabled: boolean; + matched: boolean; + invalid: boolean; + ariaLabel: string; + onChange: (value: string) => void; +}) { + const inputRef = useRef(null); + const [focused, setFocused] = useState(false); + const compact = compactPairingCode(value); + const activeIndex = Math.min(compact.length, 7); + const slots = Array.from({ length: 8 }, (_, index) => compact[index] ?? ""); + const renderSlot = (char: string, index: number) => { + const highlighted = focused && index === activeIndex && !matched && !invalid; + return ( +
+ {char || " "} +
+ ); + }; + + return ( +
inputRef.current?.focus()} + > + setFocused(true)} + onBlur={() => setFocused(false)} + onChange={(event) => onChange(event.target.value)} + className="absolute inset-0 z-10 h-full w-full cursor-text opacity-0 disabled:cursor-default" + /> +
+ {slots.slice(0, 4).map((char, index) => renderSlot(char, index))} +
+ {slots.slice(4).map((char, index) => renderSlot(char, index + 4))} +
+
+ ); +} + +function compactPairingCode(raw: string): string { + return raw.replace(/[^a-zA-Z0-9]/g, "").slice(0, 8).toUpperCase(); +} + +function formatPairingCodeInput(raw: string): string { + const compact = compactPairingCode(raw); + if (compact.length <= 4) return compact; + return `${compact.slice(0, 4)}-${compact.slice(4)}`; +} + +function normalizePairingCode(raw: string): string { + return formatPairingCodeInput(raw); +} + +function pairingChannelKey(channel: string): string { + const raw = channel.trim().toLowerCase(); + if (!raw) return ""; + return raw.split(/[.:]/)[0] ?? raw; +} + +function channelLabel(channel: string): string { + return pairingChannelPresentation(channel).label; +} + +function pairingChannelPresentation(channel: string) { + const key = pairingChannelKey(channel); + const plugin = channelUiPresentation(key); + return { + label: plugin?.displayName ?? channel, + initials: plugin?.initials ?? channel.slice(0, 2).toUpperCase(), + color: plugin?.color ?? "#10B981", + logoUrl: plugin?.logoUrl, + }; +} + +function formatPairingExpiry(seconds: number | null | undefined): string { + if (seconds == null) return "soon"; + if (seconds <= 0) return "expired"; + if (seconds < 60) return `${seconds}s`; + return `${Math.ceil(seconds / 60)} min`; +} diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 2d80a0c68..2368422ee 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -4661,6 +4661,25 @@ describe("App layout", () => { expect(within(popup).getByText("2 pending")).toBeVisible(); }); + it("shows a dismissed pairing request again when its snooze expires", async () => { + vi.useFakeTimers(); + mockFetchRoutes({ "/api/settings/pairing": { requests: [{ + code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent", + }] } }); + render(); + await act(async () => {}); + fireEvent.click(within(screen.getByRole("dialog", { name: "Pair account" })) + .getByRole("button", { name: "Close" })); + expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument(); + + await act(async () => { await vi.advanceTimersByTimeAsync(29_999); }); + expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument(); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + const popup = screen.getByRole("dialog", { name: "Pair account" }); + expect(popup).toBeVisible(); + expect(within(popup).getByRole("textbox", { name: "Pairing code" })).toBeEnabled(); + }); + it("shows a recovered pairing reply even after its failure notice was dismissed", async () => { vi.useFakeTimers(); let delivery_status = "failed";