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