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