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

__root.tsx

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