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

__root.tsx

633 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, 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 { GuestShareDialogHost } from "../components/chat/GuestShareControls";
23import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
24import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
25import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
26import { FirstRunGate } from "../components/onboarding/FirstRunGate";
27import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
28import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
29import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
30import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
31import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
32import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator";
33import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
34import { DesktopUpdateLaunchNotice } from "../components/sidebar/updateEverythingRun";
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 { HostFreezeToastCoordinator } from "../components/HostFreezeToastCoordinator";
41import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
42import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
43import { ProviderAuthCallbackCoordinator } from "../components/settings/ProviderAuthCallbackCoordinator";
44import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
45import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
46import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
47import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
48import { Button } from "../components/ui/button";
49import { MorphIcon } from "~/components/MorphIcon";
50import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
51import {
52 AnchoredToastProvider,
53 stackedThreadToast,
54 ToastProvider,
55 toastManager,
56} from "../components/ui/toast";
57import { isElectron } from "../env";
58import { cn } from "../lib/utils";
59import { applyAppearanceFontVariables } from "~/appearanceFonts";
60import { applyAppearanceContrast } from "~/appearanceContrast";
61import { useClientSettings } from "../hooks/useSettings";
62import {
63 deriveLogicalProjectKeyFromSettings,
64 derivePhysicalProjectKeyFromPath,
65 selectProjectGroupingSettings,
66} from "../logicalProject";
67import { useUiStateStore } from "../uiStateStore";
68import { syncBrowserChromeTheme } from "../hooks/useTheme";
69import { configureClientTracing } from "../observability/clientTracing";
70import { resolveInitialServerAuthGateState } from "../environments/primary";
71import { GUEST_PAGE_PATH } from "../guestPage";
72import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
73import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
74import { isLocalEnvironmentDisabled } from "../localEnvironment";
75import { useAtomValue } from "@effect/atom-react";
76import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
77import {
78 primaryServerConfigAtom,
79 primaryServerConfigEventAtom,
80 primaryServerWelcomeAtom,
81} from "../state/server";
82import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
83import {
84 createKeybindingsUpdateToastController,
85 type KeybindingsUpdateToastController,
86} from "../components/KeybindingsUpdateToast.logic";
87​
88import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
89import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
90import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
91​
92export const Route = createRootRoute({
93 beforeLoad: async ({ location }) => {
94 // Guest links open on the owner's tunnel host in a browser with no T3 session, and must
95 // not trigger pairing or an environment connection.
96 if (location.pathname === GUEST_PAGE_PATH) {
97 return {
98 authGateState: {
99 status: "guest",
100 } as const,
101 };
102 }
103​
104 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
105 return {
106 authGateState: {
107 status: "hosted-pairing",
108 } as const,
109 };
110 }
111​
112 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
113 return {
114 authGateState: {
115 status: "hosted-static",
116 } as const,
117 };
118 }
119​
120 const authGateState = await resolveInitialServerAuthGateState();
121 if (
122 authGateState.status === "authenticated" &&
123 getDesktopSnapShotBridge() &&
124 shouldResumeSnapShotSetupOnStartup() &&
125 location.pathname !== "/settings/snap-shot"
126 ) {
127 throw redirect({ to: "/settings/snap-shot", replace: true });
128 }
129 return {
130 authGateState,
131 };
132 },
133 component: RootRouteView,
134 errorComponent: RootRouteErrorView,
135 notFoundComponent: RootRouteNotFoundView,
136 head: () => ({
137 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
138 }),
139});
140​
141function RootRouteNotFoundView() {
142 return (
143 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
144 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
145 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
146 <p className="text-sm text-muted-foreground">
147 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
148 start a thread.
149 </p>
150 <Button render={<Link to="/" replace />}>Go home</Button>
151 </div>
152 </main>
153 );
155​
156function RootRouteView() {
157 useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
158 const pathname = useLocation({ select: (location) => location.pathname });
159 const { authGateState } = Route.useRouteContext();
160 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
161 // Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
162 const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
163 if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
164 const hostedPromptLinkLanding = useHostedPromptLinkLanding(
165 authGateState.status === "hosted-static",
166 );
167​
168 if (pathname === GUEST_PAGE_PATH) return <Outlet />;
169​
170 if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
171 return (
172 <>
173 <DocumentTitleSync />
174 <BrowserChromeThemeSync key={pathname} />
175 <Outlet />
176 </>
177 );
178 }
179​
180 // Handle links before onboarding redirects lose them.
181 if (hostedPromptLinkLanding !== null) {
182 return (
183 <>
184 <DocumentTitleSync />
185 <BrowserChromeThemeSync key={pathname} />
186 {hostedPromptLinkLanding}
187 </>
188 );
189 }
190​
191 if (pathname === "/welcome") {
192 return (
193 <ToastProvider>
194 <AnchoredToastProvider>
195 <DocumentTitleSync />
196 <BrowserChromeThemeSync key={pathname} />
197 <ContrastAppearanceSync />
198 <EnvironmentThemeSync />
199 <GlassAppearanceSync />
200 <FontAppearanceSync />
201 <ProviderAuthCallbackCoordinator />
202 <CustomSnoozeDialogHost />
203 <GuestShareDialogHost />
204 <CommandPalette>
205 <AppSidebarLayout>
206 <Outlet />
207 </AppSidebarLayout>
208 </CommandPalette>
209 </AnchoredToastProvider>
210 </ToastProvider>
211 );
212 }
213​
214 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
215 return (
216 <>
217 <DocumentTitleSync />
218 <BrowserChromeThemeSync key={pathname} />
219 <Outlet />
220 </>
221 );
222 }
223​
224 const appShell = (
225 <CommandPalette>
226 <AppSidebarLayout>
227 <Outlet />
228 </AppSidebarLayout>
229 </CommandPalette>
230 );
231​
232 return (
233 <ToastProvider>
234 <AnchoredToastProvider>
235 <DocumentTitleSync />
236 <BrowserChromeThemeSync key={pathname} />
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 <GuestShareDialogHost />
260 <SlowRpcRequestToastCoordinator />
261 <HostFreezeToastCoordinator />
262 <PermissionUpdateNotice />
263 {primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}
264 <ProjectCloneToastCoordinator />
265 <AddProjectToMachineDialogHost />
266 <PullRequestGuideRunCoordinator />
267 <HostedStaticEnvironmentBootstrap />
268 {primaryEnvironmentAuthenticated ? (
269 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
270 ) : null}
271 {isElectron ? <DesktopUpdateLaunchNotice /> : null}
272 {appShell}
273 {/* Keep the theme editor above the router so drafts survive navigation. */}
274 <ThemeEditorHost />
275 </FirstRunGate>
276 </AnchoredToastProvider>
277 </ToastProvider>
278 );
280​
281function EnvironmentThemeSync() {
282 useEnvironmentThemeSync();
283 // Sync palettes before adopting the environment theme so it is 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​
356// Each route paints its own surface for browser chrome to sample.
357function BrowserChromeThemeSync() {
358 useEffect(() => {
359 const frame = window.requestAnimationFrame(() => {
360 syncBrowserChromeTheme();
361 });
362 return () => {
363 window.cancelAnimationFrame(frame);
364 };
365 }, []);
366 return null;
368​
369function DocumentTitleSync() {
370 const primaryServerVersion =
371 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
372 const title = resolveServerBackedAppDisplayName({
373 baseName: APP_BASE_NAME,
374 fallbackDisplayName: APP_DISPLAY_NAME,
375 fallbackStageLabel: APP_STAGE_LABEL,
376 primaryServerVersion,
377 });
378​
379 useEffect(() => {
380 document.title = title;
381 }, [title]);
382​
383 return null;
385​
386function HostedStaticEnvironmentBootstrap() {
387 const { environments } = useEnvironments();
388 const activeEnvironmentId = useActiveEnvironmentId();
389​
390 useEffect(() => {
391 if (
392 environments.some(
393 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
394 )
395 ) {
396 return;
397 }
398​
399 if (activeEnvironmentId) {
400 return;
401 }
402​
403 const firstSavedEnvironment = environments[0];
404 if (!firstSavedEnvironment) {
405 return;
406 }
407​
408 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
409 }, [activeEnvironmentId, environments]);
410​
411 return null;
413​
414function RootRouteErrorView({ error }: ErrorComponentProps) {
415 const router = useRouter();
416 const message = errorMessage(error);
417 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
418 const pathname = useLocation({ select: (location) => location.pathname });
419 const report = errorReport(error, pathname);
420​
421 return (
422 <StandalonePage tone="error">
423 <StandalonePageHeader
424 eyebrow={APP_DISPLAY_NAME}
425 title="Something went wrong."
426 description={message}
427 />
428​
429 <div className="mt-5 flex flex-wrap gap-2">
430 <Button size="sm" onClick={() => void router.invalidate()}>
431 Try again
432 </Button>
433 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
434 Reload app
435 </Button>
436 <CopyErrorButton report={report} />
437 </div>
438​
439 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
440 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
441 <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">
442 {report}
443 </pre>
444 </div>
445 </StandalonePage>
446 );
448​
449function CopyErrorButton({ report }: { report: string }) {
450 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
451​
452 return (
453 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
454 <MorphIcon className={cn(isCopied && "text-success")} icon={isCopied ? Check : Copy} />
455 {isCopied ? "Copied" : "Copy error"}
456 </Button>
457 );
459​
460function errorMessage(error: unknown): string {
461 if (error instanceof Error && error.message.trim().length > 0) {
462 return error.message;
463 }
464​
465 if (typeof error === "string" && error.trim().length > 0) {
466 return error;
467 }
468​
469 return "An unexpected router error occurred.";
471​
472function errorDetails(error: unknown): string {
473 if (error instanceof Error) {
474 return error.stack ?? error.message;
475 }
476​
477 if (typeof error === "string") {
478 return error;
479 }
480​
481 try {
482 return JSON.stringify(error, null, 2);
483 } catch {
484 return "No additional error details are available.";
485 }
487​
488const MAX_ERROR_CAUSE_DEPTH = 5;
489​
490// Use only pathname to keep query tokens off the clipboard.
491function errorReport(error: unknown, pathname: string): string {
492 const lines = [
493 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
494 `Path: ${pathname}`,
495 `Time: ${new Date().toISOString()}`,
496 "",
497 errorDetails(error),
498 ];
499 let cause = error instanceof Error ? error.cause : undefined;
500 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
501 lines.push("", "Caused by:", errorDetails(cause));
502 cause = cause instanceof Error ? cause.cause : undefined;
503 }
504 return lines.join("\n");
506​
507function AuthenticatedTracingBootstrap() {
508 useEffect(() => {
509 void configureClientTracing();
510 }, []);
511​
512 return null;
514​
515function EventRouter({
516 skipInitialBootstrapNavigation,
517}: {
518 readonly skipInitialBootstrapNavigation: boolean;
519}) {
520 const navigate = useNavigate();
521 const pathname = useLocation({ select: (loc) => loc.pathname });
522 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
523 const primaryEnvironment = usePrimaryEnvironment();
524 const serverConfig = useAtomValue(primaryServerConfigAtom);
525 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
526 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
527 const readPathname = useEffectEvent(() => pathname);
528 const handledBootstrapThreadIdRef = useRef<string | null>(null);
529 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
530 const handledConfigEventRef = useRef(serverConfigEvent);
531 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
532 createKeybindingsUpdateToastController({}),
533 );
534​
535 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
536 if (!payload) return;
537​
538 setActiveEnvironmentId(payload.environment.environmentId);
539 void (async () => {
540 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
541 return;
542 }
543 const bootstrapProject = readProject(
544 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
545 );
546 const bootstrapProjectKey =
547 (bootstrapProject
548 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
549 : null) ??
550 (serverConfig?.cwd
551 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
552 : null) ??
553 scopedProjectKey(
554 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
555 );
556 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
557​
558 if (readPathname() !== "/") {
559 return;
560 }
561 if (skipInitialBootstrapNavigationRef.current) {
562 skipInitialBootstrapNavigationRef.current = false;
563 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
564 return;
565 }
566 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
567 return;
568 }
569 await navigate({
570 to: "/$environmentId/$threadId",
571 params: {
572 environmentId: payload.environment.environmentId,
573 threadId: payload.bootstrapThreadId,
574 },
575 replace: true,
576 });
577 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
578 })().catch(() => undefined);
579 });
580​
581 const handleServerConfigUpdated = useEffectEvent(() => {
582 const decision = keybindingsToastController.handle(serverConfigEvent);
583 if (!decision) {
584 return;
585 }
586​
587 if (decision._tag === "Success") {
588 toastManager.add({
589 type: "success",
590 title: "Keybindings updated",
591 description: "Keybindings configuration reloaded successfully.",
592 });
593 return;
594 }
595​
596 toastManager.add(
597 stackedThreadToast({
598 type: "warning",
599 title: "Invalid keybindings configuration",
600 description: (
601 <KeybindingsConfigWarning
602 message={decision.message}
603 environmentId={primaryEnvironment?.environmentId ?? null}
604 configPath={serverConfig?.keybindingsConfigPath ?? null}
605 availableEditors={serverConfig?.availableEditors ?? []}
606 />
607 ),
608 }),
609 );
610 });
611​
612 useEffect(() => {
613 if (!serverConfig) {
614 return;
615 }
616​
617 setActiveEnvironmentId(serverConfig.environment.environmentId);
618 }, [serverConfig]);
619​
620 useEffect(() => {
621 handleWelcome(serverWelcome);
622 }, [serverWelcome]);
623​
624 useEffect(() => {
625 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
626 return;
627 }
628 handledConfigEventRef.current = serverConfigEvent;
629 handleServerConfigUpdated();
630 }, [serverConfigEvent]);
631​
632 return null;