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.

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