Open History to see the last commit
1import { AuthPreviewOperateScope, type EnvironmentId } from "@t3tools/contracts";
2import type { AnyRouter } from "@tanstack/react-router";
3import { msg } from "gt-react";
4
5import { stackedThreadToast, toastManager } from "~/components/ui/toast";
6import { m } from "~/i18n/messages";
7import { isPreviewAvailableFor } from "../browser/previewRuntime";
8import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
9import { useComposerDraftStore } from "../composerDraftStore";
10import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";
11import { isAppModalPage } from "../components/sidebar/mainAppLocation";
12import { isBrowserSurfaceFocused } from "../lib/previewFocus";
13import { shouldCreateNewThreadInCurrentProject } from "../components/Sidebar.logic";
14import {
15 createNewThreadHandler,
16 readLastUsedProjectKey,
17 resolveDefaultProjectRef,
18} from "../hooks/useHandleNewThread";
19import { createScratchProjectActions } from "../hooks/useScratchProject";
20import { getClientSettings } from "../hooks/useSettings";
21import { startNewThreadFromContext } from "../lib/chatThreadActions";
22import { selectProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
23import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
24import { appAtomRegistry } from "../rpc/atomRegistry";
25import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
26import { readProjects, readThreadShell } from "../state/entities";
27import { defaultProjectFallbackReadyAtom } from "../state/projects";
28import { environmentPresentations } from "../state/presentation";
29import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
30import { readEnvironmentScope } from "../state/session";
31import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
32import { useThreadSelectionStore } from "../threadSelectionStore";
33import { resolveThreadRouteTarget } from "../threadRoutes";
34import { useUiStateStore } from "../uiStateStore";
35import { type CommandHandler, registerCommands } from "./dispatcher";
36
37const CHAT_ROUTE_ID = "/_chat";
38
39/**
40 * New-thread and preview commands, live while a chat route is showing and no
41 * modal page (Settings, Usage) covers it. Everything is read at event time, so
42 * the scope is registered once instead of re-registering on every store change.
43 */
44export function installChatRouteCommands(router: AnyRouter): () => void {
45 const handleNewThread = createNewThreadHandler(router);
46 const scratch = createScratchProjectActions({
47 environments: () =>
48 [...appAtomRegistry.get(environmentPresentations.presentationsAtom)].map(
49 ([environmentId, presentation]) => ({ ...presentation, environmentId }),
50 ),
51 primaryEnvironmentId: () => appAtomRegistry.get(primaryEnvironmentIdAtom),
52 registry: appAtomRegistry,
53 handleNewThread,
54 });
55
56 const readRouteTarget = () => resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
57 const readRouteThreadRef = () => {
58 const target = readRouteTarget();
59 return target?.kind === "server" ? target.threadRef : null;
60 };
61 const readRouteEnvironmentId = () => {
62 const target = readRouteTarget();
63 if (!target) return null;
64 return target.kind === "server"
65 ? target.threadRef.environmentId
66 : (useComposerDraftStore.getState().getDraftSession(target.draftId)?.environmentId ?? null);
67 };
68 const readPreviewOpen = () => {
69 const threadRef = readRouteThreadRef();
70 // Store-only on purpose: the URL-aware arbitration lives in ChatView's
71 // preview toggle, which the action bus reaches.
72 return threadRef
73 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) === "preview"
74 : false;
75 };
76 const readThreadContext = () => {
77 const lastUsedProjectKey = readLastUsedProjectKey();
78 const target = readRouteTarget();
79 const drafts = useComposerDraftStore.getState();
80 const activeThread = target?.kind === "server" ? readThreadShell(target.threadRef) : null;
81 const activeDraftThread = target
82 ? target.kind === "server"
83 ? drafts.getDraftThread(target.threadRef)
84 : drafts.getDraftSession(target.draftId)
85 : null;
86 return {
87 activeDraftThread,
88 activeThread: activeThread ?? undefined,
89 defaultProjectRef: resolveDefaultProjectRef(
90 readProjects(),
91 useUiStateStore.getState().projectOrder,
92 lastUsedProjectKey,
93 appAtomRegistry.get(defaultProjectFallbackReadyAtom(lastUsedProjectKey)),
94 selectProjectGroupingSettings(getClientSettings()),
95 ),
96 handleNewThread,
97 };
98 };
99 // Grouped like the sidebar, so the shortcut and the New thread button agree.
100 const readProjectGroups = () =>
101 buildSidebarProjectSnapshots({
102 projects: readProjects(),
103 groupScratchProjects: true,
104 settings: selectProjectGroupingSettings(getClientSettings()),
105 primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom),
106 resolveEnvironmentLabel: () => null,
107 });
108 const canOperatePreview = (environmentId: EnvironmentId) =>
109 readEnvironmentScope(environmentId, AuthPreviewOperateScope);
110
111 const claim = (event: KeyboardEvent) => {
112 event.preventDefault();
113 event.stopPropagation();
114 };
115
116 const startNewLocal: CommandHandler = (event) => {
117 claim(event);
118 // With no current or open project, such as when every project is archived, pick one.
119 void startNewThreadFromContext(readThreadContext()).then((started) => {
120 if (!started) openCommandPalette({ open: "new-thread-in" });
121 });
122 };
123
124 const previewCommand =
125 (action: PreviewAction): CommandHandler =>
126 (event) => {
127 claim(event);
128 const environmentId = readRouteEnvironmentId();
129 if (environmentId && canOperatePreview(environmentId)) dispatchPreviewAction(action);
130 };
131 // Unclaimed, zoom keys reach the desktop menu accelerators or the browser's own zoom.
132 const zoomCommand =
133 (action: PreviewAction): CommandHandler =>
134 (event) => {
135 if (!isBrowserSurfaceFocused()) return false;
136 previewCommand(action)(event);
137 };
138
139 return registerCommands(
140 {
141 "chat.newLocal": startNewLocal,
142 "chat.newWithoutProject": (event) => {
143 const { activeThread, activeDraftThread } = readThreadContext();
144 const environmentId = scratch.scratchEnvironmentId(
145 activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null,
146 );
147 if (environmentId === null) return;
148 claim(event);
149 void scratch.startScratchThread(environmentId);
150 },
151 "chat.new": (event) => {
152 const groups = readProjectGroups();
153 if (
154 !shouldCreateNewThreadInCurrentProject(
155 false,
156 groups.filter((group) => !group.archived).length,
157 groups.length,
158 )
159 ) {
160 claim(event);
161 openCommandPalette({ open: "new-thread-in" });
162 return;
163 }
164 startNewLocal(event);
165 },
166 "preview.toggle": (event) => {
167 claim(event);
168 const threadRef = readRouteThreadRef();
169 if (!threadRef || (!canOperatePreview(threadRef.environmentId) && !readPreviewOpen())) {
170 return;
171 }
172 if (!isPreviewAvailableFor(threadRef.environmentId)) {
173 toastManager.add(
174 stackedThreadToast({
175 type: "info",
176 title: m(msg("Preview is desktop-only")),
177 description: m(msg("Open T3 Code in the desktop app to use the in-app preview.")),
178 }),
179 );
180 return;
181 }
182 dispatchPreviewAction("toggle-panel");
183 },
184 "preview.refresh": previewCommand("refresh"),
185 "preview.focusUrl": previewCommand("focus-url"),
186 "preview.zoomIn": zoomCommand("zoom-in"),
187 "preview.zoomOut": zoomCommand("zoom-out"),
188 "preview.resetZoom": zoomCommand("reset-zoom"),
189 "preview.find": previewCommand("find"),
190 },
191 {
192 when: () =>
193 router.state.matches.some((match) => match.routeId === CHAT_ROUTE_ID) &&
194 !router.state.matches.some((match) => isAppModalPage(match.pathname)) &&
195 !isCommandPaletteOpen(),
196 context: () => {
197 const threadRef = readRouteThreadRef();
198 return {
199 terminalOpen: threadRef
200 ? selectThreadTerminalUiState(
201 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
202 threadRef,
203 ).terminalOpen
204 : false,
205 previewOpen: readPreviewOpen(),
206 };
207 },
208 onKeyDown: (event) => {
209 if (event.key !== "Escape") return false;
210 const selection = useThreadSelectionStore.getState();
211 if (selection.selectedThreadKeys.size === 0) return false;
212 event.preventDefault();
213 selection.clearSelection();
214 },
215 },
216 );
217}