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

__root.tsx

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