Skip to content

Your lightweight open-source personal agent.

refactor(webui): isolate channel pairing workflow

chengyongru792d01be0322
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<string | null>(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 = (
- <PairingCodeSlots
- value={value}
- disabled={Boolean(busyCode)}
- matched={Boolean(matchedRequest)}
- invalid={showNoMatch}
- ariaLabel={t("app.pairing.code", { defaultValue: "Pairing code" })}
- onChange={(next) => {
- attemptedCode.current = null;
- setValue(formatPairingCodeInput(next));
- }}
- />
- );
-
- return (
- <div
- role="dialog"
- aria-live="polite"
- aria-label={t("app.pairing.title", { defaultValue: "Pair a chat user" })}
- className={cn(
- "fixed right-4 top-[calc(0.75rem+env(safe-area-inset-top))] z-[70]",
- "w-[min(calc(100vw-2rem),24rem)] rounded-modal",
- floatingSurfaceElevationClassName,
- "p-4",
- "animate-in fade-in-0 slide-in-from-top-2 duration-200",
- )}
- >
- <div className="flex items-start gap-3">
- <PairingChannelBadge channel={displayRequest.channel} />
- <div className="min-w-0 flex-1">
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <p className="text-[15px] font-semibold tracking-[-0.01em]">
- {t("app.pairing.title", { defaultValue: "Pair a chat user" })}
- </p>
- <p
- className="mt-1 text-pretty text-[13px] leading-5 text-muted-foreground"
- role={displayRequest.delivery_status === "failed" ? "alert" : undefined}
- >
- {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.",
- })}
- </p>
- </div>
- <button
- type="button"
- aria-label={t("common.close", { defaultValue: "Close" })}
- onClick={() => onDismiss(displayRequest)}
- className="rounded-full p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
- >
- <X className="h-4 w-4" aria-hidden />
- </button>
- </div>
-
- {deliveryBlocked ? (
- <details className="mt-3 text-[12.5px] text-muted-foreground">
- <summary className="cursor-pointer">
- {t("app.pairing.haveCode", { defaultValue: "Already received a code?" })}
- </summary>
- {codeInput}
- </details>
- ) : (
- <>
- <label className="mt-4 block text-[12.5px] font-medium text-foreground">
- {t("app.pairing.code", { defaultValue: "Pairing code" })}
- </label>
- {codeInput}
- </>
- )}
-
- {!deliveryBlocked || total > 1 ? (
- <div className="mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground">
- <span>
- {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,
- })}
- </span>
- {total > 1 ? (
- <span className="shrink-0">
- {t("app.pairing.queueCount", {
- defaultValue: "{{count}} pending",
- count: total,
- })}
- </span>
- ) : null}
- </div>
- ) : null}
-
- {showNoMatch ? (
- <p className="mt-2 text-[12px] leading-5 text-destructive">
- {t("app.pairing.noMatch", {
- defaultValue: "No pending request matches this code.",
- })}
- </p>
- ) : null}
-
- {error ? (
- <div className="mt-2 space-y-2">
- <p role="alert" className="text-[12px] leading-5 text-destructive">{error}</p>
- {matchedRequest ? (
- <Button
- variant="outline"
- size="sm"
- disabled={Boolean(busyCode)}
- onClick={() => onApprove(matchedRequest.code)}
- >
- {t("common.retry", { defaultValue: "Retry" })}
- </Button>
- ) : null}
- </div>
- ) : null}
- </div>
- </div>
- </div>
- );
-}
-
-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 (
- <div
- className="mt-0.5 grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-2xl border bg-background shadow-sm"
- style={{
- borderColor: `${color}30`,
- boxShadow: `inset 0 0 0 1px ${color}14, 0 1px 2px rgba(15,23,42,0.06)`,
- }}
- aria-hidden
- >
- {logoUrl ? (
- <img
- src={logoUrl}
- alt=""
- decoding="async"
- loading="lazy"
- className="h-6 w-6 object-contain"
- onLoad={onLogoLoad}
- onError={onLogoError}
- />
- ) : presentation ? (
- <span className="text-[11px] font-bold tracking-[-0.02em]" style={{ color }}>
- {initials}
- </span>
- ) : (
- <ShieldCheck className="h-5 w-5" style={{ color }} />
- )}
- </div>
- );
-}
-
-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<HTMLInputElement>(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 (
- <div
- key={index}
- className={cn(
- "grid h-10 w-7 place-items-center rounded-xl border",
- "bg-background/80 font-mono text-[16px] font-semibold uppercase",
- "text-foreground shadow-[0_1px_1px_rgba(15,23,42,0.04)] transition",
- matched
- ? "border-emerald-500/45 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
- : invalid
- ? "border-destructive/55 bg-destructive/5 text-destructive"
- : highlighted
- ? "border-foreground/30 bg-background text-foreground"
- : char
- ? "border-border/80 bg-background text-foreground"
- : "border-border/55 bg-muted/35 text-muted-foreground",
- )}
- >
- {char || " "}
- </div>
- );
- };
-
- return (
- <div
- className={cn(
- "relative mt-2 rounded-2xl border border-transparent p-1",
- "transition duration-150",
- focused && !disabled ? "border-ring/20 bg-muted/35" : "bg-transparent",
- )}
- onClick={() => inputRef.current?.focus()}
- >
- <input
- ref={inputRef}
- value={value}
- aria-label={ariaLabel}
- inputMode="text"
- autoCapitalize="characters"
- autoComplete="off"
- autoCorrect="off"
- spellCheck={false}
- maxLength={9}
- disabled={disabled}
- onFocus={() => 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"
- />
- <div className="pointer-events-none flex items-center gap-1.5">
- {slots.slice(0, 4).map((char, index) => renderSlot(char, index))}
- <div className="mx-0.5 h-px w-2.5 rounded-full bg-muted-foreground/35" />
- {slots.slice(4).map((char, index) => renderSlot(char, index + 4))}
- </div>
- </div>
- );
-}
-
-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<string | null>(null);
const [isRestarting, setIsRestarting] = useState(false);
- const [pairingRequests, setPairingRequests] = useState<PairingRequestInfo[]>([]);
- const [pairingBusyCode, setPairingBusyCode] = useState<string | null>(null);
- const [pairingError, setPairingError] = useState<string | null>(null);
- const pairingRefreshRef = useRef<Promise<number> | null>(null);
- const pairingRefreshPendingRef = useRef(false);
- const [snoozedPairingCodes, setSnoozedPairingCodes] = useState<Map<string, {
- until: number;
- deliveryStatus: PairingRequestInfo["delivery_status"];
- }>>(
- () => new Map(),
- );
const [runningChatIds, setRunningChatIds] = useState<Set<string>>(() => new Set());
const [updatedChatIds, setUpdatedChatIds] = useState<Set<string>>(readSessionUpdateChatIds);
const [workspaces, setWorkspaces] = useState<WorkspacesPayload | null>(null);
const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken);
- const pageVisible = usePageVisibility();
const [settingsSnapshot, setSettingsSnapshot] = useState<SettingsPayload | null>(null);
const [settingsLoading, setSettingsLoading] = useState(true);
const settingsRefreshGenerationRef = useRef(0);
@@ -1475,80 +1114,8 @@ function Shell({
writeSessionUpdateChatIds(updatedChatIds);
}, [updatedChatIds]);
- const refreshPairingRequests = useCallback((): Promise<number> => {
- 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<ChatSummary | null>(() => {
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({
</div>
</div>
) : null}
- <PairingCodePopup
- requests={visiblePairingRequests}
- total={visiblePairingRequests.length}
- busyCode={pairingBusyCode}
- error={pairingError}
- onApprove={(code) => void onPairingAction("approve", code)}
- onDismiss={onDismissPairingRequest}
- />
+ <ChannelPairing />
</div>
</ThemeProvider>
);
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<PairingRequestInfo[]>([]);
+ const [pairingBusyCode, setPairingBusyCode] = useState<string | null>(null);
+ const [pairingError, setPairingError] = useState<string | null>(null);
+ const pairingRefreshRef = useRef<Promise<number> | null>(null);
+ const pairingRefreshPendingRef = useRef(false);
+ const [snoozedPairingCodes, setSnoozedPairingCodes] = useState<Map<string, {
+ until: number;
+ deliveryStatus: PairingRequestInfo["delivery_status"];
+ }>>(
+ () => new Map(),
+ );
+
+ const refreshPairingRequests = useCallback((): Promise<number> => {
+ 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 (
+ <PairingCodePopup
+ requests={visiblePairingRequests}
+ total={visiblePairingRequests.length}
+ busyCode={pairingBusyCode}
+ error={pairingError}
+ onApprove={(code) => 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<string | null>(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 = (
+ <PairingCodeSlots
+ value={value}
+ disabled={Boolean(busyCode)}
+ matched={Boolean(matchedRequest)}
+ invalid={showNoMatch}
+ ariaLabel={t("app.pairing.code", { defaultValue: "Pairing code" })}
+ onChange={(next) => {
+ attemptedCode.current = null;
+ setValue(formatPairingCodeInput(next));
+ }}
+ />
+ );
+
+ return (
+ <div
+ role="dialog"
+ aria-live="polite"
+ aria-label={t("app.pairing.title", { defaultValue: "Pair a chat user" })}
+ className={cn(
+ "fixed right-4 top-[calc(0.75rem+env(safe-area-inset-top))] z-[70]",
+ "w-[min(calc(100vw-2rem),24rem)] rounded-modal",
+ floatingSurfaceElevationClassName,
+ "p-4",
+ "animate-in fade-in-0 slide-in-from-top-2 duration-200",
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <PairingChannelBadge channel={displayRequest.channel} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <p className="text-[15px] font-semibold tracking-[-0.01em]">
+ {t("app.pairing.title", { defaultValue: "Pair a chat user" })}
+ </p>
+ <p
+ className="mt-1 text-pretty text-[13px] leading-5 text-muted-foreground"
+ role={displayRequest.delivery_status === "failed" ? "alert" : undefined}
+ >
+ {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.",
+ })}
+ </p>
+ </div>
+ <button
+ type="button"
+ aria-label={t("common.close", { defaultValue: "Close" })}
+ onClick={() => onDismiss(displayRequest)}
+ className="rounded-full p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
+ >
+ <X className="h-4 w-4" aria-hidden />
+ </button>
+ </div>
+
+ {deliveryBlocked ? (
+ <details className="mt-3 text-[12.5px] text-muted-foreground">
+ <summary className="cursor-pointer">
+ {t("app.pairing.haveCode", { defaultValue: "Already received a code?" })}
+ </summary>
+ {codeInput}
+ </details>
+ ) : (
+ <>
+ <label className="mt-4 block text-[12.5px] font-medium text-foreground">
+ {t("app.pairing.code", { defaultValue: "Pairing code" })}
+ </label>
+ {codeInput}
+ </>
+ )}
+
+ {!deliveryBlocked || total > 1 ? (
+ <div className="mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground">
+ <span>
+ {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,
+ })}
+ </span>
+ {total > 1 ? (
+ <span className="shrink-0">
+ {t("app.pairing.queueCount", {
+ defaultValue: "{{count}} pending",
+ count: total,
+ })}
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+
+ {showNoMatch ? (
+ <p className="mt-2 text-[12px] leading-5 text-destructive">
+ {t("app.pairing.noMatch", {
+ defaultValue: "No pending request matches this code.",
+ })}
+ </p>
+ ) : null}
+
+ {error ? (
+ <div className="mt-2 space-y-2">
+ <p role="alert" className="text-[12px] leading-5 text-destructive">{error}</p>
+ {matchedRequest ? (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={Boolean(busyCode)}
+ onClick={() => onApprove(matchedRequest.code)}
+ >
+ {t("common.retry", { defaultValue: "Retry" })}
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+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 (
+ <div
+ className="mt-0.5 grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-2xl border bg-background shadow-sm"
+ style={{
+ borderColor: `${color}30`,
+ boxShadow: `inset 0 0 0 1px ${color}14, 0 1px 2px rgba(15,23,42,0.06)`,
+ }}
+ aria-hidden
+ >
+ {logoUrl ? (
+ <img
+ src={logoUrl}
+ alt=""
+ decoding="async"
+ loading="lazy"
+ className="h-6 w-6 object-contain"
+ onLoad={onLogoLoad}
+ onError={onLogoError}
+ />
+ ) : presentation ? (
+ <span className="text-[11px] font-bold tracking-[-0.02em]" style={{ color }}>
+ {initials}
+ </span>
+ ) : (
+ <ShieldCheck className="h-5 w-5" style={{ color }} />
+ )}
+ </div>
+ );
+}
+
+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<HTMLInputElement>(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 (
+ <div
+ key={index}
+ className={cn(
+ "grid h-10 w-7 place-items-center rounded-xl border",
+ "bg-background/80 font-mono text-[16px] font-semibold uppercase",
+ "text-foreground shadow-[0_1px_1px_rgba(15,23,42,0.04)] transition",
+ matched
+ ? "border-emerald-500/45 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
+ : invalid
+ ? "border-destructive/55 bg-destructive/5 text-destructive"
+ : highlighted
+ ? "border-foreground/30 bg-background text-foreground"
+ : char
+ ? "border-border/80 bg-background text-foreground"
+ : "border-border/55 bg-muted/35 text-muted-foreground",
+ )}
+ >
+ {char || " "}
+ </div>
+ );
+ };
+
+ return (
+ <div
+ className={cn(
+ "relative mt-2 rounded-2xl border border-transparent p-1",
+ "transition duration-150",
+ focused && !disabled ? "border-ring/20 bg-muted/35" : "bg-transparent",
+ )}
+ onClick={() => inputRef.current?.focus()}
+ >
+ <input
+ ref={inputRef}
+ value={value}
+ aria-label={ariaLabel}
+ inputMode="text"
+ autoCapitalize="characters"
+ autoComplete="off"
+ autoCorrect="off"
+ spellCheck={false}
+ maxLength={9}
+ disabled={disabled}
+ onFocus={() => 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"
+ />
+ <div className="pointer-events-none flex items-center gap-1.5">
+ {slots.slice(0, 4).map((char, index) => renderSlot(char, index))}
+ <div className="mx-0.5 h-px w-2.5 rounded-full bg-muted-foreground/35" />
+ {slots.slice(4).map((char, index) => renderSlot(char, index + 4))}
+ </div>
+ </div>
+ );
+}
+
+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(<App />);
+ 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";