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