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