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

SavedEnvironmentRows.tsx

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