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