Open History to see the last commit
1import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 Outlet,
5 Link,
6 redirect,
7 createRootRoute,
8 type ErrorComponentProps,
9 useLocation,
10 useNavigate,
11 useRouter,
12} from "@tanstack/react-router";
13import { Check, Copy } from "lucide";
14import { useEffect, useEffectEvent, useRef, useState } from "react";
15
16import { APP_DISPLAY_NAME, APP_VERSION } from "../branding";
17import { AppSidebarLayout } from "../components/AppSidebarLayout";
18import { CommandPalette } from "../components/CommandPalette";
19import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
20import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
21import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog";
22import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
23import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
24import { DevReplayHost } from "../components/DevReplayHost";
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 { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";
34import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
35import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
36import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
37import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
38import { Button } from "../components/ui/button";
39import { MorphIcon } from "~/components/MorphIcon";
40import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
41import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
42import { isElectron } from "../env";
43import { cn } from "../lib/utils";
44import { useClientSettings } from "../hooks/useSettings";
45import {
46 deriveLogicalProjectKeyFromSettings,
47 derivePhysicalProjectKeyFromPath,
48 selectProjectGroupingSettings,
49} from "@t3tools/client-runtime/state/project-grouping";
50import { useUiStateStore } from "../uiStateStore";
51import { configureClientTracing } from "../observability/clientTracing";
52import { resolveInitialServerAuthGateState } from "../environments/primary";
53import { GUEST_PAGE_PATH } from "../guestPage";
54import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
55import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
56import { isLocalEnvironmentDisabled } from "../localEnvironment";
57import { useAtomValue } from "@effect/atom-react";
58import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../state/server";
59import { readProject } from "../state/entities";
60
61import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
62import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
63
64export const Route = createRootRoute({
65 beforeLoad: async ({ location }) => {
66 // Guest links open on the owner's tunnel host in a browser with no T3 session, and must
67 // not trigger pairing or an environment connection.
68 if (location.pathname === GUEST_PAGE_PATH) {
69 return {
70 authGateState: {
71 status: "guest",
72 } as const,
73 };
74 }
75
76 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
77 return {
78 authGateState: {
79 status: "hosted-pairing",
80 } as const,
81 };
82 }
83
84 if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) {
85 return {
86 authGateState: {
87 status: "hosted-static",
88 } as const,
89 };
90 }
91
92 const authGateState = await resolveInitialServerAuthGateState();
93 if (authGateState.status === "authenticated") {
94 // Idempotent, so every navigation can ask for it.
95 void configureClientTracing();
96 }
97 if (
98 authGateState.status === "authenticated" &&
99 getDesktopSnapShotBridge() &&
100 shouldResumeSnapShotSetupOnStartup() &&
101 location.pathname !== "/settings/snap-shot"
102 ) {
103 throw redirect({ to: "/settings/snap-shot", replace: true });
104 }
105 return {
106 authGateState,
107 };
108 },
109 component: RootRouteView,
110 errorComponent: RootRouteErrorView,
111 notFoundComponent: RootRouteNotFoundView,
112 head: () => ({
113 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
114 }),
115});
116
117function RootRouteNotFoundView() {
118 return (
119 <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6">
120 <div className="flex max-w-sm flex-col items-center gap-4 text-center">
121 <h1 className="text-lg font-medium text-foreground">Page not found</h1>
122 <p className="text-sm text-muted-foreground">
123 This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or
124 start a thread.
125 </p>
126 <Button render={<Link to="/" replace />}>Go home</Button>
127 </div>
128 </main>
129 );
130}
131
132function RootRouteView() {
133 // Above every branch: app services raise toasts for the whole page, so the surface they write to
134 // must not unmount when the root switches branches (for example /welcome to the app shell).
135 return (
136 <ToastProvider>
137 <AnchoredToastProvider>
138 <RootRouteBranch />
139 </AnchoredToastProvider>
140 </ToastProvider>
141 );
142}
143
144function RootRouteBranch() {
145 const pathname = useLocation({ select: (location) => location.pathname });
146 const { authGateState } = Route.useRouteContext();
147 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
148 // A sync IPC read; the setting only changes across a relaunch.
149 const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
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 === GUEST_PAGE_PATH) return <Outlet />;
158
159 if (
160 pathname === "/pair" ||
161 pathname === "/connect" ||
162 pathname === "/connect-agent" ||
163 pathname === "/approve-agent"
164 ) {
165 return <Outlet />;
166 }
167
168 // Handle links before onboarding redirects lose them.
169 if (hostedPromptLinkLanding !== null) {
170 return hostedPromptLinkLanding;
171 }
172
173 const isWelcome = pathname === "/welcome";
174 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
175 return <Outlet />;
176 }
177
178 // Settings can reopen /welcome mid-session, so it mounts everything the app does except the
179 // first-run gate and the event router, whose first navigation would leave the page.
180 const appHosts = (
181 <>
182 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
183 {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
184 <DesktopWebLinkCoordinator />
185 ) : null}
186 {isElectron ? <RunningThreadKeepAlive /> : null}
187 <RelayClientInstallDialog />
188 <ConnectOnboardingDialog />
189 <SshPasswordPromptDialog />
190 <SnapShotCoordinator />
191 <ReopenClosedViewShortcut />
192 <ConfirmDialogHost />
193 <CustomSnoozeDialogHost />
194 <GuestShareDialogHost />
195 <ProjectCloneToastCoordinator />
196 <AddProjectToMachineDialogHost />
197 <UseInAnotherAppDialogHost />
198 {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
199 </>
200 );
201 const appShell = (
202 <CommandPalette>
203 {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */}
204 <AppSidebarLayout showSidebar={!isWelcome}>
205 <Outlet />
206 </AppSidebarLayout>
207 </CommandPalette>
208 );
209
210 return (
211 <>
212 <ChatGptWelcomeCoordinator />
213 {isWelcome ? (
214 <>
215 {appHosts}
216 {appShell}
217 </>
218 ) : (
219 <FirstRunGate
220 enabled={primaryEnvironmentAuthenticated}
221 hostedStatic={authGateState.status === "hosted-static"}
222 >
223 {appHosts}
224 {primaryEnvironmentAuthenticated ? (
225 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
226 ) : null}
227 {appShell}
228 </FirstRunGate>
229 )}
230 {/* Above both shells and the router, so drafts survive navigation, including to /welcome. */}
231 <ThemeEditorHost />
232 </>
233 );
234}
235
236function RootRouteErrorView({ error }: ErrorComponentProps) {
237 const router = useRouter();
238 const message = errorMessage(error);
239 // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/".
240 const pathname = useLocation({ select: (location) => location.pathname });
241 const report = errorReport(error, pathname);
242
243 return (
244 <StandalonePage>
245 <StandalonePageHeader title="Something went wrong." description={message} />
246
247 <div className="mt-5 flex flex-wrap gap-2">
248 <Button size="sm" onClick={() => void router.invalidate()}>
249 Try again
250 </Button>
251 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
252 Reload app
253 </Button>
254 <CopyErrorButton report={report} />
255 </div>
256
257 <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
258 <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground">Error report</p>
259 <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">
260 {report}
261 </pre>
262 </div>
263 </StandalonePage>
264 );
265}
266
267function CopyErrorButton({ report }: { report: string }) {
268 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-report" });
269
270 return (
271 <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}>
272 <MorphIcon className={cn(isCopied && "text-success")} icon={isCopied ? Check : Copy} />
273 {isCopied ? "Copied" : "Copy error"}
274 </Button>
275 );
276}
277
278function errorMessage(error: unknown): string {
279 if (error instanceof Error && error.message.trim().length > 0) {
280 return error.message;
281 }
282
283 if (typeof error === "string" && error.trim().length > 0) {
284 return error;
285 }
286
287 return "An unexpected router error occurred.";
288}
289
290function errorDetails(error: unknown): string {
291 if (error instanceof Error) {
292 return error.stack ?? error.message;
293 }
294
295 if (typeof error === "string") {
296 return error;
297 }
298
299 try {
300 return JSON.stringify(error, null, 2);
301 } catch {
302 return "No additional error details are available.";
303 }
304}
305
306const MAX_ERROR_CAUSE_DEPTH = 5;
307
308// Use only pathname to keep query tokens off the clipboard.
309function errorReport(error: unknown, pathname: string): string {
310 const lines = [
311 `${APP_DISPLAY_NAME} ${APP_VERSION}`,
312 `Path: ${pathname}`,
313 `Time: ${new Date().toISOString()}`,
314 "",
315 errorDetails(error),
316 ];
317 let cause = error instanceof Error ? error.cause : undefined;
318 for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
319 lines.push("", "Caused by:", errorDetails(cause));
320 cause = cause instanceof Error ? cause.cause : undefined;
321 }
322 return lines.join("\n");
323}
324
325function EventRouter({
326 skipInitialBootstrapNavigation,
327}: {
328 readonly skipInitialBootstrapNavigation: boolean;
329}) {
330 const navigate = useNavigate();
331 const pathname = useLocation({ select: (loc) => loc.pathname });
332 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
333 const serverConfig = useAtomValue(primaryServerConfigAtom);
334 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
335 const readPathname = useEffectEvent(() => pathname);
336 const handledBootstrapThreadIdRef = useRef<string | null>(null);
337 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
338
339 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
340 if (!payload) return;
341
342 void (async () => {
343 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
344 return;
345 }
346 const bootstrapProject = readProject(
347 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
348 );
349 const bootstrapProjectKey =
350 (bootstrapProject
351 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
352 : null) ??
353 (serverConfig?.cwd
354 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
355 : null) ??
356 scopedProjectKey(
357 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
358 );
359 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
360
361 if (readPathname() !== "/") {
362 return;
363 }
364 if (skipInitialBootstrapNavigationRef.current) {
365 skipInitialBootstrapNavigationRef.current = false;
366 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
367 return;
368 }
369 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
370 return;
371 }
372 await navigate({
373 to: "/$environmentId/$threadId",
374 params: {
375 environmentId: payload.environment.environmentId,
376 threadId: payload.bootstrapThreadId,
377 },
378 replace: true,
379 });
380 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
381 })().catch(() => undefined);
382 });
383
384 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands the bootstrap project in the UI store and navigates the router on a server welcome
385 useEffect(() => {
386 handleWelcome(serverWelcome);
387 }, [serverWelcome]);
388
389 return null;
390}