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

__root.tsx

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