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

__root.tsx

388 lines14.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 { 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 { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
36import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
37import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
38import { Button } from "../components/ui/button";
39import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
40import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
41import { isElectron } from "../env";
42import { useClientSettings } from "../hooks/useSettings";
43import {
44 deriveLogicalProjectKeyFromSettings,
45 derivePhysicalProjectKeyFromPath,
46 selectProjectGroupingSettings,
47} from "@t3tools/client-runtime/state/project-grouping";
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 // A sync IPC read; the setting only changes across a relaunch.
147 const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
148 // Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
149 const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
150 if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
151 const hostedPromptLinkLanding = useHostedPromptLinkLanding(
152 authGateState.status === "hosted-static",
153 );
154​
155 if (pathname === GUEST_PAGE_PATH) return <Outlet />;
156​
157 if (
158 pathname === "/pair" ||
159 pathname === "/connect" ||
160 pathname === "/connect-agent" ||
161 pathname === "/approve-agent"
162 ) {
163 return <Outlet />;
164 }
165​
166 // Handle links before onboarding redirects lose them.
167 if (hostedPromptLinkLanding !== null) {
168 return hostedPromptLinkLanding;
169 }
170​
171 const isWelcome = pathname === "/welcome";
172 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
173 return <Outlet />;
174 }
175​
176 // Settings can reopen /welcome mid-session, so it mounts everything the app does except the
177 // first-run gate and the event router, whose first navigation would leave the page.
178 const appHosts = (
179 <>
180 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
181 {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
182 <DesktopWebLinkCoordinator />
183 ) : null}
184 {isElectron ? <RunningThreadKeepAlive /> : null}
185 <RelayClientInstallDialog />
186 <ConnectOnboardingDialog />
187 <SshPasswordPromptDialog />
188 <SnapShotCoordinator />
189 <ReopenClosedViewShortcut />
190 <ConfirmDialogHost />
191 <CustomSnoozeDialogHost />
192 <GuestShareDialogHost />
193 <ProjectCloneToastCoordinator />
194 <AddProjectToMachineDialogHost />
195 <UseInAnotherAppDialogHost />
196 {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
197 </>
198 );
199 const appShell = (
200 <CommandPalette>
201 {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */}
202 <AppSidebarLayout showSidebar={!isWelcome}>
203 <Outlet />
204 </AppSidebarLayout>
205 </CommandPalette>
206 );
207​
208 return (
209 <>
210 <ChatGptWelcomeCoordinator />
211 {isWelcome ? (
212 <>
213 {appHosts}
214 {appShell}
215 </>
216 ) : (
217 <FirstRunGate
218 enabled={primaryEnvironmentAuthenticated}
219 hostedStatic={authGateState.status === "hosted-static"}
220 >
221 {appHosts}
222 {primaryEnvironmentAuthenticated ? (
223 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
224 ) : null}
225 {appShell}
226 </FirstRunGate>
227 )}
228 {/* Above both shells and the router, so drafts survive navigation, including to /welcome. */}
229 <ThemeEditorHost />
230 </>
231 );
233​
234function RootRouteErrorView({ error }: ErrorComponentProps) {
235 const router = useRouter();
236 const message = errorMessage(error);
237 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
238 const pathname = useLocation({ select: (location) => location.pathname });
239 const report = errorReport(error, pathname);
240​
241 return (
242 <StandalonePage>
243 <StandalonePageHeader title="Something went wrong." description={message} />
244​
245 <div className="mt-5 flex flex-wrap gap-2">
246 <Button size="sm" onClick={() => void router.invalidate()}>
247 Try again
248 </Button>
249 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
250 Reload app
251 </Button>
252 <CopyErrorButton report={report} />
253 </div>
254​
255 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
256 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
257 <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">
258 {report}
259 </pre>
260 </div>
261 </StandalonePage>
262 );
264​
265function CopyErrorButton({ report }: { report: string }) {
266 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
267​
268 return (
269 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
270 {isCopied ? <CheckIcon className="text-success" /> : <CopyIcon />}
271 {isCopied ? "Copied" : "Copy error"}
272 </Button>
273 );
275​
276function errorMessage(error: unknown): string {
277 if (error instanceof Error && error.message.trim().length > 0) {
278 return error.message;
279 }
280​
281 if (typeof error === "string" && error.trim().length > 0) {
282 return error;
283 }
284​
285 return "An unexpected router error occurred.";
287​
288function errorDetails(error: unknown): string {
289 if (error instanceof Error) {
290 return error.stack ?? error.message;
291 }
292​
293 if (typeof error === "string") {
294 return error;
295 }
296​
297 try {
298 return JSON.stringify(error, null, 2);
299 } catch {
300 return "No additional error details are available.";
301 }
303​
304const MAX_ERROR_CAUSE_DEPTH = 5;
305​
306// Use only pathname to keep query tokens off the clipboard.
307function errorReport(error: unknown, pathname: string): string {
308 const lines = [
309 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
310 `Path: ${pathname}`,
311 `Time: ${new Date().toISOString()}`,
312 "",
313 errorDetails(error),
314 ];
315 let cause = error instanceof Error ? error.cause : undefined;
316 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
317 lines.push("", "Caused by:", errorDetails(cause));
318 cause = cause instanceof Error ? cause.cause : undefined;
319 }
320 return lines.join("\n");
322​
323function EventRouter({
324 skipInitialBootstrapNavigation,
325}: {
326 readonly skipInitialBootstrapNavigation: boolean;
327}) {
328 const navigate = useNavigate();
329 const pathname = useLocation({ select: (loc) => loc.pathname });
330 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
331 const serverConfig = useAtomValue(primaryServerConfigAtom);
332 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
333 const readPathname = useEffectEvent(() => pathname);
334 const handledBootstrapThreadIdRef = useRef<string | null>(null);
335 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
336​
337 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
338 if (!payload) return;
339​
340 void (async () => {
341 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
342 return;
343 }
344 const bootstrapProject = readProject(
345 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
346 );
347 const bootstrapProjectKey =
348 (bootstrapProject
349 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
350 : null) ??
351 (serverConfig?.cwd
352 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
353 : null) ??
354 scopedProjectKey(
355 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
356 );
357 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
358​
359 if (readPathname() !== "/") {
360 return;
361 }
362 if (skipInitialBootstrapNavigationRef.current) {
363 skipInitialBootstrapNavigationRef.current = false;
364 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
365 return;
366 }
367 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
368 return;
369 }
370 await navigate({
371 to: "/$environmentId/$threadId",
372 params: {
373 environmentId: payload.environment.environmentId,
374 threadId: payload.bootstrapThreadId,
375 },
376 replace: true,
377 });
378 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
379 })().catch(() => undefined);
380 });
381​
382 // 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
383 useEffect(() => {
384 handleWelcome(serverWelcome);
385 }, [serverWelcome]);
386​
387 return null;