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