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

__root.tsx

620 lines21.2 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_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 // 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 === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
156 return (
157 <>
158 <DocumentTitleSync />
159 <BrowserChromeThemeSync key={pathname} />
160 <Outlet />
161 </>
162 );
163 }
164​
165 // Ahead of first-run onboarding, which would otherwise send a new visitor to the welcome
166 // wizard and lose the link.
167 if (hostedPromptLinkLanding !== null) {
168 return (
169 <>
170 <DocumentTitleSync />
171 <BrowserChromeThemeSync key={pathname} />
172 {hostedPromptLinkLanding}
173 </>
174 );
175 }
176​
177 if (pathname === "/welcome") {
178 return (
179 <ToastProvider>
180 <AnchoredToastProvider>
181 <DocumentTitleSync />
182 <BrowserChromeThemeSync key={pathname} />
183 <ContrastAppearanceSync />
184 <EnvironmentThemeSync />
185 <GlassAppearanceSync />
186 <FontAppearanceSync />
187 <ProviderAuthCallbackCoordinator />
188 <CustomSnoozeDialogHost />
189 <CommandPalette>
190 <AppSidebarLayout>
191 <Outlet />
192 </AppSidebarLayout>
193 </CommandPalette>
194 </AnchoredToastProvider>
195 </ToastProvider>
196 );
197 }
198​
199 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
200 return (
201 <>
202 <DocumentTitleSync />
203 <BrowserChromeThemeSync key={pathname} />
204 <Outlet />
205 </>
206 );
207 }
208​
209 const appShell = (
210 <CommandPalette>
211 <AppSidebarLayout>
212 <Outlet />
213 </AppSidebarLayout>
214 </CommandPalette>
215 );
216​
217 return (
218 <ToastProvider>
219 <AnchoredToastProvider>
220 <DocumentTitleSync />
221 <BrowserChromeThemeSync key={pathname} />
222 <ContrastAppearanceSync />
223 <EnvironmentThemeSync />
224 <GlassAppearanceSync />
225 <FontAppearanceSync />
226 <ProviderAuthCallbackCoordinator />
227 <ChatGptWelcomeCoordinator />
228 <FirstRunGate
229 enabled={primaryEnvironmentAuthenticated}
230 hostedStatic={authGateState.status === "hosted-static"}
231 >
232 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
233 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
234 {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
235 {isElectron ? <RunningThreadKeepAlive /> : null}
236 <RelayClientInstallDialog />
237 <ConnectOnboardingDialog />
238 <SshPasswordPromptDialog />
239 <SnapShotCoordinator />
240 <ThreadNotificationCoordinator />
241 <ReopenClosedViewShortcut />
242 <ConfirmDialogHost />
243 <CustomSnoozeDialogHost />
244 <SlowRpcRequestToastCoordinator />
245 <PermissionUpdateNotice />
246 {primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}
247 <ProjectCloneToastCoordinator />
248 <PullRequestGuideRunCoordinator />
249 <HostedStaticEnvironmentBootstrap />
250 {primaryEnvironmentAuthenticated ? (
251 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
252 ) : null}
253 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
254 {isElectron ? <DesktopUpdateLaunchNotice /> : null}
255 {appShell}
256 {/* Above the router: a theme draft is judged by walking the app, so the
257 editor has to survive navigation away from settings. */}
258 <ThemeEditorHost />
259 </FirstRunGate>
260 </AnchoredToastProvider>
261 </ToastProvider>
262 );
264​
265function EnvironmentThemeSync() {
266 useEnvironmentThemeSync();
267 // Ordered after the palette sync so a first-run client adopting the
268 // environment's own theme finds it already in the library.
269 useDefaultThemeAdoption();
270 return null;
272​
273function ContrastAppearanceSync() {
274 const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
275 const diffColorScheme = useClientSettings((settings) => settings.diffColorScheme);
276​
277 useEffect(() => {
278 document.documentElement.dataset.diffColorScheme = diffColorScheme;
279 }, [diffColorScheme]);
280​
281 const chatWidth = useClientSettings((settings) => settings.chatWidth);
282 useEffect(() => {
283 document.documentElement.dataset.chatWidth = chatWidth;
284 }, [chatWidth]);
285​
286 useEffect(() => {
287 applyAppearanceContrast(document.documentElement, appearanceContrast);
288 }, [appearanceContrast]);
289​
290 return null;
292​
293function GlassAppearanceSync() {
294 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
295​
296 useEffect(() => {
297 const style = document.documentElement.style;
298 style.setProperty("--glass-opacity", `${glassOpacity}%`);
299 if (glassOpacity === 100) {
300 style.setProperty("--glass-blur", "0px");
301 } else {
302 style.removeProperty("--glass-blur");
303 }
304 }, [glassOpacity]);
305​
306 return null;
308​
309function FontAppearanceSync() {
310 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
311 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
312 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
313 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
314 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
315 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
316 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
317​
318 useEffect(() => {
319 applyAppearanceFontVariables(document.documentElement, {
320 sans: fontFamilySans,
321 code: fontFamilyCode,
322 composer: fontFamilyComposer,
323 sizeInterface: fontSizeInterface,
324 sizePrompt: fontSizePrompt,
325 sizeCode: fontSizeCode,
326 smoothing: fontSmoothing,
327 });
328 }, [
329 fontFamilyCode,
330 fontFamilyComposer,
331 fontFamilySans,
332 fontSizeCode,
333 fontSizeInterface,
334 fontSizePrompt,
335 fontSmoothing,
336 ]);
337​
338 return null;
340​
341/** Keyed by pathname: each route paints its own surface, which the browser chrome samples. */
342function BrowserChromeThemeSync() {
343 useEffect(() => {
344 const frame = window.requestAnimationFrame(() => {
345 syncBrowserChromeTheme();
346 });
347 return () => {
348 window.cancelAnimationFrame(frame);
349 };
350 }, []);
351 return null;
353​
354function DocumentTitleSync() {
355 const primaryServerVersion =
356 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
357 const title = resolveServerBackedAppDisplayName({
358 baseName: APP_BASE_NAME,
359 fallbackDisplayName: APP_DISPLAY_NAME,
360 fallbackStageLabel: APP_STAGE_LABEL,
361 primaryServerVersion,
362 });
363​
364 useEffect(() => {
365 document.title = title;
366 }, [title]);
367​
368 return null;
370​
371function HostedStaticEnvironmentBootstrap() {
372 const { environments } = useEnvironments();
373 const activeEnvironmentId = useActiveEnvironmentId();
374​
375 useEffect(() => {
376 if (
377 environments.some(
378 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
379 )
380 ) {
381 return;
382 }
383​
384 if (activeEnvironmentId) {
385 return;
386 }
387​
388 const firstSavedEnvironment = environments[0];
389 if (!firstSavedEnvironment) {
390 return;
391 }
392​
393 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
394 }, [activeEnvironmentId, environments]);
395​
396 return null;
398​
399function RootRouteErrorView({ error }: ErrorComponentProps) {
400 const router = useRouter();
401 const message = errorMessage(error);
402 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
403 const pathname = useLocation({ select: (location) => location.pathname });
404 const report = errorReport(error, pathname);
405​
406 return (
407 <StandalonePage tone="error">
408 <StandalonePageHeader
409 eyebrow={APP_DISPLAY_NAME}
410 title="Something went wrong."
411 description={message}
412 />
413​
414 <div className="mt-5 flex flex-wrap gap-2">
415 <Button size="sm" onClick={() => void router.invalidate()}>
416 Try again
417 </Button>
418 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
419 Reload app
420 </Button>
421 <CopyErrorButton report={report} />
422 </div>
423​
424 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
425 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
426 <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">
427 {report}
428 </pre>
429 </div>
430 </StandalonePage>
431 );
433​
434function CopyErrorButton({ report }: { report: string }) {
435 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
436​
437 return (
438 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
439 <MorphIcon className={cn(isCopied && "text-success")} icon={isCopied ? Check : Copy} />
440 {isCopied ? "Copied" : "Copy error"}
441 </Button>
442 );
444​
445function errorMessage(error: unknown): string {
446 if (error instanceof Error && error.message.trim().length > 0) {
447 return error.message;
448 }
449​
450 if (typeof error === "string" && error.trim().length > 0) {
451 return error;
452 }
453​
454 return "An unexpected router error occurred.";
456​
457function errorDetails(error: unknown): string {
458 if (error instanceof Error) {
459 return error.stack ?? error.message;
460 }
461​
462 if (typeof error === "string") {
463 return error;
464 }
465​
466 try {
467 return JSON.stringify(error, null, 2);
468 } catch {
469 return "No additional error details are available.";
470 }
472​
473const MAX_ERROR_CAUSE_DEPTH = 5;
474​
475/**
476 * Takes the pathname only so tokens in the query never land on the clipboard.
477 */
478function errorReport(error: unknown, pathname: string): string {
479 const lines = [
480 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
481 `Path: ${pathname}`,
482 `Time: ${new Date().toISOString()}`,
483 "",
484 errorDetails(error),
485 ];
486 let cause = error instanceof Error ? error.cause : undefined;
487 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
488 lines.push("", "Caused by:", errorDetails(cause));
489 cause = cause instanceof Error ? cause.cause : undefined;
490 }
491 return lines.join("\n");
493​
494function AuthenticatedTracingBootstrap() {
495 useEffect(() => {
496 void configureClientTracing();
497 }, []);
498​
499 return null;
501​
502function EventRouter({
503 skipInitialBootstrapNavigation,
504}: {
505 readonly skipInitialBootstrapNavigation: boolean;
506}) {
507 const navigate = useNavigate();
508 const pathname = useLocation({ select: (loc) => loc.pathname });
509 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
510 const primaryEnvironment = usePrimaryEnvironment();
511 const serverConfig = useAtomValue(primaryServerConfigAtom);
512 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
513 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
514 const readPathname = useEffectEvent(() => pathname);
515 const handledBootstrapThreadIdRef = useRef<string | null>(null);
516 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
517 const handledConfigEventRef = useRef(serverConfigEvent);
518 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
519 createKeybindingsUpdateToastController({}),
520 );
521​
522 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
523 if (!payload) return;
524​
525 setActiveEnvironmentId(payload.environment.environmentId);
526 void (async () => {
527 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
528 return;
529 }
530 const bootstrapProject = readProject(
531 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
532 );
533 const bootstrapProjectKey =
534 (bootstrapProject
535 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
536 : null) ??
537 (serverConfig?.cwd
538 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
539 : null) ??
540 scopedProjectKey(
541 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
542 );
543 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
544​
545 if (readPathname() !== "/") {
546 return;
547 }
548 if (skipInitialBootstrapNavigationRef.current) {
549 skipInitialBootstrapNavigationRef.current = false;
550 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
551 return;
552 }
553 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
554 return;
555 }
556 await navigate({
557 to: "/$environmentId/$threadId",
558 params: {
559 environmentId: payload.environment.environmentId,
560 threadId: payload.bootstrapThreadId,
561 },
562 replace: true,
563 });
564 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
565 })().catch(() => undefined);
566 });
567​
568 const handleServerConfigUpdated = useEffectEvent(() => {
569 const decision = keybindingsToastController.handle(serverConfigEvent);
570 if (!decision) {
571 return;
572 }
573​
574 if (decision._tag === "Success") {
575 toastManager.add({
576 type: "success",
577 title: "Keybindings updated",
578 description: "Keybindings configuration reloaded successfully.",
579 });
580 return;
581 }
582​
583 toastManager.add(
584 stackedThreadToast({
585 type: "warning",
586 title: "Invalid keybindings configuration",
587 description: (
588 <KeybindingsConfigWarning
589 message={decision.message}
590 environmentId={primaryEnvironment?.environmentId ?? null}
591 configPath={serverConfig?.keybindingsConfigPath ?? null}
592 availableEditors={serverConfig?.availableEditors ?? []}
593 />
594 ),
595 }),
596 );
597 });
598​
599 useEffect(() => {
600 if (!serverConfig) {
601 return;
602 }
603​
604 setActiveEnvironmentId(serverConfig.environment.environmentId);
605 }, [serverConfig]);
606​
607 useEffect(() => {
608 handleWelcome(serverWelcome);
609 }, [serverWelcome]);
610​
611 useEffect(() => {
612 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
613 return;
614 }
615 handledConfigEventRef.current = serverConfigEvent;
616 handleServerConfigUpdated();
617 }, [serverConfigEvent]);
618​
619 return null;