Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SavedEnvironmentRows.tsx

792 lines29.0 KB

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