feat(web): switch saved environments off instead of removing them (#11478)

Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5.1 authored and GitHub committed 2026-09-12 18:12:48 -07:00
1 parent 2db675aeff
commit 2587c8060c
40 files changed
+762 -173

No files matched your search

@@ -372,6 +372,7 @@ const migrateSavedEnvironmentRecords = Effect.fn(
profiles,
credentials,
remoteDpopTokens: [],
disabledEnvironmentIds: [],
};
});
+17 -1
View File
@@ -5,6 +5,7 @@ import {
putRemoteDpopTokenInCatalog,
registerConnectionInCatalog,
removeConnectionFromCatalog,
setConnectionEnabledInCatalog,
removeCatalogValue,
replaceCatalogValue,
} from "@t3tools/client-runtime/platform";
@@ -21,7 +22,12 @@ import * as Option from "effect/Option";
import * as CatalogStore from "./catalog-store";
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
operation:
| "list-targets"
| "list-disabled-targets"
| "register-connection"
| "remove-connection"
| "set-connection-enabled",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
@@ -39,6 +45,10 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
),
listDisabled: catalog.read.pipe(
Effect.map((document) => document.disabledEnvironmentIds),
Effect.mapError((error) => targetPersistenceError("list-disabled-targets", error)),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
@@ -49,6 +59,12 @@ export const connectionStorageLayer = Layer.effectContext(
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
setEnabled: (environmentId, enabled) =>
catalog
.update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
.pipe(
Effect.mapError((error) => targetPersistenceError("set-connection-enabled", error)),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -45,7 +45,8 @@ function ConfiguredConnectOnboardingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
const { connectedEnvironments, onSetEnvironmentEnabled, onRemoveEnvironmentPress } =
useRemoteConnections();
const { refreshRelayEnvironments } = useConnectionController();
const { connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
@@ -110,7 +111,8 @@ function ConfiguredConnectOnboardingRouteScreen() {
{isSignedIn ? (
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
onSetEnvironmentEnabled={onSetEnvironmentEnabled}
onRemoveEnvironment={onRemoveEnvironmentPress}
showHeader={false}
/>
) : (
@@ -33,7 +33,9 @@ import { type RelayEnvironmentView, useConnectionController } from "./useConnect
interface CloudEnvironmentRowsProps {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
readonly onSetEnvironmentEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
/** Long-press on a saved row. The callback owns the confirm. */
readonly onRemoveEnvironment: (environmentId: EnvironmentId) => void;
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
readonly showcaseSignedIn?: boolean;
/**
@@ -97,11 +99,6 @@ function CloudEnvironmentRowsContent(
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
@@ -144,8 +141,10 @@ function CloudEnvironmentRowsContent(
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
onSetEnabled={(enabled) =>
props.onSetEnvironmentEnabled(environment.environmentId, enabled)
}
onRemove={() => props.onRemoveEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
@@ -204,38 +203,42 @@ function CloudEnvironmentRowsContent(
);
}
/**
* A saved T3 Connect environment. The switch turns it on or off; off keeps the
* registration and cache but drops the connection and hides its errors.
* Long-press removes it from this device.
*/
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onSetEnabled: (enabled: boolean) => void;
readonly onRemove: () => void;
readonly onToggleError: () => void;
}) {
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(props.environment.environmentId),
);
const enabled = props.environment.isEnabled;
return (
<View>
<Pressable
accessibilityHint="Long press to remove from this device"
onLongPress={props.onRemove}
>
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
connectionError={enabled ? props.environment.connectionError : null}
connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
connectionState={enabled ? props.environment.connectionState : "available"}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
machine={resolveEnvironmentMachineKind(serverConfig)}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onValueChange={props.onSetEnabled}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
{...(enabled ? {} : { statusText: "Off" })}
value={enabled}
/>
</View>
</Pressable>
);
}
@@ -11,6 +11,7 @@ import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanim
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
import { ThemedSwitch } from "../../components/ThemedSwitch";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
@@ -18,6 +19,9 @@ import { serverEnvironment } from "../../state/server";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
if (!environment.isEnabled) {
return "Off";
}
return connectionStatusText({
phase: environment.connectionState,
error: environment.connectionError,
@@ -31,6 +35,7 @@ export function ConnectionEnvironmentRow(props: {
readonly onToggle: () => void;
readonly onReconnect: (environmentId: EnvironmentId) => void;
readonly onRemove: (environmentId: EnvironmentId) => void;
readonly onSetEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
readonly onUpdate: (
environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string },
@@ -41,12 +46,14 @@ export function ConnectionEnvironmentRow(props: {
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(props.environment.environmentId),
);
const enabled = props.environment.isEnabled;
const statusLabel = connectionStatusLabel(props.environment);
const statusTraceId = props.environment.connectionErrorTraceId;
const hasConnectionFailure = props.environment.connectionError !== null;
const statusTraceId = enabled ? props.environment.connectionErrorTraceId : null;
const hasConnectionFailure = enabled && props.environment.connectionError !== null;
const isRetrying =
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting";
enabled &&
(props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting");
const handleSave = useCallback(async () => {
const result = await props.onUpdate(props.environment.environmentId, {
label: label.trim(),
@@ -70,7 +77,7 @@ export function ConnectionEnvironmentRow(props: {
onPress={props.onToggle}
>
<ConnectionStatusDot
state={props.environment.connectionState}
state={enabled ? props.environment.connectionState : "available"}
pulse={isRetrying}
size={8}
/>
@@ -125,6 +132,10 @@ export function ConnectionEnvironmentRow(props: {
) : null}
</View>
<ThemedSwitch
onValueChange={(next) => props.onSetEnabled(props.environment.environmentId, next)}
value={enabled}
/>
<SymbolView
name="chevron.down"
size={12}
@@ -198,7 +209,8 @@ export function ConnectionEnvironmentRow(props: {
)}
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70 disabled:opacity-40"
disabled={!enabled}
onPress={() => props.onReconnect(props.environment.environmentId)}
>
<SymbolView
@@ -17,6 +17,7 @@ export function ConnectionsRouteScreen() {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onSetEnvironmentEnabled,
onUpdateEnvironment,
} = useRemoteConnections();
const navigation = useNavigation();
@@ -74,6 +75,7 @@ export function ConnectionsRouteScreen() {
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onSetEnabled={onSetEnvironmentEnabled}
onUpdate={onUpdateEnvironment}
/>
</View>
@@ -15,6 +15,7 @@ function connectedEnvironment(
environmentLabel: input.environmentLabel ?? input.environmentId,
displayUrl: input.displayUrl ?? `https://${input.environmentId}.example.test/`,
isRelayManaged: input.isRelayManaged,
isEnabled: input.isEnabled ?? true,
connectionState: input.connectionState ?? "connected",
connectionError: input.connectionError ?? null,
connectionErrorTraceId: input.connectionErrorTraceId ?? null,
@@ -40,6 +40,10 @@ export function useConnectionController() {
const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");
const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");
const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const setEnvironmentEnabledMutation = useAtomCommand(
environmentCatalog.setEnabled,
"environment toggle",
);
const refreshRelayEnvironments = useAtomCommand(
relayEnvironmentDiscovery.refresh,
"relay environment refresh",
@@ -93,6 +97,11 @@ export function useConnectionController() {
(environmentId: EnvironmentId) => retryEnvironmentMutation(environmentId),
[retryEnvironmentMutation],
);
const setEnvironmentEnabled = useCallback(
(environmentId: EnvironmentId, enabled: boolean) =>
setEnvironmentEnabledMutation({ environmentId, enabled }),
[setEnvironmentEnabledMutation],
);
const updateEnvironment = useCallback(
(
environmentId: EnvironmentId,
@@ -120,6 +129,7 @@ export function useConnectionController() {
connectRelayEnvironment,
removeEnvironment,
retryEnvironment,
setEnvironmentEnabled,
updateEnvironment,
refreshRelayEnvironments,
};
@@ -45,6 +45,7 @@ describe("workspace connection status", () => {
environmentLabel: "Julius’s Mac mini",
displayUrl: "",
isRelayManaged: false,
isEnabled: true,
connectionState: "reconnecting",
connectionError: null,
connectionErrorTraceId: null,
@@ -28,6 +28,7 @@ export function SettingsEnvironmentsRouteScreen() {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onSetEnvironmentEnabled,
onUpdateEnvironment,
} = useRemoteConnections();
const navigation = useNavigation();
@@ -136,6 +137,7 @@ export function SettingsEnvironmentsRouteScreen() {
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onSetEnabled={onSetEnvironmentEnabled}
onUpdate={handleUpdateEnvironment}
/>
</View>
@@ -163,7 +165,8 @@ export function SettingsEnvironmentsRouteScreen() {
user is signed out — the component gates discovery itself. */}
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
onSetEnvironmentEnabled={onSetEnvironmentEnabled}
onRemoveEnvironment={onRemoveEnvironmentPress}
{...(SHOWCASE_ENABLED
? {
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
@@ -17,6 +17,7 @@ function environment(
environmentLabel,
displayUrl,
isRelayManaged: false,
isEnabled: true,
connectionState: "connected",
connectionError: null,
connectionErrorTraceId: null,
@@ -43,6 +43,7 @@ export const SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: ReadonlyArray<ConnectedEnvir
environmentLabel: "Aurora GPU Pod",
displayUrl: "https://aurora-gpu.t3.sh",
isRelayManaged: true,
isEnabled: true,
connectionState: "connected",
connectionError: null,
connectionErrorTraceId: null,
@@ -29,7 +29,7 @@ function presentation(
serverConfig: ServerConfig | null = null,
): EnvironmentPresentation {
return {
entry: { target: target(environmentId, endpoint), profile: Option.none() },
entry: { target: target(environmentId, endpoint), profile: Option.none(), enabled: true },
connection: { phase: "connected", error: null, traceId: null },
serverConfig,
};
@@ -13,6 +13,8 @@ export interface ConnectedEnvironmentSummary {
readonly environmentLabel: string;
readonly displayUrl: string;
readonly isRelayManaged: boolean;
/** False when the user switched the environment off in Settings. */
readonly isEnabled: boolean;
readonly connectionState: EnvironmentConnectionPhase;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
@@ -94,6 +94,7 @@ export function useRemoteConnectionStatus() {
environmentLabel: environment.environmentLabel,
displayUrl: environment.displayUrl,
isRelayManaged: environment.isRelayManaged,
isEnabled: environment.isEnabled,
connectionState: environment.connectionState,
connectionError: environment.connectionError,
connectionErrorTraceId: environment.connectionErrorTraceId,
@@ -140,6 +141,11 @@ export function useRemoteConnections() {
(environmentId: EnvironmentId) => controller.retryEnvironment(environmentId),
[controller],
);
const onSetEnvironmentEnabled = useCallback(
(environmentId: EnvironmentId, enabled: boolean) =>
controller.setEnvironmentEnabled(environmentId, enabled),
[controller],
);
const onUpdateEnvironment = useCallback(
(
environmentId: EnvironmentId,
@@ -157,8 +163,8 @@ export function useRemoteConnections() {
return;
}
Alert.alert(
"Remove environment?",
`Disconnect and forget ${environment.environmentLabel} on this device.`,
"Remove from this device?",
`Forget ${environment.environmentLabel} and its cached threads on this device. Switch it off instead to keep it saved.`,
[
{ text: "Cancel", style: "cancel" },
{
@@ -184,6 +190,7 @@ export function useRemoteConnections() {
onChangeConnectionPairingUrl,
onConnectPress,
onReconnectEnvironment,
onSetEnvironmentEnabled,
onUpdateEnvironment,
onRemoveEnvironmentPress,
};
@@ -36,6 +36,7 @@ function environment(
wsBaseUrl: "wss://environment.example.test",
}),
),
enabled: true,
},
connection: {
phase,
+9 -4
View File
@@ -10,6 +10,7 @@ export interface WorkspaceEnvironment {
readonly environmentLabel: string;
readonly displayUrl: string;
readonly isRelayManaged: boolean;
readonly isEnabled: boolean;
readonly connectionState: EnvironmentConnectionPhase;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
@@ -38,6 +39,7 @@ export function projectWorkspaceEnvironment(
environmentLabel: environment.label,
displayUrl: environment.displayUrl ?? "",
isRelayManaged: environment.relayManaged,
isEnabled: environment.entry.enabled,
connectionState: environment.connection.phase,
connectionError: environment.connection.error,
connectionErrorTraceId: environment.connection.traceId,
@@ -78,7 +80,10 @@ export function projectWorkspaceState(input: {
readonly environments: ReadonlyArray<WorkspaceEnvironment>;
readonly shellSummary: EnvironmentShellSummary;
}): WorkspaceState {
const connectingEnvironments = input.environments.filter(
// Switched-off environments still count as saved connections, but they do
// not drive the overall connection state or surface their last error.
const activeEnvironments = input.environments.filter((environment) => environment.isEnabled);
const connectingEnvironments = activeEnvironments.filter(
(environment) =>
environment.connectionState === "connecting" ||
environment.connectionState === "reconnecting",
@@ -91,12 +96,12 @@ export function projectWorkspaceState(input: {
hasPendingShellSnapshot: input.shellSummary.hasSynchronizingShell,
hasReadyEnvironment:
input.networkStatus !== "offline" &&
input.environments.some((environment) => environment.connectionState === "connected"),
activeEnvironments.some((environment) => environment.connectionState === "connected"),
hasConnectingEnvironment: connectingEnvironments.length > 0,
connectingEnvironments,
connectionState: overallConnectionState(input.environments, input.networkStatus),
connectionState: overallConnectionState(activeEnvironments, input.networkStatus),
connectionError:
input.environments.find((environment) => environment.connectionError !== null)
activeEnvironments.find((environment) => environment.connectionError !== null)
?.connectionError ?? null,
shellSnapshotError: input.shellSummary.firstError,
latestCachedSnapshotReceivedAt: input.shellSummary.latestSnapshotUpdatedAt,
+34 -8
View File
@@ -4,6 +4,7 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { CircleArrowUpIcon } from "lucide-react";
import { type ComponentProps, useRef, useState } from "react";
import { requestConfirmDialog } from "~/confirmDialog";
@@ -44,8 +45,10 @@ export interface ServerUpdateTarget {
readonly continueThreadsAfterServerUpdate?: boolean;
}
type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size"> & {
type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
readonly label?: string;
/** "icon" renders a compact icon button with the label in a tooltip. */
readonly appearance?: "button" | "icon";
};
function useServerUpdate() {
@@ -94,6 +97,7 @@ export function ServerUpdatesAction({
label = "Update all",
variant = "outline",
size = "xs",
className,
}: UpdateButtonProps & {
readonly targets: ReadonlyArray<ServerUpdateTarget>;
}) {
@@ -133,6 +137,7 @@ export function ServerUpdatesAction({
<Button
size={size}
variant={variant}
className={className}
disabled={isPending || eligible.length === 0}
onClick={() => void handleUpdate()}
>
@@ -191,6 +196,8 @@ export function ServerUpdateAction({
label = "Update",
variant = "outline",
size = "xs",
className,
appearance = "button",
}: Omit<ServerUpdateTarget, "continueThreadsAfterServerUpdate"> & UpdateButtonProps) {
const isDesktopAppUpdate = selfUpdate === "desktop-managed";
const continueThreadsAfterServerUpdate = useEnvironmentSettings(
@@ -251,18 +258,37 @@ export function ServerUpdateAction({
);
}
if (selfUpdate === null) {
const command = manualServerUpdateCommand(targetVersion);
const manualCommand = selfUpdate === null ? manualServerUpdateCommand(targetVersion) : null;
const actionLabel = manualCommand !== null ? "Copy update command" : label;
const onClick =
manualCommand !== null
? () => copyToClipboard(manualCommand, { command: manualCommand })
: () => void handleUpdate();
if (appearance === "icon") {
return (
<Button size={size} variant={variant} onClick={() => copyToClipboard(command, { command })}>
Copy update command
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-xs"
variant="ghost"
className={className ?? "text-muted-foreground hover:text-foreground"}
aria-label={`${actionLabel} for ${serverLabel}`}
onClick={onClick}
/>
}
>
<CircleArrowUpIcon className="size-3.5" />
</TooltipTrigger>
<TooltipPopup side="top">{actionLabel}</TooltipPopup>
</Tooltip>
);
}
return (
<Button size={size} variant={variant} onClick={() => void handleUpdate()}>
{label}
<Button size={size} variant={variant} className={className} onClick={onClick}>
{actionLabel}
</Button>
);
}
@@ -1,5 +1,12 @@
import { ChevronsLeftRightEllipsisIcon, PlusIcon, QrCodeIcon, TerminalIcon } from "lucide-react";
import {
ChevronsLeftRightEllipsisIcon,
EllipsisIcon,
PlusIcon,
QrCodeIcon,
TerminalIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
import { Atom } from "effect/unstable/reactivity";
import {
type KeyboardEvent,
type ReactNode,
@@ -97,6 +104,7 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { QRCodeSvg } from "../ui/qr-code";
import { Spinner } from "../ui/spinner";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -145,10 +153,16 @@ import {
useEnvironments,
usePrimaryEnvironment,
} from "~/state/environments";
import { requestConfirmDialog } from "~/confirmDialog";
import { useAtomCommand } from "../../state/use-atom-command";
import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ServerUpdateAction, ServerUpdateProgress } from "../ServerUpdateAction";
import {
ServerUpdateAction,
ServerUpdateProgress,
ServerUpdatesAction,
type ServerUpdateTarget,
} from "../ServerUpdateAction";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
import {
@@ -1399,29 +1413,31 @@ function NetworkAccessDescription({
type SavedBackendListRowProps = {
environment: EnvironmentPresentation;
removingEnvironmentId: EnvironmentId | null;
onConnect: (environmentId: EnvironmentId) => void;
onRemove: (environmentId: EnvironmentId) => void;
onSetEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
onRemove: (environment: EnvironmentPresentation) => void;
};
function SavedBackendListRow({
environment,
removingEnvironmentId,
onConnect,
onSetEnabled,
onRemove,
}: SavedBackendListRowProps) {
const environmentId = environment.environmentId;
const enabled = environment.entry.enabled;
const connectionState = environment.connection.phase;
const isConnected = connectionState === "connected";
const isConnecting = connectionState === "connecting" || connectionState === "reconnecting";
const stateDotClassName =
connectionState === "connected"
const isRemoving = removingEnvironmentId === environmentId;
const stateDotClassName = !enabled
? "bg-muted-foreground/40"
: connectionState === "connected"
? "bg-success"
: connectionState === "connecting" || connectionState === "reconnecting"
? "bg-warning"
: connectionState === "error"
? "bg-destructive"
: "bg-muted-foreground/40";
const statusTooltip = connectionStatusText(environment.connection);
const statusTooltip = enabled ? connectionStatusText(environment.connection) : "Off";
const errorTraceId = environment.connection.traceId;
const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
target: "trace ID",
@@ -1461,6 +1477,7 @@ function SavedBackendListRow({
const metadataBits = [
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
environment.relayManaged ? "T3 Connect" : null,
enabled ? null : "Off",
].filter((value): value is string => value !== null);
// The WSL backend is a desktop-managed local backend (it surfaces as a bearer
@@ -1468,9 +1485,16 @@ function SavedBackendListRow({
// environment you connect to or remove here — its lifecycle is driven by the
// WSL on/off + distro picker on this page.
const isWslEnvironment = isDesktopLocalConnectionTarget(environment.entry.target);
// Only a connected, enabled machine can take a remote update; a switched-off
// one keeps the "update available" note so the icon is not a surprise later.
const showUpdateAction =
enabled &&
isConnected &&
versionMismatch !== null &&
(serverUpdateState.status === "idle" || serverUpdateState.status === "failed");
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={cn(ITEM_ROW_CLASSNAME, !enabled && "opacity-60")}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-h-5 items-center gap-1.5">
@@ -1478,7 +1502,7 @@ function SavedBackendListRow({
tooltipText={statusTooltip}
dotClassName={stateDotClassName}
pingClassName={
connectionState === "connecting" || connectionState === "reconnecting"
enabled && (connectionState === "connecting" || connectionState === "reconnecting")
? "bg-warning/60 duration-2000"
: null
}
@@ -1526,7 +1550,7 @@ function SavedBackendListRow({
</TooltipPopup>
</Tooltip>
) : null}
{environment.connection.error && !resumingServerUpdate ? (
{enabled && environment.connection.error && !resumingServerUpdate ? (
<p className="flex min-w-0 items-center gap-2 text-destructive text-xs">
<span className="min-w-0 break-words">
{connectionStatusText(environment.connection)}
@@ -1543,9 +1567,8 @@ function SavedBackendListRow({
</p>
) : null}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{versionMismatch &&
(serverUpdateState.status === "idle" || serverUpdateState.status === "failed") ? (
<div className="flex w-full shrink-0 items-center gap-1 sm:w-auto sm:justify-end">
{showUpdateAction ? (
<ServerUpdateAction
environmentId={environmentId}
serverLabel={`${environment.label} server`}
@@ -1553,7 +1576,8 @@ function SavedBackendListRow({
desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(environment.serverConfig)}
targetVersion={versionMismatch.clientVersion}
label={serverUpdateState.status === "failed" ? "Retry" : "Update"}
label={serverUpdateState.status === "failed" ? "Retry update" : "Update"}
appearance="icon"
/>
) : null}
{isWslEnvironment ? (
@@ -1571,32 +1595,44 @@ function SavedBackendListRow({
</Tooltip>
) : (
<>
{!isConnected ? (
<Button
size="xs"
variant="outline"
disabled={removingEnvironmentId === environmentId}
onClick={() => void onRemove(environmentId)}
<Tooltip>
<TooltipTrigger
render={
<Switch
size="sm"
checked={enabled}
disabled={isRemoving}
aria-label={`${enabled ? "Switch off" : "Switch on"} ${environment.label}`}
onCheckedChange={(checked) => onSetEnabled(environmentId, checked)}
/>
}
/>
<TooltipPopup side="top">{enabled ? "Switch off" : "Switch on"}</TooltipPopup>
</Tooltip>
<Menu>
<MenuTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-xs"
className="text-muted-foreground hover:text-foreground"
disabled={isRemoving}
aria-label={`More actions for ${environment.label}`}
/>
}
>
{removingEnvironmentId === environmentId ? "Removing…" : "Remove"}
</Button>
) : null}
<Button
size="xs"
variant="outline"
disabled={isConnecting || removingEnvironmentId === environmentId}
onClick={() =>
void (isConnected ? onRemove(environmentId) : onConnect(environmentId))
}
>
{isConnected
? removingEnvironmentId === environmentId
? "Disconnecting…"
: "Disconnect"
: isConnecting
? "Connecting…"
: "Connect"}
</Button>
<EllipsisIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end" className="min-w-52">
{errorTraceId ? (
<MenuItem onClick={() => copyTraceId(errorTraceId)}>Copy trace ID</MenuItem>
) : null}
<MenuItem variant="destructive" onClick={() => onRemove(environment)}>
{isRemoving ? "Removing…" : "Remove from this device…"}
</MenuItem>
</MenuPopup>
</Menu>
</>
)}
</div>
@@ -1781,7 +1817,9 @@ export function ConnectionsSettings() {
reportFailure: false,
});
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
reportFailure: false,
});
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
const primarySessionState = usePrimarySessionState();
const currentSessionScopes = desktopBridge
@@ -1797,6 +1835,59 @@ export function ConnectionsSettings() {
.toSorted((left, right) => left.label.localeCompare(right.label)),
[environments],
);
// Machines "Update all" can reach: switched on, connected, behind the client
// version, remotely updatable, and not already mid-update. The button only
// renders when this list is non-empty.
const savedServerUpdateStatesAtom = useMemo(
() =>
Atom.make((get) =>
savedEnvironments.map((environment) => ({
environment,
updateStatus: get(serverEnvironment.updateStateAtom(environment.environmentId)).status,
})),
),
[savedEnvironments],
);
const savedServerUpdateStates = useAtomValue(savedServerUpdateStatesAtom);
const savedServerUpdateTargets = useMemo(
() =>
savedServerUpdateStates.flatMap(({ environment, updateStatus }): ServerUpdateTarget[] => {
const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig);
const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig);
if (
!mismatch ||
updateStatus === "running" ||
!environment.entry.enabled ||
environment.connection.phase !== "connected" ||
isDesktopLocalConnectionTarget(environment.entry.target) ||
// Manual-update machines only offer a copy command on their row.
selfUpdate === null ||
(selfUpdate === "desktop-managed" && !desktopAppUpdate)
) {
return [];
}
return [
{
environmentId: environment.environmentId,
serverLabel: environment.label,
selfUpdate,
desktopAppUpdate,
threadContinuation: supportsServerUpdateThreadContinuation(environment.serverConfig),
continueThreadsAfterServerUpdate:
environment.serverConfig?.settings.continueThreadsAfterServerUpdate ?? false,
targetVersion: mismatch.clientVersion,
},
];
}),
[savedServerUpdateStates],
);
// Switched-off machines never receive threads, so they stay out of the
// load balancing list.
const loadBalancingEnvironments = useMemo(
() => environments.filter((environment) => environment.entry.enabled),
[environments],
);
const savedDesktopSshEnvironmentKeys = useMemo(() => {
const keys = new Set<string>();
for (const environment of savedEnvironments) {
@@ -2367,28 +2458,42 @@ export function ConnectionsSettings() {
],
);
const handleConnectSavedBackend = useCallback(
async (environmentId: EnvironmentId) => {
const handleSetSavedBackendEnabled = useCallback(
async (environmentId: EnvironmentId, enabled: boolean) => {
setSavedBackendError(null);
const result = await retryEnvironment(environmentId);
const result = await setEnvironmentEnabled({ environmentId, enabled });
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = error instanceof Error ? error.message : "Failed to connect backend.";
const message =
error instanceof Error
? error.message
: `Failed to switch the backend ${enabled ? "on" : "off"}.`;
setSavedBackendError(message);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not connect backend",
title: `Could not switch backend ${enabled ? "on" : "off"}`,
description: message,
}),
);
}
},
[retryEnvironment],
[setEnvironmentEnabled],
);
// Removing forgets the pairing, credentials, and cached threads on this
// device. Switching off is the reversible path, so removal always confirms.
const handleRemoveSavedBackend = useCallback(
async (environmentId: EnvironmentId) => {
async (environment: EnvironmentPresentation) => {
// Fail closed: no mounted confirm host means no removal.
const confirmed = await requestConfirmDialog(
`Remove ${environment.label} from this device?\nThis forgets its pairing, credentials, and cached threads here. Switch it off instead to keep it saved.`,
{ variant: "destructive" },
);
if (confirmed !== true) {
return;
}
const environmentId = environment.environmentId;
setRemovingSavedEnvironmentId(environmentId);
setSavedBackendError(null);
const result = await removeEnvironment(environmentId);
@@ -3524,65 +3629,75 @@ export function ConnectionsSettings() {
<SettingsSection
{...searchableSetting("remote-environments")}
headerAction={
<Dialog
open={addBackendDialogOpen}
onOpenChange={(open) => {
setAddBackendDialogOpen(open);
if (!open) {
setSavedBackendError(null);
}
}}
>
<Tooltip>
<TooltipTrigger
render={
<DialogTrigger
render={
<Button
size="xs"
variant="ghost"
className="font-normal text-muted-foreground/60 hover:text-muted-foreground"
aria-label="Add environment"
>
<PlusIcon className="size-3" />
<span>Add environment</span>
</Button>
}
/>
}
<div className="flex items-center gap-1">
{savedServerUpdateTargets.length > 0 ? (
<ServerUpdatesAction
targets={savedServerUpdateTargets}
variant="ghost"
className="font-normal text-muted-foreground/60 hover:text-muted-foreground"
/>
<TooltipPopup side="top">Add environment</TooltipPopup>
</Tooltip>
<DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Add Environment</DialogTitle>
<DialogDescription>Pair another environment to this client.</DialogDescription>
</DialogHeader>
<DialogPanel>
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
{renderConnectionModeCard({
mode: "remote",
title: "Remote link",
description: "Enter a backend host and pairing code.",
icon: <ChevronsLeftRightEllipsisIcon aria-hidden className="size-4" />,
})}
{desktopBridge
? renderConnectionModeCard({
mode: "ssh",
title: "SSH",
description: "Use local SSH config, agent, and tunnels for the backend.",
icon: <TerminalIcon aria-hidden className="size-4" />,
})
: null}
) : null}
<Dialog
open={addBackendDialogOpen}
onOpenChange={(open) => {
setAddBackendDialogOpen(open);
if (!open) {
setSavedBackendError(null);
}
}}
>
<Tooltip>
<TooltipTrigger
render={
<DialogTrigger
render={
<Button
size="xs"
variant="ghost"
className="font-normal text-muted-foreground/60 hover:text-muted-foreground"
aria-label="Add environment"
>
<PlusIcon className="size-3" />
<span>Add environment</span>
</Button>
}
/>
}
/>
<TooltipPopup side="top">Add environment</TooltipPopup>
</Tooltip>
<DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Add Environment</DialogTitle>
<DialogDescription>Pair another environment to this client.</DialogDescription>
</DialogHeader>
<DialogPanel>
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
{renderConnectionModeCard({
mode: "remote",
title: "Remote link",
description: "Enter a backend host and pairing code.",
icon: <ChevronsLeftRightEllipsisIcon aria-hidden className="size-4" />,
})}
{desktopBridge
? renderConnectionModeCard({
mode: "ssh",
title: "SSH",
description:
"Use local SSH config, agent, and tunnels for the backend.",
icon: <TerminalIcon aria-hidden className="size-4" />,
})
: null}
</div>
<AnimatedHeight>
{savedBackendMode === "ssh" ? renderSshFields() : renderRemoteModeBody()}
</AnimatedHeight>
</div>
<AnimatedHeight>
{savedBackendMode === "ssh" ? renderSshFields() : renderRemoteModeBody()}
</AnimatedHeight>
</div>
</DialogPanel>
</DialogPopup>
</Dialog>
</DialogPanel>
</DialogPopup>
</Dialog>
</div>
}
>
{savedEnvironments.map((environment) => (
@@ -3590,7 +3705,7 @@ export function ConnectionsSettings() {
key={environment.environmentId}
environment={environment}
removingEnvironmentId={removingSavedEnvironmentId}
onConnect={handleConnectSavedBackend}
onSetEnabled={handleSetSavedBackendEnabled}
onRemove={handleRemoveSavedBackend}
/>
))}
@@ -3599,7 +3714,7 @@ export function ConnectionsSettings() {
savedEnvironments={savedEnvironments}
/>
</SettingsSection>
<LoadBalancingSettings environments={environments} />
<LoadBalancingSettings environments={loadBalancingEnvironments} />
</SettingsPageContainer>
);
}
+1
View File
@@ -13,6 +13,7 @@ const emptyCatalog = {
profiles: [],
credentials: [],
remoteDpopTokens: [],
disabledEnvironmentIds: [],
} as const;
const decodeCatalog = Schema.decodeUnknownSync(Schema.fromJsonString(ConnectionCatalogDocument));
+11
View File
@@ -10,6 +10,7 @@ import {
registerConnectionInCatalog,
removeCatalogValue,
removeConnectionFromCatalog,
setConnectionEnabledInCatalog,
replaceCatalogValue,
} from "@t3tools/client-runtime/platform";
import { TokenStore } from "@t3tools/client-runtime/authorization";
@@ -99,8 +100,10 @@ function catalogError(operation: string, cause: unknown) {
function persistenceError(
operation:
| "list-targets"
| "list-disabled-targets"
| "register-connection"
| "remove-connection"
| "set-connection-enabled"
| "load-shell"
| "save-shell"
| "load-thread"
@@ -377,6 +380,10 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.map((document) => document.targets),
Effect.mapError((cause) => persistenceError("list-targets", cause)),
),
listDisabled: catalog.read.pipe(
Effect.map((document) => document.disabledEnvironmentIds),
Effect.mapError((cause) => persistenceError("list-disabled-targets", cause)),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
@@ -387,6 +394,10 @@ export const connectionStorageLayer = Layer.effectContext(
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
setEnabled: (environmentId, enabled) =>
catalog
.update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
.pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause))),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
+1
View File
@@ -51,6 +51,7 @@ function catalogState(environmentIds: readonly EnvironmentId[]): EnvironmentCata
label: environmentId,
}),
profile: Option.none(),
enabled: true,
},
]),
),
+6 -3
View File
@@ -8,7 +8,10 @@ import {
createShellEnvironmentAtoms,
type EnvironmentShellState,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentCatalogState } from "@t3tools/client-runtime/state/connections";
import {
type EnvironmentCatalogState,
enabledEnvironmentIds,
} from "@t3tools/client-runtime/state/connections";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
@@ -26,7 +29,7 @@ export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => {
if (Option.isNone(catalog)) {
return false;
}
for (const environmentId of catalog.value.entries.keys()) {
for (const environmentId of enabledEnvironmentIds(catalog.value)) {
if (Option.isSome(get(environmentShell.stateValueAtom(environmentId)).snapshot)) {
continue;
}
@@ -65,7 +68,7 @@ export function createAllEnvironmentProjectSnapshotsReadyAtom(input: {
) {
return false;
}
for (const environmentId of catalog.entries.keys()) {
for (const environmentId of enabledEnvironmentIds(catalog)) {
const shell = get(input.shellStateValueAtom(environmentId));
if (shell.status !== "live" || Option.isNone(shell.snapshot)) return false;
}
@@ -39,6 +39,8 @@ export type ConnectionProfile = typeof ConnectionProfile.Type;
export interface ConnectionCatalogEntry {
readonly target: ConnectionTarget;
readonly profile: Option.Option<ConnectionProfile>;
/** False when the user switched the environment off: saved, but never connects. */
readonly enabled: boolean;
}
export class BearerConnectionCredential extends Schema.TaggedClass<BearerConnectionCredential>()(
@@ -113,12 +115,14 @@ export function connectionRegistrationCatalogEntry(
return {
target: registration.target,
profile: Option.none(),
enabled: true,
};
case "BearerConnectionRegistration":
case "SshConnectionRegistration":
return {
target: registration.target,
profile: Option.some(registration.profile),
enabled: true,
};
}
}
@@ -185,6 +185,7 @@ describe("connection onboarding", () => {
wsBaseUrl: "ws://old.example.test/",
}),
),
enabled: true,
}),
credential: Option.some(new BearerConnectionCredential({ token: "bearer-token" })),
});
@@ -33,6 +33,7 @@ const ENTRY: ConnectionCatalogEntry = {
wsBaseUrl: "wss://environment.example.test",
}),
),
enabled: true,
};
function supervisorState(overrides: Partial<SupervisorConnectionState>): SupervisorConnectionState {
@@ -140,6 +140,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
readonly beforeRegistrationRemove?: (
target: ConnectionTarget,
) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
readonly initialDisabled?: ReadonlyArray<EnvironmentId>;
},
) {
const storedTargets = yield* Ref.make(
@@ -176,8 +177,12 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
);
const disconnectedSshTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
const storedDisabled = yield* Ref.make<ReadonlySet<EnvironmentId>>(
new Set(options?.initialDisabled ?? []),
);
const targetStore = Persistence.ConnectionTargetStore.of({
list: Ref.get(storedTargets).pipe(Effect.map((targets) => [...targets.values()])),
listDisabled: Ref.get(storedDisabled).pipe(Effect.map((ids) => [...ids])),
});
const registrationStore = Persistence.ConnectionRegistrationStore.of({
register: (registration) =>
@@ -237,6 +242,16 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
return next;
});
}),
setEnabled: (environmentId, enabled) =>
Ref.update(storedDisabled, (current) => {
const next = new Set(current);
if (enabled) {
next.delete(environmentId);
} else {
next.add(environmentId);
}
return next;
}),
});
const cacheStore = Persistence.EnvironmentCacheStore.of({
loadShell: (environmentId) =>
@@ -405,6 +420,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
profileReadCount,
storedCredentials,
storedRemoteTokens,
storedDisabled,
disconnectedSshTargets,
networkStatus,
};
@@ -653,6 +669,122 @@ describe("EnvironmentRegistry", () => {
}),
);
it.effect("switching an environment off disconnects it and persists the flag", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET]);
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.start;
yield* awaitConnectionState(
registry,
RELAY_TARGET.environmentId,
(state) => state.phase === "connected",
);
yield* registry.setEnabled(RELAY_TARGET.environmentId, false);
yield* awaitConnectionState(
registry,
RELAY_TARGET.environmentId,
(state) => state.phase === "available",
);
const entry = (yield* SubscriptionRef.get(registry.entries)).get(
RELAY_TARGET.environmentId,
);
expect(entry?.enabled).toBe(false);
expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(true);
expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
expect(yield* Ref.get(harness.releasedSessions)).toBe(1);
yield* registry.setEnabled(RELAY_TARGET.environmentId, true);
yield* awaitConnectionState(
registry,
RELAY_TARGET.environmentId,
(state) => state.phase === "connected",
);
expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(
false,
);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("re-registering a switched-off environment keeps it off", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
initialDisabled: [RELAY_TARGET.environmentId],
});
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.start;
yield* registry.register(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({ ...RELAY_TARGET, label: "Renamed" }),
}),
);
yield* Effect.yieldNow;
const entry = (yield* SubscriptionRef.get(registry.entries)).get(
RELAY_TARGET.environmentId,
);
expect(entry?.target.label).toBe("Renamed");
expect(entry?.enabled).toBe(false);
expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("switching an SSH environment off tears down its managed backend", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.start;
yield* awaitConnectionState(
registry,
SSH_CONNECTION.environmentId,
(state) => state.phase === "connected",
);
yield* registry.setEnabled(SSH_CONNECTION.environmentId, false);
yield* awaitConnectionState(
registry,
SSH_CONNECTION.environmentId,
(state) => state.phase === "available",
);
expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
expect((yield* Ref.get(harness.storedTargets)).has(SSH_CONNECTION.environmentId)).toBe(
true,
);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("does not connect a persisted environment that was switched off", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
initialDisabled: [RELAY_TARGET.environmentId],
});
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.start;
yield* Effect.yieldNow;
const entry = (yield* SubscriptionRef.get(registry.entries)).get(
RELAY_TARGET.environmentId,
);
expect(entry?.enabled).toBe(false);
expect((yield* registry.state(RELAY_TARGET.environmentId)).phase).toBe("available");
expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("moves durable streams to a replacement supervisor", () =>
Effect.gen(function* () {
const replacement = new RelayConnectionTarget({
@@ -90,6 +90,18 @@ export class EnvironmentRegistry extends Context.Service<
| PlatformEnvironmentRemovalError
>;
readonly retryNow: (environmentId: EnvironmentId) => Effect.Effect<void>;
/**
* Switches a saved environment on or off. Off drops the socket, stops the
* retry ladder, and persists so the next launch stays off. Registration,
* credentials, and cache are untouched.
*/
readonly setEnabled: (
environmentId: EnvironmentId,
enabled: boolean,
) => Effect.Effect<
void,
EnvironmentNotRegisteredError | Persistence.ConnectionPersistenceError
>;
readonly state: (
environmentId: EnvironmentId,
) => Effect.Effect<SupervisorConnectionState, EnvironmentNotRegisteredError>;
@@ -139,6 +151,7 @@ export const make = Effect.gen(function* () {
const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
const persistedTargets = yield* storage.list;
const disabledEnvironmentIds = new Set(yield* storage.listDisabled);
const initialEntries = new Map(
yield* Effect.forEach(
persistedTargets,
@@ -149,7 +162,11 @@ export const make = Effect.gen(function* () {
: Option.none();
return [
target.environmentId,
{ target, profile } satisfies ConnectionCatalogEntry,
{
target,
profile,
enabled: !disabledEnvironmentIds.has(target.environmentId),
} satisfies ConnectionCatalogEntry,
] as const;
}),
{ concurrency: "unbounded" },
@@ -261,7 +278,9 @@ export const make = Effect.gen(function* () {
Scope.provide(scope),
Effect.onError(() => Scope.close(scope, Exit.void)),
);
yield* supervisor.connect;
if (entry.enabled) {
yield* supervisor.connect;
}
yield* SubscriptionRef.update(serviceScopes, (current) => {
const next = new Map(current);
next.set(environmentId, { entry, supervisor, scope });
@@ -391,14 +410,19 @@ export const make = Effect.gen(function* () {
const register = Effect.fn("EnvironmentRegistry.register")(function* (
registration: ConnectionRegistration,
) {
const entry = connectionRegistrationCatalogEntry(registration);
const environmentId = entry.target.environmentId;
const registered = connectionRegistrationCatalogEntry(registration);
const environmentId = registered.target.environmentId;
yield* withLeaseLock(
environmentId,
Effect.gen(function* () {
if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
return;
}
// Editing a saved environment re-registers it; that must not switch a
// disabled one back on.
const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
const entry: ConnectionCatalogEntry =
previous === undefined ? registered : { ...registered, enabled: previous.enabled };
yield* registrations.register(registration);
yield* Ref.update(persistedTargetsByEnvironment, (current) => {
const next = new Map(current);
@@ -630,6 +654,65 @@ export const make = Effect.gen(function* () {
Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
Effect.withSpan("EnvironmentRegistry.retryNow"),
);
const setEnabled = Effect.fn("EnvironmentRegistry.setEnabled")(function* (
environmentId: EnvironmentId,
enabled: boolean,
) {
yield* withLeaseLock(
environmentId,
Effect.gen(function* () {
const entry = yield* getEntry(environmentId);
if (entry.enabled === enabled) {
return;
}
// Platform-managed environments are reconciled from the host and are
// never persisted, so only user-saved ones write the flag.
if (!(yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
yield* registrations.setEnabled(environmentId, enabled);
}
const next: ConnectionCatalogEntry = { ...entry, enabled };
// Update the lease in place so the supervisor keeps its generation and
// durable streams; `installEntryLocked` would tear it down instead.
const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
if (lease !== undefined) {
yield* SubscriptionRef.update(serviceScopes, (current) => {
const nextScopes = new Map(current);
nextScopes.set(environmentId, { ...lease, entry: next });
return nextScopes;
});
}
yield* SubscriptionRef.update(entries, (current) => {
const nextEntries = new Map(current);
nextEntries.set(environmentId, next);
return nextEntries;
});
if (lease !== undefined) {
yield* enabled ? lease.supervisor.connect : lease.supervisor.disconnect;
} else if (enabled) {
yield* createServiceScope(next);
}
// The supervisor only owns the RPC session. A managed SSH backend and
// its tunnel outlive it, so switching off tears those down as well.
if (
!enabled &&
entry.target._tag === "SshConnectionTarget" &&
Option.isSome(entry.profile) &&
isSshConnectionProfile(entry.profile.value)
) {
yield* ssh.disconnect(entry.profile.value.target).pipe(
Effect.tapError((error) =>
Effect.logWarning("Could not disconnect the switched-off SSH environment.", {
environmentId,
error,
}),
),
Effect.ignore,
);
}
}),
);
});
const state = Effect.fn("EnvironmentRegistry.state")(function* (environmentId: EnvironmentId) {
const supervisor = yield* acquireSupervisor(environmentId);
return yield* SubscriptionRef.get(supervisor.state);
@@ -669,6 +752,7 @@ export const make = Effect.gen(function* () {
remove,
removeRelayEnvironments,
retryNow,
setEnabled,
state,
stateChanges,
run,
@@ -45,7 +45,7 @@ function catalogEntry(
target: ConnectionTarget,
profile: Option.Option<ConnectionProfile> = Option.none(),
): ConnectionCatalogEntry {
return { target, profile };
return { target, profile, enabled: true };
}
function collectingTracer(spans: Array<string>): Tracer.Tracer {
@@ -56,11 +56,13 @@ const RELAY_TARGET = new RelayConnectionTarget({
const TARGET_ENTRY: ConnectionCatalogEntry = {
target: TARGET,
profile: Option.none(),
enabled: true,
};
const RELAY_ENTRY: ConnectionCatalogEntry = {
target: RELAY_TARGET,
profile: Option.none(),
enabled: true,
};
const PREPARED_CONNECTION: PreparedConnection = {
@@ -19,8 +19,10 @@ export class ConnectionPersistenceError extends Schema.TaggedError<ConnectionPer
{
operation: Schema.Literals([
"list-targets",
"list-disabled-targets",
"register-connection",
"remove-connection",
"set-connection-enabled",
"load-shell",
"save-shell",
"load-thread",
@@ -42,6 +44,8 @@ export class ConnectionTargetStore extends Context.Service<
ConnectionTargetStore,
{
readonly list: Effect.Effect<ReadonlyArray<ConnectionTarget>, ConnectionPersistenceError>;
/** Saved environments the user switched off. See `ConnectionRegistrationStore.setEnabled`. */
readonly listDisabled: Effect.Effect<ReadonlyArray<EnvironmentId>, ConnectionPersistenceError>;
}
>()("@t3tools/client-runtime/platform/persistence/ConnectionTargetStore") {}
@@ -52,6 +56,10 @@ export class ConnectionRegistrationStore extends Context.Service<
registration: ConnectionRegistration,
) => Effect.Effect<void, ConnectionPersistenceError>;
readonly remove: (target: ConnectionTarget) => Effect.Effect<void, ConnectionPersistenceError>;
readonly setEnabled: (
environmentId: EnvironmentId,
enabled: boolean,
) => Effect.Effect<void, ConnectionPersistenceError>;
}
>()("@t3tools/client-runtime/platform/persistence/ConnectionRegistrationStore") {}
@@ -22,9 +22,11 @@ import {
putRemoteDpopTokenInCatalog,
registerConnectionInCatalog,
removeConnectionFromCatalog,
setConnectionEnabledInCatalog,
} from "./storageDocument.ts";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const decodeCatalogDocument = Schema.decodeUnknownSync(ConnectionCatalogDocument);
const RELAY_TARGET = new RelayConnectionTarget({
environmentId: ENVIRONMENT_ID,
@@ -203,6 +205,54 @@ describe("ConnectionCatalogDocument", () => {
expect(putRemoteDpopTokenInCatalog(otherRelay, REMOTE_TOKEN)).toBe(otherRelay);
});
it("decodes a document written before the disabled list existed", () => {
const decoded = decodeCatalogDocument({
schemaVersion: 1,
targets: [],
profiles: [],
credentials: [],
remoteDpopTokens: [],
});
expect(decoded.disabledEnvironmentIds).toEqual([]);
});
it("switches a saved environment off and back on without touching its records", () => {
const registered = registerConnectionInCatalog(
EMPTY_CONNECTION_CATALOG_DOCUMENT,
new BearerConnectionRegistration({
target: BEARER_TARGET,
profile: BEARER_PROFILE,
credential: BEARER_CREDENTIAL,
}),
);
const disabled = setConnectionEnabledInCatalog(registered, ENVIRONMENT_ID, false);
expect(disabled.disabledEnvironmentIds).toEqual([ENVIRONMENT_ID]);
expect(disabled.targets).toEqual(registered.targets);
expect(disabled.credentials).toEqual(registered.credentials);
// Idempotent: switching off twice stores the id once.
expect(
setConnectionEnabledInCatalog(disabled, ENVIRONMENT_ID, false).disabledEnvironmentIds,
).toEqual([ENVIRONMENT_ID]);
expect(
setConnectionEnabledInCatalog(disabled, ENVIRONMENT_ID, true).disabledEnvironmentIds,
).toEqual([]);
// Re-registering (editing label or URL) keeps the flag.
expect(
registerConnectionInCatalog(
disabled,
new BearerConnectionRegistration({
target: BEARER_TARGET,
profile: BEARER_PROFILE,
credential: BEARER_CREDENTIAL,
}),
).disabledEnvironmentIds,
).toEqual([ENVIRONMENT_ID]);
expect(removeConnectionFromCatalog(disabled, BEARER_TARGET).disabledEnvironmentIds).toEqual([]);
});
it("persists the normalized SSH profile beside its target", () => {
const target = new SshConnectionTarget({
environmentId: ENVIRONMENT_ID,
@@ -1,3 +1,5 @@
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import {
@@ -20,6 +22,12 @@ export const ConnectionCatalogDocument = Schema.Struct({
profiles: Schema.Array(ConnectionProfile),
credentials: Schema.Array(StoredConnectionCredential),
remoteDpopTokens: Schema.Array(TokenStore.RemoteDpopAccessToken),
// Saved environments the user switched off. They stay registered with their
// credentials and cache but never connect until switched back on. Older
// documents predate the key, so decoding defaults it to none.
disabledEnvironmentIds: Schema.Array(EnvironmentId).pipe(
Schema.withDecodingDefaultKey(Effect.succeed([])),
),
});
export type ConnectionCatalogDocument = typeof ConnectionCatalogDocument.Type;
@@ -29,6 +37,7 @@ export const EMPTY_CONNECTION_CATALOG_DOCUMENT: ConnectionCatalogDocument = Obje
profiles: [],
credentials: [],
remoteDpopTokens: [],
disabledEnvironmentIds: [],
});
export function replaceCatalogValue<A>(
@@ -87,6 +96,11 @@ function removeConnectionMetadata(
target.environmentId,
)
: document.remoteDpopTokens,
// Re-registration passes `removeRemoteToken: false` and must keep the
// switched-off flag; only a real removal clears it.
disabledEnvironmentIds: removeRemoteToken
? removeCatalogValue(document.disabledEnvironmentIds, (value) => value, target.environmentId)
: document.disabledEnvironmentIds,
};
}
@@ -100,6 +114,8 @@ export function registerConnectionInCatalog(
);
const cleaned =
previous === undefined ? document : removeConnectionMetadata(document, previous, false);
// Re-registering (for example editing a label or URL) keeps the disabled
// flag; only `setConnectionEnabledInCatalog` or removal changes it.
const next: ConnectionCatalogDocument = {
...cleaned,
targets: replaceCatalogValue(cleaned.targets, (value) => value.environmentId, target),
@@ -140,6 +156,24 @@ export function removeConnectionFromCatalog(
return removeConnectionMetadata(document, target, true);
}
/** Flips the disabled flag for a saved environment; unknown ids are ignored. */
export function setConnectionEnabledInCatalog(
document: ConnectionCatalogDocument,
environmentId: EnvironmentId,
enabled: boolean,
): ConnectionCatalogDocument {
const registered = document.targets.some((target) => target.environmentId === environmentId);
const without = removeCatalogValue(
document.disabledEnvironmentIds,
(value) => value,
environmentId,
);
return {
...document,
disabledEnvironmentIds: registered && !enabled ? [...without, environmentId] : without,
};
}
export function putRemoteDpopTokenInCatalog(
document: ConnectionCatalogDocument,
token: TokenStore.RemoteDpopAccessToken,
@@ -20,6 +20,21 @@ export interface EnvironmentCatalogState {
readonly entries: ReadonlyMap<EnvironmentIdType, ConnectionCatalogEntry>;
}
/**
* Environments that take part in the workspace: projects, threads, and shell
* summaries only come from these. Disabled environments stay in `entries` so
* Settings can list them and switch them back on.
*/
export function* enabledEnvironmentIds(
catalog: EnvironmentCatalogState,
): Generator<EnvironmentIdType> {
for (const [environmentId, entry] of catalog.entries) {
if (entry.enabled) {
yield environmentId;
}
}
}
const EMPTY_ENVIRONMENT_CATALOG_STATE: EnvironmentCatalogState = Object.freeze({
isReady: false,
entries: new Map(),
@@ -106,6 +121,15 @@ export function createEnvironmentCatalogAtoms<R, E>(
Effect.flatMap((registry) => registry.removeRelayEnvironments()),
),
});
const setEnabled = createRuntimeCommand(runtime, {
label: "environment-catalog:set-enabled",
scheduler: commandScheduler,
concurrency: serial,
execute: (input: { readonly environmentId: EnvironmentIdType; readonly enabled: boolean }) =>
EnvironmentRegistry.EnvironmentRegistry.pipe(
Effect.flatMap((registry) => registry.setEnabled(input.environmentId, input.enabled)),
),
});
const retryNow = createRuntimeCommand(runtime, {
label: "environment-catalog:retry-now",
scheduler: commandScheduler,
@@ -126,5 +150,6 @@ export function createEnvironmentCatalogAtoms<R, E>(
remove,
removeRelayEnvironments,
retryNow,
setEnabled,
};
}
@@ -151,7 +151,10 @@ function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState
};
}
function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [ENVIRONMENT_ID]) {
function makeHarness(
environmentIds: ReadonlyArray<EnvironmentId> = [ENVIRONMENT_ID],
disabledEnvironmentIds: ReadonlySet<EnvironmentId> = new Set(),
) {
const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
);
@@ -171,6 +174,7 @@ function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [ENVIRONMENT
wsBaseUrl: "wss://example.test",
}),
profile: Option.none(),
enabled: !disabledEnvironmentIds.has(environmentId),
},
]),
),
@@ -361,6 +365,23 @@ describe("environment entity projections", () => {
}
});
it("hides projects and threads of a switched-off environment while keeping its cache", () => {
const offEnvironmentId = EnvironmentId.make("off-environment");
const harness = makeHarness([ENVIRONMENT_ID, offEnvironmentId], new Set([offEnvironmentId]));
const projects = harness.registry.get(harness.projects.projectsAtom);
const threads = harness.registry.get(harness.threadShells.threadShellsAtom);
expect(projects.every((project) => project.environmentId === ENVIRONMENT_ID)).toBe(true);
expect(projects).toHaveLength(2);
expect(threads.every((thread) => thread.environmentId === ENVIRONMENT_ID)).toBe(true);
expect(threads).toHaveLength(2);
// The per-environment atoms still read the cached snapshot, so switching
// back on restores the rows without a refetch.
expect(
harness.registry.get(harness.projects.environmentProjectsAtom(offEnvironmentId)),
).toHaveLength(2);
});
it("keeps scoped identities and list order across project and environment changes", () => {
const remoteEnvironmentId = EnvironmentId.make("remote-environment");
const harness = makeHarness([ENVIRONMENT_ID, remoteEnvironmentId]);
@@ -9,7 +9,7 @@ import { Atom } from "effect/unstable/reactivity";
import type { EnvironmentProject } from "./models.ts";
import { scopeProject } from "./models.ts";
import type { EnvironmentCatalogState } from "./connections.ts";
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
import { arrayElementsEqual, parseProjectKey, projectKey, projectRefsEqual } from "./entities.ts";
const EMPTY_PROJECTS: ReadonlyArray<OrchestrationProjectShell> = Object.freeze([]);
@@ -71,7 +71,7 @@ export function createEnvironmentProjectAtoms(input: {
let previousProjectRefs: ReadonlyArray<ScopedProjectRef> = [];
const projectRefsAtom = Atom.make((get) => {
const refs: ScopedProjectRef[] = [];
for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
refs.push(...get(environmentProjectRefsAtom(environmentId)));
}
if (projectRefsEqual(previousProjectRefs, refs)) {
@@ -20,6 +20,7 @@ function environmentEntry(environmentId: EnvironmentId, label: string) {
wsBaseUrl: `wss://${environmentId}.example.test`,
}),
profile: Option.none(),
enabled: true,
};
}
+3 -3
View File
@@ -24,7 +24,7 @@ import { subscribeDynamic } from "../rpc/client.ts";
import type { RpcSession } from "../rpc/session.ts";
import { ShellSnapshotLoader } from "./shellSnapshotHttp.ts";
import { applyShellStreamEvent } from "./shellReducer.ts";
import type { EnvironmentCatalogState } from "./connections.ts";
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
import { followStreamInEnvironment } from "./runtime.ts";
export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
@@ -342,7 +342,7 @@ export function createEnvironmentShellSummaryAtom(input: {
let firstError: string | null = null;
let latestSnapshotUpdatedAt: string | null = null;
for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
const state = get(input.shellStateValueAtom(environmentId));
hasSynchronizingShell ||= state.status === "synchronizing";
hasCachedShell ||= state.status === "cached";
@@ -383,7 +383,7 @@ export function createEnvironmentServerConfigsAtom(input: {
let previousServerConfigs = EMPTY_SERVER_CONFIGS;
return Atom.make((get) => {
const next = new Map<EnvironmentId, ServerConfig>();
for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
const config = get(input.serverConfigValueAtom(environmentId));
if (config !== null) {
next.set(environmentId, config);
@@ -11,7 +11,7 @@ import { Atom } from "effect/unstable/reactivity";
import type { EnvironmentThreadShell } from "./models.ts";
import { scopeThreadShell } from "./models.ts";
import type { EnvironmentCatalogState } from "./connections.ts";
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
import {
arrayElementsEqual,
parseProjectRefCollectionKey,
@@ -174,7 +174,7 @@ export function createEnvironmentThreadShellAtoms(input: {
let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
const threadRefsAtom = Atom.make((get) => {
const refs: ScopedThreadRef[] = [];
for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
refs.push(...get(environmentThreadRefsAtom(environmentId)));
}
if (threadRefsEqual(previousThreadRefs, refs)) {
@@ -187,7 +187,7 @@ export function createEnvironmentThreadShellAtoms(input: {
let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
const threadShellsAtom = Atom.make((get) => {
const next: EnvironmentThreadShell[] = [];
for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
for (const thread of get(environmentThreadsAtom(environmentId))) {
next.push(scopedThread(environmentId, thread));
}
@@ -181,6 +181,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
remove: () => Effect.die("Unexpected environment removal"),
removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
retryNow: () => Effect.void,
setEnabled: () => Effect.die("Unexpected environment toggle"),
state: () => SubscriptionRef.get(supervisor.state),
stateChanges: () => SubscriptionRef.changes(supervisor.state),
run: (_environmentId, effect) =>