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.

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