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