@devries-cameron20 / t3code Mirror · read-only / commits / 5d91ab1117
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 15:45 UTC

refactor(web): command palette state lives in a store, git and branch pickers drop timer and sync effects (#25733)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 21:28 UTC 5d91ab1117ad51ef1288a94717d85c70e7af09fe
23 files changed +867 -392
apps/web/src/appInit.tsx
+2
@@ -43,6 +43,7 @@ import { getRouter, type AppRouter } from "./router";
43 import { appAtomRegistry } from "./rpc/atomRegistry";
44 import { primaryServerConfigAtom } from "./state/server";
45 import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
46 +import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
47 import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
48 import { environmentThreadShells } from "./state/threads";
49 import { resolveThreadRouteTarget } from "./threadRoutes";
@@ -172,6 +173,7 @@ export function startAppServices(): AppRouter {
173 startPreviewTitleRecording();
174 startBrowserProfileReporting();
175 installChatRouteCommands(router);
176 + installCommandPaletteCommands(router);
177 registerOpenFavoriteEditorCommand();
178 startThreadOverlayRetention(router);
179 // Drafts promote as their server threads arrive, wherever the user is.
apps/web/src/commandPaletteBus.ts
+20 -16
@@ -1,34 +1,38 @@
1 import type { EnvironmentId, PullRequestLinkedThreadsResult } from "@t3tools/contracts";
2
3 +import { dispatchCommandPalette, isCommandPaletteMounted } from "./commandPaletteStore";
4 +
5 export interface CommandPaletteLinkedThreads {
6 readonly environmentId: EnvironmentId;
7 readonly threads: PullRequestLinkedThreadsResult["threads"];
8 }
9
8 -const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";
9 -
10 export interface CommandPaletteOpenDetail {
11 readonly open?: "add-project" | "new-thread-in";
12 readonly query?: string;
13 readonly linkedThreads?: CommandPaletteLinkedThreads;
14 }
15
16 -export function openCommandPalette(detail?: CommandPaletteOpenDetail): void {
17 - window.dispatchEvent(
18 - new CustomEvent(COMMAND_PALETTE_OPEN_EVENT, detail ? { detail } : undefined),
19 - );
20 -}
21 -
22 -export function onOpenCommandPalette(
23 - listener: (detail: CommandPaletteOpenDetail) => void,
24 -): () => void {
25 - const handler = (event: Event) => {
26 - listener((event as CustomEvent<CommandPaletteOpenDetail>).detail ?? {});
27 - };
28 - window.addEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
29 - return () => window.removeEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
16 +export function openCommandPalette(detail: CommandPaletteOpenDetail = {}): void {
17 + // With no palette on screen (e.g. /pair) the request is dropped; kept in the
18 + // store, it would pop a stale palette once the app shell mounts.
19 + if (!isCommandPaletteMounted()) return;
20 + if (detail.open === "new-thread-in") {
21 + dispatchCommandPalette({ _tag: "OpenNewThreadIn" });
22 + } else if (detail.open === "add-project") {
23 + dispatchCommandPalette({ _tag: "OpenAddProject" });
24 + } else if (detail.query !== undefined) {
25 + dispatchCommandPalette({
26 + _tag: "OpenSearch",
27 + query: detail.query,
28 + ...(detail.linkedThreads ? { linkedThreads: detail.linkedThreads } : {}),
29 + });
30 + } else {
31 + dispatchCommandPalette({ _tag: "SetOpen", open: true });
32 + }
33 }
34
35 +/** True while the palette popup is on screen, including its closing animation. */
36 export function isCommandPaletteOpen(): boolean {
37 return (
38 typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
apps/web/src/commandPaletteStore.ts new
+49
@@ -0,0 +1,49 @@
1 +import { useEffect } from "react";
2 +import { create } from "zustand";
3 +
4 +import {
5 + type CommandPaletteUiAction,
6 + type CommandPaletteUiState,
7 + reduceCommandPaletteUiState,
8 +} from "./components/CommandPalette.logic";
9 +
10 +const INITIAL_STATE: CommandPaletteUiState = {
11 + open: false,
12 + mode: "command",
13 + openIntent: null,
14 + session: 0,
15 +};
16 +
17 +export const useCommandPaletteStore = create<CommandPaletteUiState>(() => INITIAL_STATE);
18 +
19 +export function dispatchCommandPalette(action: CommandPaletteUiAction): void {
20 + useCommandPaletteStore.setState((state) => reduceCommandPaletteUiState(state, action), true);
21 +}
22 +
23 +// The palette is only mounted on app-shell routes (not /pair, sign-in or
24 +// landings), so its shortcuts must stay inert elsewhere.
25 +let mountedPalettes = 0;
26 +
27 +export function isCommandPaletteMounted(): boolean {
28 + return mountedPalettes > 0;
29 +}
30 +
31 +/**
32 + * Marks the palette as mounted while the calling component is. An unmounted
33 + * palette cannot stay open, so the last unmount resets the store.
34 + */
35 +export function useCommandPaletteMount(): void {
36 + // oxlint-disable-next-line t3code/react-effect-budget -- The palette's mount gates its global shortcuts, and leaving the route while it is open calls no close handler, so only unmount can reset the store.
37 + useEffect(() => {
38 + mountedPalettes += 1;
39 + return () => {
40 + mountedPalettes -= 1;
41 + if (mountedPalettes === 0) {
42 + useCommandPaletteStore.setState(
43 + (state) => ({ ...INITIAL_STATE, session: state.session + 1 }),
44 + true,
45 + );
46 + }
47 + };
48 + }, []);
49 +}
apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx new
+95
@@ -0,0 +1,95 @@
1 +import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2 +import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render } from "../../test/render";
6 +
7 +const project = vi.hoisted(() => {
8 + let value: unknown = null;
9 + const listeners = new Set<() => void>();
10 + return {
11 + // Each test starts from no project and no listeners left by an earlier test.
12 + setup: (initial: unknown) => {
13 + value = initial;
14 + listeners.clear();
15 + },
16 + get: () => value,
17 + set: (next: unknown) => {
18 + value = next;
19 + for (const listener of listeners) listener();
20 + },
21 + subscribe: (listener: () => void) => {
22 + listeners.add(listener);
23 + return () => listeners.delete(listener);
24 + },
25 + };
26 +});
27 +
28 +vi.mock(import("../state/entities"), async (original) => {
29 + const { useSyncExternalStore } = await import("react");
30 + return {
31 + ...(await original()),
32 + readProject: (() => project.get()) as never,
33 + subscribeProject: ((_ref: unknown, listener: (value: unknown) => void) =>
34 + project.subscribe(() => listener(project.get()))) as never,
35 + useProject: (() => useSyncExternalStore(project.subscribe, project.get)) as never,
36 + };
37 +});
38 +vi.mock(import("../state/environments"), async (original) => ({
39 + ...(await original()),
40 + useEnvironments: (() => ({ environments: [] })) as never,
41 +}));
42 +vi.mock(import("../hooks/useHandleNewThread"), async (original) => ({
43 + ...(await original()),
44 + useNewThreadHandler: (() => () => undefined) as never,
45 +}));
46 +vi.mock(import("../hooks/useAddProjectTargets"), async (original) => ({
47 + ...(await original()),
48 + useAddProjectTargets: (() => []) as never,
49 +}));
50 +vi.mock(import("../hooks/useLogicalProjectEnvironments"), async (original) => ({
51 + ...(await original()),
52 + useLogicalProjectEnvironments: (() => []) as never,
53 +}));
54 +
55 +import {
56 + AddProjectToMachineDialogHost,
57 + openAddProjectToMachine,
58 +} from "./AddProjectToMachineDialog";
59 +
60 +const environmentId = EnvironmentId.make("environment-1");
61 +const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-1"));
62 +const PROJECT = {
63 + environmentId,
64 + id: projectRef.projectId,
65 + title: "Repo",
66 + workspaceRoot: "/repo",
67 + repositoryIdentity: null,
68 +};
69 +
70 +describe("AddProjectToMachineDialog", () => {
71 + it("closes when its project goes away", async () => {
72 + project.setup(PROJECT);
73 + await using screen = await render(<AddProjectToMachineDialogHost />);
74 +
75 + await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: null }));
76 + await expect.element(screen.getByText("Add to another machine")).toBeInTheDocument();
77 +
78 + await act(() => project.set(null));
79 + await act(() => project.set(PROJECT));
80 + await expect.element(screen.getByText("Add to another machine")).not.toBeInTheDocument();
81 + });
82 +
83 + it("does not reopen for a project that vanished before the dialog showed", async () => {
84 + project.setup(PROJECT);
85 + await using screen = await render(<AddProjectToMachineDialogHost />);
86 +
87 + await act(() => {
88 + openAddProjectToMachine({ projectRef, targetEnvironmentId: null });
89 + project.set(null);
90 + });
91 + await act(() => project.set(PROJECT));
92 +
93 + await expect.element(screen.getByText("Add to another machine")).not.toBeInTheDocument();
94 + });
95 +});
apps/web/src/components/AddProjectToMachineDialog.tsx
+21 -10
@@ -17,7 +17,7 @@ import {
17 cloneUrlProtocol,
18 } from "@t3tools/shared/cloneUrl";
19 import { ArrowRightIcon } from "lucide-react";
20 -import { useEffect, useId, useState } from "react";
20 +import { useId, useState } from "react";
21 import { create } from "zustand";
22
23 import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
@@ -31,7 +31,7 @@ import {
31 } from "../lib/addProjectToMachine";
32 import { formatBytes } from "../lib/formatBytes";
33 import { newProjectId } from "../lib/utils";
34 -import { useProject } from "../state/entities";
34 +import { readProject, subscribeProject, useProject } from "../state/entities";
35 import { useEnvironments } from "../state/environments";
36 import { projectEnvironment } from "../state/projects";
37 import { useEnvironmentQuery } from "../state/query";
@@ -58,20 +58,35 @@ interface AddProjectToMachineRequest {
58 readonly targetEnvironmentId: EnvironmentId | null;
59 }
60
61 -const useRequest = create<{ request: AddProjectToMachineRequest | null }>(() => ({
61 +const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({
62 request: null,
63 + session: 0,
64 }));
65
66 +let endRequestWithProject: (() => void) | null = null;
67 +
68 /** Opens the dialog that clones a project onto another connected machine. */
69 export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
67 - useRequest.setState({ request });
70 + if (readProject(request.projectRef) === null) return;
71 + endRequestWithProject?.();
72 + // The request ends when its project goes away, so a project that comes back
73 + // later cannot reopen a dialog nobody asked for.
74 + endRequestWithProject = subscribeProject(request.projectRef, (project) => {
75 + if (project === null) close();
76 + });
77 + useRequest.setState((state) => ({ request, session: state.session + 1 }));
78 }
79
70 -const close = () => useRequest.setState({ request: null });
80 +function close() {
81 + endRequestWithProject?.();
82 + endRequestWithProject = null;
83 + useRequest.setState({ request: null });
84 +}
85
86 export function AddProjectToMachineDialogHost() {
87 const request = useRequest((state) => state.request);
74 - return request ? <AddProjectToMachineDialog request={request} /> : null;
88 + const session = useRequest((state) => state.session);
89 + return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;
90 }
91
92 function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
@@ -128,10 +143,6 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
143 project === null ||
144 target === null ||
145 (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
131 - useEffect(() => {
132 - if (project === null) close();
133 - }, [project]);
134 -
146 const toggleFile = (path: string, checked: boolean) => {
147 const next = new Set(selectedFiles);
148 if (checked) next.add(path);
apps/web/src/components/BranchPicker.tsx
+21 -37
@@ -1,16 +1,9 @@
1 import type { VcsRef } from "@t3tools/contracts";
2 import { LegendList, type LegendListRef } from "@legendapp/list/react";
3 -import {
4 - useEffect,
5 - useId,
6 - useLayoutEffect,
7 - useRef,
8 - useState,
9 - type ComponentProps,
10 - type ReactNode,
11 -} from "react";
3 +import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";
4
5 import { MiddleTruncate } from "./ui/middle-truncate";
6 +import { observeResize } from "../lib/observeResize";
7 import { cn } from "../lib/utils";
8 import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
9 import { RefreshIcon } from "./ui/refresh-icon";
@@ -32,7 +25,6 @@ export function BranchPicker({
25 filteredItems,
26 value,
27 query,
35 - resultsQuery,
28 onQueryChange,
29 open,
30 onOpenChange,
@@ -51,7 +43,6 @@ export function BranchPicker({
43 filteredItems: string[];
44 value: string | null;
45 query: string;
54 - resultsQuery: string;
46 onQueryChange: (value: string) => void;
47 open: boolean;
48 onOpenChange: (open: boolean) => void;
@@ -121,32 +112,22 @@ export function BranchPicker({
112 setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
113 };
114
124 - useLayoutEffect(() => {
125 - if (!open) {
126 - return;
127 - }
128 -
129 - let nestedFrame = 0;
130 - const frame = requestAnimationFrame(() => {
131 - updateBranchListScrollFades();
132 - nestedFrame = requestAnimationFrame(updateBranchListScrollFades);
133 - });
115 + // The popup mounts the list when it opens. Its content settles over a few
116 + // frames as rows measure, so the fades follow the scroller and its content.
117 + const attachBranchList = (list: LegendListRef | null) => {
118 + branchListRef.current = list;
119 + const scrollElement = list?.getScrollableNode?.();
120 + if (!(scrollElement instanceof HTMLElement)) return;
121 + const content = scrollElement.firstElementChild;
122 + const stopObserving = observeResize(
123 + content ? [scrollElement, content] : scrollElement,
124 + updateBranchListScrollFades,
125 + );
126 return () => {
135 - cancelAnimationFrame(frame);
136 - cancelAnimationFrame(nestedFrame);
127 + stopObserving();
128 + branchListRef.current = null;
129 };
138 - }, [open, updateBranchListScrollFades]);
139 -
140 - const previousResultsQuery = useRef<string | null>(null);
141 - useEffect(() => {
142 - if (!open) {
143 - previousResultsQuery.current = null;
144 - return;
145 - }
146 - if (previousResultsQuery.current === resultsQuery) return;
147 - previousResultsQuery.current = resultsQuery;
148 - void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
149 - }, [resultsQuery, open]);
130 + };
131
132 return (
133 <Combobox
@@ -173,7 +154,10 @@ export function BranchPicker({
154 <ComboboxSearchInput
155 placeholder="Search refs..."
156 value={query}
176 - onChange={(event) => onQueryChange(event.target.value)}
157 + onChange={(event) => {
158 + onQueryChange(event.target.value);
159 + void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
160 + }}
161 onKeyDown={(event) => {
162 if (event.key !== "Enter" || event.nativeEvent.isComposing || event.keyCode === 229)
163 return;
@@ -193,7 +177,7 @@ export function BranchPicker({
177 <div className="relative flex min-h-0 w-full max-h-56 flex-1 flex-col overflow-hidden">
178 <ComboboxListVirtualized className="flex size-full min-h-0 min-w-0 flex-col">
179 <LegendList<string>
196 - ref={branchListRef}
180 + ref={attachBranchList}
181 data={filteredItems}
182 keyExtractor={(item) => item}
183 {...(getItemType ? { getItemType } : {})}
apps/web/src/components/BranchToolbarBranchSelector.tsx
-1
@@ -652,7 +652,6 @@ export function BranchToolbarBranchSelector({
652 onSelectItem={selectPickerItem}
653 value={resolvedActiveBranch}
654 query={branchQuery}
655 - resultsQuery={deferredTrimmedBranchQuery}
655 onQueryChange={setBranchQuery}
656 hasNextPage={hasNextPage}
657 isFetchingNextPage={isFetchingNextPage}
apps/web/src/components/CommandPalette.browser.test.tsx new
+33
@@ -0,0 +1,33 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +import { page } from "vite-plus/test/browser";
3 +
4 +import { render } from "../../test/render";
5 +import { openCommandPalette } from "../commandPaletteBus";
6 +import { useCommandPaletteStore } from "../commandPaletteStore";
7 +import { CommandPalette } from "./CommandPalette";
8 +
9 +function setup() {
10 + useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true);
11 +}
12 +
13 +describe("CommandPalette open intents", () => {
14 + it("opens New thread in... with focus in the search input, not the Back button", async () => {
15 + setup();
16 + await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
17 +
18 + openCommandPalette({ open: "new-thread-in" });
19 +
20 + await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();
21 + });
22 +
23 + it("opens a search intent with its query in the focused input", async () => {
24 + setup();
25 + await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
26 +
27 + openCommandPalette({ query: "acme" });
28 +
29 + const input = page.getByPlaceholder("Search commands, projects, and threads...");
30 + await expect.element(input).toHaveFocus();
31 + await expect.element(input).toHaveValue("acme");
32 + });
33 +});
apps/web/src/components/CommandPalette.logic.test.ts
+57 -4
@@ -9,6 +9,7 @@ import {
9 filterPinnedBrowseEntries,
10 filterCommandPaletteGroups,
11 reduceCommandPaletteUiState,
12 + resolveAddProjectEntry,
13 createCommandPaletteSearchState,
14 reduceCommandPaletteSearchState,
15 type CommandPaletteUiState,
@@ -32,7 +33,7 @@ describe("linked pull request thread navigation", () => {
33 ],
34 };
35 const state = reduceCommandPaletteUiState(
35 - { open: false, mode: "command", openIntent: null },
36 + { open: false, mode: "command", openIntent: null, session: 0 },
37 {
38 _tag: "OpenSearch",
39 query,
@@ -59,7 +60,7 @@ describe("linked pull request thread navigation", () => {
60 describe("reduceCommandPaletteUiState", () => {
61 it("opens PR search from another overlay and replaces an earlier search", () => {
62 const first = reduceCommandPaletteUiState(
62 - { open: true, mode: "files", openIntent: null },
63 + { open: true, mode: "files", openIntent: null, session: 0 },
64 {
65 _tag: "OpenSearch",
66 query: "https://github.com/acme/web/pull/7",
@@ -69,6 +70,7 @@ describe("reduceCommandPaletteUiState", () => {
70 open: true,
71 mode: "command",
72 openIntent: { kind: "search", query: "https://github.com/acme/web/pull/7" },
73 + session: 1,
74 });
75 const second = reduceCommandPaletteUiState(first, {
76 _tag: "OpenSearch",
@@ -78,10 +80,56 @@ describe("reduceCommandPaletteUiState", () => {
80 kind: "search",
81 query: "https://github.com/acme/web/pull/8",
82 });
83 + // The second intent starts a new session, so the open palette starts over from it.
84 + expect(second.session).toBe(2);
85 expect(
86 reduceCommandPaletteUiState(second, { _tag: "SetOpen", open: false }).openIntent,
87 ).toBeNull();
88 });
89 +
90 + it("keeps the session across mode switches so only intents start the palette over", () => {
91 + let state: CommandPaletteUiState = {
92 + open: false,
93 + mode: "command",
94 + openIntent: null,
95 + session: 0,
96 + };
97 + state = reduceCommandPaletteUiState(state, { _tag: "OpenNewThreadIn" });
98 + expect(state).toMatchObject({ open: true, openIntent: { kind: "new-thread-in" }, session: 1 });
99 + state = reduceCommandPaletteUiState(state, { _tag: "ToggleMode", mode: "files" });
100 + expect(state).toMatchObject({ mode: "files", openIntent: null, session: 1 });
101 + state = reduceCommandPaletteUiState(state, { _tag: "OpenAddProject" });
102 + expect(state).toMatchObject({
103 + mode: "command",
104 + openIntent: { kind: "add-project" },
105 + session: 2,
106 + });
107 + });
108 +});
109 +
110 +describe("resolveAddProjectEntry", () => {
111 + const local = EnvironmentId.make("local");
112 + const remote = EnvironmentId.make("remote");
113 +
114 + it("sends the user to connect an environment when none can add a project", () => {
115 + expect(resolveAddProjectEntry([], null)).toEqual({ kind: "connect-environment" });
116 + });
117 +
118 + it("asks for an environment when there is a choice or no connected default", () => {
119 + expect(
120 + resolveAddProjectEntry([{ environmentId: local }, { environmentId: remote }], local),
121 + ).toEqual({ kind: "choose-environment" });
122 + expect(resolveAddProjectEntry([{ environmentId: local }], null)).toEqual({
123 + kind: "choose-environment",
124 + });
125 + });
126 +
127 + it("goes straight to sources for the only environment", () => {
128 + expect(resolveAddProjectEntry([{ environmentId: local }], local)).toEqual({
129 + kind: "choose-source",
130 + environmentId: local,
131 + });
132 + });
133 });
134
135 const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
@@ -825,7 +873,12 @@ describe("command palette search return", () => {
873 });
874
875 describe("returning from file and content search", () => {
828 - const root: CommandPaletteUiState = { open: true, mode: "command", openIntent: null };
876 + const root: CommandPaletteUiState = {
877 + open: true,
878 + mode: "command",
879 + openIntent: null,
880 + session: 0,
881 + };
882 const query = "https://github.com/acme/web/pull/7";
883 const context = {
884 query,
@@ -860,7 +913,7 @@ describe("returning from file and content search", () => {
913 it("closing a child search discards its return context before reopening", () => {
914 const child: CommandPaletteUiState = { ...root, mode: "files", parentSearch: context };
915 const closed = reduceCommandPaletteUiState(child, { _tag: "SetOpen", open: false });
863 - expect(closed).toEqual({ open: false, mode: "files", openIntent: null });
916 + expect(closed).toEqual({ open: false, mode: "files", openIntent: null, session: 0 });
917 expect(reduceCommandPaletteUiState(closed, { _tag: "BackToCommand" })).toEqual(closed);
918 expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual(root);
919 });
apps/web/src/components/CommandPalette.logic.ts
+45 -20
@@ -81,7 +81,10 @@ export type CommandPaletteOpenIntent =
81 export interface CommandPaletteUiState {
82 readonly open: boolean;
83 readonly mode: SearchOverlayMode;
84 + /** What the current palette session opened to; read once when the palette view mounts. */
85 readonly openIntent: CommandPaletteOpenIntent | null;
86 + /** Bumped by every intent so an open palette starts over from the new one. */
87 + readonly session: number;
88 readonly parentSearch?: CommandPaletteReturnContext;
89 readonly restoredSearch?: CommandPaletteReturnContext;
90 }
@@ -97,7 +100,6 @@ export type CommandPaletteUiAction =
100 | { readonly _tag: "OpenAddProject" }
101 | { readonly _tag: "OpenNewThreadIn" }
102 | { readonly _tag: "OpenChangeTheme" }
100 - | { readonly _tag: "ClearOpenIntent" }
103 | {
104 readonly _tag: "OpenChildSearch";
105 readonly mode: "files" | "content";
@@ -109,47 +111,70 @@ export function reduceCommandPaletteUiState(
111 state: CommandPaletteUiState,
112 action: CommandPaletteUiAction,
113 ): CommandPaletteUiState {
114 + const { session } = state;
115 + const openWithIntent = (openIntent: CommandPaletteOpenIntent): CommandPaletteUiState => ({
116 + open: true,
117 + mode: "command",
118 + openIntent,
119 + session: session + 1,
120 + });
121 switch (action._tag) {
122 case "SetOpen":
123 return action.open
115 - ? { open: true, mode: "command", openIntent: state.openIntent }
116 - : { open: false, mode: state.mode, openIntent: null };
124 + ? { open: true, mode: "command", openIntent: state.openIntent, session }
125 + : { open: false, mode: state.mode, openIntent: null, session };
126 case "ToggleMode":
127 return state.open && state.mode === action.mode
119 - ? { open: false, mode: state.mode, openIntent: null }
120 - : { open: true, mode: action.mode, openIntent: null };
128 + ? { open: false, mode: state.mode, openIntent: null, session }
129 + : { open: true, mode: action.mode, openIntent: null, session };
130 case "OpenChildSearch":
122 - return { open: true, mode: action.mode, openIntent: null, parentSearch: action.context };
131 + return {
132 + open: true,
133 + mode: action.mode,
134 + openIntent: null,
135 + session,
136 + parentSearch: action.context,
137 + };
138 case "BackToCommand":
139 return state.open && state.mode !== "command"
140 ? {
141 open: true,
142 mode: "command",
143 openIntent: null,
144 + session,
145 ...(state.parentSearch ? { restoredSearch: state.parentSearch } : {}),
146 }
147 : state;
148 case "OpenSearch":
133 - return {
134 - open: true,
135 - mode: "command",
136 - openIntent: {
137 - kind: "search",
138 - query: action.query,
139 - ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
140 - },
141 - };
149 + return openWithIntent({
150 + kind: "search",
151 + query: action.query,
152 + ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
153 + });
154 case "OpenAddProject":
143 - return { open: true, mode: "command", openIntent: { kind: "add-project" } };
155 + return openWithIntent({ kind: "add-project" });
156 case "OpenNewThreadIn":
145 - return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
157 + return openWithIntent({ kind: "new-thread-in" });
158 case "OpenChangeTheme":
147 - return { open: true, mode: "command", openIntent: { kind: "change-theme" } };
148 - case "ClearOpenIntent":
149 - return state.openIntent ? { ...state, openIntent: null } : state;
159 + return openWithIntent({ kind: "change-theme" });
160 }
161 }
162
163 +/** Where "Add project" starts, given the environments that can take a new project. */
164 +export type AddProjectEntry =
165 + | { readonly kind: "connect-environment" }
166 + | { readonly kind: "choose-environment" }
167 + | { readonly kind: "choose-source"; readonly environmentId: EnvironmentId };
168 +
169 +export function resolveAddProjectEntry(
170 + options: ReadonlyArray<Pick<AddProjectEnvironmentOption, "environmentId">>,
171 + defaultEnvironmentId: EnvironmentId | null,
172 +): AddProjectEntry {
173 + if (options.length === 0) return { kind: "connect-environment" };
174 + if (options.length > 1 || defaultEnvironmentId === null) return { kind: "choose-environment" };
175 + return { kind: "choose-source", environmentId: defaultEnvironmentId };
176 +}
177 +
178 export interface CommandPaletteThreadContentMatch {
179 readonly source: "user" | "assistant";
180 readonly snippet: string;
apps/web/src/components/CommandPalette.tsx
+131 -230
@@ -74,8 +74,6 @@ import { openThreadFind } from "./chat/threadFindStore";
74 import {
75 useDeferredValue,
76 useEffect,
77 - useEffectEvent,
78 - useLayoutEffect,
77 useReducer,
78 useRef,
79 useState,
@@ -97,7 +95,6 @@ import {
95 } from "./promptLinks/copyPromptLink";
96 import { useClientSettings } from "../hooks/useSettings";
97 import { useStableCallback } from "../hooks/useStableCallback";
100 -import { useTheme } from "../hooks/useTheme";
98 import { readLocalApi } from "../localApi";
99 import { desktopLocalBackendId } from "../connection/desktopLocal";
100 import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem";
@@ -130,14 +127,12 @@ import {
127 isUnsupportedWindowsProjectPath,
128 resolveProjectPathForDispatch,
129 } from "../lib/projectPaths";
133 -import { onOpenCommandPalette } from "../commandPaletteBus";
134 -import { isPreviewFocused } from "../lib/previewFocus";
135 -import { isTerminalFocused } from "../lib/terminalFocus";
130 import {
137 - PULL_REQUESTS_PANEL_REF,
138 - selectActiveRightPanel,
139 - useRightPanelStore,
140 -} from "../rightPanelStore";
131 + dispatchCommandPalette,
132 + useCommandPaletteMount,
133 + useCommandPaletteStore,
134 +} from "../commandPaletteStore";
135 +import { PULL_REQUESTS_PANEL_REF, useRightPanelStore } from "../rightPanelStore";
136 import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
137 import {
138 cn,
@@ -146,7 +141,6 @@ import {
141 isWindowsPlatform,
142 newProjectId,
143 } from "../lib/utils";
149 -import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
144 import { buildThreadRouteParams } from "../threadRoutes";
145 import { useAvailableSettingsSearchItems } from "./settings/useAvailableSettingsSearchItems";
146 import {
@@ -177,14 +171,14 @@ import {
171 getCommandPaletteMode,
172 ITEM_ICON_CLASS,
173 RECENT_THREAD_LIMIT,
180 - reduceCommandPaletteUiState,
174 createCommandPaletteSearchState,
175 + type CommandPaletteGroup,
176 + resolveAddProjectEntry,
177 type AddProjectCloneFlow,
178 type AddProjectEnvironmentOption,
179 buildPaletteRemoteSourceReadiness,
180 errorMessage,
181 getEnvironmentBrowsePlatform,
187 - overlayModeForCommand,
182 remoteProjectInputPlaceholder,
183 reduceCommandPaletteSearchState,
184 type SearchOverlayMode,
@@ -210,11 +204,7 @@ import {
204 sourceControlHostIcon,
205 } from "./CommandPaletteAddProject";
206 import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems";
213 -import {
214 - APPEARANCE_OPTIONS,
215 - notifyThemeSaveFailure,
216 - useCommandPaletteThemeItems,
217 -} from "./CommandPaletteThemeItems";
207 +import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems";
208 import {
209 CommandPaletteVirtualizedResults,
210 scrollCommandPaletteRowIntoView,
@@ -226,7 +216,6 @@ import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";
216 import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
217 import { openGuestShareDialog } from "./chat/guestShareDialogState";
218 import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
229 -import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";
219 import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
220 import { primaryServerKeybindingsAtom } from "../state/server";
221 import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
@@ -243,148 +232,40 @@ import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
232 import { threadRecentUse } from "@t3tools/shared/paletteSearch";
233
234 const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
235 +const ADD_PROJECT_ENTRY_GROUP = "add-project";
236 +const NEW_THREAD_IN_GROUP = "projects";
237 +
238 +/** The submenu an open intent starts in; its groups resolve while rendering. */
239 +function openIntentView(intent: CommandPaletteOpenIntent | null): CommandPaletteView | null {
240 + switch (intent?.kind) {
241 + case "add-project":
242 + return {
243 + addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
244 + groups: [{ value: ADD_PROJECT_ENTRY_GROUP, label: "", items: [] }],
245 + };
246 + case "new-thread-in":
247 + return {
248 + addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
249 + groups: [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: [] }],
250 + };
251 + case "change-theme":
252 + return {
253 + addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />,
254 + groups: [{ value: "themes", label: "Change theme", items: [] }],
255 + };
256 + case "search":
257 + case undefined:
258 + return null;
259 + }
260 +}
261
262 export function CommandPalette({ children }: { children: ReactNode }) {
248 - const navigate = useNavigate();
249 - const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
250 - const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {
251 - open: false,
252 - mode: "command",
253 - openIntent: null,
254 - });
255 - const setOpen = (open: boolean) => dispatch({ _tag: "SetOpen", open });
256 - const toggleMode = (mode: SearchOverlayMode) => dispatch({ _tag: "ToggleMode", mode });
257 - const openAddProject = () => dispatch({ _tag: "OpenAddProject" });
258 - const openNewThreadIn = () => dispatch({ _tag: "OpenNewThreadIn" });
259 - const clearOpenIntent = () => dispatch({ _tag: "ClearOpenIntent" });
263 + useCommandPaletteMount();
264 + const state = useCommandPaletteStore();
265 + const setOpen = (open: boolean) => dispatchCommandPalette({ _tag: "SetOpen", open });
266 const openChildSearch = (mode: "files" | "content", context: CommandPaletteReturnContext) =>
261 - dispatch({ _tag: "OpenChildSearch", mode, context });
262 - const keybindings = useAtomValue(primaryServerKeybindingsAtom);
263 - const { theme, themeHalves, resolvedTheme, appearanceMode, setAppearanceMode } = useTheme();
267 + dispatchCommandPalette({ _tag: "OpenChildSearch", mode, context });
268 const composerHandleRef = useRef<ChatComposerHandle | null>(null);
265 - const routeTarget = useThreadRouteTarget();
266 - const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
267 - const terminalOpen = useTerminalUiStateStore((state) =>
268 - routeThreadRef
269 - ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
270 - : false,
271 - );
272 - const previewOpen = useRightPanelStore((state) =>
273 - routeThreadRef
274 - ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
275 - : false,
276 - );
277 -
278 - useEffect(() => {
279 - if (!state.open || state.mode === "command") return;
280 - const onEscapeKeyDown = (event: globalThis.KeyboardEvent) => {
281 - if (event.isComposing || event.key !== "Escape") return;
282 - event.preventDefault();
283 - event.stopPropagation();
284 - dispatch({ _tag: "BackToCommand" });
285 - };
286 - window.addEventListener("keydown", onEscapeKeyDown, true);
287 - return () => window.removeEventListener("keydown", onEscapeKeyDown, true);
288 - }, [state.mode, state.open]);
289 -
290 - useEffect(() => {
291 - const onKeyDown = (event: globalThis.KeyboardEvent) => {
292 - if (event.defaultPrevented) return;
293 - const command = resolveShortcutCommand(event, keybindings, {
294 - context: {
295 - terminalFocus: isTerminalFocused(),
296 - terminalOpen,
297 - previewFocus: isPreviewFocused(),
298 - previewOpen,
299 - modelPickerOpen: composerHandleRef.current?.isModelPickerOpen() ?? false,
300 - usagePageOpen,
301 - },
302 - });
303 - if (command === "appearance.cycle") {
304 - event.preventDefault();
305 - event.stopPropagation();
306 - if (event.repeat) return;
307 - const nextMode =
308 - appearanceMode === "system" ? "light" : appearanceMode === "light" ? "dark" : "system";
309 - if (!setAppearanceMode(nextMode)) {
310 - notifyThemeSaveFailure();
311 - } else {
312 - toastManager.add({
313 - id: "appearance-cycle",
314 - title: `Appearance: ${APPEARANCE_OPTIONS.find((option) => option.mode === nextMode)?.label}`,
315 - timeout: 1500,
316 - });
317 - }
318 - return;
319 - }
320 - if (command === "theme.select") {
321 - event.preventDefault();
322 - event.stopPropagation();
323 - if (event.repeat) return;
324 - dispatch({ _tag: "OpenChangeTheme" });
325 - return;
326 - }
327 - if (command === "themeEditor.toggle") {
328 - event.preventDefault();
329 - event.stopPropagation();
330 - toggleThemeEditorForTheme({
331 - theme,
332 - themeHalves,
333 - initialAppearance: resolvedTheme,
334 - });
335 - return;
336 - }
337 - if (command === "usage.open") {
338 - event.preventDefault();
339 - event.stopPropagation();
340 - setOpen(false);
341 - void navigate({ to: "/usage" });
342 - return;
343 - }
344 - const mode = overlayModeForCommand(command);
345 - if (mode === null) {
346 - return;
347 - }
348 - event.preventDefault();
349 - event.stopPropagation();
350 - toggleMode(mode);
351 - };
352 - window.addEventListener("keydown", onKeyDown);
353 - return () => window.removeEventListener("keydown", onKeyDown);
354 - }, [
355 - appearanceMode,
356 - keybindings,
357 - navigate,
358 - previewOpen,
359 - resolvedTheme,
360 - setAppearanceMode,
361 - setOpen,
362 - terminalOpen,
363 - theme,
364 - themeHalves,
365 - toggleMode,
366 - usagePageOpen,
367 - ]);
368 -
369 - useEffect(
370 - () =>
371 - onOpenCommandPalette((detail) => {
372 - if (detail.open === "new-thread-in") {
373 - openNewThreadIn();
374 - } else if (detail.open === "add-project") {
375 - openAddProject();
376 - } else if (detail.query !== undefined) {
377 - dispatch({
378 - _tag: "OpenSearch",
379 - query: detail.query,
380 - ...(detail.linkedThreads ? { linkedThreads: detail.linkedThreads } : {}),
381 - });
382 - } else {
383 - setOpen(true);
384 - }
385 - }),
386 - [openAddProject, openNewThreadIn, setOpen],
387 - );
269
270 return (
271 <ComposerHandleContext value={composerHandleRef}>
@@ -393,7 +274,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
274 onOpenChange={(open, eventDetails) => {
275 if (!open && eventDetails.reason === "escape-key" && state.mode !== "command") {
276 eventDetails.cancel();
396 - dispatch({ _tag: "BackToCommand" });
277 + dispatchCommandPalette({ _tag: "BackToCommand" });
278 return;
279 }
280 setOpen(open);
@@ -404,11 +285,11 @@ export function CommandPalette({ children }: { children: ReactNode }) {
285 </div>
286 <CommandPaletteDialog
287 mode={state.mode}
288 + session={state.session}
289 openIntent={state.openIntent}
290 setOpen={setOpen}
291 openChildSearch={openChildSearch}
292 initialContext={state.restoredSearch}
411 - clearOpenIntent={clearOpenIntent}
293 />
294 </CommandDialog>
295 </ComposerHandleContext>
@@ -417,6 +298,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
298
299 function CommandPaletteDialog(props: {
300 readonly mode: SearchOverlayMode;
301 + readonly session: number;
302 readonly openIntent: CommandPaletteOpenIntent | null;
303 readonly setOpen: (open: boolean) => void;
304 readonly openChildSearch: (
@@ -424,7 +306,6 @@ function CommandPaletteDialog(props: {
306 context: CommandPaletteReturnContext,
307 ) => void;
308 readonly initialContext: CommandPaletteReturnContext | undefined;
427 - readonly clearOpenIntent: () => void;
309 }) {
310 const composerHandleRef = useComposerHandleContext();
311
@@ -457,11 +338,11 @@ function CommandPaletteDialog(props: {
338 <ProjectContentSearchDialog onOpenChange={props.setOpen} />
339 ) : (
340 <OpenCommandPaletteDialog
341 + key={props.session}
342 openIntent={props.openIntent}
343 setOpen={props.setOpen}
344 openChildSearch={props.openChildSearch}
345 initialContext={props.initialContext}
464 - clearOpenIntent={props.clearOpenIntent}
346 />
347 )}
348 </CommandDialogPopup>
@@ -476,28 +357,34 @@ function OpenCommandPaletteDialog(props: {
357 context: CommandPaletteReturnContext,
358 ) => void;
359 readonly initialContext: CommandPaletteReturnContext | undefined;
479 - readonly clearOpenIntent: () => void;
360 }) {
361 const navigate = useNavigate();
362 const pathname = useLocation({ select: (location) => location.pathname });
483 - const { clearOpenIntent, openIntent, openChildSearch, setOpen } = props;
484 - const initialSearch = props.initialContext ?? {
485 - query: openIntent?.kind === "search" ? openIntent.query : "",
486 - linkedThreadSearch: openIntent?.kind === "search" ? openIntent : null,
487 - };
488 - const [searchState, dispatchSearch] = useReducer(
489 - reduceCommandPaletteSearchState,
490 - initialSearch.query,
491 - createCommandPaletteSearchState,
363 + const { openChildSearch, setOpen } = props;
364 + // Keyed by palette session: the intent and restored search only seed this
365 + // mount, and closing must not change what the closing palette shows.
366 + const [initialSearch] = useState(
367 + () =>
368 + props.initialContext ?? {
369 + query: props.openIntent?.kind === "search" ? props.openIntent.query : "",
370 + linkedThreadSearch: props.openIntent?.kind === "search" ? props.openIntent : null,
371 + },
372 );
373 + const linkedThreadSearch = initialSearch.linkedThreadSearch;
374 + const [searchState, dispatchSearch] = useReducer(reduceCommandPaletteSearchState, null, () => {
375 + const view = props.initialContext ? null : openIntentView(props.openIntent);
376 + return view
377 + ? { query: "", views: [{ view, parentQuery: "" }] }
378 + : createCommandPaletteSearchState(initialSearch.query);
379 + });
380 const { query, views: viewStack } = searchState;
381 const setQuery = (query: string) => dispatchSearch({ type: "query", query });
495 - const [linkedThreadSearch, setLinkedThreadSearch] = useState(initialSearch.linkedThreadSearch);
382 const deferredQuery = useDeferredValue(query);
383 const isActionsOnly = deferredQuery.startsWith(">");
384 const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
385 const resultListRef = useRef<LegendListRef | null>(null);
500 - const highlightClearedRef = useRef(false);
386 + // A pushed view drops the typed highlight until the user moves it again.
387 + const highlightClearedRef = useRef(viewStack.length > 0);
388 function clearTypedHighlight(): void {
389 highlightClearedRef.current = true;
390 setHighlightedItemValue(null);
@@ -818,6 +705,8 @@ function OpenCommandPaletteDialog(props: {
705 useEffect(
706 () => () => {
707 browseNavigation.invalidate();
708 + // A replaced or closed session must not report its in-flight lookup.
709 + cloneLookupGeneration.current += 1;
710 },
711 [browseNavigation],
712 );
@@ -1185,22 +1074,69 @@ function OpenCommandPaletteDialog(props: {
1074 },
1075 ];
1076
1077 + const openConnectionSettings = () => {
1078 + setOpen(false);
1079 + void navigate({ to: "/settings/connections" });
1080 + };
1081 + const addProjectEntry = resolveAddProjectEntry(
1082 + addProjectEnvironmentOptions,
1083 + defaultAddProjectEnvironmentId,
1084 + );
1085 +
1086 const openAddProjectFlow = () => {
1189 - if (addProjectEnvironmentOptions.length === 0) {
1190 - setOpen(false);
1191 - void navigate({ to: "/settings/connections" });
1192 - return;
1087 + switch (addProjectEntry.kind) {
1088 + case "connect-environment":
1089 + openConnectionSettings();
1090 + return;
1091 + case "choose-environment":
1092 + pushPaletteView({
1093 + addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
1094 + groups: addProjectEnvironmentGroups,
1095 + });
1096 + return;
1097 + case "choose-source":
1098 + startAddProjectSourceSelection(addProjectEntry.environmentId);
1099 + return;
1100 }
1101 + };
1102
1195 - if (addProjectEnvironmentOptions.length > 1 || defaultAddProjectEnvironmentId === null) {
1196 - pushPaletteView({
1197 - addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
1198 - groups: addProjectEnvironmentGroups,
1199 - });
1200 - return;
1103 + // The view an "Add project" intent opens to follows the environments as they
1104 + // connect, so it resolves here instead of being fixed when the palette opened.
1105 + const addProjectEntryGroups = (): ReadonlyArray<CommandPaletteGroup> => {
1106 + switch (addProjectEntry.kind) {
1107 + case "connect-environment":
1108 + return [
1109 + {
1110 + value: ADD_PROJECT_ENTRY_GROUP,
1111 + label: "",
1112 + items: [
1113 + {
1114 + kind: "action",
1115 + value: "action:add-project:connect-environment",
1116 + searchTerms: ["connect", "environment", "connection", "settings"],
1117 + title: "Connect an environment",
1118 + description: "No connected environment can add a project",
1119 + icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
1120 + keepOpen: true,
1121 + run: async () => {
1122 + openConnectionSettings();
1123 + },
1124 + },
1125 + ],
1126 + },
1127 + ];
1128 + case "choose-environment":
1129 + return addProjectEnvironmentGroups;
1130 + case "choose-source":
1131 + return buildAddProjectSourceGroups(
1132 + addProjectEntry.environmentId,
1133 + buildPaletteRemoteSourceReadiness(
1134 + browseEnvironmentId === addProjectEntry.environmentId
1135 + ? sourceControlDiscovery.data
1136 + : null,
1137 + ),
1138 + );
1139 }
1202 -
1203 - void startAddProjectSourceSelection(defaultAddProjectEnvironmentId);
1140 };
1141
1142 const openNewProjectFlow = () => {
@@ -1246,7 +1182,7 @@ function OpenCommandPaletteDialog(props: {
1182 title: "New thread in...",
1183 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
1184 addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
1249 - groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
1185 + groups: [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: projectThreadItems }],
1186 });
1187 }
1188
@@ -1511,45 +1447,6 @@ function OpenCommandPaletteDialog(props: {
1447 actionItems.push(changeThemeItem);
1448 actionItems.push(changeAppearanceItem);
1449
1514 - // Apply intents after commit but before paint because they clear parent state and may navigate.
1515 - const projectThreadItemCount = projectThreadItems.length;
1516 - const applyOpenIntent = useEffectEvent((intent: CommandPaletteOpenIntent) => {
1517 - clearOpenIntent();
1518 - browseNavigation.invalidate();
1519 - cloneLookupGeneration.current += 1;
1520 - setIsRemoteProjectLookingUp(false);
1521 - setAddProjectEnvironmentId(null);
1522 - setAddProjectCloneFlow(null);
1523 - setNewProjectFlow(null);
1524 - setLinkedThreadSearch(intent.kind === "search" ? intent : null);
1525 - dispatchSearch({ type: "reset", query: intent.kind === "search" ? intent.query : "" });
1526 - switch (intent.kind) {
1527 - case "search":
1528 - return;
1529 - case "add-project":
1530 - openAddProjectFlow();
1531 - return;
1532 - case "new-thread-in":
1533 - pushPaletteView({
1534 - addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
1535 - groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
1536 - });
1537 - return;
1538 - case "change-theme":
1539 - pushPaletteView({
1540 - addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />,
1541 - groups: [{ value: "themes", label: "Change theme", items: [] }],
1542 - });
1543 - return;
1544 - }
1545 - });
1546 - useLayoutEffect(() => {
1547 - if (openIntent === null) return;
1548 - if (openIntent.kind === "new-thread-in" && projectThreadItemCount === 0) return;
1549 - // oxlint-disable-next-line react/set-state-in-effect -- applying the intent dispatches to the parent reducer and can navigate, neither of which may run during render.
1550 - applyOpenIntent(openIntent);
1551 - }, [openIntent, projectThreadItemCount]);
1552 -
1450 actionItems.push(themeEditorItem);
1451
1452 if (
@@ -1676,11 +1573,15 @@ function OpenCommandPaletteDialog(props: {
1573 addProjectEnvironmentId,
1574 buildPaletteRemoteSourceReadiness(sourceControlDiscovery.data),
1575 )
1679 - : currentView?.groups[0]?.value === "themes"
1680 - ? changeThemeItem.groups
1681 - : currentView?.groups[0]?.value === "appearance"
1682 - ? changeAppearanceItem.groups
1683 - : (currentView?.groups ?? rootGroups);
1576 + : currentView?.groups[0]?.value === ADD_PROJECT_ENTRY_GROUP
1577 + ? addProjectEntryGroups()
1578 + : currentView?.groups[0]?.value === NEW_THREAD_IN_GROUP
1579 + ? [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: projectThreadItems }]
1580 + : currentView?.groups[0]?.value === "themes"
1581 + ? changeThemeItem.groups
1582 + : currentView?.groups[0]?.value === "appearance"
1583 + ? changeAppearanceItem.groups
1584 + : (currentView?.groups ?? rootGroups);
1585
1586 const isLinkedThreadSearch =
1587 linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query;
apps/web/src/components/GitActionsControl.tsx
+35 -57
@@ -1,5 +1,5 @@
1 import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
2 -import { useAtomValue } from "@effect/atom-react";
2 +import { useAtomMount, useAtomValue } from "@effect/atom-react";
3 import {
4 AuthOrchestrationOperateScope,
5 AuthSourceControlWriteScope,
@@ -22,6 +22,8 @@ import type {
22 import { useNavigate } from "@tanstack/react-router";
23 import * as Option from "effect/Option";
24 import { type MouseEvent, useEffect, useEffectEvent, useRef, useState } from "react";
25 +import { useDeadlinePassed } from "../hooks/useDeadline";
26 +import { useNowSecond } from "../hooks/useNowSecond";
27 import { flushSync } from "react-dom";
28 import {
29 CheckIcon,
@@ -105,7 +107,7 @@ import { serverEnvironment } from "~/state/server";
107 import { sourceControlEnvironment } from "~/state/sourceControl";
108 import { threadEnvironment } from "~/state/threads";
109 import { useAtomCommand } from "~/state/use-atom-command";
108 -import { vcsActionManager, vcsEnvironment } from "~/state/vcs";
110 +import { vcsActionManager, vcsEnvironment, vcsStatusRevalidation } from "~/state/vcs";
111 import { randomUUID } from "~/lib/utils";
112 import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
113 import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
@@ -158,9 +160,10 @@ interface InlineGitActionSuccess {
160 readonly title: string;
161 readonly description: string | null;
162 readonly scopeKey: string;
163 + readonly expiresAtMs: number;
164 }
165
163 -const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;
166 +const inlineSuccessExpiresAt = () => Date.now() + GIT_ACTION_SUCCESS_VISIBLE_MS;
167
168 type RefreshVcsStatus = (target: {
169 readonly environmentId: ScopedThreadRef["environmentId"];
@@ -330,19 +333,19 @@ function GitActionElapsedTime({
333 startedAtMs: number | null;
334 className?: string;
335 }) {
333 - const [nowMs, setNowMs] = useState(() => Date.now());
334 -
335 - useEffect(() => {
336 - if (startedAtMs === null) {
337 - return;
338 - }
339 -
340 - const intervalId = window.setInterval(() => {
341 - setNowMs(Date.now());
342 - }, 1_000);
343 - return () => window.clearInterval(intervalId);
344 - }, [startedAtMs]);
336 + return startedAtMs === null ? null : (
337 + <RunningGitActionElapsedTime startedAtMs={startedAtMs} className={className} />
338 + );
339 +}
340
341 +function RunningGitActionElapsedTime({
342 + startedAtMs,
343 + className,
344 +}: {
345 + startedAtMs: number;
346 + className: string | undefined;
347 +}) {
348 + const nowMs = useNowSecond();
349 const elapsed = formatGitActionElapsed(startedAtMs, nowMs);
350 if (!elapsed) {
351 return null;
@@ -1011,15 +1014,9 @@ export default function GitActionsControl({
1014 useState<PendingDefaultBranchAction | null>(null);
1015 const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd };
1016 const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope));
1014 - const visibleInlineSuccess = inlineSuccess?.scopeKey === successScopeKey ? inlineSuccess : null;
1015 -
1016 - useEffect(() => {
1017 - if (!inlineSuccess) return;
1018 - const timeoutId = window.setTimeout(() => {
1019 - setInlineSuccess(null);
1020 - }, GIT_ACTION_SUCCESS_VISIBLE_MS);
1021 - return () => window.clearTimeout(timeoutId);
1022 - }, [inlineSuccess]);
1017 + const inlineSuccessExpired = useDeadlinePassed(inlineSuccess?.expiresAtMs ?? null);
1018 + const visibleInlineSuccess =
1019 + inlineSuccess?.scopeKey === successScopeKey && !inlineSuccessExpired ? inlineSuccess : null;
1020
1021 const persistThreadBranchSync = (branch: string | null, manualSelection = false) => {
1022 if (!activeThreadRef) {
@@ -1179,38 +1176,13 @@ export default function GitActionsControl({
1176 })
1177 : null;
1178
1182 - useEffect(() => {
1183 - if (gitCwd === null) {
1184 - return;
1185 - }
1186 -
1187 - let refreshTimeout: number | null = null;
1188 - const scheduleRefreshCurrentGitStatus = () => {
1189 - if (refreshTimeout !== null) {
1190 - window.clearTimeout(refreshTimeout);
1191 - }
1192 - refreshTimeout = window.setTimeout(() => {
1193 - refreshTimeout = null;
1194 - requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
1195 - }, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
1196 - };
1197 - const handleVisibilityChange = () => {
1198 - if (document.visibilityState === "visible") {
1199 - scheduleRefreshCurrentGitStatus();
1200 - }
1201 - };
1202 -
1203 - window.addEventListener("focus", scheduleRefreshCurrentGitStatus);
1204 - document.addEventListener("visibilitychange", handleVisibilityChange);
1205 -
1206 - return () => {
1207 - if (refreshTimeout !== null) {
1208 - window.clearTimeout(refreshTimeout);
1209 - }
1210 - window.removeEventListener("focus", scheduleRefreshCurrentGitStatus);
1211 - document.removeEventListener("visibilitychange", handleVisibilityChange);
1212 - };
1213 - }, [activeEnvironmentId, gitCwd, refreshVcsStatus]);
1179 + useAtomMount(
1180 + vcsStatusRevalidation(
1181 + activeEnvironmentId !== null && gitCwd !== null
1182 + ? { environmentId: activeEnvironmentId, cwd: gitCwd }
1183 + : null,
1184 + ),
1185 + );
1186
1187 // Toast actions must retain their original checkout/thread, so do not use an effect event.
1188 async function runGitActionWithToast({
@@ -1306,6 +1278,7 @@ export default function GitActionsControl({
1278 : actionResult.toast.title,
1279 description: createdPullRequest ? null : (actionResult.toast.description ?? null),
1280 scopeKey: successScopeKey,
1281 + expiresAtMs: inlineSuccessExpiresAt(),
1282 });
1283 return;
1284 }
@@ -1439,7 +1412,12 @@ export default function GitActionsControl({
1412 ? `Updated ${pullResult.refName} from ${pullResult.upstreamRef ?? "upstream"}`
1413 : `${pullResult.refName} is already synchronized.`;
1414 if (isPanel) {
1442 - setInlineSuccess({ title, description, scopeKey: successScopeKey });
1415 + setInlineSuccess({
1416 + title,
1417 + description,
1418 + scopeKey: successScopeKey,
1419 + expiresAtMs: inlineSuccessExpiresAt(),
1420 + });
1421 return;
1422 }
1423 const successToastTiming = resolveGitActionResultToastTiming("success");
apps/web/src/components/UsageToggleShortcut.browser.test.tsx
+14 -5
@@ -32,8 +32,14 @@ vi.mock(import("@tanstack/react-router"), async (original) => ({
32 useNavigate: (() => state.navigate) as never,
33 }));
34
35 +import { useCommandPaletteMount } from "../commandPaletteStore";
36 +import { installCommandPaletteCommands } from "../shortcuts/commandPaletteCommands";
37 import { registerNavigationHistoryCommands } from "./AppSidebarLayout";
36 -import { CommandPalette } from "./CommandPalette";
38 +
39 +function MountedPalette() {
40 + useCommandPaletteMount();
41 + return null;
42 +}
43
44 // regression: #21357
45 describe("usage toggle shortcut on Usage", () => {
@@ -53,12 +59,15 @@ describe("usage toggle shortcut on Usage", () => {
59 it("does not reopen Usage from the command palette", async () => {
60 vi.clearAllMocks();
61 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
56 - await using _screen = await render(<CommandPalette>{null}</CommandPalette>, {
57 - router: "/usage",
58 - });
62 + await using screen = await render(<MountedPalette />, { router: "/usage" });
63 + using navigate = vi.spyOn(screen.router!, "navigate");
64 + using commands = new DisposableStack();
65 + commands.defer(
66 + installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }),
67 + );
68
69 await userEvent.keyboard("{Control>}u{/Control}");
70
62 - expect(state.navigate).not.toHaveBeenCalled();
71 + expect(navigate).not.toHaveBeenCalled();
72 });
73 });
apps/web/src/components/WorktreeBaseBranchPicker.tsx
-1
@@ -78,7 +78,6 @@ export function WorktreeBaseBranchPicker({
78 filteredItems={items}
79 value={value || null}
80 query={query}
81 - resultsQuery={deferredQuery}
81 onQueryChange={setQuery}
82 open={open && !disabled}
83 onOpenChange={handleOpenChange}
apps/web/src/hooks/useTheme.ts
+5
@@ -485,6 +485,11 @@ function subscribe(listener: () => void): () => void {
485 };
486 }
487
488 +/** For shortcuts and other handlers outside React that read the theme at event time. */
489 +export function getThemeSnapshot(): ThemeSnapshot {
490 + return getSnapshot();
491 +}
492 +
493 /** For code outside React (worker pools) that follows the rendered appearance. */
494 export function subscribeRenderedAppearance(listener: () => void): () => void {
495 const unsubscribeTheme = subscribe(listener);
apps/web/src/lib/documentActivity.browser.test.ts new
+33
@@ -0,0 +1,33 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { subscribeDocumentReturn } from "./documentActivity";
4 +
5 +describe("subscribeDocumentReturn", () => {
6 + // Focus can come back from the preview iframe, and a quick alt-tab can miss
7 + // the blur, so a return must not depend on the cached activity flipping.
8 + it("fires on every window focus and every return to a visible tab", () => {
9 + using _focused = vi.spyOn(document, "hasFocus").mockReturnValue(true);
10 + let visibility: DocumentVisibilityState = "visible";
11 + using _visibility = vi
12 + .spyOn(document, "visibilityState", "get")
13 + .mockImplementation(() => visibility);
14 + const wake = vi.fn();
15 + using subscription = new DisposableStack();
16 + subscription.defer(subscribeDocumentReturn(wake));
17 +
18 + window.dispatchEvent(new Event("focus"));
19 + window.dispatchEvent(new Event("focus"));
20 + expect(wake).toHaveBeenCalledTimes(2);
21 +
22 + visibility = "hidden";
23 + document.dispatchEvent(new Event("visibilitychange"));
24 + expect(wake).toHaveBeenCalledTimes(2);
25 + visibility = "visible";
26 + document.dispatchEvent(new Event("visibilitychange"));
27 + expect(wake).toHaveBeenCalledTimes(3);
28 +
29 + subscription.dispose();
30 + window.dispatchEvent(new Event("focus"));
31 + expect(wake).toHaveBeenCalledTimes(3);
32 + });
33 +});
apps/web/src/lib/documentActivity.ts
+19
@@ -48,3 +48,22 @@ export function subscribeDocumentActivity(listener: () => void): () => void {
48 window.removeEventListener("blur", handleActivityEvent);
49 };
50 }
51 +
52 +/**
53 + * Fires on every window focus and every switch to a visible tab. Unlike
54 + * `subscribeDocumentActivity` it does not wait for the cached activity to flip:
55 + * focus coming back from an iframe, or an alt-tab whose blur was missed, still
56 + * counts as a return.
57 + */
58 +export function subscribeDocumentReturn(listener: () => void): () => void {
59 + if (typeof document === "undefined") return () => {};
60 + const handleVisibilityChange = () => {
61 + if (document.visibilityState === "visible") listener();
62 + };
63 + window.addEventListener("focus", listener);
64 + document.addEventListener("visibilitychange", handleVisibilityChange);
65 + return () => {
66 + window.removeEventListener("focus", listener);
67 + document.removeEventListener("visibilitychange", handleVisibilityChange);
68 + };
69 +}
apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx new
+70
@@ -0,0 +1,70 @@
1 +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +import { userEvent } from "vite-plus/test/browser";
4 +
5 +import { render } from "../../test/render";
6 +import { openCommandPalette } from "../commandPaletteBus";
7 +import { useCommandPaletteMount, useCommandPaletteStore } from "../commandPaletteStore";
8 +import { installCommandPaletteCommands } from "./commandPaletteCommands";
9 +
10 +const keybindings = compileResolvedKeybindingsConfig([
11 + { key: "mod+k", command: "commandPalette.toggle" },
12 +]);
13 +
14 +function MountedPalette() {
15 + useCommandPaletteMount();
16 + return null;
17 +}
18 +
19 +function setup() {
20 + useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true);
21 +}
22 +
23 +describe("command palette shortcuts", () => {
24 + it("stay inert on routes without the palette", async () => {
25 + setup();
26 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
27 + await using screen = await render(null, { router: "/pair" });
28 + using commands = new DisposableStack();
29 + commands.defer(
30 + installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }),
31 + );
32 +
33 + await userEvent.keyboard("{Control>}k{/Control}");
34 +
35 + expect(useCommandPaletteStore.getState().open).toBe(false);
36 + });
37 +
38 + it("open the palette while it is mounted, and it closes when it unmounts", async () => {
39 + setup();
40 + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
41 + await using screen = await render(<MountedPalette />, { router: "/" });
42 + using commands = new DisposableStack();
43 + commands.defer(
44 + installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }),
45 + );
46 +
47 + await userEvent.keyboard("{Control>}k{/Control}");
48 + expect(useCommandPaletteStore.getState().open).toBe(true);
49 +
50 + await screen.rerender(<div />);
51 + expect(useCommandPaletteStore.getState().open).toBe(false);
52 + });
53 +});
54 +
55 +describe("openCommandPalette", () => {
56 + it("drops a request made while no palette is mounted", async () => {
57 + setup();
58 + await using screen = await render(null, { router: "/pair" });
59 +
60 + openCommandPalette({ open: "new-thread-in" });
61 + await screen.rerender(<MountedPalette />);
62 + expect(useCommandPaletteStore.getState()).toMatchObject({ open: false, openIntent: null });
63 +
64 + openCommandPalette({ open: "new-thread-in" });
65 + expect(useCommandPaletteStore.getState()).toMatchObject({
66 + open: true,
67 + openIntent: { kind: "new-thread-in" },
68 + });
69 + });
70 +});
apps/web/src/shortcuts/commandPaletteCommands.ts new
+125
@@ -0,0 +1,125 @@
1 +import type { AnyRouter } from "@tanstack/react-router";
2 +
3 +import {
4 + dispatchCommandPalette,
5 + isCommandPaletteMounted,
6 + useCommandPaletteStore,
7 +} from "../commandPaletteStore";
8 +import { overlayModeForCommand } from "../components/CommandPalette.logic";
9 +import { APPEARANCE_OPTIONS, notifyThemeSaveFailure } from "../components/CommandPaletteThemeItems";
10 +import { toggleThemeEditorForTheme } from "../components/settings/themeEditorStore";
11 +import { toastManager } from "../components/ui/toast";
12 +import { getThemeSnapshot, setAppearanceMode } from "../hooks/useTheme";
13 +import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
14 +import { type CommandHandler, type CommandScopeOptions, registerCommands } from "./dispatcher";
15 +import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
16 +import { resolveThreadRouteTarget } from "../threadRoutes";
17 +
18 +function consume(event: KeyboardEvent): void {
19 + event.preventDefault();
20 + event.stopPropagation();
21 +}
22 +
23 +const toggleOverlay =
24 + (command: Parameters<typeof overlayModeForCommand>[0]): CommandHandler =>
25 + (event) => {
26 + const mode = overlayModeForCommand(command);
27 + if (mode === null) return false;
28 + consume(event);
29 + dispatchCommandPalette({ _tag: "ToggleMode", mode });
30 + };
31 +
32 +/**
33 + * Palette, theme and usage shortcuts. They read the route, panels and theme
34 + * when the key is pressed, and are live only while the palette is mounted.
35 + */
36 +export function installCommandPaletteCommands(
37 + router: AnyRouter,
38 + options: Pick<CommandScopeOptions, "keybindings"> = {},
39 +): () => void {
40 + const readRouteThreadRef = () => {
41 + const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
42 + return target?.kind === "server" ? target.threadRef : null;
43 + };
44 +
45 + // A child search (files, contents) goes back to the palette on Escape before
46 + // its own widgets or the dialog can treat the key as a close.
47 + const disposeEscape = registerCommands(
48 + {},
49 + {
50 + capture: true,
51 + when: isCommandPaletteMounted,
52 + onKeyDown: (event) => {
53 + if (event.isComposing || event.key !== "Escape") return false;
54 + const { open, mode } = useCommandPaletteStore.getState();
55 + if (!open || mode === "command") return false;
56 + consume(event);
57 + dispatchCommandPalette({ _tag: "BackToCommand" });
58 + },
59 + },
60 + );
61 +
62 + const disposeCommands = registerCommands(
63 + {
64 + "appearance.cycle": (event) => {
65 + consume(event);
66 + if (event.repeat) return;
67 + const { appearanceMode } = getThemeSnapshot();
68 + const nextMode =
69 + appearanceMode === "system" ? "light" : appearanceMode === "light" ? "dark" : "system";
70 + if (!setAppearanceMode(nextMode)) {
71 + notifyThemeSaveFailure();
72 + return;
73 + }
74 + toastManager.add({
75 + id: "appearance-cycle",
76 + title: `Appearance: ${APPEARANCE_OPTIONS.find((option) => option.mode === nextMode)?.label}`,
77 + timeout: 1500,
78 + });
79 + },
80 + "theme.select": (event) => {
81 + consume(event);
82 + if (event.repeat) return;
83 + dispatchCommandPalette({ _tag: "OpenChangeTheme" });
84 + },
85 + "themeEditor.toggle": (event) => {
86 + consume(event);
87 + const { theme, themeHalves, resolvedTheme } = getThemeSnapshot();
88 + toggleThemeEditorForTheme({ theme, themeHalves, initialAppearance: resolvedTheme });
89 + },
90 + "usage.open": (event) => {
91 + consume(event);
92 + dispatchCommandPalette({ _tag: "SetOpen", open: false });
93 + void router.navigate({ to: "/usage" });
94 + },
95 + "commandPalette.toggle": toggleOverlay("commandPalette.toggle"),
96 + "filePicker.toggle": toggleOverlay("filePicker.toggle"),
97 + "projectSearch.toggle": toggleOverlay("projectSearch.toggle"),
98 + },
99 + {
100 + ...options,
101 + when: isCommandPaletteMounted,
102 + context: () => {
103 + const threadRef = readRouteThreadRef();
104 + return {
105 + terminalOpen: threadRef
106 + ? selectThreadTerminalUiState(
107 + useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
108 + threadRef,
109 + ).terminalOpen
110 + : false,
111 + previewOpen: threadRef
112 + ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) ===
113 + "preview"
114 + : false,
115 + usagePageOpen: router.state.location.pathname === "/usage",
116 + };
117 + },
118 + },
119 + );
120 +
121 + return () => {
122 + disposeEscape();
123 + disposeCommands();
124 + };
125 +}
apps/web/src/state/entities.ts
+7
@@ -232,6 +232,13 @@ export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
232 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
233 }
234
235 +export function subscribeProject(
236 + ref: ScopedProjectRef,
237 + listener: (project: EnvironmentProject | null) => void,
238 +): () => void {
239 + return appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), listener);
240 +}
241 +
242 export function readProjects(): ReadonlyArray<EnvironmentProject> {
243 return appAtomRegistry.get(environmentProjects.projectsAtom);
244 }
apps/web/src/state/vcs.ts
+12
@@ -1,9 +1,21 @@
1 import {
2 createVcsActionManager,
3 createVcsEnvironmentAtoms,
4 + createVcsStatusRevalidationAtomFamily,
5 } from "@t3tools/client-runtime/state/vcs";
6
7 import { connectionAtomRuntime } from "../connection/runtime";
8 +import { subscribeDocumentReturn } from "../lib/documentActivity";
9
10 export const vcsEnvironment = createVcsEnvironmentAtoms(connectionAtomRuntime);
11 export const vcsActionManager = createVcsActionManager(connectionAtomRuntime);
12 +
13 +/**
14 + * Refreshes a checkout's status when the user comes back to the window, where
15 + * edits made in another app or terminal may be waiting.
16 + */
17 +export const vcsStatusRevalidation = createVcsStatusRevalidationAtomFamily({
18 + refreshStatus: vcsEnvironment.refreshStatus,
19 + subscribeWake: subscribeDocumentReturn,
20 + wakeDebounceMs: 250,
21 +});
packages/client-runtime/src/state/vcsStatusRevalidation.test.ts
+44 -5
@@ -6,15 +6,28 @@ import { createVcsStatusRevalidationAtomFamily } from "./vcsStatusRevalidation.t
6
7 const environmentId = EnvironmentId.make("environment-1");
8
9 -function setup(options: { readonly connected: boolean }) {
10 - const connectedAtom = Atom.make(options.connected);
9 +function setup(options: { readonly connected?: boolean; readonly wake?: boolean }) {
10 + const connectedAtom = Atom.make(options.connected ?? false);
11 + const wakes = new Set<() => void>();
12 const run = vi.fn(async () => AsyncResult.success(null));
13 const family = createVcsStatusRevalidationAtomFamily({
14 refreshStatus: { label: "refresh-status", run },
14 - connected: () => connectedAtom,
15 + ...(options.connected === undefined ? {} : { connected: () => connectedAtom }),
16 + ...(options.wake
17 + ? {
18 + subscribeWake: (wake: () => void) => {
19 + wakes.add(wake);
20 + return () => wakes.delete(wake);
21 + },
22 + wakeDebounceMs: 250,
23 + }
24 + : {}),
25 });
26 const registry = AtomRegistry.make();
17 - return { registry, family, connectedAtom, run };
27 + const wake = () => {
28 + for (const listener of wakes) listener();
29 + };
30 + return { registry, family, connectedAtom, run, wakes, wake };
31 }
32
33 describe("createVcsStatusRevalidationAtomFamily", () => {
@@ -46,9 +59,35 @@ describe("createVcsStatusRevalidationAtomFamily", () => {
59 unmount();
60 });
61
62 + it("debounces wake signals and stops listening with the last subscriber", () => {
63 + vi.useFakeTimers();
64 + try {
65 + const { registry, family, run, wakes, wake } = setup({ wake: true });
66 + const unmount = registry.mount(family({ environmentId, cwd: "/repo" }));
67 + expect(run).not.toHaveBeenCalled();
68 +
69 + wake();
70 + vi.advanceTimersByTime(100);
71 + wake();
72 + vi.advanceTimersByTime(249);
73 + expect(run).not.toHaveBeenCalled();
74 + vi.advanceTimersByTime(1);
75 + expect(run).toHaveBeenCalledTimes(1);
76 +
77 + wake();
78 + unmount();
79 + vi.runAllTimers();
80 + expect(run).toHaveBeenCalledTimes(1);
81 + expect(wakes.size).toBe(0);
82 + } finally {
83 + vi.useRealTimers();
84 + }
85 + });
86 +
87 it("does nothing for an idle target", () => {
50 - const { registry, family, run } = setup({ connected: true });
88 + const { registry, family, run, wakes } = setup({ connected: true, wake: true });
89 registry.mount(family(null))();
90 expect(run).not.toHaveBeenCalled();
91 + expect(wakes.size).toBe(0);
92 });
93 });
packages/client-runtime/src/state/vcsStatusRevalidation.ts
+29 -6
@@ -1,17 +1,18 @@
1 +// @effect-diagnostics globalTimers:off - The wake debounce runs in an atom subscription, outside an Effect runtime.
2 import type { EnvironmentId } from "@t3tools/contracts";
3 import { Atom, type AtomRegistry } from "effect/reactivity";
4
5 import { type AtomCommand, type AtomCommandResult, runAtomCommand } from "./runtime.ts";
6
6 -interface VcsStatusRevalidationTarget {
7 +export interface VcsStatusRevalidationTarget {
8 readonly environmentId: EnvironmentId;
9 readonly cwd: string;
10 }
11
12 /**
12 - * One atom per environment and cwd, shared by every subscriber, that refreshes
13 - * VCS status while mounted: on mount and on each reconnect, once `connected`
14 - * is true.
13 + * One atom per checkout, so controls showing it share one cadence. Refreshes on
14 + * `subscribeWake` (debounced) and whenever `connected`, if given, is true on
15 + * mount or turns true. Listening ends with the last subscriber.
16 */
17 export function createVcsStatusRevalidationAtomFamily<R>(input: {
18 readonly refreshStatus: AtomCommand<
@@ -19,7 +20,9 @@ export function createVcsStatusRevalidationAtomFamily<R>(input: {
20 R,
21 unknown
22 >;
22 - readonly connected: (environmentId: EnvironmentId) => Atom.Atom<boolean>;
23 + readonly connected?: (environmentId: EnvironmentId) => Atom.Atom<boolean>;
24 + readonly subscribeWake?: (wake: () => void) => () => void;
25 + readonly wakeDebounceMs?: number;
26 readonly onRefreshed?: (result: AtomCommandResult<R, unknown>) => void;
27 }) {
28 const family = Atom.family((target: VcsStatusRevalidationTarget) => {
@@ -36,9 +39,29 @@ export function createVcsStatusRevalidationAtomFamily<R>(input: {
39 input.onRefreshed?.(result);
40 };
41
42 + const wakeAtom = Atom.make((get) => {
43 + const subscribeWake = input.subscribeWake;
44 + if (subscribeWake === undefined) return;
45 + const registry = get.registry;
46 + let timer: ReturnType<typeof setTimeout> | undefined;
47 + const unsubscribe = subscribeWake(() => {
48 + if (timer !== undefined) clearTimeout(timer);
49 + timer = setTimeout(() => {
50 + timer = undefined;
51 + void refresh(registry);
52 + }, input.wakeDebounceMs ?? 0);
53 + });
54 + get.addFinalizer(() => {
55 + if (timer !== undefined) clearTimeout(timer);
56 + unsubscribe();
57 + });
58 + }).pipe(Atom.withLabel(`vcs-status-revalidation:wake:${key}`));
59 +
60 return Atom.make((get) => {
61 + get(wakeAtom);
62 + const connected = input.connected;
63 // Rebuilds only when the connection flag flips, so each reconnect refreshes once.
41 - if (get(input.connected(environmentId))) {
64 + if (connected !== undefined && get(connected(environmentId))) {
65 void refresh(get.registry);
66 }
67 }).pipe(Atom.withLabel(`vcs-status-revalidation:${key}`));