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

__root.tsx

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