TypeScript
feat(web): filter the sidebar by several projects at once (#25284)
mariac38b265adc40
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex f4ec80f8c5f..97b74aad621 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -59,7 +59,14 @@ import {} from "@t3tools/contracts";import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads";-import { ChevronDownIcon, FolderIcon, ListFilterIcon, PlusIcon, SettingsIcon } from "lucide-react";+import {+ CheckIcon,+ ChevronDownIcon,+ FolderIcon,+ ListFilterIcon,+ PlusIcon,+ SettingsIcon,+} from "lucide-react";import {useEffect,useLayoutEffect,@@ -98,7 +105,7 @@ import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";import { selectProjectGroupingSettings } from "../logicalProject";import {projectGroupsSpanEnvironments,- resolveSidebarProjectScopeKey,+ resolveSidebarProjectScopeKeys,getSidebarProjectSettingsKey,type SidebarProjectSnapshot,} from "../sidebarProjectGrouping";@@ -755,6 +762,19 @@ function useSidebarLookups() {};}+function ProjectScopeRowIcon(props: { isSelected: boolean; children: ReactNode }) {+ return (+ <span className="relative flex shrink-0">+ {props.children}+ {props.isSelected ? (+ <span className="pointer-events-none absolute -right-1 -bottom-1 grid size-3 place-items-center rounded-full bg-primary ring-2 ring-popover">+ <CheckIcon className="size-2 text-primary-foreground" strokeWidth={4} aria-hidden />+ </span>+ ) : null}+ </span>+ );+}+function canOperateThreads(threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,): boolean {@@ -900,8 +920,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve);const environmentMachineById = useEnvironmentMachines();const projectGroupsRef = useRef(projectGroups);- const persistedProjectScopeKey = useUiStateStore((store) => store.sidebarProjectScopeKey);- const setPersistedProjectScopeKey = useUiStateStore((store) => store.setSidebarProjectScopeKey);+ const persistedProjectScopeKeys = useUiStateStore((store) => store.sidebarProjectScopeKeys);+ const setPersistedProjectScopeKeys = useUiStateStore((store) => store.setSidebarProjectScopeKeys);const [projectScopeMenuState, dispatchProjectScopeMenu] = useReducer(reduceSidebarProjectScopeMenuState,{ open: false, query: "" },@@ -961,28 +981,29 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveconst routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;// A selection made under one scope can hold threads the next scope hides.- const setProjectScopeKey = (key: string | null) => {+ const setProjectScopeKeys = (keys: readonly string[]) => {clearSelection();- setPersistedProjectScopeKey(key);+ setPersistedProjectScopeKeys(keys);};// A scope whose project is gone reads as all projects once every snapshot has- // loaded. The stored key is left alone, so the scope returns with its project.- const chosenProjectScopeKey = resolveSidebarProjectScopeKey({+ // loaded. The stored keys are left alone, so the scope returns with its project.+ const chosenProjectScopeKeys = resolveSidebarProjectScopeKeys({groups: projectGroups,- key: persistedProjectScopeKey,+ keys: persistedProjectScopeKeys,settings: projectGroupingSettings,canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,});- const chosenProjectGroup =- chosenProjectScopeKey === null- ? null- : (projectGroups.find((project) => project.projectKey === chosenProjectScopeKey) ?? null);+ const chosenProjectGroups = projectGroups.filter((project) =>+ chosenProjectScopeKeys.includes(project.projectKey),+ );const chosenScopeProjectKeys =- chosenProjectGroup === null+ chosenProjectGroups.length === 0? null: new Set(- chosenProjectGroup.memberProjectRefs.map(- (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,+ chosenProjectGroups.flatMap((project) =>+ project.memberProjectRefs.map(+ (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,+ ),),);const threads = useQuietThreadShells();@@ -1013,7 +1034,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteRevedelegatedUnderParent,findThread: (key) => threads.find((candidate) => threadShellKey(candidate) === key),});- const projectScopeKey = revealWidensScope ? null : chosenProjectScopeKey;+ const projectScopeKeys = revealWidensScope ? [] : chosenProjectScopeKeys;+ const projectScopeKey = projectScopeKeys.length === 0 ? null : projectScopeKeys.join("\n");+ const toggleProjectScopeKey = (key: string) =>+ setProjectScopeKeys(+ projectScopeKeys.includes(key)+ ? projectScopeKeys.filter((candidate) => candidate !== key)+ : [...projectScopeKeys, key],+ );// The widened scope outlives the reveal, so it is written back to the persisted// scope. Route changes arrive from history, links and the palette, and only this// component holds the project groups that decide a widening, so no single@@ -1022,8 +1050,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveuseEffect(() => {if (!revealWidensScope) return;clearSelection();- setPersistedProjectScopeKey(null);- }, [clearSelection, revealWidensScope, setPersistedProjectScopeKey]);+ setPersistedProjectScopeKeys([]);+ }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]);const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey);const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups);const scratchMachineLabelFor = (@@ -1040,26 +1068,25 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteRevereturn environmentLabelById.get(thread.environmentId) ?? null;};const selectedProjectScopeItem =- projectScopeItems.find((item) => item.value === (projectScopeKey ?? "all")) ??- projectScopeItems[0]!;+ projectScopeKeys.length > 1+ ? null+ : (projectScopeItems.find((item) => item.value === (projectScopeKeys[0] ?? "all")) ??+ projectScopeItems[0]!);const filteredProjectScopeItems = filterSidebarProjectScopeItems({items: projectScopeItems,query: projectScopeMenuState.query,matches: (item, query) =>projectScopeFilter.contains(item, query, (candidate) => candidate.label),});- const scopedProjectGroup = revealWidensScope ? null : chosenProjectGroup;+ const scopedProjectGroups = revealWidensScope ? [] : chosenProjectGroups;+ const scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs);const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys;const threadSearch = useThreadSearch(searchEnvironmentIds,threadSearchQuery,- scopedProjectGroup === null+ scopedProjectGroups.length === 0? {}- : {- projectIds: scopedProjectGroup.memberProjectRefs.map(- (projectRef) => projectRef.projectId,- ),- },+ : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) },);const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null;const visibleDraftSessionCount = useComposerDraftStore((store) => {@@ -2022,6 +2049,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteRevethreadKey,currentThreadKey: readRouteThreadKey(router),action: "snooze",+ // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)now: new Date().toISOString(),thread: readThreadShell(threadRef),})@@ -2061,6 +2089,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve);if (threadKeys.length === 0) return;const count = threadKeys.length;+ // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)const selectionNow = new Date();const selectedThreads = threadKeys.flatMap((threadKey) => {const thread = threadByKeyRef.current.get(threadKey);@@ -2094,6 +2123,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveconst unpinMenuItem = buildBulkUnpinContextMenuItem({pinnedCount: pinnedSelectedThreads.length,});+ // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat);const clicked = await settlePromise(() =>api.contextMenu.show(@@ -2406,7 +2436,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveprojectFilter: threadProjectGroup? {label: threadProjectGroup.displayName,- isActive: projectScopeKey === threadProjectGroup.projectKey,+ isActive: projectScopeKeys.includes(threadProjectGroup.projectKey),}: null,isPinned,@@ -2444,10 +2474,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveswitch (clicked.value) {case "filter-by-project":if (threadProjectGroup) {- setProjectScopeKey(- projectScopeKey === threadProjectGroup.projectKey- ? null- : threadProjectGroup.projectKey,+ setProjectScopeKeys(+ projectScopeKeys.includes(threadProjectGroup.projectKey)+ ? []+ : [threadProjectGroup.projectKey],);}return;@@ -2732,7 +2762,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveitemToStringLabel={(item) => item.label}isItemEqualToValue={(a, b) => a.value === b.value}open={projectScopeMenuState.open}- onOpenChange={(open) => {+ onOpenChange={(open, eventDetails) => {+ if (eventDetails.isCanceled) return;if (open) suppressNextScopeChangeRef.current = false;dispatchProjectScopeMenu({ type: "open-changed", open });}}@@ -2740,29 +2771,50 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteRevehighlightedProjectScopeKeyRef.current = item?.value ?? null;}}value={selectedProjectScopeItem}- onValueChange={(item) => {+ onValueChange={(item, eventDetails) => {if (suppressNextScopeChangeRef.current) {suppressNextScopeChangeRef.current = false;return;}if (!item) return;- setProjectScopeKey(item.value === "all" ? null : item.value);+ if (item.value === "all") {+ setProjectScopeKeys([]);+ } else if (+ eventDetails.event instanceof MouseEvent &&+ eventDetails.event.shiftKey+ ) {+ // Canceling skips Base UI's commit, which would freeze the search query, and its close.+ eventDetails.cancel();+ toggleProjectScopeKey(item.value);+ } else {+ setProjectScopeKeys([item.value]);+ }}}><ComboboxTriggerrender={<SidebarHeaderIconButtonlabel={- scopedProjectGroup- ? `Filter threads by project: ${scopedProjectGroup.displayName}`+ scopedProjectGroups.length > 0+ ? `Filter threads by project: ${scopedProjectGroups.map((project) => project.displayName).join(", ")}`: "Filter threads by project"}/>}>- {scopedProjectGroup ? (+ {scopedProjectGroups.length > 1 ? (+ <span className="flex shrink-0 -space-x-1.5">+ {scopedProjectGroups.slice(0, 2).map((project) => (+ <ProjectFavicon+ key={project.projectKey}+ project={project}+ className="size-3.5"+ />+ ))}+ </span>+ ) : scopedProjectGroups[0] ? (<span className="flex shrink-0">- <ProjectFavicon project={scopedProjectGroup} className="size-4" />+ <ProjectFavicon project={scopedProjectGroups[0]} className="size-4" /></span>) : (<ListFilterIcon className="size-4" />@@ -2781,15 +2833,27 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveif (event.defaultPrevented ||event.nativeEvent.isComposing ||+ event.keyCode === 229 ||event.ctrlKey ||event.altKey ||- event.metaKey ||- (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10"))+ event.metaKey) {return;}const scopeKey = highlightedProjectScopeKeyRef.current;const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null;+ if (event.shiftKey && event.key === "Enter") {+ if (!project) return;+ event.preventDefault();+ toggleProjectScopeKey(project.projectKey);+ return;+ }+ if (+ event.key !== "ContextMenu" &&+ !(event.shiftKey && event.key === "F10")+ ) {+ return;+ }if (project) handleProjectSettings(event, project);}}onChange={(event) =>@@ -2800,23 +2864,31 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve}/><ComboboxEmpty>No matching projects.</ComboboxEmpty>- <ComboboxList>+ <ComboboxList aria-multiselectable>{(item: (typeof projectScopeItems)[number]) => {const project = projectGroupByScopeKey.get(item.value) ?? null;+ const isSelected = project+ ? projectScopeKeys.includes(item.value)+ : projectScopeKeys.length === 0;return (<ComboboxItemkey={item.value}hideIndicatorvalue={item}+ aria-selected={isSelected}+ // The icon badge marks selection; Base UI's single value would shade one row.+ data-selected={undefined}onContextMenu={(event) => {if (project) handleProjectSettings(event, project);}}>- {project ? (- <ProjectFavicon project={project} className="size-4 shrink-0" />- ) : (- <FolderIcon className="size-4 shrink-0" />- )}+ <ProjectScopeRowIcon isSelected={isSelected}>+ {project ? (+ <ProjectFavicon project={project} className="size-4 shrink-0" />+ ) : (+ <FolderIcon className="size-4 shrink-0" />+ )}+ </ProjectScopeRowIcon><span className="min-w-0 flex-1 truncate text-sm">{item.label}</span>{project && showProjectEnvironments ? (<ProjectEnvironmentBadge@@ -3261,8 +3333,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveAdd project</button></>- ) : scopedProjectGroup ? (- `No threads in ${scopedProjectGroup.displayName} yet`+ ) : scopedProjectGroups.length > 1 ? (+ "No threads in these projects yet"+ ) : scopedProjectGroups[0] ? (+ `No threads in ${scopedProjectGroups[0].displayName} yet`) : ("No threads yet")}diff --git a/apps/web/src/sidebarProjectGrouping.ts b/apps/web/src/sidebarProjectGrouping.tsindex 7182405bbd0..7764966c718 100644--- a/apps/web/src/sidebarProjectGrouping.ts+++ b/apps/web/src/sidebarProjectGrouping.ts@@ -84,6 +84,17 @@ export function resolveSidebarProjectScopeKey(input: {return group?.projectKey ?? (input.canClearMissingScope ? null : input.key);}+export function resolveSidebarProjectScopeKeys(input: {+ readonly groups: ReadonlyArray<SidebarProjectSnapshot>;+ readonly keys: ReadonlyArray<string>;+ readonly settings?: ProjectGroupingSettings;+ readonly canClearMissingScope?: boolean;+}): string[] {+ return [+ ...new Set(input.keys.flatMap((key) => resolveSidebarProjectScopeKey({ ...input, key }) ?? [])),+ ];+}+export function buildPhysicalToLogicalProjectKeyMap(input: {projects: ReadonlyArray<Project>;settings: ProjectGroupingSettings;diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.tsindex 787566116e0..dbfb60d15bd 100644--- a/apps/web/src/uiStateStore.test.ts+++ b/apps/web/src/uiStateStore.test.ts@@ -19,7 +19,7 @@ function makeUiState(overrides: Partial<UiState> = {}): UiState {return {projectExpandedById: {},projectOrder: [],- sidebarProjectScopeKey: null,+ sidebarProjectScopeKeys: [],threadLastVisitedAtById: {},threadChangedFilesExpandedById: {},defaultAdvertisedEndpointKey: null,@@ -125,7 +125,7 @@ describe("parsePersistedState", () => {"environment:thread-1": "2026-02-25T12:35:00.000Z",},defaultAdvertisedEndpointKey: "desktop-core:lan:http",- sidebarProjectScopeKey: null,+ sidebarProjectScopeKeys: [],pullRequestMergeMethod: "merge",threadChangedFilesExpandedById: {"environment:thread-1": {@@ -230,6 +230,7 @@ describe("uiStateStore persistence", () => {"environment:thread-1": "2026-02-25T12:35:00.000Z",},defaultAdvertisedEndpointKey: "desktop-core:lan:http",+ sidebarProjectScopeKeys: [],sidebarProjectScopeKey: null,threadChangedFilesExpansionVersion: 2,threadChangedFilesExpandedById: {@@ -246,14 +247,30 @@ describe("uiStateStore persistence", () => {});it("restores the sidebar project scope across reloads", () => {- persistState(makeUiState({ sidebarProjectScopeKey: "github.com/pingdotgg/t3code" }));+ const keys = ["github.com/pingdotgg/t3code", "github.com/pingdotgg/uploadthing"];+ persistState(makeUiState({ sidebarProjectScopeKeys: keys }));const persisted = JSON.parse(localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",) as PersistedUiState;- expect(parsePersistedState(persisted).sidebarProjectScopeKey).toBe(- "github.com/pingdotgg/t3code",- );+ expect(parsePersistedState(persisted).sidebarProjectScopeKeys).toEqual(keys);+ });++ it("keeps a single-project scope readable by older clients", () => {+ persistState(makeUiState({ sidebarProjectScopeKeys: ["github.com/pingdotgg/t3code"] }));++ const persisted = JSON.parse(+ localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",+ ) as PersistedUiState;++ expect(persisted.sidebarProjectScopeKey).toBe("github.com/pingdotgg/t3code");+ });++ it("restores a single-project scope saved before multi-project filtering", () => {+ expect(+ parsePersistedState({ sidebarProjectScopeKey: "github.com/pingdotgg/t3code" })+ .sidebarProjectScopeKeys,+ ).toEqual(["github.com/pingdotgg/t3code"]);});});diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.tsindex fe62eb77b70..0ecefc76a33 100644--- a/apps/web/src/uiStateStore.ts+++ b/apps/web/src/uiStateStore.ts@@ -27,6 +27,7 @@ export interface PersistedUiState {projectOrderCwds?: string[];defaultAdvertisedEndpointKey?: string | null;sidebarProjectScopeKey?: string | null;+ sidebarProjectScopeKeys?: string[];threadChangedFilesExpansionVersion?: number;threadChangedFilesExpandedById?: Record<string, Record<string, boolean>>;pullRequestMergeMethod?: string;@@ -35,7 +36,7 @@ export interface PersistedUiState {export interface UiProjectState {projectExpandedById: Record<string, boolean>;projectOrder: string[];- sidebarProjectScopeKey: string | null;+ sidebarProjectScopeKeys: string[];}export interface UiThreadState {@@ -57,7 +58,7 @@ export interface UiStateconst initialState: UiState = {projectExpandedById: {},projectOrder: [],- sidebarProjectScopeKey: null,+ sidebarProjectScopeKeys: [],threadLastVisitedAtById: {},threadChangedFilesExpandedById: {},defaultAdvertisedEndpointKey: null,@@ -150,7 +151,9 @@ export function parsePersistedState(parsed: PersistedUiState): UiState {? sanitizePersistedThreadChangedFilesExpanded(parsed.threadChangedFilesExpandedById): {},defaultAdvertisedEndpointKey: sanitizeOptionalKey(parsed.defaultAdvertisedEndpointKey),- sidebarProjectScopeKey: sanitizeOptionalKey(parsed.sidebarProjectScopeKey),+ sidebarProjectScopeKeys: sanitizeStringArray(+ parsed.sidebarProjectScopeKeys ?? [parsed.sidebarProjectScopeKey],+ ),pullRequestMergeMethod: isPullRequestMergeMethod(parsed.pullRequestMergeMethod)? parsed.pullRequestMergeMethod: initialState.pullRequestMergeMethod,@@ -224,7 +227,12 @@ export function persistState(state: UiState): void {projectOrder: state.projectOrder,threadLastVisitedAtById: state.threadLastVisitedAtById,defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey,- sidebarProjectScopeKey: state.sidebarProjectScopeKey,+ sidebarProjectScopeKeys: state.sidebarProjectScopeKeys,+ // Older clients read only this field.+ sidebarProjectScopeKey:+ state.sidebarProjectScopeKeys.length === 1+ ? (state.sidebarProjectScopeKeys[0] ?? null)+ : null,threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION,threadChangedFilesExpandedById: state.threadChangedFilesExpandedById,pullRequestMergeMethod: state.pullRequestMergeMethod,@@ -323,14 +331,17 @@ function setDefaultAdvertisedEndpointKey(state: UiState, key: string | null): Ui};}-function setSidebarProjectScopeKey(state: UiState, projectKey: string | null): UiState {- const nextKey = sanitizeOptionalKey(projectKey);- if (state.sidebarProjectScopeKey === nextKey) {+function setSidebarProjectScopeKeys(state: UiState, projectKeys: readonly string[]): UiState {+ const nextKeys = sanitizeStringArray(projectKeys);+ if (+ nextKeys.length === state.sidebarProjectScopeKeys.length &&+ nextKeys.every((key, index) => key === state.sidebarProjectScopeKeys[index])+ ) {return state;}return {...state,- sidebarProjectScopeKey: nextKey,+ sidebarProjectScopeKeys: nextKeys,};}@@ -422,7 +433,7 @@ interface UiStateStore extends UiState {markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void;setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void;setDefaultAdvertisedEndpointKey: (key: string | null) => void;- setSidebarProjectScopeKey: (projectKey: string | null) => void;+ setSidebarProjectScopeKeys: (projectKeys: readonly string[]) => void;setPullRequestMergeMethod: (method: PullRequestMergeMethod) => void;setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void;reorderProjects: (@@ -442,8 +453,8 @@ export const useUiStateStore = create<UiStateStore>((set) => ({set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)),setDefaultAdvertisedEndpointKey: (key) =>set((state) => setDefaultAdvertisedEndpointKey(state, key)),- setSidebarProjectScopeKey: (projectKey) =>- set((state) => setSidebarProjectScopeKey(state, projectKey)),+ setSidebarProjectScopeKeys: (projectKeys) =>+ set((state) => setSidebarProjectScopeKeys(state, projectKeys)),setPullRequestMergeMethod: (method) => set((state) => setPullRequestMergeMethod(state, method)),setProjectExpanded: (projectIds, expanded) =>set((state) => setProjectExpanded(state, projectIds, expanded)),