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

__root.tsx

626 lines21.6 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 { NightlyMobileBetaNotice } from "../components/NightlyMobileBeta";
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 {/* Hosted Nightly is "hosted-static", not authenticated, and needs it too. */}
269 <NightlyMobileBetaNotice />
270 {appShell}
271 {/* Above the router: a theme draft is judged by walking the app, so the
272 editor has to survive navigation away from settings. */}
273 <ThemeEditorHost />
274 </FirstRunGate>
275 </AnchoredToastProvider>
276 </ToastProvider>
277 );
279​
280/** Follows the palette the primary environment's machine publishes, if any. */
281function EnvironmentThemeSync() {
282 useEnvironmentThemeSync();
283 // Ordered after the palette sync so a first-run client adopting the
284 // environment's own theme finds it already in the library.
285 useDefaultThemeAdoption();
286 return null;
288​
289function ContrastAppearanceSync() {
290 const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
291 const diffColorScheme = useClientSettings((settings) => settings.diffColorScheme);
292​
293 useEffect(() => {
294 document.documentElement.dataset.diffColorScheme = diffColorScheme;
295 }, [diffColorScheme]);
296​
297 const chatWidth = useClientSettings((settings) => settings.chatWidth);
298 useEffect(() => {
299 document.documentElement.dataset.chatWidth = chatWidth;
300 }, [chatWidth]);
301​
302 useEffect(() => {
303 applyAppearanceContrast(document.documentElement, appearanceContrast);
304 }, [appearanceContrast]);
305​
306 return null;
308​
309function GlassAppearanceSync() {
310 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
311​
312 useEffect(() => {
313 const style = document.documentElement.style;
314 style.setProperty("--glass-opacity", `${glassOpacity}%`);
315 if (glassOpacity === 100) {
316 style.setProperty("--glass-blur", "0px");
317 } else {
318 style.removeProperty("--glass-blur");
319 }
320 }, [glassOpacity]);
321​
322 return null;
324​
325function FontAppearanceSync() {
326 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
327 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
328 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
329 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
330 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
331 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
332 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
333​
334 useEffect(() => {
335 applyAppearanceFontVariables(document.documentElement, {
336 sans: fontFamilySans,
337 code: fontFamilyCode,
338 composer: fontFamilyComposer,
339 sizeInterface: fontSizeInterface,
340 sizePrompt: fontSizePrompt,
341 sizeCode: fontSizeCode,
342 smoothing: fontSmoothing,
343 });
344 }, [
345 fontFamilyCode,
346 fontFamilyComposer,
347 fontFamilySans,
348 fontSizeCode,
349 fontSizeInterface,
350 fontSizePrompt,
351 fontSmoothing,
352 ]);
353​
354 return null;
356​
357function DocumentTitleSync() {
358 const primaryServerVersion =
359 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
360 const title = resolveServerBackedAppDisplayName({
361 baseName: APP_BASE_NAME,
362 fallbackDisplayName: APP_DISPLAY_NAME,
363 fallbackStageLabel: APP_STAGE_LABEL,
364 primaryServerVersion,
365 });
366​
367 useEffect(() => {
368 document.title = title;
369 }, [title]);
370​
371 return null;
373​
374function HostedStaticEnvironmentBootstrap() {
375 const { environments } = useEnvironments();
376 const activeEnvironmentId = useActiveEnvironmentId();
377​
378 useEffect(() => {
379 if (
380 environments.some(
381 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
382 )
383 ) {
384 return;
385 }
386​
387 if (activeEnvironmentId) {
388 return;
389 }
390​
391 const firstSavedEnvironment = environments[0];
392 if (!firstSavedEnvironment) {
393 return;
394 }
395​
396 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
397 }, [activeEnvironmentId, environments]);
398​
399 return null;
401​
402function RootRouteErrorView({ error }: ErrorComponentProps) {
403 const router = useRouter();
404 const message = errorMessage(error);
405 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
406 const pathname = useLocation({ select: (location) => location.pathname });
407 const report = useMemo(() => errorReport(error, pathname), [error, pathname]);
408​
409 return (
410 <StandalonePage tone="error">
411 <StandalonePageHeader
412 eyebrow={APP_DISPLAY_NAME}
413 title="Something went wrong."
414 description={message}
415 />
416​
417 <div className="mt-5 flex flex-wrap gap-2">
418 <Button size="sm" onClick={() => void router.invalidate()}>
419 Try again
420 </Button>
421 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
422 Reload app
423 </Button>
424 <CopyErrorButton report={report} />
425 </div>
426​
427 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
428 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
429 <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">
430 {report}
431 </pre>
432 </div>
433 </StandalonePage>
434 );
436​
437/** Copies the full error report and swaps to a check mark for a moment as confirmation. */
438function CopyErrorButton({ report }: { report: string }) {
439 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
440​
441 return (
442 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
443 <MorphIcon className={cn(isCopied && "text-success")} icon={isCopied ? Check : Copy} />
444 {isCopied ? "Copied" : "Copy error"}
445 </Button>
446 );
448​
449function errorMessage(error: unknown): string {
450 if (error instanceof Error && error.message.trim().length > 0) {
451 return error.message;
452 }
453​
454 if (typeof error === "string" && error.trim().length > 0) {
455 return error;
456 }
457​
458 return "An unexpected router error occurred.";
460​
461function errorDetails(error: unknown): string {
462 if (error instanceof Error) {
463 return error.stack ?? error.message;
464 }
465​
466 if (typeof error === "string") {
467 return error;
468 }
469​
470 try {
471 return JSON.stringify(error, null, 2);
472 } catch {
473 return "No additional error details are available.";
474 }
476​
477const MAX_ERROR_CAUSE_DEPTH = 5;
478​
479/**
480 * Full error text for bug reports: app build, page path, time, then the stack
481 * and any cause chain. Takes the pathname only so tokens in the query never
482 * land on the clipboard.
483 */
484function errorReport(error: unknown, pathname: string): string {
485 const lines = [
486 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
487 `Path: ${pathname}`,
488 `Time: ${new Date().toISOString()}`,
489 "",
490 errorDetails(error),
491 ];
492 let cause = error instanceof Error ? error.cause : undefined;
493 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
494 lines.push("", "Caused by:", errorDetails(cause));
495 cause = cause instanceof Error ? cause.cause : undefined;
496 }
497 return lines.join("\n");
499​
500function AuthenticatedTracingBootstrap() {
501 useEffect(() => {
502 void configureClientTracing();
503 }, []);
504​
505 return null;
507​
508function EventRouter({
509 skipInitialBootstrapNavigation,
510}: {
511 readonly skipInitialBootstrapNavigation: boolean;
512}) {
513 const navigate = useNavigate();
514 const pathname = useLocation({ select: (loc) => loc.pathname });
515 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
516 const primaryEnvironment = usePrimaryEnvironment();
517 const serverConfig = useAtomValue(primaryServerConfigAtom);
518 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
519 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
520 const readPathname = useEffectEvent(() => pathname);
521 const handledBootstrapThreadIdRef = useRef<string | null>(null);
522 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
523 const handledConfigEventRef = useRef(serverConfigEvent);
524 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
525 createKeybindingsUpdateToastController({}),
526 );
527​
528 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
529 if (!payload) return;
530​
531 setActiveEnvironmentId(payload.environment.environmentId);
532 void (async () => {
533 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
534 return;
535 }
536 const bootstrapProject = readProject(
537 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
538 );
539 const bootstrapProjectKey =
540 (bootstrapProject
541 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
542 : null) ??
543 (serverConfig?.cwd
544 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
545 : null) ??
546 scopedProjectKey(
547 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
548 );
549 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
550​
551 if (readPathname() !== "/") {
552 return;
553 }
554 if (skipInitialBootstrapNavigationRef.current) {
555 skipInitialBootstrapNavigationRef.current = false;
556 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
557 return;
558 }
559 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
560 return;
561 }
562 await navigate({
563 to: "/$environmentId/$threadId",
564 params: {
565 environmentId: payload.environment.environmentId,
566 threadId: payload.bootstrapThreadId,
567 },
568 replace: true,
569 });
570 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
571 })().catch(() => undefined);
572 });
573​
574 const handleServerConfigUpdated = useEffectEvent(() => {
575 const decision = keybindingsToastController.handle(serverConfigEvent);
576 if (!decision) {
577 return;
578 }
579​
580 if (decision._tag === "Success") {
581 toastManager.add({
582 type: "success",
583 title: "Keybindings updated",
584 description: "Keybindings configuration reloaded successfully.",
585 });
586 return;
587 }
588​
589 toastManager.add(
590 stackedThreadToast({
591 type: "warning",
592 title: "Invalid keybindings configuration",
593 description: (
594 <KeybindingsConfigWarning
595 message={decision.message}
596 environmentId={primaryEnvironment?.environmentId ?? null}
597 configPath={serverConfig?.keybindingsConfigPath ?? null}
598 availableEditors={serverConfig?.availableEditors ?? []}
599 />
600 ),
601 }),
602 );
603 });
604​
605 useEffect(() => {
606 if (!serverConfig) {
607 return;
608 }
609​
610 setActiveEnvironmentId(serverConfig.environment.environmentId);
611 }, [serverConfig]);
612​
613 useEffect(() => {
614 handleWelcome(serverWelcome);
615 }, [serverWelcome]);
616​
617 useEffect(() => {
618 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
619 return;
620 }
621 handledConfigEventRef.current = serverConfigEvent;
622 handleServerConfigUpdated();
623 }, [serverConfigEvent]);
624​
625 return null;