The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 1,064 lines 38.9 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m as resolveMessage } from "~/i18n/messages";
3 import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
4 import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
5 import { PlugIcon, PlusIcon, QrCodeIcon } from "lucide-react";
6 import { type ReactNode, memo, useId, useRef, useState } from "react";
7 import { T, useGT, useMessages } from "gt-react";
8 import {
9 AuthAccessWriteScope,
10 AuthDiagnosticsReadScope,
11 AuthOrchestrationReadScope,
12 AuthFilesystemReadScope,
13 AuthRelayConfigureScope,
14 AuthStandardClientScopes,
15 AuthTerminalOperateScope,
16 AuthTerminalReadScope,
17 type AuthEnvironmentScope,
18 type AuthGrantScope,
19 type AuthPairingCredentialResult,
20 type AdvertisedEndpoint,
21 type EnvironmentId,
22 } from "@t3tools/contracts";
23 import {
24 isAtomCommandInterrupted,
25 squashAtomCommandFailure,
26 } from "@t3tools/client-runtime/state/runtime";
27
28 import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
29 import { cn } from "../../lib/utils";
30 import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
31 import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
32 import {
33 canRevokeOtherClients,
34 isQrShareableEndpoint,
35 selectQrEndpointOption,
36 togglePairingScopeSelection,
37 } from "./ConnectionsSettings.logic";
38 import { useNowSecond } from "../../hooks/useNowSecond";
39 import { Input } from "../ui/input";
40 import { Checkbox } from "../ui/checkbox";
41 import {
42 Dialog,
43 DialogFooter,
44 DialogDescription,
45 DialogHeader,
46 DialogPanel,
47 DialogPopup,
48 DialogTitle,
49 DialogTrigger,
50 } from "../ui/dialog";
51 import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
52 import { QRCodeSvg } from "../ui/qr-code";
53 import { stackedThreadToast, toastManager } from "../ui/toast";
54 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
55 import { Button } from "../ui/button";
56 import { Textarea } from "../ui/textarea";
57 import {
58 type ServerClientSessionRecord,
59 type ServerPairingLinkRecord,
60 } from "~/environments/primary";
61 import { authEnvironment } from "~/state/auth";
62 import { readEnvironmentScope } from "~/state/session";
63 import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy";
64 import { useAtomCommand } from "~/state/use-atom-command";
65 import { ManagedControl } from "../ManagedPolicy";
66 import { openUseInAnotherApp } from "../mcp/UseInAnotherAppDialog";
67 import { ConnectionStatusDot } from "../ConnectionStatusDot";
68 import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
69 import {
70 formatAccessTimestamp,
71 selectPairingEndpoint,
72 isTailscaleHttpsEndpoint,
73 endpointDefaultPreferenceKey,
74 resolveAdvertisedEndpointPairingUrl,
75 resolveCurrentOriginPairingUrl,
76 isHostedAppPairingUrl,
77 endpointShareHint,
78 } from "./ConnectionsSettings.logic";
79
80 function AccessScopeSummary({
81 scopes,
82 label,
83 }: {
84 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
85 readonly label: string;
86 }) {
87 const gt = useGT();
88 const scopeCountLabel = gt("{count, plural, one {{count} scope} other {{count} scopes}}", {
89 count: scopes.length,
90 });
91
92 return (
93 <Popover>
94 <PopoverTrigger
95 openOnHover
96 delay={250}
97 closeDelay={100}
98 render={
99 <button
100 type="button"
101 aria-label={gt("{label}: show {scopes}", { label, scopes: scopeCountLabel })}
102 className="cursor-help underline decoration-border underline-offset-2 outline-hidden hover:text-foreground focus-visible:text-foreground"
103 />
104 }
105 >
106 {scopeCountLabel}
107 </PopoverTrigger>
108 <PopoverPopup
109 side="top"
110 align="start"
111 tooltipStyle
112 className="w-max max-w-80 whitespace-normal"
113 >
114 <p className="mb-1 font-medium">
115 <T>Granted scopes</T>
116 </p>
117 <div className="flex flex-col gap-0.5">
118 {scopes.map((scope) => (
119 <code key={scope} className="font-mono text-foreground/85">
120 {scope}
121 </code>
122 ))}
123 </div>
124 </PopoverPopup>
125 </Popover>
126 );
127 }
128
129 function endpointRowClassName(isAvailable: boolean) {
130 return cn(
131 "relative first:rounded-t-xl last:rounded-b-xl px-3 py-3 sm:px-4",
132 !isAvailable && "bg-muted/15",
133 );
134 }
135
136 type PairingLinkListRowProps = {
137 pairingLink: ServerPairingLinkRecord;
138 credential: string | undefined;
139 defaultShareOpen: boolean;
140 /** Whether this page is served by the environment the link pairs with. */
141 servedByEnvironment: boolean;
142 endpointUrl: string | null | undefined;
143 endpoints: ReadonlyArray<AdvertisedEndpoint>;
144 defaultEndpointKey: string | null;
145 revokingPairingLinkId: string | null;
146 onRevoke: (id: string) => void;
147 canRevoke: boolean;
148 };
149
150 const PairingLinkListRow = memo(function PairingLinkListRow({
151 pairingLink,
152 credential,
153 defaultShareOpen,
154 servedByEnvironment,
155 endpointUrl,
156 endpoints,
157 defaultEndpointKey,
158 revokingPairingLinkId,
159 onRevoke,
160 canRevoke,
161 }: PairingLinkListRowProps) {
162 const gt = useGT();
163 const m = useMessages();
164 const nowMs = useNowSecond();
165 const expiresAtMs = new Date(pairingLink.expiresAt).getTime();
166 const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);
167 const [isQrPanelOpen, setIsQrPanelOpen] = useState(defaultShareOpen);
168 const [qrEndpointId, setQrEndpointId] = useState<string | null>(null);
169 const qrPanelId = useId();
170
171 const currentOriginPairingUrl = credential ? resolveCurrentOriginPairingUrl(credential) : null;
172 const hostedPairingUrl =
173 credential && endpointUrl != null && endpointUrl !== ""
174 ? resolveHostedPairingUrl(endpointUrl, credential)
175 : null;
176 const endpointPairingUrl = (() => {
177 const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey);
178 return endpoint && credential
179 ? resolveAdvertisedEndpointPairingUrl(endpoint, credential)
180 : null;
181 })();
182 const endpointCopyOptions = (() => {
183 const options: Array<{
184 readonly id: string;
185 readonly preferenceKey: string;
186 readonly label: string;
187 readonly url: string;
188 readonly detail: string;
189 readonly qrShareable: boolean;
190 }> = [];
191 if (!credential) return options;
192 for (const endpoint of endpoints) {
193 if (endpoint.status === "unavailable") {
194 continue;
195 }
196 const url = resolveAdvertisedEndpointPairingUrl(endpoint, credential);
197 options.push({
198 id: endpoint.id,
199 preferenceKey: endpointDefaultPreferenceKey(endpoint),
200 label: endpoint.label,
201 url,
202 detail: endpointShareHint(endpoint, url, m),
203 qrShareable: isQrShareableEndpoint(endpoint),
204 });
205 }
206 return options;
207 })();
208 const shareablePairingUrl =
209 endpointPairingUrl ??
210 (credential && endpointUrl != null && endpointUrl !== ""
211 ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, credential))
212 : servedByEnvironment
213 ? currentOriginPairingUrl
214 : null);
215 const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);
216 const revealValue = failedCopyValue ?? shareablePairingUrl ?? credential ?? "";
217 const isRevealValueUrl = revealValue !== credential;
218 const isRevealValueHostedAppPairingUrl = isRevealValueUrl && isHostedAppPairingUrl(revealValue);
219 const isRevealValueQrShareable =
220 endpointCopyOptions.find((option) => option.url === revealValue)?.qrShareable ?? true;
221 const canCopyToClipboard =
222 typeof window !== "undefined" &&
223 window.isSecureContext &&
224 navigator.clipboard?.writeText != null;
225
226 const { copyToClipboard } = useCopyToClipboard<{
227 value: string;
228 kind: "code" | "hosted-link" | "link";
229 }>({
230 onError: (error, { value, kind }) => {
231 // Captured per attempt so concurrent copies cannot make the dialog
232 // reveal a different value than the one that failed.
233 setFailedCopyValue(value);
234 setIsRevealDialogOpen(true);
235 toastManager.add(
236 stackedThreadToast({
237 type: "error",
238 title: canCopyToClipboard
239 ? kind === "hosted-link"
240 ? gt("Could not copy hosted app link")
241 : kind === "link"
242 ? gt("Could not copy pairing URL")
243 : gt("Could not copy pairing code")
244 : gt("Clipboard copy unavailable"),
245 description: canCopyToClipboard ? error.message : gt("Showing the full value instead."),
246 }),
247 );
248 },
249 });
250
251 const copyPairingValue = (value: string, kind: "code" | "hosted-link" | "link") => {
252 copyToClipboard(value, { value, kind });
253 };
254
255 const copyKindForUrl = (url: string): "hosted-link" | "link" =>
256 isHostedAppPairingUrl(url) ? "hosted-link" : "link";
257
258 const handleCopyCode = () => {
259 if (credential) copyPairingValue(credential, "code");
260 };
261
262 const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);
263
264 const primaryLabel = pairingLink.label ?? gt("Pairing link");
265 const selectedQrOption = selectQrEndpointOption(
266 endpointCopyOptions,
267 qrEndpointId,
268 defaultEndpointKey,
269 );
270 const qrPairingUrl = selectedQrOption?.url ?? shareablePairingUrl;
271 const canRenderQrForSelection = selectedQrOption?.qrShareable ?? true;
272 if (expiresAtMs <= nowMs) {
273 return null;
274 }
275
276 return (
277 <div className={ITEM_ROW_CLASSNAME}>
278 <div className={ITEM_ROW_INNER_CLASSNAME}>
279 <div className="min-w-0 flex-1 space-y-1">
280 <div className="flex min-h-5 items-center gap-1.5">
281 <ConnectionStatusDot
282 tooltipText={gt("Link created at {time}", {
283 time: formatAccessTimestamp(pairingLink.createdAt),
284 })}
285 dotClassName="bg-warning"
286 />
287 <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
288 </div>
289 <p className="text-xs text-muted-foreground">
290 <Tooltip>
291 <TooltipTrigger render={<span />}>
292 {formatExpiresInLabel(pairingLink.expiresAt, nowMs, m)}
293 </TooltipTrigger>
294 <TooltipPopup side="top">{expiresAbsolute}</TooltipPopup>
295 </Tooltip>
296 <span aria-hidden> · </span>
297 <AccessScopeSummary scopes={pairingLink.scopes} label={gt("Pairing link scopes")} />
298 </p>
299 {!credential ? (
300 <p className="text-2xs text-muted-foreground/70">
301 <T>Create a new link to share from this client.</T>
302 </p>
303 ) : shareablePairingUrl === null ? (
304 <p className="text-2xs text-muted-foreground/70">
305 <T>
306 Copy the token and pair from another client using this backend&apos;s reachable
307 host.
308 </T>
309 </p>
310 ) : null}
311 </div>
312 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
313 {shareablePairingUrl && canCopyToClipboard ? (
314 <Button
315 size="xs"
316 variant="outline"
317 aria-expanded={isQrPanelOpen}
318 aria-controls={qrPanelId}
319 onClick={() => setIsQrPanelOpen((open) => !open)}
320 >
321 <QrCodeIcon aria-hidden />
322 <T>Share</T>
323 </Button>
324 ) : null}
325 <Dialog
326 open={credential !== undefined && isRevealDialogOpen}
327 onOpenChange={(open) => {
328 setIsRevealDialogOpen(open);
329 if (!open) setFailedCopyValue(null);
330 }}
331 >
332 {!credential ? null : canCopyToClipboard ? (
333 shareablePairingUrl ? null : (
334 <Button size="xs" variant="outline" onClick={handleCopyCode}>
335 <T>Copy code</T>
336 </Button>
337 )
338 ) : (
339 <DialogTrigger render={<Button size="xs" variant="outline" />}>
340 {shareablePairingUrl ? gt("Show link") : gt("Show code")}
341 </DialogTrigger>
342 )}
343 <DialogPopup className="max-w-md">
344 <DialogHeader>
345 <DialogTitle>
346 {isRevealValueUrl
347 ? isRevealValueHostedAppPairingUrl
348 ? gt("Hosted app pairing link")
349 : gt("Pairing link")
350 : gt("Pairing code")}
351 </DialogTitle>
352 <DialogDescription>
353 {isRevealValueUrl
354 ? isRevealValueHostedAppPairingUrl
355 ? gt(
356 "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect.",
357 )
358 : gt(
359 "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect.",
360 )
361 : gt(
362 "Clipboard copy is unavailable here. Manually copy this code into another client.",
363 )}
364 </DialogDescription>
365 </DialogHeader>
366 <DialogPanel>
367 <Textarea
368 readOnly
369 value={revealValue}
370 rows={isRevealValueUrl ? 4 : 3}
371 onFocus={(event) => event.currentTarget.select()}
372 onClick={(event) => event.currentTarget.select()}
373 />
374 {isRevealValueUrl && isRevealValueQrShareable ? (
375 <div className="flex justify-center rounded-xl border border-border/60 bg-muted/30 p-4">
376 <QRCodeSvg
377 value={revealValue}
378 size={132}
379 level="M"
380 marginSize={2}
381 title={gt("Pairing link. Scan to open on another device")}
382 />
383 </div>
384 ) : null}
385 </DialogPanel>
386 <DialogFooter variant="bare">
387 <Button variant="outline" onClick={() => setIsRevealDialogOpen(false)}>
388 <T>Done</T>
389 </Button>
390 {canCopyToClipboard ? (
391 <Button variant="outline" onClick={handleCopyCode}>
392 <T>Copy code</T>
393 </Button>
394 ) : null}
395 </DialogFooter>
396 </DialogPopup>
397 </Dialog>
398 <Button
399 size="xs"
400 variant="destructive-outline"
401 disabled={!canRevoke || revokingPairingLinkId === pairingLink.id}
402 onClick={() => void onRevoke(pairingLink.id)}
403 >
404 {revokingPairingLinkId === pairingLink.id ? gt("Revoking…") : gt("Revoke")}
405 </Button>
406 </div>
407 </div>
408 {isQrPanelOpen && qrPairingUrl !== null ? (
409 <div
410 id={qrPanelId}
411 className="mt-3 flex flex-col gap-4 border-t border-border/50 pt-3 sm:flex-row sm:items-start sm:justify-between"
412 >
413 <div className="min-w-0 flex-1 space-y-3">
414 {endpointCopyOptions.length > 1 ? (
415 <div
416 className="space-y-1.5"
417 role="radiogroup"
418 aria-label={gt("Endpoint the pairing QR code and URL use")}
419 >
420 <p className="text-2xs text-muted-foreground/70">
421 <T>Reach this machine via</T>
422 </p>
423 {endpointCopyOptions.map((option) => {
424 const isSelected = option.id === selectedQrOption?.id;
425 return (
426 <button
427 key={option.id}
428 type="button"
429 role="radio"
430 aria-checked={isSelected}
431 className={cn(
432 "flex w-full items-baseline gap-2 rounded-lg border px-2.5 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
433 isSelected
434 ? "border-foreground/60 bg-muted/30"
435 : "border-border/50 hover:bg-muted/20",
436 )}
437 onClick={() => setQrEndpointId(option.id)}
438 >
439 <span
440 className={cn(
441 "text-xs font-medium",
442 isSelected ? "text-foreground" : "text-muted-foreground",
443 )}
444 >
445 {option.label}
446 </span>
447 <span className="min-w-0 truncate text-2xs text-muted-foreground/70">
448 {option.detail}
449 </span>
450 </button>
451 );
452 })}
453 </div>
454 ) : null}
455 <div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-2.5 py-1.5">
456 <Tooltip>
457 <TooltipTrigger
458 render={
459 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-muted-foreground">
460 {qrPairingUrl}
461 </code>
462 }
463 />
464 <TooltipPopup side="top">{qrPairingUrl}</TooltipPopup>
465 </Tooltip>
466 <Button
467 size="xs"
468 variant="ghost"
469 className="shrink-0"
470 onClick={() => copyPairingValue(qrPairingUrl, copyKindForUrl(qrPairingUrl))}
471 >
472 <T>Copy link</T>
473 </Button>
474 </div>
475 <Button size="xs" variant="ghost" onClick={handleCopyCode}>
476 <T>Copy code only</T>
477 </Button>
478 </div>
479 {canRenderQrForSelection ? (
480 <div className="w-fit shrink-0 self-center rounded-xl bg-white p-3 sm:self-start">
481 <QRCodeSvg
482 value={qrPairingUrl}
483 size={168}
484 level="M"
485 marginSize={1}
486 title={gt("Pairing link. Scan to open on another device")}
487 />
488 </div>
489 ) : (
490 <div className="flex size-[192px] shrink-0 items-center justify-center self-center rounded-xl border border-border/50 p-4 sm:self-start">
491 <p className="text-center text-2xs text-muted-foreground/70">
492 <T>
493 No QR for this endpoint. Another device scanning a loopback link would dial
494 itself; copy the URL for use on this machine instead.
495 </T>
496 </p>
497 </div>
498 )}
499 </div>
500 ) : null}
501 </div>
502 );
503 });
504
505 type ConnectedClientListRowProps = {
506 clientSession: ServerClientSessionRecord;
507 revokingClientSessionId: string | null;
508 onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
509 canRevoke: boolean;
510 };
511
512 const ConnectedClientListRow = memo(function ConnectedClientListRow({
513 clientSession,
514 revokingClientSessionId,
515 onRevokeSession,
516 canRevoke,
517 }: ConnectedClientListRowProps) {
518 const gt = useGT();
519 const m = useMessages();
520 const nowMs = useNowSecond();
521 const isLive = clientSession.current || clientSession.connected;
522 const lastConnectedAt = clientSession.lastConnectedAt;
523 const statusTooltip = isLive
524 ? lastConnectedAt
525 ? gt("Connected for {duration}", {
526 duration: formatElapsedDurationLabel(lastConnectedAt, nowMs, m),
527 })
528 : gt("Connected")
529 : lastConnectedAt
530 ? gt("Last connected at {time}", { time: formatAccessTimestamp(lastConnectedAt) })
531 : gt("Not connected yet.");
532 const deviceInfoBits = [
533 clientSession.client.deviceType !== "unknown"
534 ? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1)
535 : null,
536 clientSession.client.os ?? null,
537 clientSession.client.browser ?? null,
538 clientSession.client.ipAddress ?? null,
539 ].filter((value): value is string => value !== null);
540 const primaryLabel =
541 clientSession.client.label ??
542 ([clientSession.client.os, clientSession.client.browser].filter(Boolean).join(" · ") ||
543 clientSession.subject);
544
545 return (
546 <div className={ITEM_ROW_CLASSNAME}>
547 <div className={ITEM_ROW_INNER_CLASSNAME}>
548 <div className="min-w-0 flex-1 space-y-1">
549 <div className="flex min-h-5 items-center gap-1.5">
550 <ConnectionStatusDot
551 tooltipText={statusTooltip}
552 dotClassName={isLive ? "bg-success" : "bg-muted-foreground/30"}
553 pingClassName={isLive ? "bg-success/60 duration-2000" : null}
554 />
555 <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
556 {clientSession.current ? (
557 <span className="text-3xs text-muted-foreground/80 rounded-md border border-border/50 bg-muted/50 px-1 py-0.5">
558 <T>This device</T>
559 </span>
560 ) : null}
561 </div>
562 <p className="text-xs text-muted-foreground">
563 {deviceInfoBits.length > 0 ? (
564 <>
565 {deviceInfoBits.join(" · ")}
566 <span aria-hidden> · </span>
567 </>
568 ) : null}
569 <AccessScopeSummary scopes={clientSession.scopes} label={gt("Client scopes")} />
570 </p>
571 </div>
572 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
573 {!clientSession.current ? (
574 <Button
575 size="xs"
576 variant="destructive-outline"
577 disabled={!canRevoke || revokingClientSessionId === clientSession.sessionId}
578 onClick={() => void onRevokeSession(clientSession.sessionId)}
579 >
580 {revokingClientSessionId === clientSession.sessionId ? gt("Revoking…") : gt("Revoke")}
581 </Button>
582 ) : null}
583 </div>
584 </div>
585 </div>
586 );
587 });
588
589 type AuthorizedClientsHeaderActionProps = {
590 environmentId: EnvironmentId;
591 onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;
592 clientSessions: ReadonlyArray<ServerClientSessionRecord> | null;
593 isRevokingOtherClients: boolean;
594 onRevokeOtherClients: () => void;
595 delegatableScopes: ReadonlyArray<AuthEnvironmentScope>;
596 };
597
598 export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
599 environmentId,
600 onPairingLinkCreated,
601 clientSessions,
602 isRevokingOtherClients,
603 onRevokeOtherClients,
604 delegatableScopes,
605 }: AuthorizedClientsHeaderActionProps) {
606 const gt = useGT();
607 const m = useMessages();
608 const pairingDenial = managedCapabilityDenial(
609 useManagedPolicy(environmentId),
610 "remoteClients",
611 m,
612 );
613 const createPairingCredential = useAtomCommand(authEnvironment.createPairingCredential, {
614 reportFailure: false,
615 });
616 const [dialogOpen, setDialogOpen] = useState(false);
617 const pairingDialogSessionRef = useRef(0);
618 const [pairingLabel, setPairingLabel] = useState("");
619 const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
620 ...AuthStandardClientScopes,
621 ]);
622 const selectedScopes = pairingScopes.filter((scope) => delegatableScopes.includes(scope));
623 const terminalSelected = selectedScopes.includes(AuthTerminalOperateScope);
624 const relayAdminSelected = selectedScopes.includes(AuthRelayConfigureScope);
625 const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
626
627 const handlePairingDialogOpenChange = (open: boolean) => {
628 setDialogOpen(open);
629 if (!open) {
630 pairingDialogSessionRef.current += 1;
631 setPairingLabel("");
632 setPairingScopes(
633 AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
634 );
635 }
636 };
637
638 const handleCreatePairingLink = async () => {
639 if (
640 selectedScopes.length === 0 ||
641 !readEnvironmentScope(environmentId, AuthAccessWriteScope) ||
642 !selectedScopes.every((scope) => readEnvironmentScope(environmentId, scope))
643 )
644 return;
645 const dialogSession = pairingDialogSessionRef.current;
646 setIsCreatingPairingLink(true);
647 const trimmedLabel = pairingLabel.trim();
648 const result = await createPairingCredential({
649 environmentId,
650 input: { ...(trimmedLabel ? { label: trimmedLabel } : {}), scopes: selectedScopes },
651 });
652 if (result._tag === "Success") {
653 onPairingLinkCreated(result.value);
654 if (dialogSession === pairingDialogSessionRef.current) {
655 handlePairingDialogOpenChange(false);
656 }
657 } else if (!isAtomCommandInterrupted(result)) {
658 const error = squashAtomCommandFailure(result);
659 const message =
660 error instanceof Error
661 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
662 : gt("Failed to create pairing URL.");
663 toastManager.add(
664 stackedThreadToast({
665 type: "error",
666 title: gt("Could not create pairing URL"),
667 description: message,
668 }),
669 );
670 }
671 setIsCreatingPairingLink(false);
672 };
673
674 const togglePairingScope = (scope: AuthGrantScope, checked: boolean) => {
675 setPairingScopes((current) => togglePairingScopeSelection(current, scope, checked));
676 };
677
678 return (
679 <div className="flex flex-wrap items-center justify-end gap-2">
680 <Button size="xs" variant="outline" onClick={() => openUseInAnotherApp(environmentId)}>
681 <PlugIcon className="size-3" />
682 <T>Use in another app (MCP)</T>
683 </Button>
684 <Button
685 size="xs"
686 variant="destructive-outline"
687 disabled={isRevokingOtherClients || !canRevokeOtherClients(clientSessions)}
688 onClick={() => void onRevokeOtherClients()}
689 >
690 {isRevokingOtherClients ? gt("Revoking…") : gt("Revoke others")}
691 </Button>
692 {pairingDenial !== undefined ? (
693 <ManagedControl reason={pairingDenial}>
694 <Button size="xs" variant="default" disabled>
695 <PlusIcon className="size-3" />
696 <T>Create link</T>
697 </Button>
698 </ManagedControl>
699 ) : null}
700 <Dialog
701 open={dialogOpen && pairingDenial === undefined}
702 onOpenChange={handlePairingDialogOpenChange}
703 >
704 {pairingDenial === undefined ? (
705 <DialogTrigger
706 render={
707 <Button size="xs" variant="default">
708 <PlusIcon className="size-3" />
709 <T>Create link</T>
710 </Button>
711 }
712 />
713 ) : null}
714 <DialogPopup className="max-w-md">
715 <DialogHeader>
716 <DialogTitle>
717 <T>Create pairing link</T>
718 </DialogTitle>
719 <DialogDescription>
720 <T>
721 Generate a one-time link that another device can use to pair with this backend as an
722 authorized client.
723 </T>
724 </DialogDescription>
725 </DialogHeader>
726 <DialogPanel>
727 <label className="block">
728 <span className="mb-1.5 block text-xs font-medium text-foreground">
729 <T>Client label (optional)</T>
730 </span>
731 <Input
732 value={pairingLabel}
733 onChange={(event) => setPairingLabel(event.target.value)}
734 placeholder={gt("e.g. Living room iPad")}
735 disabled={isCreatingPairingLink}
736 autoFocus
737 />
738 </label>
739 <section className="space-y-3">
740 <div className="flex items-center justify-between gap-3">
741 <div>
742 <h3 className="text-xs font-medium text-foreground">
743 <T>Permissions</T>
744 </h3>
745 <p className="text-xs text-muted-foreground">
746 <T>Limit what the paired client can do.</T>
747 </p>
748 </div>
749 <div className="flex gap-1">
750 <Button
751 size="xs"
752 variant="outline"
753 disabled={isCreatingPairingLink}
754 onClick={() =>
755 setPairingScopes(
756 [
757 AuthOrchestrationReadScope,
758 AuthFilesystemReadScope,
759 AuthDiagnosticsReadScope,
760 AuthTerminalReadScope,
761 ].filter((scope) => delegatableScopes.includes(scope)),
762 )
763 }
764 >
765 <T>Read only</T>
766 </Button>
767 <Button
768 size="xs"
769 variant="outline"
770 disabled={isCreatingPairingLink}
771 onClick={() =>
772 setPairingScopes(
773 AuthStandardClientScopes.filter((scope) =>
774 delegatableScopes.includes(scope),
775 ),
776 )
777 }
778 >
779 {gt("Standard", { $context: "standard permission preset" })}
780 </Button>
781 </div>
782 </div>
783 <div className="divide-y divide-border/60 rounded-lg border border-input bg-muted/25">
784 {PAIRING_SCOPE_OPTIONS.filter(({ scope }) => delegatableScopes.includes(scope)).map(
785 ({ scope, title, description }) => (
786 <label
787 key={scope}
788 className="flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40"
789 >
790 <Checkbox
791 className="mt-0.5"
792 checked={pairingScopes.includes(scope)}
793 disabled={isCreatingPairingLink}
794 onCheckedChange={(checked) => togglePairingScope(scope, checked === true)}
795 />
796 <span className="min-w-0">
797 <span className="block text-xs font-medium text-foreground">
798 {m(title)}
799 </span>
800 <span className="block text-xs leading-snug text-muted-foreground">
801 {m(description)}
802 </span>
803 {terminalSelected && scope === AuthTerminalOperateScope ? (
804 <span className="block text-xs text-warning">
805 {gt(
806 "Terminal commands can read or change files within the server account’s permissions.",
807 )}
808 </span>
809 ) : null}
810 {relayAdminSelected && scope === AuthRelayConfigureScope ? (
811 <span className="block text-xs text-warning">
812 {gt("This client can change who can issue pairing credentials.")}
813 </span>
814 ) : null}
815 </span>
816 </label>
817 ),
818 )}
819 </div>
820 {selectedScopes.length === 0 ? (
821 <p className="text-xs text-destructive">
822 <T>Select at least one permission.</T>
823 </p>
824 ) : selectedScopes.includes(AuthAccessWriteScope) ? (
825 <p className="text-xs text-warning">
826 <T>This client can create or revoke access for other devices.</T>
827 </p>
828 ) : null}
829 </section>
830 </DialogPanel>
831 <DialogFooter variant="bare">
832 <Button
833 variant="outline"
834 disabled={isCreatingPairingLink}
835 onClick={() => setDialogOpen(false)}
836 >
837 <T>Cancel</T>
838 </Button>
839 <Button
840 disabled={isCreatingPairingLink || selectedScopes.length === 0}
841 onClick={() => void handleCreatePairingLink()}
842 >
843 {isCreatingPairingLink ? gt("Creating…") : gt("Create link")}
844 </Button>
845 </DialogFooter>
846 </DialogPopup>
847 </Dialog>
848 </div>
849 );
850 });
851
852 type PairingClientsListProps = {
853 servedByEnvironment: boolean;
854 endpointUrl: string | null | undefined;
855 endpoints: ReadonlyArray<AdvertisedEndpoint>;
856 defaultEndpointKey: string | null;
857 isLoading: boolean;
858 pairingLinks: ReadonlyArray<ServerPairingLinkRecord>;
859 createdPairingCredentials: ReadonlyMap<string, string>;
860 sharedPairingLinkId: string | null;
861 clientSessions: ReadonlyArray<ServerClientSessionRecord>;
862 revokingPairingLinkId: string | null;
863 revokingClientSessionId: string | null;
864 onRevokePairingLink: (id: string) => void;
865 onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
866 canRevoke: boolean;
867 };
868
869 export const PairingClientsList = memo(function PairingClientsList({
870 servedByEnvironment,
871 endpointUrl,
872 endpoints,
873 defaultEndpointKey,
874 isLoading,
875 pairingLinks,
876 createdPairingCredentials,
877 sharedPairingLinkId,
878 clientSessions,
879 revokingPairingLinkId,
880 revokingClientSessionId,
881 onRevokePairingLink,
882 onRevokeClientSession,
883 canRevoke,
884 }: PairingClientsListProps) {
885 return (
886 <>
887 {pairingLinks.map((pairingLink) => (
888 <PairingLinkListRow
889 key={pairingLink.id}
890 pairingLink={pairingLink}
891 credential={createdPairingCredentials.get(pairingLink.id)}
892 defaultShareOpen={pairingLink.id === sharedPairingLinkId}
893 servedByEnvironment={servedByEnvironment}
894 endpointUrl={endpointUrl}
895 endpoints={endpoints}
896 defaultEndpointKey={defaultEndpointKey}
897 revokingPairingLinkId={revokingPairingLinkId}
898 onRevoke={onRevokePairingLink}
899 canRevoke={canRevoke}
900 />
901 ))}
902
903 {clientSessions.map((clientSession) => (
904 <ConnectedClientListRow
905 key={clientSession.sessionId}
906 clientSession={clientSession}
907 revokingClientSessionId={revokingClientSessionId}
908 onRevokeSession={onRevokeClientSession}
909 canRevoke={canRevoke}
910 />
911 ))}
912
913 {pairingLinks.length === 0 && clientSessions.length === 0 && !isLoading ? (
914 <div className={ITEM_ROW_CLASSNAME}>
915 <p className="text-xs text-muted-foreground/60">
916 <T>No pairing links or client sessions.</T>
917 </p>
918 </div>
919 ) : null}
920 </>
921 );
922 });
923
924 type AdvertisedEndpointListRowProps = {
925 endpoint: AdvertisedEndpoint;
926 isDefault: boolean;
927 onSetDefault: (endpoint: AdvertisedEndpoint) => void;
928 onSetupTailscaleServe: (endpoint: AdvertisedEndpoint) => void;
929 onDisableTailscaleServe: (endpoint: AdvertisedEndpoint) => void;
930 isUpdatingTailscaleServe: boolean;
931 };
932
933 export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({
934 endpoint,
935 isDefault,
936 onSetDefault,
937 onSetupTailscaleServe,
938 onDisableTailscaleServe,
939 isUpdatingTailscaleServe,
940 }: AdvertisedEndpointListRowProps) {
941 const gt = useGT();
942 const isAvailable = endpoint.status === "available";
943 const needsTailscaleSetup = isTailscaleHttpsEndpoint(endpoint) && endpoint.status !== "available";
944 const canDisableTailscaleServe =
945 isTailscaleHttpsEndpoint(endpoint) && endpoint.status === "available";
946 const shouldShowEndpointUrl = !needsTailscaleSetup;
947 const m = useMessages();
948 const remoteDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients", m);
949 return (
950 <div className={endpointRowClassName(isAvailable)}>
951 {isDefault ? (
952 <span className="absolute inset-y-2 left-0 w-1 rounded-r-full bg-primary" aria-hidden />
953 ) : null}
954 <div className="flex min-h-7 min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
955 <div className="flex min-h-7 min-w-0 flex-1 items-center gap-3">
956 <h3 className="shrink-0 text-sm leading-5 font-medium text-foreground">
957 {endpoint.label}
958 </h3>
959 {shouldShowEndpointUrl ? (
960 <Tooltip>
961 <TooltipTrigger
962 render={
963 <p className="min-w-0 truncate text-xs leading-5 text-muted-foreground">
964 {endpoint.httpBaseUrl}
965 </p>
966 }
967 />
968 <TooltipPopup side="top">{endpoint.httpBaseUrl}</TooltipPopup>
969 </Tooltip>
970 ) : null}
971 {!isAvailable ? (
972 <span className="inline-flex h-6 shrink-0 items-center rounded-md border border-border/70 px-1.5 text-3xs text-muted-foreground">
973 <T>Setup required</T>
974 </span>
975 ) : null}
976 </div>
977 <div className="ml-auto flex min-h-7 shrink-0 items-center justify-end gap-2">
978 {isDefault ? (
979 <span className="inline-flex h-6 items-center rounded-md border border-primary/30 bg-primary/10 px-1.5 text-3xs text-primary">
980 {gt("Default", { $context: "default endpoint badge" })}
981 </span>
982 ) : null}
983 {needsTailscaleSetup ? (
984 <ManagedControl reason={remoteDenial}>
985 <Button
986 size="xs"
987 variant="outline"
988 onClick={() => onSetupTailscaleServe(endpoint)}
989 disabled={isUpdatingTailscaleServe || remoteDenial !== undefined}
990 >
991 {isUpdatingTailscaleServe ? gt("Restarting…") : gt("Setup", { $context: "verb" })}
992 </Button>
993 </ManagedControl>
994 ) : null}
995 {canDisableTailscaleServe ? (
996 <Button
997 size="xs"
998 variant="destructive-outline"
999 onClick={() => onDisableTailscaleServe(endpoint)}
1000 disabled={isUpdatingTailscaleServe}
1001 >
1002 {isUpdatingTailscaleServe ? gt("Restarting…") : gt("Disable")}
1003 </Button>
1004 ) : null}
1005 {!needsTailscaleSetup && !isDefault ? (
1006 <Button size="xs" variant="outline" onClick={() => onSetDefault(endpoint)}>
1007 <T>Set as default</T>
1008 </Button>
1009 ) : null}
1010 </div>
1011 </div>
1012 </div>
1013 );
1014 });
1015
1016 export function NetworkAccessDescription({
1017 endpoint,
1018 hiddenEndpointCount,
1019 expanded,
1020 onToggleExpanded,
1021 fallback,
1022 }: {
1023 endpoint: AdvertisedEndpoint | null;
1024 hiddenEndpointCount: number;
1025 expanded: boolean;
1026 onToggleExpanded: () => void;
1027 fallback: ReactNode;
1028 }) {
1029 const gt = useGT();
1030 if (!endpoint) {
1031 return fallback;
1032 }
1033
1034 const summary = (
1035 <>
1036 <span className="min-w-0 truncate">{endpoint.httpBaseUrl}</span>
1037 {hiddenEndpointCount > 0 ? (
1038 <span className="shrink-0 text-xs font-medium">
1039 {expanded ? gt("Hide") : `+${hiddenEndpointCount}`}
1040 </span>
1041 ) : null}
1042 </>
1043 );
1044
1045 return (
1046 <span className="inline-flex min-w-0 max-w-full items-baseline gap-1">
1047 <span className="shrink-0">
1048 <T>Reachable at</T>
1049 </span>
1050 {hiddenEndpointCount > 0 ? (
1051 <button
1052 type="button"
1053 className="inline-flex min-w-0 max-w-full items-baseline gap-2 border-b border-dotted border-muted-foreground/60 text-left text-muted-foreground underline-offset-4 hover:border-foreground hover:text-foreground"
1054 onClick={onToggleExpanded}
1055 aria-expanded={expanded}
1056 >
1057 {summary}
1058 </button>
1059 ) : (
1060 <span className="inline-flex min-w-0 max-w-full items-baseline gap-2">{summary}</span>
1061 )}
1062 </span>
1063 );
1064 }