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

__root.tsx

622 lines20.9 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 { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
22import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
23import { FirstRunGate } from "../components/onboarding/FirstRunGate";
24import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
25import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
26import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
27import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
28import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
29import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
30import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
31import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";
32import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
33import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
34import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
35import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
36import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
37import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
38import { Button } from "../components/ui/button";
39import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
40import {
41 AnchoredToastProvider,
42 stackedThreadToast,
43 ToastProvider,
44 toastManager,
45} from "../components/ui/toast";
46import { resolveAndPersistPreferredEditor } from "../editorPreferences";
47import { isElectron } from "../env";
48import { applyAppearanceFontVariables } from "~/appearanceFonts";
49import { applyAppearanceContrast } from "~/appearanceContrast";
50import { useClientSettings } from "../hooks/useSettings";
51import { PlanAgentSelectionHeal } from "../planAgentSelectionHeal";
52import {
53 deriveLogicalProjectKeyFromSettings,
54 derivePhysicalProjectKeyFromPath,
55 selectProjectGroupingSettings,
56} from "../logicalProject";
57import { useUiStateStore } from "../uiStateStore";
58import { syncBrowserChromeTheme } from "../hooks/useTheme";
59import { configureClientTracing } from "../observability/clientTracing";
60import { resolveInitialServerAuthGateState } from "../environments/primary";
61import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
62import { isLocalEnvironmentDisabled } from "../localEnvironment";
63import { shellEnvironment } from "../state/shell";
64import { useAtomValue } from "@effect/atom-react";
65import { useAtomCommand } from "../state/use-atom-command";
66import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
67import {
68 primaryServerConfigAtom,
69 primaryServerConfigEventAtom,
70 primaryServerWelcomeAtom,
71} from "../state/server";
72import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
73import {
74 createKeybindingsUpdateToastController,
75 type KeybindingsUpdateToastController,
76} from "../components/KeybindingsUpdateToast.logic";
77​
78import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
79import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
80import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
81​
82export const Route = createRootRoute({
83 beforeLoad: async ({ location }) => {
84 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
85 return {
86 authGateState: {
87 status: "hosted-pairing",
88 } as const,
89 };
90 }
91​
92 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
93 return {
94 authGateState: {
95 status: "hosted-static",
96 } as const,
97 };
98 }
99​
100 const authGateState = await resolveInitialServerAuthGateState();
101 if (
102 authGateState.status === "authenticated" &&
103 getDesktopSnapShotBridge() &&
104 shouldResumeSnapShotSetupOnStartup() &&
105 location.pathname !== "/settings/snap-shot"
106 ) {
107 throw redirect({ to: "/settings/snap-shot", replace: true });
108 }
109 return {
110 authGateState,
111 };
112 },
113 component: RootRouteView,
114 errorComponent: RootRouteErrorView,
115 notFoundComponent: RootRouteNotFoundView,
116 head: () => ({
117 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
118 }),
119});
120​
121function RootRouteNotFoundView() {
122 return (
123 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
124 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
125 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
126 <p className="text-sm text-muted-foreground">
127 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
128 start a thread.
129 </p>
130 <Button render={<Link to="/" replace />}>Go home</Button>
131 </div>
132 </main>
133 );
135​
136function RootRouteView() {
137 useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
138 const pathname = useLocation({ select: (location) => location.pathname });
139 const { authGateState } = Route.useRouteContext();
140 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
141 const returningFromWelcomeRef = useRef(pathname === "/welcome");
142​
143 useEffect(() => {
144 if (pathname === "/welcome") {
145 returningFromWelcomeRef.current = true;
146 }
147 }, [pathname]);
148​
149 useEffect(() => {
150 const frame = window.requestAnimationFrame(() => {
151 syncBrowserChromeTheme();
152 });
153 return () => {
154 window.cancelAnimationFrame(frame);
155 };
156 }, [pathname]);
157​
158 if (pathname === "/pair" || pathname === "/connect") {
159 return (
160 <>
161 <DocumentTitleSync />
162 <Outlet />
163 </>
164 );
165 }
166​
167 // Show onboarding over the workspace, keeping automatic thread navigation
168 // and other startup dialogs suspended until setup finishes.
169 if (pathname === "/welcome") {
170 return (
171 <ToastProvider>
172 <AnchoredToastProvider>
173 <DocumentTitleSync />
174 <ContrastAppearanceSync />
175 <EnvironmentThemeSync />
176 <GlassAppearanceSync />
177 <FontAppearanceSync />
178 <CustomSnoozeDialogHost />
179 <CommandPalette>
180 <AppSidebarLayout>
181 <Outlet />
182 </AppSidebarLayout>
183 </CommandPalette>
184 </AnchoredToastProvider>
185 </ToastProvider>
186 );
187 }
188​
189 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
190 return (
191 <>
192 <DocumentTitleSync />
193 <Outlet />
194 </>
195 );
196 }
197​
198 const appShell = (
199 <CommandPalette>
200 <AppSidebarLayout>
201 <Outlet />
202 </AppSidebarLayout>
203 </CommandPalette>
204 );
205​
206 // FirstRunGate holds back everything below it — including EventRouter,
207 // whose welcome payload navigates into a thread — until the first-run
208 // decision is known, so a fresh install renders nothing (not the shell,
209 // not a flash of threads) before landing on the welcome wizard.
210 return (
211 <ToastProvider>
212 <AnchoredToastProvider>
213 <DocumentTitleSync />
214 <ContrastAppearanceSync />
215 <EnvironmentThemeSync />
216 <GlassAppearanceSync />
217 <FontAppearanceSync />
218 <FirstRunGate
219 enabled={primaryEnvironmentAuthenticated}
220 hostedStatic={authGateState.status === "hosted-static"}
221 >
222 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
223 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
224 {isElectron ? <RunningThreadKeepAlive /> : null}
225 <RelayClientInstallDialog />
226 <ConnectOnboardingDialog />
227 <SshPasswordPromptDialog />
228 <SnapShotCoordinator />
229 <ThreadNotificationCoordinator />
230 <ConfirmDialogHost />
231 <CustomSnoozeDialogHost />
232 <SlowRpcRequestToastCoordinator />
233 <ProjectCloneToastCoordinator />
234 <HostedStaticEnvironmentBootstrap />
235 {primaryEnvironmentAuthenticated ? (
236 <EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
237 ) : null}
238 {primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}
239 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
240 {appShell}
241 {/* Above the router: a theme draft is judged by walking the app, so the
242 editor has to survive navigation away from settings. */}
243 <ThemeEditorHost />
244 </FirstRunGate>
245 </AnchoredToastProvider>
246 </ToastProvider>
247 );
249​
250/** Follows the palette the primary environment's machine publishes, if any. */
251function EnvironmentThemeSync() {
252 useEnvironmentThemeSync();
253 // Ordered after the palette sync so a first-run client adopting the
254 // environment's own theme finds it already in the library.
255 useDefaultThemeAdoption();
256 return null;
258​
259function ContrastAppearanceSync() {
260 const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
261 const diffColorScheme = useClientSettings((settings) => settings.diffColorScheme);
262​
263 useEffect(() => {
264 document.documentElement.dataset.diffColorScheme = diffColorScheme;
265 }, [diffColorScheme]);
266​
267 useEffect(() => {
268 applyAppearanceContrast(document.documentElement, appearanceContrast);
269 }, [appearanceContrast]);
270​
271 return null;
273​
274function GlassAppearanceSync() {
275 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
276​
277 useEffect(() => {
278 const style = document.documentElement.style;
279 style.setProperty("--glass-opacity", `${glassOpacity}%`);
280 if (glassOpacity === 100) {
281 style.setProperty("--glass-blur", "0px");
282 } else {
283 style.removeProperty("--glass-blur");
284 }
285 }, [glassOpacity]);
286​
287 return null;
289​
290function FontAppearanceSync() {
291 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
292 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
293 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
294 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
295 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
296 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
297 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
298​
299 useEffect(() => {
300 applyAppearanceFontVariables(document.documentElement, {
301 sans: fontFamilySans,
302 code: fontFamilyCode,
303 composer: fontFamilyComposer,
304 sizeInterface: fontSizeInterface,
305 sizePrompt: fontSizePrompt,
306 sizeCode: fontSizeCode,
307 smoothing: fontSmoothing,
308 });
309 }, [
310 fontFamilyCode,
311 fontFamilyComposer,
312 fontFamilySans,
313 fontSizeCode,
314 fontSizeInterface,
315 fontSizePrompt,
316 fontSmoothing,
317 ]);
318​
319 return null;
321​
322function DocumentTitleSync() {
323 const primaryServerVersion =
324 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
325 const title = resolveServerBackedAppDisplayName({
326 baseName: APP_BASE_NAME,
327 fallbackDisplayName: APP_DISPLAY_NAME,
328 fallbackStageLabel: APP_STAGE_LABEL,
329 primaryServerVersion,
330 });
331​
332 useEffect(() => {
333 document.title = title;
334 }, [title]);
335​
336 return null;
338​
339function HostedStaticEnvironmentBootstrap() {
340 const { environments } = useEnvironments();
341 const activeEnvironmentId = useActiveEnvironmentId();
342​
343 useEffect(() => {
344 if (
345 environments.some(
346 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
347 )
348 ) {
349 return;
350 }
351​
352 if (activeEnvironmentId) {
353 return;
354 }
355​
356 const firstSavedEnvironment = environments[0];
357 if (!firstSavedEnvironment) {
358 return;
359 }
360​
361 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
362 }, [activeEnvironmentId, environments]);
363​
364 return null;
366​
367function RootRouteErrorView({ error }: ErrorComponentProps) {
368 const router = useRouter();
369 const message = errorMessage(error);
370 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
371 const pathname = useLocation({ select: (location) => location.pathname });
372 const report = useMemo(() => errorReport(error, pathname), [error, pathname]);
373​
374 return (
375 <StandalonePage tone="error">
376 <StandalonePageHeader
377 eyebrow={APP_DISPLAY_NAME}
378 title="Something went wrong."
379 description={message}
380 />
381​
382 <div className="mt-5 flex flex-wrap gap-2">
383 <Button size="sm" onClick={() => void router.invalidate()}>
384 Try again
385 </Button>
386 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
387 Reload app
388 </Button>
389 <CopyErrorButton report={report} />
390 </div>
391​
392 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
393 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
394 <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">
395 {report}
396 </pre>
397 </div>
398 </StandalonePage>
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;