feat(web): flatten the connections page into one environments list (#11672)

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-13 19:40:19 -07:00
1 parent 2d73746502
commit 5e961d3d7f
13 files changed
+720 -586

No files matched your search

@@ -175,7 +175,7 @@ describe("cloud onboarding discovery", () => {
finishDiscovery(linkedMachines);
});
expect(onDiscoveryReady).toHaveBeenCalledTimes(1);
expect(renderer!.root.findByType("button").children).toEqual(["Connect"]);
expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
});
it("connects and selects discovered computers by default without overwriting deselection", async () => {
@@ -232,7 +232,7 @@ describe("cloud onboarding discovery", () => {
expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
"Work laptop",
]);
expect(renderer!.root.findByType("button").children).toEqual(["Connect"]);
expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
await advance(30_000);
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
});
@@ -240,7 +240,7 @@ describe("cloud onboarding discovery", () => {
it("keeps a discovered computer visible when it is added to the browser", async () => {
discovery.listEnvironments.mockResolvedValue(linkedMachines);
await mount();
expect(renderer!.root.findByType("button").children).toEqual(["Connect"]);
expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
await act(async () => {
renderer!.update(
<CloudEnvironmentConnectRows
@@ -288,12 +288,13 @@ export function CloudEnvironmentConnectRows({
const statusText = savedConnection
? savedConnection.statusText
: availability === "online"
? "Available · Relay online"
? "T3 Connect · Not added · Relay online"
: availability === "offline"
? "Available · Relay offline"
? "T3 Connect · Not added · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable");
? "T3 Connect · Not added · Checking relay status…"
: (Option.getOrNull(error)?.message ??
"T3 Connect · Not added · Relay status unavailable");
if (selection) {
return (
<label
@@ -386,7 +387,7 @@ export function CloudEnvironmentConnectRows({
disabled={connectingEnvironmentIds.size > 0}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentIds.has(environment.environmentId) ? "Connecting…" : "Connect"}
{connectingEnvironmentIds.has(environment.environmentId) ? "Adding…" : "Add"}
</Button>
)}
</div>
@@ -6,7 +6,6 @@ import {
TerminalIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
import { useLocation } from "@tanstack/react-router";
import { Atom } from "effect/unstable/reactivity";
import {
type KeyboardEvent,
@@ -42,7 +41,7 @@ import {
type EnvironmentId,
resolveEnvironmentMachineKind,
} from "@t3tools/contracts";
import { connectionStatusText, connectionStatusTitle } from "@t3tools/client-runtime/connection";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -67,8 +66,14 @@ import {
useRelativeTimeTick,
} from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
import { EnvironmentIconPicker } from "./EnvironmentIconPicker";
import { LoadBalancingPreference, LoadBalancingSettings } from "./LoadBalancingSettings";
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
import {
EnvironmentRow,
environmentTransportLabel,
formatDesktopSshTarget,
} from "./EnvironmentRow";
import { FoldedSettingsSection } from "./FoldedSettingsSection";
import { LoadBalancingSettings } from "./LoadBalancingSettings";
import { GitHubRoutingSettings } from "./GitHubRoutingSettings";
import { Input } from "../ui/input";
import { CommandShortcut } from "../ui/command";
@@ -106,7 +111,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 { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -158,7 +163,7 @@ import {
import { requestConfirmDialog } from "~/confirmDialog";
import { useAtomCommand } from "../../state/use-atom-command";
import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
import { ConnectionStatusDot, connectionPhaseDotClassName } from "../ConnectionStatusDot";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import {
ServerUpdateAction,
ServerUpdateProgress,
@@ -288,11 +293,6 @@ function AccessScopeSummary({
);
}
function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): string {
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
return target.port ? `${authority}:${target.port}` : authority;
}
function parseManualDesktopSshTarget(input: {
readonly host: string;
readonly username: string;
@@ -436,6 +436,20 @@ function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>)
);
}
/** Closed-header summary for the Authorized clients fold. */
function summarizeAuthorizedClients(
sessions: ReadonlyArray<ServerClientSessionRecord>,
links: ReadonlyArray<ServerPairingLinkRecord>,
): string {
const parts = [
`${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`,
links.length > 0
? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}`
: null,
];
return parts.filter((part): part is string => part !== null).join(" · ");
}
function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
return [...sessions].toSorted((left, right) => {
if (left.current !== right.current) {
@@ -1419,6 +1433,44 @@ type SavedBackendListRowProps = {
onRemove: (environment: EnvironmentPresentation) => void;
};
/**
* Status word for a row subtitle: "Reconnecting: <reason>" instead of the
* long-form sentence, since the row has one line and the full text is one
* hover away.
*/
function savedBackendStatus(environment: EnvironmentPresentation): {
readonly text: string;
readonly tone: "muted" | "error";
} {
if (!environment.entry.enabled) return { text: "Off", tone: "muted" };
const { connection } = environment;
switch (connection.phase) {
case "connected":
return { text: "Connected", tone: "muted" };
case "connecting":
return { text: "Connecting", tone: "muted" };
case "reconnecting":
return {
text: connection.error ? `Reconnecting: ${connection.error}` : "Reconnecting",
tone: "error",
};
case "error":
return {
text: connection.error ? `Connection failed: ${connection.error}` : "Connection failed",
tone: "error",
};
case "offline":
return { text: "Offline", tone: "muted" };
case "available":
return { text: "Not connected", tone: "muted" };
}
}
/**
* One added machine in the Environments list. The switch is the main action;
* the update icon appears only when that machine can take an update; the
* row menu holds the icon override, trace ID, and removal.
*/
function SavedBackendListRow({
environment,
removingEnvironmentId,
@@ -1427,19 +1479,8 @@ function SavedBackendListRow({
}: SavedBackendListRowProps) {
const environmentId = environment.environmentId;
const enabled = environment.entry.enabled;
const connectionState = environment.connection.phase;
const isConnected = connectionState === "connected";
const isConnected = environment.connection.phase === "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 = enabled ? connectionStatusText(environment.connection) : "Off";
const errorTraceId = environment.connection.traceId;
const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
target: "trace ID",
@@ -1470,25 +1511,18 @@ function SavedBackendListRow({
const serverUpdateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
const resumingServerUpdate =
serverUpdateState.status === "running" && serverUpdateState.stage === "resuming";
const sshTarget =
environment.entry.target._tag === "SshConnectionTarget" &&
Option.isSome(environment.entry.profile) &&
environment.entry.profile.value._tag === "SshConnectionProfile"
? environment.entry.profile.value.target
: null;
const metadataBits = [
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
environment.relayManaged ? "T3 Connect" : null,
enabled ? null : "Off",
].filter((value): value is string => value !== null);
const status = savedBackendStatus(environment);
const serverVersion = environment.serverConfig?.environment.serverVersion ?? null;
const subtitleText = [
environmentTransportLabel(environment),
resumingServerUpdate ? "Restarting" : status.text,
enabled && versionMismatch ? serverVersion : null,
]
.filter((value): value is string => value !== null)
.join(" · ");
// The WSL backend is a desktop-managed local backend (it surfaces as a bearer
// environment whose connection id is prefixed "local:"), not a remote
// 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.
// one keeps the version note so the icon is not a surprise later.
const showUpdateAction =
enabled &&
isConnected &&
@@ -1496,153 +1530,96 @@ function SavedBackendListRow({
(serverUpdateState.status === "idle" || serverUpdateState.status === "failed");
return (
<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 flex-wrap items-center gap-x-3 gap-y-2">
<div className="flex min-h-5 min-w-0 max-w-full items-center gap-1.5">
<ConnectionStatusDot
tooltipText={statusTooltip}
dotClassName={stateDotClassName}
pingClassName={
enabled &&
(connectionState === "connecting" || connectionState === "reconnecting")
? "bg-warning/60 duration-2000"
: null
}
<EnvironmentRow
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
label={environment.label}
dimmed={!enabled}
subtitle={
<Tooltip>
<TooltipTrigger
render={
<span
className={cn(
"block truncate",
enabled && status.tone === "error" && !resumingServerUpdate && "text-destructive",
)}
/>
<EnvironmentMachineIcon
aria-hidden
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
className="size-3.5 shrink-0 text-muted-foreground"
/>
<h3 className="min-w-0 truncate text-sm font-medium text-foreground">
{environment.label}
</h3>
</div>
{isConnected ? (
<div className="w-full sm:w-auto">
<EnvironmentIconPicker
environmentId={environmentId}
serverConfig={environment.serverConfig}
size="xs"
/>
</div>
) : null}
}
>
{subtitleText}
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{enabled ? connectionStatusText(environment.connection) : "Switched off"}
{versionMismatch
? `\nUpdate available: ${versionMismatch.serverVersion} → ${versionMismatch.clientVersion}`
: ""}
</TooltipPopup>
</Tooltip>
}
below={
serverUpdateState.status !== "idle" ? (
<div className="mt-1 max-w-md">
<ServerUpdateProgress state={serverUpdateState} />
</div>
{metadataBits.length > 0 ? (
<p className="truncate text-xs text-muted-foreground">{metadataBits.join(" · ")}</p>
) : null}
{serverUpdateState.status !== "idle" ? (
<div className="max-w-md">
<ServerUpdateProgress state={serverUpdateState} />
</div>
) : versionMismatch ? (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="w-fit cursor-help rounded-sm text-left text-muted-foreground text-xs"
>
Server update available
</button>
}
/>
<TooltipPopup side="top">
{versionMismatch.serverVersion} <span aria-hidden="true">→</span>{" "}
{versionMismatch.clientVersion}
</TooltipPopup>
</Tooltip>
) : null}
{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)}
</span>
{errorTraceId ? (
<button
type="button"
className="shrink-0 underline underline-offset-2"
onClick={() => copyTraceId(errorTraceId)}
>
Copy trace ID
</button>
) : null}
</p>
) : null}
</div>
<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`}
selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(environment.serverConfig)}
targetVersion={versionMismatch.clientVersion}
label={serverUpdateState.status === "failed" ? "Retry update" : "Update"}
appearance="icon"
) : null
}
>
{showUpdateAction ? (
<ServerUpdateAction
environmentId={environmentId}
serverLabel={`${environment.label} server`}
selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(environment.serverConfig)}
targetVersion={versionMismatch.clientVersion}
label={serverUpdateState.status === "failed" ? "Retry update" : "Update"}
appearance="icon"
/>
) : null}
<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}`}
/>
}
>
<EllipsisIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end" className="min-w-52">
<EnvironmentIconMenu
environmentId={environmentId}
serverConfig={environment.serverConfig}
/>
{errorTraceId ? (
<MenuItem onClick={() => copyTraceId(errorTraceId)}>Copy trace ID</MenuItem>
) : null}
{isWslEnvironment ? (
<Tooltip>
<TooltipTrigger
render={
<Button size="xs" variant="outline" disabled>
Managed locally
</Button>
}
/>
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
Select the primary environment to turn the WSL backend on or off.
</TooltipPopup>
</Tooltip>
) : (
<>
<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}`}
/>
}
>
<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>
</div>
</div>
<MenuSeparator />
<MenuItem variant="destructive" onClick={() => onRemove(environment)}>
{isRemoving ? "Removing…" : "Remove from this device…"}
</MenuItem>
</MenuPopup>
</Menu>
</EnvironmentRow>
);
}
@@ -1817,19 +1794,6 @@ export function ConnectionsSettings() {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
const searchTargetId = useLocation({ select: (location) => location.hash.replace(/^#/, "") });
const [handledSearchTargetId, setHandledSearchTargetId] = useState<string | null>(null);
if (primaryEnvironment && handledSearchTargetId !== searchTargetId) {
setHandledSearchTargetId(searchTargetId);
if (["connections-environment", "wsl-backend"].includes(searchTargetId)) {
setSelectedEnvironmentId(primaryEnvironment.environmentId);
}
}
const selectedEnvironment =
environments.find((environment) => environment.environmentId === selectedEnvironmentId) ??
primaryEnvironment ??
environments[0];
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
const connectSshEnvironment = useAtomCommand(connectSshEnvironmentAtom, {
reportFailure: false,
@@ -1846,13 +1810,24 @@ export function ConnectionsSettings() {
? (primarySessionState.data.scopes ?? null)
: null;
const currentAuthPolicy = desktopBridge ? null : (primarySessionState.data?.auth.policy ?? null);
// Catalog order is the order the machines were added; rows never jump when
// one is switched off.
const savedEnvironments = useMemo(
() =>
environments
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
.toSorted((left, right) => left.label.localeCompare(right.label)),
environments.filter(
(environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
),
[environments],
);
// The WSL backend is managed from the WSL row under this machine, so it has
// no row of its own in the list.
const listedEnvironments = useMemo(
() =>
savedEnvironments.filter(
(environment) => !isDesktopLocalConnectionTarget(environment.entry.target),
),
[savedEnvironments],
);
// 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.
@@ -1901,10 +1876,15 @@ export function ConnectionsSettings() {
[savedServerUpdateStates],
);
// Switched-off machines never receive threads, so they stay out of the
// load balancing list.
// load balancing and GitHub sharing lists. The WSL backend has no row in
// the Environments list but does take threads, so it stays in here. This
// machine leads the list.
const loadBalancingEnvironments = useMemo(
() => environments.filter((environment) => environment.entry.enabled),
[environments],
() => [
...(primaryEnvironment ? [primaryEnvironment] : []),
...savedEnvironments.filter((environment) => environment.entry.enabled),
],
[primaryEnvironment, savedEnvironments],
);
const savedDesktopSshEnvironmentKeys = useMemo(() => {
const keys = new Set<string>();
@@ -3259,69 +3239,78 @@ export function ConnectionsSettings() {
<SettingsSection
{...searchableSetting("connections-environment")}
title={primaryEnvironment?.label ?? "Primary environment"}
>
{primaryVersionMismatch || primaryServerUpdateState.status !== "idle" ? (
<SettingsRow
title={
primaryServerUpdateState.status === "failed"
? "Update failed"
: primaryServerUpdateState.status === "running"
? "Updating server"
: "Server update available"
}
description={
primaryServerUpdateState.status !== "idle" ? (
<ServerUpdateProgress state={primaryServerUpdateState} />
) : primaryVersionMismatch ? (
<Tooltip>
<TooltipTrigger
render={
<button type="button" className="w-fit cursor-help rounded-sm text-left">
Update to match this client.
</button>
}
icon={
<EnvironmentMachineIcon
aria-hidden
kind={resolveEnvironmentMachineKind(primaryServerConfig)}
className="size-4"
/>
}
headerAction={
primaryEnvironmentId !== null ? (
<Menu>
<MenuTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-xs"
className="text-muted-foreground hover:text-foreground"
aria-label="More actions for this machine"
/>
<TooltipPopup side="top">
{primaryVersionMismatch.serverVersion} <span aria-hidden="true">→</span>{" "}
{primaryVersionMismatch.clientVersion}
</TooltipPopup>
</Tooltip>
) : null
}
control={
primaryVersionMismatch &&
primaryEnvironmentId !== null &&
primaryServerUpdateState.status !== "running" ? (
<ServerUpdateAction
size="sm"
}
>
<EllipsisIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end" className="min-w-52">
<EnvironmentIconMenu
environmentId={primaryEnvironmentId}
serverLabel={
primaryEnvironment ? `${primaryEnvironment.label} server` : "server"
}
selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
desktopAppUpdate={supportsDesktopAppUpdate(primaryServerConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(
primaryServerConfig,
)}
targetVersion={primaryVersionMismatch.clientVersion}
label={primaryServerUpdateState.status === "failed" ? "Retry" : "Update"}
serverConfig={primaryServerConfig}
/>
) : undefined
}
/>
) : null}
{primaryEnvironmentId !== null ? (
<SettingsRow
{...searchableSetting("environment-icon")}
description="The machine other devices see this environment as. Automatic uses what the server detected."
control={
<EnvironmentIconPicker
</MenuPopup>
</Menu>
) : null
}
>
<SettingsRow
title="Version"
description={
primaryServerUpdateState.status !== "idle" ? (
<ServerUpdateProgress state={primaryServerUpdateState} />
) : (
[
primaryServerConfig?.environment.serverVersion ?? null,
primaryEnvironment?.displayUrl ?? null,
]
.filter((value): value is string => value !== null)
.join(" · ") || "Loading…"
)
}
control={
primaryVersionMismatch &&
primaryEnvironmentId !== null &&
primaryServerUpdateState.status !== "running" ? (
<ServerUpdateAction
size="sm"
environmentId={primaryEnvironmentId}
serverConfig={primaryServerConfig}
serverLabel={
primaryEnvironment ? `${primaryEnvironment.label} server` : "server"
}
selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
desktopAppUpdate={supportsDesktopAppUpdate(primaryServerConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(primaryServerConfig)}
targetVersion={primaryVersionMismatch.clientVersion}
label={
primaryServerUpdateState.status === "failed"
? "Retry update"
: `Update to ${primaryVersionMismatch.clientVersion}`
}
/>
}
/>
) : null}
) : primaryServerUpdateState.status === "idle" && primaryServerConfig ? (
<span className="text-xs text-muted-foreground">Up to date</span>
) : undefined
}
/>
{desktopBridge ? (
<>
{renderNetworkAccessRow()}
@@ -3339,10 +3328,14 @@ export function ConnectionsSettings() {
</SettingsSection>
{isLocalBackendRemotelyReachable ? (
<SettingsSection
<FoldedSettingsSection
id="authorized-clients"
title="Authorized clients"
className="[&>div:first-child]:flex-wrap"
headerAction={
summary={summarizeAuthorizedClients(
desktopClientSessions,
visibleDesktopPairingLinks,
)}
control={
<AuthorizedClientsHeaderAction
onPairingLinkCreated={handlePairingLinkCreated}
clientSessions={desktopClientSessions}
@@ -3359,7 +3352,7 @@ export function ConnectionsSettings() {
>
{renderAuthorizedClients("current")}
</ScrollArea>
</SettingsSection>
</FoldedSettingsSection>
) : null}
<AlertDialog
open={isDesktopServerExposureDialogOpen}
@@ -3649,10 +3642,10 @@ export function ConnectionsSettings() {
return (
<SettingsPageContainer width="wide">
{primarySettings}
<SettingsSection
{...searchableSetting("remote-environments")}
title="Environments"
variant="plain"
headerAction={
<div className="flex items-center gap-1">
{savedServerUpdateTargets.length > 0 ? (
@@ -3725,118 +3718,22 @@ export function ConnectionsSettings() {
</div>
}
>
<div className="overflow-hidden rounded-xl border border-border/60 bg-card/40 shadow-xs/5 lg:grid lg:h-[min(34rem,calc(100dvh-18rem))] lg:min-h-[28rem] lg:grid-cols-[17rem_minmax(0,1fr)]">
<div className="border-b border-border/60 bg-muted/10 lg:flex lg:min-h-0 lg:flex-col lg:border-r lg:border-b-0">
<ScrollArea
scrollFade
chainVerticalScroll
className="max-h-64 lg:max-h-none lg:min-h-0 lg:flex-1"
>
<div className="divide-y divide-border/50" aria-label="Environments">
{(primaryEnvironment
? [primaryEnvironment, ...savedEnvironments]
: savedEnvironments
).map((environment) => {
const selected = environment.environmentId === selectedEnvironment?.environmentId;
const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
return (
<button
key={environment.environmentId}
type="button"
aria-label={"Select " + environment.label}
aria-pressed={selected}
onClick={() => setSelectedEnvironmentId(environment.environmentId)}
className={cn(
"flex min-h-18 w-full cursor-pointer items-start gap-3 px-3 py-3 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:px-4",
selected ? "bg-muted/45" : "hover:bg-muted/25",
!environment.entry.enabled && !selected && "opacity-60",
)}
>
<EnvironmentMachineIcon
aria-hidden
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
className="mt-0.5 size-4 shrink-0 text-muted-foreground"
/>
<span className="min-w-0 flex-1 space-y-1">
<span className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{environment.label}</span>
{isPrimary ? (
<span className="shrink-0 text-[10px] text-muted-foreground">
Primary
</span>
) : null}
</span>
<Tooltip>
<TooltipTrigger
render={
<span className="block truncate text-xs text-muted-foreground" />
}
>
{environment.displayUrl ?? "T3 Connect"}
</TooltipTrigger>
<TooltipPopup>{environment.displayUrl ?? "T3 Connect"}</TooltipPopup>
</Tooltip>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<span
aria-hidden
className={cn(
"size-1.5 shrink-0 rounded-full",
!environment.entry.enabled
? "bg-muted-foreground/40"
: connectionPhaseDotClassName(environment.connection.phase),
)}
/>
{environment.entry.enabled
? connectionStatusTitle(environment.connection)
: "Off"}
</span>
</span>
</button>
);
})}
</div>
</ScrollArea>
</div>
<ScrollArea
key={selectedEnvironment?.environmentId}
scrollFade
chainVerticalScroll
className="min-w-0 lg:min-h-0 lg:h-full"
>
{selectedEnvironment ? (
<div className="space-y-6 p-4">
{selectedEnvironment.entry.target._tag === "PrimaryConnectionTarget" ? (
primarySettings
) : (
<SettingsSection title="Connection">
<SavedBackendListRow
key={selectedEnvironment.environmentId}
environment={selectedEnvironment}
removingEnvironmentId={removingSavedEnvironmentId}
onSetEnabled={handleSetSavedBackendEnabled}
onRemove={handleRemoveSavedBackend}
/>
</SettingsSection>
)}
{selectedEnvironment.entry.enabled && loadBalancingEnvironments.length > 1 ? (
<SettingsSection title="Thread placement">
<LoadBalancingPreference environment={selectedEnvironment} />
</SettingsSection>
) : null}
<GitHubRoutingSettings
environments={environments}
selectedEnvironmentId={selectedEnvironment.environmentId}
/>
</div>
) : null}
</ScrollArea>
</div>
{listedEnvironments.map((environment) => (
<SavedBackendListRow
key={environment.environmentId}
environment={environment}
removingEnvironmentId={removingSavedEnvironmentId}
onSetEnabled={handleSetSavedBackendEnabled}
onRemove={handleRemoveSavedBackend}
/>
))}
<CloudRemoteEnvironmentRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironments={savedEnvironments}
/>
</SettingsSection>
<LoadBalancingSettings environments={loadBalancingEnvironments} />
<GitHubRoutingSettings environments={loadBalancingEnvironments} />
</SettingsPageContainer>
);
}
@@ -5,7 +5,6 @@ import {
type EnvironmentId,
type ServerConfig,
} from "@t3tools/contracts";
import { useCallback } from "react";
import { isElectron } from "../../env";
import { usePrimarySessionState } from "../../environments/primary";
@@ -13,15 +12,20 @@ import { useUpdateEnvironmentSettings } from "../../hooks/useSettings";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { useEnvironmentSessionState } from "../../state/session";
import { ENVIRONMENT_MACHINE_KIND_LABELS, EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
MenuItem,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuSub,
MenuSubPopup,
MenuSubTrigger,
} from "../ui/menu";
import {
resolvePrimaryOperateAccess,
resolveRemoteOperateAccess,
} from "./ProviderSettingsPanel.logic";
const AUTOMATIC_VALUE = "automatic";
/**
* Why the picker is inert, in the order the user can do something about it.
* Null means it can be changed.
@@ -68,94 +72,66 @@ function useEnvironmentOperateAccess(environmentId: EnvironmentId) {
}
/**
* Picks the machine glyph an environment wears everywhere it is listed.
* "Automatic" clears the override so the server's own detection shows
* through; the label says what that currently resolves to so the user can
* tell whether detection got it right before overriding. The control stays
* visible while locked so the current icon still reads, the same way
* server-scoped rows go inert instead of disappearing.
* "Icon" submenu for an environment's row menu. Lists the machine kinds with
* the server's own detection marked, so the user can tell whether detection
* got it right before overriding. Picking the detected kind clears the
* override. Locked environments show the reason as a disabled item instead of
* hiding the submenu, so the current icon still reads.
*/
export function EnvironmentIconPicker({
export function EnvironmentIconMenu({
environmentId,
serverConfig,
size = "sm",
}: {
readonly environmentId: EnvironmentId;
readonly serverConfig: ServerConfig | null;
readonly size?: "xs" | "sm";
}) {
const updateSettings = useUpdateEnvironmentSettings(environmentId);
const operateAccess = useEnvironmentOperateAccess(environmentId);
const lock = resolveEnvironmentIconPickerLock({ serverConfig, operateAccess });
const override = serverConfig?.settings.environmentIcon ?? null;
const detected = serverConfig?.environment.platform.machine ?? null;
// With no detection the server falls back to "server", so picking that
// kind clears the override the same way picking the detected kind does.
const detected = serverConfig?.environment.platform.machine ?? "server";
const resolved = resolveEnvironmentMachineKind(serverConfig);
const value = override ?? AUTOMATIC_VALUE;
const automaticLabel =
detected === null ? "Automatic" : `Automatic (${ENVIRONMENT_MACHINE_KIND_LABELS[detected]})`;
const handleValueChange = useCallback(
(next: string | null) => {
if (next === null) return;
if (next === AUTOMATIC_VALUE) {
updateSettings({ environmentIcon: null });
} else if (isEnvironmentMachineKind(next)) {
updateSettings({ environmentIcon: next });
}
},
[updateSettings],
);
const select = (
<Select value={value} onValueChange={handleValueChange} disabled={lock !== null}>
<SelectTrigger size={size} className="w-full sm:w-52" aria-label="Environment icon">
<SelectValue>
<span className="flex min-w-0 items-center gap-2">
<EnvironmentMachineIcon kind={resolved} className="size-3.5 shrink-0" />
<span className="truncate">
{override === null ? automaticLabel : ENVIRONMENT_MACHINE_KIND_LABELS[override]}
</span>
</span>
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value={AUTOMATIC_VALUE}>
<span className="flex min-w-0 items-center gap-2">
<EnvironmentMachineIcon kind={detected ?? "server"} className="size-3.5 shrink-0" />
<span className="truncate">{automaticLabel}</span>
</span>
</SelectItem>
{ENVIRONMENT_MACHINE_KINDS.map((kind) => (
<SelectItem hideIndicator key={kind} value={kind}>
<span className="flex min-w-0 items-center gap-2">
<EnvironmentMachineIcon kind={kind} className="size-3.5 shrink-0" />
<span className="truncate">{ENVIRONMENT_MACHINE_KIND_LABELS[kind]}</span>
</span>
</SelectItem>
))}
</SelectPopup>
</Select>
);
if (lock === null) {
return select;
}
return (
<Tooltip>
<TooltipTrigger
render={
// Focusable so keyboard users can still reach the explanation.
<span
tabIndex={0}
className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-auto"
/>
}
>
<span className="flex w-full items-center sm:w-auto">{select}</span>
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-72">
{lock}
</TooltipPopup>
</Tooltip>
<MenuSub>
<MenuSubTrigger>
<EnvironmentMachineIcon kind={resolved} />
Icon
</MenuSubTrigger>
<MenuSubPopup className="min-w-44">
{lock !== null ? (
<>
<MenuItem disabled className="whitespace-normal text-xs">
{lock}
</MenuItem>
<MenuSeparator />
</>
) : null}
<MenuRadioGroup
value={resolved}
onValueChange={(next) => {
if (lock !== null || !isEnvironmentMachineKind(next)) return;
updateSettings({ environmentIcon: next === detected ? null : next });
}}
>
{ENVIRONMENT_MACHINE_KINDS.map((kind) => (
<MenuRadioItem key={kind} value={kind} disabled={lock !== null}>
<span className="flex min-w-0 items-center gap-2">
<EnvironmentMachineIcon kind={kind} className="size-3.5 shrink-0" />
<span className="min-w-0 flex-1 truncate">
{ENVIRONMENT_MACHINE_KIND_LABELS[kind]}
</span>
{kind === detected ? (
<span className="shrink-0 text-xs text-muted-foreground">
{serverConfig?.environment.platform.machine ? "detected" : "default"}
</span>
) : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuSubPopup>
</MenuSub>
);
}
@@ -0,0 +1,74 @@
import type { DesktopSshEnvironmentTarget, EnvironmentMachineKind } from "@t3tools/contracts";
import * as Option from "effect/Option";
import type { ReactNode } from "react";
import { cn } from "~/lib/utils";
import type { EnvironmentPresentation } from "~/state/environments";
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
export function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): string {
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
return target.port ? `${authority}:${target.port}` : authority;
}
/**
* How this client reaches a machine, printed first in every environment row so
* T3 Connect, SSH, WSL, and plain remote links are told apart without a legend.
*/
export function environmentTransportLabel(environment: EnvironmentPresentation): string {
const { entry } = environment;
if (entry.target._tag === "PrimaryConnectionTarget") return "This machine";
if (environment.relayManaged) return "T3 Connect";
if (isDesktopLocalConnectionTarget(entry.target)) return "WSL";
if (
entry.target._tag === "SshConnectionTarget" &&
Option.isSome(entry.profile) &&
entry.profile.value._tag === "SshConnectionProfile"
) {
return `SSH ${formatDesktopSshTarget(entry.profile.value.target)}`;
}
return environment.displayUrl ?? "Remote link";
}
/**
* One machine in a grouped settings list: icon, name, a single subtitle line,
* and controls on the right. Every environment list on the Connections page
* uses this so the lists share one rhythm.
*/
export function EnvironmentRow({
kind,
label,
subtitle,
below,
dimmed = false,
className,
children,
}: {
readonly kind: EnvironmentMachineKind;
readonly label: string;
readonly subtitle: ReactNode;
/** Extra content under the subtitle, such as update progress. */
readonly below?: ReactNode;
readonly dimmed?: boolean;
readonly className?: string;
readonly children?: ReactNode;
}) {
return (
<div
className={cn(
"grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-3 py-2.5 sm:px-4",
dimmed && "opacity-60",
className,
)}
>
<EnvironmentMachineIcon aria-hidden kind={kind} className="size-4 text-muted-foreground" />
<div className="min-w-0">
<p className="truncate text-sm font-medium text-foreground">{label}</p>
<div className="truncate text-xs text-muted-foreground">{subtitle}</div>
{below}
</div>
<div className="flex shrink-0 items-center gap-1">{children}</div>
</div>
);
}
@@ -0,0 +1,67 @@
import { ChevronRightIcon } from "lucide-react";
import { type ReactNode, useState } from "react";
import { cn } from "~/lib/utils";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { useSettingsSearchTarget, useSettingsSearchTargetId } from "./settingsLayout";
/**
* A grouped settings section that starts closed. The header carries the title,
* a one line summary of what is set inside, and an optional control such as
* the section's own switch. A settings search that targets the section opens it.
*/
export function FoldedSettingsSection({
id,
title,
summary,
control,
children,
}: {
readonly id: string;
readonly title: string;
readonly summary?: string | null;
readonly control?: ReactNode;
readonly children: ReactNode;
}) {
const [open, setOpen] = useState(false);
const searchTargetId = useSettingsSearchTargetId();
const targetRef = useSettingsSearchTarget<HTMLElement>(id);
// A search jump lands inside the fold, so open it before the scroll runs.
const [openedForTarget, setOpenedForTarget] = useState<string | null>(null);
if (searchTargetId === id && openedForTarget !== id) {
setOpenedForTarget(id);
if (!open) setOpen(true);
}
return (
<section id={id} ref={targetRef} tabIndex={-1} className="outline-none">
<Collapsible
open={open}
onOpenChange={setOpen}
className="rounded-xl border border-border/60 bg-card/40 text-foreground shadow-xs/5"
>
<div className="flex items-center gap-4 px-3 sm:px-4">
<CollapsibleTrigger className="flex min-h-11 min-w-0 flex-1 items-center gap-2 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-md">
<ChevronRightIcon
aria-hidden
className={cn(
"size-4 shrink-0 text-muted-foreground transition-transform duration-150 motion-reduce:transition-none",
open && "rotate-90",
)}
/>
<span className="shrink-0 text-sm font-medium">{title}</span>
{summary ? (
<span className="min-w-0 truncate text-xs text-muted-foreground">{summary}</span>
) : null}
</CollapsibleTrigger>
{control ? <div className="flex shrink-0 items-center">{control}</div> : null}
</div>
<CollapsiblePanel>
<div className="border-t border-border/50 [&>*+*]:border-t [&>*+*]:border-border/50">
{children}
</div>
</CollapsiblePanel>
</Collapsible>
</section>
);
}
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vite-plus/test";
import { summarizeGitHubRouting } from "./GitHubRoutingSettings";
describe("summarizeGitHubRouting", () => {
it("is empty when no machine shares", () => {
expect(summarizeGitHubRouting([{ label: "alvin", permission: "off" }])).toBeNull();
});
it("groups sharing machines by permission, read and act first", () => {
expect(
summarizeGitHubRouting([
{ label: "alvin", permission: "read" },
{ label: "bb-1", permission: "read-write" },
{ label: "cup2", permission: "off" },
{ label: "Theo's MacBook Pro", permission: "read-write" },
]),
).toBe("bb-1, Theo's MacBook Pro read and act · alvin read PRs");
});
});
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
import {
gitHubRoutingConnectionKey,
gitHubRoutingPermissionFor,
@@ -12,7 +12,8 @@ import type { EnvironmentPresentation } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { toastManager } from "../ui/toast";
import { SettingsRow, SettingsSection } from "./settingsLayout";
import { EnvironmentRow, environmentTransportLabel } from "./EnvironmentRow";
import { FoldedSettingsSection } from "./FoldedSettingsSection";
import { searchableSetting } from "./settingsSearch";
const options: ReadonlyArray<{ value: GitHubRoutingPermission; label: string }> = [
@@ -21,73 +22,106 @@ const options: ReadonlyArray<{ value: GitHubRoutingPermission; label: string }>
{ value: "read-write", label: "Read and act" },
];
const summaryLabels = { "read-write": "read and act", read: "read PRs" } as const;
/**
* Closed-header summary: the machines that share, grouped by permission.
* Null when nothing is shared.
*/
export function summarizeGitHubRouting(
entries: ReadonlyArray<{ readonly label: string; readonly permission: GitHubRoutingPermission }>,
): string | null {
const groups = (["read-write", "read"] as const).flatMap((permission) => {
const labels = entries.filter((entry) => entry.permission === permission);
return labels.length === 0
? []
: [`${labels.map((entry) => entry.label).join(", ")} ${summaryLabels[permission]}`];
});
return groups.length === 0 ? null : groups.join(" · ");
}
/**
* Folded section under the environments list. One row per switched-on machine
* with how much of its GitHub access the other machines may use. The trust
* warning is the first line of the body so it sits next to the control.
* Rendered only when two or more machines are on.
*/
export function GitHubRoutingSettings({
environments,
selectedEnvironmentId,
}: {
readonly environments: ReadonlyArray<EnvironmentPresentation>;
readonly selectedEnvironmentId: EnvironmentId;
}) {
const permissions = useAtomValue(environmentCatalog.githubRoutingPermissionsValueAtom);
const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
const update = useAtomCommand(environmentCatalog.setGitHubRoutingPermission);
const [saving, setSaving] = useState(false);
const selectedEnvironments = environments.filter(
(environment) => environment.environmentId === selectedEnvironmentId,
);
if (environments.length < 2) return null;
const { id, title } = searchableSetting("github-routing");
return (
<SettingsSection {...searchableSetting("github-routing")}>
<SettingsRow
title="Share GitHub access"
className="sm:[&>div]:grid-cols-1 [&_p]:max-w-none"
description="Choose environments you trust to share PR data and use each other's GitHub access. Enable both environments. Read and act may use broader permissions than the original environment. This applies only to this client."
/>
{selectedEnvironments.map((environment) => (
<SettingsRow
<FoldedSettingsSection
id={id}
title={title}
summary={
summarizeGitHubRouting(
environments.map((environment) => ({
label: environment.label,
permission: gitHubRoutingPermissionFor(environment.entry, permissions),
})),
) ?? "Off"
}
>
<p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
Machines you trust here can read PR data through each other's GitHub access. Enable both
machines. Read and act may use broader permissions than the machine that owns them. This
applies only to this device.
</p>
{environments.map((environment) => (
<EnvironmentRow
key={environment.environmentId}
title="GitHub access"
description={environment.displayUrl ?? "T3 Connect"}
control={
<Select
items={options}
value={gitHubRoutingPermissionFor(environment.entry, permissions)}
disabled={
!catalog.isReady || saving || gitHubRoutingConnectionKey(environment.entry) === null
}
onValueChange={(permission) => {
if (permission === null) return;
setSaving(true);
void update({ environmentId: environment.environmentId, permission }).then(
(result) => {
setSaving(false);
if (result._tag === "Failure")
toastManager.add({
type: "error",
title: "Could not save GitHub routing permission",
});
},
);
}}
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
label={environment.label}
subtitle={environmentTransportLabel(environment)}
>
<Select
items={options}
value={gitHubRoutingPermissionFor(environment.entry, permissions)}
disabled={
!catalog.isReady || saving || gitHubRoutingConnectionKey(environment.entry) === null
}
onValueChange={(permission) => {
if (permission === null) return;
setSaving(true);
void update({ environmentId: environment.environmentId, permission }).then(
(result) => {
setSaving(false);
if (result._tag === "Failure")
toastManager.add({
type: "error",
title: "Could not save GitHub routing permission",
});
},
);
}}
>
<SelectTrigger
size="xs"
className="w-32"
aria-label={`${environment.label} GitHub routing`}
>
<SelectTrigger
size="sm"
className="w-full sm:w-40"
aria-label={`${environment.label} GitHub routing`}
>
<SelectValue />
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{options.map(({ value, label }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectPopup>
</Select>
}
/>
<SelectValue />
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{options.map(({ value, label }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectPopup>
</Select>
</EnvironmentRow>
))}
</SettingsSection>
</FoldedSettingsSection>
);
}
@@ -0,0 +1,32 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { loadPreferenceForWeight, summarizeLoadPreferences } from "./LoadBalancingSettings";
const machines = [
{ environmentId: EnvironmentId.make("a"), label: "alvin" },
{ environmentId: EnvironmentId.make("b"), label: "bb-1" },
{ environmentId: EnvironmentId.make("c"), label: "ProMini" },
];
describe("loadPreferenceForWeight", () => {
it("snaps legacy slider weights onto the four preferences", () => {
expect(loadPreferenceForWeight(undefined)).toBe(50);
expect(loadPreferenceForWeight(0)).toBe(0);
expect(loadPreferenceForWeight(10)).toBe(25);
expect(loadPreferenceForWeight(50)).toBe(50);
expect(loadPreferenceForWeight(80)).toBe(100);
});
});
describe("summarizeLoadPreferences", () => {
it("is empty when every machine is at Normal", () => {
expect(summarizeLoadPreferences(machines, { a: 50 })).toBeNull();
});
it("lists only the machines that differ from Normal, in list order", () => {
expect(summarizeLoadPreferences(machines, { b: 100, c: 0 })).toBe(
"bb-1 prefer · ProMini manual only",
);
});
});
@@ -1,3 +1,5 @@
import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
import {
useClientSettings,
useClientSettingsHydrated,
@@ -6,7 +8,8 @@ import {
import type { EnvironmentPresentation } from "~/state/environments";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import { SettingsRow, SettingsSection } from "./settingsLayout";
import { EnvironmentRow, environmentTransportLabel } from "./EnvironmentRow";
import { FoldedSettingsSection } from "./FoldedSettingsSection";
import { searchableSetting } from "./settingsSearch";
const preferences = [
@@ -14,8 +17,44 @@ const preferences = [
{ value: 50, label: "Normal" },
{ value: 25, label: "Less often" },
{ value: 0, label: "Manual only" },
];
] as const;
type LoadPreference = (typeof preferences)[number]["value"];
/** Snaps a saved weight (older builds stored a slider value) onto the four preferences. */
export function loadPreferenceForWeight(weight: number | undefined): LoadPreference {
if (weight === undefined || weight === 50) return 50;
if (weight === 0) return 0;
return weight < 50 ? 25 : 100;
}
function preferenceLabel(preference: LoadPreference): string {
return preferences.find((entry) => entry.value === preference)!.label;
}
/**
* Closed-header summary: the machines not at Normal, so the folded section
* still tells you what is set. Null when every machine is at the default.
*/
export function summarizeLoadPreferences(
environments: ReadonlyArray<Pick<EnvironmentPresentation, "environmentId" | "label">>,
weights: Readonly<Record<string, number>>,
): string | null {
const parts = environments.flatMap((environment) => {
const preference = loadPreferenceForWeight(weights[environment.environmentId]);
return preference === 50
? []
: [`${environment.label} ${preferenceLabel(preference).toLowerCase()}`];
});
return parts.length === 0 ? null : parts.join(" · ");
}
/**
* Folded section under the environments list. Its switch turns balancing on
* for this client, and the body holds one row per switched-on machine with
* how often that machine should receive new threads. Rendered only when two
* or more machines are on, since one machine has nothing to balance against.
*/
export function LoadBalancingSettings({
environments,
}: {
@@ -25,78 +64,71 @@ export function LoadBalancingSettings({
const settingsHydrated = useClientSettingsHydrated();
const updateSettings = useUpdateClientSettings();
if (environments.length < 2) {
return (
<SettingsSection {...searchableSetting("load-balancing")} variant="plain">
<p className="px-3 text-sm text-muted-foreground sm:px-4">
Connect another machine to automatically balance load across environments.
</p>
</SettingsSection>
);
}
if (environments.length < 2) return null;
const { id, title } = searchableSetting("load-balancing");
return (
<SettingsSection {...searchableSetting("load-balancing")}>
<SettingsRow
title="Automatically balance load"
description="Choose a machine automatically for new threads in shared projects."
control={
<Switch
aria-label="Automatically balance load"
checked={settings.loadBalancingEnabled}
disabled={!settingsHydrated}
onCheckedChange={(loadBalancingEnabled) => updateSettings({ loadBalancingEnabled })}
/>
}
/>
</SettingsSection>
);
}
export function LoadBalancingPreference({ environment }: { environment: EnvironmentPresentation }) {
const settings = useClientSettings();
const settingsHydrated = useClientSettingsHydrated();
const updateSettings = useUpdateClientSettings();
const weight = settings.loadBalancingWeights[environment.environmentId] ?? 50;
// Keep saved slider weights until the user chooses a different preference.
const preference = weight === 0 ? 0 : weight < 50 ? 25 : weight === 50 ? 50 : 100;
return (
<SettingsRow
title="Load preference"
description="How often this machine receives new threads when load balancing is on."
<FoldedSettingsSection
id={id}
title={title}
summary={
settings.loadBalancingEnabled
? summarizeLoadPreferences(environments, settings.loadBalancingWeights)
: "Off"
}
control={
<Select
items={preferences}
value={preference}
disabled={!settingsHydrated || !settings.loadBalancingEnabled}
onValueChange={(value) => {
if (value !== null) {
<Switch
aria-label="Automatically balance load"
checked={settings.loadBalancingEnabled}
disabled={!settingsHydrated}
onCheckedChange={(loadBalancingEnabled) => updateSettings({ loadBalancingEnabled })}
/>
}
>
<p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
New threads in shared projects start on the machine with the most free CPU and memory,
weighted by each machine's preference.
</p>
{environments.map((environment) => (
<EnvironmentRow
key={environment.environmentId}
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
label={environment.label}
subtitle={environmentTransportLabel(environment)}
>
<Select
items={preferences}
value={loadPreferenceForWeight(
settings.loadBalancingWeights[environment.environmentId],
)}
disabled={!settingsHydrated || !settings.loadBalancingEnabled}
onValueChange={(value) => {
if (value === null) return;
updateSettings({
loadBalancingWeights: {
...settings.loadBalancingWeights,
[environment.environmentId]: value,
},
});
}
}}
>
<SelectTrigger
size="sm"
className="w-full sm:w-40"
aria-label={`${environment.label} load preference`}
}}
>
<SelectValue />
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{preferences.map(({ value, label }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectPopup>
</Select>
}
/>
<SelectTrigger
size="xs"
className="w-32"
aria-label={`${environment.label} load preference`}
>
<SelectValue />
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{preferences.map(({ value, label }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectPopup>
</Select>
</EnvironmentRow>
))}
</FoldedSettingsSection>
);
}
@@ -682,7 +682,7 @@ export const SETTINGS_SEARCH_ITEMS = [
},
{
id: "connections-environment",
title: "This environment",
title: "This machine",
to: "/settings/connections",
searchTerms: [
"connections server backend local remote access administrative permissions scope pairing links qr code authorized clients sessions revoke endpoint",
@@ -690,7 +690,7 @@ export const SETTINGS_SEARCH_ITEMS = [
},
{
id: "remote-environments",
title: "Remote environments",
title: "Environments",
to: "/settings/connections",
searchTerms: ["add pair backend host code ssh config agent tunnel saved t3 connect"],
},
@@ -704,7 +704,7 @@ export const SETTINGS_SEARCH_ITEMS = [
},
{
id: "github-routing",
title: "GitHub routing",
title: "GitHub sharing",
to: "/settings/connections",
searchTerms: ["pull request trusted environments shared credentials permissions read actions"],
},
+2 -1
View File
@@ -65,7 +65,8 @@ another link to share.
Auto balance is off by default. On web and desktop, enable it in
**Settings → Connections → Load balancing** to automatically choose a machine for
new threads in projects grouped across connected environments.
new threads in projects grouped across connected environments. The section
appears once two or more machines are switched on.
Each machine starts at **Normal**. Choose **Prefer** to favor it when it has CPU and
memory available, **Less often** to reduce its share, or **Manual only** to exclude
it from automatic selection. These are preferences, not fixed traffic percentages.
+1 -1
View File
@@ -99,7 +99,7 @@ GitLab calls these merge requests.
GitHub, GitLab, and Azure DevOps support auto-merge while checks are outstanding. GitHub also
supports approving waiting fork workflows and opening a revert pull request for a merged change.
GitHub routing is off by default. In Settings → Connections (Environments on mobile), choose
GitHub sharing is off by default. In Settings → Connections → GitHub sharing (Environments on mobile), choose
**Read PRs** or **Read and act** for each environment you trust to share GitHub access.
Enable both the original environment and the environment answering its requests on this client.
**Read and act** can use broader GitHub permissions than the original environment's credential;