Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

672 linesCodeBlameRaw
1import { useEffect, useMemo, useRef, useState } from "react";
2import {
3 isRouteErrorResponse,
4 Link,
5 Links,
6 Meta,
7 Outlet,
8 Scripts,
9 ScrollRestoration,
10 type ShouldRevalidateFunctionArgs,
11 useLocation,
12 useMatches,
13 useRouteError,
14 useRouteLoaderData,
15} from "react-router";
16
17import {
18 type User,
19 awaitsConfirmation,
20 hasAccessIn,
21 sharedWorkspaces,
22} from "@g1t/contracts";
23
24import type { Route } from "./+types/root";
25import appCss from "./app.css?url";
26import displayFont from "@g1t/theme/fonts/bricolage-grotesque-latin.woff2?url";
27import sansFont from "@g1t/theme/fonts/hanken-grotesk-latin.woff2?url";
28import { ButtonLink } from "./components/ui";
29import {
30 AppShell,
31 Progress,
32 type ShellData,
33 useLeaving,
34} from "./components/shell";
35import { SiteFooter } from "./components/footer";
36import { PublicHeader } from "./components/public-header";
37import { SpikeBanner } from "./components/spike-banner";
38import { PolicyNotice } from "./components/policy-notice";
39import { identify } from "./lib/analytics.client";
40import { visitorAsksFirst } from "./lib/analytics-consent";
41import { AnalyticsConsent } from "./components/analytics-consent";
42import { readCookie } from "./lib/mission";
43import { WORKSPACE_COOKIE, workspaceFor } from "./lib/workspace-choice";
44import { PageMain } from "./components/landmark";
45import { NotFound } from "./components/not-found";
46import { frameOf } from "./lib/chrome";
47import {
48 DOCK_COOKIE,
49 SIDEBAR_COOKIE,
50 pinsToShow,
51 sidebarClosed,
52} from "./lib/apps";
53import { savedPins } from "./lib/dock.server";
54import { StandaloneFrame } from "./components/standalone";
55import {
56 ai,
57 billing,
58 chat,
59 identity,
60 inbox,
61 projects,
62} from "./lib/services.server";
63import { unreadTotals } from "./lib/chat";
64import { countsFor, readableRepos } from "./lib/access.server";
65import { agentForProviders, DEFAULT_AGENT, parseAgent, rememberAgentDefault } from "./lib/agent-setup";
66import { shortCache } from "./lib/cache.server";
67import { getViewer, viewerMiddleware } from "./lib/session.server";
68import { shortcutOf, workspaceProjects } from "./lib/workspace-projects.server";
69import { addresses } from "./lib/addresses.server";
70import { orElse, part } from "./lib/partial";
71import {
72 RELOADED_KEY,
73 RELOAD_GIVE_UP_MS,
74 clientNavigated,
75 reloadFixes,
76 reloadedBefore,
77} from "./lib/stale-build";
78import { useNonce } from "./lib/nonce";
79import { useStuckNavigationRescue } from "./lib/stuck";
80import { isNeedsSignIn } from "./lib/website-token";
81import { offerTicket, setLiveViaToken } from "./lib/live-socket";
82import { socketTicketFor } from "./lib/socket-ticket.server";
83import { DesktopApp } from "./components/desktop-app";
84import { DesktopRunnerLink } from "./components/desktop-runner-link";
85import { LiveNotifications } from "./components/notifications/live-notifications";
86import {
87 THEME_COLOR,
88 THEME_COOKIE,
89 readTheme,
90 themeAttribute,
91 useThemeChoice,
92} from "./lib/theme";
93import {
94 DEVELOPER_COOKIE,
95 readDeveloperMode,
96 useDeveloperMode,
97} from "./lib/developer-mode";
98import { RouteError } from "./components/route-error";
99import { ConnectionToast } from "./components/connection-toast";
100import { NavigationRecovery } from "./components/navigation-recovery";
101import { isNetworkFailure } from "./lib/resilient-fetch";
102import { useReconnect } from "./lib/reconnect";
103
104export const links: Route.LinksFunction = () => [
105 { rel: "icon", href: "/favicon.ico", sizes: "32x32" },
106 { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" },
107 { rel: "icon", type: "image/png", sizes: "192x192", href: "/icon-192.png" },
108 { rel: "icon", type: "image/png", sizes: "512x512", href: "/icon-512.png" },
109 // Home screens and password managers look for a square, opaque 180px tile;
110 // the "-precomposed" name is served too, for the ones that ask for it.
111 { rel: "apple-touch-icon", sizes: "180x180", href: "/apple-touch-icon.png" },
112 // Installable: name, icons and colours for "Add to Home Screen" (public/site.webmanifest;
113 // manifest.webmanifest is the same file, kept for installs that already point at it).
114 { rel: "manifest", href: "/site.webmanifest" },
115 // The text and headline faces are wanted on every page, so they start
116 // loading with the stylesheet; mono waits until something uses it.
117 {
118 rel: "preload",
119 href: sansFont,
120 as: "font",
121 type: "font/woff2",
122 crossOrigin: "anonymous",
123 },
124 {
125 rel: "preload",
126 href: displayFont,
127 as: "font",
128 type: "font/woff2",
129 crossOrigin: "anonymous",
130 },
131];
132
133export const middleware: Route.MiddlewareFunction[] = [viewerMiddleware];
134
135export async function loader({ context, params, request }: Route.LoaderArgs) {
136 const user = getViewer(context);
137 const cookies = request.headers.get("cookie");
138 const chosen = readCookie(cookies, WORKSPACE_COOKIE);
139 const dock = readCookie(cookies, DOCK_COOKIE);
140 const [shell, sounds] = await Promise.all([
141 // An account still confirming its address sees only the pages that
142 // allows (lib/confirm-gate.ts), in the visitor's frame.
143 user && !awaitsConfirmation(user)
144 ? shellFor(user, params, chosen, context).catch((error: unknown) => {
145 // A sidebar that could not be read is no reason to lose the page,
146 // or to draw it as if they were signed out.
147 console.error("root: the sidebar could not be read", error);
148 return bareShell(user, params, chosen);
149 })
150 : visitorShell(params, context),
151 // Their chat sounds, with the page, so the first live event already
152 // respects them (lib/sounds.ts); the defaults when identity is slow.
153 user && !awaitsConfirmation(user)
154 ? identity.soundSettings(user).catch(() => null)
155 : Promise.resolve(null),
156 ]);
157 // The apps this person pinned to their rail here: as their account keeps
158 // them (read with the rest of the shell), else as this device's cookie
159 // remembers them (lib/apps.ts).
160 if (shell.workspace)
161 shell.pins = pinsToShow(shell.pins, dock, shell.workspace.slug);
162 // Where this g1t lives, for clone lines, agent setup and link previews.
163 return {
164 user,
165 shell,
166 // Cache only the derived UI default, scoped to this viewer and workspace.
167 // shortCache bypasses old answers after settings writes; failures are not cached.
168 agentChoice: parseAgent(readCookie(cookies, "g1t_agent")),
169 agentDefault: user && shell.workspace
170 ? await shortCache(`agent-default:${user.id}:${shell.workspace.slug}`, 300_000, async () => {
171 const result = await ai.list(shell.workspace!.slug, user);
172 if (!result.ok) throw new Error("AI providers unavailable");
173 return agentForProviders(result.value);
174 }).catch(() => DEFAULT_AGENT)
175 : DEFAULT_AGENT,
176 // For a page opened with an access token: the feed socket's ticket,
177 // minted here so the feed opens without asking for one (lib/live-socket.ts).
178 // Without one the feed asks for its own ticket, so a ticket that could
179 // not be minted is no reason to lose the page.
180 liveTicket: user?.token?.website
181 ? orElse(await part(socketTicketFor(context, request, "/-/live"), "The live feed's ticket"), null)
182 : null,
183 // Whether they folded the sidebar away, so the page is drawn that way from the start.
184 sidebarClosed: sidebarClosed(readCookie(cookies, SIDEBAR_COOKIE)),
185 // Their Appearance, so the page is drawn in it from the first byte (lib/theme.ts).
186 theme: readTheme(readCookie(cookies, THEME_COOKIE)),
187 // Whether a page that fails says why, in full (lib/developer-mode.ts).
188 developer: readDeveloperMode(readCookie(cookies, DEVELOPER_COOKIE)),
189 // What they hear when chat moves (components/notifications/sounds.tsx).
190 sounds,
191 addresses: addresses(),
192 // Visitors from where the law asks first are asked before analytics runs.
193 analyticsConsent: visitorAsksFirst(request),
194 };
195}
196
197/**
198 * The sidebar for someone not signed in: nothing of their own, only the
199 * open counts of the project being looked at. One call, and only in a
200 * project; it answers the same for a private project as a missing one.
201 */
202async function visitorShell(
203 params: { owner?: string; repo?: string },
204 context: Route.LoaderArgs["context"],
205): Promise<ShellData> {
206 const path =
207 params.owner && params.repo
208 ? { namespace: params.owner, name: params.repo }
209 : null;
210 // The counts are the sidebar's, never the page's: without them it shows none.
211 const counts = path ? orElse(await part(countsFor(context, params), "Open counts"), null) : null;
212 return {
213 workspace: null,
214 repos: [],
215 repo:
216 path && counts?.ok
217 ? {
218 ...path,
219 member: false,
220 issues: counts.value.issues,
221 pulls: counts.value.pulls,
222 }
223 : null,
224 limit: null,
225 monthUsageMicros: null,
226 };
227}
228
229/** The sidebar from what the session already says, with no service asked. */
230function bareShell(
231 user: User,
232 params: { owner?: string; repo?: string },
233 chosen: string | null,
234): ShellData {
235 return {
236 workspace: workspaceFor(user.workspaces ?? [], chosen, params),
237 repos: [],
238 repo: null,
239 limit: null,
240 monthUsageMicros: null,
241 };
242}
243
244/**
245 * The sidebar only changes with the workspace or repository being looked
246 * at, or after something was submitted: not on every page within them.
247 */
248export function shouldRevalidate({
249 currentParams,
250 nextParams,
251 formMethod,
252 defaultShouldRevalidate,
253}: ShouldRevalidateFunctionArgs) {
254 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
255 return (
256 currentParams.owner !== nextParams.owner ||
257 currentParams.repo !== nextParams.repo
258 );
259}
260
261/**
262 * The sidebar: the workspace whose pages or project these are when it is
263 * one of yours, else the one you chose (lib/workspace-choice.ts); its
264 * projects; and the repository being looked at.
265 */
266async function shellFor(
267 user: User,
268 params: { owner?: string; repo?: string },
269 chosen: string | null,
270 context: Route.LoaderArgs["context"],
271): Promise<ShellData> {
272 const memberships = user.workspaces ?? [];
273 const workspace = workspaceFor(memberships, chosen, params);
274 const path =
275 params.owner && params.repo
276 ? { namespace: params.owner, name: params.repo }
277 : null;
278 const now = new Date();
279 const monthStart = new Date(
280 Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
281 ).toISOString();
282 // What the sidebar shows of the workspace changes rarely: kept for a few
283 // seconds per person and workspace, except just after they changed
284 // something (lib/cache.server.ts).
285 const kept = <T,>(what: string, load: () => Promise<T>) =>
286 workspace
287 ? shortCache(
288 `shell:${what}:${user.id}:${workspace.slug}`,
289 SHELL_TTL_MS,
290 load,
291 )
292 : Promise.resolve(null);
293 const [
294 listed,
295 counts,
296 status,
297 usage,
298 limit,
299 entitlements,
300 shared,
301 unread,
302 shortcuts,
303 chatUnread,
304 dockPins,
305 ] = await Promise.all([
306 // Every project, for the palette and the count; the sidebar lists only
307 // the person's pinned and recent ones (lib/pins.ts).
308 // Each of these is one part of the sidebar: one that fails leaves only
309 // itself out (logged by `part`), never the rest of the sidebar with it.
310 workspace
311 ? part(workspaceProjects(workspace.slug, user), "Projects").then((value) => orElse(value, null))
312 : Promise.resolve(null),
313 path
314 ? part(countsFor(context, params), "Open counts").then((value) => orElse(value, null))
315 : Promise.resolve(null),
316 // Whether billing is on, without reading the account: that asks the
317 // card processor about the workspace's cards, too slow for every page.
318 kept("status", () => billing.status()).catch(() => null),
319 kept(`usage:${monthStart}`, () =>
320 billing.usage(workspace!.slug, user, monthStart),
321 ).catch(() => null),
322 kept("limit", () => billing.limit(workspace!.slug, user)).catch(() => null),
323 kept("entitlements", () => billing.entitlements(workspace!.slug)).catch(
324 () => null,
325 ),
326 part(sharedRepos(user), "Shared with you").then((value) => orElse(value, [])),
327 // The bell's count: one query, never kept, so marking an item shows at once.
328 inbox.counts(user.username).catch(() => null),
329 // Never kept: opening a project moves it up Recent.
330 workspace
331 ? projects.shortcuts(workspace.slug, user).catch(() => null)
332 : Promise.resolve(null),
333 // The rail's Chat badge: never kept, and never waited on for long.
334 workspace ? chatUnreadFor(workspace.slug, user) : Promise.resolve(null),
335 // The rail's pins, kept with the account so every device shows the same
336 // rail; never kept here, so a pin shows the moment it is made. Null
337 // falls back to the cookie (lib/dock.server.ts).
338 workspace ? savedPins(user, workspace.slug) : Promise.resolve(null),
339 ]);
340 return {
341 workspace,
342 // Projects are what the sidebar lists: what the workspace builds and runs.
343 repos: listed?.ok ? listed.value.map(shortcutOf) : [],
344 pinned: (shortcuts?.pinned ?? []).map(shortcutOf),
345 recent: (shortcuts?.recent ?? []).map(shortcutOf),
346 repo:
347 path && counts?.ok
348 ? {
349 ...path,
350 // Until the repository's own page says what their role is.
351 member: hasAccessIn(user, path.namespace),
352 issues: counts.value.issues,
353 pulls: counts.value.pulls,
354 }
355 : null,
356 // Where the workspace stands against its usage limit, once billing is on.
357 limit:
358 status?.enabled && limit?.ok
359 ? {
360 exposureMicros: limit.value.exposureMicros,
361 ceilingMicros: limit.value.ceilingMicros,
362 state: limit.value.state,
363 comped: limit.value.trust === "internal",
364 }
365 : null,
366 free: Boolean(status?.free),
367 // A spend spike or a hold pauses new compute: the shell says so on every page.
368 compute:
369 workspace &&
370 entitlements &&
371 (entitlements.paused || entitlements.spike?.status === "open")
372 ? {
373 paused: entitlements.paused,
374 spike: entitlements.spike ?? null,
375 owner: workspace.role === "owner",
376 }
377 : null,
378 shared,
379 inbox: unread,
380 chat: chatUnread,
381 pins: dockPins ?? undefined,
382 // While g1t is free every charge is zero, so usage is shown at cost.
383 // Usage at price, the one figure every page shows.
384 monthUsageMicros: usage?.ok
385 ? usage.value.free
386 ? usage.value.usedMicros
387 : (usage.value.priceMicros ?? usage.value.spentMicros)
388 : null,
389 };
390}
391
392/** Starred and recent conversations Home's sidebar lists. */
393const SHELL_CONVERSATIONS = 8;
394
395/**
396 * What is unread in chat, for the rail, and the starred and latest
397 * conversations, for Home's sidebar; null when chat is slow to answer or
398 * does not.
399 */
400async function chatUnreadFor(
401 slug: string,
402 user: User,
403): Promise<ShellData["chat"]> {
404 const timeout = new Promise<null>((resolve) =>
405 setTimeout(() => resolve(null), CHAT_BADGE_WAIT_MS),
406 );
407 const read = chat
408 .sidebar(slug, user)
409 .then((result) => {
410 if (!result.ok) return null;
411 const entries = result.value.entries;
412 const latest = [...entries].sort((a, b) =>
413 (b.channel.last_message_at ?? "").localeCompare(
414 a.channel.last_message_at ?? "",
415 ),
416 );
417 return {
418 ...unreadTotals(entries),
419 starred: entries.filter((e) => e.starred).slice(0, SHELL_CONVERSATIONS),
420 recent: latest.slice(0, SHELL_CONVERSATIONS),
421 };
422 })
423 .catch(() => null);
424 return Promise.race([read, timeout]);
425}
426
427/** The longest the rail's Chat badge holds up a page. */
428const CHAT_BADGE_WAIT_MS = 300;
429
430/**
431 * How long the sidebar's workspace answers are kept: as long as someone's
432 * own changes read fresh anyway (lib/perf.ts `PRIMARY_WINDOW_SECONDS`).
433 */
434const SHELL_TTL_MS = 30_000;
435
436/** Most repositories listed under Shared with you. */
437const MAX_SHARED = 20;
438
439/**
440 * Repositories shared with the user in workspaces they do not belong to,
441 * by their grants: only those, never the workspace's other repositories.
442 */
443async function sharedRepos(user: User): Promise<ShellData["shared"]> {
444 const outside = new Set(sharedWorkspaces(user));
445 if (outside.size === 0) return [];
446 const ids = (user.grants ?? [])
447 .filter((grant) => outside.has(grant.workspace))
448 .map((grant) => grant.repo_id)
449 .slice(0, MAX_SHARED);
450 const found = await readableRepos(ids, user);
451 return found
452 .map((repo) => ({
453 namespace: repo.namespace,
454 name: repo.name,
455 isPrivate: repo.isPrivate,
456 }))
457 .sort((a, b) =>
458 `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`),
459 );
460}
461
462/**
463 * The root's data as the browser last had it. When a navigation fails in a
464 * way that takes the root's data with it, the error is still drawn in the
465 * person's own frame, signed in, not the visitor's. Never kept on the
466 * server, where one module serves everyone.
467 */
468let lastRoot: Awaited<ReturnType<typeof loader>> | undefined;
469
470export function Layout({ children }: { children: React.ReactNode }) {
471 const nonce = useNonce();
472 // Undefined when the root loader itself failed.
473 const loaded = useRouteLoaderData<typeof loader>("root");
474 const inBrowser = typeof document !== "undefined";
475 if (loaded && inBrowser) lastRoot = loaded;
476 const root = loaded ?? (inBrowser ? lastRoot : undefined);
477 const user = root?.user;
478 // A page opened with an access token signs its live sockets in with tickets (lib/live-socket.ts).
479 if (inBrowser) {
480 setLiveViaToken(Boolean(user?.token?.website));
481 offerTicket("/-/live", root?.liveTicket);
482 }
483 const { pathname } = useLocation();
484 // Drawn around the error page too: a 404 keeps the sidebar out of a
485 // project or workspace the viewer cannot see.
486 const error = useRouteError();
487 const missing = isRouteErrorResponse(error) && error.status === 404;
488 // The billing page shows the full banner itself.
489 const paused = root?.shell?.compute &&
490 root.shell.workspace &&
491 !pathname.endsWith("/-/billing") && (
492 <SpikeBanner
493 compact
494 slug={root.shell.workspace.slug}
495 entitlements={{
496 paused: root.shell.compute.paused,
497 spike: root.shell.compute.spike,
498 }}
499 owner={root.shell.compute.owner}
500 />
501 );
502 // On the few pages an account still confirming its address can open
503 // besides /confirm-email (policies, support, signing in): the way back.
504 const verify = user &&
505 awaitsConfirmation(user) &&
506 pathname !== "/confirm-email" && (
507 <p
508 role="status"
509 className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-warn/30 bg-warn/10 px-4 py-2 text-sm"
510 >
511 <span>Confirm your email address to start using g1t.</span>
512 <Link
513 to="/confirm-email"
514 className="font-medium underline underline-offset-4"
515 >
516 Enter your code
517 </Link>
518 </p>
519 );
520 // A workspace that requires two-factor authentication of someone who
521 // has not turned it on: they keep their place, and cannot use it yet.
522 const held = user?.held &&
523 user.held.length > 0 &&
524 pathname !== "/settings/two-factor" && <PolicyNotice held={user.held} />;
525 const leaving = useLeaving();
526 // Auto, Light or Dark: as the cookie said when the page was drawn, or as just switched.
527 const theme = useThemeChoice(root?.theme);
528 // Which frame the page is drawn in (lib/chrome.ts): on its own, the app's, or the public one.
529 const frame = frameOf(pathname, {
530 signedIn: user != null && !awaitsConfirmation(user),
531 workspace: (user?.workspaces ?? []).length > 0,
532 });
533 const banner =
534 paused || verify || held ? (
535 <>
536 {paused}
537 {verify}
538 {held}
539 </>
540 ) : null;
541 return (
542 <html lang="en" data-theme={themeAttribute(theme)}>
543 <head>
544 <meta charSet="utf-8" />
545 <meta
546 name="viewport"
547 content="width=device-width, initial-scale=1, viewport-fit=cover"
548 />
549 {/* The browser bar matches the page: one colour for a chosen theme, the system's for Auto. */}
550 {theme === "auto" ? (
551 <>
552 <meta
553 name="theme-color"
554 media="(prefers-color-scheme: light)"
555 content={THEME_COLOR.light}
556 />
557 <meta
558 name="theme-color"
559 media="(prefers-color-scheme: dark)"
560 content={THEME_COLOR.dark}
561 />
562 </>
563 ) : (
564 <meta name="theme-color" content={THEME_COLOR[theme]} />
565 )}
566 <meta name="mobile-web-app-capable" content="yes" />
567 <meta name="apple-mobile-web-app-capable" content="yes" />
568 <meta
569 name="apple-mobile-web-app-status-bar-style"
570 content="black-translucent"
571 />
572 {/* The stylesheet before everything React Router preloads, so a slow
573 connection paints sooner. */}
574 <link rel="stylesheet" href={appCss} precedence="default" />
575 {root?.analyticsConsent && (
576 <meta name="g1t-analytics" content="consent" />
577 )}
578 <Meta />
579 <Links nonce={nonce} />
580 </head>
581 <body
582 className="flex min-h-screen flex-col"
583 data-frame={frame === "app" && user && root?.shell ? "app" : frame}
584 >
585 {/* The first stop for the keyboard: past the menus, to the page. */}
586 <a
587 href="#content"
588 className="sr-only rounded-md bg-fg px-3 py-2 text-sm font-medium text-bg focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-70"
589 >
590 Skip to content
591 </a>
592 {frame === "standalone" ? (
593 <StandaloneFrame>{children}</StandaloneFrame>
594 ) : frame === "app" && user && root?.shell ? (
595 <AppShell
596 user={user}
597 shell={root.shell}
598 missing={missing}
599 banner={banner}
600 sidebarClosed={root.sidebarClosed}
601 >
602 {children}
603 </AppShell>
604 ) : (
605 <>
606 <Progress />
607 <PublicHeader user={user} />
608 {banner}
609 <div
610 id="content"
611 tabIndex={-1}
612 {...leaving}
613 className={`grow outline-none ${leaving.className}`}
614 >
615 {children}
616 </div>
617 <SiteFooter user={user} />
618 </>
619 )}
620 {/* A page that cannot reach g1t says so, and keeps what it shows (lib/resilient-fetch.ts). */}
621 <ConnectionToast />
622 <NavigationRecovery />
623 {/* Live notifications for the signed-in: the feed socket, toasts, the tab's count (components/notifications). */}
624 {user && !awaitsConfirmation(user) && (
625 <LiveNotifications
626 workspace={root?.shell?.workspace?.slug ?? null}
627 inbox={root?.shell?.inbox?.unread ?? null}
628 sounds={root?.sounds ?? null}
629 me={{ id: user.id, username: user.username }}
630 />
631 )}
632 {/* Inside the desktop app: who its runner runs for, and its registration (lib/desktop-runner.ts). */}
633 {(!user || !awaitsConfirmation(user)) && (
634 <DesktopRunnerLink
635 offer={{
636 signedIn: user != null,
637 workspaces: (user?.workspaces ?? [])
638 .filter((m) => m.role === "owner")
639 .map((m) => ({ slug: m.slug, name: m.name ?? null })),
640 current: root?.shell?.workspace?.slug ?? null,
641 }}
642 />
643 )}
644 {/* Inside the desktop app: its settings dialog, and the runner's menu under the title bar's dot. */}
645 <DesktopApp />
646 <AnalyticsConsent />
647 <ScrollRestoration nonce={nonce} />
648 <Scripts nonce={nonce} />
649 </body>
650 </html>
651 );
652}
653
654export default function App() {
655 const root = useRouteLoaderData<typeof loader>("root");
656 const userId = root?.user?.id ?? null;
657 const agentDefault = root?.agentDefault ?? DEFAULT_AGENT;
658 useEffect(() => { rememberAgentDefault(agentDefault); }, [agentDefault]);
659 // Tell analytics who is signed in, once per change; signing out forgets them.
660 const lastUserId = useRef<string | null>(null);
661 useEffect(() => {
662 identify(userId, lastUserId.current);
663 lastUserId.current = userId;
664 }, [userId]);
665 // A navigation that never arrives is loaded as a whole page (lib/stuck.ts).
666 useStuckNavigationRescue();
667 return <Outlet />;
668}
669
670export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
671 return <RouteError error={error} />;
672}