TypeScript
refactor(web): command palette state lives in a store, git and branch pickers drop timer and sync effects (#25733)
Julius Marminge5d91ab1117ad
diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsxindex 0be6d822c86..e33b11c55f4 100644--- a/apps/web/src/appInit.tsx+++ b/apps/web/src/appInit.tsx@@ -43,6 +43,7 @@ import { getRouter, type AppRouter } from "./router";import { appAtomRegistry } from "./rpc/atomRegistry";import { primaryServerConfigAtom } from "./state/server";import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";+import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";import { environmentThreadShells } from "./state/threads";import { resolveThreadRouteTarget } from "./threadRoutes";@@ -172,6 +173,7 @@ export function startAppServices(): AppRouter {startPreviewTitleRecording();startBrowserProfileReporting();installChatRouteCommands(router);+ installCommandPaletteCommands(router);registerOpenFavoriteEditorCommand();startThreadOverlayRetention(router);// Drafts promote as their server threads arrive, wherever the user is.diff --git a/apps/web/src/commandPaletteBus.ts b/apps/web/src/commandPaletteBus.tsindex fe30e76a94c..2766f6db6b3 100644--- a/apps/web/src/commandPaletteBus.ts+++ b/apps/web/src/commandPaletteBus.ts@@ -1,34 +1,38 @@import type { EnvironmentId, PullRequestLinkedThreadsResult } from "@t3tools/contracts";+import { dispatchCommandPalette, isCommandPaletteMounted } from "./commandPaletteStore";+export interface CommandPaletteLinkedThreads {readonly environmentId: EnvironmentId;readonly threads: PullRequestLinkedThreadsResult["threads"];}-const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";-export interface CommandPaletteOpenDetail {readonly open?: "add-project" | "new-thread-in";readonly query?: string;readonly linkedThreads?: CommandPaletteLinkedThreads;}-export function openCommandPalette(detail?: CommandPaletteOpenDetail): void {- window.dispatchEvent(- new CustomEvent(COMMAND_PALETTE_OPEN_EVENT, detail ? { detail } : undefined),- );-}--export function onOpenCommandPalette(- listener: (detail: CommandPaletteOpenDetail) => void,-): () => void {- const handler = (event: Event) => {- listener((event as CustomEvent<CommandPaletteOpenDetail>).detail ?? {});- };- window.addEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);- return () => window.removeEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);+export function openCommandPalette(detail: CommandPaletteOpenDetail = {}): void {+ // With no palette on screen (e.g. /pair) the request is dropped; kept in the+ // store, it would pop a stale palette once the app shell mounts.+ if (!isCommandPaletteMounted()) return;+ if (detail.open === "new-thread-in") {+ dispatchCommandPalette({ _tag: "OpenNewThreadIn" });+ } else if (detail.open === "add-project") {+ dispatchCommandPalette({ _tag: "OpenAddProject" });+ } else if (detail.query !== undefined) {+ dispatchCommandPalette({+ _tag: "OpenSearch",+ query: detail.query,+ ...(detail.linkedThreads ? { linkedThreads: detail.linkedThreads } : {}),+ });+ } else {+ dispatchCommandPalette({ _tag: "SetOpen", open: true });+ }}+/** True while the palette popup is on screen, including its closing animation. */export function isCommandPaletteOpen(): boolean {return (typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== nulldiff --git a/apps/web/src/commandPaletteStore.ts b/apps/web/src/commandPaletteStore.tsnew file mode 100644index 00000000000..f8dee5413fb--- /dev/null+++ b/apps/web/src/commandPaletteStore.ts@@ -0,0 +1,49 @@+import { useEffect } from "react";+import { create } from "zustand";++import {+ type CommandPaletteUiAction,+ type CommandPaletteUiState,+ reduceCommandPaletteUiState,+} from "./components/CommandPalette.logic";++const INITIAL_STATE: CommandPaletteUiState = {+ open: false,+ mode: "command",+ openIntent: null,+ session: 0,+};++export const useCommandPaletteStore = create<CommandPaletteUiState>(() => INITIAL_STATE);++export function dispatchCommandPalette(action: CommandPaletteUiAction): void {+ useCommandPaletteStore.setState((state) => reduceCommandPaletteUiState(state, action), true);+}++// The palette is only mounted on app-shell routes (not /pair, sign-in or+// landings), so its shortcuts must stay inert elsewhere.+let mountedPalettes = 0;++export function isCommandPaletteMounted(): boolean {+ return mountedPalettes > 0;+}++/**+ * Marks the palette as mounted while the calling component is. An unmounted+ * palette cannot stay open, so the last unmount resets the store.+ */+export function useCommandPaletteMount(): void {+ // 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.+ useEffect(() => {+ mountedPalettes += 1;+ return () => {+ mountedPalettes -= 1;+ if (mountedPalettes === 0) {+ useCommandPaletteStore.setState(+ (state) => ({ ...INITIAL_STATE, session: state.session + 1 }),+ true,+ );+ }+ };+ }, []);+}diff --git a/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx b/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsxnew file mode 100644index 00000000000..1ca6c0422c5--- /dev/null+++ b/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx@@ -0,0 +1,95 @@+import { EnvironmentId, ProjectId } from "@t3tools/contracts";+import { scopeProjectRef } from "@t3tools/client-runtime/environment";+import { describe, expect, it, vi } from "vite-plus/test";++import { act, render } from "../../test/render";++const project = vi.hoisted(() => {+ let value: unknown = null;+ const listeners = new Set<() => void>();+ return {+ // Each test starts from no project and no listeners left by an earlier test.+ setup: (initial: unknown) => {+ value = initial;+ listeners.clear();+ },+ get: () => value,+ set: (next: unknown) => {+ value = next;+ for (const listener of listeners) listener();+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+});++vi.mock(import("../state/entities"), async (original) => {+ const { useSyncExternalStore } = await import("react");+ return {+ ...(await original()),+ readProject: (() => project.get()) as never,+ subscribeProject: ((_ref: unknown, listener: (value: unknown) => void) =>+ project.subscribe(() => listener(project.get()))) as never,+ useProject: (() => useSyncExternalStore(project.subscribe, project.get)) as never,+ };+});+vi.mock(import("../state/environments"), async (original) => ({+ ...(await original()),+ useEnvironments: (() => ({ environments: [] })) as never,+}));+vi.mock(import("../hooks/useHandleNewThread"), async (original) => ({+ ...(await original()),+ useNewThreadHandler: (() => () => undefined) as never,+}));+vi.mock(import("../hooks/useAddProjectTargets"), async (original) => ({+ ...(await original()),+ useAddProjectTargets: (() => []) as never,+}));+vi.mock(import("../hooks/useLogicalProjectEnvironments"), async (original) => ({+ ...(await original()),+ useLogicalProjectEnvironments: (() => []) as never,+}));++import {+ AddProjectToMachineDialogHost,+ openAddProjectToMachine,+} from "./AddProjectToMachineDialog";++const environmentId = EnvironmentId.make("environment-1");+const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-1"));+const PROJECT = {+ environmentId,+ id: projectRef.projectId,+ title: "Repo",+ workspaceRoot: "/repo",+ repositoryIdentity: null,+};++describe("AddProjectToMachineDialog", () => {+ it("closes when its project goes away", async () => {+ project.setup(PROJECT);+ await using screen = await render(<AddProjectToMachineDialogHost />);++ await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: null }));+ await expect.element(screen.getByText("Add to another machine")).toBeInTheDocument();++ await act(() => project.set(null));+ await act(() => project.set(PROJECT));+ await expect.element(screen.getByText("Add to another machine")).not.toBeInTheDocument();+ });++ it("does not reopen for a project that vanished before the dialog showed", async () => {+ project.setup(PROJECT);+ await using screen = await render(<AddProjectToMachineDialogHost />);++ await act(() => {+ openAddProjectToMachine({ projectRef, targetEnvironmentId: null });+ project.set(null);+ });+ await act(() => project.set(PROJECT));++ await expect.element(screen.getByText("Add to another machine")).not.toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsxindex fc6dce938ec..2ce491703d1 100644--- a/apps/web/src/components/AddProjectToMachineDialog.tsx+++ b/apps/web/src/components/AddProjectToMachineDialog.tsx@@ -17,7 +17,7 @@ import {cloneUrlProtocol,} from "@t3tools/shared/cloneUrl";import { ArrowRightIcon } from "lucide-react";-import { useEffect, useId, useState } from "react";+import { useId, useState } from "react";import { create } from "zustand";import { type DraftId, useComposerDraftStore } from "../composerDraftStore";@@ -31,7 +31,7 @@ import {} from "../lib/addProjectToMachine";import { formatBytes } from "../lib/formatBytes";import { newProjectId } from "../lib/utils";-import { useProject } from "../state/entities";+import { readProject, subscribeProject, useProject } from "../state/entities";import { useEnvironments } from "../state/environments";import { projectEnvironment } from "../state/projects";import { useEnvironmentQuery } from "../state/query";@@ -58,20 +58,35 @@ interface AddProjectToMachineRequest {readonly targetEnvironmentId: EnvironmentId | null;}-const useRequest = create<{ request: AddProjectToMachineRequest | null }>(() => ({+const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({request: null,+ session: 0,}));+let endRequestWithProject: (() => void) | null = null;+/** Opens the dialog that clones a project onto another connected machine. */export function openAddProjectToMachine(request: AddProjectToMachineRequest) {- useRequest.setState({ request });+ if (readProject(request.projectRef) === null) return;+ endRequestWithProject?.();+ // The request ends when its project goes away, so a project that comes back+ // later cannot reopen a dialog nobody asked for.+ endRequestWithProject = subscribeProject(request.projectRef, (project) => {+ if (project === null) close();+ });+ useRequest.setState((state) => ({ request, session: state.session + 1 }));}-const close = () => useRequest.setState({ request: null });+function close() {+ endRequestWithProject?.();+ endRequestWithProject = null;+ useRequest.setState({ request: null });+}export function AddProjectToMachineDialogHost() {const request = useRequest((state) => state.request);- return request ? <AddProjectToMachineDialog request={request} /> : null;+ const session = useRequest((state) => state.session);+ return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;}function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {@@ -128,10 +143,6 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineReproject === null ||target === null ||(canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);- useEffect(() => {- if (project === null) close();- }, [project]);-const toggleFile = (path: string, checked: boolean) => {const next = new Set(selectedFiles);if (checked) next.add(path);diff --git a/apps/web/src/components/BranchPicker.tsx b/apps/web/src/components/BranchPicker.tsxindex 199c5352009..cfa082368a9 100644--- a/apps/web/src/components/BranchPicker.tsx+++ b/apps/web/src/components/BranchPicker.tsx@@ -1,16 +1,9 @@import type { VcsRef } from "@t3tools/contracts";import { LegendList, type LegendListRef } from "@legendapp/list/react";-import {- useEffect,- useId,- useLayoutEffect,- useRef,- useState,- type ComponentProps,- type ReactNode,-} from "react";+import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";import { MiddleTruncate } from "./ui/middle-truncate";+import { observeResize } from "../lib/observeResize";import { cn } from "../lib/utils";import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";import { RefreshIcon } from "./ui/refresh-icon";@@ -32,7 +25,6 @@ export function BranchPicker({filteredItems,value,query,- resultsQuery,onQueryChange,open,onOpenChange,@@ -51,7 +43,6 @@ export function BranchPicker({filteredItems: string[];value: string | null;query: string;- resultsQuery: string;onQueryChange: (value: string) => void;open: boolean;onOpenChange: (open: boolean) => void;@@ -121,32 +112,22 @@ export function BranchPicker({setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);};- useLayoutEffect(() => {- if (!open) {- return;- }-- let nestedFrame = 0;- const frame = requestAnimationFrame(() => {- updateBranchListScrollFades();- nestedFrame = requestAnimationFrame(updateBranchListScrollFades);- });+ // The popup mounts the list when it opens. Its content settles over a few+ // frames as rows measure, so the fades follow the scroller and its content.+ const attachBranchList = (list: LegendListRef | null) => {+ branchListRef.current = list;+ const scrollElement = list?.getScrollableNode?.();+ if (!(scrollElement instanceof HTMLElement)) return;+ const content = scrollElement.firstElementChild;+ const stopObserving = observeResize(+ content ? [scrollElement, content] : scrollElement,+ updateBranchListScrollFades,+ );return () => {- cancelAnimationFrame(frame);- cancelAnimationFrame(nestedFrame);+ stopObserving();+ branchListRef.current = null;};- }, [open, updateBranchListScrollFades]);-- const previousResultsQuery = useRef<string | null>(null);- useEffect(() => {- if (!open) {- previousResultsQuery.current = null;- return;- }- if (previousResultsQuery.current === resultsQuery) return;- previousResultsQuery.current = resultsQuery;- void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });- }, [resultsQuery, open]);+ };return (<Combobox@@ -173,7 +154,10 @@ export function BranchPicker({<ComboboxSearchInputplaceholder="Search refs..."value={query}- onChange={(event) => onQueryChange(event.target.value)}+ onChange={(event) => {+ onQueryChange(event.target.value);+ void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });+ }}onKeyDown={(event) => {if (event.key !== "Enter" || event.nativeEvent.isComposing || event.keyCode === 229)return;@@ -193,7 +177,7 @@ export function BranchPicker({<div className="relative flex min-h-0 w-full max-h-56 flex-1 flex-col overflow-hidden"><ComboboxListVirtualized className="flex size-full min-h-0 min-w-0 flex-col"><LegendList<string>- ref={branchListRef}+ ref={attachBranchList}data={filteredItems}keyExtractor={(item) => item}{...(getItemType ? { getItemType } : {})}diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsxindex 60eef31b1b6..8a55b276a64 100644--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx@@ -652,7 +652,6 @@ export function BranchToolbarBranchSelector({onSelectItem={selectPickerItem}value={resolvedActiveBranch}query={branchQuery}- resultsQuery={deferredTrimmedBranchQuery}onQueryChange={setBranchQuery}hasNextPage={hasNextPage}isFetchingNextPage={isFetchingNextPage}diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsxnew file mode 100644index 00000000000..3883a3e2258--- /dev/null+++ b/apps/web/src/components/CommandPalette.browser.test.tsx@@ -0,0 +1,33 @@+import { describe, expect, it } from "vite-plus/test";+import { page } from "vite-plus/test/browser";++import { render } from "../../test/render";+import { openCommandPalette } from "../commandPaletteBus";+import { useCommandPaletteStore } from "../commandPaletteStore";+import { CommandPalette } from "./CommandPalette";++function setup() {+ useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true);+}++describe("CommandPalette open intents", () => {+ it("opens New thread in... with focus in the search input, not the Back button", async () => {+ setup();+ await using _screen = await render(<CommandPalette>{null}</CommandPalette>);++ openCommandPalette({ open: "new-thread-in" });++ await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();+ });++ it("opens a search intent with its query in the focused input", async () => {+ setup();+ await using _screen = await render(<CommandPalette>{null}</CommandPalette>);++ openCommandPalette({ query: "acme" });++ const input = page.getByPlaceholder("Search commands, projects, and threads...");+ await expect.element(input).toHaveFocus();+ await expect.element(input).toHaveValue("acme");+ });+});diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.tsindex f37f5405c59..7ec1a3e9ac1 100644--- a/apps/web/src/components/CommandPalette.logic.test.ts+++ b/apps/web/src/components/CommandPalette.logic.test.ts@@ -9,6 +9,7 @@ import {filterPinnedBrowseEntries,filterCommandPaletteGroups,reduceCommandPaletteUiState,+ resolveAddProjectEntry,createCommandPaletteSearchState,reduceCommandPaletteSearchState,type CommandPaletteUiState,@@ -32,7 +33,7 @@ describe("linked pull request thread navigation", () => {],};const state = reduceCommandPaletteUiState(- { open: false, mode: "command", openIntent: null },+ { open: false, mode: "command", openIntent: null, session: 0 },{_tag: "OpenSearch",query,@@ -59,7 +60,7 @@ describe("linked pull request thread navigation", () => {describe("reduceCommandPaletteUiState", () => {it("opens PR search from another overlay and replaces an earlier search", () => {const first = reduceCommandPaletteUiState(- { open: true, mode: "files", openIntent: null },+ { open: true, mode: "files", openIntent: null, session: 0 },{_tag: "OpenSearch",query: "https://github.com/acme/web/pull/7",@@ -69,6 +70,7 @@ describe("reduceCommandPaletteUiState", () => {open: true,mode: "command",openIntent: { kind: "search", query: "https://github.com/acme/web/pull/7" },+ session: 1,});const second = reduceCommandPaletteUiState(first, {_tag: "OpenSearch",@@ -78,10 +80,56 @@ describe("reduceCommandPaletteUiState", () => {kind: "search",query: "https://github.com/acme/web/pull/8",});+ // The second intent starts a new session, so the open palette starts over from it.+ expect(second.session).toBe(2);expect(reduceCommandPaletteUiState(second, { _tag: "SetOpen", open: false }).openIntent,).toBeNull();});++ it("keeps the session across mode switches so only intents start the palette over", () => {+ let state: CommandPaletteUiState = {+ open: false,+ mode: "command",+ openIntent: null,+ session: 0,+ };+ state = reduceCommandPaletteUiState(state, { _tag: "OpenNewThreadIn" });+ expect(state).toMatchObject({ open: true, openIntent: { kind: "new-thread-in" }, session: 1 });+ state = reduceCommandPaletteUiState(state, { _tag: "ToggleMode", mode: "files" });+ expect(state).toMatchObject({ mode: "files", openIntent: null, session: 1 });+ state = reduceCommandPaletteUiState(state, { _tag: "OpenAddProject" });+ expect(state).toMatchObject({+ mode: "command",+ openIntent: { kind: "add-project" },+ session: 2,+ });+ });+});++describe("resolveAddProjectEntry", () => {+ const local = EnvironmentId.make("local");+ const remote = EnvironmentId.make("remote");++ it("sends the user to connect an environment when none can add a project", () => {+ expect(resolveAddProjectEntry([], null)).toEqual({ kind: "connect-environment" });+ });++ it("asks for an environment when there is a choice or no connected default", () => {+ expect(+ resolveAddProjectEntry([{ environmentId: local }, { environmentId: remote }], local),+ ).toEqual({ kind: "choose-environment" });+ expect(resolveAddProjectEntry([{ environmentId: local }], null)).toEqual({+ kind: "choose-environment",+ });+ });++ it("goes straight to sources for the only environment", () => {+ expect(resolveAddProjectEntry([{ environmentId: local }], local)).toEqual({+ kind: "choose-source",+ environmentId: local,+ });+ });});const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");@@ -825,7 +873,12 @@ describe("command palette search return", () => {});describe("returning from file and content search", () => {- const root: CommandPaletteUiState = { open: true, mode: "command", openIntent: null };+ const root: CommandPaletteUiState = {+ open: true,+ mode: "command",+ openIntent: null,+ session: 0,+ };const query = "https://github.com/acme/web/pull/7";const context = {query,@@ -860,7 +913,7 @@ describe("returning from file and content search", () => {it("closing a child search discards its return context before reopening", () => {const child: CommandPaletteUiState = { ...root, mode: "files", parentSearch: context };const closed = reduceCommandPaletteUiState(child, { _tag: "SetOpen", open: false });- expect(closed).toEqual({ open: false, mode: "files", openIntent: null });+ expect(closed).toEqual({ open: false, mode: "files", openIntent: null, session: 0 });expect(reduceCommandPaletteUiState(closed, { _tag: "BackToCommand" })).toEqual(closed);expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual(root);});diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.tsindex 55ed4af28aa..61020288893 100644--- a/apps/web/src/components/CommandPalette.logic.ts+++ b/apps/web/src/components/CommandPalette.logic.ts@@ -81,7 +81,10 @@ export type CommandPaletteOpenIntent =export interface CommandPaletteUiState {readonly open: boolean;readonly mode: SearchOverlayMode;+ /** What the current palette session opened to; read once when the palette view mounts. */readonly openIntent: CommandPaletteOpenIntent | null;+ /** Bumped by every intent so an open palette starts over from the new one. */+ readonly session: number;readonly parentSearch?: CommandPaletteReturnContext;readonly restoredSearch?: CommandPaletteReturnContext;}@@ -97,7 +100,6 @@ export type CommandPaletteUiAction =| { readonly _tag: "OpenAddProject" }| { readonly _tag: "OpenNewThreadIn" }| { readonly _tag: "OpenChangeTheme" }- | { readonly _tag: "ClearOpenIntent" }| {readonly _tag: "OpenChildSearch";readonly mode: "files" | "content";@@ -109,47 +111,70 @@ export function reduceCommandPaletteUiState(state: CommandPaletteUiState,action: CommandPaletteUiAction,): CommandPaletteUiState {+ const { session } = state;+ const openWithIntent = (openIntent: CommandPaletteOpenIntent): CommandPaletteUiState => ({+ open: true,+ mode: "command",+ openIntent,+ session: session + 1,+ });switch (action._tag) {case "SetOpen":return action.open- ? { open: true, mode: "command", openIntent: state.openIntent }- : { open: false, mode: state.mode, openIntent: null };+ ? { open: true, mode: "command", openIntent: state.openIntent, session }+ : { open: false, mode: state.mode, openIntent: null, session };case "ToggleMode":return state.open && state.mode === action.mode- ? { open: false, mode: state.mode, openIntent: null }- : { open: true, mode: action.mode, openIntent: null };+ ? { open: false, mode: state.mode, openIntent: null, session }+ : { open: true, mode: action.mode, openIntent: null, session };case "OpenChildSearch":- return { open: true, mode: action.mode, openIntent: null, parentSearch: action.context };+ return {+ open: true,+ mode: action.mode,+ openIntent: null,+ session,+ parentSearch: action.context,+ };case "BackToCommand":return state.open && state.mode !== "command"? {open: true,mode: "command",openIntent: null,+ session,...(state.parentSearch ? { restoredSearch: state.parentSearch } : {}),}: state;case "OpenSearch":- return {- open: true,- mode: "command",- openIntent: {- kind: "search",- query: action.query,- ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),- },- };+ return openWithIntent({+ kind: "search",+ query: action.query,+ ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),+ });case "OpenAddProject":- return { open: true, mode: "command", openIntent: { kind: "add-project" } };+ return openWithIntent({ kind: "add-project" });case "OpenNewThreadIn":- return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };+ return openWithIntent({ kind: "new-thread-in" });case "OpenChangeTheme":- return { open: true, mode: "command", openIntent: { kind: "change-theme" } };- case "ClearOpenIntent":- return state.openIntent ? { ...state, openIntent: null } : state;+ return openWithIntent({ kind: "change-theme" });}}+/** Where "Add project" starts, given the environments that can take a new project. */+export type AddProjectEntry =+ | { readonly kind: "connect-environment" }+ | { readonly kind: "choose-environment" }+ | { readonly kind: "choose-source"; readonly environmentId: EnvironmentId };++export function resolveAddProjectEntry(+ options: ReadonlyArray<Pick<AddProjectEnvironmentOption, "environmentId">>,+ defaultEnvironmentId: EnvironmentId | null,+): AddProjectEntry {+ if (options.length === 0) return { kind: "connect-environment" };+ if (options.length > 1 || defaultEnvironmentId === null) return { kind: "choose-environment" };+ return { kind: "choose-source", environmentId: defaultEnvironmentId };+}+export interface CommandPaletteThreadContentMatch {readonly source: "user" | "assistant";readonly snippet: string;diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex a89c3960fd9..5fbd9b4eaa2 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -74,8 +74,6 @@ import { openThreadFind } from "./chat/threadFindStore";import {useDeferredValue,useEffect,- useEffectEvent,- useLayoutEffect,useReducer,useRef,useState,@@ -97,7 +95,6 @@ import {} from "./promptLinks/copyPromptLink";import { useClientSettings } from "../hooks/useSettings";import { useStableCallback } from "../hooks/useStableCallback";-import { useTheme } from "../hooks/useTheme";import { readLocalApi } from "../localApi";import { desktopLocalBackendId } from "../connection/desktopLocal";import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem";@@ -130,14 +127,12 @@ import {isUnsupportedWindowsProjectPath,resolveProjectPathForDispatch,} from "../lib/projectPaths";-import { onOpenCommandPalette } from "../commandPaletteBus";-import { isPreviewFocused } from "../lib/previewFocus";-import { isTerminalFocused } from "../lib/terminalFocus";import {- PULL_REQUESTS_PANEL_REF,- selectActiveRightPanel,- useRightPanelStore,-} from "../rightPanelStore";+ dispatchCommandPalette,+ useCommandPaletteMount,+ useCommandPaletteStore,+} from "../commandPaletteStore";+import { PULL_REQUESTS_PANEL_REF, useRightPanelStore } from "../rightPanelStore";import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";import {cn,@@ -146,7 +141,6 @@ import {isWindowsPlatform,newProjectId,} from "../lib/utils";-import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";import { buildThreadRouteParams } from "../threadRoutes";import { useAvailableSettingsSearchItems } from "./settings/useAvailableSettingsSearchItems";import {@@ -177,14 +171,14 @@ import {getCommandPaletteMode,ITEM_ICON_CLASS,RECENT_THREAD_LIMIT,- reduceCommandPaletteUiState,createCommandPaletteSearchState,+ type CommandPaletteGroup,+ resolveAddProjectEntry,type AddProjectCloneFlow,type AddProjectEnvironmentOption,buildPaletteRemoteSourceReadiness,errorMessage,getEnvironmentBrowsePlatform,- overlayModeForCommand,remoteProjectInputPlaceholder,reduceCommandPaletteSearchState,type SearchOverlayMode,@@ -210,11 +204,7 @@ import {sourceControlHostIcon,} from "./CommandPaletteAddProject";import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems";-import {- APPEARANCE_OPTIONS,- notifyThemeSaveFailure,- useCommandPaletteThemeItems,-} from "./CommandPaletteThemeItems";+import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems";import {CommandPaletteVirtualizedResults,scrollCommandPaletteRowIntoView,@@ -226,7 +216,6 @@ import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";import { canShareWithGuestAtom } from "./chat/guestShareAvailability";import { openGuestShareDialog } from "./chat/guestShareDialogState";import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";-import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";import { primaryServerKeybindingsAtom } from "../state/server";import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";@@ -243,148 +232,40 @@ import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";import { threadRecentUse } from "@t3tools/shared/paletteSearch";const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];+const ADD_PROJECT_ENTRY_GROUP = "add-project";+const NEW_THREAD_IN_GROUP = "projects";++/** The submenu an open intent starts in; its groups resolve while rendering. */+function openIntentView(intent: CommandPaletteOpenIntent | null): CommandPaletteView | null {+ switch (intent?.kind) {+ case "add-project":+ return {+ addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,+ groups: [{ value: ADD_PROJECT_ENTRY_GROUP, label: "", items: [] }],+ };+ case "new-thread-in":+ return {+ addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,+ groups: [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: [] }],+ };+ case "change-theme":+ return {+ addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />,+ groups: [{ value: "themes", label: "Change theme", items: [] }],+ };+ case "search":+ case undefined:+ return null;+ }+}export function CommandPalette({ children }: { children: ReactNode }) {- const navigate = useNavigate();- const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });- const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {- open: false,- mode: "command",- openIntent: null,- });- const setOpen = (open: boolean) => dispatch({ _tag: "SetOpen", open });- const toggleMode = (mode: SearchOverlayMode) => dispatch({ _tag: "ToggleMode", mode });- const openAddProject = () => dispatch({ _tag: "OpenAddProject" });- const openNewThreadIn = () => dispatch({ _tag: "OpenNewThreadIn" });- const clearOpenIntent = () => dispatch({ _tag: "ClearOpenIntent" });+ useCommandPaletteMount();+ const state = useCommandPaletteStore();+ const setOpen = (open: boolean) => dispatchCommandPalette({ _tag: "SetOpen", open });const openChildSearch = (mode: "files" | "content", context: CommandPaletteReturnContext) =>- dispatch({ _tag: "OpenChildSearch", mode, context });- const keybindings = useAtomValue(primaryServerKeybindingsAtom);- const { theme, themeHalves, resolvedTheme, appearanceMode, setAppearanceMode } = useTheme();+ dispatchCommandPalette({ _tag: "OpenChildSearch", mode, context });const composerHandleRef = useRef<ChatComposerHandle | null>(null);- const routeTarget = useThreadRouteTarget();- const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;- const terminalOpen = useTerminalUiStateStore((state) =>- routeThreadRef- ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen- : false,- );- const previewOpen = useRightPanelStore((state) =>- routeThreadRef- ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"- : false,- );-- useEffect(() => {- if (!state.open || state.mode === "command") return;- const onEscapeKeyDown = (event: globalThis.KeyboardEvent) => {- if (event.isComposing || event.key !== "Escape") return;- event.preventDefault();- event.stopPropagation();- dispatch({ _tag: "BackToCommand" });- };- window.addEventListener("keydown", onEscapeKeyDown, true);- return () => window.removeEventListener("keydown", onEscapeKeyDown, true);- }, [state.mode, state.open]);-- useEffect(() => {- const onKeyDown = (event: globalThis.KeyboardEvent) => {- if (event.defaultPrevented) return;- const command = resolveShortcutCommand(event, keybindings, {- context: {- terminalFocus: isTerminalFocused(),- terminalOpen,- previewFocus: isPreviewFocused(),- previewOpen,- modelPickerOpen: composerHandleRef.current?.isModelPickerOpen() ?? false,- usagePageOpen,- },- });- if (command === "appearance.cycle") {- event.preventDefault();- event.stopPropagation();- if (event.repeat) return;- const nextMode =- appearanceMode === "system" ? "light" : appearanceMode === "light" ? "dark" : "system";- if (!setAppearanceMode(nextMode)) {- notifyThemeSaveFailure();- } else {- toastManager.add({- id: "appearance-cycle",- title: `Appearance: ${APPEARANCE_OPTIONS.find((option) => option.mode === nextMode)?.label}`,- timeout: 1500,- });- }- return;- }- if (command === "theme.select") {- event.preventDefault();- event.stopPropagation();- if (event.repeat) return;- dispatch({ _tag: "OpenChangeTheme" });- return;- }- if (command === "themeEditor.toggle") {- event.preventDefault();- event.stopPropagation();- toggleThemeEditorForTheme({- theme,- themeHalves,- initialAppearance: resolvedTheme,- });- return;- }- if (command === "usage.open") {- event.preventDefault();- event.stopPropagation();- setOpen(false);- void navigate({ to: "/usage" });- return;- }- const mode = overlayModeForCommand(command);- if (mode === null) {- return;- }- event.preventDefault();- event.stopPropagation();- toggleMode(mode);- };- window.addEventListener("keydown", onKeyDown);- return () => window.removeEventListener("keydown", onKeyDown);- }, [- appearanceMode,- keybindings,- navigate,- previewOpen,- resolvedTheme,- setAppearanceMode,- setOpen,- terminalOpen,- theme,- themeHalves,- toggleMode,- usagePageOpen,- ]);-- useEffect(- () =>- onOpenCommandPalette((detail) => {- if (detail.open === "new-thread-in") {- openNewThreadIn();- } else if (detail.open === "add-project") {- openAddProject();- } else if (detail.query !== undefined) {- dispatch({- _tag: "OpenSearch",- query: detail.query,- ...(detail.linkedThreads ? { linkedThreads: detail.linkedThreads } : {}),- });- } else {- setOpen(true);- }- }),- [openAddProject, openNewThreadIn, setOpen],- );return (<ComposerHandleContext value={composerHandleRef}>@@ -393,7 +274,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {onOpenChange={(open, eventDetails) => {if (!open && eventDetails.reason === "escape-key" && state.mode !== "command") {eventDetails.cancel();- dispatch({ _tag: "BackToCommand" });+ dispatchCommandPalette({ _tag: "BackToCommand" });return;}setOpen(open);@@ -404,11 +285,11 @@ export function CommandPalette({ children }: { children: ReactNode }) {</div><CommandPaletteDialogmode={state.mode}+ session={state.session}openIntent={state.openIntent}setOpen={setOpen}openChildSearch={openChildSearch}initialContext={state.restoredSearch}- clearOpenIntent={clearOpenIntent}/></CommandDialog></ComposerHandleContext>@@ -417,6 +298,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {function CommandPaletteDialog(props: {readonly mode: SearchOverlayMode;+ readonly session: number;readonly openIntent: CommandPaletteOpenIntent | null;readonly setOpen: (open: boolean) => void;readonly openChildSearch: (@@ -424,7 +306,6 @@ function CommandPaletteDialog(props: {context: CommandPaletteReturnContext,) => void;readonly initialContext: CommandPaletteReturnContext | undefined;- readonly clearOpenIntent: () => void;}) {const composerHandleRef = useComposerHandleContext();@@ -457,11 +338,11 @@ function CommandPaletteDialog(props: {<ProjectContentSearchDialog onOpenChange={props.setOpen} />) : (<OpenCommandPaletteDialog+ key={props.session}openIntent={props.openIntent}setOpen={props.setOpen}openChildSearch={props.openChildSearch}initialContext={props.initialContext}- clearOpenIntent={props.clearOpenIntent}/>)}</CommandDialogPopup>@@ -476,28 +357,34 @@ function OpenCommandPaletteDialog(props: {context: CommandPaletteReturnContext,) => void;readonly initialContext: CommandPaletteReturnContext | undefined;- readonly clearOpenIntent: () => void;}) {const navigate = useNavigate();const pathname = useLocation({ select: (location) => location.pathname });- const { clearOpenIntent, openIntent, openChildSearch, setOpen } = props;- const initialSearch = props.initialContext ?? {- query: openIntent?.kind === "search" ? openIntent.query : "",- linkedThreadSearch: openIntent?.kind === "search" ? openIntent : null,- };- const [searchState, dispatchSearch] = useReducer(- reduceCommandPaletteSearchState,- initialSearch.query,- createCommandPaletteSearchState,+ const { openChildSearch, setOpen } = props;+ // Keyed by palette session: the intent and restored search only seed this+ // mount, and closing must not change what the closing palette shows.+ const [initialSearch] = useState(+ () =>+ props.initialContext ?? {+ query: props.openIntent?.kind === "search" ? props.openIntent.query : "",+ linkedThreadSearch: props.openIntent?.kind === "search" ? props.openIntent : null,+ },);+ const linkedThreadSearch = initialSearch.linkedThreadSearch;+ const [searchState, dispatchSearch] = useReducer(reduceCommandPaletteSearchState, null, () => {+ const view = props.initialContext ? null : openIntentView(props.openIntent);+ return view+ ? { query: "", views: [{ view, parentQuery: "" }] }+ : createCommandPaletteSearchState(initialSearch.query);+ });const { query, views: viewStack } = searchState;const setQuery = (query: string) => dispatchSearch({ type: "query", query });- const [linkedThreadSearch, setLinkedThreadSearch] = useState(initialSearch.linkedThreadSearch);const deferredQuery = useDeferredValue(query);const isActionsOnly = deferredQuery.startsWith(">");const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);const resultListRef = useRef<LegendListRef | null>(null);- const highlightClearedRef = useRef(false);+ // A pushed view drops the typed highlight until the user moves it again.+ const highlightClearedRef = useRef(viewStack.length > 0);function clearTypedHighlight(): void {highlightClearedRef.current = true;setHighlightedItemValue(null);@@ -818,6 +705,8 @@ function OpenCommandPaletteDialog(props: {useEffect(() => () => {browseNavigation.invalidate();+ // A replaced or closed session must not report its in-flight lookup.+ cloneLookupGeneration.current += 1;},[browseNavigation],);@@ -1185,22 +1074,69 @@ function OpenCommandPaletteDialog(props: {},];+ const openConnectionSettings = () => {+ setOpen(false);+ void navigate({ to: "/settings/connections" });+ };+ const addProjectEntry = resolveAddProjectEntry(+ addProjectEnvironmentOptions,+ defaultAddProjectEnvironmentId,+ );+const openAddProjectFlow = () => {- if (addProjectEnvironmentOptions.length === 0) {- setOpen(false);- void navigate({ to: "/settings/connections" });- return;+ switch (addProjectEntry.kind) {+ case "connect-environment":+ openConnectionSettings();+ return;+ case "choose-environment":+ pushPaletteView({+ addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,+ groups: addProjectEnvironmentGroups,+ });+ return;+ case "choose-source":+ startAddProjectSourceSelection(addProjectEntry.environmentId);+ return;}+ };- if (addProjectEnvironmentOptions.length > 1 || defaultAddProjectEnvironmentId === null) {- pushPaletteView({- addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,- groups: addProjectEnvironmentGroups,- });- return;+ // The view an "Add project" intent opens to follows the environments as they+ // connect, so it resolves here instead of being fixed when the palette opened.+ const addProjectEntryGroups = (): ReadonlyArray<CommandPaletteGroup> => {+ switch (addProjectEntry.kind) {+ case "connect-environment":+ return [+ {+ value: ADD_PROJECT_ENTRY_GROUP,+ label: "",+ items: [+ {+ kind: "action",+ value: "action:add-project:connect-environment",+ searchTerms: ["connect", "environment", "connection", "settings"],+ title: "Connect an environment",+ description: "No connected environment can add a project",+ icon: <SettingsIcon className={ITEM_ICON_CLASS} />,+ keepOpen: true,+ run: async () => {+ openConnectionSettings();+ },+ },+ ],+ },+ ];+ case "choose-environment":+ return addProjectEnvironmentGroups;+ case "choose-source":+ return buildAddProjectSourceGroups(+ addProjectEntry.environmentId,+ buildPaletteRemoteSourceReadiness(+ browseEnvironmentId === addProjectEntry.environmentId+ ? sourceControlDiscovery.data+ : null,+ ),+ );}-- void startAddProjectSourceSelection(defaultAddProjectEnvironmentId);};const openNewProjectFlow = () => {@@ -1246,7 +1182,7 @@ function OpenCommandPaletteDialog(props: {title: "New thread in...",icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,- groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],+ groups: [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: projectThreadItems }],});}@@ -1511,45 +1447,6 @@ function OpenCommandPaletteDialog(props: {actionItems.push(changeThemeItem);actionItems.push(changeAppearanceItem);- // Apply intents after commit but before paint because they clear parent state and may navigate.- const projectThreadItemCount = projectThreadItems.length;- const applyOpenIntent = useEffectEvent((intent: CommandPaletteOpenIntent) => {- clearOpenIntent();- browseNavigation.invalidate();- cloneLookupGeneration.current += 1;- setIsRemoteProjectLookingUp(false);- setAddProjectEnvironmentId(null);- setAddProjectCloneFlow(null);- setNewProjectFlow(null);- setLinkedThreadSearch(intent.kind === "search" ? intent : null);- dispatchSearch({ type: "reset", query: intent.kind === "search" ? intent.query : "" });- switch (intent.kind) {- case "search":- return;- case "add-project":- openAddProjectFlow();- return;- case "new-thread-in":- pushPaletteView({- addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,- groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],- });- return;- case "change-theme":- pushPaletteView({- addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />,- groups: [{ value: "themes", label: "Change theme", items: [] }],- });- return;- }- });- useLayoutEffect(() => {- if (openIntent === null) return;- if (openIntent.kind === "new-thread-in" && projectThreadItemCount === 0) return;- // 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.- applyOpenIntent(openIntent);- }, [openIntent, projectThreadItemCount]);-actionItems.push(themeEditorItem);if (@@ -1676,11 +1573,15 @@ function OpenCommandPaletteDialog(props: {addProjectEnvironmentId,buildPaletteRemoteSourceReadiness(sourceControlDiscovery.data),)- : currentView?.groups[0]?.value === "themes"- ? changeThemeItem.groups- : currentView?.groups[0]?.value === "appearance"- ? changeAppearanceItem.groups- : (currentView?.groups ?? rootGroups);+ : currentView?.groups[0]?.value === ADD_PROJECT_ENTRY_GROUP+ ? addProjectEntryGroups()+ : currentView?.groups[0]?.value === NEW_THREAD_IN_GROUP+ ? [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: projectThreadItems }]+ : currentView?.groups[0]?.value === "themes"+ ? changeThemeItem.groups+ : currentView?.groups[0]?.value === "appearance"+ ? changeAppearanceItem.groups+ : (currentView?.groups ?? rootGroups);const isLinkedThreadSearch =linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query;diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsxindex 32d9f81e3ac..9f6dcc42626 100644--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@ -1,5 +1,5 @@import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";-import { useAtomValue } from "@effect/atom-react";+import { useAtomMount, useAtomValue } from "@effect/atom-react";import {AuthOrchestrationOperateScope,AuthSourceControlWriteScope,@@ -22,6 +22,8 @@ import type {import { useNavigate } from "@tanstack/react-router";import * as Option from "effect/Option";import { type MouseEvent, useEffect, useEffectEvent, useRef, useState } from "react";+import { useDeadlinePassed } from "../hooks/useDeadline";+import { useNowSecond } from "../hooks/useNowSecond";import { flushSync } from "react-dom";import {CheckIcon,@@ -105,7 +107,7 @@ import { serverEnvironment } from "~/state/server";import { sourceControlEnvironment } from "~/state/sourceControl";import { threadEnvironment } from "~/state/threads";import { useAtomCommand } from "~/state/use-atom-command";-import { vcsActionManager, vcsEnvironment } from "~/state/vcs";+import { vcsActionManager, vcsEnvironment, vcsStatusRevalidation } from "~/state/vcs";import { randomUUID } from "~/lib/utils";import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";@@ -158,9 +160,10 @@ interface InlineGitActionSuccess {readonly title: string;readonly description: string | null;readonly scopeKey: string;+ readonly expiresAtMs: number;}-const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;+const inlineSuccessExpiresAt = () => Date.now() + GIT_ACTION_SUCCESS_VISIBLE_MS;type RefreshVcsStatus = (target: {readonly environmentId: ScopedThreadRef["environmentId"];@@ -330,19 +333,19 @@ function GitActionElapsedTime({startedAtMs: number | null;className?: string;}) {- const [nowMs, setNowMs] = useState(() => Date.now());-- useEffect(() => {- if (startedAtMs === null) {- return;- }-- const intervalId = window.setInterval(() => {- setNowMs(Date.now());- }, 1_000);- return () => window.clearInterval(intervalId);- }, [startedAtMs]);+ return startedAtMs === null ? null : (+ <RunningGitActionElapsedTime startedAtMs={startedAtMs} className={className} />+ );+}+function RunningGitActionElapsedTime({+ startedAtMs,+ className,+}: {+ startedAtMs: number;+ className: string | undefined;+}) {+ const nowMs = useNowSecond();const elapsed = formatGitActionElapsed(startedAtMs, nowMs);if (!elapsed) {return null;@@ -1011,15 +1014,9 @@ export default function GitActionsControl({useState<PendingDefaultBranchAction | null>(null);const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd };const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope));- const visibleInlineSuccess = inlineSuccess?.scopeKey === successScopeKey ? inlineSuccess : null;-- useEffect(() => {- if (!inlineSuccess) return;- const timeoutId = window.setTimeout(() => {- setInlineSuccess(null);- }, GIT_ACTION_SUCCESS_VISIBLE_MS);- return () => window.clearTimeout(timeoutId);- }, [inlineSuccess]);+ const inlineSuccessExpired = useDeadlinePassed(inlineSuccess?.expiresAtMs ?? null);+ const visibleInlineSuccess =+ inlineSuccess?.scopeKey === successScopeKey && !inlineSuccessExpired ? inlineSuccess : null;const persistThreadBranchSync = (branch: string | null, manualSelection = false) => {if (!activeThreadRef) {@@ -1179,38 +1176,13 @@ export default function GitActionsControl({}): null;- useEffect(() => {- if (gitCwd === null) {- return;- }-- let refreshTimeout: number | null = null;- const scheduleRefreshCurrentGitStatus = () => {- if (refreshTimeout !== null) {- window.clearTimeout(refreshTimeout);- }- refreshTimeout = window.setTimeout(() => {- refreshTimeout = null;- requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);- }, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);- };- const handleVisibilityChange = () => {- if (document.visibilityState === "visible") {- scheduleRefreshCurrentGitStatus();- }- };-- window.addEventListener("focus", scheduleRefreshCurrentGitStatus);- document.addEventListener("visibilitychange", handleVisibilityChange);-- return () => {- if (refreshTimeout !== null) {- window.clearTimeout(refreshTimeout);- }- window.removeEventListener("focus", scheduleRefreshCurrentGitStatus);- document.removeEventListener("visibilitychange", handleVisibilityChange);- };- }, [activeEnvironmentId, gitCwd, refreshVcsStatus]);+ useAtomMount(+ vcsStatusRevalidation(+ activeEnvironmentId !== null && gitCwd !== null+ ? { environmentId: activeEnvironmentId, cwd: gitCwd }+ : null,+ ),+ );// Toast actions must retain their original checkout/thread, so do not use an effect event.async function runGitActionWithToast({@@ -1306,6 +1278,7 @@ export default function GitActionsControl({: actionResult.toast.title,description: createdPullRequest ? null : (actionResult.toast.description ?? null),scopeKey: successScopeKey,+ expiresAtMs: inlineSuccessExpiresAt(),});return;}@@ -1439,7 +1412,12 @@ export default function GitActionsControl({? `Updated ${pullResult.refName} from ${pullResult.upstreamRef ?? "upstream"}`: `${pullResult.refName} is already synchronized.`;if (isPanel) {- setInlineSuccess({ title, description, scopeKey: successScopeKey });+ setInlineSuccess({+ title,+ description,+ scopeKey: successScopeKey,+ expiresAtMs: inlineSuccessExpiresAt(),+ });return;}const successToastTiming = resolveGitActionResultToastTiming("success");diff --git a/apps/web/src/components/UsageToggleShortcut.browser.test.tsx b/apps/web/src/components/UsageToggleShortcut.browser.test.tsxindex a93990dccd4..dfa75bdfccd 100644--- a/apps/web/src/components/UsageToggleShortcut.browser.test.tsx+++ b/apps/web/src/components/UsageToggleShortcut.browser.test.tsx@@ -32,8 +32,14 @@ vi.mock(import("@tanstack/react-router"), async (original) => ({useNavigate: (() => state.navigate) as never,}));+import { useCommandPaletteMount } from "../commandPaletteStore";+import { installCommandPaletteCommands } from "../shortcuts/commandPaletteCommands";import { registerNavigationHistoryCommands } from "./AppSidebarLayout";-import { CommandPalette } from "./CommandPalette";++function MountedPalette() {+ useCommandPaletteMount();+ return null;+}// regression: #21357describe("usage toggle shortcut on Usage", () => {@@ -53,12 +59,15 @@ describe("usage toggle shortcut on Usage", () => {it("does not reopen Usage from the command palette", async () => {vi.clearAllMocks();using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");- await using _screen = await render(<CommandPalette>{null}</CommandPalette>, {- router: "/usage",- });+ await using screen = await render(<MountedPalette />, { router: "/usage" });+ using navigate = vi.spyOn(screen.router!, "navigate");+ using commands = new DisposableStack();+ commands.defer(+ installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }),+ );await userEvent.keyboard("{Control>}u{/Control}");- expect(state.navigate).not.toHaveBeenCalled();+ expect(navigate).not.toHaveBeenCalled();});});diff --git a/apps/web/src/components/WorktreeBaseBranchPicker.tsx b/apps/web/src/components/WorktreeBaseBranchPicker.tsxindex 0ad0f7005e3..2fde4980e04 100644--- a/apps/web/src/components/WorktreeBaseBranchPicker.tsx+++ b/apps/web/src/components/WorktreeBaseBranchPicker.tsx@@ -78,7 +78,6 @@ export function WorktreeBaseBranchPicker({filteredItems={items}value={value || null}query={query}- resultsQuery={deferredQuery}onQueryChange={setQuery}open={open && !disabled}onOpenChange={handleOpenChange}diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.tsindex ddd89eea229..6addce1543c 100644--- a/apps/web/src/hooks/useTheme.ts+++ b/apps/web/src/hooks/useTheme.ts@@ -485,6 +485,11 @@ function subscribe(listener: () => void): () => void {};}+/** For shortcuts and other handlers outside React that read the theme at event time. */+export function getThemeSnapshot(): ThemeSnapshot {+ return getSnapshot();+}+/** For code outside React (worker pools) that follows the rendered appearance. */export function subscribeRenderedAppearance(listener: () => void): () => void {const unsubscribeTheme = subscribe(listener);diff --git a/apps/web/src/lib/documentActivity.browser.test.ts b/apps/web/src/lib/documentActivity.browser.test.tsnew file mode 100644index 00000000000..55782168f4d--- /dev/null+++ b/apps/web/src/lib/documentActivity.browser.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { subscribeDocumentReturn } from "./documentActivity";++describe("subscribeDocumentReturn", () => {+ // Focus can come back from the preview iframe, and a quick alt-tab can miss+ // the blur, so a return must not depend on the cached activity flipping.+ it("fires on every window focus and every return to a visible tab", () => {+ using _focused = vi.spyOn(document, "hasFocus").mockReturnValue(true);+ let visibility: DocumentVisibilityState = "visible";+ using _visibility = vi+ .spyOn(document, "visibilityState", "get")+ .mockImplementation(() => visibility);+ const wake = vi.fn();+ using subscription = new DisposableStack();+ subscription.defer(subscribeDocumentReturn(wake));++ window.dispatchEvent(new Event("focus"));+ window.dispatchEvent(new Event("focus"));+ expect(wake).toHaveBeenCalledTimes(2);++ visibility = "hidden";+ document.dispatchEvent(new Event("visibilitychange"));+ expect(wake).toHaveBeenCalledTimes(2);+ visibility = "visible";+ document.dispatchEvent(new Event("visibilitychange"));+ expect(wake).toHaveBeenCalledTimes(3);++ subscription.dispose();+ window.dispatchEvent(new Event("focus"));+ expect(wake).toHaveBeenCalledTimes(3);+ });+});diff --git a/apps/web/src/lib/documentActivity.ts b/apps/web/src/lib/documentActivity.tsindex e7290a7e9bf..e9316555e74 100644--- a/apps/web/src/lib/documentActivity.ts+++ b/apps/web/src/lib/documentActivity.ts@@ -48,3 +48,22 @@ export function subscribeDocumentActivity(listener: () => void): () => void {window.removeEventListener("blur", handleActivityEvent);};}++/**+ * Fires on every window focus and every switch to a visible tab. Unlike+ * `subscribeDocumentActivity` it does not wait for the cached activity to flip:+ * focus coming back from an iframe, or an alt-tab whose blur was missed, still+ * counts as a return.+ */+export function subscribeDocumentReturn(listener: () => void): () => void {+ if (typeof document === "undefined") return () => {};+ const handleVisibilityChange = () => {+ if (document.visibilityState === "visible") listener();+ };+ window.addEventListener("focus", listener);+ document.addEventListener("visibilitychange", handleVisibilityChange);+ return () => {+ window.removeEventListener("focus", listener);+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ };+}diff --git a/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx b/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsxnew file mode 100644index 00000000000..310cbac99ed--- /dev/null+++ b/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx@@ -0,0 +1,70 @@+import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings";+import { describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import { render } from "../../test/render";+import { openCommandPalette } from "../commandPaletteBus";+import { useCommandPaletteMount, useCommandPaletteStore } from "../commandPaletteStore";+import { installCommandPaletteCommands } from "./commandPaletteCommands";++const keybindings = compileResolvedKeybindingsConfig([+ { key: "mod+k", command: "commandPalette.toggle" },+]);++function MountedPalette() {+ useCommandPaletteMount();+ return null;+}++function setup() {+ useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true);+}++describe("command palette shortcuts", () => {+ it("stay inert on routes without the palette", async () => {+ setup();+ using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");+ await using screen = await render(null, { router: "/pair" });+ using commands = new DisposableStack();+ commands.defer(+ installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }),+ );++ await userEvent.keyboard("{Control>}k{/Control}");++ expect(useCommandPaletteStore.getState().open).toBe(false);+ });++ it("open the palette while it is mounted, and it closes when it unmounts", async () => {+ setup();+ using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");+ await using screen = await render(<MountedPalette />, { router: "/" });+ using commands = new DisposableStack();+ commands.defer(+ installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }),+ );++ await userEvent.keyboard("{Control>}k{/Control}");+ expect(useCommandPaletteStore.getState().open).toBe(true);++ await screen.rerender(<div />);+ expect(useCommandPaletteStore.getState().open).toBe(false);+ });+});++describe("openCommandPalette", () => {+ it("drops a request made while no palette is mounted", async () => {+ setup();+ await using screen = await render(null, { router: "/pair" });++ openCommandPalette({ open: "new-thread-in" });+ await screen.rerender(<MountedPalette />);+ expect(useCommandPaletteStore.getState()).toMatchObject({ open: false, openIntent: null });++ openCommandPalette({ open: "new-thread-in" });+ expect(useCommandPaletteStore.getState()).toMatchObject({+ open: true,+ openIntent: { kind: "new-thread-in" },+ });+ });+});diff --git a/apps/web/src/shortcuts/commandPaletteCommands.ts b/apps/web/src/shortcuts/commandPaletteCommands.tsnew file mode 100644index 00000000000..716717061e8--- /dev/null+++ b/apps/web/src/shortcuts/commandPaletteCommands.ts@@ -0,0 +1,125 @@+import type { AnyRouter } from "@tanstack/react-router";++import {+ dispatchCommandPalette,+ isCommandPaletteMounted,+ useCommandPaletteStore,+} from "../commandPaletteStore";+import { overlayModeForCommand } from "../components/CommandPalette.logic";+import { APPEARANCE_OPTIONS, notifyThemeSaveFailure } from "../components/CommandPaletteThemeItems";+import { toggleThemeEditorForTheme } from "../components/settings/themeEditorStore";+import { toastManager } from "../components/ui/toast";+import { getThemeSnapshot, setAppearanceMode } from "../hooks/useTheme";+import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";+import { type CommandHandler, type CommandScopeOptions, registerCommands } from "./dispatcher";+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";+import { resolveThreadRouteTarget } from "../threadRoutes";++function consume(event: KeyboardEvent): void {+ event.preventDefault();+ event.stopPropagation();+}++const toggleOverlay =+ (command: Parameters<typeof overlayModeForCommand>[0]): CommandHandler =>+ (event) => {+ const mode = overlayModeForCommand(command);+ if (mode === null) return false;+ consume(event);+ dispatchCommandPalette({ _tag: "ToggleMode", mode });+ };++/**+ * Palette, theme and usage shortcuts. They read the route, panels and theme+ * when the key is pressed, and are live only while the palette is mounted.+ */+export function installCommandPaletteCommands(+ router: AnyRouter,+ options: Pick<CommandScopeOptions, "keybindings"> = {},+): () => void {+ const readRouteThreadRef = () => {+ const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});+ return target?.kind === "server" ? target.threadRef : null;+ };++ // A child search (files, contents) goes back to the palette on Escape before+ // its own widgets or the dialog can treat the key as a close.+ const disposeEscape = registerCommands(+ {},+ {+ capture: true,+ when: isCommandPaletteMounted,+ onKeyDown: (event) => {+ if (event.isComposing || event.key !== "Escape") return false;+ const { open, mode } = useCommandPaletteStore.getState();+ if (!open || mode === "command") return false;+ consume(event);+ dispatchCommandPalette({ _tag: "BackToCommand" });+ },+ },+ );++ const disposeCommands = registerCommands(+ {+ "appearance.cycle": (event) => {+ consume(event);+ if (event.repeat) return;+ const { appearanceMode } = getThemeSnapshot();+ const nextMode =+ appearanceMode === "system" ? "light" : appearanceMode === "light" ? "dark" : "system";+ if (!setAppearanceMode(nextMode)) {+ notifyThemeSaveFailure();+ return;+ }+ toastManager.add({+ id: "appearance-cycle",+ title: `Appearance: ${APPEARANCE_OPTIONS.find((option) => option.mode === nextMode)?.label}`,+ timeout: 1500,+ });+ },+ "theme.select": (event) => {+ consume(event);+ if (event.repeat) return;+ dispatchCommandPalette({ _tag: "OpenChangeTheme" });+ },+ "themeEditor.toggle": (event) => {+ consume(event);+ const { theme, themeHalves, resolvedTheme } = getThemeSnapshot();+ toggleThemeEditorForTheme({ theme, themeHalves, initialAppearance: resolvedTheme });+ },+ "usage.open": (event) => {+ consume(event);+ dispatchCommandPalette({ _tag: "SetOpen", open: false });+ void router.navigate({ to: "/usage" });+ },+ "commandPalette.toggle": toggleOverlay("commandPalette.toggle"),+ "filePicker.toggle": toggleOverlay("filePicker.toggle"),+ "projectSearch.toggle": toggleOverlay("projectSearch.toggle"),+ },+ {+ ...options,+ when: isCommandPaletteMounted,+ context: () => {+ const threadRef = readRouteThreadRef();+ return {+ terminalOpen: threadRef+ ? selectThreadTerminalUiState(+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,+ threadRef,+ ).terminalOpen+ : false,+ previewOpen: threadRef+ ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) ===+ "preview"+ : false,+ usagePageOpen: router.state.location.pathname === "/usage",+ };+ },+ },+ );++ return () => {+ disposeEscape();+ disposeCommands();+ };+}diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex f7c5fc1d756..af71b314c4c 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -232,6 +232,13 @@ export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {return appAtomRegistry.get(environmentProjects.projectAtom(ref));}+export function subscribeProject(+ ref: ScopedProjectRef,+ listener: (project: EnvironmentProject | null) => void,+): () => void {+ return appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), listener);+}+export function readProjects(): ReadonlyArray<EnvironmentProject> {return appAtomRegistry.get(environmentProjects.projectsAtom);}diff --git a/apps/web/src/state/vcs.ts b/apps/web/src/state/vcs.tsindex dc8c251149f..fd4f34caaa6 100644--- a/apps/web/src/state/vcs.ts+++ b/apps/web/src/state/vcs.ts@@ -1,9 +1,21 @@import {createVcsActionManager,createVcsEnvironmentAtoms,+ createVcsStatusRevalidationAtomFamily,} from "@t3tools/client-runtime/state/vcs";import { connectionAtomRuntime } from "../connection/runtime";+import { subscribeDocumentReturn } from "../lib/documentActivity";export const vcsEnvironment = createVcsEnvironmentAtoms(connectionAtomRuntime);export const vcsActionManager = createVcsActionManager(connectionAtomRuntime);++/**+ * Refreshes a checkout's status when the user comes back to the window, where+ * edits made in another app or terminal may be waiting.+ */+export const vcsStatusRevalidation = createVcsStatusRevalidationAtomFamily({+ refreshStatus: vcsEnvironment.refreshStatus,+ subscribeWake: subscribeDocumentReturn,+ wakeDebounceMs: 250,+});diff --git a/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts b/packages/client-runtime/src/state/vcsStatusRevalidation.test.tsindex ed2b7f56acf..9a1d8c3dd27 100644--- a/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts+++ b/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts@@ -6,15 +6,28 @@ import { createVcsStatusRevalidationAtomFamily } from "./vcsStatusRevalidation.tconst environmentId = EnvironmentId.make("environment-1");-function setup(options: { readonly connected: boolean }) {- const connectedAtom = Atom.make(options.connected);+function setup(options: { readonly connected?: boolean; readonly wake?: boolean }) {+ const connectedAtom = Atom.make(options.connected ?? false);+ const wakes = new Set<() => void>();const run = vi.fn(async () => AsyncResult.success(null));const family = createVcsStatusRevalidationAtomFamily({refreshStatus: { label: "refresh-status", run },- connected: () => connectedAtom,+ ...(options.connected === undefined ? {} : { connected: () => connectedAtom }),+ ...(options.wake+ ? {+ subscribeWake: (wake: () => void) => {+ wakes.add(wake);+ return () => wakes.delete(wake);+ },+ wakeDebounceMs: 250,+ }+ : {}),});const registry = AtomRegistry.make();- return { registry, family, connectedAtom, run };+ const wake = () => {+ for (const listener of wakes) listener();+ };+ return { registry, family, connectedAtom, run, wakes, wake };}describe("createVcsStatusRevalidationAtomFamily", () => {@@ -46,9 +59,35 @@ describe("createVcsStatusRevalidationAtomFamily", () => {unmount();});+ it("debounces wake signals and stops listening with the last subscriber", () => {+ vi.useFakeTimers();+ try {+ const { registry, family, run, wakes, wake } = setup({ wake: true });+ const unmount = registry.mount(family({ environmentId, cwd: "/repo" }));+ expect(run).not.toHaveBeenCalled();++ wake();+ vi.advanceTimersByTime(100);+ wake();+ vi.advanceTimersByTime(249);+ expect(run).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(run).toHaveBeenCalledTimes(1);++ wake();+ unmount();+ vi.runAllTimers();+ expect(run).toHaveBeenCalledTimes(1);+ expect(wakes.size).toBe(0);+ } finally {+ vi.useRealTimers();+ }+ });+it("does nothing for an idle target", () => {- const { registry, family, run } = setup({ connected: true });+ const { registry, family, run, wakes } = setup({ connected: true, wake: true });registry.mount(family(null))();expect(run).not.toHaveBeenCalled();+ expect(wakes.size).toBe(0);});});diff --git a/packages/client-runtime/src/state/vcsStatusRevalidation.ts b/packages/client-runtime/src/state/vcsStatusRevalidation.tsindex bb3cc43a875..58f5f9c9a7e 100644--- a/packages/client-runtime/src/state/vcsStatusRevalidation.ts+++ b/packages/client-runtime/src/state/vcsStatusRevalidation.ts@@ -1,17 +1,18 @@+// @effect-diagnostics globalTimers:off - The wake debounce runs in an atom subscription, outside an Effect runtime.import type { EnvironmentId } from "@t3tools/contracts";import { Atom, type AtomRegistry } from "effect/reactivity";import { type AtomCommand, type AtomCommandResult, runAtomCommand } from "./runtime.ts";-interface VcsStatusRevalidationTarget {+export interface VcsStatusRevalidationTarget {readonly environmentId: EnvironmentId;readonly cwd: string;}/**- * One atom per environment and cwd, shared by every subscriber, that refreshes- * VCS status while mounted: on mount and on each reconnect, once `connected`- * is true.+ * One atom per checkout, so controls showing it share one cadence. Refreshes on+ * `subscribeWake` (debounced) and whenever `connected`, if given, is true on+ * mount or turns true. Listening ends with the last subscriber.*/export function createVcsStatusRevalidationAtomFamily<R>(input: {readonly refreshStatus: AtomCommand<@@ -19,7 +20,9 @@ export function createVcsStatusRevalidationAtomFamily<R>(input: {R,unknown>;- readonly connected: (environmentId: EnvironmentId) => Atom.Atom<boolean>;+ readonly connected?: (environmentId: EnvironmentId) => Atom.Atom<boolean>;+ readonly subscribeWake?: (wake: () => void) => () => void;+ readonly wakeDebounceMs?: number;readonly onRefreshed?: (result: AtomCommandResult<R, unknown>) => void;}) {const family = Atom.family((target: VcsStatusRevalidationTarget) => {@@ -36,9 +39,29 @@ export function createVcsStatusRevalidationAtomFamily<R>(input: {input.onRefreshed?.(result);};+ const wakeAtom = Atom.make((get) => {+ const subscribeWake = input.subscribeWake;+ if (subscribeWake === undefined) return;+ const registry = get.registry;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const unsubscribe = subscribeWake(() => {+ if (timer !== undefined) clearTimeout(timer);+ timer = setTimeout(() => {+ timer = undefined;+ void refresh(registry);+ }, input.wakeDebounceMs ?? 0);+ });+ get.addFinalizer(() => {+ if (timer !== undefined) clearTimeout(timer);+ unsubscribe();+ });+ }).pipe(Atom.withLabel(`vcs-status-revalidation:wake:${key}`));+return Atom.make((get) => {+ get(wakeAtom);+ const connected = input.connected;// Rebuilds only when the connection flag flips, so each reconnect refreshes once.- if (get(input.connected(environmentId))) {+ if (connected !== undefined && get(connected(environmentId))) {void refresh(get.registry);}}).pipe(Atom.withLabel(`vcs-status-revalidation:${key}`));