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