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