@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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