Skip to content
528 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 { type User, awaitsConfirmation, hasAccessIn, sharedWorkspaces } from "@g1t/contracts";
18
19import type { Route } from "./+types/root";
20import appCss from "./app.css?url";
21import displayFont from "@g1t/theme/fonts/bricolage-grotesque-latin.woff2?url";
22import sansFont from "@g1t/theme/fonts/hanken-grotesk-latin.woff2?url";
23import { ButtonLink } from "./components/ui";
24import { AppShell, Progress, type ShellData, useLeaving } from "./components/shell";
25import { SiteFooter } from "./components/footer";
26import { PublicHeader } from "./components/public-header";
27import { SpikeBanner } from "./components/spike-banner";
28import { PolicyNotice } from "./components/policy-notice";
29import { identify } from "./lib/analytics.client";
30import { visitorAsksFirst } from "./lib/analytics-consent";
31import { AnalyticsConsent } from "./components/analytics-consent";
32import { readCookie } from "./lib/mission";
33import { WORKSPACE_COOKIE, workspaceFor } from "./lib/workspace-choice";
34import { PageMain } from "./components/landmark";
35import { NotFound } from "./components/not-found";
36import { frameOf } from "./lib/chrome";
37import { DOCK_COOKIE, SIDEBAR_COOKIE, pinsToShow, sidebarClosed } from "./lib/apps";
38import { savedPins } from "./lib/dock.server";
39import { StandaloneFrame } from "./components/standalone";
40import { billing, chat, inbox, projects, workspaceAgents } from "./lib/services.server";
41import { unreadTotals } from "./lib/chat";
42import { countsFor, readableRepos } from "./lib/access.server";
43import { shortCache } from "./lib/cache.server";
44import { getViewer, viewerMiddleware } from "./lib/session.server";
45import { shortcutOf, workspaceProjects } from "./lib/workspace-projects.server";
46import { registrationMode } from "./lib/registration.server";
47import { addresses } from "./lib/addresses.server";
48import { RELOADED_KEY, RELOAD_GIVE_UP_MS, clientNavigated, reloadFixes, reloadedBefore } from "./lib/stale-build";
49import { useNonce } from "./lib/nonce";
50import { isNeedsSignIn } from "./lib/website-token";
51import { setLiveViaToken } from "./lib/live-socket";
52import { LiveNotifications } from "./components/notifications/live-notifications";
53
54
55export const links: Route.LinksFunction = () => [
56 { rel: "icon", href: "/favicon.ico", sizes: "32x32" },
57 { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" },
58 { rel: "icon", type: "image/png", sizes: "192x192", href: "/icon-192.png" },
59 { rel: "icon", type: "image/png", sizes: "512x512", href: "/icon-512.png" },
60 // Home screens and password managers look for a square, opaque 180px tile;
61 // the "-precomposed" name is served too, for the ones that ask for it.
62 { rel: "apple-touch-icon", sizes: "180x180", href: "/apple-touch-icon.png" },
63 // Installable: name, icons and colours for "Add to Home Screen" (public/site.webmanifest;
64 // manifest.webmanifest is the same file, kept for installs that already point at it).
65 { rel: "manifest", href: "/site.webmanifest" },
66 // The text and headline faces are wanted on every page, so they start
67 // loading with the stylesheet; mono waits until something uses it.
68 { rel: "preload", href: sansFont, as: "font", type: "font/woff2", crossOrigin: "anonymous" },
69 { rel: "preload", href: displayFont, as: "font", type: "font/woff2", crossOrigin: "anonymous" },
70];
71
72export const middleware: Route.MiddlewareFunction[] = [viewerMiddleware];
73
74export async function loader({ context, params, request }: Route.LoaderArgs) {
75 const user = getViewer(context);
76 const cookies = request.headers.get("cookie");
77 const chosen = readCookie(cookies, WORKSPACE_COOKIE);
78 const dock = readCookie(cookies, DOCK_COOKIE);
79 // Whether sign-up takes an invite: the sign-up page says so, and
80 // Settings → Invites offers invites to g1t only then. Cached per isolate.
81 const [shell, mode] = await Promise.all([
82 // An account still confirming its address sees only the pages that
83 // allows (lib/confirm-gate.ts), in the visitor's frame.
84 user && !awaitsConfirmation(user)
85 ? shellFor(user, params, chosen, context).catch((error: unknown) => {
86 // A sidebar that could not be read is no reason to lose the page,
87 // or to draw it as if they were signed out.
88 console.error("root: the sidebar could not be read", error);
89 return bareShell(user, params, chosen);
90 })
91 : visitorShell(params, context),
92 registrationMode(),
93 ]);
94 // The apps this person pinned to their dock here: as their account keeps
95 // them (read with the rest of the shell), else as this device's cookie
96 // remembers them (lib/apps.ts).
97 if (shell.workspace) shell.pins = pinsToShow(shell.pins, dock, shell.workspace.slug);
98 // Where this g1t lives, for clone lines, agent setup and link previews.
99 return {
100 user,
101 shell,
102 // Whether they folded the sidebar away, so the page is drawn that way from the start.
103 sidebarClosed: sidebarClosed(readCookie(cookies, SIDEBAR_COOKIE)),
104 inviteOnly: mode !== "open",
105 addresses: addresses(),
106 // Visitors from where the law asks first are asked before analytics runs.
107 analyticsConsent: visitorAsksFirst(request),
108 };
109}
110
111/**
112 * The sidebar for someone not signed in: nothing of their own, only the
113 * open counts of the project being looked at. One call, and only in a
114 * project; it answers the same for a private project as a missing one.
115 */
116async function visitorShell(params: { owner?: string; repo?: string }, context: Route.LoaderArgs["context"]): Promise<ShellData> {
117 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
118 const counts = path ? await countsFor(context, params) : null;
119 return {
120 workspace: null,
121 repos: [],
122 repo: path && counts?.ok ? { ...path, member: false, issues: counts.value.issues, pulls: counts.value.pulls } : null,
123 limit: null,
124 monthUsageMicros: null,
125 };
126}
127
128/** The sidebar from what the session already says, with no service asked. */
129function bareShell(user: User, params: { owner?: string; repo?: string }, chosen: string | null): ShellData {
130 return {
131 workspace: workspaceFor(user.workspaces ?? [], chosen, params),
132 repos: [],
133 repo: null,
134 limit: null,
135 monthUsageMicros: null,
136 };
137}
138
139/**
140 * The sidebar only changes with the workspace or repository being looked
141 * at, or after something was submitted: not on every page within them.
142 */
143export function shouldRevalidate({
144 currentParams,
145 nextParams,
146 formMethod,
147 defaultShouldRevalidate,
148}: ShouldRevalidateFunctionArgs) {
149 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
150 return currentParams.owner !== nextParams.owner || currentParams.repo !== nextParams.repo;
151}
152
153/**
154 * The sidebar: the workspace whose pages or project these are when it is
155 * one of yours, else the one you chose (lib/workspace-choice.ts); its
156 * projects; and the repository being looked at.
157 */
158async function shellFor(
159 user: User,
160 params: { owner?: string; repo?: string },
161 chosen: string | null,
162 context: Route.LoaderArgs["context"],
163): Promise<ShellData> {
164 const memberships = user.workspaces ?? [];
165 const workspace = workspaceFor(memberships, chosen, params);
166 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
167 const now = new Date();
168 const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
169 // What the sidebar shows of the workspace changes rarely: kept for a few
170 // seconds per person and workspace, except just after they changed
171 // something (lib/cache.server.ts).
172 const kept = <T,>(what: string, load: () => Promise<T>) =>
173 workspace ? shortCache(`shell:${what}:${user.id}:${workspace.slug}`, SHELL_TTL_MS, load) : Promise.resolve(null);
174 const [listed, counts, status, usage, limit, entitlements, shared, unread, shortcuts, chatUnread, teamAgents, dockPins] = await Promise.all([
175 // Every project, for the palette and the count; the sidebar lists only
176 // the person's pinned and recent ones (lib/pins.ts).
177 workspace ? workspaceProjects(workspace.slug, user) : Promise.resolve(null),
178 path ? countsFor(context, params) : Promise.resolve(null),
179 // Whether billing is on, without reading the account: that asks the
180 // card processor about the workspace's cards, too slow for every page.
181 kept("status", () => billing.status()).catch(() => null),
182 kept(`usage:${monthStart}`, () => billing.usage(workspace!.slug, user, monthStart)).catch(() => null),
183 kept("limit", () => billing.limit(workspace!.slug, user)).catch(() => null),
184 kept("entitlements", () => billing.entitlements(workspace!.slug)).catch(() => null),
185 sharedRepos(user),
186 // The bell's count: one query, never kept, so marking an item shows at once.
187 inbox.counts(user.username).catch(() => null),
188 // Never kept: opening a project moves it up Recent.
189 workspace ? projects.shortcuts(workspace.slug, user).catch(() => null) : Promise.resolve(null),
190 // The rail's Chat badge: never kept, and never waited on for long.
191 workspace ? chatUnreadFor(workspace.slug, user) : Promise.resolve(null),
192 // Home's Recent and the Agents sidebar, on every page: never waited on for long.
193 workspace ? agentsFor(workspace.slug, user) : Promise.resolve(null),
194 // The dock's pins, kept with the account so every device shows the same
195 // dock; never kept here, so a pin shows the moment it is made. Null
196 // falls back to the cookie (lib/dock.server.ts).
197 workspace ? savedPins(user, workspace.slug) : Promise.resolve(null),
198 ]);
199 return {
200 workspace,
201 // Projects are what the sidebar lists: what the workspace builds and runs.
202 repos: listed?.ok ? listed.value.map(shortcutOf) : [],
203 pinned: (shortcuts?.pinned ?? []).map(shortcutOf),
204 recent: (shortcuts?.recent ?? []).map(shortcutOf),
205 repo:
206 path && counts?.ok
207 ? {
208 ...path,
209 // Until the repository's own page says what their role is.
210 member: hasAccessIn(user, path.namespace),
211 issues: counts.value.issues,
212 pulls: counts.value.pulls,
213 }
214 : null,
215 // Where the workspace stands against its usage limit, once billing is on.
216 limit:
217 status?.enabled && limit?.ok
218 ? {
219 exposureMicros: limit.value.exposureMicros,
220 ceilingMicros: limit.value.ceilingMicros,
221 state: limit.value.state,
222 comped: limit.value.trust === "internal",
223 }
224 : null,
225 free: Boolean(status?.free),
226 // A spend spike or a hold pauses new compute: the shell says so on every page.
227 compute:
228 workspace && entitlements && (entitlements.paused || entitlements.spike?.status === "open")
229 ? { paused: entitlements.paused, spike: entitlements.spike ?? null, owner: workspace.role === "owner" }
230 : null,
231 shared,
232 inbox: unread,
233 chat: chatUnread,
234 agents: teamAgents,
235 pins: dockPins ?? undefined,
236 // While g1t is free every charge is zero, so usage is shown at cost.
237 // Usage at price, the one figure every page shows.
238 monthUsageMicros: usage?.ok ? (usage.value.free ? usage.value.usedMicros : (usage.value.priceMicros ?? usage.value.spentMicros)) : null,
239 };
240}
241
242/** Starred and recent conversations Home's sidebar lists. */
243const SHELL_CONVERSATIONS = 8;
244
245/**
246 * What is unread in chat, for the rail, and the starred and latest
247 * conversations, for Home's sidebar; null when chat is slow to answer or
248 * does not.
249 */
250async function chatUnreadFor(slug: string, user: User): Promise<ShellData["chat"]> {
251 const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), CHAT_BADGE_WAIT_MS));
252 const read = chat
253 .sidebar(slug, user)
254 .then((result) => {
255 if (!result.ok) return null;
256 const entries = result.value.entries;
257 const latest = [...entries].sort((a, b) => (b.channel.last_message_at ?? "").localeCompare(a.channel.last_message_at ?? ""));
258 return {
259 ...unreadTotals(entries),
260 starred: entries.filter((e) => e.starred).slice(0, SHELL_CONVERSATIONS),
261 recent: latest.slice(0, SHELL_CONVERSATIONS),
262 };
263 })
264 .catch(() => null);
265 return Promise.race([read, timeout]);
266}
267
268/** The workspace's agents, as the shell lists them; null when the agents service is slow or down. */
269async function agentsFor(slug: string, user: User): Promise<ShellData["agents"]> {
270 const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), CHAT_BADGE_WAIT_MS));
271 const read = workspaceAgents
272 .list(slug, user)
273 .then((result) =>
274 result.ok
275 ? result.value
276 .filter((agent) => !agent.archived_at)
277 .map((agent) => ({
278 id: agent.id,
279 handle: agent.handle,
280 display_name: agent.display_name,
281 avatar: agent.avatar,
282 avatar_seed: agent.avatar_seed,
283 role: agent.role,
284 title: agent.title,
285 team: agent.team,
286 department: agent.department,
287 status: agent.status,
288 builtin: agent.builtin === true,
289 }))
290 : null,
291 )
292 .catch(() => null);
293 return Promise.race([read, timeout]);
294}
295
296/** The longest the rail's Chat badge holds up a page. */
297const CHAT_BADGE_WAIT_MS = 300;
298
299/**
300 * How long the sidebar's workspace answers are kept: as long as someone's
301 * own changes read fresh anyway (lib/perf.ts `PRIMARY_WINDOW_SECONDS`).
302 */
303const SHELL_TTL_MS = 30_000;
304
305/** Most repositories listed under Shared with you. */
306const MAX_SHARED = 20;
307
308/**
309 * Repositories shared with the user in workspaces they do not belong to,
310 * by their grants: only those, never the workspace's other repositories.
311 */
312async function sharedRepos(user: User): Promise<ShellData["shared"]> {
313 const outside = new Set(sharedWorkspaces(user));
314 if (outside.size === 0) return [];
315 const ids = (user.grants ?? []).filter((grant) => outside.has(grant.workspace)).map((grant) => grant.repo_id).slice(0, MAX_SHARED);
316 const found = await readableRepos(ids, user);
317 return found
318 .map((repo) => ({ namespace: repo.namespace, name: repo.name, isPrivate: repo.isPrivate }))
319 .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`));
320}
321
322/**
323 * The root's data as the browser last had it. When a navigation fails in a
324 * way that takes the root's data with it, the error is still drawn in the
325 * person's own frame, signed in, not the visitor's. Never kept on the
326 * server, where one module serves everyone.
327 */
328let lastRoot: Awaited<ReturnType<typeof loader>> | undefined;
329
330export function Layout({ children }: { children: React.ReactNode }) {
331 const nonce = useNonce();
332 // Undefined when the root loader itself failed.
333 const loaded = useRouteLoaderData<typeof loader>("root");
334 const inBrowser = typeof document !== "undefined";
335 if (loaded && inBrowser) lastRoot = loaded;
336 const root = loaded ?? (inBrowser ? lastRoot : undefined);
337 const user = root?.user;
338 // A page opened with an access token signs its live sockets in with tickets (lib/live-socket.ts).
339 if (inBrowser) setLiveViaToken(Boolean(user?.token?.website));
340 const { pathname, search } = useLocation();
341 // Drawn around the error page too: a 404 keeps the sidebar out of a
342 // project or workspace the viewer cannot see.
343 const error = useRouteError();
344 const missing = isRouteErrorResponse(error) && error.status === 404;
345 // The billing page shows the full banner itself.
346 const paused = root?.shell?.compute && root.shell.workspace && !pathname.endsWith("/-/billing") && (
347 <SpikeBanner
348 compact
349 slug={root.shell.workspace.slug}
350 entitlements={{ paused: root.shell.compute.paused, spike: root.shell.compute.spike }}
351 owner={root.shell.compute.owner}
352 />
353 );
354 // On the few pages an account still confirming its address can open
355 // besides /confirm-email (policies, support, signing in): the way back.
356 const verify = user && awaitsConfirmation(user) && pathname !== "/confirm-email" && (
357 <p
358 role="status"
359 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"
360 >
361 <span>Confirm your email address to start using g1t.</span>
362 <Link to="/confirm-email" className="font-medium underline underline-offset-4">
363 Enter your code
364 </Link>
365 </p>
366 );
367 // A workspace that requires two-factor authentication of someone who
368 // has not turned it on: they keep their place, and cannot use it yet.
369 const held = user?.held && user.held.length > 0 && pathname !== "/settings/two-factor" && <PolicyNotice held={user.held} />;
370 const leaving = useLeaving();
371 // Which frame the page is drawn in (lib/chrome.ts): on its own, the app's, or the public one.
372 const frame = frameOf(pathname, {
373 signedIn: user != null && !awaitsConfirmation(user),
374 workspace: (user?.workspaces ?? []).length > 0,
375 });
376 const banner =
377 paused || verify || held ? (
378 <>
379 {paused}
380 {verify}
381 {held}
382 </>
383 ) : null;
384 return (
385 <html lang="en">
386 <head>
387 <meta charSet="utf-8" />
388 <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
389 <meta name="theme-color" content="#0f0f11" />
390 <meta name="mobile-web-app-capable" content="yes" />
391 <meta name="apple-mobile-web-app-capable" content="yes" />
392 <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
393 {/* The stylesheet before everything React Router preloads, so a slow
394 connection paints sooner. */}
395 <link rel="stylesheet" href={appCss} precedence="default" />
396 {root?.analyticsConsent && <meta name="g1t-analytics" content="consent" />}
397 <Meta />
398 <Links nonce={nonce} />
399 </head>
400 <body className="flex min-h-screen flex-col" data-frame={frame === "app" && user && root?.shell ? "app" : frame}>
401 {/* The first stop for the keyboard: past the menus, to the page. */}
402 <a
403 href="#content"
404 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]"
405 >
406 Skip to content
407 </a>
408 {frame === "standalone" ? (
409 <StandaloneFrame>{children}</StandaloneFrame>
410 ) : frame === "app" && user && root?.shell ? (
411 <AppShell user={user} shell={root.shell} missing={missing} banner={banner} sidebarClosed={root.sidebarClosed}>
412 {children}
413 </AppShell>
414 ) : (
415 <>
416 <Progress />
417 <PublicHeader user={user} />
418 {banner}
419 <div id="content" tabIndex={-1} {...leaving} className={`grow outline-none ${leaving.className}`}>
420 {children}
421 </div>
422 <SiteFooter user={user} />
423 </>
424 )}
425 {/* Live notifications for the signed-in: the feed socket, toasts, the tab's count (components/notifications). */}
426 {user && !awaitsConfirmation(user) && (
427 <LiveNotifications workspace={root?.shell?.workspace?.slug ?? null} inbox={root?.shell?.inbox?.unread ?? null} />
428 )}
429 <AnalyticsConsent />
430 <ScrollRestoration nonce={nonce} />
431 <Scripts nonce={nonce} />
432 </body>
433 </html>
434 );
435}
436
437export default function App() {
438 const userId = useRouteLoaderData<typeof loader>("root")?.user?.id ?? null;
439 // Tell analytics who is signed in, once per change; signing out forgets them.
440 const lastUserId = useRef<string | null>(null);
441 useEffect(() => {
442 identify(userId, lastUserId.current);
443 lastUserId.current = userId;
444 }, [userId]);
445 return <Outlet />;
446}
447
448export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
449 const location = useLocation();
450 const matches = useMatches();
451 const href = location.pathname + location.search + location.hash;
452 // A tab left open across a deploy: load the address again as a whole
453 // page, once, rather than show an error the reload fixes. A document load
454 // never reloads, so the server and the hydrating client render the same.
455 const reloadable = reloadFixes({
456 error,
457 status: isRouteErrorResponse(error) ? error.status : undefined,
458 clientNavigation: clientNavigated(location.key),
459 caughtByCatchAll: matches.at(-1)?.id === "routes/not-found",
460 });
461 // Already loaded again once, or the reload never started: show the page.
462 const tried = useMemo(() => reloadable && reloadedBefore(href), [reloadable, href]);
463 const [gaveUp, setGaveUp] = useState<string | null>(null);
464 const reload = reloadable && !tried && gaveUp !== href;
465 useEffect(() => {
466 if (!reload) return;
467 try {
468 sessionStorage.setItem(RELOADED_KEY, href);
469 } catch {
470 // No session storage: reload anyway; a document load never asks again.
471 }
472 window.location.assign(href);
473 const timer = window.setTimeout(() => setGaveUp(href), RELOAD_GIVE_UP_MS);
474 return () => window.clearTimeout(timer);
475 }, [reload, href]);
476 if (reload) {
477 return (
478 <PageMain className="mx-auto max-w-xl px-4 py-32 text-center text-sm text-muted" aria-busy="true">
479 <title>Loading · g1t</title>
480 Loading the latest version of g1t…
481 </PageMain>
482 );
483 }
484
485 let title = "Something went wrong";
486 let details = "An unexpected error occurred. Try again in a moment.";
487 let stack: string | undefined;
488
489 if (isRouteErrorResponse(error)) {
490 // The same page for something private and something missing.
491 if (error.status === 404) {
492 return (
493 <>
494 <title>Not found · g1t</title>
495 <NotFound data={error.data} />
496 </>
497 );
498 }
499 if (typeof error.data === "string" && error.data) {
500 details = error.data;
501 }
502 // A token asked for what needs a real sign-in (lib/website-token.ts).
503 if (isNeedsSignIn(error.data)) {
504 title = "This needs you to sign in";
505 details = error.data.message;
506 }
507 } else if (import.meta.env.DEV && error instanceof Error) {
508 details = error.message;
509 stack = error.stack;
510 }
511
512 return (
513 <PageMain className="mx-auto max-w-xl px-4 py-32 text-center">
514 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
515 <p className="mt-3 text-muted">{details}</p>
516 <div className="mt-8">
517 <ButtonLink to="/" variant="quiet">
518 Back to home
519 </ButtonLink>
520 </div>
521 {stack && (
522 <pre className="mt-8 overflow-x-auto rounded-lg border border-line p-4 text-left text-xs">
523 <code>{stack}</code>
524 </pre>
525 )}
526 </PageMain>
527 );
528}