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

__root.tsx

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