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