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

__root.tsx

534 lines18.5 KB

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