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

SavedEnvironmentRows.tsx

844 lines31.3 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 { retryClerkLoadForEnvironment } from "../clerk/clerkLoadFailure";
56import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages";
57import { TunnelLimitAlert, TunnelUsageMeter } from "../cloud/TunnelUsage";
58import { environmentCatalog } from "~/connection/catalog";
59import { readEnvironmentScope } from "~/state/session";
60import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
61import { APP_VERSION } from "~/branding";
62import { useManagedPolicy } from "~/state/managedPolicy";
63import { useAtomCommand } from "../../state/use-atom-command";
64import { useUpdateEnvironmentSettings } from "~/hooks/useSettings";
65import { serverEnvironment } from "~/state/server";
66import {
67 OutdatedServerUpdateAction,
68 ServerUpdateAction,
69 ServerUpdateProgress,
70} from "../ServerUpdateAction";
71import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
72import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
73​
74type SavedBackendListRowProps = {
75 environment: EnvironmentPresentation;
76 removingEnvironmentId: EnvironmentId | null;
77 onSetEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
78 onRemove: (environment: EnvironmentPresentation) => void;
79 onAddRoute: (environment: EnvironmentPresentation) => void;
80};
81​
82function savedBackendStatus(environment: EnvironmentPresentation): {
83 readonly text: string;
84 readonly tone: "muted" | "error";
85} {
86 if (!environment.entry.enabled && environment.connection.phase !== "unsupported")
87 return { text: "Off", tone: "muted" };
88 const { connection } = environment;
89 switch (connection.phase) {
90 case "connected":
91 return { text: "Connected", tone: "muted" };
92 case "connecting":
93 return { text: "Connecting", tone: "muted" };
94 case "reconnecting":
95 if (connection.awaitingApproval) {
96 return { text: connection.error ?? "Waiting for approval", tone: "muted" };
97 }
98 return {
99 text: connection.error ? `Reconnecting: ${connection.error}` : "Reconnecting",
100 tone: "error",
101 };
102 case "unsupported":
103 return { text: "Client not supported", tone: "muted" };
104 case "error":
105 return {
106 text: connection.error ? `Connection failed: ${connection.error}` : "Connection failed",
107 tone: "error",
108 };
109 case "offline":
110 return { text: "Offline", tone: "muted" };
111 case "available":
112 return { text: "Not connected", tone: "muted" };
113 }
115​
116export function SavedBackendListRow({
117 environment,
118 removingEnvironmentId,
119 onSetEnabled,
120 onRemove,
121 onAddRoute,
122}: SavedBackendListRowProps) {
123 const [routesOpen, setRoutesOpen] = useState(false);
124 const [permissionsOpen, setPermissionsOpen] = useState(false);
125 const [diagnosisOpen, setDiagnosisOpen] = useState(false);
126 const environmentId = environment.environmentId;
127 const unsupported = environment.connection.phase === "unsupported";
128 const blocked = unsupported && !hasSavedBearerRoute(environment.entry);
129 const enabled = environment.entry.enabled && !unsupported;
130 const isConnected = environment.connection.phase === "connected";
131 const isRemoving = removingEnvironmentId === environmentId;
132 const errorTraceId = environment.connection.traceId;
133 const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
134 target: "trace ID",
135 onError: (error) => {
136 toastManager.add(
137 stackedThreadToast({
138 type: "error",
139 title: "Could not copy trace ID",
140 description: error.message,
141 }),
142 );
143 },
144 });
145 const copyTraceId = (traceId: string) => {
146 copyTraceIdToClipboard(traceId, { traceId });
147 };
148 const { copyToClipboard: copyMcpUrl } = useCopyToClipboard<{ url: string }>({
149 target: "MCP URL",
150 onCopy: ({ url }) => {
151 toastManager.add({
152 type: "success",
153 title: "MCP URL copied",
154 description: `Add it to an agent, e.g. claude mcp add --transport http t3 ${url}`,
155 });
156 },
157 onError: (error) => {
158 toastManager.add(
159 stackedThreadToast({
160 type: "error",
161 title: "Could not copy MCP URL",
162 description: error.message,
163 }),
164 );
165 },
166 });
167 const versionMismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
168 const serverUpdateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
169 const resumingServerUpdate =
170 serverUpdateState.status === "running" && serverUpdateState.stage === "resuming";
171 const status = savedBackendStatus(environment);
172 const serverVersion = environment.serverConfig?.environment.serverVersion ?? null;
173 // Discovery empties its map on every refresh, so hold the last descriptor
174 // seen or the glyph would blink back to the generic one each time.
175 const relayDiscovery = useRelayEnvironmentDiscovery();
176 const discoveredDescriptor = Option.getOrNull(
177 relayDiscovery.environments.get(environmentId)?.status ?? Option.none(),
178 )?.descriptor;
179 const [lastDescriptor, setLastDescriptor] = useState(discoveredDescriptor);
180 if (discoveredDescriptor !== undefined && discoveredDescriptor !== lastDescriptor) {
181 setLastDescriptor(discoveredDescriptor);
182 }
183 const discoveredRelayHttpBaseUrl =
184 relayDiscovery.environments.get(environmentId)?.environment.endpoint.httpBaseUrl;
185 const [lastRelayHttpBaseUrl, setLastRelayHttpBaseUrl] = useState(discoveredRelayHttpBaseUrl);
186 if (
187 discoveredRelayHttpBaseUrl !== undefined &&
188 discoveredRelayHttpBaseUrl !== lastRelayHttpBaseUrl
189 ) {
190 setLastRelayHttpBaseUrl(discoveredRelayHttpBaseUrl);
191 }
192 const retryNow = useAtomCommand(environmentCatalog.retryNow);
193 const {
194 diagnosis: currentDiagnosis,
195 state: connectionState,
196 relayOnly,
197 } = useConnectionDiagnosis(environment);
198 const diagnosis = resumingServerUpdate ? null : currentDiagnosis;
199 const prepared = usePreparedConnection(environmentId);
200 const connectedTarget = isConnected && prepared._tag === "Some" ? prepared.value.target : null;
201 const mcpUrl = environmentMcpUrl({
202 entry: environment.entry,
203 relayHttpBaseUrl: discoveredRelayHttpBaseUrl ?? lastRelayHttpBaseUrl,
204 connectedTarget,
205 });
206 const machineKind = resolveEnvironmentMachineKind(
207 environment.serverConfig ??
208 (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
209 );
210 const routeCount = connectionRoutes(environment.entry).length;
211 const subtitleText = [
212 environmentTransportLabel(environment, connectedTarget),
213 // The headline below names the failure in full.
214 diagnosis ? null : resumingServerUpdate ? "Restarting" : status.text,
215 enabled && versionMismatch ? serverVersion : null,
216 ]
217 .filter((value): value is string => value !== null)
218 .join(" · ");
219​
220 const showUpdateAction =
221 enabled &&
222 isConnected &&
223 versionMismatch !== null &&
224 (serverUpdateState.status === "idle" || serverUpdateState.status === "failed");
225​
226 const statusTooltip = `${
227 unsupported
228 ? (environment.connection.error ?? connectionStatusText(environment.connection))
229 : enabled
230 ? connectionStatusText(environment.connection)
231 : "Switched off"
232 }${
233 versionMismatch
234 ? `\nUpdate available: ${versionMismatch.serverVersion} → ${versionMismatch.clientVersion}`
235 : ""
236 }`;
237​
238 return (
239 <EnvironmentRow
240 kind={machineKind}
241 label={environment.label}
242 dimmed={!enabled}
243 subtitle={
244 <span className="flex min-w-0 items-center gap-1">
245 <Tooltip>
246 {/* The status can change while the tooltip is open, and base-ui only
247 re-measures the popup when the trigger's payload changes. */}
248 <TooltipTrigger
249 payload={statusTooltip}
250 render={
251 <span
252 className={cn(
253 "min-w-0 truncate",
254 enabled &&
255 status.tone === "error" &&
256 !resumingServerUpdate &&
257 !diagnosis &&
258 "text-destructive",
259 )}
260 />
261 }
262 >
263 {subtitleText}
264 </TooltipTrigger>
265 <TooltipPopup side="top" className="whitespace-pre-wrap">
266 {statusTooltip}
267 </TooltipPopup>
268 </Tooltip>
269 <span aria-hidden className="shrink-0">
270 ·
271 </span>
272 <button
273 type="button"
274 aria-expanded={routesOpen}
275 onClick={() => setRoutesOpen((open) => !open)}
276 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"
277 >
278 {routeCount === 1 ? "Routes" : `${routeCount} routes`}
279 <ChevronRightIcon
280 aria-hidden
281 className={cn(
282 "size-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none",
283 routesOpen && "rotate-90",
284 )}
285 />
286 </button>
287 <span aria-hidden className="shrink-0">
288 ·
289 </span>
290 <button
291 type="button"
292 aria-expanded={permissionsOpen}
293 aria-controls={`remote-permissions-${environmentId}`}
294 onClick={() => setPermissionsOpen((open) => !open)}
295 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"
296 >
297 Permissions
298 <ChevronRightIcon
299 aria-hidden
300 className={cn(
301 "size-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none",
302 permissionsOpen && "rotate-90",
303 )}
304 />
305 </button>
306 </span>
307 }
308 below={
309 <>
310 {diagnosis ? (
311 <ConnectionDiagnosisSummary
312 diagnosis={diagnosis}
313 retryAt={connectionState.phase === "backoff" ? connectionState.retryAt : null}
314 attempt={connectionState.attempt}
315 expanded={diagnosisOpen}
316 onToggle={() => setDiagnosisOpen((open) => !open)}
317 />
318 ) : null}
319 {serverUpdateState.status !== "idle" ? (
320 <div className="mt-1 max-w-md">
321 <ServerUpdateProgress state={serverUpdateState} />
322 </div>
323 ) : null}
324 </>
325 }
326 detail={
327 <>
328 {diagnosis && diagnosisOpen ? (
329 <ConnectionDiagnosisPanel
330 hostLabel={environment.label}
331 diagnosis={diagnosis}
332 onRetry={() => {
333 if (!retryClerkLoadForEnvironment(environment.entry)) void retryNow(environmentId);
334 }}
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 connectDeviceApproval,
526}: {
527 readonly environmentId: EnvironmentId;
528 readonly canManageRelay: boolean;
529 readonly connectDeviceApproval: ConnectDeviceApprovalControl | null;
530}) {
531 const updateEnvironmentSettings = useUpdateEnvironmentSettings(environmentId);
532 const {
533 isSignedIn,
534 linkState: cloudLinkState,
535 linkRevoked,
536 managedTunnelActive,
537 managedTunnelOutOfSync,
538 publishAgentActivity,
539 holdWebhooksWhileOffline,
540 operationError,
541 tunnelLimit,
542 reconcileCloudState,
543 } = useCloudLinkController(environmentId);
544 const { openAuthPrompt } = useT3ConnectAuthPrompt();
545 // The server unlinks and refuses relay changes under such a policy; unlinking stays possible.
546 const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");
547 const turnOn = useT3ConnectTurnOn(environmentId);
548 // Turning on links from this desktop's own backend only; turning off works from anywhere.
549 const showSwitch = isElectron && (turnOn.kind !== "on-host" || managedTunnelActive);
550 const [isUpdating, setIsUpdating] = useState(false);
551 const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
552​
553 const disabledReason = canManageRelay
554 ? null
555 : "Your session does not have permission to manage T3 Connect access.";
556 const isBusy = isUpdating || isUpdatingPreference;
557 const switchDisabled =
558 !canManageRelay ||
559 !isSignedIn ||
560 cloudLinkState.data === null ||
561 cloudLinkState.isPending ||
562 isBusy;
563 // `isSignedIn` is undefined until Clerk loads. Signed out, one row shows a
564 // sign-in button instead of its switch; the onboarding dialog that opens after
565 // a fresh sign-in offers both linking and publishing.
566 const signedOut = isSignedIn === false;
567 const signInButton = (
568 <Button size="sm" variant="outline" onClick={openAuthPrompt}>
569 Sign in
570 </Button>
571 );
572 const refreshLinkState = useEffectEvent(cloudLinkState.refresh);
573 // The server rechecks reachability when the tunnel's 30 s readiness poll changes.
574 // Poll while mounted, so a failed read does not stop later ones.
575 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- 30 s interval that refreshes the cloud link reachability while mounted
576 useEffect(() => {
577 const interval = window.setInterval(() => refreshLinkState(), 30_000);
578 return () => window.clearInterval(interval);
579 }, []);
580 const reachability = managedTunnelActive ? cloudLinkState.data?.reachability : undefined;
581 const reachabilityStatus =
582 reachability?.status === "reachable" ? (
583 formatConnectReachable(reachability)
584 ) : reachability?.status === "unreachable" ? (
585 <span className="block text-destructive">
586 {[reachability.reason, reachability.hint, `Fix: ${reachability.fix}`]
587 .filter(Boolean)
588 .join(" ")}{" "}
589 <a
590 href={connectReachabilityHelpUrl(reachability.cause)}
591 target="_blank"
592 rel="noreferrer"
593 className="underline underline-offset-2"
594 >
595 More info
596 </a>
597 </span>
598 ) : null;
599​
600 const updateManagedTunnel = async (enabled: boolean) => {
601 if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;
602 setIsUpdating(true);
603 const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
604 if (ok) {
605 toastManager.add({
606 type: "success",
607 title: enabled
608 ? "T3 Connect linked"
609 : publishAgentActivity
610 ? "T3 Connect tunnel disabled"
611 : "T3 Connect unlinked",
612 description: enabled
613 ? "This environment is available through T3 Connect."
614 : publishAgentActivity
615 ? "The managed tunnel was removed. Agent activity publishing stays on."
616 : "This environment is no longer available through T3 Connect.",
617 });
618 }
619 setIsUpdating(false);
620 };
621​
622 const updatePublishAgentActivity = async (enabled: boolean) => {
623 if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;
624 setIsUpdatingPreference(true);
625 const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });
626 if (ok) {
627 toastManager.add({
628 type: "success",
629 title: enabled ? "Agent activity enabled" : "Agent activity disabled",
630 description: enabled
631 ? "This environment publishes agent activity to your mobile clients."
632 : "This environment will stop publishing agent activity.",
633 });
634 }
635 setIsUpdatingPreference(false);
636 };
637​
638 const updateHoldWebhooks = async (enabled: boolean) => {
639 setIsUpdatingPreference(true);
640 const ok = await reconcileCloudState({
641 managedTunnel: managedTunnelActive,
642 publish: publishAgentActivity,
643 holdWebhooksWhileOffline: enabled,
644 });
645 if (ok) {
646 toastManager.add({
647 type: "success",
648 title: enabled ? "Webhooks held while offline" : "Webhooks no longer held",
649 description: enabled
650 ? "T3 Connect keeps webhook requests for up to 24 hours while this environment is offline."
651 : "Requests to an offline environment now fail. Anything already held is still delivered.",
652 });
653 }
654 setIsUpdatingPreference(false);
655 };
656​
657 return (
658 <>
659 {showSwitch ? (
660 <SettingsRow
661 title={searchableSetting("t3-connect").title}
662 description={
663 connectDenial !== undefined && !managedTunnelActive
664 ? connectDenial
665 : signedOut
666 ? "Sign in to make this environment available to your other devices through T3 Connect."
667 : linkRevoked
668 ? "This environment was removed from T3 Connect. Turn it on to link it again."
669 : managedTunnelActive
670 ? reachability?.status === "unreachable"
671 ? "T3 Connect is on, but other devices cannot reach this environment."
672 : reachability?.status === "reachable"
673 ? "This environment is available to your other devices through T3 Connect."
674 : "T3 Connect is on. Reachability has not been checked yet."
675 : managedTunnelOutOfSync
676 ? "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."
677 : "Make this environment available to your other devices through T3 Connect."
678 }
679 status={operationError ?? cloudLinkState.error ?? reachabilityStatus}
680 managed={managedTunnelActive ? undefined : connectDenial}
681 control={
682 signedOut ? (
683 signInButton
684 ) : (
685 <CloudLinkSwitch
686 checked={managedTunnelActive}
687 disabled={switchDisabled}
688 disabledReason={disabledReason}
689 onCheckedChange={(enabled) => void updateManagedTunnel(enabled)}
690 />
691 )
692 }
693 >
694 {signedOut || connectDenial !== undefined ? null : (
695 <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />
696 )}
697 </SettingsRow>
698 ) : linkRevoked ? (
699 <SettingsRow
700 title={searchableSetting("t3-connect").title}
701 description="This environment was removed from T3 Connect. Run `t3 connect link` on the host to link it again."
702 />
703 ) : isElectron ? (
704 <SettingsRow
705 title={searchableSetting("t3-connect").title}
706 description="Run `t3 connect link` on the host, then restart T3 Code there."
707 />
708 ) : null}
709 {signedOut && showSwitch ? null : (
710 <SettingsRow
711 title={searchableSetting("publish-agent-activity").title}
712 description={
713 signedOut
714 ? "Sign in to send activity to mobile notifications and Live Activities."
715 : "Send activity to mobile notifications and Live Activities without T3 Connect."
716 }
717 managed={connectDenial}
718 control={
719 signedOut ? (
720 signInButton
721 ) : (
722 <CloudLinkSwitch
723 ariaLabel="Publish agent activity to mobile clients"
724 checked={publishAgentActivity}
725 disabled={switchDisabled}
726 disabledReason={disabledReason}
727 onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
728 />
729 )
730 }
731 />
732 )}
733 {managedTunnelActive && !signedOut ? (
734 <SettingsRow
735 title={searchableSetting("hold-webhooks-while-offline").title}
736 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."
737 managed={connectDenial}
738 control={
739 <CloudLinkSwitch
740 ariaLabel="Hold webhook requests while this environment is offline"
741 checked={holdWebhooksWhileOffline}
742 disabled={switchDisabled}
743 disabledReason={disabledReason}
744 onCheckedChange={(enabled) => void updateHoldWebhooks(enabled)}
745 />
746 }
747 />
748 ) : null}
749 {managedTunnelActive && connectDeviceApproval ? (
750 <SettingsRow
751 title={searchableSetting("connect-device-approval").title}
752 description="Devices that sign in to your T3 Connect account wait until someone already connected here approves them."
753 managed={connectDenial}
754 control={
755 <CloudLinkSwitch
756 ariaLabel="Require approval for new T3 Connect devices"
757 checked={connectDeviceApproval.required}
758 disabled={!connectDeviceApproval.canManage}
759 disabledReason={
760 connectDeviceApproval.canManage
761 ? null
762 : "Your session does not have permission to manage access."
763 }
764 onCheckedChange={(enabled) =>
765 updateEnvironmentSettings({ requireConnectDeviceApproval: enabled })
766 }
767 />
768 }
769 />
770 ) : null}
771 </>
772 );
774​
775/** Older servers have no device approval, so callers pass null and the row stays hidden. */
776export interface ConnectDeviceApprovalControl {
777 readonly required: boolean;
778 readonly canManage: boolean;
780​
781export function CloudLinkRow({
782 environmentId,
783 canReadRelay,
784 canManageRelay,
785 connectDeviceApproval,
786}: {
787 readonly environmentId: EnvironmentId;
788 readonly canReadRelay: boolean;
789 readonly canManageRelay: boolean;
790 readonly connectDeviceApproval: ConnectDeviceApprovalControl | null;
791}) {
792 if (!hasCloudPublicConfig()) return null;
793 if (!canReadRelay) {
794 return (
795 <SettingsRow
796 title="T3 Connect"
797 description="To edit these settings, pair this connection with both View relay and Manage relay permissions."
798 />
799 );
800 }
801 return (
802 <ConfiguredCloudLinkRow
803 environmentId={environmentId}
804 canManageRelay={canManageRelay}
805 connectDeviceApproval={connectDeviceApproval}
806 />
807 );
809​
810function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
811 return (
812 <Empty className="min-h-52">
813 <EmptyMedia variant="icon">
814 <ChevronsLeftRightEllipsisIcon />
815 </EmptyMedia>
816 <EmptyHeader>
817 <EmptyTitle>No saved remote environments</EmptyTitle>
818 <EmptyDescription>
819 {cloudEnabled
820 ? "Click “Add environment” to pair another environment, or connect one from T3 Connect."
821 : "Click “Add environment” to pair another environment."}
822 </EmptyDescription>
823 </EmptyHeader>
824 </Empty>
825 );
827​
828export function CloudRemoteEnvironmentRows({
829 primaryEnvironmentId,
830 savedEnvironments,
831}: {
832 readonly primaryEnvironmentId: EnvironmentId | null;
833 readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;
834}) {
835 return hasCloudPublicConfig() ? (
836 <CloudEnvironmentConnectRows
837 primaryEnvironmentId={primaryEnvironmentId}
838 savedEnvironments={savedEnvironments}
839 empty={<EmptyRemoteEnvironments />}
840 />
841 ) : savedEnvironments.length === 0 ? (
842 <EmptyRemoteEnvironments cloudEnabled={false} />
843 ) : null;