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.

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