Skip to content
2,164 linesCodeBlameRaw
1import { Activity, BarChart3, Building2, MessagesSquare, Bell, BookMarked, BookOpen, Bookmark, Blocks, Bot, Box, Check, ChevronDown, ChevronLeft, ChevronRight, CircleDot, GripVertical, CircleUserRound, Code2, Coins, Compass, CreditCard, Fingerprint, GanttChart, Gauge, GitBranch, GitPullRequest, Globe, History, KanbanSquare, Keyboard, KeyRound, Layers, LayoutDashboard, LayoutGrid, LifeBuoy, ListTree, Lock, LogOut, Mail, Network, Package, PanelLeft, PlayCircle, Plug, Plus, Rocket, Search, ServerCog, Settings, Shapes, ShieldCheck, Scale, Smile, Sparkles, Store, House, Ticket, TrendingUp, UserPlus, UserRoundKey, Users, UsersRound, Webhook, X, ArrowLeftRight } from "lucide-react";
2import { Fragment, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
3import { Link, NavLink, useFetcher, useLocation, useNavigation, useRouteLoaderData, useSubmit } from "react-router";
4
5import { type Abilities, type ChatSidebarEntry, type InboxCounts, type WorkspaceAgent, type Membership, type Spike, type User, hasCodeAccess, mayCreateTeams, shownUsername } from "@g1t/contracts";
6
7import { InMain } from "./landmark";
8import { CommandPalette, type PaletteCommand, PaletteKey, usePaletteShortcut } from "./command-palette";
9import { NotificationsBell } from "./inbox";
10import { SpendPill } from "./spend";
11import { PinButton } from "./pin-button";
12import { Hint } from "./ui/hint";
13import { Sheet, SheetContent, SheetTitle } from "./ui/sheet";
14import { StatusDot, useSiteStatus } from "./footer";
15import { Logo, MarkGlyph } from "./logo";
16import { Avatar, SoonPill } from "./ui";
17import { Skeleton } from "./ui/skeleton";
18import { Button } from "./ui/button";
19import { Separator } from "./ui/separator";
20import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "./ui/breadcrumb";
21import {
22 DropdownMenu,
23 DropdownMenuContent,
24 DropdownMenuGroup,
25 DropdownMenuItem,
26 DropdownMenuLabel,
27 DropdownMenuSeparator,
28 DropdownMenuTrigger,
29} from "./ui/dropdown-menu";
30import { type RoadmapItem, roadmapIn, roadmapItem } from "../lib/roadmap";
31import { type ModeKey, SETTINGS_PAGES, homePagePath, modeOf } from "../lib/workspace-nav";
32import { AgentsSidebar } from "./agents-mode";
33import { ChatSidebar } from "./chat/sidebar";
34import { FoliosSidebar } from "./folios/sidebar";
35import { Dock, ShortcutsDialog, WorkspaceSwitcher, sidebarKeyLabel } from "./dock";
36import { BottomBar, isConversation, useVisualViewport } from "./mobile";
37import { useChatSidebar } from "./chat/actions";
38import { unreadTotals } from "../lib/chat";
39import { SETTINGS_CAPABILITY, type ViewerAccess, seesSettings } from "../lib/access";
40import { projectPages } from "../lib/chrome";
41import { ACCOUNT_SETTINGS, type AccountSettingsPage, FIRST_SETTINGS_PAGE, accountSettingsPage } from "../lib/account-settings";
42import { type PinnableApp, sidebarCookie } from "../lib/apps";
43import { REASON_FILTERS, inboxReason, inboxView } from "../lib/inbox";
44import { GithubMark } from "./github";
45import { useInviteOnly } from "../lib/registration";
46import { STATUS_URL, statusTitle } from "../lib/status";
47import { type ShortcutProject, movedPin, recentWith } from "../lib/pins";
48import type { AccountMenuData } from "../routes/settings-menu-json";
49import { useLiveBadges } from "../lib/notify-client";
50import { OwnPresenceDot, OwnPresenceItems, StatusDialog } from "./presence";
51import { THEME_COMMANDS, ThemeMenuSwitch } from "./theme-switch";
52
53/**
54 * What the sidebar needs, worked out by the root loader. For a visitor who
55 * is not signed in there is no workspace, no projects and no usage: only
56 * the project being looked at, if they can see it.
57 */
58export type ShellData = {
59 /** The workspace the sidebar is about: the one being looked at, or their first. */
60 workspace: Membership | null;
61 /** All its projects, by name, for the palette: `name` is the slug in their address. */
62 repos: ShortcutProject[];
63 /** The person's pinned projects in it, in their order (lib/pins.ts). */
64 pinned?: ShortcutProject[];
65 /** What they opened there last, latest first, leaving out the pinned. */
66 recent?: ShortcutProject[];
67 /** Repositories shared with them in workspaces they do not belong to. */
68 shared?: { namespace: string; name: string; isPrivate: boolean }[];
69 /** The project being looked at, if any, whoever owns it. */
70 repo: {
71 namespace: string;
72 name: string;
73 member: boolean;
74 issues: number;
75 pulls: number;
76 } | null;
77 /** Where the workspace stands against its usage limit, if billing is on. */
78 limit: {
79 exposureMicros: number;
80 ceilingMicros: number | null;
81 state: "ok" | "warning" | "stopped";
82 comped: boolean;
83 } | null;
84 /** Whether g1t charges nothing for now, while it is being built out. */
85 free?: boolean;
86 /** What its agents have cost since the start of the month. */
87 /** This month's usage: charged, or at cost while g1t is free. */
88 monthUsageMicros: number | null;
89 /** Whether new compute is paused (a spend spike or a hold), and whether the viewer can answer it. */
90 compute?: { paused: string | null; spike: Spike | null; owner: boolean } | null;
91 /** What is unread in their notifications, for the dock and the bell. Absent for a visitor. */
92 inbox?: InboxCounts | null;
93 /**
94 * Chat, for the dock's badge: what is unread, and the
95 * starred and latest conversations. Null when chat did not answer in time.
96 */
97 chat?: { unread: number; mentions: number; starred?: ChatSidebarEntry[]; recent?: ChatSidebarEntry[] } | null;
98 /** The workspace's agents, g1t first, for the Agents sidebar; null when not known. */
99 agents?: ShellAgent[] | null;
100 /** The apps this person pinned to their dock in the workspace (lib/apps.ts). */
101 pins?: PinnableApp[];
102};
103
104/** An agent as the shell lists it. */
105export type ShellAgent = Pick<
106 WorkspaceAgent,
107 "id" | "handle" | "display_name" | "avatar" | "avatar_seed" | "role" | "status" | "title" | "team" | "department" | "builtin"
108> & { scope?: WorkspaceAgent["scope"] };
109
110function SidebarLink({
111 to,
112 icon,
113 end,
114 count,
115 also,
116 drill,
117 current: lit,
118 children,
119}: {
120 to: string;
121 icon: ReactNode;
122 end?: boolean;
123 count?: number;
124 /** Other path prefixes under which this link is the current one. */
125 also?: string | string[];
126 /** It opens a list of its own: a chevron says so, always or on hover. */
127 drill?: boolean | "hover";
128 /** Whether it is the current row, when the list works that out itself. */
129 current?: boolean;
130 children: ReactNode;
131}) {
132 const { pathname } = useLocation();
133 const navigation = useNavigation();
134 // NavLink's own pending state compares paths only, so a list whose rows
135 // differ by query (Notifications' views and reasons) would light every
136 // row while one loads. Where the list says which row is current, a row
137 // is pending only when the page on its way is that row's, query and all.
138 const loading = navigation.location;
139 const pendingHere = loading != null && `${loading.pathname}${loading.search}` === to;
140 return (
141 <NavLink
142 to={to}
143 end={end}
144 prefetch="intent"
145 className={({ isActive, isPending }) => {
146 const current =
147 lit ??
148 (isActive || [also ?? []].flat().some((prefix) => pathname === prefix || pathname.startsWith(prefix + "/")));
149 const pending = lit === undefined ? isPending : pendingHere;
150 return `group flex h-8 items-center gap-2.5 rounded-md px-2 text-[0.8125rem] transition-colors ${
151 current
152 ? "bg-raised font-medium text-fg"
153 : pending
154 ? "bg-raised/60 text-fg"
155 : "text-muted hover:bg-raised/60 hover:text-fg"
156 }`;
157 }}
158 >
159 <span className="shrink-0 text-faint group-hover:text-muted">{icon}</span>
160 <span className="min-w-0 grow truncate">{children}</span>
161 {count != null && count > 0 && (
162 <span className="rounded bg-line px-1.5 text-[0.6875rem] tabular-nums text-muted">
163 {count}
164 </span>
165 )}
166 {drill && (
167 <ChevronRight
168 size={14}
169 aria-hidden="true"
170 className={`-mr-0.5 shrink-0 text-faint transition-opacity ${drill === "hover" ? "opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100" : ""}`}
171 />
172 )}
173 </NavLink>
174 );
175}
176
177/**
178 * Something a project will have, shown where it will live so people can
179 * see where g1t is going. Not a link: nothing is behind it yet.
180 */
181function SidebarSoon({ icon, children, about }: { icon: ReactNode; children: ReactNode; about: string }) {
182 return (
183 <Hint label={about} side="right">
184 <div aria-disabled="true" className="flex h-8 cursor-default items-center gap-2.5 rounded-md px-2 text-[0.8125rem] text-faint">
185 <span className="shrink-0 opacity-70">{icon}</span>
186 <span className="grow truncate">{children}</span>
187 <span className="sr-only">{about}</span>
188 <SoonPill />
189 </div>
190 </Hint>
191 );
192}
193
194/**
195 * A page that is coming, as a link to its roadmap page: faint, with Soon,
196 * and marked current on any of its section's Soon pages.
197 */
198function SidebarSoonLink({
199 to,
200 also,
201 icon,
202 about,
203 current: lit,
204 children,
205}: {
206 to: string;
207 also?: string[];
208 icon: ReactNode;
209 about: string;
210 /** Whether it is the current row, when the list works that out itself. */
211 current?: boolean;
212 children: ReactNode;
213}) {
214 const { pathname } = useLocation();
215 return (
216 // The hint wraps a plain box: Radix's asChild merges className as a
217 // string, which would break NavLink's className function.
218 <Hint label={about} side="right">
219 <div>
220 <NavLink
221 to={to}
222 prefetch="intent"
223 className={({ isActive }) => {
224 const current = lit ?? (isActive || (also ?? []).some((prefix) => pathname === prefix || pathname.startsWith(prefix + "/")));
225 return `group flex h-8 items-center gap-2.5 rounded-md px-2 text-[0.8125rem] transition-colors ${
226 current ? "bg-raised font-medium text-fg" : "text-faint hover:bg-raised/60 hover:text-muted"
227 }`;
228 }}
229 >
230 <span className="shrink-0 opacity-80">{icon}</span>
231 <span className="min-w-0 grow truncate">{children}</span>
232 <SoonPill />
233 </NavLink>
234 </div>
235 </Hint>
236 );
237}
238
239/** Icons for what spans projects. */
240const WORKSPACE_ICONS: Record<string, ReactNode> = {
241 board: <KanbanSquare size={15} />,
242 roadmap: <GanttChart size={15} />,
243 teams: <UsersRound size={15} />,
244 packages: <Package size={15} />,
245 fleet: <Bot size={15} />,
246};
247
248/** The Soon pages of a section, as paths, so its link is current on them. */
249function soonPaths(base: string, section: RoadmapItem["section"]): string[] {
250 return roadmapIn(section).map((item) => `${base}/soon/${item.key}`);
251}
252
253function SidebarGroup({
254 title,
255 action,
256 className = "",
257 children,
258}: {
259 title: string;
260 action?: ReactNode;
261 className?: string;
262 children: ReactNode;
263}) {
264 return (
265 <section className={className}>
266 <div className="mb-1 flex h-6 items-center justify-between px-2">
267 <h2 className="text-xs font-medium text-faint">{title}</h2>
268 {action}
269 </div>
270 <div className="space-y-px">{children}</div>
271 </section>
272 );
273}
274
275/** What a workspace is called where people read it: its display name, else its slug. */
276function displayName(membership: Membership): string {
277 return membership.name?.trim() || membership.slug;
278}
279
280/**
281 * The fine print, as one quiet row at the foot of the account menu and the
282 * visitor's panel: each link a full-height target, left-aligned. In the
283 * menu each is a menu item, so the arrow keys reach it.
284 */
285const LEGAL_LINKS: [string, string][] = [
286 ["Policies", "/policies"],
287 ["Privacy", "/policies/privacy"],
288 ["Security", "/security"],
289];
290const LEGAL_LINK = "flex h-7 items-center rounded px-1.5 text-xs text-faint outline-none transition-colors";
291
292function MenuLegalRow() {
293 return (
294 <div role="group" aria-label="Legal" className="flex items-center gap-0.5 px-0.5 pt-0.5">
295 {LEGAL_LINKS.map(([label, to], index) => (
296 <span key={to} className="flex items-center gap-0.5">
297 {index > 0 && (
298 <span aria-hidden="true" className="text-[0.625rem] text-line-strong">
299 ·
300 </span>
301 )}
302 <DropdownMenuItem asChild className={`${LEGAL_LINK} py-0 data-highlighted:bg-line data-highlighted:text-fg`}>
303 <Link to={to}>{label}</Link>
304 </DropdownMenuItem>
305 </span>
306 ))}
307 </div>
308 );
309}
310
311/** Status's row: the live dot and two or three words, fetched when the menu opens. */
312function StatusSummary({ open }: { open: boolean }) {
313 const status = useSiteStatus(open);
314 const words = statusTitle(status);
315 return (
316 <span className="ml-auto flex min-w-0 items-center gap-1.5 pl-2 text-xs text-faint">
317 {/* The words say it; the dot's own words for screen readers would repeat them. */}
318 <span aria-hidden="true" className="flex">
319 <StatusDot state={status?.overall.state ?? null} />
320 </span>
321 {words ? <span className="truncate">{words}</span> : <Skeleton className="h-3 w-20" />}
322 </span>
323 );
324}
325
326/** A menu row: an icon, words, and whatever sits at its end. */
327const MENU_ROW = "h-9 gap-2.5 px-2.5 text-[0.8125rem]";
328
329/**
330 * Your account, at the foot of the dock (or in the header, before you have
331 * a workspace): who you are and your status, your profile and settings,
332 * and help: the documentation, support, status and the keyboard's
333 * shortcuts; then signing out and the fine print.
334 */
335function AccountMenu({ user, side = "right" }: { user: User; side?: "right" | "bottom" }) {
336 const submit = useSubmit();
337 const [open, setOpen] = useState(false);
338 const [keys, setKeys] = useState(false);
339 // Your status's dialog: outside the menu, so the menu closes behind it.
340 const [editing, setEditing] = useState(false);
341 // Name, primary address and invites left: asked for once, as soon as the
342 // pointer or focus reaches the button, so they are there when it opens.
343 const details = useFetcher<AccountMenuData | null>({ key: "account-menu" });
344 const prefetch = () => {
345 if (details.state === "idle" && details.data === undefined) details.load("/settings/menu.json");
346 };
347 useEffect(() => {
348 if (open) prefetch();
349 // eslint-disable-next-line react-hooks/exhaustive-deps
350 }, [open]);
351 const me = details.data ?? null;
352 // Still on its way: shapes where the words will be, the same size.
353 const loading = details.data === undefined && details.state !== "idle";
354 // While anyone can sign up, listed once the data says there are invites to look back on.
355 const invitesListed = useInviteOnly() || me?.invites_page === true;
356 const profile = `/u/${user.username}`;
357 return (
358 <>
359 <DropdownMenu open={open} onOpenChange={setOpen}>
360 {/* The avatar alone, with a dot that says how others see you (components/presence.tsx). */}
361 <DropdownMenuTrigger
362 aria-label={`Account menu for ${shownUsername(user)}`}
363 onPointerEnter={prefetch}
364 onFocus={prefetch}
365 className="relative flex rounded-full outline-none transition-transform hover:scale-[1.04] focus-visible:ring-2 focus-visible:ring-accent data-[state=open]:ring-2 data-[state=open]:ring-line-strong"
366 >
367 <Avatar name={user.username} image={user.avatar} size={side === "right" ? 32 : 28} />
368 <OwnPresenceDot ring={side === "right" ? "var(--color-dock)" : "var(--color-bg)"} className="absolute -right-0.5 -bottom-0.5" />
369 </DropdownMenuTrigger>
370 <DropdownMenuContent align="end" side={side} sideOffset={side === "right" ? 14 : 6} collisionPadding={8} className="w-[17.5rem] p-1.5">
371 {/* Who is signed in, and a way to their profile. */}
372 <DropdownMenuItem asChild className="gap-3 px-2 py-2">
373 <Link to={profile} aria-label={`${me?.name ?? shownUsername(user)} (@${shownUsername(user)}), your profile`}>
374 <Avatar name={user.username} image={user.avatar} size={36} />
375 <span className="flex min-w-0 grow flex-col leading-tight" aria-busy={loading}>
376 {loading ? (
377 <Skeleton className="my-[0.1875rem] h-3.5 w-28" />
378 ) : (
379 <span className="truncate text-sm font-medium text-fg">{me?.name ?? shownUsername(user)}</span>
380 )}
381 <span className="truncate font-mono text-xs text-muted">@{shownUsername(user)}</span>
382 {loading ? (
383 <Skeleton className="mt-1 h-3 w-40" />
384 ) : (
385 me?.email && <span className="mt-0.5 truncate text-xs text-faint">{me.email}</span>
386 )}
387 </span>
388 </Link>
389 </DropdownMenuItem>
390 <DropdownMenuSeparator className="my-1.5" />
391 {/* Your status, away, and pausing notifications. */}
392 <DropdownMenuGroup>
393 <OwnPresenceItems className="min-h-9 py-1.5 text-[0.8125rem]" onEdit={() => setEditing(true)} />
394 </DropdownMenuGroup>
395 <DropdownMenuSeparator className="my-1.5" />
396 <DropdownMenuGroup>
397 <DropdownMenuItem asChild className={MENU_ROW}>
398 <Link to={profile}>
399 <CircleUserRound />
400 Your profile
401 </Link>
402 </DropdownMenuItem>
403 <DropdownMenuItem asChild className={MENU_ROW}>
404 <Link to={FIRST_SETTINGS_PAGE}>
405 <Settings />
406 Your settings
407 </Link>
408 </DropdownMenuItem>
409 {invitesListed && (
410 <DropdownMenuItem asChild className={MENU_ROW}>
411 <Link to="/settings/invites">
412 <Ticket />
413 {ACCOUNT_SETTINGS.invites.title}
414 {loading && <Skeleton className="ml-auto h-4 w-12 rounded-full" />}
415 {me?.invites_left != null && (
416 <span className="ml-auto rounded-full bg-line px-1.5 text-[0.6875rem] tabular-nums text-muted">
417 {me.invites_left} left
418 </span>
419 )}
420 </Link>
421 </DropdownMenuItem>
422 )}
423 </DropdownMenuGroup>
424 <DropdownMenuSeparator className="my-1.5" />
425 {/* Auto, Light or Dark, switched in place (lib/theme.ts). */}
426 <ThemeMenuSwitch />
427 <DropdownMenuSeparator className="my-1.5" />
428 <DropdownMenuGroup>
429 <DropdownMenuItem asChild className={MENU_ROW}>
430 <a href="https://docs.g1t.sh/">
431 <BookOpen />
432 Documentation
433 </a>
434 </DropdownMenuItem>
435 <DropdownMenuItem asChild className={MENU_ROW}>
436 <Link to="/support">
437 <LifeBuoy />
438 Support
439 </Link>
440 </DropdownMenuItem>
441 <DropdownMenuItem asChild className={MENU_ROW}>
442 <a href={STATUS_URL}>
443 <Activity />
444 Status
445 <StatusSummary open={open} />
446 </a>
447 </DropdownMenuItem>
448 <DropdownMenuItem className={MENU_ROW} onSelect={() => setKeys(true)}>
449 <Keyboard />
450 Keyboard shortcuts
451 <PaletteKey className="ml-auto font-sans text-xs text-faint" />
452 </DropdownMenuItem>
453 </DropdownMenuGroup>
454 <DropdownMenuSeparator className="my-1.5" />
455 {/* Submitted from here: the menu closes on select, and a button
456 that has left the page cannot submit a form. */}
457 <DropdownMenuItem className={MENU_ROW} onSelect={() => submit(null, { method: "post", action: "/logout" })}>
458 <LogOut />
459 Sign out
460 </DropdownMenuItem>
461 <DropdownMenuSeparator className="my-1.5" />
462 <MenuLegalRow />
463 </DropdownMenuContent>
464 </DropdownMenu>
465 <StatusDialog open={editing} onOpenChange={setEditing} />
466 <ShortcutsDialog open={keys} onOpenChange={setKeys} />
467 </>
468 );
469}
470
471/**
472 * A workspace's settings pages, which the sidebar drills into: how it is
473 * set up and connected (guardrails, secrets, integrations,
474 * webhooks), what it pays, its repositories, tokens and record. The main
475 * list keeps the places work happens and who belongs; every member can
476 * still open these.
477 */
478const SETTINGS_PAGE =
479 new RegExp(`^/([^/]+)/-/(${SETTINGS_PAGES.join("|")})(/|$)`);
480/** A project's settings pages, which the project's menu drills into. */
481const REPO_SETTINGS_PAGE = /^\/([^/]+)\/([^/-][^/]*)\/settings(\/|$)/;
482
483/**
484 * The sidebar's lists are a stack, the way a phone pushes a screen: one
485 * drilled into slides in from the right over the full width, while the one
486 * it covers drifts a quarter of the way left and fades, both on one long
487 * ease-out, the fade quicker than the move so the two never blur together.
488 * Going back reverses it.
489 */
490const LAYER =
491 "absolute inset-0 [transition:translate_380ms_cubic-bezier(0.32,0.72,0,1),opacity_220ms_ease-out] will-change-[translate,opacity] motion-reduce:transition-none";
492/** One list, filling its layer. */
493const PANEL = "h-full overflow-y-auto px-2 pb-4";
494
495/** One list in the stack: what it is, and its rows. */
496type Level = { key: string; node: ReactNode };
497
498/** True once the page has hydrated, so what the server drew never animates in. */
499function useHydrated(): boolean {
500 const [hydrated, setHydrated] = useState(false);
501 useEffect(() => setHydrated(true), []);
502 return hydrated;
503}
504
505/**
506 * Drilling in and out of the sidebar's lists. `trail` is the way from the
507 * main list to the one shown, worked out from the address, so a link
508 * straight to a settings page opens the sidebar already drilled in, and
509 * leaving it comes back out. Lists deeper than the one shown stay in
510 * place, off to the right, so going back slides them away rather than
511 * dropping them. Moving to a list at the same depth (a workspace's settings
512 * to a project) fades the new one in where it is.
513 */
514function Drill({ trail }: { trail: Level[] }) {
515 const depth = trail.length - 1;
516 const hydrated = useHydrated();
517 const stack = useRef<Level[]>(trail);
518 const before = stack.current;
519 const within = trail.every((level, index) => before[index]?.key === level.key);
520 stack.current = within ? [...trail, ...before.slice(trail.length)] : trail;
521 const levels = stack.current;
522 // What was showing last time, to tell drilling in from moving across.
523 const shown = useRef({ depth, keys: levels.map((level) => level.key) });
524 useEffect(() => {
525 shown.current = { depth, keys: levels.map((level) => level.key) };
526 });
527 return (
528 <div className="relative min-h-0 grow overflow-hidden">
529 {levels.map((level, index) => {
530 const current = index === depth;
531 const place =
532 index < depth
533 ? "pointer-events-none -translate-x-1/4 opacity-0"
534 : current
535 ? "translate-x-0 opacity-100"
536 : "pointer-events-none translate-x-full opacity-0";
537 // A list that was not there before arrives: from the right when
538 // drilling in, in place when moving across.
539 const arriving = hydrated && current && !shown.current.keys.includes(level.key);
540 const enter = arriving
541 ? depth > shown.current.depth
542 ? "starting:translate-x-full starting:opacity-0"
543 : "starting:opacity-0"
544 : "";
545 return (
546 <div key={level.key} className={`${LAYER} ${place} ${enter}`} inert={!current} aria-hidden={!current || undefined}>
547 {level.node}
548 </div>
549 );
550 })}
551 </div>
552 );
553}
554
555/**
556 * The row at the top of a list drilled into: the list's name, which goes
557 * back out, and what it belongs to, faint at the end.
558 */
559function BackRow({ to, label, context }: { to: string; label: ReactNode; context?: ReactNode }) {
560 return (
561 <Link
562 to={to}
563 prefetch="intent"
564 className="group mt-3 flex h-8 items-center gap-1.5 rounded-md pr-2 pl-1 text-[0.8125rem] font-medium text-fg transition-colors hover:bg-raised/60"
565 >
566 <ChevronLeft size={16} className="shrink-0 text-faint transition-transform group-hover:-translate-x-0.5 group-hover:text-muted" />
567 <span className="min-w-0 shrink-0 truncate">{label}</span>
568 {context && (
569 <span className="ml-auto min-w-0 truncate pl-2 font-mono text-[0.6875rem] font-normal text-faint">{context}</span>
570 )}
571 </Link>
572 );
573}
574
575/** A thin rule between groups of a list. */
576function Rule() {
577 return <div role="separator" className="mx-2 my-2.5 h-px bg-line" />;
578}
579
580/** A quiet heading inside a group: Pinned, Recent. */
581function SidebarSubhead({ children }: { children: ReactNode }) {
582 return <h3 className="px-2 pt-1.5 pb-0.5 text-[0.6875rem] font-medium tracking-wide text-faint">{children}</h3>;
583}
584
585/**
586 * The workspace's projects as the sidebar keeps them, however many there
587 * are: the person's pins in their order, what they opened last, and the
588 * way to all of them. Pins move by dragging, or with Alt and the arrow
589 * keys; the projects service keeps the order.
590 */
591function SidebarProjects({ slug, shell, current }: { slug: string; shell: ShellData; current: boolean }) {
592 const reorder = useFetcher({ key: `pins:${slug}` });
593 const saved = shell.pinned ?? [];
594 // While a new order is on its way, it shows as made.
595 const asked = reorder.formData?.get("intent") === "reorder" ? reorder.formData.getAll("slug").map(String) : null;
596 const pinned = asked
597 ? asked.map((name) => saved.find((project) => project.name === name)).filter((project): project is ShortcutProject => project != null)
598 : saved;
599 const active = shell.repo ? { namespace: shell.repo.namespace, name: shell.repo.name, isPrivate: false } : null;
600 const recent = recentWith(shell.recent ?? [], pinned, active, slug);
601 const [dragging, setDragging] = useState<number | null>(null);
602 const move = (from: number, by: number) => {
603 const next = movedPin(pinned, from, by);
604 if (!next) return;
605 const form = new FormData();
606 form.set("intent", "reorder");
607 for (const project of next) form.append("slug", project.name);
608 reorder.submit(form, { method: "post", action: `/${slug}/-/pins` });
609 };
610 // Each row pins or unpins in place: the pin shows on hover or focus, and
611 // stays shown on a pinned row's hover so it reads as "unpin".
612 const row = (project: ShortcutProject, isPinned: boolean) => (
613 <div className="group/row relative">
614 <SidebarLink to={`/${project.namespace}/${project.name}`} icon={project.isPrivate ? <Lock size={15} /> : <Box size={15} />} drill="hover">
615 <span className="block truncate pr-6">{project.title ?? project.name}</span>
616 </SidebarLink>
617 <PinButton
618 workspace={slug}
619 slug={project.name}
620 name={project.title ?? project.name}
621 pinned={isPinned}
622 small
623 className="absolute top-1/2 right-6 -translate-y-1/2 opacity-0 transition-opacity group-hover/row:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100"
624 />
625 </div>
626 );
627 return (
628 <SidebarGroup
629 title="Projects"
630 action={
631 <Link to="/new" aria-label="New project" className="rounded p-0.5 text-faint hover:bg-raised hover:text-fg">
632 <Plus size={13} />
633 </Link>
634 }
635 >
636 {/* Only there once something is pinned: each row below has its own pin. */}
637 {pinned.length > 0 && (
638 <>
639 <SidebarSubhead>Pinned</SidebarSubhead>
640 <ul aria-label="Pinned projects" className="space-y-px">
641 {pinned.map((project, index) => (
642 <li
643 key={project.name}
644 draggable={pinned.length > 1}
645 onDragStart={(event) => {
646 setDragging(index);
647 event.dataTransfer.effectAllowed = "move";
648 }}
649 onDragOver={(event) => {
650 if (dragging != null) event.preventDefault();
651 }}
652 onDrop={(event) => {
653 event.preventDefault();
654 if (dragging != null && dragging !== index) move(dragging, index - dragging);
655 setDragging(null);
656 }}
657 onDragEnd={() => setDragging(null)}
658 onKeyDown={(event) => {
659 if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return;
660 event.preventDefault();
661 move(index, event.key === "ArrowUp" ? -1 : 1);
662 }}
663 className={`group/pin relative ${dragging === index ? "opacity-50" : ""}`}
664 >
665 {row(project, true)}
666 {pinned.length > 1 && (
667 <Hint label="Drag, or Alt and an arrow key, to reorder" side="right">
668 <span className="absolute top-1/2 -left-1.5 -translate-y-1/2 cursor-grab text-faint opacity-0 transition-opacity group-hover/pin:opacity-100">
669 <GripVertical size={12} aria-hidden="true" />
670 </span>
671 </Hint>
672 )}
673 </li>
674 ))}
675 </ul>
676 </>
677 )}
678 {recent.length > 0 && (
679 <>
680 <SidebarSubhead>Recent</SidebarSubhead>
681 {recent.map((project) => (
682 <div key={`${project.namespace}/${project.name}`}>{row(project, false)}</div>
683 ))}
684 </>
685 )}
686 <div className="pt-1">
687 <SidebarLink to={`/${slug}/-/projects`} icon={<LayoutGrid size={15} />} count={shell.repos.length} current={current}>
688 All projects
689 </SidebarLink>
690 </div>
691 </SidebarGroup>
692 );
693}
694
695/** Insights, coming: the workspace's own page says what it will be. */
696const INSIGHTS = roadmapItem("insights");
697
698/**
699 * What the repository menu needs. Known from the address before the page's
700 * data arrives, so the menu is right from the first frame; the counts fill
701 * in once it does.
702 */
703type MenuRepo = {
704 namespace: string;
705 name: string;
706 member: boolean;
707 /** Whether they see its settings; from the repository's page once it loads. */
708 settings?: boolean;
709 /** What they may do there, once the repository's page loads. */
710 can?: Abilities;
711 issues?: number;
712 pulls?: number;
713};
714
715function sameRepo(a: { namespace: string; name: string } | null, b: { namespace: string; name: string } | null) {
716 return (
717 a != null &&
718 b != null &&
719 a.namespace.toLowerCase() === b.namespace.toLowerCase() &&
720 a.name.toLowerCase() === b.name.toLowerCase()
721 );
722}
723
724/**
725 * A project's own list, drilled into while you are in it: everything about
726 * the project, running and its code, and nothing else, with the way back
727 * out to all of them.
728 */
729function RepoMenu({
730 repo,
731 isPrivate,
732 back,
733}: {
734 repo: MenuRepo;
735 isPrivate: boolean;
736 /** Where the way back leads: the workspace's projects, mission control, or Explore. */
737 back: { to: string; label: string };
738}) {
739 const base = `/${repo.namespace}/${repo.name}`;
740 // What a member sees, and what everyone who can see the project does.
741 const shows = new Set(projectPages(repo.member, repo.can));
742 return (
743 <nav aria-label={`${repo.namespace}/${repo.name}`} className={PANEL}>
744 <BackRow to={back.to} label={back.label} />
745 <Hint label="Overview" side="right">
746 <div>
747 <NavLink
748 to={base}
749 end
750 prefetch="intent"
751 className={({ isActive }) =>
752 `mt-2 flex items-center gap-2 rounded-md px-2 py-1.5 transition-colors ${isActive ? "bg-raised" : "hover:bg-raised/60"}`
753 }
754 >
755 <span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-raised text-muted ring-1 ring-line">
756 {isPrivate ? <Lock size={13} /> : <Box size={13} />}
757 </span>
758 <span className="min-w-0 truncate font-mono text-[0.8125rem]">
759 <span className="text-faint">{repo.namespace}/</span>
760 <span className="font-semibold text-fg">{repo.name}</span>
761 </span>
762 </NavLink>
763 </div>
764 </Hint>
765 {/* A project's pages, in the order people use them. A page with more
766 than one view shows them as tabs across its top. */}
767 <Rule />
768 <div className="space-y-px">
769 <SidebarLink to={`${base}/code`} also={[`${base}/tree`, `${base}/blob`, `${base}/commits`, `${base}/commit`, `${base}/branches`, `${base}/tags`, `${base}/compare`, ...soonPaths(base, "Code")]} icon={<Code2 size={15} />}>
770 Code
771 </SidebarLink>
772 <SidebarLink to={`${base}/issues`} also={[`${base}/plans`, `${base}/milestones`, `${base}/labels`, ...soonPaths(base, "Issues")]} icon={<CircleDot size={15} />} count={repo.issues}>
773 Issues
774 </SidebarLink>
775 <SidebarLink to={`${base}/pulls`} also={[`${base}/pull`, `${base}/queue`]} icon={<GitPullRequest size={15} />} count={repo.pulls}>
776 Pull requests
777 </SidebarLink>
778 <SidebarLink to={`${base}/agents`} also={[`${base}/sessions`, `${base}/memory`, ...soonPaths(base, "Agents")]} icon={<Bot size={15} />}>
779 Agents
780 </SidebarLink>
781 <SidebarLink to={`${base}/actions`} icon={<PlayCircle size={15} />}>
782 Workflows
783 </SidebarLink>
784 </div>
785 <Rule />
786 <div className="space-y-px">
787 {shows.has("deployments") ? (
788 <SidebarLink to={`${base}/deployments`} also={soonPaths(base, "Deployments")} icon={<Rocket size={15} />}>
789 Deployments
790 </SidebarLink>
791 ) : null}
792 <SidebarSoonLink to={`${base}/soon/logs`} also={soonPaths(base, "Observability")} icon={<Activity size={15} />} about="Logs, errors, uptime and analytics of the project's deployed apps.">
793 Observability
794 </SidebarSoonLink>
795 {shows.has("security") ? (
796 <SidebarLink to={`${base}/security`} also={soonPaths(base, "Security")} icon={<ShieldCheck size={15} />}>
797 Security
798 </SidebarLink>
799 ) : null}
800 <SidebarLink
801 to={`${base}/contributors`}
802 also={[`${base}/activity`, `${base}/stargazers`, ...soonPaths(base, "Insights")]}
803 icon={<BarChart3 size={15} />}
804 >
805 Insights
806 </SidebarLink>
807 </div>
808 {(repo.settings ?? shows.has("settings")) && (
809 <>
810 <Rule />
811 <SidebarLink to={`${base}/settings`} icon={<Settings size={15} />} drill>
812 Settings
813 </SidebarLink>
814 </>
815 )}
816 </nav>
817 );
818}
819
820/**
821 * A project's settings, drilled into from its list: what is about running
822 * it, then its agents, then its code and who can reach it. The way back
823 * leads to the project.
824 */
825function RepoSettingsMenu({ repo }: { repo: MenuRepo }) {
826 const base = `/${repo.namespace}/${repo.name}`;
827 // Each page shows to the roles that can use it, once the role is known.
828 const shows = (page: string) => !repo.can || repo.can[SETTINGS_CAPABILITY[page] ?? "administer"];
829 const running = shows("deployments");
830 const agents = shows("agents") || shows("guardrails");
831 return (
832 <nav aria-label={`${repo.namespace}/${repo.name} settings`} className={PANEL}>
833 <BackRow to={base} label="Settings" context={`${repo.namespace}/${repo.name}`} />
834 {shows("") && (
835 <div className="mt-2 space-y-px">
836 <SidebarLink to={`${base}/settings`} end icon={<Settings size={15} />}>
837 General
838 </SidebarLink>
839 </div>
840 )}
841 {running && (
842 <>
843 {shows("") && <Rule />}
844 <div className={shows("") ? "space-y-px" : "mt-2 space-y-px"}>
845 <SidebarLink to={`${base}/settings/deployments`} icon={<Rocket size={15} />}>
846 Deployments
847 </SidebarLink>
848 <SidebarLink to={`${base}/settings/domains`} icon={<Globe size={15} />}>
849 Domains
850 </SidebarLink>
851 </div>
852 </>
853 )}
854 {agents && (
855 <>
856 <Rule />
857 <div className="space-y-px">
858 {shows("agents") && (
859 <SidebarLink to={`${base}/settings/agents`} icon={<Bot size={15} />}>
860 Agents
861 </SidebarLink>
862 )}
863 {shows("guardrails") && (
864 <SidebarLink to={`${base}/settings/guardrails`} icon={<ShieldCheck size={15} />}>
865 Guardrails
866 </SidebarLink>
867 )}
868 </div>
869 </>
870 )}
871 <Rule />
872 <div className="space-y-px">
873 {shows("repository") && (
874 <SidebarLink to={`${base}/settings/repository`} icon={<BookMarked size={15} />}>
875 Repository
876 </SidebarLink>
877 )}
878 {shows("mirroring") && (
879 <SidebarLink to={`${base}/settings/mirroring`} icon={<ArrowLeftRight size={15} />}>
880 Mirroring
881 </SidebarLink>
882 )}
883 {shows("access") && (
884 <SidebarLink to={`${base}/settings/access`} icon={<Users size={15} />}>
885 Access
886 </SidebarLink>
887 )}
888 {shows("keys") && (
889 <SidebarLink to={`${base}/settings/keys`} icon={<KeyRound size={15} />}>
890 Deploy keys
891 </SidebarLink>
892 )}
893 {shows("branches") && (
894 <SidebarLink to={`${base}/settings/branches`} icon={<GitBranch size={15} />}>
895 Branches and merging
896 </SidebarLink>
897 )}
898 {shows("rules") && (
899 <SidebarLink to={`${base}/settings/rules`} icon={<Scale size={15} />}>
900 Rules
901 </SidebarLink>
902 )}
903 {shows("secrets") && (
904 <SidebarLink to={`${base}/settings/secrets`} icon={<Lock size={15} />}>
905 Secrets and variables
906 </SidebarLink>
907 )}
908 {shows("actions") && (
909 <SidebarLink to={`${base}/settings/actions`} icon={<PlayCircle size={15} />}>
910 Actions
911 </SidebarLink>
912 )}
913 {shows("environments") && (
914 <SidebarLink to={`${base}/settings/environments`} icon={<Layers size={15} />}>
915 Environments
916 </SidebarLink>
917 )}
918 {shows("runners") && (
919 <SidebarLink to={`${base}/settings/runners`} icon={<ServerCog size={15} />}>
920 Runners
921 </SidebarLink>
922 )}
923 {shows("webhooks") && (
924 <SidebarLink to={`${base}/settings/webhooks`} icon={<Webhook size={15} />}>
925 Webhooks
926 </SidebarLink>
927 )}
928 </div>
929 </nav>
930 );
931}
932
933/**
934 * Whether the menus list Settings → Invites (invites to g1t): always while
935 * sign-up takes an invite; once anyone can sign up, only for someone with
936 * invites already made to look back on, which the account menu's data says.
937 */
938function useInvitesListed(): boolean {
939 const inviteOnly = useInviteOnly();
940 const details = useFetcher<AccountMenuData | null>({ key: "account-menu" });
941 useEffect(() => {
942 if (!inviteOnly && details.state === "idle" && details.data === undefined) details.load("/settings/menu.json");
943 // eslint-disable-next-line react-hooks/exhaustive-deps
944 }, [inviteOnly]);
945 return inviteOnly || details.data?.invites_page === true;
946}
947
948/** Your own settings, drilled into from Your settings: one page each. */
949function AccountSettingsMenu({ username }: { username: string }) {
950 const invites = useInvitesListed();
951 const link = (page: AccountSettingsPage, icon: ReactNode) => (
952 <SidebarLink to={`/settings/${page}`} icon={icon}>
953 {ACCOUNT_SETTINGS[page].title}
954 </SidebarLink>
955 );
956 return (
957 <nav aria-label="Your settings" className={PANEL}>
958 <BackRow to="/" label="Your settings" context={username} />
959 <div className="mt-2 space-y-px">
960 {link("profile", <CircleUserRound size={15} />)}
961 {link("emails", <Mail size={15} />)}
962 {invites && link("invites", <Ticket size={15} />)}
963 </div>
964 <Rule />
965 <div className="space-y-px">
966 {link("keys", <Fingerprint size={15} />)}
967 {link("tokens", <KeyRound size={15} />)}
968 </div>
969 <Rule />
970 <div className="space-y-px">
971 {link("integrations", <Blocks size={15} />)}
972 {link("github", <GithubMark className="size-[15px]" />)}
973 {link("applications", <Plug size={15} />)}
974 </div>
975 <Rule />
976 <div className="space-y-px">
977 {link("two-factor", <ShieldCheck size={15} />)}
978 {link("security-log", <History size={15} />)}
979 </div>
980 </nav>
981 );
982}
983
984/**
985 * Code's sidebar: its Overview, the projects, what spans them and what is
986 * coming; in a project, drilled into the project's own list, and its
987 * settings one level further in. The address says which, so a link
988 * straight to a project opens the sidebar already drilled in.
989 */
990function CodeSidebar({
991 user,
992 shell,
993 missing = false,
994}: {
995 user: User;
996 shell: ShellData;
997 /** The page is a 404: the address names nothing the viewer can see. */
998 missing?: boolean;
999}) {
1000 const ws = shell.workspace;
1001 const { pathname } = useLocation();
1002 const going = useNavigation().location?.pathname;
1003 // Where the sidebar is drilled to follows the page being gone to, so it
1004 // moves as the link is followed, not once the page arrives.
1005 const target = going ?? pathname;
1006 // On a 404, the address is not a place: no list is drilled into from it,
1007 // except the project's own when the project is real and visible and only
1008 // something inside it is missing (a file, a commit, an issue).
1009 const lost = missing && going == null;
1010 const active = shell.repo;
1011 // In a repository, or on the way into one, its own list.
1012 const repoPath = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(target);
1013 const reserved = new Set(["settings", "explore", "search", "new", "u", "pricing", "avatars", "workspaces", "login", "logout", "register", "verify", "forgot", "reset", "device", "oauth", "policies", "security", "support", "status", "invite", "notifications", "inbox", ".well-known"]);
1014 // An invitation to a repository is answered before its menu means anything.
1015 const inRepo =
1016 repoPath != null &&
1017 !reserved.has(repoPath[1]) &&
1018 repoPath[2] !== "-" &&
1019 !/^\/[^/]+\/[^/]+\/invitations\/?$/.test(target) &&
1020 (!lost || sameRepo(active, { namespace: repoPath[1]!, name: repoPath[2]! }));
1021 // A project's settings, one level further in.
1022 const inRepoSettings = inRepo && REPO_SETTINGS_PAGE.test(target);
1023 // The repository the menu is for: the one loaded if it is the one being
1024 // gone to, else what the address says, at once.
1025 const targetRepo = inRepo && repoPath ? { namespace: repoPath[1], name: repoPath[2] } : null;
1026 const guessed: MenuRepo | null = targetRepo
1027 ? sameRepo(active, targetRepo)
1028 ? active
1029 : {
1030 ...targetRepo,
1031 member: (user.workspaces ?? []).some((m) => m.slug === targetRepo.namespace.toLowerCase()),
1032 }
1033 : null;
1034 // The viewer's role there, from the repository's page once it has loaded.
1035 const page = useRouteLoaderData("routes/repo/layout") as
1036 | { repo?: { namespace: string; name: string }; access?: ViewerAccess }
1037 | undefined;
1038 const menuRepo: MenuRepo | null =
1039 guessed && page?.access && page.repo && sameRepo(page.repo, guessed)
1040 ? { ...guessed, member: page.access.insider, settings: seesSettings(page.access), can: page.access.can }
1041 : guessed;
1042
1043 // The way from Code's list to the one shown.
1044 const trail: Level[] = [{ key: "main", node: ws ? <CodeMenu shell={shell} slug={ws.slug} /> : null }];
1045 if (menuRepo) {
1046 const key = `repo:${menuRepo.namespace}/${menuRepo.name}`.toLowerCase();
1047 // Out of a project: to its workspace's projects when they are yours.
1048 const home = (user.workspaces ?? []).find((m) => m.slug === menuRepo.namespace.toLowerCase());
1049 const back = home ? { to: `/${home.slug}/-/projects`, label: "All projects" } : { to: ws ? `/${ws.slug}/-/overview` : "/explore", label: "Code" };
1050 trail.push({
1051 key,
1052 node: (
1053 <RepoMenu
1054 repo={menuRepo}
1055 isPrivate={[...shell.repos, ...(shell.shared ?? [])].some((repo) => sameRepo(repo, menuRepo) && repo.isPrivate)}
1056 back={back}
1057 />
1058 ),
1059 });
1060 if (inRepoSettings) trail.push({ key: `${key}:settings`, node: <RepoSettingsMenu repo={menuRepo} /> });
1061 }
1062
1063 return (
1064 <div className="flex h-full flex-col">
1065 <ModeHeader title="Code" />
1066 <Drill trail={trail} />
1067 </div>
1068 );
1069}
1070
1071/**
1072 * A mode's sidebar heading: its name, quiet, under the workspace's
1073 * switcher, with what it makes at the end.
1074 */
1075export function ModeHeader({ title, action }: { title: ReactNode; action?: ReactNode }) {
1076 return (
1077 <div className="flex h-9 shrink-0 items-center gap-1 pr-1 pl-3">
1078 <h2 className="min-w-0 grow truncate text-xs font-medium text-faint">{title}</h2>
1079 {action}
1080 </div>
1081 );
1082}
1083
1084/**
1085 * Code's own list (beside the dock): only code. Its Overview (Mission
1086 * control's code panels), the projects, what spans them, and what is
1087 * coming. The workspace's people, money and settings are elsewhere;
1088 * agents, context and memory are Agents'.
1089 */
1090function CodeMenu({ shell, slug }: { shell: ShellData; slug: string }) {
1091 const { pathname } = useLocation();
1092 const going = useNavigation().location?.pathname;
1093 const path = going ?? pathname;
1094 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1095 const shared = shell.shared ?? [];
1096 return (
1097 <nav aria-label="Code" className={PANEL}>
1098 <div className="space-y-px">
1099 <SidebarLink to={`/${slug}/-/overview`} icon={<LayoutDashboard size={15} />} current={at("overview")}>
1100 Overview
1101 </SidebarLink>
1102 </div>
1103 <div className="mt-3">
1104 <SidebarProjects slug={slug} shell={shell} current={at("projects")} />
1105 </div>
1106 <Rule />
1107 <div className="space-y-px">
1108 <SidebarLink to={`/${slug}/-/security`} icon={<ShieldCheck size={15} />} current={at("security") && !at("security/settings")}>
1109 Security
1110 </SidebarLink>
1111 <SidebarLink to={`/${slug}/-/packages`} icon={<Package size={15} />} current={at("packages")}>
1112 Packages
1113 </SidebarLink>
1114 {INSIGHTS && (
1115 <SidebarSoonLink to={`/${slug}/-/insights`} icon={<TrendingUp size={15} />} about={INSIGHTS.summary} current={at("insights")}>
1116 {INSIGHTS.title}
1117 </SidebarSoonLink>
1118 )}
1119 {roadmapIn("Workspace")
1120 .filter((item) => item.key !== "insights" && item.key !== "teams" && item.key !== "fleet")
1121 .map((item) => (
1122 <SidebarSoonLink key={item.key} to={`/${slug}/-/soon/${item.key}`} icon={WORKSPACE_ICONS[item.key] ?? <Sparkles size={15} />} about={item.summary}>
1123 {item.title === "Board" ? "Boards" : item.title}
1124 </SidebarSoonLink>
1125 ))}
1126 </div>
1127 {shared.length > 0 && (
1128 <>
1129 <Rule />
1130 <SidebarGroup title="Shared with you">
1131 {shared.map((repo) => (
1132 <SidebarLink
1133 key={`${repo.namespace}/${repo.name}`}
1134 to={`/${repo.namespace}/${repo.name}`}
1135 icon={repo.isPrivate ? <Lock size={15} /> : <Box size={15} />}
1136 drill="hover"
1137 >
1138 <span className="font-mono text-faint">{repo.namespace}/</span>
1139 {repo.name}
1140 </SidebarLink>
1141 ))}
1142 </SidebarGroup>
1143 </>
1144 )}
1145 </nav>
1146 );
1147}
1148
1149/** Workspace pages that sit in its Settings list, drilled into from the Workspace sidebar. */
1150const WORKSPACE_SETTINGS = ["settings", "repositories", "tokens", "personal-access-tokens", "secrets", "actions", "webhooks", "emoji"];
1151
1152/**
1153 * The Workspace mode's sidebar: the workspace itself, for every member.
1154 * Its overview, money, machines, connections, policies and record, then its
1155 * settings as a list of their own. Owner-only pages stay owner-only.
1156 */
1157export function WorkspaceSidebar({ slug, owner }: { slug: string; owner: boolean }) {
1158 const { pathname } = useLocation();
1159 const going = useNavigation().location?.pathname;
1160 const path = going ?? pathname;
1161 const page = path.startsWith(`/${slug}/-/`) ? path.slice(`/${slug}/-/`.length) : "";
1162 const top = page.split("/")[0] ?? "";
1163 const at = (...pages: string[]) => pages.some((p) => page === p || page.startsWith(`${p}/`));
1164 const inSettings = WORKSPACE_SETTINGS.includes(top);
1165 const main = (
1166 <nav aria-label="Workspace" className={PANEL}>
1167 <div className="space-y-px">
1168 <SidebarLink to={`/${slug}/-/workspace`} icon={<LayoutGrid size={15} />} current={at("workspace")}>
1169 Overview
1170 </SidebarLink>
1171 </div>
1172 <SidebarGroup title="Money" className="mt-3">
1173 <SidebarLink to={`/${slug}/-/spend`} icon={<Coins size={15} />} current={at("spend")}>
1174 Spend
1175 </SidebarLink>
1176 <SidebarLink to={`/${slug}/-/usage`} icon={<BarChart3 size={15} />} current={at("usage")}>
1177 Usage
1178 </SidebarLink>
1179 <SidebarLink to={`/${slug}/-/gateway`} icon={<Network size={15} />} current={at("gateway")}>
1180 AI Gateway
1181 </SidebarLink>
1182 <SidebarLink to={`/${slug}/-/billing`} icon={<CreditCard size={15} />} current={at("billing")}>
1183 Billing and plans
1184 </SidebarLink>
1185 </SidebarGroup>
1186 {owner && (
1187 <SidebarGroup title="Compute" className="mt-3">
1188 <SidebarLink to={`/${slug}/-/runners`} icon={<ServerCog size={15} />} current={at("runners")}>
1189 Runners
1190 </SidebarLink>
1191 </SidebarGroup>
1192 )}
1193 <SidebarGroup title="Connections" className="mt-3">
1194 <SidebarLink to={`/${slug}/-/integrations`} icon={<Plug size={15} />} current={at("integrations")}>
1195 Integrations
1196 </SidebarLink>
1197 </SidebarGroup>
1198 <SidebarGroup title="Security policies" className="mt-3">
1199 <SidebarLink to={`/${slug}/-/security/settings`} icon={<ShieldCheck size={15} />} current={at("security/settings")}>
1200 Security settings
1201 </SidebarLink>
1202 <SidebarLink to={`/${slug}/-/guardrails`} icon={<Gauge size={15} />} current={at("guardrails")}>
1203 Guardrails
1204 </SidebarLink>
1205 <SidebarLink to={`/${slug}/-/rules`} icon={<Scale size={15} />} current={at("rules")}>
1206 Rules
1207 </SidebarLink>
1208 </SidebarGroup>
1209 <Rule />
1210 <div className="space-y-px">
1211 <SidebarLink to={`/${slug}/-/audit`} icon={<History size={15} />} current={at("audit")}>
1212 Audit log
1213 </SidebarLink>
1214 <SidebarLink to={owner ? `/${slug}/-/settings` : `/${slug}/-/repositories`} icon={<Settings size={15} />} drill current={inSettings}>
1215 Settings
1216 </SidebarLink>
1217 </div>
1218 </nav>
1219 );
1220 const settings = (
1221 <nav aria-label="Workspace settings" className={PANEL}>
1222 <BackRow to={`/${slug}/-/workspace`} label="Settings" context={slug} />
1223 <div className="mt-2 space-y-px">
1224 {owner && (
1225 <SidebarLink to={`/${slug}/-/settings`} icon={<Settings size={15} />} end>
1226 General
1227 </SidebarLink>
1228 )}
1229 <SidebarLink to={`/${slug}/-/settings/chat`} icon={<MessagesSquare size={15} />}>
1230 Chat
1231 </SidebarLink>
1232 <SidebarLink to={`/${slug}/-/repositories`} icon={<BookMarked size={15} />}>
1233 Repositories
1234 </SidebarLink>
1235 <SidebarLink to={`/${slug}/-/tokens`} icon={<KeyRound size={15} />}>
1236 Access tokens
1237 </SidebarLink>
1238 {owner && (
1239 <SidebarLink to={`/${slug}/-/personal-access-tokens`} icon={<UserRoundKey size={15} />}>
1240 Personal access tokens
1241 </SidebarLink>
1242 )}
1243 <SidebarLink to={`/${slug}/-/webhooks`} icon={<Webhook size={15} />}>
1244 Webhooks
1245 </SidebarLink>
1246 <SidebarLink to={`/${slug}/-/emoji`} icon={<Smile size={15} />}>
1247 Emoji
1248 </SidebarLink>
1249 </div>
1250 <SidebarGroup title="Runs" className="mt-3">
1251 <SidebarLink to={`/${slug}/-/secrets`} icon={<Lock size={15} />}>
1252 Secrets and variables
1253 </SidebarLink>
1254 <SidebarLink to={`/${slug}/-/actions`} icon={<PlayCircle size={15} />}>
1255 Actions
1256 </SidebarLink>
1257 </SidebarGroup>
1258 </nav>
1259 );
1260 const trail: Level[] = [{ key: "workspace", node: main }];
1261 if (inSettings) trail.push({ key: "workspace:settings", node: settings });
1262 return (
1263 <div className="flex h-full flex-col">
1264 <ModeHeader title="Workspace" />
1265 <Drill trail={trail} />
1266 </div>
1267 );
1268}
1269
1270/**
1271 * People's sidebar: everyone in the workspace, people and agents; its
1272 * teams; the org chart; and, to manage who belongs, members and invites.
1273 */
1274function PeopleSidebar({ slug }: { slug: string }) {
1275 const { pathname } = useLocation();
1276 const going = useNavigation().location?.pathname;
1277 const path = going ?? pathname;
1278 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1279 return (
1280 <div className="flex h-full flex-col">
1281 <ModeHeader title="People" />
1282 <nav aria-label="People" className={PANEL}>
1283 <div className="space-y-px">
1284 <SidebarLink to={`/${slug}/-/people`} icon={<Users size={15} />} current={at("people")}>
1285 Everyone
1286 </SidebarLink>
1287 <SidebarLink to={`/${slug}/-/teams`} icon={<UsersRound size={15} />} current={at("teams")}>
1288 Teams
1289 </SidebarLink>
1290 <SidebarLink to={`/${slug}/-/org-chart`} icon={<Network size={15} />} current={at("org-chart")}>
1291 Org chart
1292 </SidebarLink>
1293 </div>
1294 <SidebarGroup title="Membership" className="mt-3">
1295 <SidebarLink to={`/${slug}/-/members`} icon={<UserPlus size={15} />} current={at("members")}>
1296 Members and invites
1297 </SidebarLink>
1298 </SidebarGroup>
1299 </nav>
1300 </div>
1301 );
1302}
1303
1304/**
1305 * Notifications' sidebar: what you have not finished with, what you saved
1306 * and what is done; then why you were told, which narrows any of them.
1307 */
1308function NotificationsSidebar({ counts }: { counts: InboxCounts | null }) {
1309 const { search } = useLocation();
1310 const params = new URLSearchParams(search);
1311 const view = inboxView(params.get("view"));
1312 const reason = inboxReason(params.get("reason"));
1313 const tab = params.get("tab");
1314 const address = (changes: Record<string, string | null>) => {
1315 const merged: Record<string, string | null> = { tab, view: view === "inbox" ? null : view, reason, ...changes };
1316 const next = new URLSearchParams();
1317 for (const [name, value] of Object.entries(merged)) if (value) next.set(name, value);
1318 const query = next.toString();
1319 return query ? `/notifications?${query}` : "/notifications";
1320 };
1321 const views = [
1322 { view: "inbox", label: "Everything", icon: <Bell size={15} />, count: counts?.unread },
1323 { view: "saved", label: "Saved", icon: <Bookmark size={15} /> },
1324 { view: "done", label: "Done", icon: <Check size={15} /> },
1325 ] as const;
1326 return (
1327 <div className="flex h-full flex-col">
1328 <ModeHeader title="Notifications" />
1329 <nav aria-label="Notifications" className={PANEL}>
1330 <div className="space-y-px">
1331 {views.map((entry) => (
1332 <SidebarLink
1333 key={entry.view}
1334 to={address({ view: entry.view === "inbox" ? null : entry.view, before: null })}
1335 icon={entry.icon}
1336 count={"count" in entry ? (entry.count ?? undefined) : undefined}
1337 current={view === entry.view}
1338 >
1339 {entry.label}
1340 </SidebarLink>
1341 ))}
1342 </div>
1343 <SidebarGroup title="Why you were told" className="mt-4">
1344 {REASON_FILTERS.map((entry) => (
1345 <SidebarLink
1346 key={entry.reason ?? "any"}
1347 to={address({ reason: entry.reason, before: null })}
1348 icon={<span className="block size-[15px]" />}
1349 current={reason === entry.reason}
1350 >
1351 {entry.reason == null ? "Any reason" : entry.label}
1352 </SidebarLink>
1353 ))}
1354 </SidebarGroup>
1355 </nav>
1356 </div>
1357 );
1358}
1359
1360/** Your own settings, beside the page: under the account menu, not any workspace's. */
1361export function AccountSidebar({ username }: { username: string }) {
1362 return (
1363 <div className="flex h-full flex-col">
1364 <ModeHeader title="Your account" />
1365 <div className="min-h-0 grow">
1366 <AccountSettingsMenu username={username} />
1367 </div>
1368 </div>
1369 );
1370}
1371
1372/** Words for the sections a path can end in. */
1373const SECTIONS: Record<string, string> = {
1374 issues: "Issues",
1375 milestones: "Milestones",
1376 labels: "Labels",
1377 pulls: "Pull requests",
1378 queue: "Merge queue",
1379 commits: "Commits",
1380 plans: "Outcomes",
1381 actions: "Workflows",
1382 soon: "Soon",
1383 deployments: "Deployments",
1384 repository: "Repository",
1385 access: "Access",
1386 invitations: "Invitation",
1387 repositories: "Repositories",
1388 branches: "Branches",
1389 tags: "Tags",
1390 compare: "Compare",
1391 code: "Files",
1392 secrets: "Secrets and variables",
1393 settings: "Settings",
1394 people: "People",
1395 "org-chart": "Org chart",
1396 members: "Members and invites",
1397 projects: "Projects",
1398 teams: "Teams",
1399 tokens: "Access tokens",
1400 "personal-access-tokens": "Personal access tokens",
1401 spend: "Spend",
1402 receipts: "Receipts",
1403 usage: "Usage",
1404 gateway: "AI Gateway",
1405 billing: "Billing and plans",
1406 integrations: "Integrations",
1407 webhooks: "Webhooks",
1408 emoji: "Emoji",
1409 domains: "Domains",
1410 guardrails: "Guardrails",
1411 rules: "Rules",
1412 audit: "Audit log",
1413 tree: "Files",
1414 blob: "Files",
1415 agents: "Agents",
1416 context: "Context",
1417 memory: "Memory",
1418 security: "Security",
1419 packages: "Packages",
1420 runners: "Runners",
1421 environments: "Environments",
1422 workflows: "Workflows",
1423 observability: "Observability",
1424 insights: "Insights",
1425 sessions: "Sessions",
1426 chat: "Chat",
1427 artifacts: "Artifacts",
1428 home: "Home",
1429 apps: "Apps",
1430 marketplace: "Marketplace",
1431 "code-access": "Code access",
1432 overview: "Overview",
1433 workspace: "Workspace",
1434};
1435
1436/** Settings pages whose name differs from the section's of the same word. */
1437const SETTINGS_SECTIONS: Record<string, string> = { branches: "Branches and merging", actions: "Actions" };
1438
1439/** Where the page is, as a trail of links: workspace / repository / section. */
1440function Breadcrumbs({
1441 pathname,
1442 missing,
1443 repo,
1444 workspace,
1445}: {
1446 pathname: string;
1447 missing?: boolean;
1448 repo?: ShellData["repo"];
1449 /** The workspace you are in: the switcher names it, so the trail starts after it. */
1450 workspace: string | null;
1451}) {
1452 // A 404 names nothing from the address, unless the project is real and
1453 // visible and only something inside it is missing.
1454 const visibleRepo = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(pathname);
1455 if (missing && !(visibleRepo && sameRepo(repo ?? null, { namespace: visibleRepo[1]!, name: visibleRepo[2]! }))) {
1456 return <Here>Not found</Here>;
1457 }
1458 const parts = pathname.split("/").filter(Boolean);
1459 const reserved = ["settings", "explore", "new", "search", "workspaces", "policies", "security", "support", "status", "invite", "notifications"];
1460 if (parts.length === 0) return <Here>Home</Here>;
1461 // Your settings: Settings / Emails.
1462 if (parts[0] === "settings") {
1463 const page = accountSettingsPage(pathname);
1464 return <Trail trail={[{ label: "Settings", to: FIRST_SETTINGS_PAGE }, ...(page ? [{ label: ACCOUNT_SETTINGS[page].title, to: `/settings/${page}` }] : [])]} />;
1465 }
1466 if (reserved.includes(parts[0]!)) {
1467 const words: Record<string, string> = {
1468 settings: "Account",
1469 explore: "Explore",
1470 new: "New project",
1471 search: "Search",
1472 workspaces: "New workspace",
1473 policies: "Policies",
1474 security: "Security",
1475 support: "Support",
1476 status: "Status",
1477 invite: "Invite",
1478 notifications: "Notifications",
1479 };
1480 return <Here>{words[parts[0]!]}</Here>;
1481 }
1482 // A person's profile, by their handle.
1483 if (parts[0] === "u" && parts[1]) return <ProfileCrumb username={parts[1]} />;
1484 const [owner, second, third, fourth] = parts;
1485 const ours = workspace != null && owner!.toLowerCase() === workspace.toLowerCase();
1486 const trail: Crumb[] = ours ? [] : [{ label: owner!, to: `/${owner}`, mono: true }];
1487 if (second === "-") {
1488 const page = `/${owner}/-/${third}`;
1489 if (third && SETTINGS_PAGE.test(page)) {
1490 trail.push({ label: "Settings", to: `/${owner}/-/settings` });
1491 trail.push({ label: third === "settings" ? "General" : (SECTIONS[third] ?? third), to: page });
1492 } else if (third) {
1493 trail.push({ label: SECTIONS[third] ?? third, to: page });
1494 // The Marketplace names its tab (Marketplace / Extensions), and Agents its templates.
1495 const tabs: Record<string, string> =
1496 third === "marketplace" ? { integrations: "Integrations", extensions: "Extensions", requests: "Requests" } : third === "agents" ? { templates: "Templates" } : {};
1497 const tab = fourth ? tabs[fourth] : undefined;
1498 if (tab) trail.push({ label: tab, to: `${page}/${fourth}` });
1499 }
1500 } else if (second) {
1501 const repo = `/${owner}/${second}`;
1502 trail.push({ label: second, to: repo, mono: true });
1503 if (third === "pull" && fourth) trail.push({ label: `Pull request #${fourth}`, short: `#${fourth}`, to: `${repo}/pull/${fourth}` });
1504 else if (third === "issues" && fourth && fourth !== "new") trail.push({ label: `Issue #${fourth}`, short: `#${fourth}`, to: `${repo}/issues/${fourth}` });
1505 else if (third === "commit" && fourth) trail.push({ label: fourth.slice(0, 7), to: `${repo}/commit/${fourth}`, mono: true });
1506 else if (third && SECTIONS[third]) {
1507 trail.push({ label: SECTIONS[third]!, to: `${repo}/${third}` });
1508 // A settings page names which one: Settings / Secrets and variables.
1509 if (third === "settings" && fourth && SECTIONS[fourth]) {
1510 trail.push({ label: SETTINGS_SECTIONS[fourth] ?? SECTIONS[fourth]!, to: `${repo}/settings/${fourth}` });
1511 }
1512 }
1513 }
1514 if (trail.length === 0) trail.push({ label: "Overview", to: `/${owner}` });
1515 return <Trail trail={trail} />;
1516}
1517
1518/** A profile's place in the top bar: the person's avatar and @handle, from the page once it has loaded. */
1519function ProfileCrumb({ username }: { username: string }) {
1520 const page = useRouteLoaderData("routes/user") as { profile?: { username: string; displayUsername?: string | null; avatar: string | null } } | undefined;
1521 const profile = page?.profile?.username.toLowerCase() === username.toLowerCase() ? page.profile : null;
1522 return (
1523 <Breadcrumb className="min-w-0">
1524 <BreadcrumbList>
1525 <BreadcrumbItem>
1526 <BreadcrumbPage asChild className="flex items-center gap-2 hover:bg-raised">
1527 <Link to={`/u/${profile?.username ?? username}`}>
1528 <Avatar name={profile?.username ?? username} image={profile?.avatar ?? null} size={20} />
1529 <span className="truncate font-mono text-[0.8125rem]">@{profile ? shownUsername(profile) : username}</span>
1530 </Link>
1531 </BreadcrumbPage>
1532 </BreadcrumbItem>
1533 </BreadcrumbList>
1534 </Breadcrumb>
1535 );
1536}
1537
1538/** A page with no trail to it, such as Today or Search: its name alone. */
1539function Here({ children }: { children: ReactNode }) {
1540 return (
1541 <Breadcrumb className="min-w-0">
1542 <BreadcrumbList>
1543 <BreadcrumbItem>
1544 <BreadcrumbPage>{children}</BreadcrumbPage>
1545 </BreadcrumbItem>
1546 </BreadcrumbList>
1547 </Breadcrumb>
1548 );
1549}
1550
1551/** One link of the trail; `short` is what a phone shows when it is the page itself. */
1552type Crumb = { label: string; to: string; mono?: boolean; short?: string };
1553
1554/**
1555 * The trail of links. On a phone there is room for one: the page itself,
1556 * with a way back to where it sits; the whole trail from a wider screen up.
1557 */
1558function Trail({ trail }: { trail: Crumb[] }) {
1559 // Up on a phone, unless up is the workspace itself: its pages are the tabs.
1560 const up = trail.length > 1 && !/^\/[^/]+$/.test(trail[trail.length - 2]!.to) ? trail[trail.length - 2]! : null;
1561 return (
1562 <Breadcrumb className="flex min-w-0 items-center">
1563 {up && (
1564 <Button asChild variant="ghost" size="icon-bar" className="-ml-1 sm:hidden">
1565 <Link to={up.to} prefetch="intent" aria-label={`Back to ${up.label}`}>
1566 <ChevronLeft size={16} />
1567 </Link>
1568 </Button>
1569 )}
1570 <BreadcrumbList>
1571 {trail.map((crumb, index) => {
1572 const last = index === trail.length - 1;
1573 const label =
1574 last && crumb.short ? (
1575 <>
1576 <span className="sm:hidden">{crumb.short}</span>
1577 <span className="hidden sm:inline">{crumb.label}</span>
1578 </>
1579 ) : (
1580 crumb.label
1581 );
1582 const mono = crumb.mono ? "font-mono text-[0.8125rem]" : "";
1583 return (
1584 <Fragment key={index}>
1585 {index > 0 && <BreadcrumbSeparator className="max-sm:hidden" />}
1586 <BreadcrumbItem className={last ? "" : "max-sm:hidden"}>
1587 {last ? (
1588 // The page you are on is still a link: to its own top, as the trail always was.
1589 <BreadcrumbPage asChild className={`hover:bg-raised ${mono}`}>
1590 <Link to={crumb.to} prefetch="intent">
1591 {label}
1592 </Link>
1593 </BreadcrumbPage>
1594 ) : (
1595 <BreadcrumbLink asChild className={mono}>
1596 <Link to={crumb.to} prefetch="intent">
1597 {label}
1598 </Link>
1599 </BreadcrumbLink>
1600 )}
1601 </BreadcrumbItem>
1602 </Fragment>
1603 );
1604 })}
1605 </BreadcrumbList>
1606 </Breadcrumb>
1607 );
1608}
1609
1610type Command = PaletteCommand;
1611
1612/** Everything the palette can jump to, from what the sidebar already knows. */
1613function commandsFor(user: User, shell: ShellData): Command[] {
1614 const ws = shell.workspace;
1615 const commands: Command[] = [
1616 ...(ws
1617 ? [
1618 { label: "Home", to: homePagePath(ws.slug), icon: <House size={15} /> },
1619 { label: "Chat", to: `/${ws.slug}/-/chat`, icon: <MessagesSquare size={15} /> },
1620 { label: "Agents", to: `/${ws.slug}/-/agents`, icon: <Sparkles size={15} /> },
1621 ...(hasCodeAccess(ws) ? [{ label: "Code overview", to: `/${ws.slug}/-/overview`, icon: <Code2 size={15} /> }] : []),
1622 { label: "Artifacts", to: `/${ws.slug}/-/artifacts`, icon: <Shapes size={15} /> },
1623 { label: "Apps", hint: "Everything installed that you can use", to: `/${ws.slug}/-/apps`, icon: <LayoutGrid size={15} /> },
1624 { label: "Marketplace", hint: "Extensions and integrations to add", to: `/${ws.slug}/-/marketplace`, icon: <Store size={15} /> },
1625 { label: "Agent templates", hint: "Starting points for a new agent", to: `/${ws.slug}/-/agents/templates`, icon: <Bot size={15} /> },
1626 { label: "Workspace", hint: "Billing, policies, settings", to: `/${ws.slug}/-/workspace`, icon: <Building2 size={15} /> },
1627 ]
1628 : []),
1629 ...(shell.repos.length > 0
1630 ? [{ label: "Put an agent on it", hint: "Open an issue and assign g1t", to: "/?agent=new", icon: <Sparkles size={15} /> }]
1631 : []),
1632 { label: "Explore repositories", to: "/explore", icon: <Compass size={15} /> },
1633 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
1634 { label: "Notifications", hint: "What needs you", to: "/notifications", icon: <Bell size={15} /> },
1635 { label: "New project", to: "/new", icon: <Plus size={15} /> },
1636 { label: "New workspace", to: "/workspaces/new", icon: <Plus size={15} /> },
1637 { label: "Your settings", to: FIRST_SETTINGS_PAGE, icon: <Settings size={15} /> },
1638 ...(Object.keys(ACCOUNT_SETTINGS) as AccountSettingsPage[])
1639 .filter((page) => page !== "profile")
1640 .map((page) => ({ label: ACCOUNT_SETTINGS[page].title, hint: "Your settings", to: `/settings/${page}`, icon: <Settings size={15} /> })),
1641 ...THEME_COMMANDS,
1642 ];
1643 const repo = shell.repo;
1644 if (repo) {
1645 const base = `/${repo.namespace}/${repo.name}`;
1646 const name = `${repo.namespace}/${repo.name}`;
1647 commands.unshift(
1648 { label: "Overview", hint: name, to: base, icon: <LayoutGrid size={15} /> },
1649 { label: "Code", hint: name, to: `${base}/code`, icon: <Code2 size={15} /> },
1650 { label: "Issues", hint: name, to: `${base}/issues`, icon: <CircleDot size={15} /> },
1651 { label: "New issue", hint: name, to: `${base}/issues/new`, icon: <Plus size={15} /> },
1652 ...(repo.member
1653 ? [{ label: `Put an agent on ${repo.name}`, hint: name, to: `${base}/issues/new?agent=1`, icon: <Sparkles size={15} /> }]
1654 : []),
1655 { label: "Pull requests", hint: name, to: `${base}/pulls`, icon: <GitPullRequest size={15} /> },
1656 { label: "Commits", hint: name, to: `${base}/commits`, icon: <History size={15} /> },
1657 ...(repo.member
1658 ? [
1659 { label: "Plan work", hint: name, to: `${base}/plans`, icon: <ListTree size={15} /> },
1660 { label: "Deployments", hint: name, to: `${base}/deployments`, icon: <Rocket size={15} /> },
1661 { label: "Secrets and variables", hint: name, to: `${base}/settings/secrets`, icon: <Lock size={15} /> },
1662 { label: "Project settings", hint: name, to: `${base}/settings`, icon: <Settings size={15} /> },
1663 { label: "Repository settings", hint: name, to: `${base}/settings/repository`, icon: <Settings size={15} /> },
1664 ]
1665 : []),
1666 );
1667 }
1668 for (const membership of user.workspaces ?? []) {
1669 commands.push(
1670 { label: displayName(membership), hint: `Workspace · ${membership.slug}`, to: `/${membership.slug}`, icon: <Avatar name={membership.slug} image={membership.avatar} size={15} square /> },
1671 { label: "All projects", hint: membership.slug, to: `/${membership.slug}/-/projects`, icon: <LayoutGrid size={15} /> },
1672 { label: "People", hint: membership.slug, to: `/${membership.slug}/-/people`, icon: <Users size={15} /> },
1673 { label: "Spend", hint: `${membership.slug} · Budgets and receipts`, to: `/${membership.slug}/-/spend`, icon: <Coins size={15} /> },
1674 { label: "Usage", hint: membership.slug, to: `/${membership.slug}/-/usage`, icon: <BarChart3 size={15} /> },
1675 { label: "AI Gateway", hint: `${membership.slug} · Usage`, to: `/${membership.slug}/-/gateway`, icon: <Network size={15} /> },
1676 { label: "Billing and plans", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/billing`, icon: <CreditCard size={15} /> },
1677 { label: "Access tokens", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/tokens`, icon: <KeyRound size={15} /> },
1678 { label: "Integrations", hint: membership.slug, to: `/${membership.slug}/-/integrations`, icon: <Plug size={15} /> },
1679 );
1680 }
1681 for (const listed of shell.repos) {
1682 commands.push({
1683 label: listed.title ?? listed.name,
1684 hint: `${listed.namespace} · Project`,
1685 to: `/${listed.namespace}/${listed.name}`,
1686 icon: <Box size={15} />,
1687 });
1688 }
1689 // "Put an agent on …": one per project, after the projects themselves.
1690 for (const listed of shell.repos) {
1691 if (repo && listed.namespace === repo.namespace && listed.name === repo.name) continue;
1692 commands.push({
1693 label: `Put an agent on ${listed.title ?? listed.name}`,
1694 hint: `${listed.namespace}/${listed.name}`,
1695 to: `/${listed.namespace}/${listed.name}/issues/new?agent=1`,
1696 icon: <Sparkles size={15} />,
1697 });
1698 }
1699 return commands;
1700}
1701
1702/**
1703 * The page while the next one loads: after a moment it dims, under the
1704 * bar below, so it is plainly on its way out rather than frozen, and the
1705 * next page fades up from there. Sending a form does not dim it: the
1706 * form's button says it is working. Spread on the element holding the page.
1707 */
1708export function useLeaving() {
1709 const navigation = useNavigation();
1710 const method = navigation.formMethod?.toUpperCase();
1711 const leaving = navigation.state === "loading" && (method == null || method === "GET");
1712 return {
1713 "aria-busy": leaving || undefined,
1714 className: `transition-opacity motion-reduce:transition-none ${leaving ? "opacity-60 delay-200 duration-300" : "duration-150"}`,
1715 };
1716}
1717
1718/**
1719 * A bar across the top of the page while the next one loads, as GitHub
1720 * has: it appears at once, creeps towards the end while waiting, then fills
1721 * and fades when the page arrives.
1722 */
1723export function Progress() {
1724 const navigation = useNavigation();
1725 const busy = navigation.state !== "idle";
1726 const [width, setWidth] = useState(0);
1727 const [visible, setVisible] = useState(false);
1728 useEffect(() => {
1729 if (busy) {
1730 setVisible(true);
1731 setWidth(12);
1732 // Slows as it goes, never quite arriving until the page does.
1733 const timer = setInterval(() => setWidth((now) => now + (90 - now) * 0.12), 200);
1734 return () => clearInterval(timer);
1735 }
1736 setWidth((now) => (now > 0 ? 100 : 0));
1737 const fade = setTimeout(() => setVisible(false), 250);
1738 const reset = setTimeout(() => setWidth(0), 550);
1739 return () => {
1740 clearTimeout(fade);
1741 clearTimeout(reset);
1742 };
1743 }, [busy]);
1744 return (
1745 <div
1746 aria-hidden="true"
1747 className={`pointer-events-none fixed inset-x-0 top-0 z-[60] h-[3px] transition-opacity duration-300 ${
1748 visible ? "opacity-100" : "opacity-0"
1749 }`}
1750 >
1751 <div
1752 className="h-full bg-accent shadow-[0_0_10px_var(--color-accent)] transition-[width] duration-200 ease-out"
1753 style={{ width: `${width}%` }}
1754 />
1755 </div>
1756 );
1757}
1758
1759/**
1760 * The top bar's way to g1t: the direct message with the workspace's
1761 * orchestrator, opened or made. The one tinted control in the bar: the
1762 * lavender pixel 1 bare beside its words, on a wash of the accent.
1763 */
1764function AskG1tButton({ slug }: { slug: string }) {
1765 return (
1766 <Hint label="Ask g1t">
1767 <Button asChild variant="soft" size="bar" className="gap-2 lg:px-3">
1768 <Link to={`/${slug}/-/chat?agent=g1t`} aria-label="Ask g1t">
1769 <MarkGlyph className="h-3.5" />
1770 <span className="max-lg:hidden">Ask g1t</span>
1771 </Link>
1772 </Button>
1773 </Hint>
1774 );
1775}
1776
1777/**
1778 * Which sidebar sits beside the page: each mode's own, or none. Home and
1779 * Apps are pages at full width, and so are g1t's public pages, such as a
1780 * profile, which are no workspace's. Without a workspace, only your own
1781 * settings and Notifications have one.
1782 */
1783function sidebarFor(mode: ModeKey, workspace: boolean): Panel | null {
1784 if (!workspace) return mode === "account" || mode === "notifications" ? mode : null;
1785 if (mode === "home" || mode === "apps" || mode === "site") return null;
1786 return mode;
1787}
1788
1789/** The sidebars that sit beside the page, one per mode that has one. */
1790type Panel = "chat" | "artifacts" | "agents" | "code" | "notifications" | "people" | "workspace" | "account";
1791
1792/** Each sidebar's name, for the button that opens it on a phone. */
1793const MODE_MENU: Record<Panel, string> = {
1794 chat: "Chat",
1795 artifacts: "Artifacts",
1796 agents: "Agents",
1797 code: "Code",
1798 notifications: "Notifications",
1799 people: "People",
1800 workspace: "Workspace",
1801 account: "Your account",
1802};
1803
1804/** Whether a key press happened in something you type into, where Ctrl B is the editor's. */
1805function typing(target: EventTarget | null): boolean {
1806 if (!(target instanceof HTMLElement)) return false;
1807 return target.isContentEditable || target.closest("input, textarea, select, [contenteditable=''], [contenteditable='true'], [role='textbox']") != null;
1808}
1809
1810/** Ctrl B (⌘B on a Mac) shows or hides the sidebar, except while typing. */
1811function useSidebarShortcut(toggle: () => void) {
1812 useEffect(() => {
1813 const onKey = (event: KeyboardEvent) => {
1814 if (event.key.toLowerCase() !== "b" || event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey)) return;
1815 if (event.defaultPrevented || typing(event.target)) return;
1816 event.preventDefault();
1817 toggle();
1818 };
1819 window.addEventListener("keydown", onKey);
1820 return () => window.removeEventListener("keydown", onKey);
1821 }, [toggle]);
1822}
1823
1824/**
1825 * Search or jump to: the command palette. On a computer it looks like the
1826 * field it opens, with its shortcut; on a phone, a magnifier.
1827 */
1828function SearchButton({ onClick }: { onClick: () => void }) {
1829 return (
1830 <>
1831 <Button variant="ghost" size="icon-bar" aria-label="Search or jump to" onClick={onClick} className="md:hidden">
1832 <Search size={18} />
1833 </Button>
1834 <Button
1835 variant="outline"
1836 size="sm"
1837 aria-label="Search or jump to"
1838 onClick={onClick}
1839 className="mr-1 w-[min(18rem,26vw)] justify-start bg-surface font-normal text-faint hover:bg-surface hover:text-muted max-md:hidden"
1840 >
1841 <Search size={15} />
1842 <span className="grow truncate text-left">Search or jump to</span>
1843 <PaletteKey className="rounded border border-line bg-bg px-1.5 font-mono text-[0.625rem] leading-4 text-muted" />
1844 </Button>
1845 </>
1846 );
1847}
1848
1849/** The button that shows or hides the sidebar. */
1850function SidebarToggle({ onClick, open, className = "" }: { onClick: () => void; open: boolean; className?: string }) {
1851 const key = sidebarKeyLabel(typeof navigator === "undefined" ? null : navigator.platform);
1852 return (
1853 <Hint label={`Toggle sidebar (${key})`}>
1854 <Button variant="ghost" size="icon-sm" aria-label={open ? "Hide the sidebar" : "Show the sidebar"} aria-expanded={open} onClick={onClick} className={className}>
1855 <PanelLeft size={17} />
1856 </Button>
1857 </Hint>
1858 );
1859}
1860
1861/**
1862 * The app: three surfaces that never blur
1863 * together. The dock, a floating bar of apps down the left; the mode's
1864 * sidebar, flat on the background beside it, which folds away with Ctrl B
1865 * and is a drawer below 1024px; and the page, a rounded panel inset from
1866 * the window, with its header across the top: the sidebar's toggle, where
1867 * you are, search, Ask g1t and Create new. On a phone the dock is a bar
1868 * along the bottom. Only for someone signed in; without a workspace yet,
1869 * there is no dock.
1870 */
1871export function AppShell({
1872 user,
1873 shell,
1874 missing = false,
1875 banner,
1876 sidebarClosed = false,
1877 children,
1878}: {
1879 user: User;
1880 shell: ShellData;
1881 /** The page is a 404 (see CodeSidebar). */
1882 missing?: boolean;
1883 banner?: ReactNode;
1884 /** Whether the person folded the sidebar away, as their cookie says. */
1885 sidebarClosed?: boolean;
1886 children: ReactNode;
1887}) {
1888 const { pathname } = useLocation();
1889 const [drawer, setDrawer] = useState(false);
1890 const [closed, setClosed] = useState(sidebarClosed);
1891 const [palette, setPalette] = useState(false);
1892 const commands = useMemo(() => commandsFor(user, shell), [user, shell]);
1893
1894 // A new page closes the drawer.
1895 useEffect(() => setDrawer(false), [pathname]);
1896 usePaletteShortcut(() => setPalette((open) => !open));
1897 const leaving = useLeaving();
1898 useVisualViewport();
1899 // Whether the page has scrolled under the top bar, which then draws its line (see data-page-head).
1900 const [scrolled, setScrolled] = useState(false);
1901 useEffect(() => {
1902 const onScroll = () => setScrolled(window.scrollY > 2);
1903 onScroll();
1904 window.addEventListener("scroll", onScroll, { passive: true });
1905 return () => window.removeEventListener("scroll", onScroll);
1906 }, []);
1907
1908 const going = useNavigation().location?.pathname;
1909 const ws = shell.workspace;
1910 const mode = modeOf(going ?? pathname, ws?.slug ?? null);
1911 const panel = sidebarFor(mode, ws != null);
1912 const code = ws ? hasCodeAccess(ws) : false;
1913 const { sidebar: chatSidebar } = useChatSidebar();
1914 // Notify: the feed socket's live counts (lib/notify-client.ts) once it has them; the page's until then.
1915 const live = useLiveBadges(ws?.slug);
1916 const chatUnread = chatSidebar
1917 ? unreadTotals(chatSidebar.entries)
1918 : live?.chat != null
1919 ? { unread: live.chat, mentions: live.mentions ?? 0 }
1920 : (shell.chat ?? { unread: 0, mentions: 0 });
1921 const notificationsUnread = live?.inbox ?? shell.inbox?.unread ?? 0;
1922 const unread = { notifications: notificationsUnread, chat: chatUnread.unread, mentions: chatUnread.mentions };
1923
1924 // Folding the sidebar away on a computer is remembered, so the next page is drawn the same from the server.
1925 const toggleSidebar = useCallback(() => {
1926 if (!window.matchMedia("(min-width: 1024px)").matches) {
1927 setDrawer((open) => !open);
1928 return;
1929 }
1930 setClosed((was) => {
1931 document.cookie = sidebarCookie(!was, window.location.protocol === "https:");
1932 return !was;
1933 });
1934 }, []);
1935 useSidebarShortcut(useCallback(() => {
1936 if (panel) toggleSidebar();
1937 }, [panel, toggleSidebar]));
1938
1939 const inline = panel != null && !closed;
1940 const sidebarNode = () => {
1941 if (!panel) return null;
1942 if (!ws) return panel === "notifications" ? <NotificationsSidebar counts={shell.inbox ?? null} /> : <AccountSidebar username={user.username} />;
1943 switch (panel) {
1944 case "code":
1945 return <CodeSidebar user={user} shell={shell} missing={missing} />;
1946 case "chat":
1947 return <ChatSidebar slug={ws.slug} />;
1948 case "artifacts":
1949 return <FoliosSidebar slug={ws.slug} />;
1950 case "agents":
1951 return <AgentsSidebar slug={ws.slug} shellAgents={shell.agents ?? null} code={code} owner={ws.role === "owner"} />;
1952 case "notifications":
1953 return <NotificationsSidebar counts={shell.inbox ?? null} />;
1954 case "people":
1955 return <PeopleSidebar slug={ws.slug} />;
1956 case "workspace":
1957 return <WorkspaceSidebar slug={ws.slug} owner={ws.role === "owner"} />;
1958 case "account":
1959 return <AccountSidebar username={user.username} />;
1960 }
1961 };
1962 // The sidebar's top row: the workspace and its switcher, and the way to fold the sidebar or close the drawer.
1963 const sidebarTop = (inDrawer: boolean) => (
1964 <div className="flex h-14 shrink-0 items-center gap-1 pr-1 pl-1">
1965 {ws ? (
1966 <WorkspaceSwitcher user={user} workspace={ws} />
1967 ) : (
1968 <Link to="/" aria-label="g1t" className="mr-auto flex h-9 items-center rounded-md px-2">
1969 <Logo className="text-[1.125rem]" />
1970 </Link>
1971 )}
1972 {inDrawer ? (
1973 <button type="button" aria-label="Close menu" onClick={() => setDrawer(false)} className="flex size-8 shrink-0 items-center justify-center rounded-md text-faint hover:bg-raised hover:text-fg">
1974 <X size={16} />
1975 </button>
1976 ) : (
1977 <SidebarToggle open onClick={toggleSidebar} />
1978 )}
1979 </div>
1980 );
1981
1982 // On a phone (below 768px): the bottom bar, and a conversation full screen.
1983 const conversation = isConversation(going ?? pathname);
1984 // Where the page panel starts: 8px past the dock (88px), or right after the sidebar (260px) when it is open.
1985 const left = ws ? (inline ? "md:left-24 lg:left-[21.75rem]" : "md:left-24") : inline ? "md:left-2 lg:left-[16.75rem]" : "md:left-2";
1986 const pad = ws ? (inline ? "md:pl-24 lg:pl-[21.75rem]" : "md:pl-24") : inline ? "md:pl-2 lg:pl-[16.75rem]" : "md:pl-2";
1987
1988 return (
1989 // The drawer is a sheet: a dialog that holds focus, closes on Escape or
1990 // a tap outside, and gives focus back to the button that opened it.
1991 <Sheet open={drawer} onOpenChange={setDrawer}>
1992 <Progress />
1993 {ws && (
1994 <div className="fixed top-2 bottom-2 left-2 z-40 hidden w-20 md:block">
1995 <Dock
1996 workspace={ws}
1997 pins={shell.pins ?? []}
1998 unread={unread}
1999 account={<AccountMenu user={user} />}
2000 />
2001 </div>
2002 )}
2003 {panel && (
2004 <aside
2005 aria-label={`${MODE_MENU[panel]} sidebar`}
2006 className={`fixed inset-y-0 z-40 hidden w-[16.25rem] flex-col pr-0.5 pl-1.5 ${ws ? "left-[5.5rem]" : "left-0"} ${inline ? "lg:flex" : ""}`}
2007 >
2008 {sidebarTop(false)}
2009 <div className="min-h-0 grow">{sidebarNode()}</div>
2010 </aside>
2011 )}
2012 <SheetContent
2013 side="left"
2014 showClose={false}
2015 aria-describedby={undefined}
2016 // Focus would land on the workspace's switcher and open its menu's hint; the sheet itself takes it instead.
2017 onOpenAutoFocus={(event) => {
2018 event.preventDefault();
2019 (event.currentTarget as HTMLElement | null)?.focus();
2020 }}
2021 className="flex w-[min(18.5rem,86vw)] flex-col border-line bg-shell px-1.5 pb-[env(safe-area-inset-bottom)] max-md:[&_nav_a]:min-h-10"
2022 >
2023 <SheetTitle className="sr-only">{panel ? `${MODE_MENU[panel]} menu` : "Menu"}</SheetTitle>
2024 {sidebarTop(true)}
2025 <div className="min-h-0 grow">{sidebarNode()}</div>
2026 </SheetContent>
2027
2028 <div className={`min-h-dvh px-1.5 pt-(--frame-top) pb-(--tabbar-h) md:pr-2 ${pad}`}>
2029 {/* A page whose own header sits right under this bar (data-page-head: a conversation's, a project's) reads as one
2030 block with it: no line between them until the page scrolls under the bar. A sticky one (data-page-head="sticky",
2031 an open artifact's) stays under the bar, so the line is always its. */}
2032 <div className="flex min-h-[calc(100dvh-var(--frame-top)-var(--tabbar-h))] min-w-0 flex-col rounded-[14px] bg-bg [&:has([data-page-head])>header:not([data-scrolled])]:border-b-transparent [&:has([data-page-head=sticky])>header]:border-b-transparent">
2033 <header
2034 data-scrolled={scrolled || undefined}
2035 className={`sticky top-(--frame-top) z-30 flex h-14 items-center gap-1 rounded-t-[14px] border-b border-line bg-bg pr-2 pl-2 transition-[border-color] duration-150 sm:pr-3 ${inline ? "lg:pl-3.5" : ""} ${conversation ? "max-md:hidden" : ""}`}
2036 >
2037 {panel && (
2038 <SidebarToggle open={drawer} onClick={toggleSidebar} className={`max-md:size-11 ${inline ? "lg:hidden" : ""}`} />
2039 )}
2040 {ws && (
2041 <span className={`flex min-w-0 shrink items-center gap-1.5 ${inline ? "lg:hidden" : ""}`}>
2042 <WorkspaceSwitcher user={user} workspace={ws} compact />
2043 <span aria-hidden="true" className="text-line-strong">
2044 /
2045 </span>
2046 </span>
2047 )}
2048 <Breadcrumbs pathname={pathname} missing={missing} repo={shell.repo} workspace={ws?.slug ?? null} />
2049 {/* Search, then what's yours (spend, Ask g1t), then the bell and Create new: one height, one rhythm. */}
2050 <div className="ml-auto flex shrink-0 items-center gap-1 md:gap-1.5">
2051 <SearchButton onClick={() => setPalette(true)} />
2052 {/* Your spend this month, or the workspace's for owners and billing managers; on a phone it is on Spend. */}
2053 {ws && (
2054 <span className="flex max-md:hidden">
2055 <SpendPill slug={ws.slug} mayWorkspace={ws.role === "owner" || !!ws.org_roles?.includes("billing_manager")} />
2056 </span>
2057 )}
2058 {ws && <AskG1tButton slug={ws.slug} />}
2059 <Separator orientation="vertical" className="mx-1 data-[orientation=vertical]:h-5 max-md:hidden" />
2060 {/* On a phone, Notifications is in the bottom bar. */}
2061 <span className="flex max-md:hidden">
2062 <NotificationsBell counts={shell.inbox ? { ...shell.inbox, unread: notificationsUnread } : null} />
2063 </span>
2064 <CreateMenu shell={shell} />
2065 {/* Without a workspace there is no dock: the account is here. */}
2066 {!ws && <AccountMenu user={user} side="bottom" />}
2067 </div>
2068 </header>
2069 {banner}
2070 <main id="content" tabIndex={-1} {...leaving} className={`min-w-0 grow outline-none ${leaving.className}`}>
2071 <InMain.Provider value={true}>{children}</InMain.Provider>
2072 </main>
2073 </div>
2074 </div>
2075 {/* The panel's edge: a rounded frame over the page, with the background beyond it, so what scrolls stays inside.
2076 Every page has it, a conversation too; only a phone's conversation, full screen over everything, goes without. */}
2077 <div
2078 aria-hidden="true"
2079 className={`pointer-events-none fixed top-(--frame-top) right-1.5 bottom-(--tabbar-h) left-1.5 z-[35] rounded-[14px] shadow-[0_0_0_1px_var(--color-line),0_0_0_100vmax_var(--color-shell)] md:right-2 ${left} ${conversation ? "max-md:hidden" : ""}`}
2080 />
2081 {ws && <BottomBar user={user} workspace={ws} pins={shell.pins ?? []} unread={unread} onReselect={panel ? () => setDrawer(true) : undefined} />}
2082 <CommandPalette open={palette} onOpenChange={setPalette} commands={commands} repo={shell.repo ? `${shell.repo.namespace}/${shell.repo.name}` : null} />
2083 </Sheet>
2084 );
2085}
2086
2087/** Create new: a project, an issue in the one you are in, a workspace or a team. */
2088function CreateMenu({ shell }: { shell: ShellData }) {
2089 return (
2090 <DropdownMenu>
2091 <Hint label="Create new">
2092 <DropdownMenuTrigger asChild>
2093 <Button variant="ghost" size="bar" aria-label="Create new" className="gap-0.5 px-1.5 text-fg/90">
2094 <Plus size={17} className="max-md:size-5" />
2095 <ChevronDown size={12} className="text-faint max-md:hidden" />
2096 </Button>
2097 </DropdownMenuTrigger>
2098 </Hint>
2099 <DropdownMenuContent align="end" className="min-w-52">
2100 {shell.repo && (
2101 <>
2102 <DropdownMenuLabel className="truncate">In {shell.repo.name}</DropdownMenuLabel>
2103 <DropdownMenuItem asChild>
2104 <Link to={`/${shell.repo.namespace}/${shell.repo.name}/issues/new`}>
2105 <CircleDot />
2106 New issue
2107 </Link>
2108 </DropdownMenuItem>
2109 {shell.repo.member && (
2110 <DropdownMenuItem asChild>
2111 <Link to={`/${shell.repo.namespace}/${shell.repo.name}/plans`}>
2112 <ListTree />
2113 Plan work
2114 </Link>
2115 </DropdownMenuItem>
2116 )}
2117 <DropdownMenuSeparator />
2118 </>
2119 )}
2120 <DropdownMenuItem asChild>
2121 <Link to="/?agent=new">
2122 <Sparkles />
2123 Put an agent on it
2124 </Link>
2125 </DropdownMenuItem>
2126 <DropdownMenuItem asChild>
2127 <Link to="/new">
2128 <Box />
2129 New project
2130 </Link>
2131 </DropdownMenuItem>
2132 <DropdownMenuItem asChild>
2133 <Link to="/new/github">
2134 <GitBranch />
2135 Import from GitHub
2136 </Link>
2137 </DropdownMenuItem>
2138 <DropdownMenuSeparator />
2139 <DropdownMenuItem asChild>
2140 <Link to="/workspaces/new">
2141 <Users />
2142 New workspace
2143 </Link>
2144 </DropdownMenuItem>
2145 {/* A team in the workspace you are in, for whoever it lets create one. */}
2146 {shell.workspace &&
2147 (mayCreateTeams(shell.workspace.team_creation, shell.workspace.role) ? (
2148 <DropdownMenuItem asChild>
2149 <Link to={`/${shell.workspace.slug}/-/teams/new`}>
2150 <UsersRound />
2151 New team
2152 </Link>
2153 </DropdownMenuItem>
2154 ) : (
2155 <DropdownMenuItem disabled>
2156 <UsersRound />
2157 New team
2158 <span className="ml-auto pl-3 text-xs text-faint">Owners only</span>
2159 </DropdownMenuItem>
2160 ))}
2161 </DropdownMenuContent>
2162 </DropdownMenu>
2163 );
2164}