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

__root.tsx

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