The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): chat route shortcuts register once instead of rebuilding on every store change (#25366)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 13:11 UTC
dd5b5401e1f240f4314af29edf431369d182f386
7 files changed
+319
-220
apps/web/src/appInit.tsx
+2
@@ -42,6 +42,7 @@ import { startProviderAuthDelivery } from "./providerAuthDelivery";
42
import { getRouter, type AppRouter } from "./router";
43
import { appAtomRegistry } from "./rpc/atomRegistry";
44
import { primaryServerConfigAtom } from "./state/server";
45
+import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
46
import { resolveThreadRouteTarget } from "./threadRoutes";
47
48
/** Writes appearance settings onto the document, touching only the groups that changed. */
@@ -168,6 +169,7 @@ export function startAppServices(): AppRouter {
169
if (isElectron) startElectronBrowserHost();
170
startPreviewTitleRecording();
171
startBrowserProfileReporting();
172
+ installChatRouteCommands(router);
173
startThreadOverlayRetention(router);
174
startMainAppLocationTracking(router);
175
startBackgroundThreadAnnouncements(appAtomRegistry, router);
apps/web/src/hooks/useHandleNewThread.test.ts
+1
-1
@@ -213,7 +213,7 @@ vi.mock("../uiStateStore", () => ({
213
legacyProjectCwdPreferenceKey: () => "remote-project",
214
useUiStateStore: () => [],
215
}));
216
-vi.mock("./useSettings", () => ({ useClientSettings: () => ({}) }));
216
+vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) }));
217
218
import { useNewThreadHandler } from "./useHandleNewThread";
219
apps/web/src/hooks/useHandleNewThread.ts
+27
-16
@@ -4,7 +4,7 @@ import {
4
scopeThreadRef,
5
} from "@t3tools/client-runtime/environment";
6
import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts";
7
-import { useRouter } from "@tanstack/react-router";
7
+import { type AnyRouter, useRouter } from "@tanstack/react-router";
8
import {
9
composerDraftHasUserContent,
10
markPromotedDraftThreadByRef,
@@ -34,13 +34,14 @@ import {
34
resolveNewDraftStartFromOrigin,
35
resolveNewThreadModelSelectionOverride,
36
} from "../lib/chatThreadActions";
37
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
38
import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults";
39
import { appAtomRegistry } from "../rpc/atomRegistry";
40
import { environmentSummaries } from "../state/presentation";
41
import { environmentServerConfigsAtom } from "../state/server";
42
import { resolveThreadRouteTarget } from "../threadRoutes";
43
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
43
-import { useClientSettings } from "./useSettings";
44
+import { getClientSettings } from "./useSettings";
45
import { useThreadRouteTarget } from "./useThreadRouteTarget";
46
import { readUnloadedThreadCount } from "../state/olderSettledShelf";
47
@@ -61,8 +62,12 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
62
}
63
64
export function useNewThreadHandler() {
64
- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
65
- const router = useRouter();
65
+ return createNewThreadHandler(useRouter());
66
+}
67
+
68
+export type NewThreadHandler = ReturnType<typeof createNewThreadHandler>;
69
+
70
+export function createNewThreadHandler(router: AnyRouter) {
71
const getCurrentRouteTarget = () => {
72
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
73
return resolveThreadRouteTarget(currentRouteParams);
@@ -79,6 +84,7 @@ export function useNewThreadHandler() {
84
},
85
): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
86
const projects = readProjects();
87
+ const projectGroupingSettings = selectProjectGroupingSettings(getClientSettings());
88
// Read at call time; status pushes replace the config map and would recreate every sidebar handler.
89
const environmentServerConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
90
const targetServerSettings =
@@ -383,6 +389,22 @@ export function useNewThreadHandler() {
389
};
390
}
391
392
+export function resolveDefaultProjectRef(
393
+ projects: ReadonlyArray<EnvironmentProject>,
394
+ projectOrder: readonly string[],
395
+): ScopedProjectRef | null {
396
+ const [defaultProject] = orderItemsByPreferredIds({
397
+ items: projects,
398
+ preferredIds: projectOrder,
399
+ getId: getProjectOrderKey,
400
+ getPreferenceIds: (project) => [
401
+ getProjectOrderKey(project),
402
+ legacyProjectCwdPreferenceKey(project.workspaceRoot),
403
+ ],
404
+ });
405
+ return defaultProject ? scopeProjectRef(defaultProject.environmentId, defaultProject.id) : null;
406
+}
407
+
408
export function useHandleNewThread() {
409
const projectOrder = useUiStateStore((store) => store.projectOrder);
410
const routeTarget = useThreadRouteTarget();
@@ -399,18 +421,7 @@ export function useHandleNewThread() {
421
);
422
const projects = useProjects();
423
const handleNewThread = useNewThreadHandler();
402
- const [defaultProject] = orderItemsByPreferredIds({
403
- items: projects,
404
- preferredIds: projectOrder,
405
- getId: getProjectOrderKey,
406
- getPreferenceIds: (project) => [
407
- getProjectOrderKey(project),
408
- legacyProjectCwdPreferenceKey(project.workspaceRoot),
409
- ],
410
- });
411
- const defaultProjectRef = defaultProject
412
- ? scopeProjectRef(defaultProject.environmentId, defaultProject.id)
413
- : null;
424
+ const defaultProjectRef = resolveDefaultProjectRef(projects, projectOrder);
425
426
return {
427
activeDraftThread,
apps/web/src/hooks/useScratchProject.ts
+42
-13
@@ -1,17 +1,20 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3
import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
4
import {
5
isAtomCommandInterrupted,
6
+ runAtomCommand,
7
squashAtomCommandFailure,
8
} from "@t3tools/client-runtime/state/runtime";
9
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
10
import type { EnvironmentId } from "@t3tools/contracts";
11
+import type { AtomRegistry } from "effect/reactivity";
12
+import { useContext } from "react";
13
14
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
11
-import { useEnvironments } from "~/state/environments";
15
+import { type EnvironmentPresentation, useEnvironments } from "~/state/environments";
16
import { projectEnvironment } from "~/state/projects";
13
-import { useAtomCommand } from "~/state/use-atom-command";
14
-import { useNewThreadHandler } from "./useHandleNewThread";
17
+import { type NewThreadHandler, useNewThreadHandler } from "./useHandleNewThread";
18
19
function reportScratchFailure(title: string, error: unknown) {
20
toastManager.add(
@@ -23,19 +26,26 @@ function reportScratchFailure(title: string, error: unknown) {
26
);
27
}
28
26
-export function useScratchProject() {
27
- const { environments } = useEnvironments();
28
- const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
29
- const handleNewThread = useNewThreadHandler();
29
+type ScratchEnvironment = Pick<EnvironmentPresentation, "connection" | "serverConfig"> & {
30
+ readonly environmentId: EnvironmentId;
31
+};
32
33
+export function createScratchProjectActions(input: {
34
+ readonly environments: () => Iterable<ScratchEnvironment>;
35
+ readonly registry: AtomRegistry.AtomRegistry;
36
+ readonly handleNewThread: NewThreadHandler;
37
+}) {
38
const scratchWorkspaceRootFor = (environmentId: EnvironmentId | null): string | null => {
32
- const environment = environments.find((entry) => entry.environmentId === environmentId);
39
+ let environment: ScratchEnvironment | undefined;
40
+ for (const entry of input.environments()) {
41
+ if (entry.environmentId === environmentId) environment = entry;
42
+ }
43
return availableScratchWorkspaceRoot(environment?.connection.phase, environment?.serverConfig);
44
};
45
46
const scratchEnvironmentId = (current: EnvironmentId | null): EnvironmentId | null => {
47
if (current !== null) return scratchWorkspaceRootFor(current) !== null ? current : null;
38
- const offering = environments.filter(
48
+ const offering = [...input.environments()].filter(
49
(entry) => scratchWorkspaceRootFor(entry.environmentId) !== null,
50
);
51
return offering.length === 1 ? (offering[0]?.environmentId ?? null) : null;
@@ -45,7 +55,13 @@ export function useScratchProject() {
55
environmentId: EnvironmentId,
56
failureTitle = "Could not start without a project",
57
): Promise<EnvironmentProject | null> => {
48
- const result = await openScratch({ environmentId, input: {} });
58
+ const command = projectEnvironment.openScratch;
59
+ const result = await runAtomCommand(
60
+ input.registry,
61
+ command,
62
+ { environmentId, input: {} },
63
+ { label: command.label, reportFailure: false, reportDefect: true },
64
+ );
65
if (result._tag === "Success") return result.value;
66
if (!isAtomCommandInterrupted(result)) {
67
reportScratchFailure(failureTitle, squashAtomCommandFailure(result));
@@ -56,11 +72,24 @@ export function useScratchProject() {
72
const startScratchThread = async (environmentId: EnvironmentId) => {
73
const project = await openScratchProject(environmentId);
74
if (project) {
59
- await handleNewThread(scopeProjectRef(project.environmentId, project.id)).catch(
60
- (error: unknown) => reportScratchFailure("Could not start without a project", error),
61
- );
75
+ await input
76
+ .handleNewThread(scopeProjectRef(project.environmentId, project.id))
77
+ .catch((error: unknown) =>
78
+ reportScratchFailure("Could not start without a project", error),
79
+ );
80
}
81
};
82
83
return { scratchWorkspaceRootFor, scratchEnvironmentId, openScratchProject, startScratchThread };
84
}
85
+
86
+export function useScratchProject() {
87
+ const { environments } = useEnvironments();
88
+ const registry = useContext(RegistryContext);
89
+ const handleNewThread = useNewThreadHandler();
90
+ return createScratchProjectActions({
91
+ environments: () => environments,
92
+ registry,
93
+ handleNewThread,
94
+ });
95
+}
apps/web/src/routes/_chat.tsx
+1
-190
@@ -1,203 +1,15 @@
1
-import { AuthPreviewOperateScope } from "@t3tools/contracts";
1
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2
import { Outlet, createFileRoute, redirect, useMatches } from "@tanstack/react-router";
4
-import { useAtomValue } from "@effect/atom-react";
5
-import { useEffect, useState } from "react";
3
+import { useState } from "react";
4
7
-import { isCommandPaletteOpen } from "../commandPaletteBus";
5
import { ThreadRouteView } from "../components/ThreadRouteView";
6
import { isAppModalPage } from "../components/sidebar/mainAppLocation";
7
import { SidebarInset } from "../components/ui/sidebar";
8
import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../threadRoutes";
9
import { retainThreadFindForRoute } from "../components/chat/threadFindStore";
10
import { ThreadLinkPrompt } from "../components/promptLinks/ThreadLinkPrompt";
14
-import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";
15
-import { openCommandPalette } from "../commandPaletteBus";
16
-import { useProjects } from "../state/entities";
17
-import { isPreviewAvailableFor } from "../browser/previewRuntime";
18
-import { usePrimaryEnvironmentId } from "../state/environments";
19
-import { useEnvironmentScope } from "../state/session";
20
-import { selectProjectGroupingSettings } from "../logicalProject";
21
-import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
22
-import { dispatchPreviewAction } from "../components/preview/previewActionBus";
23
-import { useHandleNewThread } from "../hooks/useHandleNewThread";
24
-import { useScratchProject } from "../hooks/useScratchProject";
25
-import { startNewThreadFromContext } from "../lib/chatThreadActions";
26
-import { isPreviewFocused } from "../lib/previewFocus";
27
-import { isTerminalFocused } from "../lib/terminalFocus";
28
-import { isEditableFocused } from "../lib/editableFocus";
29
-import { isModelPickerOpen } from "../modelPickerVisibility";
30
-import { resolveShortcutCommand } from "../keybindings";
31
-import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
32
-import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
33
-import { useThreadSelectionStore } from "../threadSelectionStore";
34
-import { stackedThreadToast, toastManager } from "~/components/ui/toast";
35
-import { primaryServerKeybindingsAtom } from "~/state/server";
11
import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
12
38
-function ChatRouteGlobalShortcuts() {
39
- const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
40
- const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
41
- const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
42
- useHandleNewThread();
43
- const canOperatePreview = useEnvironmentScope(
44
- routeThreadRef?.environmentId ?? null,
45
- AuthPreviewOperateScope,
46
- );
47
- const keybindings = useAtomValue(primaryServerKeybindingsAtom);
48
- const legacySidebarEnabled = useLegacySidebarEnabled();
49
- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
50
- const projects = useProjects();
51
- const primaryEnvironmentId = usePrimaryEnvironmentId();
52
- const { scratchEnvironmentId, startScratchThread } = useScratchProject();
53
- const projectGroupCount = buildSidebarProjectSnapshots({
54
- projects,
55
- settings: projectGroupingSettings,
56
- primaryEnvironmentId,
57
- resolveEnvironmentLabel: () => null,
58
- }).length;
59
- const terminalOpen = useTerminalUiStateStore((state) =>
60
- routeThreadRef
61
- ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
62
- : false,
63
- );
64
- // This flag is store-only; dispatch the action bus to reuse ChatView's URL-aware arbitration.
65
- const previewOpen = useRightPanelStore((state) =>
66
- routeThreadRef
67
- ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
68
- : false,
69
- );
70
- useEffect(() => {
71
- const onWindowKeyDown = (event: KeyboardEvent) => {
72
- if (event.defaultPrevented) return;
73
- const command = resolveShortcutCommand(event, keybindings, {
74
- context: {
75
- terminalFocus: isTerminalFocused(),
76
- terminalOpen,
77
- previewFocus: isPreviewFocused(),
78
- previewOpen,
79
- editableFocus: isEditableFocused(event.target),
80
- modelPickerOpen: isModelPickerOpen(),
81
- },
82
- });
83
-
84
- if (isCommandPaletteOpen()) {
85
- return;
86
- }
87
-
88
- if (event.key === "Escape" && selectedThreadKeysSize > 0) {
89
- event.preventDefault();
90
- clearSelection();
91
- return;
92
- }
93
-
94
- if (command === "chat.newLocal") {
95
- event.preventDefault();
96
- event.stopPropagation();
97
- void startNewThreadFromContext({
98
- activeDraftThread,
99
- activeThread: activeThread ?? undefined,
100
- defaultProjectRef,
101
- handleNewThread,
102
- });
103
- return;
104
- }
105
-
106
- if (command === "chat.newWithoutProject") {
107
- const environmentId = scratchEnvironmentId(
108
- activeThread?.environmentId ?? activeDraftThread?.environmentId ?? primaryEnvironmentId,
109
- );
110
- if (environmentId === null) return;
111
- event.preventDefault();
112
- event.stopPropagation();
113
- void startScratchThread(environmentId);
114
- return;
115
- }
116
-
117
- if (command === "chat.new") {
118
- event.preventDefault();
119
- event.stopPropagation();
120
- if (!legacySidebarEnabled && projectGroupCount > 1) {
121
- openCommandPalette({ open: "new-thread-in" });
122
- return;
123
- }
124
- void startNewThreadFromContext({
125
- activeDraftThread,
126
- activeThread: activeThread ?? undefined,
127
- defaultProjectRef,
128
- handleNewThread,
129
- });
130
- return;
131
- }
132
-
133
- if (command === "preview.toggle") {
134
- event.preventDefault();
135
- event.stopPropagation();
136
- if (!routeThreadRef || (!canOperatePreview && !previewOpen)) return;
137
- if (!isPreviewAvailableFor(routeThreadRef.environmentId)) {
138
- toastManager.add(
139
- stackedThreadToast({
140
- type: "info",
141
- title: "Preview is desktop-only",
142
- description: "Open T3 Code in the desktop app to use the in-app preview.",
143
- }),
144
- );
145
- return;
146
- }
147
- dispatchPreviewAction("toggle-panel");
148
- return;
149
- }
150
-
151
- if (
152
- command === "preview.refresh" ||
153
- command === "preview.focusUrl" ||
154
- command === "preview.zoomIn" ||
155
- command === "preview.zoomOut" ||
156
- command === "preview.resetZoom"
157
- ) {
158
- event.preventDefault();
159
- event.stopPropagation();
160
- if (!canOperatePreview) return;
161
- const action =
162
- command === "preview.refresh"
163
- ? "refresh"
164
- : command === "preview.focusUrl"
165
- ? "focus-url"
166
- : command === "preview.zoomIn"
167
- ? "zoom-in"
168
- : command === "preview.zoomOut"
169
- ? "zoom-out"
170
- : "reset-zoom";
171
- dispatchPreviewAction(action);
172
- }
173
- };
174
-
175
- window.addEventListener("keydown", onWindowKeyDown);
176
- return () => {
177
- window.removeEventListener("keydown", onWindowKeyDown);
178
- };
179
- }, [
180
- activeDraftThread,
181
- activeThread,
182
- clearSelection,
183
- canOperatePreview,
184
- handleNewThread,
185
- keybindings,
186
- defaultProjectRef,
187
- previewOpen,
188
- primaryEnvironmentId,
189
- projectGroupCount,
190
- routeThreadRef,
191
- scratchEnvironmentId,
192
- selectedThreadKeysSize,
193
- startScratchThread,
194
- legacySidebarEnabled,
195
- terminalOpen,
196
- ]);
197
-
198
- return null;
199
-}
200
-
13
function threadRouteTargetKey(target: ThreadRouteTarget | null) {
14
if (!target) return null;
15
return target.kind === "server" ? scopedThreadKey(target.threadRef) : target.draftId;
@@ -218,7 +30,6 @@ function ChatRouteLayout() {
30
const shownTarget = modalOpen ? backgroundTarget : threadTarget;
31
return (
32
<>
221
- {modalOpen ? null : <ChatRouteGlobalShortcuts />}
33
{shownTarget?.kind === "server" && !modalOpen ? (
34
<ThreadLinkPrompt threadRef={shownTarget.threadRef} />
35
) : null}
apps/web/src/shortcuts/chatRouteCommands.browser.test.ts
new
+67
@@ -0,0 +1,67 @@
1
+import type { AnyRouter } from "@tanstack/react-router";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { useThreadSelectionStore } from "../threadSelectionStore";
5
+import { installChatRouteCommands } from "./chatRouteCommands";
6
+
7
+type Match = { readonly routeId: string; readonly pathname: string };
8
+
9
+function routerAt(matches: Match[]) {
10
+ const state = { matches: matches.map((match) => ({ ...match, params: {} })) };
11
+ return {
12
+ router: { state } as unknown as AnyRouter,
13
+ navigate: (next: Match[]) => {
14
+ state.matches = next.map((match) => ({ ...match, params: {} }));
15
+ },
16
+ };
17
+}
18
+
19
+const CHAT: Match[] = [
20
+ { routeId: "__root__", pathname: "/" },
21
+ { routeId: "/_chat", pathname: "/" },
22
+];
23
+
24
+function pressEscape(): KeyboardEvent {
25
+ const event = new KeyboardEvent("keydown", { key: "Escape", cancelable: true, bubbles: true });
26
+ window.dispatchEvent(event);
27
+ return event;
28
+}
29
+
30
+function selectThread(threadKey: string) {
31
+ useThreadSelectionStore.getState().clearSelection();
32
+ useThreadSelectionStore.getState().toggleThread(threadKey);
33
+}
34
+
35
+describe("chat route commands", () => {
36
+ it("clears a selection made after install, reading the store at keypress time", () => {
37
+ const { router } = routerAt(CHAT);
38
+ using stack = new DisposableStack();
39
+ stack.defer(installChatRouteCommands(router));
40
+ stack.defer(() => useThreadSelectionStore.getState().clearSelection());
41
+
42
+ selectThread("env:thread-1");
43
+ const event = pressEscape();
44
+
45
+ expect(event.defaultPrevented).toBe(true);
46
+ expect(useThreadSelectionStore.getState().selectedThreadKeys.size).toBe(0);
47
+ // With nothing selected, Escape is left for other handlers.
48
+ expect(pressEscape().defaultPrevented).toBe(false);
49
+ });
50
+
51
+ it("stays out of the way off the chat route and under modal pages", () => {
52
+ const { router, navigate } = routerAt([{ routeId: "__root__", pathname: "/pair" }]);
53
+ using stack = new DisposableStack();
54
+ stack.defer(installChatRouteCommands(router));
55
+ stack.defer(() => useThreadSelectionStore.getState().clearSelection());
56
+ selectThread("env:thread-1");
57
+
58
+ expect(pressEscape().defaultPrevented).toBe(false);
59
+
60
+ navigate([...CHAT, { routeId: "/_chat/settings", pathname: "/settings" }]);
61
+ expect(pressEscape().defaultPrevented).toBe(false);
62
+ expect(useThreadSelectionStore.getState().selectedThreadKeys.size).toBe(1);
63
+
64
+ navigate(CHAT);
65
+ expect(pressEscape().defaultPrevented).toBe(true);
66
+ });
67
+});
apps/web/src/shortcuts/chatRouteCommands.ts
new
+179
@@ -0,0 +1,179 @@
1
+import { AuthPreviewOperateScope, type EnvironmentId } from "@t3tools/contracts";
2
+import type { AnyRouter } from "@tanstack/react-router";
3
+
4
+import { stackedThreadToast, toastManager } from "~/components/ui/toast";
5
+import { isPreviewAvailableFor } from "../browser/previewRuntime";
6
+import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
7
+import { useComposerDraftStore } from "../composerDraftStore";
8
+import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";
9
+import { isAppModalPage } from "../components/sidebar/mainAppLocation";
10
+import { createNewThreadHandler, resolveDefaultProjectRef } from "../hooks/useHandleNewThread";
11
+import { createScratchProjectActions } from "../hooks/useScratchProject";
12
+import { getClientSettings } from "../hooks/useSettings";
13
+import { startNewThreadFromContext } from "../lib/chatThreadActions";
14
+import { selectProjectGroupingSettings } from "../logicalProject";
15
+import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
16
+import { appAtomRegistry } from "../rpc/atomRegistry";
17
+import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
18
+import { readProjects, readThreadShell } from "../state/entities";
19
+import { environmentPresentations } from "../state/presentation";
20
+import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
21
+import { readEnvironmentScope } from "../state/session";
22
+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
23
+import { useThreadSelectionStore } from "../threadSelectionStore";
24
+import { resolveThreadRouteTarget } from "../threadRoutes";
25
+import { useUiStateStore } from "../uiStateStore";
26
+import { type CommandHandler, registerCommands } from "./dispatcher";
27
+
28
+const CHAT_ROUTE_ID = "/_chat";
29
+
30
+/**
31
+ * New-thread and preview commands, live while a chat route is showing and no
32
+ * modal page (Settings, Usage) covers it. Everything is read at event time, so
33
+ * the scope is registered once instead of re-registering on every store change.
34
+ */
35
+export function installChatRouteCommands(router: AnyRouter): () => void {
36
+ const handleNewThread = createNewThreadHandler(router);
37
+ const scratch = createScratchProjectActions({
38
+ environments: () =>
39
+ [...appAtomRegistry.get(environmentPresentations.presentationsAtom)].map(
40
+ ([environmentId, presentation]) => ({ ...presentation, environmentId }),
41
+ ),
42
+ registry: appAtomRegistry,
43
+ handleNewThread,
44
+ });
45
+
46
+ const readRouteTarget = () => resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
47
+ const readRouteThreadRef = () => {
48
+ const target = readRouteTarget();
49
+ return target?.kind === "server" ? target.threadRef : null;
50
+ };
51
+ const readPreviewOpen = () => {
52
+ const threadRef = readRouteThreadRef();
53
+ // Store-only on purpose: the URL-aware arbitration lives in ChatView's
54
+ // preview toggle, which the action bus reaches.
55
+ return threadRef
56
+ ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) === "preview"
57
+ : false;
58
+ };
59
+ const readThreadContext = () => {
60
+ const target = readRouteTarget();
61
+ const drafts = useComposerDraftStore.getState();
62
+ const activeThread = target?.kind === "server" ? readThreadShell(target.threadRef) : null;
63
+ const activeDraftThread = target
64
+ ? target.kind === "server"
65
+ ? drafts.getDraftThread(target.threadRef)
66
+ : drafts.getDraftSession(target.draftId)
67
+ : null;
68
+ return {
69
+ activeDraftThread,
70
+ activeThread: activeThread ?? undefined,
71
+ defaultProjectRef: resolveDefaultProjectRef(
72
+ readProjects(),
73
+ useUiStateStore.getState().projectOrder,
74
+ ),
75
+ handleNewThread,
76
+ };
77
+ };
78
+ const readProjectGroupCount = () =>
79
+ buildSidebarProjectSnapshots({
80
+ projects: readProjects(),
81
+ settings: selectProjectGroupingSettings(getClientSettings()),
82
+ primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom),
83
+ resolveEnvironmentLabel: () => null,
84
+ }).length;
85
+ const canOperatePreview = (environmentId: EnvironmentId) =>
86
+ readEnvironmentScope(environmentId, AuthPreviewOperateScope);
87
+
88
+ const claim = (event: KeyboardEvent) => {
89
+ event.preventDefault();
90
+ event.stopPropagation();
91
+ };
92
+
93
+ const startNewLocal: CommandHandler = (event) => {
94
+ claim(event);
95
+ void startNewThreadFromContext(readThreadContext());
96
+ };
97
+
98
+ const previewCommand =
99
+ (action: PreviewAction): CommandHandler =>
100
+ (event) => {
101
+ claim(event);
102
+ const threadRef = readRouteThreadRef();
103
+ if (threadRef && canOperatePreview(threadRef.environmentId)) dispatchPreviewAction(action);
104
+ };
105
+
106
+ return registerCommands(
107
+ {
108
+ "chat.newLocal": startNewLocal,
109
+ "chat.newWithoutProject": (event) => {
110
+ const { activeThread, activeDraftThread } = readThreadContext();
111
+ const environmentId = scratch.scratchEnvironmentId(
112
+ activeThread?.environmentId ??
113
+ activeDraftThread?.environmentId ??
114
+ appAtomRegistry.get(primaryEnvironmentIdAtom),
115
+ );
116
+ if (environmentId === null) return;
117
+ claim(event);
118
+ void scratch.startScratchThread(environmentId);
119
+ },
120
+ "chat.new": (event) => {
121
+ // Pre-hydration settings are the defaults, where the legacy sidebar is off.
122
+ if (!getClientSettings().legacySidebarEnabled && readProjectGroupCount() > 1) {
123
+ claim(event);
124
+ openCommandPalette({ open: "new-thread-in" });
125
+ return;
126
+ }
127
+ startNewLocal(event);
128
+ },
129
+ "preview.toggle": (event) => {
130
+ claim(event);
131
+ const threadRef = readRouteThreadRef();
132
+ if (!threadRef || (!canOperatePreview(threadRef.environmentId) && !readPreviewOpen())) {
133
+ return;
134
+ }
135
+ if (!isPreviewAvailableFor(threadRef.environmentId)) {
136
+ toastManager.add(
137
+ stackedThreadToast({
138
+ type: "info",
139
+ title: "Preview is desktop-only",
140
+ description: "Open T3 Code in the desktop app to use the in-app preview.",
141
+ }),
142
+ );
143
+ return;
144
+ }
145
+ dispatchPreviewAction("toggle-panel");
146
+ },
147
+ "preview.refresh": previewCommand("refresh"),
148
+ "preview.focusUrl": previewCommand("focus-url"),
149
+ "preview.zoomIn": previewCommand("zoom-in"),
150
+ "preview.zoomOut": previewCommand("zoom-out"),
151
+ "preview.resetZoom": previewCommand("reset-zoom"),
152
+ },
153
+ {
154
+ when: () =>
155
+ router.state.matches.some((match) => match.routeId === CHAT_ROUTE_ID) &&
156
+ !router.state.matches.some((match) => isAppModalPage(match.pathname)) &&
157
+ !isCommandPaletteOpen(),
158
+ context: () => {
159
+ const threadRef = readRouteThreadRef();
160
+ return {
161
+ terminalOpen: threadRef
162
+ ? selectThreadTerminalUiState(
163
+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
164
+ threadRef,
165
+ ).terminalOpen
166
+ : false,
167
+ previewOpen: readPreviewOpen(),
168
+ };
169
+ },
170
+ onKeyDown: (event) => {
171
+ if (event.key !== "Escape") return false;
172
+ const selection = useThreadSelectionStore.getState();
173
+ if (selection.selectedThreadKeys.size === 0) return false;
174
+ event.preventDefault();
175
+ selection.clearSelection();
176
+ },
177
+ },
178
+ );
179
+}