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