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

__root.tsx

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