Open History to see the last commit
1import { AuthPreviewOperateScope } from "@t3tools/contracts";
2import { Outlet, createFileRoute, redirect, useParams } from "@tanstack/react-router";
3import { useAtomValue } from "@effect/atom-react";
4import { useEffect, useMemo } from "react";
5
6import { isCommandPaletteOpen } from "../commandPaletteBus";
7import { ThreadRouteView } from "../components/ThreadRouteView";
8import { resolveThreadRouteTarget } from "../threadRoutes";
9import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";
10import { openCommandPalette } from "../commandPaletteBus";
11import { useProjects } from "../state/entities";
12import { isPreviewAvailableFor } from "../browser/previewRuntime";
13import { usePrimaryEnvironmentId } from "../state/environments";
14import { useEnvironmentScope } from "../state/session";
15import { selectProjectGroupingSettings } from "../logicalProject";
16import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
17import { dispatchPreviewAction } from "../components/preview/previewActionBus";
18import { useHandleNewThread } from "../hooks/useHandleNewThread";
19import { useScratchProject } from "../hooks/useScratchProject";
20import { startNewThreadFromContext } from "../lib/chatThreadActions";
21import { isPreviewFocused } from "../lib/previewFocus";
22import { isTerminalFocused } from "../lib/terminalFocus";
23import { isEditableFocused } from "../lib/editableFocus";
24import { isModelPickerOpen } from "../modelPickerVisibility";
25import { undoLatestThreadAction } from "../hooks/showThreadUndoNotice";
26import { resolveShortcutCommand } from "../keybindings";
27import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
28import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
29import { useThreadSelectionStore } from "../threadSelectionStore";
30import { stackedThreadToast, toastManager } from "~/components/ui/toast";
31import { primaryServerKeybindingsAtom } from "~/state/server";
32
33function ChatRouteGlobalShortcuts() {
34 const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
35 const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
36 const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
37 useHandleNewThread();
38 const canOperatePreview = useEnvironmentScope(
39 routeThreadRef?.environmentId ?? null,
40 AuthPreviewOperateScope,
41 );
42 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
43 const legacySidebarEnabled = useLegacySidebarEnabled();
44 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
45 const projects = useProjects();
46 const primaryEnvironmentId = usePrimaryEnvironmentId();
47 const { scratchEnvironmentId, startScratchThread } = useScratchProject();
48 const projectGroupCount = useMemo(
49 () =>
50 buildSidebarProjectSnapshots({
51 projects,
52 settings: projectGroupingSettings,
53 primaryEnvironmentId,
54 resolveEnvironmentLabel: () => null,
55 }).length,
56 [primaryEnvironmentId, projectGroupingSettings, projects],
57 );
58 const terminalOpen = useTerminalUiStateStore((state) =>
59 routeThreadRef
60 ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
61 : false,
62 );
63 // The `previewOpen` shortcut-context flag here uses the store-only value;
64 // the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
65 // which we invoke via the action bus to avoid duplicating the rule.
66 const previewOpen = useRightPanelStore((state) =>
67 routeThreadRef
68 ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
69 : false,
70 );
71 useEffect(() => {
72 const onWindowKeyDown = (event: KeyboardEvent) => {
73 if (event.defaultPrevented) return;
74 const command = resolveShortcutCommand(event, keybindings, {
75 context: {
76 terminalFocus: isTerminalFocused(),
77 terminalOpen,
78 previewFocus: isPreviewFocused(),
79 previewOpen,
80 editableFocus: isEditableFocused(event.target),
81 modelPickerOpen: isModelPickerOpen(),
82 },
83 });
84
85 if (isCommandPaletteOpen()) {
86 return;
87 }
88
89 if (command === "thread.undo") {
90 if (event.repeat || isModelPickerOpen()) return;
91 if (undoLatestThreadAction()) {
92 event.preventDefault();
93 event.stopPropagation();
94 }
95 return;
96 }
97
98 if (event.key === "Escape" && selectedThreadKeysSize > 0) {
99 event.preventDefault();
100 clearSelection();
101 return;
102 }
103
104 if (command === "chat.newLocal") {
105 event.preventDefault();
106 event.stopPropagation();
107 void startNewThreadFromContext({
108 activeDraftThread,
109 activeThread: activeThread ?? undefined,
110 defaultProjectRef,
111 handleNewThread,
112 });
113 return;
114 }
115
116 if (command === "chat.newWithoutProject") {
117 const environmentId = scratchEnvironmentId(
118 activeThread?.environmentId ?? activeDraftThread?.environmentId ?? primaryEnvironmentId,
119 );
120 if (environmentId === null) return;
121 event.preventDefault();
122 event.stopPropagation();
123 void startScratchThread(environmentId);
124 return;
125 }
126
127 if (command === "chat.new") {
128 event.preventDefault();
129 event.stopPropagation();
130 // The default sidebar routes creation through the command palette
131 // whenever there is a real choice to make; the legacy sidebar (and
132 // single-project setups) keep the immediate contextual create.
133 if (!legacySidebarEnabled && projectGroupCount > 1) {
134 openCommandPalette({ open: "new-thread-in" });
135 return;
136 }
137 void startNewThreadFromContext({
138 activeDraftThread,
139 activeThread: activeThread ?? undefined,
140 defaultProjectRef,
141 handleNewThread,
142 });
143 return;
144 }
145
146 if (command === "preview.toggle") {
147 event.preventDefault();
148 event.stopPropagation();
149 if (!routeThreadRef || (!canOperatePreview && !previewOpen)) return;
150 if (!isPreviewAvailableFor(routeThreadRef.environmentId)) {
151 toastManager.add(
152 stackedThreadToast({
153 type: "info",
154 title: "Preview is desktop-only",
155 description: "Open T3 Code in the desktop app to use the in-app preview.",
156 }),
157 );
158 return;
159 }
160 dispatchPreviewAction("toggle-panel");
161 return;
162 }
163
164 // The remaining preview commands only fire when the panel is the
165 // currently-focused tenant. The `when: previewFocus` rule already
166 // gates this, but defend against the keybinding being misconfigured.
167 if (
168 command === "preview.refresh" ||
169 command === "preview.focusUrl" ||
170 command === "preview.zoomIn" ||
171 command === "preview.zoomOut" ||
172 command === "preview.resetZoom"
173 ) {
174 event.preventDefault();
175 event.stopPropagation();
176 if (!canOperatePreview) return;
177 const action =
178 command === "preview.refresh"
179 ? "refresh"
180 : command === "preview.focusUrl"
181 ? "focus-url"
182 : command === "preview.zoomIn"
183 ? "zoom-in"
184 : command === "preview.zoomOut"
185 ? "zoom-out"
186 : "reset-zoom";
187 dispatchPreviewAction(action);
188 }
189 };
190
191 window.addEventListener("keydown", onWindowKeyDown);
192 return () => {
193 window.removeEventListener("keydown", onWindowKeyDown);
194 };
195 }, [
196 activeDraftThread,
197 activeThread,
198 clearSelection,
199 canOperatePreview,
200 handleNewThread,
201 keybindings,
202 defaultProjectRef,
203 previewOpen,
204 primaryEnvironmentId,
205 projectGroupCount,
206 routeThreadRef,
207 scratchEnvironmentId,
208 selectedThreadKeysSize,
209 startScratchThread,
210 legacySidebarEnabled,
211 terminalOpen,
212 ]);
213
214 return null;
215}
216
217function ChatRouteLayout() {
218 // Both thread routes render here, not in their own leaf components, so the
219 // draft-to-thread promotion keeps one ChatView mounted across the swap.
220 const threadTarget = useParams({
221 strict: false,
222 select: (params) => resolveThreadRouteTarget(params),
223 });
224 return (
225 <>
226 <ChatRouteGlobalShortcuts />
227 {threadTarget ? <ThreadRouteView target={threadTarget} /> : <Outlet />}
228 </>
229 );
230}
231
232export const Route = createFileRoute("/_chat")({
233 beforeLoad: async ({ context }) => {
234 if (
235 context.authGateState.status !== "authenticated" &&
236 context.authGateState.status !== "hosted-static"
237 ) {
238 throw redirect({ to: "/pair", replace: true });
239 }
240 },
241 component: ChatRouteLayout,
242});