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