flagon-io/g1t

public

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/apps/web/app/root.tsx

461 lines16,634 bytesCodeBlame
1import {
2 BookOpen,
3 ChevronDown,
4 Compass,
5 CreditCard,
6 LayoutDashboard,
7 LogIn,
8 LogOut,
9 Plus,
10 Search,
11 Settings,
12} from "lucide-react";
13import { useState } from "react";
14import {
15 Form,
16 isRouteErrorResponse,
17 Link,
18 Links,
19 Meta,
20 NavLink,
21 Outlet,
22 Scripts,
23 ScrollRestoration,
24 type ShouldRevalidateFunctionArgs,
25 useParams,
26 useRouteLoaderData,
27 useSubmit,
28} from "react-router";
29
30import type { User } from "@g1t/contracts";
31
32import type { Route } from "./+types/root";
33import "./app.css";
34import { Logo } from "./components/logo";
35import { Avatar, ButtonLink, notACredential } from "./components/ui";
36import {
37 DropdownMenu,
38 DropdownMenuContent,
39 DropdownMenuItem,
40 DropdownMenuLabel,
41 DropdownMenuSeparator,
42 DropdownMenuTrigger,
43} from "./components/ui/dropdown-menu";
44import { AppShell, Progress, type ShellData } from "./components/shell";
45import { CommandPalette, type PaletteCommand, usePaletteShortcut } from "./components/command-palette";
46import { billing, projects, work } from "./lib/services.server";
47import { getViewer, roleIn, viewerMiddleware } from "./lib/session.server";
48
49export const links: Route.LinksFunction = () => [
50 { rel: "icon", href: "/favicon.ico", sizes: "32x32" },
51 { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" },
52 { rel: "icon", type: "image/png", sizes: "192x192", href: "/icon-192.png" },
53 { rel: "apple-touch-icon", href: "/apple-touch-icon.png" },
54 { rel: "preconnect", href: "https://fonts.googleapis.com" },
55 {
56 rel: "preconnect",
57 href: "https://fonts.gstatic.com",
58 crossOrigin: "anonymous",
59 },
60 {
61 rel: "stylesheet",
62 href: "https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,400..700&family=JetBrains+Mono:wght@400;500;600&display=swap",
63 },
64];
65
66export const middleware: Route.MiddlewareFunction[] = [viewerMiddleware];
67
68export async function loader({ context, params }: Route.LoaderArgs) {
69 const user = getViewer(context);
70 return { user, shell: user ? await shellFor(user, params) : null };
71}
72
73/**
74 * The sidebar only changes with the workspace or repository being looked
75 * at, or after something was submitted: not on every page within them.
76 */
77export function shouldRevalidate({
78 currentParams,
79 nextParams,
80 formMethod,
81 defaultShouldRevalidate,
82}: ShouldRevalidateFunctionArgs) {
83 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
84 return currentParams.owner !== nextParams.owner || currentParams.repo !== nextParams.repo;
85}
86
87/**
88 * The sidebar: the workspace being looked at if they belong to it, else
89 * their first; its repositories; and the repository being looked at.
90 */
91async function shellFor(
92 user: User,
93 params: { owner?: string; repo?: string },
94): Promise<ShellData> {
95 const memberships = user.workspaces ?? [];
96 const here = params.owner ? memberships.find((m) => m.slug === params.owner?.toLowerCase()) : undefined;
97 const workspace = here ?? memberships[0] ?? null;
98 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
99 const now = new Date();
100 const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
101 const [listed, counts, account, usage, limit] = await Promise.all([
102 workspace ? projects.list(workspace.slug, user) : Promise.resolve(null),
103 path ? work.counts(path, user) : Promise.resolve(null),
104 workspace ? billing.account(workspace.slug, user) : Promise.resolve(null),
105 workspace ? billing.usage(workspace.slug, user, monthStart) : Promise.resolve(null),
106 workspace ? billing.limit(workspace.slug, user).catch(() => null) : Promise.resolve(null),
107 ]);
108 return {
109 workspace,
110 // Projects are what the sidebar lists: what the workspace builds and runs.
111 repos: listed?.ok
112 ? listed.value.map((project) => ({
113 namespace: project.workspace,
114 name: project.slug,
115 title: project.name,
116 isPrivate: project.private,
117 }))
118 : [],
119 repo:
120 path && counts?.ok
121 ? {
122 ...path,
123 member: roleIn(user, path.namespace) != null,
124 issues: counts.value.issues,
125 pulls: counts.value.pulls,
126 }
127 : null,
128 // Where the workspace stands against its usage limit, once billing is on.
129 limit:
130 account?.ok && account.value.status.enabled && limit?.ok
131 ? {
132 exposureMicros: limit.value.exposureMicros,
133 ceilingMicros: limit.value.ceilingMicros,
134 state: limit.value.state,
135 comped: limit.value.trust === "internal",
136 }
137 : null,
138 free: account?.ok ? Boolean(account.value.status.free) : false,
139 // While g1t is free every charge is zero, so usage is shown at cost.
140 monthUsageMicros: usage?.ok ? (usage.value.free ? usage.value.usedMicros : usage.value.spentMicros) : null,
141 };
142}
143
144function HeaderLink({ to, children }: { to: string; children: React.ReactNode }) {
145 return (
146 <NavLink
147 to={to}
148 className={({ isActive }) =>
149 `rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-raised hover:text-fg ${
150 isActive ? "text-fg" : "text-muted"
151 }`
152 }
153 >
154 {children}
155 </NavLink>
156 );
157}
158
159/** What the palette offers someone without the app's sidebar. */
160const PUBLIC_COMMANDS: PaletteCommand[] = [
161 { label: "Explore", hint: "Public projects", to: "/explore", icon: <Compass size={15} /> },
162 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
163 { label: "Pricing", to: "/pricing", icon: <CreditCard size={15} /> },
164 { label: "Documentation", to: "https://docs.g1t.sh/", icon: <BookOpen size={15} /> },
165 { label: "Sign in", to: "/login", icon: <LogIn size={15} /> },
166 { label: "Sign up", to: "/register", icon: <Plus size={15} /> },
167];
168
169function Header({ user }: { user: User | null | undefined }) {
170 const submit = useSubmit();
171 const [palette, setPalette] = useState(false);
172 usePaletteShortcut(() => setPalette((open) => !open));
173 const params = useParams();
174 const repo = params.owner && params.repo ? `${params.owner}/${params.repo}` : null;
175 return (
176 <header className="sticky top-0 z-40 border-b border-line bg-surface/85 backdrop-blur">
177 <div className="mx-auto flex h-14 max-w-6xl items-center gap-2 px-4">
178 <Link to="/" aria-label="g1t home" className="mr-2">
179 <Logo />
180 </Link>
181 <Form action="/search" role="search" className="relative hidden grow sm:block sm:max-w-xs">
182 <Search
183 size={14}
184 className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-faint"
185 />
186 <input
187 name="q"
188 {...notACredential()}
189 placeholder="Search g1t"
190 aria-label="Search g1t"
191 className="w-full rounded-md border border-line bg-bg py-1.5 pr-12 pl-8 text-sm outline-none transition-colors placeholder:text-faint hover:border-line-strong focus:border-accent-dim"
192 />
193 <kbd className="pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 rounded bg-raised px-1.5 font-mono text-[0.625rem] text-muted ring-1 ring-line">
194 ⌘K
195 </kbd>
196 </Form>
197 <button
198 type="button"
199 aria-label="Search g1t"
200 onClick={() => setPalette(true)}
201 className="rounded-md p-1.5 text-muted transition-colors hover:bg-raised hover:text-fg sm:hidden"
202 >
203 <Search size={16} />
204 </button>
205 <CommandPalette
206 open={palette}
207 onOpenChange={setPalette}
208 commands={user ? [{ label: "Mission control", to: "/", icon: <LayoutDashboard size={15} /> }, ...PUBLIC_COMMANDS.slice(0, 4)] : PUBLIC_COMMANDS}
209 repo={repo}
210 />
211 <nav className="flex items-center gap-0.5">
212 <HeaderLink to="/explore">Explore</HeaderLink>
213 <HeaderLink to="/pricing">Pricing</HeaderLink>
214 <HeaderLink to="https://docs.g1t.sh/">Docs</HeaderLink>
215 </nav>
216 <div className="ml-auto flex items-center gap-2">
217 {user ? (
218 <>
219 <Link
220 to="/new"
221 aria-label="New project"
222 className="rounded-md border border-line p-1.5 text-muted transition-colors hover:border-line-strong hover:text-fg"
223 >
224 <Plus size={16} />
225 </Link>
226 <DropdownMenu>
227 <DropdownMenuTrigger
228 aria-label="Account menu"
229 className="flex items-center gap-1.5 rounded-md p-1 outline-none transition-colors hover:bg-raised data-[state=open]:bg-raised"
230 >
231 <Avatar name={user.username} image={user.avatar} size={24} />
232 <ChevronDown size={14} className="text-faint" />
233 </DropdownMenuTrigger>
234 <DropdownMenuContent align="end" className="w-56">
235 <DropdownMenuLabel>
236 Signed in as{" "}
237 <span className="font-mono font-medium text-fg">
238 {user.username}
239 </span>
240 </DropdownMenuLabel>
241 <DropdownMenuSeparator />
242 {(user.workspaces ?? []).map((membership) => (
243 <DropdownMenuItem asChild key={membership.slug}>
244 <Link to={`/${membership.slug}`}>
245 <Avatar name={membership.slug} image={membership.avatar} size={16} square />
246 <span className="min-w-0 truncate">{membership.name || membership.slug}</span>
247 </Link>
248 </DropdownMenuItem>
249 ))}
250 <DropdownMenuItem asChild>
251 <Link to="/workspaces/new">
252 <Plus />
253 New workspace
254 </Link>
255 </DropdownMenuItem>
256 <DropdownMenuSeparator />
257 <DropdownMenuItem asChild>
258 <Link to="/">
259 <LayoutDashboard />
260 Mission control
261 </Link>
262 </DropdownMenuItem>
263 <DropdownMenuItem asChild>
264 <Link to="/new">
265 <Plus />
266 New project
267 </Link>
268 </DropdownMenuItem>
269 <DropdownMenuSeparator />
270 <DropdownMenuItem asChild>
271 <Link to="/settings">
272 <Settings />
273 Settings
274 </Link>
275 </DropdownMenuItem>
276 <DropdownMenuItem asChild>
277 <Link to="https://docs.g1t.sh/quickstart/">
278 <BookOpen />
279 Documentation
280 </Link>
281 </DropdownMenuItem>
282 <DropdownMenuSeparator />
283 {/* Submitted from here: the menu closes on select, and a button
284 that has left the page cannot submit a form. */}
285 <DropdownMenuItem
286 onSelect={() => submit(null, { method: "post", action: "/logout" })}
287 >
288 <LogOut />
289 Sign out
290 </DropdownMenuItem>
291 </DropdownMenuContent>
292 </DropdownMenu>
293 </>
294 ) : (
295 <>
296 <HeaderLink to="/login">Sign in</HeaderLink>
297 <ButtonLink to="/register">Sign up</ButtonLink>
298 </>
299 )}
300 </div>
301 </div>
302 </header>
303 );
304}
305
306const FOOTER_LINKS: { title: string; links: [string, string][] }[] = [
307 {
308 title: "Product",
309 links: [
310 ["Explore repositories", "/explore"],
311 ["Pricing", "/pricing"],
312 ["g1t agents", "https://docs.g1t.sh/guides/g1t-agents/"],
313 ["Bring your own agent", "https://docs.g1t.sh/guides/bring-your-own-agent/"],
314 ["Integrations", "https://docs.g1t.sh/guides/integrations/"],
315 ["Model providers", "https://docs.g1t.sh/guides/models/"],
316 ["Sign up", "/register"],
317 ],
318 },
319 {
320 title: "Developers",
321 links: [
322 ["Quickstart", "https://docs.g1t.sh/quickstart/"],
323 ["How g1t works", "https://docs.g1t.sh/concepts/overview/"],
324 ["API reference", "https://docs.g1t.sh/reference/api/"],
325 ["OpenAPI", "https://api.g1t.sh/openapi.json"],
326 ["llms.txt", "/llms.txt"],
327 ],
328 },
329 {
330 title: "Project",
331 links: [
332 ["Source on g1t", "/syntaqx/g1t"],
333 ["MIT license", "/syntaqx/g1t/blob/main/LICENSE"],
334 ],
335 },
336];
337
338function Footer() {
339 return (
340 <footer className="mt-24 border-t border-line">
341 <div className="mx-auto flex max-w-6xl flex-wrap gap-x-20 gap-y-8 px-4 py-12">
342 <div className="grow">
343 <Logo />
344 <p className="mt-3 max-w-xs text-sm text-muted">
345 A git forge for agents. Open source under the MIT license, built on
346 Cloudflare Workers and Artifacts.
347 </p>
348 </div>
349 {FOOTER_LINKS.map((group) => (
350 <div key={group.title}>
351 <p className="text-sm font-medium">{group.title}</p>
352 <ul className="mt-3 space-y-2 text-sm text-muted">
353 {group.links.map(([label, to]) => (
354 <li key={to}>
355 {/* Plain links: some targets are files or other hosts. */}
356 <a href={to} className="hover:text-fg">
357 {label}
358 </a>
359 </li>
360 ))}
361 </ul>
362 </div>
363 ))}
364 </div>
365 <div className="border-t border-line">
366 <p className="mx-auto max-w-6xl px-4 py-5 text-xs text-faint">
367 g1t is open source software, built on Cloudflare Workers and
368 Artifacts.
369 </p>
370 </div>
371 </footer>
372 );
373}
374
375export function Layout({ children }: { children: React.ReactNode }) {
376 // Undefined when the root loader itself failed.
377 const root = useRouteLoaderData<typeof loader>("root");
378 const user = root?.user;
379 const banner = user && !user.verified && (
380 <Form
381 method="post"
382 action="/verify"
383 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"
384 >
385 <span>
386 Confirm your email address to create repositories and push. We
387 sent you a link.
388 </span>
389 <button type="submit" className="font-medium underline underline-offset-4">
390 Send it again
391 </button>
392 </Form>
393 );
394 return (
395 <html lang="en">
396 <head>
397 <meta charSet="utf-8" />
398 <meta name="viewport" content="width=device-width, initial-scale=1" />
399 <meta name="theme-color" content="#0f0f11" />
400 <Meta />
401 <Links />
402 </head>
403 <body className="flex min-h-screen flex-col">
404 {user && root?.shell ? (
405 <AppShell user={user} shell={root.shell} banner={banner}>
406 {children}
407 </AppShell>
408 ) : (
409 <>
410 <Progress />
411 <Header user={user} />
412 {banner}
413 <div className="grow">{children}</div>
414 <Footer />
415 </>
416 )}
417 <ScrollRestoration />
418 <Scripts />
419 </body>
420 </html>
421 );
422}
423
424export default function App() {
425 return <Outlet />;
426}
427
428export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
429 let title = "Something went wrong";
430 let details = "An unexpected error occurred. Try again in a moment.";
431 let stack: string | undefined;
432
433 if (isRouteErrorResponse(error)) {
434 if (error.status === 404) {
435 title = "Page not found";
436 details = "There is nothing at this address, or you do not have access to it.";
437 } else if (typeof error.data === "string" && error.data) {
438 details = error.data;
439 }
440 } else if (import.meta.env.DEV && error instanceof Error) {
441 details = error.message;
442 stack = error.stack;
443 }
444
445 return (
446 <main className="mx-auto max-w-xl px-4 py-32 text-center">
447 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
448 <p className="mt-3 text-muted">{details}</p>
449 <div className="mt-8">
450 <ButtonLink to="/" variant="quiet">
451 Back to home
452 </ButtonLink>
453 </div>
454 {stack && (
455 <pre className="mt-8 overflow-x-auto rounded-lg border border-line p-4 text-left text-xs">
456 <code>{stack}</code>
457 </pre>
458 )}
459 </main>
460 );
461}