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