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

__root.tsx

627 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 { 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 const chatWidth = useClientSettings((settings) => settings.chatWidth);
268 useEffect(() => {
269 document.documentElement.dataset.chatWidth = chatWidth;
270 }, [chatWidth]);
271​
272 useEffect(() => {
273 applyAppearanceContrast(document.documentElement, appearanceContrast);
274 }, [appearanceContrast]);
275​
276 return null;
278​
279function GlassAppearanceSync() {
280 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
281​
282 useEffect(() => {
283 const style = document.documentElement.style;
284 style.setProperty("--glass-opacity", `${glassOpacity}%`);
285 if (glassOpacity === 100) {
286 style.setProperty("--glass-blur", "0px");
287 } else {
288 style.removeProperty("--glass-blur");
289 }
290 }, [glassOpacity]);
291​
292 return null;
294​
295function FontAppearanceSync() {
296 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
297 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
298 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
299 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
300 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
301 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
302 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
303​
304 useEffect(() => {
305 applyAppearanceFontVariables(document.documentElement, {
306 sans: fontFamilySans,
307 code: fontFamilyCode,
308 composer: fontFamilyComposer,
309 sizeInterface: fontSizeInterface,
310 sizePrompt: fontSizePrompt,
311 sizeCode: fontSizeCode,
312 smoothing: fontSmoothing,
313 });
314 }, [
315 fontFamilyCode,
316 fontFamilyComposer,
317 fontFamilySans,
318 fontSizeCode,
319 fontSizeInterface,
320 fontSizePrompt,
321 fontSmoothing,
322 ]);
323​
324 return null;
326​
327function DocumentTitleSync() {
328 const primaryServerVersion =
329 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
330 const title = resolveServerBackedAppDisplayName({
331 baseName: APP_BASE_NAME,
332 fallbackDisplayName: APP_DISPLAY_NAME,
333 fallbackStageLabel: APP_STAGE_LABEL,
334 primaryServerVersion,
335 });
336​
337 useEffect(() => {
338 document.title = title;
339 }, [title]);
340​
341 return null;
343​
344function HostedStaticEnvironmentBootstrap() {
345 const { environments } = useEnvironments();
346 const activeEnvironmentId = useActiveEnvironmentId();
347​
348 useEffect(() => {
349 if (
350 environments.some(
351 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
352 )
353 ) {
354 return;
355 }
356​
357 if (activeEnvironmentId) {
358 return;
359 }
360​
361 const firstSavedEnvironment = environments[0];
362 if (!firstSavedEnvironment) {
363 return;
364 }
365​
366 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
367 }, [activeEnvironmentId, environments]);
368​
369 return null;
371​
372function RootRouteErrorView({ error }: ErrorComponentProps) {
373 const router = useRouter();
374 const message = errorMessage(error);
375 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
376 const pathname = useLocation({ select: (location) => location.pathname });
377 const report = useMemo(() => errorReport(error, pathname), [error, pathname]);
378​
379 return (
380 <StandalonePage tone="error">
381 <StandalonePageHeader
382 eyebrow={APP_DISPLAY_NAME}
383 title="Something went wrong."
384 description={message}
385 />
386​
387 <div className="mt-5 flex flex-wrap gap-2">
388 <Button size="sm" onClick={() => void router.invalidate()}>
389 Try again
390 </Button>
391 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
392 Reload app
393 </Button>
394 <CopyErrorButton report={report} />
395 </div>
396​
397 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
398 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
399 <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">
400 {report}
401 </pre>
402 </div>
403 </StandalonePage>
404 );
406​
407/** Copies the full error report and swaps to a check mark for a moment as confirmation. */
408function CopyErrorButton({ report }: { report: string }) {
409 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
410​
411 return (
412 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
413 {isCopied ? <CheckIcon className="text-success" /> : <CopyIcon />}
414 {isCopied ? "Copied" : "Copy error"}
415 </Button>
416 );
418​
419function errorMessage(error: unknown): string {
420 if (error instanceof Error && error.message.trim().length > 0) {
421 return error.message;
422 }
423​
424 if (typeof error === "string" && error.trim().length > 0) {
425 return error;
426 }
427​
428 return "An unexpected router error occurred.";
430​
431function errorDetails(error: unknown): string {
432 if (error instanceof Error) {
433 return error.stack ?? error.message;
434 }
435​
436 if (typeof error === "string") {
437 return error;
438 }
439​
440 try {
441 return JSON.stringify(error, null, 2);
442 } catch {
443 return "No additional error details are available.";
444 }
446​
447const MAX_ERROR_CAUSE_DEPTH = 5;
448​
449/**
450 * Full error text for bug reports: app build, page path, time, then the stack
451 * and any cause chain. Takes the pathname only so tokens in the query never
452 * land on the clipboard.
453 */
454function errorReport(error: unknown, pathname: string): string {
455 const lines = [
456 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
457 `Path: ${pathname}`,
458 `Time: ${new Date().toISOString()}`,
459 "",
460 errorDetails(error),
461 ];
462 let cause = error instanceof Error ? error.cause : undefined;
463 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
464 lines.push("", "Caused by:", errorDetails(cause));
465 cause = cause instanceof Error ? cause.cause : undefined;
466 }
467 return lines.join("\n");
469​
470function AuthenticatedTracingBootstrap() {
471 useEffect(() => {
472 void configureClientTracing();
473 }, []);
474​
475 return null;
477​
478function EventRouter({
479 skipInitialBootstrapNavigation,
480}: {
481 readonly skipInitialBootstrapNavigation: boolean;
482}) {
483 const navigate = useNavigate();
484 const pathname = useLocation({ select: (loc) => loc.pathname });
485 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
486 const primaryEnvironment = usePrimaryEnvironment();
487 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
488 reportFailure: false,
489 });
490 const serverConfig = useAtomValue(primaryServerConfigAtom);
491 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
492 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
493 const readPathname = useEffectEvent(() => pathname);
494 const handledBootstrapThreadIdRef = useRef<string | null>(null);
495 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
496 const handledConfigEventRef = useRef(serverConfigEvent);
497 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
498 createKeybindingsUpdateToastController({}),
499 );
500​
501 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
502 if (!payload) return;
503​
504 setActiveEnvironmentId(payload.environment.environmentId);
505 void (async () => {
506 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
507 return;
508 }
509 const bootstrapProject = readProject(
510 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
511 );
512 const bootstrapProjectKey =
513 (bootstrapProject
514 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
515 : null) ??
516 (serverConfig?.cwd
517 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
518 : null) ??
519 scopedProjectKey(
520 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
521 );
522 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
523​
524 if (readPathname() !== "/") {
525 return;
526 }
527 if (skipInitialBootstrapNavigationRef.current) {
528 skipInitialBootstrapNavigationRef.current = false;
529 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
530 return;
531 }
532 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
533 return;
534 }
535 await navigate({
536 to: "/$environmentId/$threadId",
537 params: {
538 environmentId: payload.environment.environmentId,
539 threadId: payload.bootstrapThreadId,
540 },
541 replace: true,
542 });
543 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
544 })().catch(() => undefined);
545 });
546​
547 const handleServerConfigUpdated = useEffectEvent(() => {
548 const decision = keybindingsToastController.handle(serverConfigEvent);
549 if (!decision) {
550 return;
551 }
552​
553 if (decision._tag === "Success") {
554 toastManager.add({
555 type: "success",
556 title: "Keybindings updated",
557 description: "Keybindings configuration reloaded successfully.",
558 });
559 return;
560 }
561​
562 toastManager.add(
563 stackedThreadToast({
564 type: "warning",
565 title: "Invalid keybindings configuration",
566 description: decision.message,
567 actionVariant: "outline",
568 actionProps: {
569 children: "Open keybindings.json",
570 onClick: () => {
571 if (!serverConfig || !primaryEnvironment) {
572 return;
573 }
574​
575 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
576 if (!editor) {
577 return;
578 }
579 void (async () => {
580 const result = await openInEditor({
581 environmentId: primaryEnvironment.environmentId,
582 input: {
583 cwd: serverConfig.keybindingsConfigPath,
584 editor,
585 },
586 });
587 if (result._tag === "Success") {
588 return;
589 }
590 const error = squashAtomCommandFailure(result);
591 toastManager.add(
592 stackedThreadToast({
593 type: "error",
594 title: "Unable to open keybindings file",
595 description:
596 error instanceof Error ? error.message : "Unknown error opening file.",
597 }),
598 );
599 })();
600 },
601 },
602 }),
603 );
604 });
605​
606 useEffect(() => {
607 if (!serverConfig) {
608 return;
609 }
610​
611 setActiveEnvironmentId(serverConfig.environment.environmentId);
612 }, [serverConfig]);
613​
614 useEffect(() => {
615 handleWelcome(serverWelcome);
616 }, [serverWelcome]);
617​
618 useEffect(() => {
619 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
620 return;
621 }
622 handledConfigEventRef.current = serverConfigEvent;
623 handleServerConfigUpdated();
624 }, [serverConfigEvent]);
625​
626 return null;