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

__root.tsx

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