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 { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";
31import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
32import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
33import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
34import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
35import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
36import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
37import { Button } from "../components/ui/button";
38import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
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 <ProjectCloneToastCoordinator />
231 <HostedStaticEnvironmentBootstrap />
232 {primaryEnvironmentAuthenticated ? (
233 <EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
234 ) : null}
235 {primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}
236 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
237 {appShell}
238 {/* Above the router: a theme draft is judged by walking the app, so the
239 editor has to survive navigation away from settings. */}
240 <ThemeEditorHost />
241 </FirstRunGate>
242 </AnchoredToastProvider>
243 </ToastProvider>
244 );
245}
246
247/** Follows the palette the primary environment's machine publishes, if any. */
248function EnvironmentThemeSync() {
249 useEnvironmentThemeSync();
250 // Ordered after the palette sync so a first-run client adopting the
251 // environment's own theme finds it already in the library.
252 useDefaultThemeAdoption();
253 return null;
254}
255
256function ContrastAppearanceSync() {
257 const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
258 const diffColorScheme = useClientSettings((settings) => settings.diffColorScheme);
259
260 useEffect(() => {
261 document.documentElement.dataset.diffColorScheme = diffColorScheme;
262 }, [diffColorScheme]);
263
264 useEffect(() => {
265 applyAppearanceContrast(document.documentElement, appearanceContrast);
266 }, [appearanceContrast]);
267
268 return null;
269}
270
271function GlassAppearanceSync() {
272 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
273
274 useEffect(() => {
275 const style = document.documentElement.style;
276 style.setProperty("--glass-opacity", `${glassOpacity}%`);
277 if (glassOpacity === 100) {
278 style.setProperty("--glass-blur", "0px");
279 } else {
280 style.removeProperty("--glass-blur");
281 }
282 }, [glassOpacity]);
283
284 return null;
285}
286
287function FontAppearanceSync() {
288 const fontFamilySans = useClientSettings((settings) => settings.fontFamilySans);
289 const fontFamilyCode = useClientSettings((settings) => settings.fontFamilyCode);
290 const fontFamilyComposer = useClientSettings((settings) => settings.fontFamilyComposer);
291 const fontSizeInterface = useClientSettings((settings) => settings.fontSizeInterface);
292 const fontSizePrompt = useClientSettings((settings) => settings.fontSizePrompt);
293 const fontSizeCode = useClientSettings((settings) => settings.fontSizeCode);
294 const fontSmoothing = useClientSettings((settings) => settings.fontSmoothing);
295
296 useEffect(() => {
297 applyAppearanceFontVariables(document.documentElement, {
298 sans: fontFamilySans,
299 code: fontFamilyCode,
300 composer: fontFamilyComposer,
301 sizeInterface: fontSizeInterface,
302 sizePrompt: fontSizePrompt,
303 sizeCode: fontSizeCode,
304 smoothing: fontSmoothing,
305 });
306 }, [
307 fontFamilyCode,
308 fontFamilyComposer,
309 fontFamilySans,
310 fontSizeCode,
311 fontSizeInterface,
312 fontSizePrompt,
313 fontSmoothing,
314 ]);
315
316 return null;
317}
318
319function DocumentTitleSync() {
320 const primaryServerVersion =
321 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
322 const title = resolveServerBackedAppDisplayName({
323 baseName: APP_BASE_NAME,
324 fallbackDisplayName: APP_DISPLAY_NAME,
325 fallbackStageLabel: APP_STAGE_LABEL,
326 primaryServerVersion,
327 });
328
329 useEffect(() => {
330 document.title = title;
331 }, [title]);
332
333 return null;
334}
335
336function HostedStaticEnvironmentBootstrap() {
337 const { environments } = useEnvironments();
338 const activeEnvironmentId = useActiveEnvironmentId();
339
340 useEffect(() => {
341 if (
342 environments.some(
343 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
344 )
345 ) {
346 return;
347 }
348
349 if (activeEnvironmentId) {
350 return;
351 }
352
353 const firstSavedEnvironment = environments[0];
354 if (!firstSavedEnvironment) {
355 return;
356 }
357
358 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
359 }, [activeEnvironmentId, environments]);
360
361 return null;
362}
363
364function RootRouteErrorView({ error }: ErrorComponentProps) {
365 const router = useRouter();
366 const message = errorMessage(error);
367 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
368 const pathname = useLocation({ select: (location) => location.pathname });
369 const report = useMemo(() => errorReport(error, pathname), [error, pathname]);
370
371 return (
372 <StandalonePage tone="error">
373 <StandalonePageHeader
374 eyebrow={APP_DISPLAY_NAME}
375 title="Something went wrong."
376 description={message}
377 />
378
379 <div className="mt-5 flex flex-wrap gap-2">
380 <Button size="sm" onClick={() => void router.invalidate()}>
381 Try again
382 </Button>
383 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
384 Reload app
385 </Button>
386 <CopyErrorButton report={report} />
387 </div>
388
389 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
390 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
391 <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">
392 {report}
393 </pre>
394 </div>
395 </StandalonePage>
396 );
397}
398
399/** Copies the full error report and swaps to a check mark for a moment as confirmation. */
400function CopyErrorButton({ report }: { report: string }) {
401 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
402
403 return (
404 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
405 {isCopied ? <CheckIcon className="text-success" /> : <CopyIcon />}
406 {isCopied ? "Copied" : "Copy error"}
407 </Button>
408 );
409}
410
411function errorMessage(error: unknown): string {
412 if (error instanceof Error && error.message.trim().length > 0) {
413 return error.message;
414 }
415
416 if (typeof error === "string" && error.trim().length > 0) {
417 return error;
418 }
419
420 return "An unexpected router error occurred.";
421}
422
423function errorDetails(error: unknown): string {
424 if (error instanceof Error) {
425 return error.stack ?? error.message;
426 }
427
428 if (typeof error === "string") {
429 return error;
430 }
431
432 try {
433 return JSON.stringify(error, null, 2);
434 } catch {
435 return "No additional error details are available.";
436 }
437}
438
439const MAX_ERROR_CAUSE_DEPTH = 5;
440
441/**
442 * Full error text for bug reports: app build, page path, time, then the stack
443 * and any cause chain. Takes the pathname only so tokens in the query never
444 * land on the clipboard.
445 */
446function errorReport(error: unknown, pathname: string): string {
447 const lines = [
448 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
449 `Path: ${pathname}`,
450 `Time: ${new Date().toISOString()}`,
451 "",
452 errorDetails(error),
453 ];
454 let cause = error instanceof Error ? error.cause : undefined;
455 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
456 lines.push("", "Caused by:", errorDetails(cause));
457 cause = cause instanceof Error ? cause.cause : undefined;
458 }
459 return lines.join("\n");
460}
461
462function AuthenticatedTracingBootstrap() {
463 useEffect(() => {
464 void configureClientTracing();
465 }, []);
466
467 return null;
468}
469
470function EventRouter({
471 skipInitialBootstrapNavigation,
472}: {
473 readonly skipInitialBootstrapNavigation: boolean;
474}) {
475 const navigate = useNavigate();
476 const pathname = useLocation({ select: (loc) => loc.pathname });
477 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
478 const primaryEnvironment = usePrimaryEnvironment();
479 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
480 reportFailure: false,
481 });
482 const serverConfig = useAtomValue(primaryServerConfigAtom);
483 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
484 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
485 const readPathname = useEffectEvent(() => pathname);
486 const handledBootstrapThreadIdRef = useRef<string | null>(null);
487 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
488 const handledConfigEventRef = useRef(serverConfigEvent);
489 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
490 createKeybindingsUpdateToastController({}),
491 );
492
493 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
494 if (!payload) return;
495
496 setActiveEnvironmentId(payload.environment.environmentId);
497 void (async () => {
498 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
499 return;
500 }
501 const bootstrapProject = readProject(
502 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
503 );
504 const bootstrapProjectKey =
505 (bootstrapProject
506 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
507 : null) ??
508 (serverConfig?.cwd
509 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
510 : null) ??
511 scopedProjectKey(
512 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
513 );
514 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
515
516 if (readPathname() !== "/") {
517 return;
518 }
519 if (skipInitialBootstrapNavigationRef.current) {
520 skipInitialBootstrapNavigationRef.current = false;
521 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
522 return;
523 }
524 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
525 return;
526 }
527 await navigate({
528 to: "/$environmentId/$threadId",
529 params: {
530 environmentId: payload.environment.environmentId,
531 threadId: payload.bootstrapThreadId,
532 },
533 replace: true,
534 });
535 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
536 })().catch(() => undefined);
537 });
538
539 const handleServerConfigUpdated = useEffectEvent(() => {
540 const decision = keybindingsToastController.handle(serverConfigEvent);
541 if (!decision) {
542 return;
543 }
544
545 if (decision._tag === "Success") {
546 toastManager.add({
547 type: "success",
548 title: "Keybindings updated",
549 description: "Keybindings configuration reloaded successfully.",
550 });
551 return;
552 }
553
554 toastManager.add(
555 stackedThreadToast({
556 type: "warning",
557 title: "Invalid keybindings configuration",
558 description: decision.message,
559 actionVariant: "outline",
560 actionProps: {
561 children: "Open keybindings.json",
562 onClick: () => {
563 if (!serverConfig || !primaryEnvironment) {
564 return;
565 }
566
567 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
568 if (!editor) {
569 return;
570 }
571 void (async () => {
572 const result = await openInEditor({
573 environmentId: primaryEnvironment.environmentId,
574 input: {
575 cwd: serverConfig.keybindingsConfigPath,
576 editor,
577 },
578 });
579 if (result._tag === "Success") {
580 return;
581 }
582 const error = squashAtomCommandFailure(result);
583 toastManager.add(
584 stackedThreadToast({
585 type: "error",
586 title: "Unable to open keybindings file",
587 description:
588 error instanceof Error ? error.message : "Unknown error opening file.",
589 }),
590 );
591 })();
592 },
593 },
594 }),
595 );
596 });
597
598 useEffect(() => {
599 if (!serverConfig) {
600 return;
601 }
602
603 setActiveEnvironmentId(serverConfig.environment.environmentId);
604 }, [serverConfig]);
605
606 useEffect(() => {
607 handleWelcome(serverWelcome);
608 }, [serverWelcome]);
609
610 useEffect(() => {
611 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
612 return;
613 }
614 handledConfigEventRef.current = serverConfigEvent;
615 handleServerConfigUpdated();
616 }, [serverConfigEvent]);
617
618 return null;
619}