fix: open command palette instead of custom dialog for new thread picker in SidebarV2 (#4269)

This commit is contained in:
Utkarsh Patil authored and GitHub committed 2026-07-22 15:54:09 +00:00
1 parent 376c149eac
commit 9fe4832a3f
10 files changed
+118 -217

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
// Tiny event bus allowing components to programmatically open the command palette
// without owning its React state.
const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";
export interface CommandPaletteOpenDetail {
readonly open?: "add-project" | "new-thread-in";
}
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);
}
/** Read at event time so consumers do not subscribe to transient dialog state. */
export function isCommandPaletteOpen(): boolean {
return (
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
);
}
-29
View File
@@ -1,29 +0,0 @@
import { createContext, use, type ReactNode } from "react";
const OpenAddProjectCommandPaletteContext = createContext<(() => void) | null>(null);
export function OpenAddProjectCommandPaletteProvider(props: {
readonly children: ReactNode;
readonly openAddProject: () => void;
}) {
return (
<OpenAddProjectCommandPaletteContext value={props.openAddProject}>
{props.children}
</OpenAddProjectCommandPaletteContext>
);
}
export function useOpenAddProjectCommandPalette(): () => void {
const openAddProject = use(OpenAddProjectCommandPaletteContext);
if (!openAddProject) {
throw new Error("Command palette actions must be used inside CommandPalette");
}
return openAddProject;
}
/** Read at event time so the chat tree does not subscribe to transient dialog state. */
export function isCommandPaletteOpen(): boolean {
return (
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
);
}
+1 -1
View File
@@ -112,7 +112,7 @@ import {
} from "../types";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { isCommandPaletteOpen } from "../commandPaletteContext";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
+62 -15
View File
@@ -43,7 +43,7 @@ import {
type ReactNode,
} from "react";
import { useAtomValue } from "@effect/atom-react";
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
@@ -77,6 +77,7 @@ import {
isUnsupportedWindowsProjectPath,
resolveProjectPathForDispatch,
} from "../lib/projectPaths";
import { onOpenCommandPalette } from "../commandPaletteBus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { getLatestThreadForProject } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
@@ -334,7 +335,7 @@ function errorMessage(error: unknown): string {
}
interface CommandPaletteOpenIntent {
readonly kind: "add-project";
readonly kind: "add-project" | "new-thread-in";
}
interface CommandPaletteUiState {
@@ -346,6 +347,7 @@ type CommandPaletteUiAction =
| { readonly _tag: "SetOpen"; readonly open: boolean }
| { readonly _tag: "Toggle" }
| { readonly _tag: "OpenAddProject" }
| { readonly _tag: "OpenNewThreadIn" }
| { readonly _tag: "ClearOpenIntent" };
function reduceCommandPaletteUiState(
@@ -362,6 +364,8 @@ function reduceCommandPaletteUiState(
return { open: !state.open, openIntent: null };
case "OpenAddProject":
return { open: true, openIntent: { kind: "add-project" } };
case "OpenNewThreadIn":
return { open: true, openIntent: { kind: "new-thread-in" } };
case "ClearOpenIntent":
return state.openIntent ? { ...state, openIntent: null } : state;
}
@@ -375,6 +379,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
@@ -409,20 +414,32 @@ export function CommandPalette({ children }: { children: ReactNode }) {
return () => window.removeEventListener("keydown", onKeyDown);
}, [keybindings, terminalOpen, toggleOpen]);
useEffect(
() =>
onOpenCommandPalette((detail) => {
if (detail.open === "new-thread-in") {
openNewThreadIn();
} else if (detail.open === "add-project") {
openAddProject();
} else {
setOpen(true);
}
}),
[openAddProject, openNewThreadIn, setOpen],
);
return (
<OpenAddProjectCommandPaletteProvider openAddProject={openAddProject}>
<ComposerHandleContext value={composerHandleRef}>
<CommandDialog open={state.open} onOpenChange={setOpen}>
{children}
<CommandPaletteDialog
open={state.open}
openIntent={state.openIntent}
setOpen={setOpen}
clearOpenIntent={clearOpenIntent}
/>
</CommandDialog>
</ComposerHandleContext>
</OpenAddProjectCommandPaletteProvider>
<ComposerHandleContext value={composerHandleRef}>
<CommandDialog open={state.open} onOpenChange={setOpen}>
{children}
<CommandPaletteDialog
open={state.open}
openIntent={state.openIntent}
setOpen={setOpen}
clearOpenIntent={clearOpenIntent}
/>
</CommandDialog>
</ComposerHandleContext>
);
}
@@ -960,6 +977,36 @@ function OpenCommandPaletteDialog(props: {
openAddProjectFlow();
}, [clearOpenIntent, openAddProjectFlow, openIntent]);
useLayoutEffect(() => {
if (openIntent?.kind !== "new-thread-in" || projectThreadItems.length === 0) {
return;
}
clearOpenIntent();
setAddProjectCloneFlow(null);
setViewStack([]);
setQuery("");
const currentPrefix =
currentProjectEnvironmentId && currentProjectId
? `new-thread-in:${currentProjectEnvironmentId}:${currentProjectId}`
: null;
const prioritized = currentPrefix
? [
...projectThreadItems.filter((item) => item.value === currentPrefix),
...projectThreadItems.filter((item) => item.value !== currentPrefix),
]
: projectThreadItems;
pushPaletteView({
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
groups: [{ value: "projects", label: "Projects", items: prioritized }],
});
}, [
clearOpenIntent,
currentProjectEnvironmentId,
currentProjectId,
openIntent,
projectThreadItems,
]);
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (projects.length > 0) {
+5 -2
View File
@@ -177,7 +177,7 @@ import {
useSidebar,
} from "./ui/sidebar";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
import { openCommandPalette } from "../commandPaletteBus";
import {
archiveSelectedThreadEntries,
buildMultiSelectThreadContextMenuItems,
@@ -3086,7 +3086,10 @@ export default function Sidebar() {
: false,
);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const openAddProjectCommandPalette = useOpenAddProjectCommandPalette();
const openAddProjectCommandPalette = useCallback(
() => openCommandPalette({ open: "add-project" }),
[],
);
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<string>
>(() => new Set());
+10 -146
View File
@@ -57,14 +57,8 @@ import { useUiStateStore } from "../uiStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useThreadActions } from "../hooks/useThreadActions";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
import { onOpenNewThreadPicker } from "../newThreadPickerBus";
import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "./ui/dialog";
import {
resolveThreadActionProjectRef,
startNewThreadFromContext,
startNewThreadInProjectFromContext,
} from "../lib/chatThreadActions";
import { openCommandPalette } from "../commandPaletteBus";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { useClientSettings } from "../hooks/useSettings";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
@@ -630,7 +624,10 @@ export default function SidebarV2() {
reportFailure: false,
});
const newThreadContext = useHandleNewThread();
const openAddProjectCommandPalette = useOpenAddProjectCommandPalette();
const openAddProjectCommandPalette = useCallback(
() => openCommandPalette({ open: "add-project" }),
[],
);
const { environments } = useEnvironments();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
@@ -1301,12 +1298,8 @@ export default function SidebarV2() {
// New thread defaults to the project you're in (active thread's project,
// falling back to the top project) — same resolution the command palette
// uses. The chevron menu is the explicit project picker the flat list no
// longer gets from per-project headers.
const [newThreadPickerOpen, setNewThreadPickerOpen] = useState(false);
// chat.new (mod+shift+o / mod+n) is handled by the _chat route layout; in
// v2 with multiple projects it opens this picker via the event bus.
useEffect(() => onOpenNewThreadPicker(() => setNewThreadPickerOpen(true)), []);
// uses. The command palette already offers a "New thread in..." submenu
// for multi-project setups.
const handleNewThreadClick = useCallback(() => {
// One project: nothing to pick, create immediately.
if (projects.length <= 1) {
@@ -1319,57 +1312,9 @@ export default function SidebarV2() {
});
return;
}
setNewThreadPickerOpen(true);
if (isMobile) setOpenMobile(false);
openCommandPalette({ open: "new-thread-in" });
}, [isMobile, newThreadContext, projects.length, setOpenMobile]);
const createThreadInProject = useCallback(
(environmentId: (typeof projects)[number]["environmentId"], projectId: string) => {
setNewThreadPickerOpen(false);
if (isMobile) setOpenMobile(false);
const project = projects.find(
(candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
);
if (!project) return;
void startNewThreadInProjectFromContext(
{
activeDraftThread: newThreadContext.activeDraftThread,
activeThread: newThreadContext.activeThread ?? undefined,
defaultProjectRef: newThreadContext.defaultProjectRef,
handleNewThread: newThreadContext.handleNewThread,
},
scopeProjectRef(project.environmentId, project.id),
);
},
[isMobile, newThreadContext, projects, setOpenMobile],
);
const contextualProjectRef = resolveThreadActionProjectRef({
activeDraftThread: newThreadContext.activeDraftThread,
activeThread: newThreadContext.activeThread ?? undefined,
defaultProjectRef: newThreadContext.defaultProjectRef,
handleNewThread: newThreadContext.handleNewThread,
});
const newThreadTargetRef = scopedProject
? scopeProjectRef(scopedProject.environmentId, scopedProject.id)
: contextualProjectRef;
const newThreadTargetProject = newThreadTargetRef
? (projects.find(
(project) =>
project.environmentId === newThreadTargetRef.environmentId &&
project.id === newThreadTargetRef.projectId,
) ?? null)
: null;
// Picker order: the contextual default first (preselected), everything else
// after — the common case is Enter/click on the top row.
const newThreadPickerProjects = useMemo(() => {
if (!newThreadTargetProject) return projects;
return [
newThreadTargetProject,
...projects.filter(
(project) =>
project.environmentId !== newThreadTargetProject.environmentId ||
project.id !== newThreadTargetProject.id,
),
];
}, [newThreadTargetProject, projects]);
const commandPaletteShortcutLabel = shortcutLabelForCommand(keybindings, "commandPalette.toggle");
// Same resolution as v1: prefer the local-thread binding, fall back to
@@ -1639,87 +1584,6 @@ export default function SidebarV2() {
</SidebarContent>
<SidebarSeparator />
<SidebarChromeFooter />
<Dialog open={newThreadPickerOpen} onOpenChange={setNewThreadPickerOpen}>
<DialogPopup className="max-w-sm p-0">
<DialogHeader className="px-4 pb-2 pt-4">
<DialogTitle className="text-sm">New thread in…</DialogTitle>
</DialogHeader>
<div
className="flex flex-col gap-0.5 px-2 pb-3"
role="listbox"
aria-label="Choose a project for the new thread"
onKeyDown={(event) => {
if (
event.key !== "ArrowDown" &&
event.key !== "ArrowUp" &&
event.key !== "Home" &&
event.key !== "End"
) {
return;
}
const container = event.currentTarget;
const options = [...container.querySelectorAll<HTMLButtonElement>("button")];
if (options.length === 0) return;
const currentIndex = options.findIndex((option) => option === document.activeElement);
const nextIndex =
event.key === "Home"
? 0
: event.key === "End"
? options.length - 1
: event.key === "ArrowDown"
? (currentIndex + 1) % options.length
: (currentIndex - 1 + options.length) % options.length;
event.preventDefault();
options[nextIndex]?.focus();
}}
>
{newThreadPickerProjects.map((project, index) => {
const isDefault = index === 0 && newThreadTargetProject !== null;
return (
<button
key={`${project.environmentId}:${project.id}`}
type="button"
autoFocus={isDefault}
onClick={() => createThreadInProject(project.environmentId, project.id)}
className={cn(
"flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-left transition-colors",
"hover:bg-accent focus:bg-accent focus:outline-none",
isDefault && "bg-accent/50",
)}
>
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className="size-4"
/>
<span className="min-w-0 flex-1">
<span className="block truncate text-[13px] font-medium text-foreground">
{project.title}
</span>
<span className="block truncate font-mono text-[10px] text-muted-foreground/60">
{project.workspaceRoot}
</span>
</span>
{isDefault ? (
<Kbd className="h-4 shrink-0 rounded-sm px-1.5 text-[10px]">↵</Kbd>
) : null}
</button>
);
})}
<button
type="button"
onClick={() => {
setNewThreadPickerOpen(false);
openAddProjectCommandPalette();
}}
className="mt-1 flex items-center gap-2.5 rounded-lg border border-dashed border-border px-2.5 py-2 text-left text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent focus:text-foreground focus:outline-none"
>
<PlusIcon className="size-4" />
Add project
</button>
</div>
</DialogPopup>
</Dialog>
</>
);
}
@@ -1,9 +1,9 @@
import type { ScopedProjectRef } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { FolderPlusIcon } from "lucide-react";
import { useMemo } from "react";
import { useCallback, useMemo } from "react";
import { useOpenAddProjectCommandPalette } from "~/commandPaletteContext";
import { openCommandPalette } from "~/commandPaletteBus";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useProjects, useThreadShells } from "~/state/entities";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
@@ -29,7 +29,7 @@ export function DraftHeroHeadline({
const projects = useProjects();
const threads = useThreadShells();
const handleNewThread = useNewThreadHandler();
const openAddProject = useOpenAddProjectCommandPalette();
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
const orderedProjects = useMemo(
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
-14
View File
@@ -1,14 +0,0 @@
// Tiny event bus connecting the global chat.new shortcut (handled in the
// _chat route layout) to SidebarV2's project picker dialog. The route layer
// can't render the picker itself — it lives with the sidebar — and the
// sidebar can't own the window keydown handler without racing the layout's.
const NEW_THREAD_PICKER_EVENT = "t3code:open-new-thread-picker";
export function openNewThreadPicker(): void {
window.dispatchEvent(new CustomEvent(NEW_THREAD_PICKER_EVENT));
}
export function onOpenNewThreadPicker(listener: () => void): () => void {
window.addEventListener(NEW_THREAD_PICKER_EVENT, listener);
return () => window.removeEventListener(NEW_THREAD_PICKER_EVENT, listener);
}
+3 -3
View File
@@ -1,9 +1,9 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { createFileRoute, Link } from "@tanstack/react-router";
import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
import { openCommandPalette } from "../commandPaletteBus";
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
import { Button } from "../components/ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
@@ -105,7 +105,7 @@ function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {
}
function NoProjectsHero() {
const openAddProject = useOpenAddProjectCommandPalette();
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
+4 -4
View File
@@ -2,9 +2,9 @@ import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useAtomValue } from "@effect/atom-react";
import { useEffect } from "react";
import { isCommandPaletteOpen } from "../commandPaletteContext";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { useClientSettings } from "../hooks/useSettings";
import { openNewThreadPicker } from "../newThreadPickerBus";
import { openCommandPalette } from "../commandPaletteBus";
import { useProjects } from "../state/entities";
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
@@ -80,11 +80,11 @@ function ChatRouteGlobalShortcuts() {
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
// Sidebar v2 routes creation through its project picker whenever
// Sidebar v2 routes creation through the command palette whenever
// there is a real choice to make; v1 (and single-project setups)
// keep the immediate contextual create.
if (sidebarV2Enabled && projectCount > 1) {
openNewThreadPicker();
openCommandPalette({ open: "new-thread-in" });
return;
}
void startNewThreadFromContext({