TypeScript
refactor(web): chat route shortcuts register once instead of rebuilding on every store change (#25366)
Julius Marmingedd5b5401e1f2
diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsxindex b8fab6ce9ff..a8ecc16df3d 100644--- a/apps/web/src/appInit.tsx+++ b/apps/web/src/appInit.tsx@@ -42,6 +42,7 @@ import { startProviderAuthDelivery } from "./providerAuthDelivery";import { getRouter, type AppRouter } from "./router";import { appAtomRegistry } from "./rpc/atomRegistry";import { primaryServerConfigAtom } from "./state/server";+import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";import { resolveThreadRouteTarget } from "./threadRoutes";/** Writes appearance settings onto the document, touching only the groups that changed. */@@ -168,6 +169,7 @@ export function startAppServices(): AppRouter {if (isElectron) startElectronBrowserHost();startPreviewTitleRecording();startBrowserProfileReporting();+ installChatRouteCommands(router);startThreadOverlayRetention(router);startMainAppLocationTracking(router);startBackgroundThreadAnnouncements(appAtomRegistry, router);diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.tsindex 3a30af7e713..ac18db8d7c5 100644--- a/apps/web/src/hooks/useHandleNewThread.test.ts+++ b/apps/web/src/hooks/useHandleNewThread.test.ts@@ -213,7 +213,7 @@ vi.mock("../uiStateStore", () => ({legacyProjectCwdPreferenceKey: () => "remote-project",useUiStateStore: () => [],}));-vi.mock("./useSettings", () => ({ useClientSettings: () => ({}) }));+vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) }));import { useNewThreadHandler } from "./useHandleNewThread";diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.tsindex c89b4b73a4d..90a45540b24 100644--- a/apps/web/src/hooks/useHandleNewThread.ts+++ b/apps/web/src/hooks/useHandleNewThread.ts@@ -4,7 +4,7 @@ import {scopeThreadRef,} from "@t3tools/client-runtime/environment";import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts";-import { useRouter } from "@tanstack/react-router";+import { type AnyRouter, useRouter } from "@tanstack/react-router";import {composerDraftHasUserContent,markPromotedDraftThreadByRef,@@ -34,13 +34,14 @@ import {resolveNewDraftStartFromOrigin,resolveNewThreadModelSelectionOverride,} from "../lib/chatThreadActions";+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults";import { appAtomRegistry } from "../rpc/atomRegistry";import { environmentSummaries } from "../state/presentation";import { environmentServerConfigsAtom } from "../state/server";import { resolveThreadRouteTarget } from "../threadRoutes";import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";-import { useClientSettings } from "./useSettings";+import { getClientSettings } from "./useSettings";import { useThreadRouteTarget } from "./useThreadRouteTarget";import { readUnloadedThreadCount } from "../state/olderSettledShelf";@@ -61,8 +62,12 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef}export function useNewThreadHandler() {- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);- const router = useRouter();+ return createNewThreadHandler(useRouter());+}++export type NewThreadHandler = ReturnType<typeof createNewThreadHandler>;++export function createNewThreadHandler(router: AnyRouter) {const getCurrentRouteTarget = () => {const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};return resolveThreadRouteTarget(currentRouteParams);@@ -79,6 +84,7 @@ export function useNewThreadHandler() {},): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {const projects = readProjects();+ const projectGroupingSettings = selectProjectGroupingSettings(getClientSettings());// Read at call time; status pushes replace the config map and would recreate every sidebar handler.const environmentServerConfigs = appAtomRegistry.get(environmentServerConfigsAtom);const targetServerSettings =@@ -383,6 +389,22 @@ export function useNewThreadHandler() {};}+export function resolveDefaultProjectRef(+ projects: ReadonlyArray<EnvironmentProject>,+ projectOrder: readonly string[],+): ScopedProjectRef | null {+ const [defaultProject] = orderItemsByPreferredIds({+ items: projects,+ preferredIds: projectOrder,+ getId: getProjectOrderKey,+ getPreferenceIds: (project) => [+ getProjectOrderKey(project),+ legacyProjectCwdPreferenceKey(project.workspaceRoot),+ ],+ });+ return defaultProject ? scopeProjectRef(defaultProject.environmentId, defaultProject.id) : null;+}+export function useHandleNewThread() {const projectOrder = useUiStateStore((store) => store.projectOrder);const routeTarget = useThreadRouteTarget();@@ -399,18 +421,7 @@ export function useHandleNewThread() {);const projects = useProjects();const handleNewThread = useNewThreadHandler();- const [defaultProject] = orderItemsByPreferredIds({- items: projects,- preferredIds: projectOrder,- getId: getProjectOrderKey,- getPreferenceIds: (project) => [- getProjectOrderKey(project),- legacyProjectCwdPreferenceKey(project.workspaceRoot),- ],- });- const defaultProjectRef = defaultProject- ? scopeProjectRef(defaultProject.environmentId, defaultProject.id)- : null;+ const defaultProjectRef = resolveDefaultProjectRef(projects, projectOrder);return {activeDraftThread,diff --git a/apps/web/src/hooks/useScratchProject.ts b/apps/web/src/hooks/useScratchProject.tsindex 8b9991f9efc..936da409659 100644--- a/apps/web/src/hooks/useScratchProject.ts+++ b/apps/web/src/hooks/useScratchProject.ts@@ -1,17 +1,20 @@+import { RegistryContext } from "@effect/atom-react";import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";import {isAtomCommandInterrupted,+ runAtomCommand,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import type { EnvironmentId } from "@t3tools/contracts";+import type { AtomRegistry } from "effect/reactivity";+import { useContext } from "react";import { stackedThreadToast, toastManager } from "~/components/ui/toast";-import { useEnvironments } from "~/state/environments";+import { type EnvironmentPresentation, useEnvironments } from "~/state/environments";import { projectEnvironment } from "~/state/projects";-import { useAtomCommand } from "~/state/use-atom-command";-import { useNewThreadHandler } from "./useHandleNewThread";+import { type NewThreadHandler, useNewThreadHandler } from "./useHandleNewThread";function reportScratchFailure(title: string, error: unknown) {toastManager.add(@@ -23,19 +26,26 @@ function reportScratchFailure(title: string, error: unknown) {);}-export function useScratchProject() {- const { environments } = useEnvironments();- const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });- const handleNewThread = useNewThreadHandler();+type ScratchEnvironment = Pick<EnvironmentPresentation, "connection" | "serverConfig"> & {+ readonly environmentId: EnvironmentId;+};+export function createScratchProjectActions(input: {+ readonly environments: () => Iterable<ScratchEnvironment>;+ readonly registry: AtomRegistry.AtomRegistry;+ readonly handleNewThread: NewThreadHandler;+}) {const scratchWorkspaceRootFor = (environmentId: EnvironmentId | null): string | null => {- const environment = environments.find((entry) => entry.environmentId === environmentId);+ let environment: ScratchEnvironment | undefined;+ for (const entry of input.environments()) {+ if (entry.environmentId === environmentId) environment = entry;+ }return availableScratchWorkspaceRoot(environment?.connection.phase, environment?.serverConfig);};const scratchEnvironmentId = (current: EnvironmentId | null): EnvironmentId | null => {if (current !== null) return scratchWorkspaceRootFor(current) !== null ? current : null;- const offering = environments.filter(+ const offering = [...input.environments()].filter((entry) => scratchWorkspaceRootFor(entry.environmentId) !== null,);return offering.length === 1 ? (offering[0]?.environmentId ?? null) : null;@@ -45,7 +55,13 @@ export function useScratchProject() {environmentId: EnvironmentId,failureTitle = "Could not start without a project",): Promise<EnvironmentProject | null> => {- const result = await openScratch({ environmentId, input: {} });+ const command = projectEnvironment.openScratch;+ const result = await runAtomCommand(+ input.registry,+ command,+ { environmentId, input: {} },+ { label: command.label, reportFailure: false, reportDefect: true },+ );if (result._tag === "Success") return result.value;if (!isAtomCommandInterrupted(result)) {reportScratchFailure(failureTitle, squashAtomCommandFailure(result));@@ -56,11 +72,24 @@ export function useScratchProject() {const startScratchThread = async (environmentId: EnvironmentId) => {const project = await openScratchProject(environmentId);if (project) {- await handleNewThread(scopeProjectRef(project.environmentId, project.id)).catch(- (error: unknown) => reportScratchFailure("Could not start without a project", error),- );+ await input+ .handleNewThread(scopeProjectRef(project.environmentId, project.id))+ .catch((error: unknown) =>+ reportScratchFailure("Could not start without a project", error),+ );}};return { scratchWorkspaceRootFor, scratchEnvironmentId, openScratchProject, startScratchThread };}++export function useScratchProject() {+ const { environments } = useEnvironments();+ const registry = useContext(RegistryContext);+ const handleNewThread = useNewThreadHandler();+ return createScratchProjectActions({+ environments: () => environments,+ registry,+ handleNewThread,+ });+}diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsxindex d965760e827..8b5d7af3468 100644--- a/apps/web/src/routes/_chat.tsx+++ b/apps/web/src/routes/_chat.tsx@@ -1,203 +1,15 @@-import { AuthPreviewOperateScope } from "@t3tools/contracts";import { scopedThreadKey } from "@t3tools/client-runtime/environment";import { Outlet, createFileRoute, redirect, useMatches } from "@tanstack/react-router";-import { useAtomValue } from "@effect/atom-react";-import { useEffect, useState } from "react";+import { useState } from "react";-import { isCommandPaletteOpen } from "../commandPaletteBus";import { ThreadRouteView } from "../components/ThreadRouteView";import { isAppModalPage } from "../components/sidebar/mainAppLocation";import { SidebarInset } from "../components/ui/sidebar";import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../threadRoutes";import { retainThreadFindForRoute } from "../components/chat/threadFindStore";import { ThreadLinkPrompt } from "../components/promptLinks/ThreadLinkPrompt";-import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";-import { openCommandPalette } from "../commandPaletteBus";-import { useProjects } from "../state/entities";-import { isPreviewAvailableFor } from "../browser/previewRuntime";-import { usePrimaryEnvironmentId } from "../state/environments";-import { useEnvironmentScope } from "../state/session";-import { selectProjectGroupingSettings } from "../logicalProject";-import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";-import { dispatchPreviewAction } from "../components/preview/previewActionBus";-import { useHandleNewThread } from "../hooks/useHandleNewThread";-import { useScratchProject } from "../hooks/useScratchProject";-import { startNewThreadFromContext } from "../lib/chatThreadActions";-import { isPreviewFocused } from "../lib/previewFocus";-import { isTerminalFocused } from "../lib/terminalFocus";-import { isEditableFocused } from "../lib/editableFocus";-import { isModelPickerOpen } from "../modelPickerVisibility";-import { resolveShortcutCommand } from "../keybindings";-import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";-import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";-import { useThreadSelectionStore } from "../threadSelectionStore";-import { stackedThreadToast, toastManager } from "~/components/ui/toast";-import { primaryServerKeybindingsAtom } from "~/state/server";import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";-function ChatRouteGlobalShortcuts() {- const clearSelection = useThreadSelectionStore((state) => state.clearSelection);- const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);- const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =- useHandleNewThread();- const canOperatePreview = useEnvironmentScope(- routeThreadRef?.environmentId ?? null,- AuthPreviewOperateScope,- );- const keybindings = useAtomValue(primaryServerKeybindingsAtom);- const legacySidebarEnabled = useLegacySidebarEnabled();- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);- const projects = useProjects();- const primaryEnvironmentId = usePrimaryEnvironmentId();- const { scratchEnvironmentId, startScratchThread } = useScratchProject();- const projectGroupCount = buildSidebarProjectSnapshots({- projects,- settings: projectGroupingSettings,- primaryEnvironmentId,- resolveEnvironmentLabel: () => null,- }).length;- const terminalOpen = useTerminalUiStateStore((state) =>- routeThreadRef- ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen- : false,- );- // This flag is store-only; dispatch the action bus to reuse ChatView's URL-aware arbitration.- const previewOpen = useRightPanelStore((state) =>- routeThreadRef- ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"- : false,- );- useEffect(() => {- const onWindowKeyDown = (event: KeyboardEvent) => {- if (event.defaultPrevented) return;- const command = resolveShortcutCommand(event, keybindings, {- context: {- terminalFocus: isTerminalFocused(),- terminalOpen,- previewFocus: isPreviewFocused(),- previewOpen,- editableFocus: isEditableFocused(event.target),- modelPickerOpen: isModelPickerOpen(),- },- });-- if (isCommandPaletteOpen()) {- return;- }-- if (event.key === "Escape" && selectedThreadKeysSize > 0) {- event.preventDefault();- clearSelection();- return;- }-- if (command === "chat.newLocal") {- event.preventDefault();- event.stopPropagation();- void startNewThreadFromContext({- activeDraftThread,- activeThread: activeThread ?? undefined,- defaultProjectRef,- handleNewThread,- });- return;- }-- if (command === "chat.newWithoutProject") {- const environmentId = scratchEnvironmentId(- activeThread?.environmentId ?? activeDraftThread?.environmentId ?? primaryEnvironmentId,- );- if (environmentId === null) return;- event.preventDefault();- event.stopPropagation();- void startScratchThread(environmentId);- return;- }-- if (command === "chat.new") {- event.preventDefault();- event.stopPropagation();- if (!legacySidebarEnabled && projectGroupCount > 1) {- openCommandPalette({ open: "new-thread-in" });- return;- }- void startNewThreadFromContext({- activeDraftThread,- activeThread: activeThread ?? undefined,- defaultProjectRef,- handleNewThread,- });- return;- }-- if (command === "preview.toggle") {- event.preventDefault();- event.stopPropagation();- if (!routeThreadRef || (!canOperatePreview && !previewOpen)) return;- if (!isPreviewAvailableFor(routeThreadRef.environmentId)) {- toastManager.add(- stackedThreadToast({- type: "info",- title: "Preview is desktop-only",- description: "Open T3 Code in the desktop app to use the in-app preview.",- }),- );- return;- }- dispatchPreviewAction("toggle-panel");- return;- }-- if (- command === "preview.refresh" ||- command === "preview.focusUrl" ||- command === "preview.zoomIn" ||- command === "preview.zoomOut" ||- command === "preview.resetZoom"- ) {- event.preventDefault();- event.stopPropagation();- if (!canOperatePreview) return;- const action =- command === "preview.refresh"- ? "refresh"- : command === "preview.focusUrl"- ? "focus-url"- : command === "preview.zoomIn"- ? "zoom-in"- : command === "preview.zoomOut"- ? "zoom-out"- : "reset-zoom";- dispatchPreviewAction(action);- }- };-- window.addEventListener("keydown", onWindowKeyDown);- return () => {- window.removeEventListener("keydown", onWindowKeyDown);- };- }, [- activeDraftThread,- activeThread,- clearSelection,- canOperatePreview,- handleNewThread,- keybindings,- defaultProjectRef,- previewOpen,- primaryEnvironmentId,- projectGroupCount,- routeThreadRef,- scratchEnvironmentId,- selectedThreadKeysSize,- startScratchThread,- legacySidebarEnabled,- terminalOpen,- ]);-- return null;-}-function threadRouteTargetKey(target: ThreadRouteTarget | null) {if (!target) return null;return target.kind === "server" ? scopedThreadKey(target.threadRef) : target.draftId;@@ -218,7 +30,6 @@ function ChatRouteLayout() {const shownTarget = modalOpen ? backgroundTarget : threadTarget;return (<>- {modalOpen ? null : <ChatRouteGlobalShortcuts />}{shownTarget?.kind === "server" && !modalOpen ? (<ThreadLinkPrompt threadRef={shownTarget.threadRef} />) : null}diff --git a/apps/web/src/shortcuts/chatRouteCommands.browser.test.ts b/apps/web/src/shortcuts/chatRouteCommands.browser.test.tsnew file mode 100644index 00000000000..66cf7ee413a--- /dev/null+++ b/apps/web/src/shortcuts/chatRouteCommands.browser.test.ts@@ -0,0 +1,67 @@+import type { AnyRouter } from "@tanstack/react-router";+import { describe, expect, it } from "vite-plus/test";++import { useThreadSelectionStore } from "../threadSelectionStore";+import { installChatRouteCommands } from "./chatRouteCommands";++type Match = { readonly routeId: string; readonly pathname: string };++function routerAt(matches: Match[]) {+ const state = { matches: matches.map((match) => ({ ...match, params: {} })) };+ return {+ router: { state } as unknown as AnyRouter,+ navigate: (next: Match[]) => {+ state.matches = next.map((match) => ({ ...match, params: {} }));+ },+ };+}++const CHAT: Match[] = [+ { routeId: "__root__", pathname: "/" },+ { routeId: "/_chat", pathname: "/" },+];++function pressEscape(): KeyboardEvent {+ const event = new KeyboardEvent("keydown", { key: "Escape", cancelable: true, bubbles: true });+ window.dispatchEvent(event);+ return event;+}++function selectThread(threadKey: string) {+ useThreadSelectionStore.getState().clearSelection();+ useThreadSelectionStore.getState().toggleThread(threadKey);+}++describe("chat route commands", () => {+ it("clears a selection made after install, reading the store at keypress time", () => {+ const { router } = routerAt(CHAT);+ using stack = new DisposableStack();+ stack.defer(installChatRouteCommands(router));+ stack.defer(() => useThreadSelectionStore.getState().clearSelection());++ selectThread("env:thread-1");+ const event = pressEscape();++ expect(event.defaultPrevented).toBe(true);+ expect(useThreadSelectionStore.getState().selectedThreadKeys.size).toBe(0);+ // With nothing selected, Escape is left for other handlers.+ expect(pressEscape().defaultPrevented).toBe(false);+ });++ it("stays out of the way off the chat route and under modal pages", () => {+ const { router, navigate } = routerAt([{ routeId: "__root__", pathname: "/pair" }]);+ using stack = new DisposableStack();+ stack.defer(installChatRouteCommands(router));+ stack.defer(() => useThreadSelectionStore.getState().clearSelection());+ selectThread("env:thread-1");++ expect(pressEscape().defaultPrevented).toBe(false);++ navigate([...CHAT, { routeId: "/_chat/settings", pathname: "/settings" }]);+ expect(pressEscape().defaultPrevented).toBe(false);+ expect(useThreadSelectionStore.getState().selectedThreadKeys.size).toBe(1);++ navigate(CHAT);+ expect(pressEscape().defaultPrevented).toBe(true);+ });+});diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.tsnew file mode 100644index 00000000000..40a6b0e006c--- /dev/null+++ b/apps/web/src/shortcuts/chatRouteCommands.ts@@ -0,0 +1,179 @@+import { AuthPreviewOperateScope, type EnvironmentId } from "@t3tools/contracts";+import type { AnyRouter } from "@tanstack/react-router";++import { stackedThreadToast, toastManager } from "~/components/ui/toast";+import { isPreviewAvailableFor } from "../browser/previewRuntime";+import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";+import { useComposerDraftStore } from "../composerDraftStore";+import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";+import { isAppModalPage } from "../components/sidebar/mainAppLocation";+import { createNewThreadHandler, resolveDefaultProjectRef } from "../hooks/useHandleNewThread";+import { createScratchProjectActions } from "../hooks/useScratchProject";+import { getClientSettings } from "../hooks/useSettings";+import { startNewThreadFromContext } from "../lib/chatThreadActions";+import { selectProjectGroupingSettings } from "../logicalProject";+import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";+import { readProjects, readThreadShell } from "../state/entities";+import { environmentPresentations } from "../state/presentation";+import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";+import { readEnvironmentScope } from "../state/session";+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";+import { useThreadSelectionStore } from "../threadSelectionStore";+import { resolveThreadRouteTarget } from "../threadRoutes";+import { useUiStateStore } from "../uiStateStore";+import { type CommandHandler, registerCommands } from "./dispatcher";++const CHAT_ROUTE_ID = "/_chat";++/**+ * New-thread and preview commands, live while a chat route is showing and no+ * modal page (Settings, Usage) covers it. Everything is read at event time, so+ * the scope is registered once instead of re-registering on every store change.+ */+export function installChatRouteCommands(router: AnyRouter): () => void {+ const handleNewThread = createNewThreadHandler(router);+ const scratch = createScratchProjectActions({+ environments: () =>+ [...appAtomRegistry.get(environmentPresentations.presentationsAtom)].map(+ ([environmentId, presentation]) => ({ ...presentation, environmentId }),+ ),+ registry: appAtomRegistry,+ handleNewThread,+ });++ const readRouteTarget = () => resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});+ const readRouteThreadRef = () => {+ const target = readRouteTarget();+ return target?.kind === "server" ? target.threadRef : null;+ };+ const readPreviewOpen = () => {+ const threadRef = readRouteThreadRef();+ // Store-only on purpose: the URL-aware arbitration lives in ChatView's+ // preview toggle, which the action bus reaches.+ return threadRef+ ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) === "preview"+ : false;+ };+ const readThreadContext = () => {+ const target = readRouteTarget();+ const drafts = useComposerDraftStore.getState();+ const activeThread = target?.kind === "server" ? readThreadShell(target.threadRef) : null;+ const activeDraftThread = target+ ? target.kind === "server"+ ? drafts.getDraftThread(target.threadRef)+ : drafts.getDraftSession(target.draftId)+ : null;+ return {+ activeDraftThread,+ activeThread: activeThread ?? undefined,+ defaultProjectRef: resolveDefaultProjectRef(+ readProjects(),+ useUiStateStore.getState().projectOrder,+ ),+ handleNewThread,+ };+ };+ const readProjectGroupCount = () =>+ buildSidebarProjectSnapshots({+ projects: readProjects(),+ settings: selectProjectGroupingSettings(getClientSettings()),+ primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom),+ resolveEnvironmentLabel: () => null,+ }).length;+ const canOperatePreview = (environmentId: EnvironmentId) =>+ readEnvironmentScope(environmentId, AuthPreviewOperateScope);++ const claim = (event: KeyboardEvent) => {+ event.preventDefault();+ event.stopPropagation();+ };++ const startNewLocal: CommandHandler = (event) => {+ claim(event);+ void startNewThreadFromContext(readThreadContext());+ };++ const previewCommand =+ (action: PreviewAction): CommandHandler =>+ (event) => {+ claim(event);+ const threadRef = readRouteThreadRef();+ if (threadRef && canOperatePreview(threadRef.environmentId)) dispatchPreviewAction(action);+ };++ return registerCommands(+ {+ "chat.newLocal": startNewLocal,+ "chat.newWithoutProject": (event) => {+ const { activeThread, activeDraftThread } = readThreadContext();+ const environmentId = scratch.scratchEnvironmentId(+ activeThread?.environmentId ??+ activeDraftThread?.environmentId ??+ appAtomRegistry.get(primaryEnvironmentIdAtom),+ );+ if (environmentId === null) return;+ claim(event);+ void scratch.startScratchThread(environmentId);+ },+ "chat.new": (event) => {+ // Pre-hydration settings are the defaults, where the legacy sidebar is off.+ if (!getClientSettings().legacySidebarEnabled && readProjectGroupCount() > 1) {+ claim(event);+ openCommandPalette({ open: "new-thread-in" });+ return;+ }+ startNewLocal(event);+ },+ "preview.toggle": (event) => {+ claim(event);+ const threadRef = readRouteThreadRef();+ if (!threadRef || (!canOperatePreview(threadRef.environmentId) && !readPreviewOpen())) {+ return;+ }+ if (!isPreviewAvailableFor(threadRef.environmentId)) {+ toastManager.add(+ stackedThreadToast({+ type: "info",+ title: "Preview is desktop-only",+ description: "Open T3 Code in the desktop app to use the in-app preview.",+ }),+ );+ return;+ }+ dispatchPreviewAction("toggle-panel");+ },+ "preview.refresh": previewCommand("refresh"),+ "preview.focusUrl": previewCommand("focus-url"),+ "preview.zoomIn": previewCommand("zoom-in"),+ "preview.zoomOut": previewCommand("zoom-out"),+ "preview.resetZoom": previewCommand("reset-zoom"),+ },+ {+ when: () =>+ router.state.matches.some((match) => match.routeId === CHAT_ROUTE_ID) &&+ !router.state.matches.some((match) => isAppModalPage(match.pathname)) &&+ !isCommandPaletteOpen(),+ context: () => {+ const threadRef = readRouteThreadRef();+ return {+ terminalOpen: threadRef+ ? selectThreadTerminalUiState(+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,+ threadRef,+ ).terminalOpen+ : false,+ previewOpen: readPreviewOpen(),+ };+ },+ onKeyDown: (event) => {+ if (event.key !== "Escape") return false;+ const selection = useThreadSelectionStore.getState();+ if (selection.selectedThreadKeys.size === 0) return false;+ event.preventDefault();+ selection.clearSelection();+ },+ },+ );+}