Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

__root.tsx

396 lines14.5 KB

1import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 Outlet,
5 Link,
6 redirect,
7 createRootRoute,
8 type ErrorComponentProps,
9 useLocation,
10 useNavigate,
11 useRouter,
12} from "@tanstack/react-router";
13import { CheckIcon, CopyIcon } from "lucide-react";
14import { useEffect, useEffectEvent, useRef, useState } from "react";
15​
16import { APP_DISPLAY_NAME, APP_VERSION } from "../branding";
17import { AppSidebarLayout } from "../components/AppSidebarLayout";
18import { CommandPalette } from "../components/CommandPalette";
19import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
20import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
21import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog";
22import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
23import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
24import { DevReplayHost } from "../components/DevReplayHost";
25import { FirstRunGate } from "../components/onboarding/FirstRunGate";
26import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
27import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
28import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
29import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
30import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
31import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator";
32import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
33import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";
34import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
35import { ConnectDeviceApprovalCoordinator } from "../components/ConnectDeviceApprovalCoordinator";
36import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
37import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
38import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
39import { Button } from "../components/ui/button";
40import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
41import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
42import { isElectron } from "../env";
43import { useClientSettings } from "../hooks/useSettings";
44import {
45 deriveLogicalProjectKeyFromSettings,
46 derivePhysicalProjectKeyFromPath,
47 selectProjectGroupingSettings,
48} from "@t3tools/client-runtime/state/project-grouping";
49import { useUiStateStore } from "../uiStateStore";
50import { configureClientTracing } from "../observability/clientTracing";
51import { resolveInitialServerAuthGateState } from "../environments/primary";
52import { GUEST_PAGE_PATH } from "../guestPage";
53import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
54import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
55import { isLocalEnvironmentDisabled } from "../localEnvironment";
56import { useAtomValue } from "@effect/atom-react";
57import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../state/server";
58import { readProject } from "../state/entities";
59​
60import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
61import { isChunkLoadError } from "../lib/chunkReloadGuard";
62import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
63​
64export const Route = createRootRoute({
65 beforeLoad: async ({ location }) => {
66 // Guest links open on the owner's tunnel host in a browser with no T3 session, and must
67 // not trigger pairing or an environment connection.
68 if (location.pathname === GUEST_PAGE_PATH) {
69 return {
70 authGateState: {
71 status: "guest",
72 } as const,
73 };
74 }
75​
76 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
77 return {
78 authGateState: {
79 status: "hosted-pairing",
80 } as const,
81 };
82 }
83​
84 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
85 return {
86 authGateState: {
87 status: "hosted-static",
88 } as const,
89 };
90 }
91​
92 const authGateState = await resolveInitialServerAuthGateState();
93 if (authGateState.status === "authenticated") {
94 // Idempotent, so every navigation can ask for it.
95 void configureClientTracing();
96 }
97 if (
98 authGateState.status === "authenticated" &&
99 getDesktopSnapShotBridge() &&
100 shouldResumeSnapShotSetupOnStartup() &&
101 location.pathname !== "/settings/snap-shot"
102 ) {
103 throw redirect({ to: "/settings/snap-shot", replace: true });
104 }
105 return {
106 authGateState,
107 };
108 },
109 component: RootRouteView,
110 errorComponent: RootRouteErrorView,
111 notFoundComponent: RootRouteNotFoundView,
112 head: () => ({
113 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
114 }),
115});
116​
117function RootRouteNotFoundView() {
118 return (
119 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
120 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
121 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
122 <p className="text-sm text-muted-foreground">
123 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
124 start a thread.
125 </p>
126 <Button render={<Link to="/" replace />}>Go home</Button>
127 </div>
128 </main>
129 );
131​
132function RootRouteView() {
133 // Above every branch: app services raise toasts for the whole page, so the surface they write to
134 // must not unmount when the root switches branches (for example /welcome to the app shell).
135 return (
136 <ToastProvider>
137 <AnchoredToastProvider>
138 <RootRouteBranch />
139 </AnchoredToastProvider>
140 </ToastProvider>
141 );
143​
144function RootRouteBranch() {
145 const pathname = useLocation({ select: (location) => location.pathname });
146 const { authGateState } = Route.useRouteContext();
147 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
148 // A sync IPC read; the setting only changes across a relaunch.
149 const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
150 // Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
151 const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
152 if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
153 const hostedPromptLinkLanding = useHostedPromptLinkLanding(
154 authGateState.status === "hosted-static",
155 );
156​
157 if (pathname === GUEST_PAGE_PATH) return <Outlet />;
158​
159 if (
160 pathname === "/pair" ||
161 pathname === "/connect" ||
162 pathname === "/connect-agent" ||
163 pathname === "/approve-agent"
164 ) {
165 return <Outlet />;
166 }
167​
168 // Handle links before onboarding redirects lose them.
169 if (hostedPromptLinkLanding !== null) {
170 return hostedPromptLinkLanding;
171 }
172​
173 const isWelcome = pathname === "/welcome";
174 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
175 return <Outlet />;
176 }
177​
178 // Settings can reopen /welcome mid-session, so it mounts everything the app does except the
179 // first-run gate and the event router, whose first navigation would leave the page.
180 const appHosts = (
181 <>
182 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
183 {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
184 <DesktopWebLinkCoordinator />
185 ) : null}
186 {isElectron ? <RunningThreadKeepAlive /> : null}
187 <RelayClientInstallDialog />
188 <ConnectOnboardingDialog />
189 <SshPasswordPromptDialog />
190 <SnapShotCoordinator />
191 <ReopenClosedViewShortcut />
192 <ConfirmDialogHost />
193 <CustomSnoozeDialogHost />
194 <GuestShareDialogHost />
195 <ProjectCloneToastCoordinator />
196 <ConnectDeviceApprovalCoordinator />
197 <AddProjectToMachineDialogHost />
198 <UseInAnotherAppDialogHost />
199 {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
200 </>
201 );
202 const appShell = (
203 <CommandPalette>
204 {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */}
205 <AppSidebarLayout showSidebar={!isWelcome}>
206 <Outlet />
207 </AppSidebarLayout>
208 </CommandPalette>
209 );
210​
211 return (
212 <>
213 <ChatGptWelcomeCoordinator />
214 {isWelcome ? (
215 <>
216 {appHosts}
217 {appShell}
218 </>
219 ) : (
220 <FirstRunGate
221 enabled={primaryEnvironmentAuthenticated}
222 hostedStatic={authGateState.status === "hosted-static"}
223 >
224 {appHosts}
225 {primaryEnvironmentAuthenticated ? (
226 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
227 ) : null}
228 {appShell}
229 </FirstRunGate>
230 )}
231 {/* Above both shells and the router, so drafts survive navigation, including to /welcome. */}
232 <ThemeEditorHost />
233 </>
234 );
236​
237function RootRouteErrorView({ error }: ErrorComponentProps) {
238 const router = useRouter();
239 const message = errorMessage(error);
240 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
241 const pathname = useLocation({ select: (location) => location.pathname });
242 const report = errorReport(error, pathname);
243​
244 return (
245 <StandalonePage>
246 <StandalonePageHeader title="Something went wrong." description={message} />
247​
248 <div className="mt-5 flex flex-wrap gap-2">
249 <Button
250 size="sm"
251 onClick={() =>
252 isChunkLoadError(error) ? window.location.reload() : void router.invalidate()
253 }
254 >
255 Try again
256 </Button>
257 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
258 Reload app
259 </Button>
260 <CopyErrorButton report={report} />
261 </div>
262​
263 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
264 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
265 <pre className="max-h-64 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs whitespace-pre-wrap text-foreground/85">
266 {report}
267 </pre>
268 </div>
269 </StandalonePage>
270 );
272​
273function CopyErrorButton({ report }: { report: string }) {
274 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
275​
276 return (
277 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
278 {isCopied ? <CheckIcon className="text-success" /> : <CopyIcon />}
279 {isCopied ? "Copied" : "Copy error"}
280 </Button>
281 );
283​
284function errorMessage(error: unknown): string {
285 if (error instanceof Error && error.message.trim().length > 0) {
286 return error.message;
287 }
288​
289 if (typeof error === "string" && error.trim().length > 0) {
290 return error;
291 }
292​
293 return "An unexpected router error occurred.";
295​
296function errorDetails(error: unknown): string {
297 if (error instanceof Error) {
298 return error.stack ?? error.message;
299 }
300​
301 if (typeof error === "string") {
302 return error;
303 }
304​
305 try {
306 return JSON.stringify(error, null, 2);
307 } catch {
308 return "No additional error details are available.";
309 }
311​
312const MAX_ERROR_CAUSE_DEPTH = 5;
313​
314// Use only pathname to keep query tokens off the clipboard.
315function errorReport(error: unknown, pathname: string): string {
316 const lines = [
317 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
318 `Path: ${pathname}`,
319 `Time: ${new Date().toISOString()}`,
320 "",
321 errorDetails(error),
322 ];
323 let cause = error instanceof Error ? error.cause : undefined;
324 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
325 lines.push("", "Caused by:", errorDetails(cause));
326 cause = cause instanceof Error ? cause.cause : undefined;
327 }
328 return lines.join("\n");
330​
331function EventRouter({
332 skipInitialBootstrapNavigation,
333}: {
334 readonly skipInitialBootstrapNavigation: boolean;
335}) {
336 const navigate = useNavigate();
337 const pathname = useLocation({ select: (loc) => loc.pathname });
338 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
339 const serverConfig = useAtomValue(primaryServerConfigAtom);
340 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
341 const readPathname = useEffectEvent(() => pathname);
342 const handledBootstrapThreadIdRef = useRef<string | null>(null);
343 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
344​
345 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
346 if (!payload) return;
347​
348 void (async () => {
349 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
350 return;
351 }
352 const bootstrapProject = readProject(
353 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
354 );
355 const bootstrapProjectKey =
356 (bootstrapProject
357 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
358 : null) ??
359 (serverConfig?.cwd
360 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
361 : null) ??
362 scopedProjectKey(
363 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
364 );
365 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
366​
367 if (readPathname() !== "/") {
368 return;
369 }
370 if (skipInitialBootstrapNavigationRef.current) {
371 skipInitialBootstrapNavigationRef.current = false;
372 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
373 return;
374 }
375 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
376 return;
377 }
378 await navigate({
379 to: "/$environmentId/$threadId",
380 params: {
381 environmentId: payload.environment.environmentId,
382 threadId: payload.bootstrapThreadId,
383 },
384 replace: true,
385 });
386 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
387 })().catch(() => undefined);
388 });
389​
390 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands the bootstrap project in the UI store and navigates the router on a server welcome
391 useEffect(() => {
392 handleWelcome(serverWelcome);
393 }, [serverWelcome]);
394​
395 return null;