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

__root.tsx

526 lines17.6 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 { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
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 { PullRequestGuideRunCoordinator } from "../components/pullRequest/guide/PullRequestGuideRunCoordinator";
35import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
36import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
37import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
38import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
39import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
40import { Button } from "../components/ui/button";
41import { MorphIcon } from "~/components/MorphIcon";
42import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
43import {
44 AnchoredToastProvider,
45 stackedThreadToast,
46 ToastProvider,
47 toastManager,
48} from "../components/ui/toast";
49import { isElectron } from "../env";
50import { cn } from "../lib/utils";
51import { useClientSettings } from "../hooks/useSettings";
52import {
53 deriveLogicalProjectKeyFromSettings,
54 derivePhysicalProjectKeyFromPath,
55 selectProjectGroupingSettings,
56} from "../logicalProject";
57import { useUiStateStore } from "../uiStateStore";
58import { syncBrowserChromeTheme } from "../hooks/useTheme";
59import { configureClientTracing } from "../observability/clientTracing";
60import { resolveInitialServerAuthGateState } from "../environments/primary";
61import { GUEST_PAGE_PATH } from "../guestPage";
62import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
63import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
64import { isLocalEnvironmentDisabled } from "../localEnvironment";
65import { useAtomValue } from "@effect/atom-react";
66import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
67import {
68 primaryServerConfigAtom,
69 primaryServerConfigEventAtom,
70 primaryServerWelcomeAtom,
71} from "../state/server";
72import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
73import {
74 createKeybindingsUpdateToastController,
75 type KeybindingsUpdateToastController,
76} from "../components/KeybindingsUpdateToast.logic";
77​
78import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
79import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
80import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
81​
82export const Route = createRootRoute({
83 beforeLoad: async ({ location }) => {
84 // Guest links open on the owner's tunnel host in a browser with no T3 session, and must
85 // not trigger pairing or an environment connection.
86 if (location.pathname === GUEST_PAGE_PATH) {
87 return {
88 authGateState: {
89 status: "guest",
90 } as const,
91 };
92 }
93​
94 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
95 return {
96 authGateState: {
97 status: "hosted-pairing",
98 } as const,
99 };
100 }
101​
102 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
103 return {
104 authGateState: {
105 status: "hosted-static",
106 } as const,
107 };
108 }
109​
110 const authGateState = await resolveInitialServerAuthGateState();
111 if (
112 authGateState.status === "authenticated" &&
113 getDesktopSnapShotBridge() &&
114 shouldResumeSnapShotSetupOnStartup() &&
115 location.pathname !== "/settings/snap-shot"
116 ) {
117 throw redirect({ to: "/settings/snap-shot", replace: true });
118 }
119 return {
120 authGateState,
121 };
122 },
123 component: RootRouteView,
124 errorComponent: RootRouteErrorView,
125 notFoundComponent: RootRouteNotFoundView,
126 head: () => ({
127 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
128 }),
129});
130​
131function RootRouteNotFoundView() {
132 return (
133 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
134 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
135 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
136 <p className="text-sm text-muted-foreground">
137 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
138 start a thread.
139 </p>
140 <Button render={<Link to="/" replace />}>Go home</Button>
141 </div>
142 </main>
143 );
145​
146function RootRouteView() {
147 // Above every branch: app services raise toasts for the whole page, so the surface they write to
148 // must not unmount when the root switches branches (for example /welcome to the app shell).
149 return (
150 <ToastProvider>
151 <AnchoredToastProvider>
152 <RootRouteBranch />
153 </AnchoredToastProvider>
154 </ToastProvider>
155 );
157​
158function RootRouteBranch() {
159 useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
160 const pathname = useLocation({ select: (location) => location.pathname });
161 const { authGateState } = Route.useRouteContext();
162 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
163 // Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
164 const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
165 if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
166 const hostedPromptLinkLanding = useHostedPromptLinkLanding(
167 authGateState.status === "hosted-static",
168 );
169​
170 if (pathname === GUEST_PAGE_PATH) return <Outlet />;
171​
172 if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
173 return (
174 <>
175 <BrowserChromeThemeSync key={pathname} />
176 <Outlet />
177 </>
178 );
179 }
180​
181 // Handle links before onboarding redirects lose them.
182 if (hostedPromptLinkLanding !== null) {
183 return (
184 <>
185 <BrowserChromeThemeSync key={pathname} />
186 {hostedPromptLinkLanding}
187 </>
188 );
189 }
190​
191 if (pathname === "/welcome") {
192 return (
193 <>
194 <BrowserChromeThemeSync key={pathname} />
195 <EnvironmentThemeSync />
196 <CustomSnoozeDialogHost />
197 <GuestShareDialogHost />
198 <CommandPalette>
199 <AppSidebarLayout>
200 <Outlet />
201 </AppSidebarLayout>
202 </CommandPalette>
203 </>
204 );
205 }
206​
207 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
208 return (
209 <>
210 <BrowserChromeThemeSync key={pathname} />
211 <Outlet />
212 </>
213 );
214 }
215​
216 const appShell = (
217 <CommandPalette>
218 <AppSidebarLayout>
219 <Outlet />
220 </AppSidebarLayout>
221 </CommandPalette>
222 );
223​
224 return (
225 <>
226 <BrowserChromeThemeSync key={pathname} />
227 <EnvironmentThemeSync />
228 <ChatGptWelcomeCoordinator />
229 <FirstRunGate
230 enabled={primaryEnvironmentAuthenticated}
231 hostedStatic={authGateState.status === "hosted-static"}
232 >
233 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
234 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
235 {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
236 {isElectron ? <RunningThreadKeepAlive /> : null}
237 <RelayClientInstallDialog />
238 <ConnectOnboardingDialog />
239 <SshPasswordPromptDialog />
240 <SnapShotCoordinator />
241 <ReopenClosedViewShortcut />
242 <ConfirmDialogHost />
243 <CustomSnoozeDialogHost />
244 <GuestShareDialogHost />
245 <SlowRpcRequestToastCoordinator />
246 <ProjectCloneToastCoordinator />
247 <AddProjectToMachineDialogHost />
248 <PullRequestGuideRunCoordinator />
249 <HostedStaticEnvironmentBootstrap />
250 {primaryEnvironmentAuthenticated ? (
251 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
252 ) : null}
253 {appShell}
254 {/* Keep the theme editor above the router so drafts survive navigation. */}
255 <ThemeEditorHost />
256 </FirstRunGate>
257 </>
258 );
260​
261function EnvironmentThemeSync() {
262 useEnvironmentThemeSync();
263 return null;
265​
266// Each route paints its own surface for browser chrome to sample.
267function BrowserChromeThemeSync() {
268 useEffect(() => {
269 const frame = window.requestAnimationFrame(() => {
270 syncBrowserChromeTheme();
271 });
272 return () => {
273 window.cancelAnimationFrame(frame);
274 };
275 }, []);
276 return null;
278​
279function HostedStaticEnvironmentBootstrap() {
280 const { environments } = useEnvironments();
281 const activeEnvironmentId = useActiveEnvironmentId();
282​
283 useEffect(() => {
284 if (
285 environments.some(
286 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
287 )
288 ) {
289 return;
290 }
291​
292 if (activeEnvironmentId) {
293 return;
294 }
295​
296 const firstSavedEnvironment = environments[0];
297 if (!firstSavedEnvironment) {
298 return;
299 }
300​
301 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
302 }, [activeEnvironmentId, environments]);
303​
304 return null;
306​
307function RootRouteErrorView({ error }: ErrorComponentProps) {
308 const router = useRouter();
309 const message = errorMessage(error);
310 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
311 const pathname = useLocation({ select: (location) => location.pathname });
312 const report = errorReport(error, pathname);
313​
314 return (
315 <StandalonePage tone="error">
316 <StandalonePageHeader
317 eyebrow={APP_DISPLAY_NAME}
318 title="Something went wrong."
319 description={message}
320 />
321​
322 <div className="mt-5 flex flex-wrap gap-2">
323 <Button size="sm" onClick={() => void router.invalidate()}>
324 Try again
325 </Button>
326 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
327 Reload app
328 </Button>
329 <CopyErrorButton report={report} />
330 </div>
331​
332 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
333 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
334 <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">
335 {report}
336 </pre>
337 </div>
338 </StandalonePage>
339 );
341​
342function CopyErrorButton({ report }: { report: string }) {
343 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
344​
345 return (
346 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
347 <MorphIcon className={cn(isCopied && "text-success")} icon={isCopied ? Check : Copy} />
348 {isCopied ? "Copied" : "Copy error"}
349 </Button>
350 );
352​
353function errorMessage(error: unknown): string {
354 if (error instanceof Error && error.message.trim().length > 0) {
355 return error.message;
356 }
357​
358 if (typeof error === "string" && error.trim().length > 0) {
359 return error;
360 }
361​
362 return "An unexpected router error occurred.";
364​
365function errorDetails(error: unknown): string {
366 if (error instanceof Error) {
367 return error.stack ?? error.message;
368 }
369​
370 if (typeof error === "string") {
371 return error;
372 }
373​
374 try {
375 return JSON.stringify(error, null, 2);
376 } catch {
377 return "No additional error details are available.";
378 }
380​
381const MAX_ERROR_CAUSE_DEPTH = 5;
382​
383// Use only pathname to keep query tokens off the clipboard.
384function errorReport(error: unknown, pathname: string): string {
385 const lines = [
386 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
387 `Path: ${pathname}`,
388 `Time: ${new Date().toISOString()}`,
389 "",
390 errorDetails(error),
391 ];
392 let cause = error instanceof Error ? error.cause : undefined;
393 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
394 lines.push("", "Caused by:", errorDetails(cause));
395 cause = cause instanceof Error ? cause.cause : undefined;
396 }
397 return lines.join("\n");
399​
400function AuthenticatedTracingBootstrap() {
401 useEffect(() => {
402 void configureClientTracing();
403 }, []);
404​
405 return null;
407​
408function EventRouter({
409 skipInitialBootstrapNavigation,
410}: {
411 readonly skipInitialBootstrapNavigation: boolean;
412}) {
413 const navigate = useNavigate();
414 const pathname = useLocation({ select: (loc) => loc.pathname });
415 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
416 const primaryEnvironment = usePrimaryEnvironment();
417 const serverConfig = useAtomValue(primaryServerConfigAtom);
418 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
419 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
420 const readPathname = useEffectEvent(() => pathname);
421 const handledBootstrapThreadIdRef = useRef<string | null>(null);
422 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
423 const handledConfigEventRef = useRef(serverConfigEvent);
424 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
425 createKeybindingsUpdateToastController({}),
426 );
427​
428 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
429 if (!payload) return;
430​
431 setActiveEnvironmentId(payload.environment.environmentId);
432 void (async () => {
433 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
434 return;
435 }
436 const bootstrapProject = readProject(
437 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
438 );
439 const bootstrapProjectKey =
440 (bootstrapProject
441 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
442 : null) ??
443 (serverConfig?.cwd
444 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
445 : null) ??
446 scopedProjectKey(
447 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
448 );
449 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
450​
451 if (readPathname() !== "/") {
452 return;
453 }
454 if (skipInitialBootstrapNavigationRef.current) {
455 skipInitialBootstrapNavigationRef.current = false;
456 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
457 return;
458 }
459 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
460 return;
461 }
462 await navigate({
463 to: "/$environmentId/$threadId",
464 params: {
465 environmentId: payload.environment.environmentId,
466 threadId: payload.bootstrapThreadId,
467 },
468 replace: true,
469 });
470 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
471 })().catch(() => undefined);
472 });
473​
474 const handleServerConfigUpdated = useEffectEvent(() => {
475 const decision = keybindingsToastController.handle(serverConfigEvent);
476 if (!decision) {
477 return;
478 }
479​
480 if (decision._tag === "Success") {
481 toastManager.add({
482 type: "success",
483 title: "Keybindings updated",
484 description: "Keybindings configuration reloaded successfully.",
485 });
486 return;
487 }
488​
489 toastManager.add(
490 stackedThreadToast({
491 type: "warning",
492 title: "Invalid keybindings configuration",
493 description: (
494 <KeybindingsConfigWarning
495 message={decision.message}
496 environmentId={primaryEnvironment?.environmentId ?? null}
497 configPath={serverConfig?.keybindingsConfigPath ?? null}
498 availableEditors={serverConfig?.availableEditors ?? []}
499 />
500 ),
501 }),
502 );
503 });
504​
505 useEffect(() => {
506 if (!serverConfig) {
507 return;
508 }
509​
510 setActiveEnvironmentId(serverConfig.environment.environmentId);
511 }, [serverConfig]);
512​
513 useEffect(() => {
514 handleWelcome(serverWelcome);
515 }, [serverWelcome]);
516​
517 useEffect(() => {
518 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
519 return;
520 }
521 handledConfigEventRef.current = serverConfigEvent;
522 handleServerConfigUpdated();
523 }, [serverConfigEvent]);
524​
525 return null;