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