@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 1,948 lines 77.3 KB
Raw
1 import { errorDisplayMessage, thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m as resolveMessage } from "~/i18n/messages";
3 import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
4 import { SessionPermissions } from "./SessionPermissions";
5 import { useSearch } from "@tanstack/react-router";
6 import { ChevronRightIcon, EllipsisIcon } from "lucide-react";
7 import { useAtom, useAtomValue } from "@effect/atom-react";
8 import { type ReactNode, useState } from "react";
9 import { T, useGT, useMessages, Var } from "gt-react";
10 import {
11 AuthAccessReadScope,
12 AuthAccessWriteScope,
13 AuthEnvironmentMaintainScope,
14 AuthRelayReadScope,
15 AuthRelayWriteScope,
16 allowsPreviewTunnel,
17 isManagedSettingPath,
18 type AuthClientSession,
19 type AuthPairingLink,
20 type AuthPairingCredentialResult,
21 type AdvertisedEndpoint,
22 type DesktopServerExposureState,
23 type DesktopWslState,
24 EnvironmentId,
25 resolveEnvironmentMachineKind,
26 } from "@t3tools/contracts";
27 import {
28 isAtomCommandInterrupted,
29 settlePromise,
30 squashAtomCommandFailure,
31 } from "@t3tools/client-runtime/state/runtime";
32 import * as Cause from "effect/Cause";
33
34 import { isLocalEnvironmentDisabled } from "../../localEnvironment";
35 import {
36 applyWslEnableSelection,
37 connectDeviceName,
38 isWslSettingsRowVisible,
39 missingTailscaleEndpointDescription,
40 resolveLocalVersionStatusLabel,
41 resolveTailscaleServeBaseUrl,
42 } from "./ConnectionsSettings.logic";
43 import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
44 import { useAccessEnvironment } from "./useAccessEnvironment";
45 import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
46 import { ManagedByOrganization } from "../ManagedPolicy";
47 import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
48 import { useSearchableSetting } from "./settingsSearch";
49 import { ConnectDeviceApprovalSettings } from "./ConnectDeviceApprovalSettings";
50 import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
51 import { FoldedSettingsSection } from "./FoldedSettingsSection";
52 import { EnvironmentsMap } from "./EnvironmentsMap";
53 import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";
54 import { addEnvironmentPrefillAtom } from "~/state/linkedThreadView";
55 import { Toggle, ToggleGroup } from "../ui/toggle-group";
56 import { useMediaQuery } from "~/hooks/useMediaQuery";
57 import { usePeerLinkHosts } from "~/state/peerLinks";
58 import { LoadBalancingSettings } from "./LoadBalancingSettings";
59 import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";
60 import { Input } from "../ui/input";
61 import {
62 Dialog,
63 DialogClose,
64 DialogFooter,
65 DialogDescription,
66 DialogHeader,
67 DialogPanel,
68 DialogPopup,
69 DialogTitle,
70 } from "../ui/dialog";
71 import { ScrollArea } from "../ui/scroll-area";
72 import {
73 AlertDialog,
74 AlertDialogClose,
75 AlertDialogDescription,
76 AlertDialogFooter,
77 AlertDialogHeader,
78 AlertDialogPopup,
79 AlertDialogTitle,
80 } from "../ui/alert-dialog";
81 import { Spinner } from "../ui/spinner";
82 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
83 import { Menu, MenuPopup, MenuTrigger } from "../ui/menu";
84 import { Switch } from "../ui/switch";
85 import { stackedThreadToast, toastManager } from "../ui/toast";
86 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
87 import { Button } from "../ui/button";
88 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
89 import { type ServerClientSessionRecord } from "~/environments/primary";
90 import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
91 import { useUiStateStore } from "~/uiStateStore";
92 import {
93 resolveServerConfigVersionMismatch,
94 resolveServerSelfUpdateCapability,
95 supportsDesktopAppUpdate,
96 } from "~/versionSkew";
97 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
98 import { RemoveT3ConnectEnvironmentDialog } from "../clerk/RemoveT3ConnectEnvironmentDialog";
99 import { authEnvironment } from "~/state/auth";
100 import { environmentCatalog } from "~/connection/catalog";
101 import {
102 readEnvironmentScope,
103 useEnvironmentScope,
104 useEnvironmentSessionState,
105 } from "~/state/session";
106 import { useEnvironmentQuery } from "~/state/query";
107 import {
108 desktopNetworkAccessStateAtom,
109 refreshDesktopNetworkAccessState,
110 } from "~/state/desktopNetworkAccess";
111 import { desktopWslAccessStateAtom, refreshDesktopWslState } from "~/state/desktopWslState";
112 import { useDesktopUpdateState } from "~/state/desktopUpdate";
113 import {
114 type EnvironmentPresentation,
115 useEnvironment,
116 useEnvironments,
117 usePrimaryEnvironment,
118 } from "~/state/environments";
119 import { requestConfirmDialog } from "~/confirmDialog";
120 import { useUpdateEnvironmentSettings } from "~/hooks/useSettings";
121 import { useAtomCommand } from "../../state/use-atom-command";
122 import { environmentIdsKey } from "~/state/environmentAtomList";
123 import { environmentUpdateStatesAtom, serverEnvironment } from "~/state/server";
124 import {
125 ServerUpdateAction,
126 ServerUpdateProgress,
127 ServerUpdatesAction,
128 type ServerUpdateTarget,
129 } from "../ServerUpdateAction";
130 import {
131 sortDesktopPairingLinks,
132 summarizeAuthorizedClients,
133 sortDesktopClientSessions,
134 toDesktopPairingLinkRecord,
135 toDesktopClientSessionRecord,
136 selectPairingEndpoint,
137 isServerNetworkAccessible,
138 isTailscaleHttpsEndpoint,
139 endpointDefaultPreferenceKey,
140 } from "./ConnectionsSettings.logic";
141 import {
142 AdvertisedEndpointListRow,
143 AuthorizedClientsHeaderAction,
144 NetworkAccessDescription,
145 PairingClientsList,
146 } from "./AuthorizedClientsSettings";
147 import { ITEM_ROW_CLASSNAME } from "./itemRows";
148 import {
149 CloudLinkRow,
150 CloudRemoteEnvironmentRows,
151 SavedBackendListRow,
152 } from "./SavedEnvironmentRows";
153 import { AddEnvironmentDialog } from "./AddEnvironmentDialog";
154 import {
155 type ConnectDeviceRevokeRequest,
156 RevokeConnectDeviceDialog,
157 } from "./RevokeConnectDeviceDialog";
158
159 // Sessions T3 Connect minted for a device signed in to the linked account.
160 const CLOUD_CONNECT_SESSION_SUBJECT = "cloud-connect";
161 const DEFAULT_TAILSCALE_SERVE_PORT = 443;
162 const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
163
164 // Colons are invalid in distro names, keeping picker sentinels collision-free.
165 const BACKEND_VALUE_DEFAULT_WSL = "backend:default-wsl";
166 const BACKEND_VALUE_WSL_OFF = "backend:wsl-off";
167
168 // Subscribes on its own so desktop download progress does not re-render the page.
169 function LocalVersionStatusLabel() {
170 const m = useMessages();
171 const updateState = useDesktopUpdateState();
172 return (
173 <span className="text-xs text-muted-foreground">
174 {resolveLocalVersionStatusLabel(updateState, m)}
175 </span>
176 );
177 }
178
179 /** Environments lists the machines this app connects to; access covers who may reach one of them. */
180 export function ConnectionsSettings({ view }: { readonly view: "environments" | "access" }) {
181 return view === "access" ? (
182 <AccessSettings />
183 ) : (
184 <ConnectionsSettingsContent view="environments" accessEnvironmentId={null} />
185 );
186 }
187
188 function AccessSettings() {
189 const gt = useGT();
190 // A link that names an environment, such as the MCP wizard's, opens the page on it. The
191 // settings layout remounts this page when the link changes.
192 const linkedEnvironmentId = useSearch({
193 strict: false,
194 select: (search) =>
195 typeof search.machine === "string" ? EnvironmentId.make(search.machine) : null,
196 });
197 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(linkedEnvironmentId);
198 const { candidates, environment: accessEnvironment } =
199 useAccessEnvironment(selectedEnvironmentId);
200 const accessEnvironmentId = accessEnvironment?.environmentId ?? null;
201 const picker =
202 candidates.length > 1 && accessEnvironmentId !== null ? (
203 <div className="flex min-w-0 items-center gap-1.5 px-3 text-sm text-muted-foreground sm:px-4">
204 <span className="shrink-0">
205 <T>Showing access for</T>
206 </span>
207 <Select
208 value={accessEnvironmentId}
209 onValueChange={(next) => {
210 if (next !== null) setSelectedEnvironmentId(next);
211 }}
212 >
213 <SelectTrigger size="sm" className="w-auto max-w-72" aria-label={gt("Environment")}>
214 <SelectValue>
215 {(value: EnvironmentId) => {
216 const environment = candidates.find(
217 (candidate) => candidate.environmentId === value,
218 );
219 return environment ? settingsScopeEnvironmentLabel(environment, candidates) : null;
220 }}
221 </SelectValue>
222 </SelectTrigger>
223 <SelectPopup alignItemWithTrigger={false}>
224 {candidates.map((environment) => (
225 <SelectItem
226 hideIndicator
227 key={environment.environmentId}
228 value={environment.environmentId}
229 >
230 <span className="flex min-w-0 items-center gap-2">
231 <EnvironmentMachineIcon
232 aria-hidden
233 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
234 className="size-3.5 shrink-0"
235 />
236 <span className="min-w-0 truncate">
237 {settingsScopeEnvironmentLabel(environment, candidates)}
238 </span>
239 {environment.connection.phase !== "connected" ? (
240 <span className="shrink-0 text-xs text-muted-foreground">
241 <T>Offline</T>
242 </span>
243 ) : null}
244 </span>
245 </SelectItem>
246 ))}
247 </SelectPopup>
248 </Select>
249 </div>
250 ) : null;
251 // Keyed so pairing credentials and pending work never carry over to another environment.
252 return (
253 <ConnectionsSettingsContent
254 key={accessEnvironmentId ?? "none"}
255 view="access"
256 accessEnvironmentId={accessEnvironmentId}
257 accessEnvironmentPicker={picker}
258 />
259 );
260 }
261
262 function ConnectionsSettingsContent({
263 view,
264 accessEnvironmentId,
265 accessEnvironmentPicker = null,
266 }: {
267 readonly view: "environments" | "access";
268 readonly accessEnvironmentId: EnvironmentId | null;
269 readonly accessEnvironmentPicker?: ReactNode;
270 }) {
271 const searchableSetting = useSearchableSetting();
272 const gt = useGT();
273 const m = useMessages();
274 const desktopBridge = window.desktopBridge;
275 const { environments } = useEnvironments();
276 const primaryEnvironment = usePrimaryEnvironment();
277 const peerLinkHosts = usePeerLinkHosts();
278 const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
279 const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
280 reportFailure: false,
281 });
282 const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
283 const accessEnvironment = useEnvironment(accessEnvironmentId);
284 // Desktop network, Tailscale, and WSL controls change the backend this app spawned.
285 const isPrimaryAccess =
286 accessEnvironmentId !== null && accessEnvironmentId === primaryEnvironmentId;
287 const accessSessionState = useEnvironmentSessionState(accessEnvironmentId);
288 const currentSessionScopes = accessSessionState.data?.authenticated
289 ? (accessSessionState.data.permissions ?? accessSessionState.data.scopes ?? null)
290 : null;
291 const currentAuthPolicy = desktopBridge ? null : (accessSessionState.data?.auth.policy ?? null);
292 const savedEnvironments = environments.filter(
293 (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
294 );
295 const listedEnvironments = savedEnvironments.filter(
296 (environment) => !isDesktopLocalConnectionTarget(environment.entry.target),
297 );
298 const savedUpdateStates = useAtomValue(
299 environmentUpdateStatesAtom(
300 environmentIdsKey(savedEnvironments.map(({ environmentId }) => environmentId)),
301 ),
302 );
303 const savedServerUpdateStates = savedEnvironments.map((environment, index) => ({
304 environment,
305 updateStatus: savedUpdateStates[index]!.status,
306 }));
307 const savedServerUpdateTargets = savedServerUpdateStates.flatMap(
308 ({ environment, updateStatus }): ServerUpdateTarget[] => {
309 const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig, m);
310 const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig);
311 const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig);
312 if (
313 !mismatch ||
314 updateStatus === "running" ||
315 !environment.entry.enabled ||
316 environment.connection.phase !== "connected" ||
317 isDesktopLocalConnectionTarget(environment.entry.target) ||
318 selfUpdate === null ||
319 (selfUpdate === "desktop-managed" && !desktopAppUpdate)
320 ) {
321 return [];
322 }
323 return [
324 {
325 environmentId: environment.environmentId,
326 serverLabel: environment.label,
327 selfUpdate,
328 installation: environment.serverConfig?.environment.capabilities.serverInstallation,
329 desktopAppUpdate,
330 targetVersion: mismatch.clientVersion,
331 },
332 ];
333 },
334 );
335 const loadBalancingEnvironments = [
336 ...(primaryEnvironment ? [primaryEnvironment] : []),
337 ...savedEnvironments.filter((environment) => environment.entry.enabled),
338 ].filter((environment) => environment.connection.phase !== "unsupported");
339 const [desktopServerExposureMutationError, setDesktopServerExposureMutationError] = useState<
340 string | null
341 >(null);
342 const [desktopAccessManagementMutationError, setDesktopAccessManagementMutationError] = useState<
343 string | null
344 >(null);
345 const [createdPairingCredentials, setCreatedPairingCredentials] = useState<
346 ReadonlyMap<string, string>
347 >(() => new Map());
348 const [newestPairingLinkId, setNewestPairingLinkId] = useState<string | null>(null);
349 const handlePairingLinkCreated = (created: AuthPairingCredentialResult) => {
350 setCreatedPairingCredentials((current) => new Map(current).set(created.id, created.credential));
351 setNewestPairingLinkId(created.id);
352 };
353 const [revokingDesktopPairingLinkId, setRevokingDesktopPairingLinkId] = useState<string | null>(
354 null,
355 );
356 const [revokingDesktopClientSessionId, setRevokingDesktopClientSessionId] = useState<
357 string | null
358 >(null);
359 const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false);
360 const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
361 const [routeTarget, setRouteTarget] = useState<EnvironmentPresentation | null>(null);
362 // An address the map already knows for the machine being added; remounts the dialog with it.
363 const [addBackendHost, setAddBackendHost] = useState("");
364 const [savedBackendError, setSavedBackendError] = useState<string | null>(null);
365 // Set by a read-only linked thread whose machine this client is about to pair with.
366 const [addPrefill, setAddPrefill] = useAtom(addEnvironmentPrefillAtom);
367 const handleAddBackendDialogOpenChange = (open: boolean) => {
368 setAddBackendDialogOpen(open);
369 if (open) {
370 setRouteTarget(null);
371 setAddBackendHost("");
372 } else {
373 setSavedBackendError(null);
374 setAddPrefill(null);
375 }
376 };
377 const openAddRoute = (target: EnvironmentPresentation) => {
378 setRouteTarget(target);
379 setAddBackendHost("");
380 setSavedBackendError(null);
381 setAddBackendDialogOpen(true);
382 };
383 const openAddEnvironment = (host = "") => {
384 setRouteTarget(null);
385 setAddBackendHost(host);
386 setSavedBackendError(null);
387 setAddBackendDialogOpen(true);
388 };
389 // The map is the page's main view where there is room; the list is its equivalent everywhere.
390 const roomForMap = useMediaQuery("md");
391 const [pickedEnvironmentsView, setPickedEnvironmentsView] = useState<"map" | "list" | null>(null);
392 const environmentsView = roomForMap ? (pickedEnvironmentsView ?? "map") : "list";
393 const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] =
394 useState<EnvironmentId | null>(null);
395 const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false);
396 const [isUpdatingTailscaleServe, setIsUpdatingTailscaleServe] = useState(false);
397 const [isUpdatingWslBackend, setIsUpdatingWslBackend] = useState(false);
398 const [desktopWslMutationError, setDesktopWslMutationError] = useState<string | null>(null);
399 type PendingWslChange =
400 | { readonly kind: "disable"; readonly wasWslOnly: boolean }
401 | { readonly kind: "distro"; readonly nextDistro: string | null }
402 | { readonly kind: "enable"; readonly nextDistro: string | null }
403 | { readonly kind: "wsl-only"; readonly nextValue: boolean };
404 const [pendingWslChange, setPendingWslChange] = useState<PendingWslChange | null>(null);
405 const isWslConfirmDialogOpen = pendingWslChange !== null;
406 const [pendingTailscaleServeEndpoint, setPendingTailscaleServeEndpoint] =
407 useState<AdvertisedEndpoint | null>(null);
408 const [disableTailscaleServeDialogOpen, setDisableTailscaleServeDialogOpen] = useState(false);
409 const [tailscaleServePortInput, setTailscaleServePortInput] = useState(
410 String(DEFAULT_TAILSCALE_SERVE_PORT),
411 );
412 const [pendingDesktopServerExposureMode, setPendingDesktopServerExposureMode] = useState<
413 DesktopServerExposureState["mode"] | null
414 >(null);
415 const primaryServerConfig = primaryEnvironment?.serverConfig ?? null;
416 // Turning remote access off stays possible; only the way in is managed.
417 const remoteClientsDenial = managedCapabilityDenial(
418 primaryServerConfig?.managedPolicy,
419 "remoteClients",
420 m,
421 );
422 const primaryVersionMismatch = resolveServerConfigVersionMismatch(primaryServerConfig, m);
423 const primaryServerUpdateState = useAtomValue(
424 serverEnvironment.updateStateAtom(primaryEnvironmentId),
425 );
426 const [isAdvertisedEndpointListExpanded, setIsAdvertisedEndpointListExpanded] = useState(false);
427 const defaultAdvertisedEndpointKey = useUiStateStore(
428 (state) => state.defaultAdvertisedEndpointKey,
429 );
430 const setDefaultAdvertisedEndpointKey = useUiStateStore(
431 (state) => state.setDefaultAdvertisedEndpointKey,
432 );
433 const canReadAccess = useEnvironmentScope(accessEnvironmentId, AuthAccessReadScope);
434 const canWriteAccess = useEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope);
435 const canReadRelay = useEnvironmentScope(accessEnvironmentId, AuthRelayReadScope);
436 const canMaintain = useEnvironmentScope(accessEnvironmentId, AuthEnvironmentMaintainScope);
437 const canManageRelay = useEnvironmentScope(accessEnvironmentId, AuthRelayWriteScope);
438 const canManageLocalBackend = isPrimaryAccess && !isLocalEnvironmentDisabled() && canMaintain;
439 const showsAccess = view === "access";
440 const authAccessChanges = useEnvironmentQuery(
441 showsAccess && canReadAccess && accessEnvironmentId !== null
442 ? authEnvironment.accessChanges({
443 environmentId: accessEnvironmentId,
444 input: null,
445 })
446 : null,
447 m,
448 );
449 const revokePairingLink = useAtomCommand(authEnvironment.revokePairingLink, {
450 reportFailure: false,
451 });
452 const revokeClient = useAtomCommand(authEnvironment.revokeClient, { reportFailure: false });
453 const revokeOtherClients = useAtomCommand(authEnvironment.revokeOtherClients, {
454 reportFailure: false,
455 });
456 const desktopNetworkAccess = useEnvironmentQuery(
457 showsAccess && canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null,
458 m,
459 );
460 const desktopWsl = useEnvironmentQuery(
461 showsAccess && canManageLocalBackend && desktopBridge ? desktopWslAccessStateAtom : null,
462 m,
463 );
464 const desktopWslState = desktopWsl.data;
465 const desktopWslError = desktopWslMutationError ?? desktopWsl.error;
466 const isLoadingWslState = desktopWsl.isPending && desktopWsl.data === null;
467 const desktopServerExposureState = desktopNetworkAccess.data?.serverExposureState ?? null;
468 const desktopAdvertisedEndpoints =
469 desktopNetworkAccess.data?.advertisedEndpoints ?? EMPTY_ADVERTISED_ENDPOINTS;
470 const desktopServerExposureError =
471 desktopServerExposureMutationError ?? desktopNetworkAccess.error;
472 const desktopAccessManagementError =
473 desktopAccessManagementMutationError ?? authAccessChanges.error;
474 const isLoadingDesktopAccessManagement =
475 authAccessChanges.isPending && authAccessChanges.data === null;
476 const desktopPairingLinks = (() => {
477 const event = authAccessChanges.data;
478 if (event?.type !== "snapshot") return [];
479 return sortDesktopPairingLinks(
480 event.payload.pairingLinks.map((pairingLink: AuthPairingLink) =>
481 toDesktopPairingLinkRecord(pairingLink),
482 ),
483 );
484 })();
485 const desktopClientSessions = (() => {
486 const event = authAccessChanges.data;
487 if (event?.type !== "snapshot") return [];
488 return sortDesktopClientSessions(
489 event.payload.clientSessions.map((clientSession: AuthClientSession) =>
490 toDesktopClientSessionRecord(clientSession),
491 ),
492 );
493 })();
494 const isLocalBackendNetworkAccessible = desktopBridge
495 ? desktopServerExposureState?.mode === "network-accessible"
496 : isServerNetworkAccessible({
497 authPolicy: currentAuthPolicy,
498 directEndpoints: accessEnvironment?.serverConfig?.directEndpoints,
499 });
500 const trimmedTailscaleServePortInput = tailscaleServePortInput.trim();
501 const parsedTailscaleServePort = Number(trimmedTailscaleServePortInput);
502 const isTailscaleServePortValid =
503 /^\d+$/u.test(trimmedTailscaleServePortInput) &&
504 Number.isInteger(parsedTailscaleServePort) &&
505 parsedTailscaleServePort >= 1 &&
506 parsedTailscaleServePort <= 65_535;
507
508 const pendingTailscaleServeBaseUrl = resolveTailscaleServeBaseUrl(
509 pendingTailscaleServeEndpoint,
510 parsedTailscaleServePort,
511 isTailscaleServePortValid,
512 );
513
514 const handleDesktopServerExposureChange = async (checked: boolean) => {
515 if (
516 !desktopBridge ||
517 primaryEnvironmentId === null ||
518 !readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
519 )
520 return;
521 setIsUpdatingDesktopServerExposure(true);
522 setDesktopServerExposureMutationError(null);
523 try {
524 await desktopBridge.setServerExposureMode(checked ? "network-accessible" : "local-only");
525 refreshDesktopNetworkAccessState();
526 setPendingDesktopServerExposureMode(null);
527 setIsUpdatingDesktopServerExposure(false);
528 } catch (error) {
529 const message =
530 error instanceof Error
531 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
532 : gt("Failed to update network exposure.");
533 setPendingDesktopServerExposureMode(null);
534 setDesktopServerExposureMutationError(message);
535 toastManager.add(
536 stackedThreadToast({
537 type: "error",
538 title: gt("Could not update network access"),
539 description: message,
540 }),
541 );
542 setIsUpdatingDesktopServerExposure(false);
543 }
544 };
545
546 const handleConfirmDesktopServerExposureChange = () => {
547 if (pendingDesktopServerExposureMode === null) return;
548 const checked = pendingDesktopServerExposureMode === "network-accessible";
549 void handleDesktopServerExposureChange(checked);
550 };
551
552 const handleConfirmTailscaleServeSetup = async () => {
553 if (
554 !desktopBridge ||
555 primaryEnvironmentId === null ||
556 !readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
557 )
558 return;
559 if (!isTailscaleServePortValid) return;
560 setIsUpdatingTailscaleServe(true);
561 setDesktopServerExposureMutationError(null);
562 const settled = await settlePromise(async () => {
563 await desktopBridge.setTailscaleServeEnabled({
564 enabled: true,
565 port: parsedTailscaleServePort,
566 });
567 refreshDesktopNetworkAccessState();
568 setPendingTailscaleServeEndpoint(null);
569 });
570 if (settled._tag === "Failure") {
571 const error = Cause.squash(settled.cause);
572 const message =
573 error instanceof Error
574 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
575 : gt("Failed to configure Tailscale HTTPS.");
576 setDesktopServerExposureMutationError(message);
577 toastManager.add(
578 stackedThreadToast({
579 type: "error",
580 title: gt("Could not set up Tailscale HTTPS"),
581 description: message,
582 }),
583 );
584 }
585 setIsUpdatingTailscaleServe(false);
586 };
587
588 const handleStartTailscaleServeSetup = (endpoint: AdvertisedEndpoint) => {
589 setTailscaleServePortInput(
590 String(desktopServerExposureState?.tailscaleServePort ?? DEFAULT_TAILSCALE_SERVE_PORT),
591 );
592 setPendingTailscaleServeEndpoint(endpoint);
593 };
594
595 const handleConfirmTailscaleServeDisable = async () => {
596 if (
597 !desktopBridge ||
598 primaryEnvironmentId === null ||
599 !readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
600 )
601 return;
602 setIsUpdatingTailscaleServe(true);
603 setDesktopServerExposureMutationError(null);
604 const settled = await settlePromise(async () => {
605 await desktopBridge.setTailscaleServeEnabled({
606 enabled: false,
607 port: desktopServerExposureState?.tailscaleServePort ?? DEFAULT_TAILSCALE_SERVE_PORT,
608 });
609 refreshDesktopNetworkAccessState();
610 setDisableTailscaleServeDialogOpen(false);
611 });
612 if (settled._tag === "Failure") {
613 const error = Cause.squash(settled.cause);
614 const message =
615 error instanceof Error
616 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
617 : gt("Failed to disable Tailscale HTTPS.");
618 setDesktopServerExposureMutationError(message);
619 toastManager.add(
620 stackedThreadToast({
621 type: "error",
622 title: gt("Could not disable Tailscale HTTPS"),
623 description: message,
624 }),
625 );
626 }
627 setIsUpdatingTailscaleServe(false);
628 };
629
630 const handleStartTailscaleServeDisable = (_endpoint: AdvertisedEndpoint) => {
631 setDisableTailscaleServeDialogOpen(true);
632 };
633
634 const handleRevokeDesktopPairingLink = async (id: string) => {
635 if (
636 accessEnvironmentId === null ||
637 !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope)
638 )
639 return;
640 setRevokingDesktopPairingLinkId(id);
641 setDesktopAccessManagementMutationError(null);
642 const result = await revokePairingLink({ environmentId: accessEnvironmentId, input: { id } });
643 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
644 const error = squashAtomCommandFailure(result);
645 const message =
646 error instanceof Error
647 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
648 : gt("Failed to revoke pairing link.");
649 setDesktopAccessManagementMutationError(message);
650 toastManager.add(
651 stackedThreadToast({
652 type: "error",
653 title: gt("Could not revoke pairing link"),
654 description: message,
655 }),
656 );
657 }
658 setRevokingDesktopPairingLinkId(null);
659 };
660
661 const handleRevokeDesktopClientSession = async (
662 sessionId: ServerClientSessionRecord["sessionId"],
663 ) => {
664 if (
665 accessEnvironmentId === null ||
666 !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope)
667 )
668 return;
669 setRevokingDesktopClientSessionId(sessionId);
670 setDesktopAccessManagementMutationError(null);
671 const result = await revokeClient({ environmentId: accessEnvironmentId, input: { sessionId } });
672 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
673 const error = squashAtomCommandFailure(result);
674 const message =
675 error instanceof Error
676 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
677 : gt("Failed to revoke client access.");
678 setDesktopAccessManagementMutationError(message);
679 toastManager.add(
680 stackedThreadToast({
681 type: "error",
682 title: gt("Could not revoke client access"),
683 description: message,
684 }),
685 );
686 }
687 setRevokingDesktopClientSessionId(null);
688 };
689
690 const handleRevokeOtherDesktopClients = async () => {
691 if (
692 accessEnvironmentId === null ||
693 !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope)
694 )
695 return;
696 setIsRevokingOtherDesktopClients(true);
697 setDesktopAccessManagementMutationError(null);
698 const result = await revokeOtherClients({ environmentId: accessEnvironmentId, input: null });
699 if (result._tag === "Success") {
700 toastManager.add({
701 type: "success",
702 title:
703 result.value === 1
704 ? gt("Revoked 1 other client")
705 : gt("{count, plural, other {Revoked {count} clients}}", { count: result.value }),
706 description: gt("Other paired clients will need a new pairing link before reconnecting."),
707 });
708 } else if (!isAtomCommandInterrupted(result)) {
709 const error = squashAtomCommandFailure(result);
710 const message =
711 error instanceof Error
712 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
713 : gt("Failed to revoke other clients.");
714 setDesktopAccessManagementMutationError(message);
715 toastManager.add(
716 stackedThreadToast({
717 type: "error",
718 title: gt("Could not revoke other clients"),
719 description: message,
720 }),
721 );
722 }
723 setIsRevokingOtherDesktopClients(false);
724 };
725
726 const handleSetSavedBackendEnabled = async (environmentId: EnvironmentId, enabled: boolean) => {
727 setSavedBackendError(null);
728 const result = await setEnvironmentEnabled({ environmentId, enabled });
729 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
730 const error = squashAtomCommandFailure(result);
731 const message =
732 error instanceof Error
733 ? (errorDisplayMessage(error, resolveMessage) ?? error.message)
734 : enabled
735 ? gt("Failed to switch the backend on.")
736 : gt("Failed to switch the backend off.");
737 setSavedBackendError(message);
738 toastManager.add(
739 stackedThreadToast({
740 type: "error",
741 title: enabled ? gt("Could not switch backend on") : gt("Could not switch backend off"),
742 description: message,
743 }),
744 );
745 }
746 };
747
748 const removeSavedBackend = async (environment: EnvironmentPresentation) => {
749 const environmentId = environment.environmentId;
750 setRemovingSavedEnvironmentId(environmentId);
751 setSavedBackendError(null);
752 const result = await removeEnvironment(environmentId);
753 setRemovingSavedEnvironmentId(null);
754 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
755 const error = squashAtomCommandFailure(result);
756 const message =
757 error instanceof Error
758 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
759 : gt("Failed to remove backend.");
760 setSavedBackendError(message);
761 toastManager.add(
762 stackedThreadToast({
763 type: "error",
764 title: gt("Could not remove backend"),
765 description: message,
766 }),
767 );
768 }
769 };
770
771 // Removing a T3 Connect route preserves account registration; use a separate dialog pointing to
772 // deregistration.
773 const [pendingT3ConnectRemoval, setPendingT3ConnectRemoval] =
774 useState<EnvironmentPresentation | null>(null);
775 const handleRemoveSavedBackend = async (environment: EnvironmentPresentation) => {
776 if (environment.relayManaged && hasCloudPublicConfig()) {
777 setPendingT3ConnectRemoval(environment);
778 return;
779 }
780 const confirmed = await requestConfirmDialog(
781 gt(
782 "Remove {environment} from this device?\nThis forgets its pairing, credentials, and cached threads here. Switch it off instead to keep it saved.",
783 { environment: environment.label },
784 ),
785 { variant: "destructive" },
786 );
787 if (confirmed === true) await removeSavedBackend(environment);
788 };
789
790 // T3 Connect devices waiting for approval have their own list.
791 const visibleDesktopPairingLinks = desktopPairingLinks.filter(
792 (pairingLink) => pairingLink.connectDeviceRequest === undefined,
793 );
794 const connectDeviceRequests = desktopPairingLinks.filter(
795 (pairingLink) => pairingLink.connectDeviceRequest !== undefined,
796 );
797 // Older servers omit the list; they cannot hold devices for approval.
798 const connectDevices =
799 authAccessChanges.data?.type === "snapshot"
800 ? (authAccessChanges.data.payload.connectDevices ?? null)
801 : null;
802 const updateAccessSettings = useUpdateEnvironmentSettings(accessEnvironmentId);
803 const [pendingConnectRevoke, setPendingConnectRevoke] =
804 useState<ConnectDeviceRevokeRequest | null>(null);
805 // With approval off a revoked T3 Connect device signs straight back in, so offer to turn it
806 // on. Older servers have no such setting, and revoking there goes ahead as before.
807 const connectApprovalOff =
808 accessEnvironment?.serverConfig?.settings.requireConnectDeviceApproval === false;
809 const requestConnectRevoke = (title: string, revoke: () => Promise<void>) => {
810 if (connectApprovalOff && canWriteAccess) setPendingConnectRevoke({ title, revoke });
811 else void revoke();
812 };
813 const requireConnectApproval = () =>
814 new Promise<boolean>((resolve) =>
815 updateAccessSettings(
816 { requireConnectDeviceApproval: true },
817 { onSaved: () => resolve(true), onFailed: () => resolve(false) },
818 ),
819 );
820 const requestRevokeClientSession = (sessionId: ServerClientSessionRecord["sessionId"]) => {
821 const session = desktopClientSessions.find((candidate) => candidate.sessionId === sessionId);
822 if (session?.subject === CLOUD_CONNECT_SESSION_SUBJECT) {
823 requestConnectRevoke(gt("Revoke {name}?", { name: connectDeviceName(session, m) }), () =>
824 handleRevokeDesktopClientSession(sessionId),
825 );
826 } else {
827 void handleRevokeDesktopClientSession(sessionId);
828 }
829 };
830 const requestRevokeOtherClients = () => {
831 const revokesConnectDevices =
832 (connectDevices?.length ?? 0) > 0 ||
833 desktopClientSessions.some(
834 (session) => !session.current && session.subject === CLOUD_CONNECT_SESSION_SUBJECT,
835 );
836 if (revokesConnectDevices) {
837 requestConnectRevoke(gt("Revoke all other clients?"), handleRevokeOtherDesktopClients);
838 } else {
839 void handleRevokeOtherDesktopClients();
840 }
841 };
842 const tailscaleHttpsEndpoint = desktopAdvertisedEndpoints.find(isTailscaleHttpsEndpoint) ?? null;
843 const visibleDesktopNetworkAdvertisedEndpoints = isLocalBackendNetworkAccessible
844 ? desktopAdvertisedEndpoints.filter((endpoint) => !isTailscaleHttpsEndpoint(endpoint))
845 : [];
846 const visibleDesktopAdvertisedEndpoints = tailscaleHttpsEndpoint
847 ? [...visibleDesktopNetworkAdvertisedEndpoints, tailscaleHttpsEndpoint]
848 : visibleDesktopNetworkAdvertisedEndpoints;
849 const defaultDesktopNetworkAdvertisedEndpoint = selectPairingEndpoint(
850 visibleDesktopNetworkAdvertisedEndpoints,
851 defaultAdvertisedEndpointKey,
852 );
853 const defaultDesktopAdvertisedEndpoint =
854 defaultDesktopNetworkAdvertisedEndpoint ??
855 selectPairingEndpoint(
856 tailscaleHttpsEndpoint ? [tailscaleHttpsEndpoint] : [],
857 defaultAdvertisedEndpointKey,
858 );
859 const defaultDesktopAdvertisedEndpointKey = defaultDesktopAdvertisedEndpoint
860 ? endpointDefaultPreferenceKey(defaultDesktopAdvertisedEndpoint)
861 : null;
862 const handleSetDefaultAdvertisedEndpoint = (endpoint: AdvertisedEndpoint) => {
863 setDefaultAdvertisedEndpointKey(endpointDefaultPreferenceKey(endpoint));
864 };
865
866 const renderNetworkAccessToggle = () => (
867 <Switch
868 checked={desktopServerExposureState?.mode === "network-accessible"}
869 disabled={!desktopServerExposureState || isUpdatingDesktopServerExposure}
870 onCheckedChange={(checked) => {
871 setPendingDesktopServerExposureMode(checked ? "network-accessible" : "local-only");
872 }}
873 aria-label={gt("Enable network access")}
874 />
875 );
876 const renderEndpointRows = () =>
877 isAdvertisedEndpointListExpanded
878 ? visibleDesktopNetworkAdvertisedEndpoints.map((endpoint) => {
879 const endpointKey = endpointDefaultPreferenceKey(endpoint);
880 return (
881 <AdvertisedEndpointListRow
882 key={endpoint.id}
883 endpoint={endpoint}
884 isDefault={endpointKey === defaultDesktopAdvertisedEndpointKey}
885 onSetDefault={handleSetDefaultAdvertisedEndpoint}
886 onSetupTailscaleServe={handleStartTailscaleServeSetup}
887 onDisableTailscaleServe={handleStartTailscaleServeDisable}
888 isUpdatingTailscaleServe={isUpdatingTailscaleServe}
889 />
890 );
891 })
892 : null;
893 const applyWslSettingChange = async (apply: () => Promise<DesktopWslState>) => {
894 if (
895 !desktopBridge ||
896 primaryEnvironmentId === null ||
897 !readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
898 )
899 return;
900 setIsUpdatingWslBackend(true);
901 setDesktopWslMutationError(null);
902 const settled = await settlePromise(async () => {
903 await apply();
904 refreshDesktopWslState();
905 });
906 if (settled._tag === "Failure") {
907 const error = Cause.squash(settled.cause);
908 const message =
909 error instanceof Error
910 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
911 : gt("Failed to update WSL backend.");
912 setDesktopWslMutationError(message);
913 toastManager.add(
914 stackedThreadToast({
915 type: "error",
916 title: gt("Could not change WSL backend"),
917 description: message,
918 }),
919 );
920 refreshDesktopWslState();
921 }
922 setIsUpdatingWslBackend(false);
923 };
924
925 const loadWslState = () => {
926 setDesktopWslMutationError(null);
927 refreshDesktopWslState();
928 };
929
930 const hasWslRegistrationToLose = environments.some((environment) =>
931 isDesktopLocalConnectionTarget(environment.entry.target),
932 );
933
934 const handleSelectWslMode = (value: string) => {
935 if (!desktopBridge || !desktopWslState) return;
936 const defaultDistroName =
937 desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null;
938 if (value === BACKEND_VALUE_WSL_OFF) {
939 // Unavailable WSL can remain wslOnly while disabled; switching to Windows must clear both.
940 if (!desktopWslState.enabled && !desktopWslState.wslOnly) return;
941 const wasWslOnly = desktopWslState.wslOnly;
942 if (hasWslRegistrationToLose || wasWslOnly) {
943 setPendingWslChange({ kind: "disable", wasWslOnly });
944 return;
945 }
946 void applyWslSettingChange(() => desktopBridge.setWslBackendEnabled(false));
947 return;
948 }
949 const nextDistro = value === BACKEND_VALUE_DEFAULT_WSL ? null : value;
950 const resolvedNext = nextDistro ?? defaultDistroName;
951 if (!desktopWslState.enabled) {
952 setPendingWslChange({ kind: "enable", nextDistro });
953 return;
954 }
955 const resolvedCurrent = desktopWslState.distro ?? defaultDistroName;
956 if (resolvedCurrent === resolvedNext) return;
957 if (hasWslRegistrationToLose || desktopWslState.wslOnly) {
958 setPendingWslChange({ kind: "distro", nextDistro });
959 return;
960 }
961 void applyWslSettingChange(() => desktopBridge.setWslDistro(nextDistro));
962 };
963
964 const handleConfirmEnableWsl = (mode: "both" | "wsl-only") => {
965 if (!desktopBridge || !pendingWslChange || pendingWslChange.kind !== "enable") return;
966 const nextDistro = pendingWslChange.nextDistro;
967 setPendingWslChange(null);
968 const persistedDistro = desktopWslState?.distro ?? null;
969 void applyWslSettingChange(() =>
970 applyWslEnableSelection({
971 bridge: desktopBridge,
972 mode,
973 nextDistro,
974 persistedDistro,
975 }),
976 );
977 };
978
979 const handleToggleWslOnly = (enabled: boolean) => {
980 if (!desktopBridge || !desktopWslState || desktopWslState.wslOnly === enabled) return;
981 setPendingWslChange({ kind: "wsl-only", nextValue: enabled });
982 };
983
984 const handleConfirmWslChange = () => {
985 if (!desktopBridge || !pendingWslChange) return;
986 const change = pendingWslChange;
987 if (change.kind === "enable") return;
988 setPendingWslChange(null);
989 if (change.kind === "disable") {
990 void applyWslSettingChange(async () => {
991 const next = await desktopBridge.setWslBackendEnabled(false);
992 if (change.wasWslOnly) {
993 return await desktopBridge.setWslOnly(false);
994 }
995 return next;
996 });
997 return;
998 }
999 if (change.kind === "distro") {
1000 void applyWslSettingChange(() => desktopBridge.setWslDistro(change.nextDistro));
1001 return;
1002 }
1003 void applyWslSettingChange(() => desktopBridge.setWslOnly(change.nextValue));
1004 };
1005
1006 const renderWslRow = () => {
1007 if (!desktopWslState) {
1008 if (
1009 isWslSettingsRowVisible({ state: null, error: desktopWslError }) &&
1010 canManageLocalBackend
1011 ) {
1012 return (
1013 <SettingsRow
1014 {...searchableSetting("wsl-backend")}
1015 description={gt("Couldn't load the WSL backend state.")}
1016 status={<span className="block text-destructive">{desktopWslError}</span>}
1017 control={
1018 <Button
1019 size="sm"
1020 variant="outline"
1021 onClick={loadWslState}
1022 disabled={isLoadingWslState}
1023 >
1024 {isLoadingWslState ? gt("Retrying…") : gt("Retry")}
1025 </Button>
1026 }
1027 />
1028 );
1029 }
1030 return null;
1031 }
1032 if (!isWslSettingsRowVisible({ state: desktopWslState, error: desktopWslError })) {
1033 return null;
1034 }
1035 if (!desktopWslState.available) {
1036 return (
1037 <SettingsRow
1038 {...searchableSetting("wsl-backend")}
1039 description={gt(
1040 "WSL is unavailable, so Windows is running instead. Turn WSL off to clear this preference.",
1041 )}
1042 status={
1043 desktopWslError ? (
1044 <span className="block text-destructive">{desktopWslError}</span>
1045 ) : null
1046 }
1047 control={
1048 <Button
1049 size="sm"
1050 variant="outline"
1051 disabled={isUpdatingWslBackend}
1052 onClick={() => handleSelectWslMode(BACKEND_VALUE_WSL_OFF)}
1053 >
1054 <T>Switch to Windows</T>
1055 </Button>
1056 }
1057 />
1058 );
1059 }
1060 const defaultDistroName =
1061 desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null;
1062 const selectValue = !desktopWslState.enabled
1063 ? BACKEND_VALUE_WSL_OFF
1064 : (desktopWslState.distro ?? defaultDistroName ?? BACKEND_VALUE_DEFAULT_WSL);
1065 const selectLabel =
1066 selectValue === BACKEND_VALUE_WSL_OFF
1067 ? gt("Off", { $context: "WSL backend is off" })
1068 : selectValue === BACKEND_VALUE_DEFAULT_WSL
1069 ? gt("Default distro")
1070 : selectValue;
1071 return (
1072 <>
1073 <SettingsRow
1074 {...searchableSetting("wsl-backend")}
1075 description={gt(
1076 "Run the selected WSL distro alongside Windows. Projects remain on their current filesystem.",
1077 )}
1078 status={
1079 desktopWslError ? (
1080 <span className="block text-destructive">{desktopWslError}</span>
1081 ) : desktopWslState.preflightError ? (
1082 <span className="block text-destructive">
1083 <T>
1084 WSL backend couldn't start: <Var>{desktopWslState.preflightError}</Var>
1085 </T>
1086 </span>
1087 ) : null
1088 }
1089 control={
1090 <Select
1091 value={selectValue}
1092 onValueChange={(value) => {
1093 if (typeof value !== "string") return;
1094 handleSelectWslMode(value);
1095 }}
1096 >
1097 <SelectTrigger
1098 size="sm"
1099 className="w-full sm:w-56"
1100 aria-label={gt("WSL backend")}
1101 disabled={isUpdatingWslBackend}
1102 >
1103 <SelectValue>{selectLabel}</SelectValue>
1104 </SelectTrigger>
1105 <SelectPopup align="end" alignItemWithTrigger={false}>
1106 <SelectItem hideIndicator value={BACKEND_VALUE_WSL_OFF}>
1107 {gt("Off", { $context: "WSL backend is off" })}
1108 </SelectItem>
1109 {desktopWslState.distros.length === 0 ? (
1110 <SelectItem hideIndicator value={BACKEND_VALUE_DEFAULT_WSL}>
1111 <T>Default distro</T>
1112 </SelectItem>
1113 ) : (
1114 desktopWslState.distros.map((distro) => (
1115 <SelectItem hideIndicator key={distro.name} value={distro.name}>
1116 {distro.name}
1117 {distro.isDefault ? ` ${gt("(default)")}` : ""}
1118 </SelectItem>
1119 ))
1120 )}
1121 </SelectPopup>
1122 </Select>
1123 }
1124 />
1125 {desktopWslState.enabled ? (
1126 <SettingsRow
1127 title={gt("WSL only")}
1128 description={gt("Run only the WSL backend. T3 Code restarts when this changes.")}
1129 className="bg-muted/20 pl-7 sm:pl-8"
1130 control={
1131 <Switch
1132 checked={desktopWslState.wslOnly}
1133 disabled={isUpdatingWslBackend}
1134 onCheckedChange={(checked) => handleToggleWslOnly(checked)}
1135 aria-label={gt("Run WSL only")}
1136 />
1137 }
1138 />
1139 ) : null}
1140 </>
1141 );
1142 };
1143
1144 const renderTailscaleRow = () => (
1145 <SettingsRow
1146 title={searchableSetting("tailscale-https").title}
1147 description={
1148 tailscaleHttpsEndpoint
1149 ? tailscaleHttpsEndpoint.status === "available"
1150 ? tailscaleHttpsEndpoint.httpBaseUrl
1151 : gt("Use Tailscale Serve to expose this backend through a MagicDNS HTTPS URL.")
1152 : missingTailscaleEndpointDescription(desktopServerExposureState, m)
1153 }
1154 control={
1155 tailscaleHttpsEndpoint ? (
1156 <Switch
1157 checked={tailscaleHttpsEndpoint.status === "available"}
1158 disabled={isUpdatingTailscaleServe}
1159 onCheckedChange={(checked) => {
1160 if (checked) {
1161 handleStartTailscaleServeSetup(tailscaleHttpsEndpoint);
1162 return;
1163 }
1164 handleStartTailscaleServeDisable(tailscaleHttpsEndpoint);
1165 }}
1166 aria-label={gt("Enable Tailscale HTTPS")}
1167 />
1168 ) : null
1169 }
1170 managed={tailscaleHttpsEndpoint?.status === "available" ? undefined : remoteClientsDenial}
1171 />
1172 );
1173 const newestPairingLink = visibleDesktopPairingLinks.find(
1174 (pairingLink) => pairingLink.id === newestPairingLinkId,
1175 );
1176 const renderPairingClientsList = (
1177 pairingLinks: typeof visibleDesktopPairingLinks,
1178 clientSessions: typeof desktopClientSessions,
1179 ) => (
1180 <PairingClientsList
1181 servedByEnvironment={isPrimaryAccess}
1182 endpointUrl={desktopServerExposureState?.endpointUrl}
1183 endpoints={visibleDesktopAdvertisedEndpoints}
1184 defaultEndpointKey={defaultDesktopAdvertisedEndpointKey}
1185 isLoading={isLoadingDesktopAccessManagement}
1186 pairingLinks={pairingLinks}
1187 createdPairingCredentials={createdPairingCredentials}
1188 sharedPairingLinkId={newestPairingLinkId}
1189 clientSessions={clientSessions}
1190 revokingPairingLinkId={revokingDesktopPairingLinkId}
1191 revokingClientSessionId={revokingDesktopClientSessionId}
1192 onRevokePairingLink={handleRevokeDesktopPairingLink}
1193 onRevokeClientSession={requestRevokeClientSession}
1194 canRevoke={canWriteAccess}
1195 />
1196 );
1197 const renderAuthorizedClients = () => (
1198 <>
1199 {desktopAccessManagementError ? (
1200 <div className={ITEM_ROW_CLASSNAME}>
1201 <p className="text-xs text-destructive">{desktopAccessManagementError}</p>
1202 </div>
1203 ) : null}
1204 {renderPairingClientsList(visibleDesktopPairingLinks, desktopClientSessions)}
1205 </>
1206 );
1207 const renderNetworkAccessRow = () => (
1208 <SettingsRow
1209 title={searchableSetting("network-access").title}
1210 description={
1211 isLocalBackendNetworkAccessible ? (
1212 <NetworkAccessDescription
1213 endpoint={defaultDesktopNetworkAdvertisedEndpoint}
1214 hiddenEndpointCount={Math.max(visibleDesktopNetworkAdvertisedEndpoints.length - 1, 0)}
1215 expanded={isAdvertisedEndpointListExpanded}
1216 onToggleExpanded={() => setIsAdvertisedEndpointListExpanded((expanded) => !expanded)}
1217 fallback={
1218 desktopServerExposureState?.endpointUrl
1219 ? gt("Reachable at {url}", { url: desktopServerExposureState.endpointUrl })
1220 : desktopServerExposureState?.advertisedHost
1221 ? gt("Exposed on all interfaces. Pairing links use {host}.", {
1222 host: desktopServerExposureState.advertisedHost,
1223 })
1224 : gt("Exposed on all interfaces.")
1225 }
1226 />
1227 ) : desktopServerExposureState ? (
1228 gt("Limited to this machine.")
1229 ) : (
1230 gt("Loading…")
1231 )
1232 }
1233 status={
1234 desktopServerExposureError ? (
1235 <span className="block text-destructive">{desktopServerExposureError}</span>
1236 ) : null
1237 }
1238 control={renderNetworkAccessToggle()}
1239 managed={isLocalBackendNetworkAccessible ? undefined : remoteClientsDenial}
1240 />
1241 );
1242 const renderDisabledNetworkAccessRow = () => (
1243 <SettingsRow
1244 title={searchableSetting("network-access").title}
1245 description={
1246 desktopBridge
1247 ? gt("This connection cannot view or change network exposure.")
1248 : isLocalBackendNetworkAccessible
1249 ? gt(
1250 "Remote access is already configured. Change network exposure where the server starts.",
1251 )
1252 : currentAuthPolicy === "loopback-browser"
1253 ? gt(
1254 "Only this machine can connect. Restart with a non-loopback host for remote pairing.",
1255 )
1256 : gt("Network exposure information is unavailable.")
1257 }
1258 control={
1259 !desktopBridge &&
1260 (currentAuthPolicy === "remote-reachable" || currentAuthPolicy === "loopback-browser") ? (
1261 <Tooltip>
1262 <TooltipTrigger
1263 render={
1264 <span className="inline-flex">
1265 <Switch
1266 checked={isLocalBackendNetworkAccessible}
1267 disabled
1268 aria-label={gt("Enable network access")}
1269 />
1270 </span>
1271 }
1272 />
1273 <TooltipPopup side="top">
1274 <T>
1275 Network exposure changes restart the backend and must be controlled where the server
1276 process is launched.
1277 </T>
1278 </TooltipPopup>
1279 </Tooltip>
1280 ) : undefined
1281 }
1282 />
1283 );
1284
1285 const accessServerConfig = accessEnvironment?.serverConfig ?? null;
1286 const accessPolicy = accessServerConfig?.managedPolicy;
1287 const previewTunnelDenial =
1288 managedCapabilityDenial(accessPolicy, "previewTunnel", m) ??
1289 (accessPolicy !== undefined && isManagedSettingPath(accessPolicy, "enablePreviewTunnel")
1290 ? gt("Managed by {organization}.", { organization: accessPolicy.organization })
1291 : undefined);
1292 const primarySettings = (
1293 <>
1294 {accessEnvironmentPicker}
1295 {accessEnvironmentId !== null ? (
1296 <>
1297 <SettingsSection
1298 {...searchableSetting("connections-environment")}
1299 title={
1300 accessEnvironment?.label ??
1301 (desktopBridge ? gt("This machine") : gt("Primary environment"))
1302 }
1303 icon={
1304 <EnvironmentMachineIcon
1305 aria-hidden
1306 kind={
1307 accessServerConfig ? resolveEnvironmentMachineKind(accessServerConfig) : "desktop"
1308 }
1309 className="size-4"
1310 />
1311 }
1312 headerAction={
1313 accessEnvironmentId !== null ? (
1314 <Menu>
1315 <MenuTrigger
1316 render={
1317 <Button
1318 type="button"
1319 variant="ghost-muted"
1320 size="icon-xs"
1321 aria-label={gt("More actions for this machine")}
1322 />
1323 }
1324 >
1325 <EllipsisIcon className="size-3.5" />
1326 </MenuTrigger>
1327 <MenuPopup align="end">
1328 <EnvironmentIconMenu
1329 environmentId={accessEnvironmentId}
1330 serverConfig={accessServerConfig}
1331 />
1332 </MenuPopup>
1333 </Menu>
1334 ) : null
1335 }
1336 >
1337 {accessServerConfig?.managedPolicy ? (
1338 <div className="px-3 py-2 sm:px-4">
1339 <ManagedByOrganization policy={accessServerConfig.managedPolicy} />
1340 </div>
1341 ) : null}
1342 {canManageLocalBackend ? (
1343 <SettingsRow
1344 title={gt("Version")}
1345 description={
1346 primaryServerUpdateState.status !== "idle" ? (
1347 <ServerUpdateProgress state={primaryServerUpdateState} />
1348 ) : (
1349 [
1350 primaryServerConfig?.environment.serverVersion ?? null,
1351 primaryEnvironment?.displayUrl ?? null,
1352 ]
1353 .filter((value): value is string => value !== null)
1354 .join(" · ") || gt("Loading…")
1355 )
1356 }
1357 control={
1358 primaryVersionMismatch &&
1359 primaryEnvironmentId !== null &&
1360 primaryServerUpdateState.status !== "running" ? (
1361 <ServerUpdateAction
1362 size="sm"
1363 environmentId={primaryEnvironmentId}
1364 serverLabel={
1365 primaryEnvironment
1366 ? gt("{environment} server", { environment: primaryEnvironment.label })
1367 : gt("server")
1368 }
1369 selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
1370 installation={
1371 primaryServerConfig?.environment.capabilities.serverInstallation
1372 }
1373 desktopAppUpdate={supportsDesktopAppUpdate(primaryServerConfig)}
1374 targetVersion={primaryVersionMismatch.clientVersion}
1375 label={
1376 primaryServerUpdateState.status === "failed"
1377 ? gt("Retry update")
1378 : gt("Update to {version}", {
1379 version: primaryVersionMismatch.clientVersion,
1380 })
1381 }
1382 />
1383 ) : primaryServerUpdateState.status === "idle" && primaryServerConfig ? (
1384 <LocalVersionStatusLabel />
1385 ) : undefined
1386 }
1387 />
1388 ) : null}
1389 {canManageLocalBackend && desktopBridge ? (
1390 <>
1391 {renderNetworkAccessRow()}
1392 {renderEndpointRows()}
1393 {renderTailscaleRow()}
1394 {renderWslRow()}
1395 </>
1396 ) : canManageLocalBackend ? (
1397 renderDisabledNetworkAccessRow()
1398 ) : null}
1399 {canReadRelay || canManageRelay ? (
1400 <CloudLinkRow
1401 environmentId={accessEnvironmentId}
1402 canReadRelay={canReadRelay}
1403 canManageRelay={canManageRelay}
1404 connectDeviceApproval={
1405 accessServerConfig?.settings.requireConnectDeviceApproval === undefined
1406 ? null
1407 : {
1408 required: accessServerConfig.settings.requireConnectDeviceApproval,
1409 canManage: canWriteAccess,
1410 }
1411 }
1412 />
1413 ) : null}
1414 {accessServerConfig?.environment.capabilities.previewTunnelSetting ? (
1415 <SettingsRow
1416 title={searchableSetting("preview-tunnel").title}
1417 description={gt(
1418 "Lets other devices open this machine's local servers: browser tabs loaded on the device, Open on this device, and port forwarding. Off: browser tabs stream from this machine.",
1419 )}
1420 managed={previewTunnelDenial}
1421 control={
1422 <Switch
1423 checked={allowsPreviewTunnel(accessServerConfig)}
1424 disabled={!canWriteAccess}
1425 aria-label={gt("Allow the preview tunnel")}
1426 onCheckedChange={(enabled) =>
1427 void updateAccessSettings({ enablePreviewTunnel: enabled })
1428 }
1429 />
1430 }
1431 />
1432 ) : null}
1433 {accessEnvironment ? (
1434 <details className="group px-3 sm:px-4">
1435 <summary className="flex min-h-11 cursor-pointer list-none items-center gap-2 rounded-md text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring [&::-webkit-details-marker]:hidden">
1436 <T>Permissions</T>
1437 <ChevronRightIcon
1438 aria-hidden
1439 className="size-3 text-muted-foreground group-open:rotate-90"
1440 />
1441 </summary>
1442 <SessionPermissions
1443 environmentId={accessEnvironment.environmentId}
1444 connected={accessEnvironment.connection.phase === "connected"}
1445 />
1446 </details>
1447 ) : null}
1448 </SettingsSection>
1449
1450 {canReadAccess || canWriteAccess ? (
1451 <FoldedSettingsSection
1452 id="authorized-clients"
1453 title={gt("Authorized clients")}
1454 collapsedContent={
1455 canReadAccess && newestPairingLink
1456 ? renderPairingClientsList([newestPairingLink], [])
1457 : undefined
1458 }
1459 summary={summarizeAuthorizedClients(
1460 desktopClientSessions,
1461 visibleDesktopPairingLinks,
1462 m,
1463 )}
1464 control={
1465 canWriteAccess ? (
1466 <AuthorizedClientsHeaderAction
1467 environmentId={accessEnvironmentId}
1468 delegatableScopes={currentSessionScopes ?? []}
1469 onPairingLinkCreated={handlePairingLinkCreated}
1470 clientSessions={
1471 canReadAccess &&
1472 authAccessChanges.error === null &&
1473 authAccessChanges.data?.type === "snapshot"
1474 ? desktopClientSessions
1475 : null
1476 }
1477 isRevokingOtherClients={isRevokingOtherDesktopClients}
1478 onRevokeOtherClients={requestRevokeOtherClients}
1479 />
1480 ) : undefined
1481 }
1482 >
1483 <ScrollArea
1484 scrollFade
1485 chainVerticalScroll
1486 className="max-h-[22.5rem]"
1487 data-testid="authorized-clients-scroll-area"
1488 >
1489 {canReadAccess ? (
1490 renderAuthorizedClients()
1491 ) : (
1492 <p className="px-4 py-3 text-xs text-muted-foreground">
1493 <T>
1494 This connection can create access links but cannot view authorized clients.
1495 </T>
1496 </p>
1497 )}
1498 </ScrollArea>
1499 </FoldedSettingsSection>
1500 ) : null}
1501 {canReadAccess &&
1502 connectDevices !== null &&
1503 (connectDeviceRequests.length > 0 || connectDevices.length > 0) ? (
1504 <ConnectDeviceApprovalSettings
1505 environmentId={accessEnvironmentId}
1506 requests={connectDeviceRequests}
1507 devices={connectDevices}
1508 canWrite={canWriteAccess}
1509 requestRevoke={requestConnectRevoke}
1510 />
1511 ) : null}
1512 <RevokeConnectDeviceDialog
1513 request={pendingConnectRevoke}
1514 onClose={() => setPendingConnectRevoke(null)}
1515 requireApproval={requireConnectApproval}
1516 />
1517 <AlertDialog
1518 open={pendingDesktopServerExposureMode !== null && canManageLocalBackend}
1519 onOpenChange={(open) => {
1520 if (!open && !isUpdatingDesktopServerExposure)
1521 setPendingDesktopServerExposureMode(null);
1522 }}
1523 >
1524 <AlertDialogPopup>
1525 <AlertDialogHeader>
1526 <AlertDialogTitle>
1527 {pendingDesktopServerExposureMode === "network-accessible"
1528 ? gt("Enable network access?")
1529 : gt("Disable network access?")}
1530 </AlertDialogTitle>
1531 <AlertDialogDescription>
1532 {pendingDesktopServerExposureMode === "network-accessible"
1533 ? gt(
1534 "Let your other devices connect to T3 Code over the network. Pair devices to give them access. T3 Code will restart.",
1535 )
1536 : gt(
1537 "Devices connected over your local network will disconnect. Existing tunnels, such as T3 Connect or Tailscale HTTPS, keep working. T3 Code will restart.",
1538 )}
1539 </AlertDialogDescription>
1540 </AlertDialogHeader>
1541 <AlertDialogFooter>
1542 <AlertDialogClose
1543 disabled={isUpdatingDesktopServerExposure}
1544 render={<Button variant="outline" disabled={isUpdatingDesktopServerExposure} />}
1545 >
1546 <span className="[text-box:trim-both_cap_alphabetic]">
1547 <T>Cancel</T>
1548 </span>
1549 </AlertDialogClose>
1550 <Button
1551 variant="default"
1552 onClick={handleConfirmDesktopServerExposureChange}
1553 disabled={
1554 !canManageLocalBackend ||
1555 pendingDesktopServerExposureMode === null ||
1556 isUpdatingDesktopServerExposure
1557 }
1558 >
1559 {isUpdatingDesktopServerExposure && <Spinner size="sm" />}
1560 <span className="[text-box:trim-both_cap_alphabetic]">
1561 {isUpdatingDesktopServerExposure
1562 ? gt("Restarting…")
1563 : pendingDesktopServerExposureMode === "network-accessible"
1564 ? gt("Restart and enable")
1565 : gt("Restart and disable")}
1566 </span>
1567 </Button>
1568 </AlertDialogFooter>
1569 </AlertDialogPopup>
1570 </AlertDialog>
1571 <AlertDialog
1572 open={isWslConfirmDialogOpen && canManageLocalBackend}
1573 onOpenChange={(open) => {
1574 if (isUpdatingWslBackend) return;
1575 if (!open) setPendingWslChange(null);
1576 }}
1577 >
1578 <AlertDialogPopup>
1579 <AlertDialogHeader>
1580 <AlertDialogTitle>
1581 {pendingWslChange?.kind === "disable"
1582 ? pendingWslChange.wasWslOnly
1583 ? gt("Turn off WSL and switch back to Windows?")
1584 : gt("Disable WSL backend?")
1585 : pendingWslChange?.kind === "distro"
1586 ? gt("Switch WSL distro?")
1587 : pendingWslChange?.kind === "enable"
1588 ? gt("Start the WSL backend")
1589 : pendingWslChange?.nextValue
1590 ? gt("Run only the WSL backend?")
1591 : gt("Re-enable the Windows backend?")}
1592 </AlertDialogTitle>
1593 <AlertDialogDescription>
1594 {pendingWslChange?.kind === "disable"
1595 ? pendingWslChange.wasWslOnly
1596 ? gt(
1597 "T3 Code will restart on the Windows backend. Threads and projects opened against WSL stay safe inside the distro and become available again when you re-enable WSL.",
1598 )
1599 : gt(
1600 "The WSL backend will stop. Threads and projects opened against WSL stay safe inside the distro, but they'll be unavailable in T3 Code until you re-enable WSL.",
1601 )
1602 : pendingWslChange?.kind === "distro"
1603 ? gt(
1604 "T3 Code will restart the WSL backend on the new distro. Sessions still running on the current distro will be interrupted.",
1605 )
1606 : pendingWslChange?.kind === "enable"
1607 ? gt(
1608 "Run the WSL backend alongside the Windows one, or stop the Windows backend and use only WSL? You can change this later from Settings.",
1609 )
1610 : pendingWslChange?.nextValue
1611 ? gt(
1612 "T3 Code will restart and start only the WSL backend. Your Windows-side projects won't be accessible until you turn this off again.",
1613 )
1614 : gt(
1615 "T3 Code will restart and bring the Windows backend back up alongside WSL.",
1616 )}
1617 </AlertDialogDescription>
1618 </AlertDialogHeader>
1619 <AlertDialogFooter>
1620 <AlertDialogClose
1621 disabled={isUpdatingWslBackend}
1622 render={<Button variant="outline" disabled={isUpdatingWslBackend} />}
1623 >
1624 <T>Cancel</T>
1625 </AlertDialogClose>
1626 {pendingWslChange?.kind === "enable" ? (
1627 <>
1628 <Button
1629 variant="outline"
1630 onClick={() => handleConfirmEnableWsl("wsl-only")}
1631 disabled={isUpdatingWslBackend || !canManageLocalBackend}
1632 >
1633 {isUpdatingWslBackend ? (
1634 <>
1635 <Spinner size="sm" />
1636 <T>Applying…</T>
1637 </>
1638 ) : (
1639 gt("Use only WSL")
1640 )}
1641 </Button>
1642 <Button
1643 variant="default"
1644 onClick={() => handleConfirmEnableWsl("both")}
1645 disabled={isUpdatingWslBackend || !canManageLocalBackend}
1646 >
1647 {isUpdatingWslBackend ? (
1648 <>
1649 <Spinner size="sm" />
1650 <T>Applying…</T>
1651 </>
1652 ) : (
1653 gt("Run both backends")
1654 )}
1655 </Button>
1656 </>
1657 ) : (
1658 <Button
1659 variant={
1660 pendingWslChange?.kind === "disable" ||
1661 (pendingWslChange?.kind === "wsl-only" && pendingWslChange.nextValue)
1662 ? "destructive"
1663 : "default"
1664 }
1665 onClick={handleConfirmWslChange}
1666 disabled={isUpdatingWslBackend || !canManageLocalBackend}
1667 >
1668 {isUpdatingWslBackend ? (
1669 <>
1670 <Spinner size="sm" />
1671 <T>Applying…</T>
1672 </>
1673 ) : pendingWslChange?.kind === "disable" ? (
1674 pendingWslChange.wasWslOnly ? (
1675 gt("Switch to Windows")
1676 ) : (
1677 gt("Disable WSL")
1678 )
1679 ) : pendingWslChange?.kind === "distro" ? (
1680 gt("Switch distro")
1681 ) : pendingWslChange?.nextValue ? (
1682 gt("Restart and enable")
1683 ) : (
1684 gt("Restart and disable")
1685 )}
1686 </Button>
1687 )}
1688 </AlertDialogFooter>
1689 </AlertDialogPopup>
1690 </AlertDialog>
1691 <AlertDialog
1692 open={disableTailscaleServeDialogOpen && canManageLocalBackend}
1693 onOpenChange={(open) => {
1694 if (isUpdatingTailscaleServe) return;
1695 setDisableTailscaleServeDialogOpen(open);
1696 }}
1697 >
1698 <AlertDialogPopup>
1699 <AlertDialogHeader>
1700 <AlertDialogTitle>
1701 <T>Disable Tailscale HTTPS?</T>
1702 </AlertDialogTitle>
1703 <AlertDialogDescription>
1704 <T>T3 Code will restart the local backend without Tailscale Serve.</T>
1705 </AlertDialogDescription>
1706 </AlertDialogHeader>
1707 <AlertDialogFooter>
1708 <AlertDialogClose
1709 disabled={isUpdatingTailscaleServe}
1710 render={<Button variant="outline" disabled={isUpdatingTailscaleServe} />}
1711 >
1712 <T>Cancel</T>
1713 </AlertDialogClose>
1714 <Button
1715 variant="destructive"
1716 onClick={() => void handleConfirmTailscaleServeDisable()}
1717 disabled={isUpdatingTailscaleServe || !canManageLocalBackend}
1718 >
1719 {isUpdatingTailscaleServe ? (
1720 <>
1721 <Spinner size="sm" />
1722 <T>Restarting…</T>
1723 </>
1724 ) : (
1725 gt("Restart and disable")
1726 )}
1727 </Button>
1728 </AlertDialogFooter>
1729 </AlertDialogPopup>
1730 </AlertDialog>
1731 <Dialog
1732 open={pendingTailscaleServeEndpoint !== null}
1733 onOpenChange={(open) => {
1734 if (isUpdatingTailscaleServe) return;
1735 if (!open) setPendingTailscaleServeEndpoint(null);
1736 }}
1737 >
1738 <DialogPopup className="max-w-md">
1739 <DialogHeader>
1740 <DialogTitle>
1741 <T>Set up Tailscale HTTPS?</T>
1742 </DialogTitle>
1743 <DialogDescription>
1744 <T>
1745 T3 Code will restart the local backend with Tailscale Serve enabled and ask
1746 Tailscale to proxy HTTPS traffic to this backend.
1747 </T>
1748 </DialogDescription>
1749 </DialogHeader>
1750 <DialogPanel>
1751 <label className="block">
1752 <span className="text-sm font-medium text-foreground">
1753 <T>HTTPS port</T>
1754 </span>
1755 <Input
1756 className="mt-2"
1757 type="number"
1758 inputMode="numeric"
1759 min={1}
1760 max={65_535}
1761 step={1}
1762 value={tailscaleServePortInput}
1763 onChange={(event) => setTailscaleServePortInput(event.target.value)}
1764 disabled={isUpdatingTailscaleServe}
1765 />
1766 </label>
1767 {!isTailscaleServePortValid ? (
1768 <p className="mt-2 text-xs text-destructive">
1769 <T>Enter a port from 1 to 65535.</T>
1770 </p>
1771 ) : null}
1772 <div className="rounded-md border border-border/70 bg-muted/20 px-3 py-2">
1773 <p className="text-xs font-medium text-muted-foreground">
1774 <T>HTTPS endpoint</T>
1775 </p>
1776 <Tooltip>
1777 <TooltipTrigger
1778 render={
1779 <p className="mt-1 truncate text-sm text-foreground">
1780 {pendingTailscaleServeBaseUrl ?? gt("Pending MagicDNS endpoint")}
1781 </p>
1782 }
1783 />
1784 {pendingTailscaleServeBaseUrl ? (
1785 <TooltipPopup side="top">{pendingTailscaleServeBaseUrl}</TooltipPopup>
1786 ) : null}
1787 </Tooltip>
1788 </div>
1789 </DialogPanel>
1790 <DialogFooter>
1791 <DialogClose
1792 disabled={isUpdatingTailscaleServe}
1793 render={<Button variant="outline" disabled={isUpdatingTailscaleServe} />}
1794 >
1795 <T>Cancel</T>
1796 </DialogClose>
1797 <Button
1798 onClick={() => void handleConfirmTailscaleServeSetup()}
1799 disabled={isUpdatingTailscaleServe || !isTailscaleServePortValid}
1800 >
1801 {isUpdatingTailscaleServe ? (
1802 <>
1803 <Spinner size="sm" />
1804 <T>Restarting…</T>
1805 </>
1806 ) : (
1807 gt("Enable")
1808 )}
1809 </Button>
1810 </DialogFooter>
1811 </DialogPopup>
1812 </Dialog>
1813 </>
1814 ) : (
1815 <SettingsSection {...searchableSetting("connections-environment")}>
1816 <SettingsRow
1817 title={gt("No environment selected")}
1818 description={gt("Connect an environment to view its settings and access.")}
1819 />
1820 </SettingsSection>
1821 )}
1822 </>
1823 );
1824
1825 if (showsAccess) return <SettingsPageContainer>{primarySettings}</SettingsPageContainer>;
1826
1827 return (
1828 <SettingsPageContainer>
1829 {desktopBridge ? (
1830 <SettingsSection id="this-app" title={gt("This app")}>
1831 <LocalEnvironmentSetting />
1832 </SettingsSection>
1833 ) : null}
1834 <SettingsSection
1835 {...searchableSetting("remote-environments")}
1836 title={gt("Environments")}
1837 titleAction={
1838 roomForMap ? (
1839 <ToggleGroup
1840 aria-label={gt("Show environments as")}
1841 value={[environmentsView]}
1842 onValueChange={(next) => {
1843 const value = next[0];
1844 if (value === "map" || value === "list") setPickedEnvironmentsView(value);
1845 }}
1846 >
1847 <Toggle value="map">
1848 {gt("Map", { $context: "view switch: show machines as a diagram" })}
1849 </Toggle>
1850 <Toggle value="list">
1851 {gt("List", { $context: "view switch: show items as a list" })}
1852 </Toggle>
1853 </ToggleGroup>
1854 ) : null
1855 }
1856 headerAction={
1857 <div className="flex items-center gap-1">
1858 {savedServerUpdateTargets.length > 0 ? (
1859 <ServerUpdatesAction targets={savedServerUpdateTargets} variant="ghost-muted" />
1860 ) : null}
1861 {/* Actions on several machines at once, such as linking several, go here. */}
1862 <AddEnvironmentDialog
1863 key={`${addPrefill?.environmentId ?? "any"}:${addBackendHost}`}
1864 open={addBackendDialogOpen || addPrefill !== null}
1865 prefill={addPrefill}
1866 routeTarget={routeTarget}
1867 initialHost={addBackendHost}
1868 error={savedBackendError}
1869 savedEnvironments={savedEnvironments}
1870 onOpenChange={handleAddBackendDialogOpenChange}
1871 onErrorChange={setSavedBackendError}
1872 />
1873 </div>
1874 }
1875 >
1876 {environmentsView === "map" ? (
1877 <EnvironmentsMap
1878 footerId={searchableSetting("linked-environments").id}
1879 onAddEnvironment={openAddEnvironment}
1880 renderSavedEnvironment={(environment) =>
1881 listedEnvironments.some(
1882 (listed) => listed.environmentId === environment.environmentId,
1883 ) ? (
1884 <SavedBackendListRow
1885 key={environment.environmentId}
1886 environment={environment}
1887 initialRoutesOpen
1888 removingEnvironmentId={removingSavedEnvironmentId}
1889 onSetEnabled={handleSetSavedBackendEnabled}
1890 onRemove={handleRemoveSavedBackend}
1891 onAddRoute={openAddRoute}
1892 />
1893 ) : null
1894 }
1895 renderConnectMachine={(environmentId) => (
1896 <CloudRemoteEnvironmentRows
1897 only={environmentId}
1898 primaryEnvironmentId={primaryEnvironmentId}
1899 savedEnvironments={savedEnvironments}
1900 />
1901 )}
1902 />
1903 ) : (
1904 <>
1905 {listedEnvironments.map((environment) => (
1906 <SavedBackendListRow
1907 key={environment.environmentId}
1908 environment={environment}
1909 removingEnvironmentId={removingSavedEnvironmentId}
1910 onSetEnabled={handleSetSavedBackendEnabled}
1911 onRemove={handleRemoveSavedBackend}
1912 onAddRoute={openAddRoute}
1913 />
1914 ))}
1915 <CloudRemoteEnvironmentRows
1916 primaryEnvironmentId={primaryEnvironmentId}
1917 savedEnvironments={savedEnvironments}
1918 />
1919 </>
1920 )}
1921 </SettingsSection>
1922 {hasCloudPublicConfig() ? (
1923 <RemoveT3ConnectEnvironmentDialog
1924 environmentLabel={pendingT3ConnectRemoval?.label ?? null}
1925 environmentId={pendingT3ConnectRemoval?.environmentId ?? null}
1926 onCancel={() => setPendingT3ConnectRemoval(null)}
1927 onConfirm={() => {
1928 if (!pendingT3ConnectRemoval) return;
1929 setPendingT3ConnectRemoval(null);
1930 void removeSavedBackend(pendingT3ConnectRemoval);
1931 }}
1932 />
1933 ) : null}
1934 {environmentsView === "list"
1935 ? peerLinkHosts.map((environment, index) => (
1936 <LinkedEnvironmentsSettings
1937 key={environment.environmentId}
1938 environmentId={environment.environmentId}
1939 environmentLabel={peerLinkHosts.length > 1 ? environment.label : null}
1940 isSearchTarget={index === 0}
1941 />
1942 ))
1943 : null}
1944 <LoadBalancingSettings environments={loadBalancingEnvironments} />
1945 <PullRequestRoutingSettings environments={loadBalancingEnvironments} />
1946 </SettingsPageContainer>
1947 );
1948 }