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

SavedEnvironmentRows.tsx

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