feat(web): pick settings environment and project as two selects (#10636)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-11 13:56:39 -07:00
1 parent 2c0e891740
commit 8b2c0465de
9 files changed
+764 -201

No files matched your search

@@ -68,7 +68,6 @@ import {
} from "../../providerInstances";
import { getCustomModelOptionsByInstance } from "../../modelSelection";
import {
buildSidebarProjectSnapshots,
type SidebarProjectGroupMember,
type SidebarProjectSnapshot,
} from "../../sidebarProjectGrouping";
@@ -115,6 +114,7 @@ import {
ProjectFaviconPickerDialog,
} from "./ProjectFaviconPickerDialog";
import { projectGroupTitleNeedsUpdate } from "./ProjectSettingsPanel.logic";
import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
const ProjectIconPickerDialog = lazy(() =>
import("./ProjectIconPickerDialog").then((module) => ({
@@ -128,31 +128,6 @@ export const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, st
separate: "Keep separate",
};
/** Logical project groups for the settings page, sorted by display name. */
export function useSettingsProjectGroups(): SidebarProjectSnapshot[] {
const projects = useProjects();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const { environments } = useEnvironments();
const environmentLabelById = useMemo(
() =>
new Map(
environments.map((environment) => [environment.environmentId, environment.label] as const),
),
[environments],
);
return useMemo(
() =>
buildSidebarProjectSnapshots({
projects,
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
}).sort((a, b) => a.displayName.localeCompare(b.displayName)),
[environmentLabelById, primaryEnvironmentId, projectGroupingSettings, projects],
);
}
function memberKey(member: { environmentId: string; id: string }): string {
return `${member.environmentId}:${member.id}`;
}
@@ -160,9 +135,11 @@ function memberKey(member: { environmentId: string; id: string }): string {
export function ProjectSettingsPanel({
projectKey,
environmentId = null,
checkoutKey = null,
}: {
projectKey: string;
environmentId?: EnvironmentId | null;
checkoutKey?: string | null;
}) {
const groups = useSettingsProjectGroups();
const navigate = useNavigate();
@@ -171,9 +148,11 @@ export function ProjectSettingsPanel({
const members = useMemo(
() =>
selected?.memberProjects.filter(
(member) => environmentId === null || member.environmentId === environmentId,
(member) =>
(environmentId === null || member.environmentId === environmentId) &&
(checkoutKey === null || member.physicalProjectKey === checkoutKey),
) ?? [],
[selected, environmentId],
[selected, environmentId, checkoutKey],
);
// Remember the members of the last rendered group so a grouping-rule change
@@ -181,6 +160,7 @@ export function ProjectSettingsPanel({
const lastSelectionRef = useRef<{
key: string;
environmentId: EnvironmentId | null;
checkoutKey: string | null;
memberKeys: string[];
} | null>(null);
useEffect(() => {
@@ -188,28 +168,38 @@ export function ProjectSettingsPanel({
lastSelectionRef.current = {
key: selected.projectKey,
environmentId,
checkoutKey,
memberKeys: members.map((member) => member.physicalProjectKey),
};
}, [selected, members, environmentId]);
}, [selected, members, environmentId, checkoutKey]);
// A grouping-rule change replaces the group key mid-visit; follow the
// project to its new key instead of parking on the not-found state.
useEffect(() => {
if (members.length > 0) return;
const last = lastSelectionRef.current;
if (last?.key !== projectKey || last.environmentId !== environmentId) return;
if (
last?.key !== projectKey ||
last.environmentId !== environmentId ||
last.checkoutKey !== checkoutKey
)
return;
const successor = groups.find((group) =>
group.memberProjects.some((member) => last.memberKeys.includes(member.physicalProjectKey)),
);
if (successor) {
void navigate({
to: "/settings/projects",
search: { project: successor.projectKey, machine: environmentId ?? undefined },
search: {
project: successor.projectKey,
machine: environmentId ?? undefined,
checkout: checkoutKey ?? undefined,
},
replace: true,
hashScrollIntoView: false,
});
}
}, [groups, navigate, projectKey, members.length, environmentId]);
}, [groups, navigate, projectKey, members.length, environmentId, checkoutKey]);
if (!selected) {
return (
@@ -223,7 +213,7 @@ export function ProjectSettingsPanel({
if (members.length === 0)
return (
<p className="p-8 text-sm text-muted-foreground">
This project has no checkout on this machine.
This checkout is no longer available in the selected project and environment.
</p>
);
const scopedGroup = {
@@ -234,7 +224,7 @@ export function ProjectSettingsPanel({
};
return (
<ProjectDetail
key={`${selected.projectKey}:${environmentId ?? "all"}`}
key={`${selected.projectKey}:${environmentId ?? "all"}:${checkoutKey ?? "all"}`}
group={scopedGroup}
hasOtherMembers={members.length < selected.memberProjects.length}
/>
@@ -879,23 +869,14 @@ function ProjectDetail({
draftStore.clearProjectDraftThreadId(projectRef);
}
if (isWholeGroup) {
if (hasOtherMembers) {
void navigate({
to: "/settings/projects",
search: { project: group.projectKey, machine: undefined },
replace: true,
});
} else {
void navigate({ to: "/", replace: true });
}
if (isWholeGroup && !hasOtherMembers) {
void navigate({ to: "/", replace: true });
}
},
[
deleteProject,
group.displayName,
group.memberProjects.length,
group.projectKey,
hasOtherMembers,
navigate,
reportFailure,
@@ -1,168 +1,53 @@
import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
import { ChevronDownIcon, FolderIcon } from "lucide-react";
import { type ReactNode, useState } from "react";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { ProjectFavicon } from "../ProjectFavicon";
import { WorkspacePageContainer } from "../WorkspacePageContainer";
import { useEnvironments } from "../../state/environments";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import {
Combobox,
ComboboxEmpty,
ComboboxSearchInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "../ui/combobox";
import { selectTriggerVariants } from "../ui/select";
import { cn } from "../../lib/utils";
import { ProjectSettingsPanel, useSettingsProjectGroups } from "./ProjectSettingsPanel";
import { ProjectSettingsPanel } from "./ProjectSettingsPanel";
import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
function ScopePicker({
label,
value,
options,
onChange,
}: {
label: "project" | "machine";
value: string | null;
options: ReadonlyArray<{ value: string; label: string; icon?: ReactNode }>;
onChange: (value: string | null) => void;
}) {
const [query, setQuery] = useState("");
const selected = options.find((option) => option.value === value);
const allIcon =
label === "project" ? <FolderIcon aria-hidden className="size-3.5 shrink-0" /> : null;
const items = [{ value: "all", label: `All ${label}s`, icon: allIcon }, ...options];
return (
<Combobox
items={items}
value={items.find((item) => item.value === (value ?? "all")) ?? null}
inputValue={query}
onInputValueChange={setQuery}
onOpenChange={() => setQuery("")}
onValueChange={(next) => {
if (next) onChange(next.value === "all" ? null : next.value);
}}
>
<ComboboxTrigger
aria-label={`${label === "project" ? "Project" : "Machine"} scope`}
className={cn(selectTriggerVariants({ size: "compact" }), "w-auto min-w-0 max-w-52")}
>
<span className="flex min-w-0 items-center gap-1.5">
{value === null ? allIcon : selected?.icon}
<span className="truncate">
{value === null ? `All ${label}s` : (selected?.label ?? `Unavailable ${label}`)}
</span>
</span>
<ChevronDownIcon aria-hidden className="-me-1 size-3 opacity-50" />
</ComboboxTrigger>
<ComboboxPopup align="start" className="w-64">
<ComboboxSearchInput aria-label={`Search ${label}s`} placeholder={`Search ${label}s...`} />
<ComboboxEmpty>No matching {label}s.</ComboboxEmpty>
<ComboboxList>
{(item: (typeof items)[number]) => (
<ComboboxItem
key={item.value}
value={item}
contentClassName="flex min-w-0 items-center gap-2"
>
{item.icon}
<span className="truncate">{item.label}</span>
</ComboboxItem>
)}
</ComboboxList>
</ComboboxPopup>
</Combobox>
);
}
import { SettingsScopeSelects } from "./SettingsScopeSelects";
import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
export function ProjectsSettings({
projectKey,
machineId,
value,
onScopeChange,
}: {
projectKey: string | null;
machineId: string | null;
onScopeChange: (project: string | null, machine: string | null) => void;
value: SettingsScopeSearch;
onScopeChange: (scope: SettingsScopeSearch) => void;
}) {
const groups = useSettingsProjectGroups();
const { environments } = useEnvironments();
const machine = environments.find((environment) => environment.environmentId === machineId);
const machineOptions = environments.map((environment) => ({
value: environment.environmentId,
label: environment.label,
icon: (
<EnvironmentMachineIcon
aria-hidden
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
className="size-3.5 shrink-0"
/>
),
}));
const scope = resolveSettingsScope(value, groups, environments);
// The panel follows remembered members when grouping replaces a project key.
const projectScope =
scope.kind === "project" ||
scope.kind === "checkout" ||
(scope.kind === "unavailable" &&
(scope.reason === "project-missing" || scope.reason === "checkout-missing"));
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="scrollbar-gutter-both shrink-0 overflow-y-auto">
<WorkspacePageContainer className="pb-0">
<div
className="flex flex-wrap items-center gap-2"
role="group"
aria-label="Settings scope"
>
{environments.length > 3 ? (
<ScopePicker
label="machine"
value={machineId}
options={machineOptions}
onChange={(value) => onScopeChange(projectKey, value)}
/>
) : (
<ToggleGroup
aria-label="Machine scope"
variant="segmented"
className="max-w-full flex-wrap"
value={[machineId ?? "all"]}
onValueChange={(next) => {
const value = next[0];
if (value) onScopeChange(projectKey, value === "all" ? null : value);
}}
>
<Toggle value="all">All machines</Toggle>
{machineOptions.map((option) => (
<Toggle key={option.value} value={option.value} title={option.label}>
{option.icon}
<span className="max-w-36 truncate">{option.label}</span>
</Toggle>
))}
</ToggleGroup>
)}
<div className="ms-auto">
<ScopePicker
label="project"
value={projectKey}
options={groups.map((group) => ({
value: group.projectKey,
label: group.displayName,
icon: <ProjectFavicon project={group} className="size-3.5" />,
}))}
onChange={(value) => onScopeChange(value, machineId)}
/>
</div>
</div>
<WorkspacePageContainer className="items-end pb-0">
<SettingsScopeSelects
value={value}
groups={groups}
environments={environments}
onChange={onScopeChange}
/>
</WorkspacePageContainer>
</div>
{machineId !== null && !machine ? (
<p className="p-8 text-sm text-muted-foreground">This machine is no longer available.</p>
) : projectKey === null ? (
<ProjectDefaultsSettings environmentId={machine?.environmentId ?? null} />
) : (
{value.project && projectScope ? (
<ProjectSettingsPanel
projectKey={projectKey}
environmentId={machine?.environmentId ?? null}
projectKey={value.project}
environmentId={value.machine ? EnvironmentId.make(value.machine) : null}
checkoutKey={value.checkout ?? null}
/>
) : scope.kind === "unavailable" ? (
<p className="p-8 text-sm text-muted-foreground">{scope.message}</p>
) : (
<ProjectDefaultsSettings
environmentId={scope.kind === "environment" ? scope.environmentId : null}
/>
)}
</div>
);
}
import { EnvironmentId } from "@t3tools/contracts";
@@ -0,0 +1,88 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
environmentAxisValue,
projectAxisValue,
selectEnvironmentAxis,
selectProjectAxis,
settingsScopeEnvironmentLabel,
} from "./SettingsScopeSelects.logic";
const first = {
environmentId: EnvironmentId.make("first"),
label: "Development",
displayUrl: "https://first.example.com",
};
const second = {
environmentId: EnvironmentId.make("second"),
label: "Development",
displayUrl: "https://second.example.com",
};
describe("settings scope environment labels", () => {
it("distinguishes same-name environments by address", () => {
const environments = [first, second];
expect(
environments.map((environment) => settingsScopeEnvironmentLabel(environment, environments)),
).toEqual([
"Development · https://first.example.com",
"Development · https://second.example.com",
]);
});
it("falls back to environment IDs when duplicate names have no display URL", () => {
const environments = [first, second].map((environment) => ({
...environment,
displayUrl: null,
}));
expect(
environments.map((environment) => settingsScopeEnvironmentLabel(environment, environments)),
).toEqual(["Development · first", "Development · second"]);
});
it("keeps unique names compact and removes disambiguation after a rename", () => {
expect(settingsScopeEnvironmentLabel(first, [first])).toBe("Development");
expect(settingsScopeEnvironmentLabel(first, [first, { ...second, label: "Production" }])).toBe(
"Development",
);
});
});
describe("settings scope axes", () => {
it("maps each axis to its search key and back", () => {
expect(projectAxisValue({})).toBe("all");
expect(projectAxisValue({ project: "app" })).toBe("app");
expect(selectProjectAxis({ machine: "second" }, "app")).toEqual({
project: "app",
machine: "second",
});
expect(selectProjectAxis({ machine: "second", project: "app" }, "all")).toEqual({
machine: "second",
});
expect(selectEnvironmentAxis({ project: "app" }, "first")).toEqual({
project: "app",
machine: "first",
});
expect(selectEnvironmentAxis({ project: "app", machine: "first" }, "all")).toEqual({
project: "app",
});
});
it("drops a checkout narrowing from older links when either axis changes", () => {
const checkout = { project: "app", checkout: "app@first", machine: "first" };
expect(selectEnvironmentAxis(checkout, "second")).toEqual({
project: "app",
machine: "second",
});
expect(selectProjectAxis(checkout, "app")).toEqual({ project: "app", machine: "first" });
});
});
describe("environmentAxisValue", () => {
it("shows the checkout's environment for a legacy checkout link", () => {
expect(environmentAxisValue({ project: "p", checkout: "c" }, "laptop")).toBe("laptop");
expect(environmentAxisValue({ project: "p" }, null)).toBe("all");
expect(environmentAxisValue({ machine: "desk" }, "laptop")).toBe("desk");
});
});
@@ -0,0 +1,55 @@
import type { EnvironmentPresentation } from "../../state/environments";
import type { SettingsScopeSearch } from "./settingsScope";
type ScopeEnvironment = Pick<EnvironmentPresentation, "environmentId" | "label" | "displayUrl">;
export function settingsScopeEnvironmentLabel(
environment: ScopeEnvironment,
environments: readonly ScopeEnvironment[],
) {
const duplicate = environments.some(
(other) =>
other.environmentId !== environment.environmentId && other.label === environment.label,
);
return duplicate
? `${environment.label} · ${environment.displayUrl ?? environment.environmentId}`
: environment.label;
}
export const ALL_ENVIRONMENTS_VALUE = "all";
export const ALL_PROJECTS_VALUE = "all";
/**
* The environment axis: `all` or an environment id. A legacy checkout link
* without `machine` still names one environment, which the resolver supplies.
*/
export function environmentAxisValue(
search: SettingsScopeSearch,
resolvedEnvironmentId?: string | null,
): string {
return search.machine ?? resolvedEnvironmentId ?? ALL_ENVIRONMENTS_VALUE;
}
/** The project axis: `all` or a project key. */
export function projectAxisValue(search: SettingsScopeSearch): string {
return search.project ?? ALL_PROJECTS_VALUE;
}
/** Choosing an environment keeps the project; a pre-existing checkout narrowing is dropped. */
export function selectEnvironmentAxis(
search: SettingsScopeSearch,
value: string,
): SettingsScopeSearch {
const next: SettingsScopeSearch = {};
if (search.project) next.project = search.project;
if (value !== ALL_ENVIRONMENTS_VALUE) next.machine = value;
return next;
}
/** Choosing a project keeps the environment axis. */
export function selectProjectAxis(search: SettingsScopeSearch, value: string): SettingsScopeSearch {
const next: SettingsScopeSearch = {};
if (value !== ALL_PROJECTS_VALUE) next.project = value;
if (search.machine) next.machine = search.machine;
return next;
}
@@ -0,0 +1,154 @@
import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
import { LayersIcon } from "lucide-react";
import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
import type { EnvironmentPresentation } from "../../state/environments";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { ProjectFavicon } from "../ProjectFavicon";
import {
Select,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "../ui/select";
import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
import {
ALL_ENVIRONMENTS_VALUE,
ALL_PROJECTS_VALUE,
environmentAxisValue,
projectAxisValue,
selectEnvironmentAxis,
selectProjectAxis,
settingsScopeEnvironmentLabel,
} from "./SettingsScopeSelects.logic";
const TRIGGER_CLASSNAME = "w-auto min-w-0 max-w-56 justify-start";
/**
* Two independent targets: which environments a change applies to, and
* which project it overrides. A project is the same project on every
* environment; the environment select alone decides where the override is
* written. Each axis defaults to "all".
*/
export function SettingsScopeSelects({
value,
groups,
environments,
onChange,
}: {
value: SettingsScopeSearch;
groups: readonly SidebarProjectSnapshot[];
environments: readonly EnvironmentPresentation[];
onChange: (next: SettingsScopeSearch) => void;
}) {
const resolved = resolveSettingsScope(value, groups, environments);
const environmentValue = environmentAxisValue(
value,
resolved.kind === "checkout" ? resolved.environmentId : null,
);
const projectValue = projectAxisValue(value);
const selectedEnvironment = environments.find(
(environment) => environment.environmentId === environmentValue,
);
const selectedGroup = groups.find((group) => group.projectKey === value.project);
return (
<div className="flex min-w-0 items-center gap-1.5" role="group" aria-label="Settings scope">
<Select
value={environmentValue}
onValueChange={(next) => {
if (typeof next === "string") onChange(selectEnvironmentAxis(value, next));
}}
>
<SelectTrigger size="compact" aria-label="Environment scope" className={TRIGGER_CLASSNAME}>
<SelectValue>
<span className="flex min-w-0 items-center gap-1.5">
{selectedEnvironment ? (
<EnvironmentMachineIcon
aria-hidden
kind={resolveEnvironmentMachineKind(selectedEnvironment.serverConfig)}
className="size-3.5"
/>
) : (
<LayersIcon aria-hidden className="size-3.5" />
)}
<span className="truncate">
{selectedEnvironment
? settingsScopeEnvironmentLabel(selectedEnvironment, environments)
: environmentValue !== ALL_ENVIRONMENTS_VALUE
? "Unavailable environment"
: "All environments"}
</span>
</span>
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false} className="min-w-56">
<SelectItem value={ALL_ENVIRONMENTS_VALUE}>
<span className="flex items-center gap-2">
<LayersIcon aria-hidden className="size-3.5" />
All environments
</span>
</SelectItem>
<SelectGroup>
<SelectGroupLabel>Environments</SelectGroupLabel>
{environments.map((environment) => (
<SelectItem key={environment.environmentId} value={environment.environmentId}>
<span className="flex w-full min-w-0 items-center gap-2">
<EnvironmentMachineIcon
aria-hidden
kind={resolveEnvironmentMachineKind(environment.serverConfig)}
className="size-3.5"
/>
<span className="min-w-0 flex-1 truncate">
{settingsScopeEnvironmentLabel(environment, environments)}
</span>
{environment.connection.phase === "connected" ? null : (
<span className="text-xs text-muted-foreground">Offline</span>
)}
</span>
</SelectItem>
))}
</SelectGroup>
</SelectPopup>
</Select>
<Select
value={projectValue}
onValueChange={(next) => {
if (typeof next === "string") onChange(selectProjectAxis(value, next));
}}
>
<SelectTrigger size="compact" aria-label="Project scope" className={TRIGGER_CLASSNAME}>
<SelectValue>
<span className="flex min-w-0 items-center gap-1.5">
{selectedGroup ? (
<ProjectFavicon project={selectedGroup} className="size-3.5" />
) : null}
<span className="truncate">
{selectedGroup?.displayName ??
(value.project ? "Unavailable project" : "All projects")}
</span>
</span>
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false} className="min-w-56">
<SelectItem value={ALL_PROJECTS_VALUE}>All projects</SelectItem>
{groups.map((group) => (
<SelectItem key={group.projectKey} value={group.projectKey}>
<span className="flex w-full min-w-0 items-center gap-2">
<ProjectFavicon project={group} className="size-3.5" />
<span className="min-w-0 flex-1 truncate">{group.displayName}</span>
</span>
</SelectItem>
))}
</SelectPopup>
</Select>
{resolved.kind === "unavailable" ? (
<span className="truncate text-xs text-muted-foreground">{resolved.message}</span>
) : null}
</div>
);
}
@@ -0,0 +1,216 @@
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type {
SidebarProjectGroupMember,
SidebarProjectSnapshot,
} from "../../sidebarProjectGrouping";
import { resolveSettingsScope, validateSettingsScopeSearch } from "./settingsScope";
const laptopId = EnvironmentId.make("laptop");
const serverId = EnvironmentId.make("server");
const environments = [
{ environmentId: laptopId, label: "Laptop" },
{ environmentId: serverId, label: "Server" },
];
function member(id: string, environmentId: EnvironmentId): SidebarProjectGroupMember {
return {
id: ProjectId.make(id),
environmentId,
title: "T3 Code",
workspaceRoot: `/repos/${id}`,
physicalProjectKey: `${environmentId}:/repos/${id}`,
environmentLabel:
environments.find((environment) => environment.environmentId === environmentId)?.label ??
null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-09-07T00:00:00.000Z",
updatedAt: "2026-09-07T00:00:00.000Z",
};
}
const first = member("first", laptopId);
const second = member("second", laptopId);
const third = member("third", serverId);
const other = member("other", serverId);
function group(
projectKey: string,
members: readonly SidebarProjectGroupMember[],
): SidebarProjectSnapshot {
return {
...members[0]!,
projectKey,
displayName: projectKey,
memberProjects: members,
memberProjectRefs: members.map((project) => ({
environmentId: project.environmentId,
projectId: project.id,
})),
groupedProjectCount: members.length,
environmentPresence: "mixed",
allRemoteMembersAreDesktopLocal: false,
allRemoteMembersAreWsl: false,
remoteEnvironmentLabels: [],
};
}
const groups = [group("t3code", [first, second, third]), group("other", [other])];
describe("settings scope search", () => {
it.each(["device", "all"] as const)(
"clears narrower targets for an explicit %s selection",
(scope) => {
expect(
validateSettingsScopeSearch({
scope,
project: "t3code",
machine: laptopId,
checkout: first.physicalProjectKey,
}),
).toEqual({ scope });
},
);
it("retains legacy project and machine links without inventing an explicit broad scope", () => {
expect(
validateSettingsScopeSearch({ project: "t3code", machine: laptopId, unused: true }),
).toEqual({
project: "t3code",
machine: laptopId,
});
});
it("retains an orphan checkout so it cannot turn into all environments", () => {
const search = validateSettingsScopeSearch({ checkout: first.physicalProjectKey });
expect(search).toEqual({ checkout: first.physicalProjectKey });
expect(resolveSettingsScope(search, groups, environments)).toMatchObject({
kind: "unavailable",
reason: "project-required",
members: [],
environmentIds: [],
});
});
});
describe("settings scope resolution", () => {
it("distinguishes this device from the default aggregate target", () => {
expect(resolveSettingsScope({}, groups, environments)).toMatchObject({
kind: "all",
environmentIds: [laptopId, serverId],
});
expect(resolveSettingsScope({ scope: "device" }, groups, environments)).toMatchObject({
kind: "device",
members: [],
environmentIds: [],
});
});
it("resolves one environment without targeting its project overrides", () => {
expect(resolveSettingsScope({ machine: serverId }, groups, environments)).toMatchObject({
kind: "environment",
environmentId: serverId,
environmentIds: [serverId],
members: [],
});
});
it("keeps all physical members in a project aggregate, including several on one environment", () => {
expect(resolveSettingsScope({ project: "t3code" }, groups, environments)).toMatchObject({
kind: "project",
environmentId: null,
members: [first, second, third],
environmentIds: [laptopId, serverId],
});
});
it("preserves legacy project plus machine aggregates with multiple checkouts", () => {
expect(
resolveSettingsScope({ project: "t3code", machine: laptopId }, groups, environments),
).toMatchObject({
kind: "project",
environmentId: laptopId,
label: "t3code / Laptop",
members: [first, second],
environmentIds: [laptopId],
});
});
it("narrows a checkout target to exactly one member, deriving its environment when omitted", () => {
expect(
resolveSettingsScope(
{ project: "t3code", checkout: second.physicalProjectKey },
groups,
environments,
),
).toMatchObject({
kind: "checkout",
checkout: second,
environmentId: laptopId,
label: "t3code / Laptop · /repos/second",
members: [second],
environmentIds: [laptopId],
});
});
it.each([
{ project: "missing" },
{ machine: "removed" },
{ project: "t3code", machine: "removed" },
{ project: "t3code", checkout: "deleted" },
{ project: "other", machine: laptopId },
{ project: "other", checkout: first.physicalProjectKey },
{ project: "t3code", machine: serverId, checkout: first.physicalProjectKey },
])("never widens an invalid or stale target: %j", (search) => {
expect(resolveSettingsScope(search, groups, environments)).toMatchObject({
kind: "unavailable",
members: [],
environmentIds: [],
});
});
it("leaves a removed checkout unavailable while sibling checkouts remain", () => {
const search = {
project: "t3code",
machine: laptopId,
checkout: first.physicalProjectKey,
};
expect(resolveSettingsScope(search, groups, environments)).toMatchObject({
kind: "checkout",
members: [first],
});
expect(
resolveSettingsScope(search, [group("t3code", [second, third])], environments),
).toMatchObject({ kind: "unavailable", members: [], environmentIds: [] });
});
it("does not select another environment after removing a project's last local checkout", () => {
const search = { project: "t3code", machine: laptopId };
expect(resolveSettingsScope(search, groups, environments)).toMatchObject({
kind: "project",
members: [first, second],
});
expect(resolveSettingsScope(search, [group("t3code", [third])], environments)).toMatchObject({
kind: "unavailable",
members: [],
environmentIds: [],
});
});
it("rejects a cached checkout whose environment was removed", () => {
expect(
resolveSettingsScope(
{ project: "t3code", checkout: third.physicalProjectKey },
groups,
environments.slice(0, 1),
),
).toMatchObject({
kind: "unavailable",
reason: "environment-missing",
members: [],
environmentIds: [],
});
});
});
@@ -0,0 +1,163 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type {
SidebarProjectGroupMember,
SidebarProjectSnapshot,
} from "../../sidebarProjectGrouping";
import type { EnvironmentPresentation } from "../../state/environments";
export interface SettingsScopeSearch {
scope?: "device" | "all" | undefined;
project?: string | undefined;
machine?: string | undefined;
checkout?: string | undefined;
}
type ScopeTargets = {
label: string;
members: readonly SidebarProjectGroupMember[];
environmentIds: readonly EnvironmentId[];
};
export type ResolvedSettingsScope = ScopeTargets &
(
| { kind: "device" | "all" }
| { kind: "environment"; environmentId: EnvironmentId }
| {
kind: "project";
group: SidebarProjectSnapshot;
environmentId: EnvironmentId | null;
}
| {
kind: "checkout";
group: SidebarProjectSnapshot;
checkout: SidebarProjectGroupMember;
environmentId: EnvironmentId;
}
| {
kind: "unavailable";
reason: "project-required" | "project-missing" | "environment-missing" | "checkout-missing";
message: string;
}
);
/** Explicit broad targets replace narrower selections; stale IDs remain visible to the resolver. */
export function validateSettingsScopeSearch(raw: Record<string, unknown>): SettingsScopeSearch {
if (raw.scope === "device" || raw.scope === "all") return { scope: raw.scope };
const stringValue = (value: unknown) =>
typeof value === "string" && value.trim().length > 0 ? value : undefined;
const project = stringValue(raw.project);
const machine = stringValue(raw.machine);
const checkout = stringValue(raw.checkout);
return {
...(project === undefined ? {} : { project }),
...(machine === undefined ? {} : { machine }),
...(checkout === undefined ? {} : { checkout }),
};
}
/** Resolves only existing targets. An unavailable selection never broadens a subsequent write. */
export function resolveSettingsScope(
search: SettingsScopeSearch,
groups: readonly SidebarProjectSnapshot[],
environments: readonly Pick<EnvironmentPresentation, "environmentId" | "label">[],
): ResolvedSettingsScope {
const unavailable = (
reason: Extract<ResolvedSettingsScope, { kind: "unavailable" }>["reason"],
message: string,
): ResolvedSettingsScope => ({
kind: "unavailable",
reason,
label: "Unavailable selection",
message,
members: [],
environmentIds: [],
});
if (search.scope === "device") {
return { kind: "device", label: "This device", members: [], environmentIds: [] };
}
if (search.scope === "all") {
return {
kind: "all",
label: "All environments",
members: [],
environmentIds: environments.map((environment) => environment.environmentId),
};
}
if (search.checkout && !search.project) {
return unavailable("project-required", "Select a project to choose one of its checkouts.");
}
const environment = environments.find((candidate) => candidate.environmentId === search.machine);
if (search.machine && !environment) {
return unavailable("environment-missing", "This environment is no longer available.");
}
if (search.project) {
const group = groups.find((candidate) => candidate.projectKey === search.project);
if (!group) return unavailable("project-missing", "This project is no longer available.");
const members = group.memberProjects.filter(
(member) =>
(search.machine === undefined || member.environmentId === search.machine) &&
(search.checkout === undefined || member.physicalProjectKey === search.checkout),
);
if (members.length === 0) {
return unavailable(
"checkout-missing",
search.checkout
? "This checkout is no longer available in the selected project and environment."
: "This project has no checkout on this environment.",
);
}
if (search.checkout) {
const checkout = members[0]!;
const checkoutEnvironment = environments.find(
(candidate) => candidate.environmentId === checkout.environmentId,
);
if (!checkoutEnvironment) {
return unavailable(
"environment-missing",
"This checkout's environment is no longer available.",
);
}
const sharesEnvironment = group.memberProjects.some(
(member) =>
member.environmentId === checkout.environmentId &&
member.physicalProjectKey !== checkout.physicalProjectKey,
);
return {
kind: "checkout",
group,
checkout,
environmentId: checkout.environmentId,
label: `${group.displayName} / ${checkoutEnvironment.label}${sharesEnvironment ? ` · ${checkout.workspaceRoot}` : ""}`,
members,
environmentIds: [checkout.environmentId],
};
}
return {
kind: "project",
group,
environmentId: environment?.environmentId ?? null,
label: `${group.displayName} / ${environment?.label ?? "All checkouts"}`,
members,
environmentIds: [...new Set(members.map((member) => member.environmentId))],
};
}
if (environment) {
return {
kind: "environment",
environmentId: environment.environmentId,
label: environment.label,
members: [],
environmentIds: [environment.environmentId],
};
}
return {
kind: "all",
label: "All environments",
members: [],
environmentIds: environments.map((candidate) => candidate.environmentId),
};
}
@@ -0,0 +1,24 @@
import { useMemo } from "react";
import { useClientSettings } from "../../hooks/useSettings";
import { selectProjectGroupingSettings } from "../../logicalProject";
import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";
import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
import { useProjects } from "../../state/entities";
/** Settings uses the same logical projects as the sidebar, sorted by display name. */
export function useSettingsProjectGroups() {
const projects = useProjects();
const settings = useClientSettings(selectProjectGroupingSettings);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const { environments } = useEnvironments();
return useMemo(() => {
const labels = new Map(environments.map((entry) => [entry.environmentId, entry.label]));
return buildSidebarProjectSnapshots({
projects,
settings,
primaryEnvironmentId,
resolveEnvironmentLabel: (id) => labels.get(id) ?? null,
}).sort((a, b) => a.displayName.localeCompare(b.displayName));
}, [environments, primaryEnvironmentId, projects, settings]);
}
+6 -9
View File
@@ -1,24 +1,21 @@
import { createFileRoute } from "@tanstack/react-router";
import { ProjectsSettings } from "../components/settings/ProjectsSettings";
import { validateSettingsScopeSearch } from "../components/settings/settingsScope";
export const Route = createFileRoute("/settings/projects")({
validateSearch: (search: Record<string, unknown>) => ({
project: typeof search.project === "string" ? search.project : undefined,
machine: typeof search.machine === "string" ? search.machine : undefined,
}),
validateSearch: validateSettingsScopeSearch,
component: ProjectsRoute,
});
function ProjectsRoute() {
const { project, machine } = Route.useSearch();
const search = Route.useSearch();
const navigate = Route.useNavigate();
return (
<ProjectsSettings
projectKey={project ?? null}
machineId={machine ?? null}
onScopeChange={(project, machine) => {
value={search}
onScopeChange={(scope) => {
void navigate({
search: { project: project ?? undefined, machine: machine ?? undefined },
search: scope,
replace: true,
});
}}