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

__root.tsx

624 lines21.4 KB

1import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import {
5 Outlet,
6 Link,
7 redirect,
8 createRootRoute,
9 type ErrorComponentProps,
10 useLocation,
11 useNavigate,
12 useRouter,
13} from "@tanstack/react-router";
14import { CheckIcon, CopyIcon } from "lucide-react";
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 { ConfirmDialogHost } from "../components/ConfirmDialogHost";
22import { FirstRunGate } from "../components/onboarding/FirstRunGate";
23import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
24import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
25import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
26import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
27import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
28import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
29import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";
30import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
31import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
32import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
33import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
34import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
35import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
36import { Button } from "../components/ui/button";
37import {
38 AnchoredToastProvider,
39 stackedThreadToast,
40 ToastProvider,
41 toastManager,
42} from "../components/ui/toast";
43import { resolveAndPersistPreferredEditor } from "../editorPreferences";
44import { applyAppearanceFontVariables } from "~/appearanceFonts";
45import { applyAppearanceContrast } from "~/appearanceContrast";
46import { useClientSettings } from "../hooks/useSettings";
47import { PlanAgentSelectionHeal } from "../planAgentSelectionHeal";
48import {
49 deriveLogicalProjectKeyFromSettings,
50 derivePhysicalProjectKeyFromPath,
51 selectProjectGroupingSettings,
52} from "../logicalProject";
53import { useUiStateStore } from "../uiStateStore";
54import { syncBrowserChromeTheme } from "../hooks/useTheme";
55import { configureClientTracing } from "../observability/clientTracing";
56import { resolveInitialServerAuthGateState } from "../environments/primary";
57import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
58import { isLocalEnvironmentDisabled } from "../localEnvironment";
59import { shellEnvironment } from "../state/shell";
60import { useAtomValue } from "@effect/atom-react";
61import { useAtomCommand } from "../state/use-atom-command";
62import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
63import {
64 primaryServerConfigAtom,
65 primaryServerConfigEventAtom,
66 primaryServerWelcomeAtom,
67} from "../state/server";
68import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
69import {
70 createKeybindingsUpdateToastController,
71 type KeybindingsUpdateToastController,
72} from "../components/KeybindingsUpdateToast.logic";
73​
74import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
75import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
76import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
77​
78export const Route = createRootRoute({
79 beforeLoad: async ({ location }) => {
80 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
81 return {
82 authGateState: {
83 status: "hosted-pairing",
84 } as const,
85 };
86 }
87​
88 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
89 return {
90 authGateState: {
91 status: "hosted-static",
92 } as const,
93 };
94 }
95​
96 const authGateState = await resolveInitialServerAuthGateState();
97 if (
98 authGateState.status === "authenticated" &&
99 getDesktopSnapShotBridge() &&
100 shouldResumeSnapShotSetupOnStartup() &&
101 location.pathname !== "/settings/snap-shot"
102 ) {
103 throw redirect({ to: "/settings/snap-shot", replace: true });
104 }
105 return {
106 authGateState,
107 };
108 },
109 component: RootRouteView,
110 errorComponent: RootRouteErrorView,
111 notFoundComponent: RootRouteNotFoundView,
112 head: () => ({
113 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
114 }),
115});
116​
117function RootRouteNotFoundView() {
118 return (
119 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
120 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
121 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
122 <p className="text-sm text-muted-foreground">
123 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
124 start a thread.
125 </p>
126 <Button render={<Link to="/" replace />}>Go home</Button>
127 </div>
128 </main>
129 );
131​
132function RootRouteView() {
133 useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
134 const pathname = useLocation({ select: (location) => location.pathname });
135 const { authGateState } = Route.useRouteContext();
136 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
137 const returningFromWelcomeRef = useRef(pathname === "/welcome");
138​
139 useEffect(() => {
140 if (pathname === "/welcome") {
141 returningFromWelcomeRef.current = true;
142 }
143 }, [pathname]);
144​
145 useEffect(() => {
146 const frame = window.requestAnimationFrame(() => {
147 syncBrowserChromeTheme();
148 });
149 return () => {
150 window.cancelAnimationFrame(frame);
151 };
152 }, [pathname]);
153​
154 if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {
155 return (
156 <>
157 <DocumentTitleSync />
158 <Outlet />
159 </>
160 );
161 }
162​
163 // Show onboarding over the workspace, keeping automatic thread navigation
164 // and other startup dialogs suspended until setup finishes.
165 if (pathname === "/welcome") {
166 return (
167 <ToastProvider>
168 <AnchoredToastProvider>
169 <DocumentTitleSync />
170 <ContrastAppearanceSync />
171 <EnvironmentThemeSync />
172 <GlassAppearanceSync />
173 <FontAppearanceSync />
174 <CommandPalette>
175 <AppSidebarLayout>
176 <Outlet />
177 </AppSidebarLayout>
178 </CommandPalette>
179 </AnchoredToastProvider>
180 </ToastProvider>
181 );
182 }
183​
184 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
185 return (
186 <>
187 <DocumentTitleSync />
188 <Outlet />
189 </>
190 );
191 }
192​
193 const appShell = (
194 <CommandPalette>
195 <AppSidebarLayout>
196 <Outlet />
197 </AppSidebarLayout>
198 </CommandPalette>
199 );
200​
201 // FirstRunGate holds back everything below it — including EventRouter,
202 // whose welcome payload navigates into a thread — until the first-run
203 // decision is known, so a fresh install renders nothing (not the shell,
204 // not a flash of threads) before landing on the welcome wizard.
205 return (
206 <ToastProvider>
207 <AnchoredToastProvider>
208 <DocumentTitleSync />
209 <ContrastAppearanceSync />
210 <EnvironmentThemeSync />
211 <GlassAppearanceSync />
212 <FontAppearanceSync />
213 <FirstRunGate
214 enabled={primaryEnvironmentAuthenticated}
215 hostedStatic={authGateState.status === "hosted-static"}
216 >
217 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
218 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
219 <RelayClientInstallDialog />
220 <ConnectOnboardingDialog />
221 <SshPasswordPromptDialog />
222 <SnapShotCoordinator />
223 <ThreadNotificationCoordinator />
224 <ConfirmDialogHost />
225 <SlowRpcRequestToastCoordinator />
226 <ProjectCloneToastCoordinator />
227 <HostedStaticEnvironmentBootstrap />
228 {primaryEnvironmentAuthenticated ? (
229 <EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
230 ) : null}
231 {primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}
232 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
233 {appShell}
234 {/* Above the router: a theme draft is judged by walking the app, so the
235 editor has to survive navigation away from settings. */}
236 <ThemeEditorHost />
237 </FirstRunGate>
238 </AnchoredToastProvider>
239 </ToastProvider>
240 );
242​
243/** Follows the palette the primary environment's machine publishes, if any. */
244function EnvironmentThemeSync() {
245 useEnvironmentThemeSync();
246 // Ordered after the palette sync so a first-run client adopting the
247 // environment's own theme finds it already in the library.
248 useDefaultThemeAdoption();
249 return null;
251​
252function ContrastAppearanceSync() {
253 const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
254 const diffColorScheme = useClientSettings((settings) => settings.diffColorScheme);
255​
256 useEffect(() => {
257 document.documentElement.dataset.diffColorScheme = diffColorScheme;
258 }, [diffColorScheme]);
259​
260 useEffect(() => {
261 applyAppearanceContrast(document.documentElement, appearanceContrast);
262 }, [appearanceContrast]);
263​
264 return null;
266​
267function GlassAppearanceSync() {
268 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
269​
270 useEffect(() => {
271 const style = document.documentElement.style;
272 style.setProperty("--glass-opacity", `${glassOpacity}%`);
273 if (glassOpacity === 100) {
274 style.setProperty("--glass-blur", "0px");
275 } else {
276 style.removeProperty("--glass-blur");
277 }
278 }, [glassOpacity]);
279​
280 return null;
282​
283function FontAppearanceSync() {
284 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
285 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
286 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
287 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
288 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
289 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
290 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
291​
292 useEffect(() => {
293 applyAppearanceFontVariables(document.documentElement, {
294 sans: fontFamilySans,
295 code: fontFamilyCode,
296 composer: fontFamilyComposer,
297 sizeInterface: fontSizeInterface,
298 sizePrompt: fontSizePrompt,
299 sizeCode: fontSizeCode,
300 smoothing: fontSmoothing,
301 });
302 }, [
303 fontFamilyCode,
304 fontFamilyComposer,
305 fontFamilySans,
306 fontSizeCode,
307 fontSizeInterface,
308 fontSizePrompt,
309 fontSmoothing,
310 ]);
311​
312 return null;
314​
315function DocumentTitleSync() {
316 const primaryServerVersion =
317 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
318 const title = resolveServerBackedAppDisplayName({
319 baseName: APP_BASE_NAME,
320 fallbackDisplayName: APP_DISPLAY_NAME,
321 fallbackStageLabel: APP_STAGE_LABEL,
322 primaryServerVersion,
323 });
324​
325 useEffect(() => {
326 document.title = title;
327 }, [title]);
328​
329 return null;
331​
332function HostedStaticEnvironmentBootstrap() {
333 const { environments } = useEnvironments();
334 const activeEnvironmentId = useActiveEnvironmentId();
335​
336 useEffect(() => {
337 if (
338 environments.some(
339 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
340 )
341 ) {
342 return;
343 }
344​
345 if (activeEnvironmentId) {
346 return;
347 }
348​
349 const firstSavedEnvironment = environments[0];
350 if (!firstSavedEnvironment) {
351 return;
352 }
353​
354 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
355 }, [activeEnvironmentId, environments]);
356​
357 return null;
359​
360function RootRouteErrorView({ error }: ErrorComponentProps) {
361 const router = useRouter();
362 const message = errorMessage(error);
363 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
364 const pathname = useLocation({ select: (location) => location.pathname });
365 const report = useMemo(() => errorReport(error, pathname), [error, pathname]);
366​
367 return (
368 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
369 <div className="pointer-events-none absolute inset-0 opacity-80">
370 <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
371 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
372 </div>
373​
374 <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
375 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
376 {APP_DISPLAY_NAME}
377 </p>
378 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
379 Something went wrong.
380 </h1>
381 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
382​
383 <div className="mt-5 flex flex-wrap gap-2">
384 <Button size="sm" onClick={() => void router.invalidate()}>
385 Try again
386 </Button>
387 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
388 Reload app
389 </Button>
390 <CopyErrorButton report={report} />
391 </div>
392​
393 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
394 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
395 <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">
396 {report}
397 </pre>
398 </div>
399 </section>
400 </div>
401 );
403​
404/** Copies the full error report and swaps to a check mark for a moment as confirmation. */
405function CopyErrorButton({ report }: { report: string }) {
406 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
407​
408 return (
409 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
410 {isCopied ? <CheckIcon className="text-success" /> : <CopyIcon />}
411 {isCopied ? "Copied" : "Copy error"}
412 </Button>
413 );
415​
416function errorMessage(error: unknown): string {
417 if (error instanceof Error && error.message.trim().length > 0) {
418 return error.message;
419 }
420​
421 if (typeof error === "string" && error.trim().length > 0) {
422 return error;
423 }
424​
425 return "An unexpected router error occurred.";
427​
428function errorDetails(error: unknown): string {
429 if (error instanceof Error) {
430 return error.stack ?? error.message;
431 }
432​
433 if (typeof error === "string") {
434 return error;
435 }
436​
437 try {
438 return JSON.stringify(error, null, 2);
439 } catch {
440 return "No additional error details are available.";
441 }
443​
444const MAX_ERROR_CAUSE_DEPTH = 5;
445​
446/**
447 * Full error text for bug reports: app build, page path, time, then the stack
448 * and any cause chain. Takes the pathname only so tokens in the query never
449 * land on the clipboard.
450 */
451function errorReport(error: unknown, pathname: string): string {
452 const lines = [
453 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
454 `Path: ${pathname}`,
455 `Time: ${new Date().toISOString()}`,
456 "",
457 errorDetails(error),
458 ];
459 let cause = error instanceof Error ? error.cause : undefined;
460 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
461 lines.push("", "Caused by:", errorDetails(cause));
462 cause = cause instanceof Error ? cause.cause : undefined;
463 }
464 return lines.join("\n");
466​
467function AuthenticatedTracingBootstrap() {
468 useEffect(() => {
469 void configureClientTracing();
470 }, []);
471​
472 return null;
474​
475function EventRouter({
476 skipInitialBootstrapNavigation,
477}: {
478 readonly skipInitialBootstrapNavigation: boolean;
479}) {
480 const navigate = useNavigate();
481 const pathname = useLocation({ select: (loc) => loc.pathname });
482 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
483 const primaryEnvironment = usePrimaryEnvironment();
484 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
485 reportFailure: false,
486 });
487 const serverConfig = useAtomValue(primaryServerConfigAtom);
488 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
489 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
490 const readPathname = useEffectEvent(() => pathname);
491 const handledBootstrapThreadIdRef = useRef<string | null>(null);
492 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
493 const handledConfigEventRef = useRef(serverConfigEvent);
494 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
495 createKeybindingsUpdateToastController({}),
496 );
497​
498 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
499 if (!payload) return;
500​
501 setActiveEnvironmentId(payload.environment.environmentId);
502 void (async () => {
503 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
504 return;
505 }
506 const bootstrapProject = readProject(
507 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
508 );
509 const bootstrapProjectKey =
510 (bootstrapProject
511 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
512 : null) ??
513 (serverConfig?.cwd
514 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
515 : null) ??
516 scopedProjectKey(
517 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
518 );
519 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
520​
521 if (readPathname() !== "/") {
522 return;
523 }
524 if (skipInitialBootstrapNavigationRef.current) {
525 skipInitialBootstrapNavigationRef.current = false;
526 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
527 return;
528 }
529 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
530 return;
531 }
532 await navigate({
533 to: "/$environmentId/$threadId",
534 params: {
535 environmentId: payload.environment.environmentId,
536 threadId: payload.bootstrapThreadId,
537 },
538 replace: true,
539 });
540 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
541 })().catch(() => undefined);
542 });
543​
544 const handleServerConfigUpdated = useEffectEvent(() => {
545 const decision = keybindingsToastController.handle(serverConfigEvent);
546 if (!decision) {
547 return;
548 }
549​
550 if (decision._tag === "Success") {
551 toastManager.add({
552 type: "success",
553 title: "Keybindings updated",
554 description: "Keybindings configuration reloaded successfully.",
555 });
556 return;
557 }
558​
559 toastManager.add(
560 stackedThreadToast({
561 type: "warning",
562 title: "Invalid keybindings configuration",
563 description: decision.message,
564 actionVariant: "outline",
565 actionProps: {
566 children: "Open keybindings.json",
567 onClick: () => {
568 if (!serverConfig || !primaryEnvironment) {
569 return;
570 }
571​
572 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
573 if (!editor) {
574 return;
575 }
576 void (async () => {
577 const result = await openInEditor({
578 environmentId: primaryEnvironment.environmentId,
579 input: {
580 cwd: serverConfig.keybindingsConfigPath,
581 editor,
582 },
583 });
584 if (result._tag === "Success") {
585 return;
586 }
587 const error = squashAtomCommandFailure(result);
588 toastManager.add(
589 stackedThreadToast({
590 type: "error",
591 title: "Unable to open keybindings file",
592 description:
593 error instanceof Error ? error.message : "Unknown error opening file.",
594 }),
595 );
596 })();
597 },
598 },
599 }),
600 );
601 });
602​
603 useEffect(() => {
604 if (!serverConfig) {
605 return;
606 }
607​
608 setActiveEnvironmentId(serverConfig.environment.environmentId);
609 }, [serverConfig]);
610​
611 useEffect(() => {
612 handleWelcome(serverWelcome);
613 }, [serverWelcome]);
614​
615 useEffect(() => {
616 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
617 return;
618 }
619 handledConfigEventRef.current = serverConfigEvent;
620 handleServerConfigUpdated();
621 }, [serverConfigEvent]);
622​
623 return null;