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.

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