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