Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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