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