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

__root.tsx

615 lines20.8 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, useMemo, useRef, useState } from "react";
16​
17import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL, APP_VERSION } from "../branding";
18import { resolveServerBackedAppDisplayName } from "../branding.logic";
19import { AppSidebarLayout } from "../components/AppSidebarLayout";
20import { CommandPalette } from "../components/CommandPalette";
21import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
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 { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
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 { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
40import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
41import { ProviderAuthCallbackCoordinator } from "../components/settings/ProviderAuthCallbackCoordinator";
42import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
43import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
44import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
45import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
46import { Button } from "../components/ui/button";
47import { MorphIcon } from "~/components/MorphIcon";
48import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
49import {
50 AnchoredToastProvider,
51 stackedThreadToast,
52 ToastProvider,
53 toastManager,
54} from "../components/ui/toast";
55import { isElectron } from "../env";
56import { cn } from "../lib/utils";
57import { applyAppearanceFontVariables } from "~/appearanceFonts";
58import { applyAppearanceContrast } from "~/appearanceContrast";
59import { useClientSettings } from "../hooks/useSettings";
60import {
61 deriveLogicalProjectKeyFromSettings,
62 derivePhysicalProjectKeyFromPath,
63 selectProjectGroupingSettings,
64} from "../logicalProject";
65import { useUiStateStore } from "../uiStateStore";
66import { syncBrowserChromeTheme } from "../hooks/useTheme";
67import { configureClientTracing } from "../observability/clientTracing";
68import { resolveInitialServerAuthGateState } from "../environments/primary";
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 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
92 return {
93 authGateState: {
94 status: "hosted-pairing",
95 } as const,
96 };
97 }
98​
99 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
100 return {
101 authGateState: {
102 status: "hosted-static",
103 } as const,
104 };
105 }
106​
107 const authGateState = await resolveInitialServerAuthGateState();
108 if (
109 authGateState.status === "authenticated" &&
110 getDesktopSnapShotBridge() &&
111 shouldResumeSnapShotSetupOnStartup() &&
112 location.pathname !== "/settings/snap-shot"
113 ) {
114 throw redirect({ to: "/settings/snap-shot", replace: true });
115 }
116 return {
117 authGateState,
118 };
119 },
120 component: RootRouteView,
121 errorComponent: RootRouteErrorView,
122 notFoundComponent: RootRouteNotFoundView,
123 head: () => ({
124 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
125 }),
126});
127​
128function RootRouteNotFoundView() {
129 return (
130 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
131 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
132 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
133 <p className="text-sm text-muted-foreground">
134 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
135 start a thread.
136 </p>
137 <Button render={<Link to="/" replace />}>Go home</Button>
138 </div>
139 </main>
140 );
142​
143function RootRouteView() {
144 useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
145 const pathname = useLocation({ select: (location) => location.pathname });
146 const { authGateState } = Route.useRouteContext();
147 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
148 const returningFromWelcomeRef = useRef(pathname === "/welcome");
149 const hostedPromptLinkLanding = useHostedPromptLinkLanding(
150 authGateState.status === "hosted-static",
151 );
152​
153 useEffect(() => {
154 if (pathname === "/welcome") {
155 returningFromWelcomeRef.current = true;
156 }
157 }, [pathname]);
158​
159 useEffect(() => {
160 const frame = window.requestAnimationFrame(() => {
161 syncBrowserChromeTheme();
162 });
163 return () => {
164 window.cancelAnimationFrame(frame);
165 };
166 }, [pathname]);
167​
168 if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
169 return (
170 <>
171 <DocumentTitleSync />
172 <Outlet />
173 </>
174 );
175 }
176​
177 // Ahead of first-run onboarding, which would otherwise send a new visitor to the welcome
178 // wizard and lose the link.
179 if (hostedPromptLinkLanding !== null) {
180 return (
181 <>
182 <DocumentTitleSync />
183 {hostedPromptLinkLanding}
184 </>
185 );
186 }
187​
188 if (pathname === "/welcome") {
189 return (
190 <ToastProvider>
191 <AnchoredToastProvider>
192 <DocumentTitleSync />
193 <ContrastAppearanceSync />
194 <EnvironmentThemeSync />
195 <GlassAppearanceSync />
196 <FontAppearanceSync />
197 <ProviderAuthCallbackCoordinator />
198 <CustomSnoozeDialogHost />
199 <CommandPalette>
200 <AppSidebarLayout>
201 <Outlet />
202 </AppSidebarLayout>
203 </CommandPalette>
204 </AnchoredToastProvider>
205 </ToastProvider>
206 );
207 }
208​
209 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
210 return (
211 <>
212 <DocumentTitleSync />
213 <Outlet />
214 </>
215 );
216 }
217​
218 const appShell = (
219 <CommandPalette>
220 <AppSidebarLayout>
221 <Outlet />
222 </AppSidebarLayout>
223 </CommandPalette>
224 );
225​
226 return (
227 <ToastProvider>
228 <AnchoredToastProvider>
229 <DocumentTitleSync />
230 <ContrastAppearanceSync />
231 <EnvironmentThemeSync />
232 <GlassAppearanceSync />
233 <FontAppearanceSync />
234 <ProviderAuthCallbackCoordinator />
235 <ChatGptWelcomeCoordinator />
236 <FirstRunGate
237 enabled={primaryEnvironmentAuthenticated}
238 hostedStatic={authGateState.status === "hosted-static"}
239 >
240 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
241 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
242 {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
243 {isElectron ? <RunningThreadKeepAlive /> : null}
244 <RelayClientInstallDialog />
245 <ConnectOnboardingDialog />
246 <SshPasswordPromptDialog />
247 <SnapShotCoordinator />
248 <ThreadNotificationCoordinator />
249 <ReopenClosedViewShortcut />
250 <ConfirmDialogHost />
251 <CustomSnoozeDialogHost />
252 <SlowRpcRequestToastCoordinator />
253 <PermissionUpdateNotice />
254 {primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}
255 <ProjectCloneToastCoordinator />
256 <PullRequestGuideRunCoordinator />
257 <HostedStaticEnvironmentBootstrap />
258 {primaryEnvironmentAuthenticated ? (
259 <EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
260 ) : null}
261 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
262 {isElectron ? <DesktopUpdateLaunchNotice /> : null}
263 {appShell}
264 {/* Above the router: a theme draft is judged by walking the app, so the
265 editor has to survive navigation away from settings. */}
266 <ThemeEditorHost />
267 </FirstRunGate>
268 </AnchoredToastProvider>
269 </ToastProvider>
270 );
272​
273function EnvironmentThemeSync() {
274 useEnvironmentThemeSync();
275 // Ordered after the palette sync so a first-run client adopting the
276 // environment's own theme finds it already in the library.
277 useDefaultThemeAdoption();
278 return null;
280​
281function ContrastAppearanceSync() {
282 const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
283 const diffColorScheme = useClientSettings((settings) => settings.diffColorScheme);
284​
285 useEffect(() => {
286 document.documentElement.dataset.diffColorScheme = diffColorScheme;
287 }, [diffColorScheme]);
288​
289 const chatWidth = useClientSettings((settings) => settings.chatWidth);
290 useEffect(() => {
291 document.documentElement.dataset.chatWidth = chatWidth;
292 }, [chatWidth]);
293​
294 useEffect(() => {
295 applyAppearanceContrast(document.documentElement, appearanceContrast);
296 }, [appearanceContrast]);
297​
298 return null;
300​
301function GlassAppearanceSync() {
302 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
303​
304 useEffect(() => {
305 const style = document.documentElement.style;
306 style.setProperty("--glass-opacity", `${glassOpacity}%`);
307 if (glassOpacity === 100) {
308 style.setProperty("--glass-blur", "0px");
309 } else {
310 style.removeProperty("--glass-blur");
311 }
312 }, [glassOpacity]);
313​
314 return null;
316​
317function FontAppearanceSync() {
318 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
319 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
320 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
321 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
322 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
323 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
324 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
325​
326 useEffect(() => {
327 applyAppearanceFontVariables(document.documentElement, {
328 sans: fontFamilySans,
329 code: fontFamilyCode,
330 composer: fontFamilyComposer,
331 sizeInterface: fontSizeInterface,
332 sizePrompt: fontSizePrompt,
333 sizeCode: fontSizeCode,
334 smoothing: fontSmoothing,
335 });
336 }, [
337 fontFamilyCode,
338 fontFamilyComposer,
339 fontFamilySans,
340 fontSizeCode,
341 fontSizeInterface,
342 fontSizePrompt,
343 fontSmoothing,
344 ]);
345​
346 return null;
348​
349function DocumentTitleSync() {
350 const primaryServerVersion =
351 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
352 const title = resolveServerBackedAppDisplayName({
353 baseName: APP_BASE_NAME,
354 fallbackDisplayName: APP_DISPLAY_NAME,
355 fallbackStageLabel: APP_STAGE_LABEL,
356 primaryServerVersion,
357 });
358​
359 useEffect(() => {
360 document.title = title;
361 }, [title]);
362​
363 return null;
365​
366function HostedStaticEnvironmentBootstrap() {
367 const { environments } = useEnvironments();
368 const activeEnvironmentId = useActiveEnvironmentId();
369​
370 useEffect(() => {
371 if (
372 environments.some(
373 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
374 )
375 ) {
376 return;
377 }
378​
379 if (activeEnvironmentId) {
380 return;
381 }
382​
383 const firstSavedEnvironment = environments[0];
384 if (!firstSavedEnvironment) {
385 return;
386 }
387​
388 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
389 }, [activeEnvironmentId, environments]);
390​
391 return null;
393​
394function RootRouteErrorView({ error }: ErrorComponentProps) {
395 const router = useRouter();
396 const message = errorMessage(error);
397 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
398 const pathname = useLocation({ select: (location) => location.pathname });
399 const report = useMemo(() => errorReport(error, pathname), [error, pathname]);
400​
401 return (
402 <StandalonePage tone="error">
403 <StandalonePageHeader
404 eyebrow={APP_DISPLAY_NAME}
405 title="Something went wrong."
406 description={message}
407 />
408​
409 <div className="mt-5 flex flex-wrap gap-2">
410 <Button size="sm" onClick={() => void router.invalidate()}>
411 Try again
412 </Button>
413 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
414 Reload app
415 </Button>
416 <CopyErrorButton report={report} />
417 </div>
418​
419 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
420 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
421 <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">
422 {report}
423 </pre>
424 </div>
425 </StandalonePage>
426 );
428​
429function CopyErrorButton({ report }: { report: string }) {
430 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
431​
432 return (
433 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
434 <MorphIcon className={cn(isCopied && "text-success")} icon={isCopied ? Check : Copy} />
435 {isCopied ? "Copied" : "Copy error"}
436 </Button>
437 );
439​
440function errorMessage(error: unknown): string {
441 if (error instanceof Error && error.message.trim().length > 0) {
442 return error.message;
443 }
444​
445 if (typeof error === "string" && error.trim().length > 0) {
446 return error;
447 }
448​
449 return "An unexpected router error occurred.";
451​
452function errorDetails(error: unknown): string {
453 if (error instanceof Error) {
454 return error.stack ?? error.message;
455 }
456​
457 if (typeof error === "string") {
458 return error;
459 }
460​
461 try {
462 return JSON.stringify(error, null, 2);
463 } catch {
464 return "No additional error details are available.";
465 }
467​
468const MAX_ERROR_CAUSE_DEPTH = 5;
469​
470/**
471 * Takes the pathname only so tokens in the query never land on the clipboard.
472 */
473function errorReport(error: unknown, pathname: string): string {
474 const lines = [
475 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
476 `Path: ${pathname}`,
477 `Time: ${new Date().toISOString()}`,
478 "",
479 errorDetails(error),
480 ];
481 let cause = error instanceof Error ? error.cause : undefined;
482 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
483 lines.push("", "Caused by:", errorDetails(cause));
484 cause = cause instanceof Error ? cause.cause : undefined;
485 }
486 return lines.join("\n");
488​
489function AuthenticatedTracingBootstrap() {
490 useEffect(() => {
491 void configureClientTracing();
492 }, []);
493​
494 return null;
496​
497function EventRouter({
498 skipInitialBootstrapNavigation,
499}: {
500 readonly skipInitialBootstrapNavigation: boolean;
501}) {
502 const navigate = useNavigate();
503 const pathname = useLocation({ select: (loc) => loc.pathname });
504 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
505 const primaryEnvironment = usePrimaryEnvironment();
506 const serverConfig = useAtomValue(primaryServerConfigAtom);
507 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
508 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
509 const readPathname = useEffectEvent(() => pathname);
510 const handledBootstrapThreadIdRef = useRef<string | null>(null);
511 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
512 const handledConfigEventRef = useRef(serverConfigEvent);
513 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
514 createKeybindingsUpdateToastController({}),
515 );
516​
517 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
518 if (!payload) return;
519​
520 setActiveEnvironmentId(payload.environment.environmentId);
521 void (async () => {
522 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
523 return;
524 }
525 const bootstrapProject = readProject(
526 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
527 );
528 const bootstrapProjectKey =
529 (bootstrapProject
530 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
531 : null) ??
532 (serverConfig?.cwd
533 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
534 : null) ??
535 scopedProjectKey(
536 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
537 );
538 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
539​
540 if (readPathname() !== "/") {
541 return;
542 }
543 if (skipInitialBootstrapNavigationRef.current) {
544 skipInitialBootstrapNavigationRef.current = false;
545 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
546 return;
547 }
548 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
549 return;
550 }
551 await navigate({
552 to: "/$environmentId/$threadId",
553 params: {
554 environmentId: payload.environment.environmentId,
555 threadId: payload.bootstrapThreadId,
556 },
557 replace: true,
558 });
559 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
560 })().catch(() => undefined);
561 });
562​
563 const handleServerConfigUpdated = useEffectEvent(() => {
564 const decision = keybindingsToastController.handle(serverConfigEvent);
565 if (!decision) {
566 return;
567 }
568​
569 if (decision._tag === "Success") {
570 toastManager.add({
571 type: "success",
572 title: "Keybindings updated",
573 description: "Keybindings configuration reloaded successfully.",
574 });
575 return;
576 }
577​
578 toastManager.add(
579 stackedThreadToast({
580 type: "warning",
581 title: "Invalid keybindings configuration",
582 description: (
583 <KeybindingsConfigWarning
584 message={decision.message}
585 environmentId={primaryEnvironment?.environmentId ?? null}
586 configPath={serverConfig?.keybindingsConfigPath ?? null}
587 availableEditors={serverConfig?.availableEditors ?? []}
588 />
589 ),
590 }),
591 );
592 });
593​
594 useEffect(() => {
595 if (!serverConfig) {
596 return;
597 }
598​
599 setActiveEnvironmentId(serverConfig.environment.environmentId);
600 }, [serverConfig]);
601​
602 useEffect(() => {
603 handleWelcome(serverWelcome);
604 }, [serverWelcome]);
605​
606 useEffect(() => {
607 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
608 return;
609 }
610 handledConfigEventRef.current = serverConfigEvent;
611 handleServerConfigUpdated();
612 }, [serverConfigEvent]);
613​
614 return null;