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

__root.tsx

625 lines21.5 KB

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