Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

__root.tsx

423 lines15.5 KB

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