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

__root.tsx

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