Open History to see the last commit
1import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
2import { SessionPermissions } from "./SessionPermissions";
3import {
4 ChevronRightIcon,
5 ChevronsLeftRightEllipsisIcon,
6 EllipsisIcon,
7 PencilIcon,
8 RouteIcon,
9} from "lucide-react";
10import { useAtomValue } from "@effect/atom-react";
11import { useEffect, useEffectEvent, useState } from "react";
12import {
13 AuthRelayWriteScope,
14 type EnvironmentId,
15 connectReachabilityHelpUrl,
16 formatConnectReachable,
17 resolveEnvironmentMachineKind,
18} from "@t3tools/contracts";
19import {
20 connectionRoutes,
21 hasSavedBearerRoute,
22 connectionErrorText,
23 connectionStatusText,
24 environmentMcpUrl,
25 localEnvironmentMcpUrl,
26 type ConnectionCatalogEntry,
27} from "@t3tools/client-runtime/connection";
28import * as Option from "effect/Option";
29import { msg, T, useGT, useMessages, plural, part } from "gt-react";
30import { m, type MessageResolver } from "../../i18n/messages";
31
32import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
33import { cn } from "../../lib/utils";
34import { SettingsRow } from "./settingsLayout";
35import { useSearchableSetting } from "./settingsSearch";
36import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
37import { EnvironmentRoutesList } from "./EnvironmentRoutesList";
38import { RenameEnvironmentDialog } from "./RenameEnvironmentDialog";
39import {
40 ConnectionDiagnosisPanel,
41 ConnectionDiagnosisSummary,
42 useConnectionDiagnosis,
43} from "./ConnectionDiagnosisDetails";
44import { usePreparedConnection } from "~/state/session";
45import { EnvironmentRow, environmentTransportLabel } from "./EnvironmentRow";
46import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu";
47import { Switch } from "../ui/switch";
48import { stackedThreadToast, toastManager } from "../ui/toast";
49import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
50import { SharedTooltipTrigger } from "../ui/shared-tooltip";
51import { Button, InlineButton } from "../ui/button";
52import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
53import {
54 resolveServerConfigVersionMismatch,
55 resolveServerSelfUpdateCapability,
56 supportsDesktopAppUpdate,
57} from "~/versionSkew";
58import { hasCloudPublicConfig } from "~/cloud/publicConfig";
59import { useT3ConnectTurnOn } from "~/cloud/useT3ConnectTurnOn";
60import { useCloudLinkController } from "~/cloud/useCloudLinkController";
61import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState";
62import { t3ConnectMcpUrl } from "~/cloud/t3ConnectState";
63import { useManagedTunnelUsage } from "~/cloud/managedRelayState";
64import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages";
65import { TunnelLimitAlert, TunnelUsageMeter, TunnelUsageMeterSkeleton } from "../cloud/TunnelUsage";
66import { environmentCatalog } from "~/connection/catalog";
67import { isLoopbackHostname } from "~/environments/primary/target";
68import { readEnvironmentScope } from "~/state/session";
69import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
70import { APP_VERSION } from "~/branding";
71import { useManagedPolicy } from "~/state/managedPolicy";
72import { useAtomCommand } from "../../state/use-atom-command";
73import { useUpdateEnvironmentSettings } from "~/hooks/useSettings";
74import { serverEnvironment } from "~/state/server";
75import {
76 OutdatedServerUpdateAction,
77 ServerUpdateAction,
78 ServerUpdateProgress,
79} from "../ServerUpdateAction";
80import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
81import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
82
83type SavedBackendListRowProps = {
84 environment: EnvironmentPresentation;
85 removingEnvironmentId: EnvironmentId | null;
86 onSetEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
87 onRemove: (environment: EnvironmentPresentation) => void;
88 onAddRoute: (environment: EnvironmentPresentation) => void;
89 /** The map's details open on a machine's routes; the list keeps them folded. */
90 initialRoutesOpen?: boolean;
91};
92
93export function savedBackendStatus(
94 environment: EnvironmentPresentation,
95 resolve: MessageResolver = m,
96): {
97 readonly text: string;
98 readonly tone: "muted" | "error";
99} {
100 if (!environment.entry.enabled && environment.connection.phase !== "unsupported")
101 return { text: resolve(msg({ context: "environment switched off" })`Off`), tone: "muted" };
102 const { connection } = environment;
103 const error = connectionErrorText(connection, resolve);
104 switch (connection.phase) {
105 case "connected":
106 return { text: resolve(msg("Connected")), tone: "muted" };
107 case "connecting":
108 return { text: resolve(msg("Connecting")), tone: "muted" };
109 case "reconnecting":
110 if (connection.awaitingApproval) {
111 return { text: error ?? resolve(msg("Waiting for approval")), tone: "muted" };
112 }
113 return {
114 text: error ? resolve(msg`Reconnecting: ${{ error }}`) : resolve(msg("Reconnecting")),
115 tone: "error",
116 };
117 case "unsupported":
118 return { text: resolve(msg("Client not supported")), tone: "muted" };
119 case "error":
120 return {
121 text: error
122 ? resolve(msg`Connection failed: ${{ error }}`)
123 : resolve(msg("Connection failed")),
124 tone: "error",
125 };
126 case "offline":
127 return { text: resolve(msg("Offline")), tone: "muted" };
128 case "available":
129 return { text: resolve(msg("Not connected")), tone: "muted" };
130 }
131}
132
133function useCopyMcpUrl() {
134 const gt = useGT();
135 return useCopyToClipboard<{ url: string }>({
136 target: {
137 target: "MCP URL",
138 unavailableMessage: msg("Clipboard API is unavailable while copying MCP URL."),
139 failureMessage: msg("Failed to copy MCP URL to the clipboard."),
140 },
141 onCopy: ({ url }) => {
142 toastManager.add({
143 type: "success",
144 title: gt`MCP URL copied`,
145 description: gt`Add it to an agent, e.g. claude mcp add --transport http t3 ${{ url }}`,
146 });
147 },
148 onError: (error) => {
149 toastManager.add(
150 stackedThreadToast({
151 type: "error",
152 title: gt`Could not copy MCP URL`,
153 description: error.message,
154 }),
155 );
156 },
157 });
158}
159
160export function SavedBackendListRow({
161 environment,
162 removingEnvironmentId,
163 onSetEnabled,
164 onRemove,
165 onAddRoute,
166 initialRoutesOpen = false,
167}: SavedBackendListRowProps) {
168 const messages = useMessages();
169 const gt = useGT();
170 const [routesOpen, setRoutesOpen] = useState(initialRoutesOpen);
171 const [permissionsOpen, setPermissionsOpen] = useState(false);
172 const [diagnosisOpen, setDiagnosisOpen] = useState(false);
173 const [renameOpen, setRenameOpen] = useState(false);
174 const environmentId = environment.environmentId;
175 const unsupported = environment.connection.phase === "unsupported";
176 const blocked = unsupported && !hasSavedBearerRoute(environment.entry);
177 const enabled = environment.entry.enabled && !unsupported;
178 const isConnected = environment.connection.phase === "connected";
179 const isRemoving = removingEnvironmentId === environmentId;
180 const errorTraceId = environment.connection.traceId;
181 const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
182 target: {
183 target: "trace ID",
184 unavailableMessage: msg("Clipboard API is unavailable while copying trace ID."),
185 failureMessage: msg("Failed to copy trace ID to the clipboard."),
186 },
187 onError: (error) => {
188 toastManager.add(
189 stackedThreadToast({
190 type: "error",
191 title: gt`Could not copy trace ID`,
192 description: error.message,
193 }),
194 );
195 },
196 });
197 const copyTraceId = (traceId: string) => {
198 copyTraceIdToClipboard(traceId, { traceId });
199 };
200 const { copyToClipboard: copyMcpUrl } = useCopyMcpUrl();
201 const versionMismatch = resolveServerConfigVersionMismatch(environment.serverConfig, messages);
202 const serverUpdateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
203 const resumingServerUpdate =
204 serverUpdateState.status === "running" && serverUpdateState.stage === "resuming";
205 const status = savedBackendStatus(environment, messages);
206 const serverVersion = environment.serverConfig?.environment.serverVersion ?? null;
207 // Discovery empties its map on every refresh, so hold the last descriptor
208 // seen or the glyph would blink back to the generic one each time.
209 const relayDiscovery = useRelayEnvironmentDiscovery();
210 const discoveredDescriptor = Option.getOrNull(
211 relayDiscovery.environments.get(environmentId)?.status ?? Option.none(),
212 )?.descriptor;
213 const [lastDescriptor, setLastDescriptor] = useState(discoveredDescriptor);
214 if (discoveredDescriptor !== undefined && discoveredDescriptor !== lastDescriptor) {
215 setLastDescriptor(discoveredDescriptor);
216 }
217 const discoveredRelayHttpBaseUrl =
218 relayDiscovery.environments.get(environmentId)?.environment.endpoint.httpBaseUrl;
219 const [lastRelayHttpBaseUrl, setLastRelayHttpBaseUrl] = useState(discoveredRelayHttpBaseUrl);
220 if (
221 discoveredRelayHttpBaseUrl !== undefined &&
222 discoveredRelayHttpBaseUrl !== lastRelayHttpBaseUrl
223 ) {
224 setLastRelayHttpBaseUrl(discoveredRelayHttpBaseUrl);
225 }
226 const retryNow = useAtomCommand(environmentCatalog.retryNow);
227 const {
228 diagnosis: currentDiagnosis,
229 state: connectionState,
230 relayOnly,
231 } = useConnectionDiagnosis(environment);
232 const diagnosis = resumingServerUpdate ? null : currentDiagnosis;
233 const prepared = usePreparedConnection(environmentId);
234 const connectedTarget = isConnected && prepared._tag === "Some" ? prepared.value.target : null;
235 const mcpUrl = environmentMcpUrl({
236 entry: environment.entry,
237 relayHttpBaseUrl: discoveredRelayHttpBaseUrl ?? lastRelayHttpBaseUrl,
238 connectedTarget,
239 });
240 const machineKind = resolveEnvironmentMachineKind(
241 environment.serverConfig ??
242 (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
243 );
244 const routeCount = connectionRoutes(environment.entry).length;
245 const subtitleText = [
246 environmentTransportLabel(environment, connectedTarget, messages),
247 // The headline below names the failure in full.
248 diagnosis ? null : resumingServerUpdate ? gt`Restarting` : status.text,
249 enabled && versionMismatch ? serverVersion : null,
250 ]
251 .filter((value): value is string => value !== null)
252 .join(" · ");
253
254 const showUpdateAction =
255 enabled &&
256 isConnected &&
257 versionMismatch !== null &&
258 (serverUpdateState.status === "idle" || serverUpdateState.status === "failed");
259
260 const statusTooltip = `${
261 unsupported
262 ? (connectionErrorText(environment.connection, messages) ??
263 connectionStatusText(environment.connection, messages))
264 : enabled
265 ? connectionStatusText(environment.connection, messages)
266 : gt`Switched off`
267 }${
268 versionMismatch
269 ? `\n${gt`Update available: ${{ serverVersion: versionMismatch.serverVersion }} → ${{ clientVersion: versionMismatch.clientVersion }}`}`
270 : ""
271 }`;
272
273 return (
274 <EnvironmentRow
275 kind={machineKind}
276 label={environment.label}
277 dimmed={!enabled}
278 subtitle={
279 <span className="flex min-w-0 items-center gap-1">
280 <Tooltip>
281 {/* The status can change while the tooltip is open, and base-ui only
282 re-measures the popup when the trigger's payload changes. */}
283 <TooltipTrigger
284 payload={statusTooltip}
285 render={
286 <span
287 className={cn(
288 "min-w-0 truncate",
289 enabled &&
290 status.tone === "error" &&
291 !resumingServerUpdate &&
292 !diagnosis &&
293 "text-destructive",
294 )}
295 />
296 }
297 >
298 {subtitleText}
299 </TooltipTrigger>
300 <TooltipPopup side="top" className="whitespace-pre-wrap">
301 {statusTooltip}
302 </TooltipPopup>
303 </Tooltip>
304 <span aria-hidden className="shrink-0">
305 ·
306 </span>
307 <button
308 type="button"
309 aria-expanded={routesOpen}
310 onClick={() => setRoutesOpen((open) => !open)}
311 className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
312 >
313 {routeCount === 1
314 ? gt`Routes`
315 : gt`${plural(
316 { count: routeCount },
317 {
318 one: part`${{ count: routeCount }} route`,
319 other: part`${{ count: routeCount }} routes`,
320 },
321 )}`}
322 <ChevronRightIcon
323 aria-hidden
324 className={cn(
325 "size-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none",
326 routesOpen && "rotate-90",
327 )}
328 />
329 </button>
330 <span aria-hidden className="shrink-0">
331 ·
332 </span>
333 <button
334 type="button"
335 aria-expanded={permissionsOpen}
336 aria-controls={`remote-permissions-${environmentId}`}
337 onClick={() => setPermissionsOpen((open) => !open)}
338 className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
339 >
340 <T>Permissions</T>
341 <ChevronRightIcon
342 aria-hidden
343 className={cn(
344 "size-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none",
345 permissionsOpen && "rotate-90",
346 )}
347 />
348 </button>
349 </span>
350 }
351 below={
352 <>
353 {diagnosis ? (
354 <ConnectionDiagnosisSummary
355 diagnosis={diagnosis}
356 retryAt={connectionState.phase === "backoff" ? connectionState.retryAt : null}
357 attempt={connectionState.attempt}
358 expanded={diagnosisOpen}
359 onToggle={() => setDiagnosisOpen((open) => !open)}
360 />
361 ) : null}
362 {serverUpdateState.status !== "idle" ? (
363 <div className="mt-1 max-w-md">
364 <ServerUpdateProgress state={serverUpdateState} />
365 </div>
366 ) : null}
367 </>
368 }
369 detail={
370 <>
371 {diagnosis && diagnosisOpen ? (
372 <ConnectionDiagnosisPanel
373 hostLabel={environment.label}
374 diagnosis={diagnosis}
375 onRetry={() => void retryNow(environmentId)}
376 onAddRoute={relayOnly ? () => onAddRoute(environment) : null}
377 />
378 ) : null}
379 {routesOpen && (
380 <EnvironmentRoutesList
381 environment={environment}
382 onAddRoute={() => onAddRoute(environment)}
383 />
384 )}
385 {permissionsOpen && (
386 <div
387 id={`remote-permissions-${environmentId}`}
388 className="mt-2 border-t border-border/50"
389 >
390 <SessionPermissions
391 environmentId={environmentId}
392 connected={isConnected}
393 routeContext
394 />
395 </div>
396 )}
397 </>
398 }
399 >
400 {unsupported &&
401 environment.entry.serverUpdateRequired === true &&
402 serverUpdateState.status !== "running" ? (
403 <OutdatedServerUpdateAction
404 environmentId={environmentId}
405 serverLabel={gt({
406 context: "names a T3 server inside sentences such as {serverLabel} updated",
407 })`${{ label: environment.label }} server`}
408 fromVersion={lastDescriptor?.serverVersion}
409 targetVersion={APP_VERSION}
410 label={serverUpdateState.status === "failed" ? gt`Retry update` : gt`Update`}
411 />
412 ) : null}
413 {showUpdateAction ? (
414 <ServerUpdateAction
415 environmentId={environmentId}
416 serverLabel={gt({
417 context: "names a T3 server inside sentences such as {serverLabel} updated",
418 })`${{ label: environment.label }} server`}
419 selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
420 installation={environment.serverConfig?.environment.capabilities.serverInstallation}
421 desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)}
422 targetVersion={versionMismatch.clientVersion}
423 label={serverUpdateState.status === "failed" ? gt`Retry update` : gt`Update`}
424 appearance="icon"
425 />
426 ) : null}
427 <SharedTooltipTrigger
428 render={
429 <Switch
430 size="sm"
431 checked={enabled}
432 disabled={isRemoving || blocked}
433 aria-label={
434 enabled
435 ? gt`Switch off ${{ label: environment.label }}`
436 : gt`Switch on ${{ label: environment.label }}`
437 }
438 onCheckedChange={(checked) => onSetEnabled(environmentId, checked)}
439 />
440 }
441 label={blocked ? gt`Client not supported` : enabled ? gt`Switch off` : gt`Switch on`}
442 />
443 <Menu>
444 <MenuTrigger
445 render={
446 <Button
447 type="button"
448 variant="ghost-muted"
449 size="icon-xs"
450 disabled={isRemoving}
451 aria-label={gt`More actions for ${{ label: environment.label }}`}
452 />
453 }
454 >
455 <EllipsisIcon className="size-3.5" />
456 </MenuTrigger>
457 <MenuPopup align="end">
458 <EnvironmentIconMenu
459 environmentId={environmentId}
460 serverConfig={environment.serverConfig}
461 />
462 {environment.relayManaged ? null : (
463 <MenuItem onClick={() => setRenameOpen(true)}>
464 <PencilIcon />
465 <T>Rename…</T>
466 </MenuItem>
467 )}
468 <MenuItem onClick={() => setRoutesOpen((open) => !open)}>
469 <RouteIcon />
470 {routesOpen ? gt`Hide routes` : gt`Routes`}
471 </MenuItem>
472 {mcpUrl ? (
473 <MenuItem onClick={() => copyMcpUrl(mcpUrl, { url: mcpUrl })}>
474 <T>Copy MCP URL</T>
475 </MenuItem>
476 ) : null}
477 {errorTraceId ? (
478 <MenuItem onClick={() => copyTraceId(errorTraceId)}>
479 <T>Copy trace ID</T>
480 </MenuItem>
481 ) : null}
482 <MenuSeparator />
483 <MenuItem variant="destructive" onClick={() => onRemove(environment)}>
484 {isRemoving ? gt`Removing…` : gt`Remove from this device…`}
485 </MenuItem>
486 </MenuPopup>
487 </Menu>
488 <RenameEnvironmentDialog
489 open={renameOpen}
490 onOpenChange={setRenameOpen}
491 environmentId={environmentId}
492 label={environment.label}
493 />
494 </EnvironmentRow>
495 );
496}
497
498/** Copying the host's own MCP address, for hosted agents or agents on this machine. */
499export function LocalEnvironmentMcpUrlRow({ entry }: { readonly entry: ConnectionCatalogEntry }) {
500 const cloudLink = usePrimaryCloudLinkState();
501 const setting = useSearchableSetting();
502 const gt = useGT();
503 const { copyToClipboard: copyMcpUrl } = useCopyMcpUrl();
504 const tunnelMcpUrl = t3ConnectMcpUrl({
505 thisMachine: true,
506 tunnelHostname: cloudLink.data?.tunnelHostname,
507 relayEndpoint: undefined,
508 });
509 const mcpUrl = tunnelMcpUrl ?? localEnvironmentMcpUrl({ entry });
510 if (mcpUrl === null) return null;
511 const tunnelAvailable = tunnelMcpUrl !== null;
512 const tunnelReachability = tunnelAvailable ? cloudLink.data?.reachability : undefined;
513 const loopback = isLoopbackHostname(new URL(mcpUrl).hostname);
514 return (
515 <SettingsRow
516 {...setting("mcp-url")}
517 description={
518 tunnelReachability?.status === "reachable"
519 ? gt`Tunnel connected. Give this URL to a hosted agent, such as ChatGPT: ${{ url: mcpUrl }}`
520 : tunnelReachability?.status === "unreachable"
521 ? gt`T3 Connect is unreachable right now, so a hosted agent can use this URL after the tunnel recovers: ${{ url: mcpUrl }}`
522 : tunnelAvailable
523 ? gt`Give this URL to a hosted agent, such as ChatGPT: ${{ url: mcpUrl }}`
524 : loopback
525 ? gt`Give this URL to an agent running on this machine: ${{ url: mcpUrl }}`
526 : gt`Give this URL to an agent that can reach this environment: ${{ url: mcpUrl }}`
527 }
528 control={
529 <Button size="sm" variant="outline" onClick={() => copyMcpUrl(mcpUrl, { url: mcpUrl })}>
530 <T>Copy</T>
531 </Button>
532 }
533 />
534 );
535}
536
537function CloudLinkSwitch({
538 checked,
539 disabled,
540 disabledReason,
541 onCheckedChange,
542 ariaLabel,
543}: {
544 readonly checked: boolean;
545 readonly disabled: boolean;
546 readonly disabledReason: string | null;
547 readonly onCheckedChange?: (enabled: boolean) => void;
548 readonly ariaLabel?: string;
549}) {
550 const gt = useGT();
551 const control = (
552 <Switch
553 aria-label={ariaLabel ?? gt`Enable T3 Connect`}
554 checked={checked}
555 disabled={disabled}
556 {...(onCheckedChange ? { onCheckedChange } : {})}
557 />
558 );
559 return disabledReason ? (
560 <SharedTooltipTrigger
561 render={<span className="inline-flex">{control}</span>}
562 label={disabledReason}
563 />
564 ) : (
565 control
566 );
567}
568
569/** Tunnel meter, plus the upgrade prompt after the relay refuses a tunnel at the cap. */
570function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number | null }) {
571 const usage = useManagedTunnelUsage();
572 const accountPage = useT3ConnectAccountPage();
573 const openAccountPage = accountPage.open;
574 // Usage when the relay refused. The relay also counts tunnels still being set up, so only
575 // a freed tunnel or a higher cap clears the alert, not a meter that merely shows room.
576 const [usedAtRefusal, setUsedAtRefusal] = useState<number | null>(null);
577 if (tunnelLimit === null) {
578 if (usedAtRefusal !== null) setUsedAtRefusal(null);
579 } else if (usedAtRefusal === null && usage.used !== null) {
580 setUsedAtRefusal(usage.used);
581 }
582 const showLimitAlert =
583 tunnelLimit !== null &&
584 !(usedAtRefusal !== null && usage.used !== null && usage.used < usedAtRefusal) &&
585 !(usage.limit !== null && usage.limit > tunnelLimit);
586 const meter =
587 usage.used !== null && usage.limit !== null ? (
588 <TunnelUsageMeter
589 used={usage.used}
590 limit={usage.limit}
591 action={
592 // At the cap the alert below carries the same actions.
593 !openAccountPage || showLimitAlert ? null : usage.upgrade ? (
594 <InlineButton onClick={() => openAccountPage("t3-chat")}>
595 <T>Get more tunnels</T>
596 </InlineButton>
597 ) : usage.used >= usage.limit ? (
598 <InlineButton onClick={() => openAccountPage("t3-connect")}>
599 <T>Manage tunnels</T>
600 </InlineButton>
601 ) : null
602 }
603 />
604 ) : usage.loading ? (
605 <TunnelUsageMeterSkeleton />
606 ) : null;
607 return (
608 <>
609 {meter || showLimitAlert ? (
610 <div className="flex flex-col gap-3 pb-3">
611 {meter}
612 {showLimitAlert ? (
613 <TunnelLimitAlert
614 upgrade={usage.upgrade}
615 onLinkT3Chat={openAccountPage ? () => openAccountPage("t3-chat") : null}
616 onManageTunnels={openAccountPage ? () => openAccountPage("t3-connect") : null}
617 />
618 ) : null}
619 </div>
620 ) : null}
621 {/* Kept outside the conditional so an open account page does not remount. */}
622 {accountPage.portals}
623 </>
624 );
625}
626
627function ConfiguredCloudLinkRow({
628 environmentId,
629 canManageRelay,
630 connectDeviceApproval,
631}: {
632 readonly environmentId: EnvironmentId;
633 readonly canManageRelay: boolean;
634 readonly connectDeviceApproval: ConnectDeviceApprovalControl | null;
635}) {
636 const setting = useSearchableSetting();
637 const gt = useGT();
638 const updateEnvironmentSettings = useUpdateEnvironmentSettings(environmentId);
639 const {
640 isSignedIn,
641 linkState: cloudLinkState,
642 linkRevoked,
643 managedTunnelActive,
644 managedTunnelOutOfSync,
645 publishAgentActivity,
646 holdWebhooksWhileOffline,
647 operationError,
648 tunnelLimit,
649 needsRelayConfiguration,
650 reconcileCloudState,
651 } = useCloudLinkController(environmentId);
652 const { openAuthPrompt } = useT3ConnectAuthPrompt();
653 // The server unlinks and refuses relay changes under such a policy; unlinking stays possible.
654 const messages = useMessages();
655 const connectDenial = managedCapabilityDenial(
656 useManagedPolicy(environmentId),
657 "connect",
658 messages,
659 );
660 const turnOn = useT3ConnectTurnOn(environmentId);
661 // Turning on needs relay configuration permission; turning off works from anywhere.
662 const showSwitch = turnOn.kind !== "on-host" || managedTunnelActive;
663 const [isUpdating, setIsUpdating] = useState(false);
664 const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
665
666 const disabledReason = canManageRelay
667 ? null
668 : gt`Your session does not have permission to manage T3 Connect access.`;
669 const isBusy = isUpdating || isUpdatingPreference;
670 const switchDisabled =
671 !canManageRelay ||
672 !isSignedIn ||
673 cloudLinkState.data === null ||
674 cloudLinkState.isPending ||
675 isBusy;
676 const configureReason = gt`This connection needs the relay configuration permission to configure T3 Connect.`;
677 const tunnelNeedsConfigure = needsRelayConfiguration({
678 managedTunnel: !managedTunnelActive,
679 publish: publishAgentActivity,
680 });
681 const publishNeedsConfigure = needsRelayConfiguration({
682 managedTunnel: managedTunnelActive,
683 publish: !publishAgentActivity,
684 });
685 // `isSignedIn` is undefined until Clerk loads. Signed out, one row shows a
686 // sign-in button instead of its switch; the onboarding dialog that opens after
687 // a fresh sign-in offers both linking and publishing.
688 const signedOut = isSignedIn === false;
689 const signInButton = (
690 <Button size="sm" variant="outline" onClick={openAuthPrompt}>
691 <T>Sign in</T>
692 </Button>
693 );
694 const refreshLinkState = useEffectEvent(cloudLinkState.refresh);
695 // The onboarding dialog keeps this atom mounted from app start, so its revalidate-on-mount never
696 // fires for this row. Refresh on open, but leave a read that is still running to answer.
697 const refreshOnOpen = useEffectEvent(() => {
698 if (!cloudLinkState.isPending) cloudLinkState.refresh();
699 });
700 // The server rechecks reachability when the tunnel's 30 s readiness poll changes.
701 // Poll while mounted, so a failed read does not stop later ones.
702 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the cloud link state on open and every 30 s while mounted
703 useEffect(() => {
704 refreshOnOpen();
705 const interval = window.setInterval(() => refreshLinkState(), 30_000);
706 return () => window.clearInterval(interval);
707 }, []);
708 const reachability = managedTunnelActive ? cloudLinkState.data?.reachability : undefined;
709 const reachabilityStatus =
710 reachability?.status === "reachable" ? (
711 formatConnectReachable(reachability)
712 ) : reachability?.status === "unreachable" ? (
713 <span className="block text-destructive">
714 {[reachability.reason, reachability.hint, gt`Fix: ${{ fix: reachability.fix }}`]
715 .filter(Boolean)
716 .join(" ")}{" "}
717 <a
718 href={connectReachabilityHelpUrl(reachability.cause)}
719 target="_blank"
720 rel="noreferrer"
721 className="underline underline-offset-2"
722 >
723 <T>More info</T>
724 </a>
725 </span>
726 ) : null;
727
728 const updateManagedTunnel = async (enabled: boolean) => {
729 if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;
730 setIsUpdating(true);
731 const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
732 if (ok) {
733 toastManager.add({
734 type: "success",
735 title: enabled
736 ? gt`T3 Connect linked`
737 : publishAgentActivity
738 ? gt`T3 Connect tunnel disabled`
739 : gt`T3 Connect unlinked`,
740 description: enabled
741 ? gt`This environment is available through T3 Connect.`
742 : publishAgentActivity
743 ? gt`The managed tunnel was removed. Agent activity publishing stays on.`
744 : gt`This environment is no longer available through T3 Connect.`,
745 });
746 }
747 setIsUpdating(false);
748 };
749
750 const updatePublishAgentActivity = async (enabled: boolean) => {
751 if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;
752 setIsUpdatingPreference(true);
753 const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });
754 if (ok) {
755 toastManager.add({
756 type: "success",
757 title: enabled ? gt`Agent activity enabled` : gt`Agent activity disabled`,
758 description: enabled
759 ? gt`This environment publishes agent activity to your mobile clients.`
760 : gt`This environment will stop publishing agent activity.`,
761 });
762 }
763 setIsUpdatingPreference(false);
764 };
765
766 const updateHoldWebhooks = async (enabled: boolean) => {
767 setIsUpdatingPreference(true);
768 const ok = await reconcileCloudState({
769 managedTunnel: managedTunnelActive,
770 publish: publishAgentActivity,
771 holdWebhooksWhileOffline: enabled,
772 });
773 if (ok) {
774 toastManager.add({
775 type: "success",
776 title: enabled ? gt`Webhooks held while offline` : gt`Webhooks no longer held`,
777 description: enabled
778 ? gt`T3 Connect keeps webhook requests for up to 24 hours while this environment is offline.`
779 : gt`Requests to an offline environment now fail. Anything already held is still delivered.`,
780 });
781 }
782 setIsUpdatingPreference(false);
783 };
784
785 return (
786 <>
787 {showSwitch ? (
788 <SettingsRow
789 title={setting("t3-connect").title}
790 description={
791 connectDenial !== undefined && !managedTunnelActive
792 ? connectDenial
793 : signedOut
794 ? gt`Sign in to make this environment available to your other devices through T3 Connect.`
795 : linkRevoked
796 ? gt`This environment was removed from T3 Connect. Turn it on to link it again.`
797 : managedTunnelActive
798 ? reachability?.status === "unreachable"
799 ? gt`T3 Connect is on, but other devices cannot reach this environment.`
800 : reachability?.status === "reachable"
801 ? gt`This environment is available to your other devices through T3 Connect.`
802 : gt`T3 Connect is on. Reachability has not been checked yet.`
803 : managedTunnelOutOfSync
804 ? gt`T3 Connect is out of sync. This environment is linked only to publish agent activity, so other devices cannot connect. Turn T3 Connect on to repair it.`
805 : gt`Make this environment available to your other devices through T3 Connect.`
806 }
807 status={operationError ?? cloudLinkState.error ?? reachabilityStatus}
808 managed={managedTunnelActive ? undefined : connectDenial}
809 control={
810 signedOut ? (
811 signInButton
812 ) : (
813 <CloudLinkSwitch
814 checked={managedTunnelActive}
815 disabled={switchDisabled || tunnelNeedsConfigure}
816 disabledReason={disabledReason ?? (tunnelNeedsConfigure ? configureReason : null)}
817 onCheckedChange={(enabled) => void updateManagedTunnel(enabled)}
818 />
819 )
820 }
821 >
822 {signedOut || connectDenial !== undefined ? null : (
823 <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />
824 )}
825 </SettingsRow>
826 ) : linkRevoked ? (
827 <SettingsRow
828 title={setting("t3-connect").title}
829 description={gt`This environment was removed from T3 Connect. Run \`t3 connect link\` on the host to link it again.`}
830 />
831 ) : (
832 <SettingsRow
833 title={setting("t3-connect").title}
834 description={gt`Run \`t3 connect link\` on the host, then restart T3 Code there.`}
835 />
836 )}
837 {signedOut && showSwitch ? null : (
838 <SettingsRow
839 title={setting("publish-agent-activity").title}
840 description={
841 signedOut
842 ? gt`Sign in to send activity to mobile notifications and Live Activities.`
843 : gt`Send activity to mobile notifications and Live Activities without T3 Connect.`
844 }
845 managed={connectDenial}
846 control={
847 signedOut ? (
848 signInButton
849 ) : (
850 <CloudLinkSwitch
851 ariaLabel={gt`Publish agent activity to mobile clients`}
852 checked={publishAgentActivity}
853 disabled={switchDisabled || publishNeedsConfigure}
854 disabledReason={disabledReason ?? (publishNeedsConfigure ? configureReason : null)}
855 onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
856 />
857 )
858 }
859 />
860 )}
861 {managedTunnelActive && !signedOut ? (
862 <SettingsRow
863 title={setting("hold-webhooks-while-offline").title}
864 description={gt`Keep webhook requests for up to 24 hours while this environment is offline, then deliver them. Off: T3 Connect only forwards requests and stores nothing.`}
865 managed={connectDenial}
866 control={
867 <CloudLinkSwitch
868 ariaLabel={gt`Hold webhook requests while this environment is offline`}
869 checked={holdWebhooksWhileOffline}
870 disabled={switchDisabled}
871 disabledReason={disabledReason}
872 onCheckedChange={(enabled) => void updateHoldWebhooks(enabled)}
873 />
874 }
875 />
876 ) : null}
877 {managedTunnelActive && connectDeviceApproval ? (
878 <SettingsRow
879 title={setting("connect-device-approval").title}
880 description={gt`Devices that sign in to your T3 Connect account wait until someone already connected here approves them.`}
881 managed={connectDenial}
882 control={
883 <CloudLinkSwitch
884 ariaLabel={gt`Require approval for new T3 Connect devices`}
885 checked={connectDeviceApproval.required}
886 disabled={!connectDeviceApproval.canManage}
887 disabledReason={
888 connectDeviceApproval.canManage
889 ? null
890 : gt`Your session does not have permission to manage access.`
891 }
892 onCheckedChange={(enabled) =>
893 updateEnvironmentSettings({ requireConnectDeviceApproval: enabled })
894 }
895 />
896 }
897 />
898 ) : null}
899 </>
900 );
901}
902
903/** Older servers have no device approval, so callers pass null and the row stays hidden. */
904export interface ConnectDeviceApprovalControl {
905 readonly required: boolean;
906 readonly canManage: boolean;
907}
908
909export function CloudLinkRow({
910 environmentId,
911 canReadRelay,
912 canManageRelay,
913 connectDeviceApproval,
914}: {
915 readonly environmentId: EnvironmentId;
916 readonly canReadRelay: boolean;
917 readonly canManageRelay: boolean;
918 readonly connectDeviceApproval: ConnectDeviceApprovalControl | null;
919}) {
920 const gt = useGT();
921 if (!hasCloudPublicConfig()) return null;
922 if (!canReadRelay) {
923 return (
924 <SettingsRow
925 title={gt`T3 Connect`}
926 description={gt`To edit these settings, pair this connection with both View relay and Manage relay permissions.`}
927 />
928 );
929 }
930 return (
931 <ConfiguredCloudLinkRow
932 environmentId={environmentId}
933 canManageRelay={canManageRelay}
934 connectDeviceApproval={connectDeviceApproval}
935 />
936 );
937}
938
939function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
940 const gt = useGT();
941 return (
942 <Empty className="min-h-52">
943 <EmptyMedia variant="icon">
944 <ChevronsLeftRightEllipsisIcon />
945 </EmptyMedia>
946 <EmptyHeader>
947 <EmptyTitle>
948 <T>No saved remote environments</T>
949 </EmptyTitle>
950 <EmptyDescription>
951 {cloudEnabled
952 ? gt`Click “Add environment” to pair another environment, or connect one from T3 Connect.`
953 : gt`Click “Add environment” to pair another environment.`}
954 </EmptyDescription>
955 </EmptyHeader>
956 </Empty>
957 );
958}
959
960export function CloudRemoteEnvironmentRows({
961 primaryEnvironmentId,
962 savedEnvironments,
963 only,
964}: {
965 readonly primaryEnvironmentId: EnvironmentId | null;
966 readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;
967 readonly only?: EnvironmentId;
968}) {
969 if (only !== undefined) {
970 return (
971 <CloudEnvironmentConnectRows
972 only={only}
973 primaryEnvironmentId={primaryEnvironmentId}
974 savedEnvironments={savedEnvironments}
975 />
976 );
977 }
978 return hasCloudPublicConfig() ? (
979 <CloudEnvironmentConnectRows
980 primaryEnvironmentId={primaryEnvironmentId}
981 savedEnvironments={savedEnvironments}
982 empty={<EmptyRemoteEnvironments />}
983 />
984 ) : savedEnvironments.length === 0 ? (
985 <EmptyRemoteEnvironments cloudEnabled={false} />
986 ) : null;
987}