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

__root.tsx

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