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

__root.tsx

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