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