Skip to content
2,062 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, 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", "webhooks", "emoji"];
1140
1141/**
1142 * The Workspace mode's sidebar: the workspace itself, for every member.
1143 * Its overview, money, machines, 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 {owner && (
1170 <SidebarGroup title="Compute" className="mt-3">
1171 <SidebarLink to={`/${slug}/-/runners`} icon={<ServerCog size={15} />} current={at("runners")}>
1172 Runners
1173 </SidebarLink>
1174 </SidebarGroup>
1175 )}
1176 <SidebarGroup title="Connections" className="mt-3">
1177 <SidebarLink to={`/${slug}/-/integrations`} icon={<Plug size={15} />} current={at("integrations")}>
1178 Integrations
1179 </SidebarLink>
1180 </SidebarGroup>
1181 <SidebarGroup title="Security policies" className="mt-3">
1182 <SidebarLink to={`/${slug}/-/security/settings`} icon={<ShieldCheck size={15} />} current={at("security/settings")}>
1183 Security settings
1184 </SidebarLink>
1185 <SidebarLink to={`/${slug}/-/guardrails`} icon={<Gauge size={15} />} current={at("guardrails")}>
1186 Guardrails
1187 </SidebarLink>
1188 <SidebarLink to={`/${slug}/-/rules`} icon={<Scale size={15} />} current={at("rules")}>
1189 Rules
1190 </SidebarLink>
1191 </SidebarGroup>
1192 <Rule />
1193 <div className="space-y-px">
1194 <SidebarLink to={`/${slug}/-/audit`} icon={<History size={15} />} current={at("audit")}>
1195 Audit log
1196 </SidebarLink>
1197 <SidebarLink to={owner ? `/${slug}/-/settings` : `/${slug}/-/repositories`} icon={<Settings size={15} />} drill current={inSettings}>
1198 Settings
1199 </SidebarLink>
1200 </div>
1201 </nav>
1202 );
1203 const settings = (
1204 <nav aria-label="Workspace settings" className={PANEL}>
1205 <BackRow to={`/${slug}/-/workspace`} label="Settings" context={slug} />
1206 <div className="mt-2 space-y-px">
1207 {owner && (
1208 <SidebarLink to={`/${slug}/-/settings`} icon={<Settings size={15} />} end>
1209 General
1210 </SidebarLink>
1211 )}
1212 <SidebarLink to={`/${slug}/-/settings/chat`} icon={<MessagesSquare size={15} />}>
1213 Chat
1214 </SidebarLink>
1215 <SidebarLink to={`/${slug}/-/repositories`} icon={<BookMarked size={15} />}>
1216 Repositories
1217 </SidebarLink>
1218 <SidebarLink to={`/${slug}/-/tokens`} icon={<KeyRound size={15} />}>
1219 Access tokens
1220 </SidebarLink>
1221 {owner && (
1222 <SidebarLink to={`/${slug}/-/personal-access-tokens`} icon={<UserRoundKey size={15} />}>
1223 Personal access tokens
1224 </SidebarLink>
1225 )}
1226 <SidebarLink to={`/${slug}/-/webhooks`} icon={<Webhook size={15} />}>
1227 Webhooks
1228 </SidebarLink>
1229 <SidebarLink to={`/${slug}/-/emoji`} icon={<Smile size={15} />}>
1230 Emoji
1231 </SidebarLink>
1232 </div>
1233 <SidebarGroup title="Runs" className="mt-3">
1234 <SidebarLink to={`/${slug}/-/secrets`} icon={<Lock size={15} />}>
1235 Secrets and variables
1236 </SidebarLink>
1237 <SidebarLink to={`/${slug}/-/actions`} icon={<PlayCircle size={15} />}>
1238 Actions
1239 </SidebarLink>
1240 </SidebarGroup>
1241 </nav>
1242 );
1243 const trail: Level[] = [{ key: "workspace", node: main }];
1244 if (inSettings) trail.push({ key: "workspace:settings", node: settings });
1245 return (
1246 <div className="flex h-full flex-col">
1247 <ModeHeader title="Workspace" />
1248 <Drill trail={trail} />
1249 </div>
1250 );
1251}
1252
1253/** People's sidebar: everyone in the workspace, and its teams. */
1254function PeopleSidebar({ slug }: { slug: string }) {
1255 const { pathname } = useLocation();
1256 const going = useNavigation().location?.pathname;
1257 const path = going ?? pathname;
1258 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1259 return (
1260 <div className="flex h-full flex-col">
1261 <ModeHeader title="People" />
1262 <nav aria-label="People" className={PANEL}>
1263 <div className="space-y-px">
1264 <SidebarLink to={`/${slug}/-/people`} icon={<Users size={15} />} current={at("people")}>
1265 Everyone
1266 </SidebarLink>
1267 <SidebarLink to={`/${slug}/-/teams`} icon={<UsersRound size={15} />} current={at("teams")}>
1268 Teams
1269 </SidebarLink>
1270 </div>
1271 </nav>
1272 </div>
1273 );
1274}
1275
1276/**
1277 * Notifications' sidebar: what you have not finished with, what you saved
1278 * and what is done; then why you were told, which narrows any of them.
1279 */
1280function NotificationsSidebar({ counts }: { counts: InboxCounts | null }) {
1281 const { search } = useLocation();
1282 const params = new URLSearchParams(search);
1283 const view = inboxView(params.get("view"));
1284 const reason = inboxReason(params.get("reason"));
1285 const tab = params.get("tab");
1286 const address = (changes: Record<string, string | null>) => {
1287 const merged: Record<string, string | null> = { tab, view: view === "inbox" ? null : view, reason, ...changes };
1288 const next = new URLSearchParams();
1289 for (const [name, value] of Object.entries(merged)) if (value) next.set(name, value);
1290 const query = next.toString();
1291 return query ? `/notifications?${query}` : "/notifications";
1292 };
1293 const views = [
1294 { view: "inbox", label: "Everything", icon: <Bell size={15} />, count: counts?.unread },
1295 { view: "saved", label: "Saved", icon: <Bookmark size={15} /> },
1296 { view: "done", label: "Done", icon: <Check size={15} /> },
1297 ] as const;
1298 return (
1299 <div className="flex h-full flex-col">
1300 <ModeHeader title="Notifications" />
1301 <nav aria-label="Notifications" className={PANEL}>
1302 <div className="space-y-px">
1303 {views.map((entry) => (
1304 <SidebarLink
1305 key={entry.view}
1306 to={address({ view: entry.view === "inbox" ? null : entry.view, before: null })}
1307 icon={entry.icon}
1308 count={"count" in entry ? (entry.count ?? undefined) : undefined}
1309 current={view === entry.view}
1310 >
1311 {entry.label}
1312 </SidebarLink>
1313 ))}
1314 </div>
1315 <SidebarGroup title="Why you were told" className="mt-4">
1316 {REASON_FILTERS.map((entry) => (
1317 <SidebarLink
1318 key={entry.reason ?? "any"}
1319 to={address({ reason: entry.reason, before: null })}
1320 icon={<span className="block size-[15px]" />}
1321 current={reason === entry.reason}
1322 >
1323 {entry.reason == null ? "Any reason" : entry.label}
1324 </SidebarLink>
1325 ))}
1326 </SidebarGroup>
1327 </nav>
1328 </div>
1329 );
1330}
1331
1332/** Your own settings, beside the page: under the account menu, not any workspace's. */
1333export function AccountSidebar({ username }: { username: string }) {
1334 return (
1335 <div className="flex h-full flex-col">
1336 <ModeHeader title="Your account" />
1337 <div className="min-h-0 grow">
1338 <AccountSettingsMenu username={username} />
1339 </div>
1340 </div>
1341 );
1342}
1343
1344/** Words for the sections a path can end in. */
1345const SECTIONS: Record<string, string> = {
1346 issues: "Issues",
1347 milestones: "Milestones",
1348 labels: "Labels",
1349 pulls: "Pull requests",
1350 queue: "Merge queue",
1351 commits: "Commits",
1352 plans: "Outcomes",
1353 actions: "Workflows",
1354 soon: "Soon",
1355 deployments: "Deployments",
1356 repository: "Repository",
1357 access: "Access",
1358 invitations: "Invitation",
1359 repositories: "Repositories",
1360 branches: "Branches",
1361 tags: "Tags",
1362 compare: "Compare",
1363 code: "Files",
1364 secrets: "Secrets and variables",
1365 settings: "Settings",
1366 people: "People",
1367 projects: "Projects",
1368 teams: "Teams",
1369 tokens: "Access tokens",
1370 "personal-access-tokens": "Personal access tokens",
1371 usage: "Usage",
1372 gateway: "AI Gateway",
1373 billing: "Billing and plans",
1374 integrations: "Integrations",
1375 webhooks: "Webhooks",
1376 emoji: "Emoji",
1377 domains: "Domains",
1378 guardrails: "Guardrails",
1379 rules: "Rules",
1380 audit: "Audit log",
1381 tree: "Files",
1382 blob: "Files",
1383 agents: "Agents",
1384 context: "Context",
1385 memory: "Memory",
1386 security: "Security",
1387 packages: "Packages",
1388 runners: "Runners",
1389 environments: "Environments",
1390 workflows: "Workflows",
1391 observability: "Observability",
1392 insights: "Insights",
1393 sessions: "Sessions",
1394 chat: "Chat",
1395 artifacts: "Artifacts",
1396 today: "Today",
1397 apps: "Apps",
1398 "code-access": "Code access",
1399 overview: "Overview",
1400 workspace: "Workspace",
1401};
1402
1403/** Settings pages whose name differs from the section's of the same word. */
1404const SETTINGS_SECTIONS: Record<string, string> = { branches: "Branches and merging", actions: "Actions" };
1405
1406/** Where the page is, as a trail of links: workspace / repository / section. */
1407function Breadcrumbs({
1408 pathname,
1409 missing,
1410 repo,
1411 workspace,
1412}: {
1413 pathname: string;
1414 missing?: boolean;
1415 repo?: ShellData["repo"];
1416 /** The workspace you are in: the switcher names it, so the trail starts after it. */
1417 workspace: string | null;
1418}) {
1419 // A 404 names nothing from the address, unless the project is real and
1420 // visible and only something inside it is missing.
1421 const visibleRepo = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(pathname);
1422 if (missing && !(visibleRepo && sameRepo(repo ?? null, { namespace: visibleRepo[1]!, name: visibleRepo[2]! }))) {
1423 return <span className="text-sm font-medium">Not found</span>;
1424 }
1425 const parts = pathname.split("/").filter(Boolean);
1426 const reserved = ["settings", "explore", "new", "search", "workspaces", "policies", "security", "support", "status", "invite", "notifications"];
1427 if (parts.length === 0) return <span className="text-sm font-medium">Today</span>;
1428 // Your settings: Settings / Emails.
1429 if (parts[0] === "settings") {
1430 const page = accountSettingsPage(pathname);
1431 return <Trail trail={[{ label: "Settings", to: FIRST_SETTINGS_PAGE }, ...(page ? [{ label: ACCOUNT_SETTINGS[page].title, to: `/settings/${page}` }] : [])]} />;
1432 }
1433 if (reserved.includes(parts[0]!)) {
1434 const words: Record<string, string> = {
1435 settings: "Account",
1436 explore: "Explore",
1437 new: "New project",
1438 search: "Search",
1439 workspaces: "New workspace",
1440 policies: "Policies",
1441 security: "Security",
1442 support: "Support",
1443 status: "Status",
1444 invite: "Invite",
1445 notifications: "Notifications",
1446 };
1447 return <span className="text-sm font-medium">{words[parts[0]!]}</span>;
1448 }
1449 // A person's profile, by their handle.
1450 if (parts[0] === "u" && parts[1]) return <ProfileCrumb username={parts[1]} />;
1451 const [owner, second, third, fourth] = parts;
1452 const ours = workspace != null && owner!.toLowerCase() === workspace.toLowerCase();
1453 const trail: Crumb[] = ours ? [] : [{ label: owner!, to: `/${owner}`, mono: true }];
1454 if (second === "-") {
1455 const page = `/${owner}/-/${third}`;
1456 if (third && SETTINGS_PAGE.test(page)) {
1457 trail.push({ label: "Settings", to: `/${owner}/-/settings` });
1458 trail.push({ label: third === "settings" ? "General" : (SECTIONS[third] ?? third), to: page });
1459 } else if (third) trail.push({ label: SECTIONS[third] ?? third, to: page });
1460 } else if (second) {
1461 const repo = `/${owner}/${second}`;
1462 trail.push({ label: second, to: repo, mono: true });
1463 if (third === "pull" && fourth) trail.push({ label: `Pull request #${fourth}`, short: `#${fourth}`, to: `${repo}/pull/${fourth}` });
1464 else if (third === "issues" && fourth && fourth !== "new") trail.push({ label: `Issue #${fourth}`, short: `#${fourth}`, to: `${repo}/issues/${fourth}` });
1465 else if (third === "commit" && fourth) trail.push({ label: fourth.slice(0, 7), to: `${repo}/commit/${fourth}`, mono: true });
1466 else if (third && SECTIONS[third]) {
1467 trail.push({ label: SECTIONS[third]!, to: `${repo}/${third}` });
1468 // A settings page names which one: Settings / Secrets and variables.
1469 if (third === "settings" && fourth && SECTIONS[fourth]) {
1470 trail.push({ label: SETTINGS_SECTIONS[fourth] ?? SECTIONS[fourth]!, to: `${repo}/settings/${fourth}` });
1471 }
1472 }
1473 }
1474 if (trail.length === 0) trail.push({ label: "Overview", to: `/${owner}` });
1475 return <Trail trail={trail} />;
1476}
1477
1478/** A profile's place in the top bar: the person's avatar and @handle, from the page once it has loaded. */
1479function ProfileCrumb({ username }: { username: string }) {
1480 const page = useRouteLoaderData("routes/user") as { profile?: { username: string; displayUsername?: string | null; avatar: string | null } } | undefined;
1481 const profile = page?.profile?.username.toLowerCase() === username.toLowerCase() ? page.profile : null;
1482 return (
1483 <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">
1484 <Avatar name={profile?.username ?? username} image={profile?.avatar ?? null} size={20} />
1485 <span className="truncate font-mono text-[0.8125rem] font-medium">@{profile ? shownUsername(profile) : username}</span>
1486 </Link>
1487 );
1488}
1489
1490/** One link of the trail; `short` is what a phone shows when it is the page itself. */
1491type Crumb = { label: string; to: string; mono?: boolean; short?: string };
1492
1493/**
1494 * The trail of links. On a phone there is room for one: the page itself,
1495 * with a way back to where it sits; the whole trail from a wider screen up.
1496 */
1497function Trail({ trail }: { trail: Crumb[] }) {
1498 // Up on a phone, unless up is the workspace itself: its pages are the tabs.
1499 const up = trail.length > 1 && !/^\/[^/]+$/.test(trail[trail.length - 2]!.to) ? trail[trail.length - 2]! : null;
1500 return (
1501 <nav aria-label="Where you are" className="flex min-w-0 items-center gap-1.5 text-sm">
1502 {up && (
1503 <Link
1504 to={up.to}
1505 prefetch="intent"
1506 aria-label={`Back to ${up.label}`}
1507 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"
1508 >
1509 <ChevronLeft size={16} />
1510 </Link>
1511 )}
1512 {trail.map((crumb, index) => {
1513 const last = index === trail.length - 1;
1514 return (
1515 <span key={index} className={`min-w-0 items-center gap-1.5 ${last ? "flex" : "hidden sm:flex"}`}>
1516 {index > 0 && <span className="hidden text-line-strong sm:inline">/</span>}
1517 <Link
1518 to={crumb.to}
1519 prefetch="intent"
1520 aria-current={last ? "page" : undefined}
1521 className={`truncate rounded px-1 py-0.5 transition-colors hover:bg-raised ${
1522 last ? "font-medium text-fg" : "text-muted hover:text-fg"
1523 } ${crumb.mono ? "font-mono text-[0.8125rem]" : ""}`}
1524 >
1525 {last && crumb.short ? (
1526 <>
1527 <span className="sm:hidden">{crumb.short}</span>
1528 <span className="hidden sm:inline">{crumb.label}</span>
1529 </>
1530 ) : (
1531 crumb.label
1532 )}
1533 </Link>
1534 </span>
1535 );
1536 })}
1537 </nav>
1538 );
1539}
1540
1541type Command = PaletteCommand;
1542
1543/** Everything the palette can jump to, from what the sidebar already knows. */
1544function commandsFor(user: User, shell: ShellData): Command[] {
1545 const ws = shell.workspace;
1546 const commands: Command[] = [
1547 ...(ws
1548 ? [
1549 { label: "Today", to: todayPath(ws.slug), icon: <Sun size={15} /> },
1550 { label: "Chat", to: `/${ws.slug}/-/chat`, icon: <MessagesSquare size={15} /> },
1551 { label: "Agents", to: `/${ws.slug}/-/agents`, icon: <Sparkles size={15} /> },
1552 ...(hasCodeAccess(ws) ? [{ label: "Code overview", to: `/${ws.slug}/-/overview`, icon: <Code2 size={15} /> }] : []),
1553 { label: "Artifacts", to: `/${ws.slug}/-/artifacts`, icon: <Shapes size={15} /> },
1554 { label: "Apps", hint: "Everything installed that you can use", to: `/${ws.slug}/-/apps`, icon: <LayoutGrid size={15} /> },
1555 { label: "Workspace", hint: "Billing, policies, settings", to: `/${ws.slug}/-/workspace`, icon: <Building2 size={15} /> },
1556 ]
1557 : []),
1558 ...(shell.repos.length > 0
1559 ? [{ label: "Put an agent on it", hint: "Open an issue and assign g1t", to: "/?agent=new", icon: <Sparkles size={15} /> }]
1560 : []),
1561 { label: "Explore repositories", to: "/explore", icon: <Compass size={15} /> },
1562 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
1563 { label: "Notifications", hint: "What needs you", to: "/notifications", icon: <Bell size={15} /> },
1564 { label: "New project", to: "/new", icon: <Plus size={15} /> },
1565 { label: "New workspace", to: "/workspaces/new", icon: <Plus size={15} /> },
1566 { label: "Your settings", to: FIRST_SETTINGS_PAGE, icon: <Settings size={15} /> },
1567 ...(Object.keys(ACCOUNT_SETTINGS) as AccountSettingsPage[])
1568 .filter((page) => page !== "profile")
1569 .map((page) => ({ label: ACCOUNT_SETTINGS[page].title, hint: "Your settings", to: `/settings/${page}`, icon: <Settings size={15} /> })),
1570 ...THEME_COMMANDS,
1571 ];
1572 const repo = shell.repo;
1573 if (repo) {
1574 const base = `/${repo.namespace}/${repo.name}`;
1575 const name = `${repo.namespace}/${repo.name}`;
1576 commands.unshift(
1577 { label: "Overview", hint: name, to: base, icon: <LayoutGrid size={15} /> },
1578 { label: "Code", hint: name, to: `${base}/code`, icon: <Code2 size={15} /> },
1579 { label: "Issues", hint: name, to: `${base}/issues`, icon: <CircleDot size={15} /> },
1580 { label: "New issue", hint: name, to: `${base}/issues/new`, icon: <Plus size={15} /> },
1581 ...(repo.member
1582 ? [{ label: `Put an agent on ${repo.name}`, hint: name, to: `${base}/issues/new?agent=1`, icon: <Sparkles size={15} /> }]
1583 : []),
1584 { label: "Pull requests", hint: name, to: `${base}/pulls`, icon: <GitPullRequest size={15} /> },
1585 { label: "Commits", hint: name, to: `${base}/commits`, icon: <History size={15} /> },
1586 ...(repo.member
1587 ? [
1588 { label: "Plan work", hint: name, to: `${base}/plans`, icon: <ListTree size={15} /> },
1589 { label: "Deployments", hint: name, to: `${base}/deployments`, icon: <Rocket size={15} /> },
1590 { label: "Secrets and variables", hint: name, to: `${base}/settings/secrets`, icon: <Lock size={15} /> },
1591 { label: "Project settings", hint: name, to: `${base}/settings`, icon: <Settings size={15} /> },
1592 { label: "Repository settings", hint: name, to: `${base}/settings/repository`, icon: <Settings size={15} /> },
1593 ]
1594 : []),
1595 );
1596 }
1597 for (const membership of user.workspaces ?? []) {
1598 commands.push(
1599 { label: displayName(membership), hint: `Workspace · ${membership.slug}`, to: `/${membership.slug}`, icon: <Avatar name={membership.slug} image={membership.avatar} size={15} square /> },
1600 { label: "All projects", hint: membership.slug, to: `/${membership.slug}/-/projects`, icon: <LayoutGrid size={15} /> },
1601 { label: "People", hint: membership.slug, to: `/${membership.slug}/-/people`, icon: <Users size={15} /> },
1602 { label: "Usage", hint: membership.slug, to: `/${membership.slug}/-/usage`, icon: <BarChart3 size={15} /> },
1603 { label: "AI Gateway", hint: `${membership.slug} · Usage`, to: `/${membership.slug}/-/gateway`, icon: <Network size={15} /> },
1604 { label: "Billing and plans", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/billing`, icon: <CreditCard size={15} /> },
1605 { label: "Access tokens", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/tokens`, icon: <KeyRound size={15} /> },
1606 { label: "Integrations", hint: membership.slug, to: `/${membership.slug}/-/integrations`, icon: <Plug size={15} /> },
1607 );
1608 }
1609 for (const listed of shell.repos) {
1610 commands.push({
1611 label: listed.title ?? listed.name,
1612 hint: `${listed.namespace} · Project`,
1613 to: `/${listed.namespace}/${listed.name}`,
1614 icon: <Box size={15} />,
1615 });
1616 }
1617 // "Put an agent on …": one per project, after the projects themselves.
1618 for (const listed of shell.repos) {
1619 if (repo && listed.namespace === repo.namespace && listed.name === repo.name) continue;
1620 commands.push({
1621 label: `Put an agent on ${listed.title ?? listed.name}`,
1622 hint: `${listed.namespace}/${listed.name}`,
1623 to: `/${listed.namespace}/${listed.name}/issues/new?agent=1`,
1624 icon: <Sparkles size={15} />,
1625 });
1626 }
1627 return commands;
1628}
1629
1630/**
1631 * The page while the next one loads: after a moment it dims, under the
1632 * bar below, so it is plainly on its way out rather than frozen, and the
1633 * next page fades up from there. Sending a form does not dim it: the
1634 * form's button says it is working. Spread on the element holding the page.
1635 */
1636export function useLeaving() {
1637 const navigation = useNavigation();
1638 const method = navigation.formMethod?.toUpperCase();
1639 const leaving = navigation.state === "loading" && (method == null || method === "GET");
1640 return {
1641 "aria-busy": leaving || undefined,
1642 className: `transition-opacity motion-reduce:transition-none ${leaving ? "opacity-60 delay-200 duration-300" : "duration-150"}`,
1643 };
1644}
1645
1646/**
1647 * A bar across the top of the page while the next one loads, as GitHub
1648 * has: it appears at once, creeps towards the end while waiting, then fills
1649 * and fades when the page arrives.
1650 */
1651export function Progress() {
1652 const navigation = useNavigation();
1653 const busy = navigation.state !== "idle";
1654 const [width, setWidth] = useState(0);
1655 const [visible, setVisible] = useState(false);
1656 useEffect(() => {
1657 if (busy) {
1658 setVisible(true);
1659 setWidth(12);
1660 // Slows as it goes, never quite arriving until the page does.
1661 const timer = setInterval(() => setWidth((now) => now + (90 - now) * 0.12), 200);
1662 return () => clearInterval(timer);
1663 }
1664 setWidth((now) => (now > 0 ? 100 : 0));
1665 const fade = setTimeout(() => setVisible(false), 250);
1666 const reset = setTimeout(() => setWidth(0), 550);
1667 return () => {
1668 clearTimeout(fade);
1669 clearTimeout(reset);
1670 };
1671 }, [busy]);
1672 return (
1673 <div
1674 aria-hidden="true"
1675 className={`pointer-events-none fixed inset-x-0 top-0 z-[60] h-[3px] transition-opacity duration-300 ${
1676 visible ? "opacity-100" : "opacity-0"
1677 }`}
1678 >
1679 <div
1680 className="h-full bg-accent shadow-[0_0_10px_var(--color-accent)] transition-[width] duration-200 ease-out"
1681 style={{ width: `${width}%` }}
1682 />
1683 </div>
1684 );
1685}
1686
1687/** The top bar's way to g1t: the direct message with the workspace's orchestrator, opened or made. */
1688function AskG1tButton({ slug }: { slug: string }) {
1689 return (
1690 <Hint label="Ask g1t">
1691 <Link
1692 to={`/${slug}/-/chat?agent=g1t`}
1693 aria-label="Ask g1t"
1694 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"
1695 >
1696 <G1tMark size={18} />
1697 <span className="hidden lg:inline">Ask g1t</span>
1698 </Link>
1699 </Hint>
1700 );
1701}
1702
1703/**
1704 * Which sidebar sits beside the page: each mode's own, or none. Today and
1705 * Apps are pages at full width, and so are g1t's public pages, such as a
1706 * profile, which are no workspace's. Without a workspace, only your own
1707 * settings and Notifications have one.
1708 */
1709function sidebarFor(mode: ModeKey, workspace: boolean): Panel | null {
1710 if (!workspace) return mode === "account" || mode === "notifications" ? mode : null;
1711 if (mode === "today" || mode === "apps" || mode === "site") return null;
1712 return mode;
1713}
1714
1715/** The sidebars that sit beside the page, one per mode that has one. */
1716type Panel = "chat" | "artifacts" | "agents" | "code" | "notifications" | "people" | "workspace" | "account";
1717
1718/** Each sidebar's name, for the button that opens it on a phone. */
1719const MODE_MENU: Record<Panel, string> = {
1720 chat: "Chat",
1721 artifacts: "Artifacts",
1722 agents: "Agents",
1723 code: "Code",
1724 notifications: "Notifications",
1725 people: "People",
1726 workspace: "Workspace",
1727 account: "Your account",
1728};
1729
1730/** Whether a key press happened in something you type into, where Ctrl B is the editor's. */
1731function typing(target: EventTarget | null): boolean {
1732 if (!(target instanceof HTMLElement)) return false;
1733 return target.isContentEditable || target.closest("input, textarea, select, [contenteditable=''], [contenteditable='true'], [role='textbox']") != null;
1734}
1735
1736/** Ctrl B (⌘B on a Mac) shows or hides the sidebar, except while typing. */
1737function useSidebarShortcut(toggle: () => void) {
1738 useEffect(() => {
1739 const onKey = (event: KeyboardEvent) => {
1740 if (event.key.toLowerCase() !== "b" || event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey)) return;
1741 if (event.defaultPrevented || typing(event.target)) return;
1742 event.preventDefault();
1743 toggle();
1744 };
1745 window.addEventListener("keydown", onKey);
1746 return () => window.removeEventListener("keydown", onKey);
1747 }, [toggle]);
1748}
1749
1750/** The button that shows or hides the sidebar. */
1751function SidebarToggle({ onClick, open, className = "" }: { onClick: () => void; open: boolean; className?: string }) {
1752 const key = sidebarKeyLabel(typeof navigator === "undefined" ? null : navigator.platform);
1753 return (
1754 <Hint label={`Toggle sidebar (${key})`}>
1755 <button
1756 type="button"
1757 aria-label={open ? "Hide the sidebar" : "Show the sidebar"}
1758 aria-expanded={open}
1759 onClick={onClick}
1760 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}`}
1761 >
1762 <PanelLeft size={17} />
1763 </button>
1764 </Hint>
1765 );
1766}
1767
1768/**
1769 * The app: three surfaces that never blur
1770 * together. The dock, a floating bar of apps down the left; the mode's
1771 * sidebar, flat on the background beside it, which folds away with Ctrl B
1772 * and is a drawer below 1024px; and the page, a rounded panel inset from
1773 * the window, with its header across the top: the sidebar's toggle, where
1774 * you are, search, Ask g1t and Create new. On a phone the dock is a bar
1775 * along the bottom. Only for someone signed in; without a workspace yet,
1776 * there is no dock.
1777 */
1778export function AppShell({
1779 user,
1780 shell,
1781 missing = false,
1782 banner,
1783 sidebarClosed = false,
1784 children,
1785}: {
1786 user: User;
1787 shell: ShellData;
1788 /** The page is a 404 (see CodeSidebar). */
1789 missing?: boolean;
1790 banner?: ReactNode;
1791 /** Whether the person folded the sidebar away, as their cookie says. */
1792 sidebarClosed?: boolean;
1793 children: ReactNode;
1794}) {
1795 const { pathname } = useLocation();
1796 const [drawer, setDrawer] = useState(false);
1797 const [closed, setClosed] = useState(sidebarClosed);
1798 const [palette, setPalette] = useState(false);
1799 const commands = useMemo(() => commandsFor(user, shell), [user, shell]);
1800
1801 // A new page closes the drawer.
1802 useEffect(() => setDrawer(false), [pathname]);
1803 usePaletteShortcut(() => setPalette((open) => !open));
1804 const leaving = useLeaving();
1805 useVisualViewport();
1806
1807 const going = useNavigation().location?.pathname;
1808 const ws = shell.workspace;
1809 const mode = modeOf(going ?? pathname, ws?.slug ?? null);
1810 const panel = sidebarFor(mode, ws != null);
1811 const code = ws ? hasCodeAccess(ws) : false;
1812 const { sidebar: chatSidebar } = useChatSidebar();
1813 // Notify: the feed socket's live counts (lib/notify-client.ts) once it has them; the page's until then.
1814 const live = useLiveBadges(ws?.slug);
1815 const chatUnread = chatSidebar
1816 ? unreadTotals(chatSidebar.entries)
1817 : live?.chat != null
1818 ? { unread: live.chat, mentions: live.mentions ?? 0 }
1819 : (shell.chat ?? { unread: 0, mentions: 0 });
1820 const notificationsUnread = live?.inbox ?? shell.inbox?.unread ?? 0;
1821 const unread = { notifications: notificationsUnread, chat: chatUnread.unread, mentions: chatUnread.mentions };
1822
1823 // Folding the sidebar away on a computer is remembered, so the next page is drawn the same from the server.
1824 const toggleSidebar = useCallback(() => {
1825 if (!window.matchMedia("(min-width: 1024px)").matches) {
1826 setDrawer((open) => !open);
1827 return;
1828 }
1829 setClosed((was) => {
1830 document.cookie = sidebarCookie(!was, window.location.protocol === "https:");
1831 return !was;
1832 });
1833 }, []);
1834 useSidebarShortcut(useCallback(() => {
1835 if (panel) toggleSidebar();
1836 }, [panel, toggleSidebar]));
1837
1838 const inline = panel != null && !closed;
1839 const sidebarNode = () => {
1840 if (!panel) return null;
1841 if (!ws) return panel === "notifications" ? <NotificationsSidebar counts={shell.inbox ?? null} /> : <AccountSidebar username={user.username} />;
1842 switch (panel) {
1843 case "code":
1844 return <CodeSidebar user={user} shell={shell} missing={missing} />;
1845 case "chat":
1846 return <ChatSidebar slug={ws.slug} />;
1847 case "artifacts":
1848 return <FoliosSidebar slug={ws.slug} />;
1849 case "agents":
1850 return <AgentsSidebar slug={ws.slug} shellAgents={shell.agents ?? null} code={code} owner={ws.role === "owner"} />;
1851 case "notifications":
1852 return <NotificationsSidebar counts={shell.inbox ?? null} />;
1853 case "people":
1854 return <PeopleSidebar slug={ws.slug} />;
1855 case "workspace":
1856 return <WorkspaceSidebar slug={ws.slug} owner={ws.role === "owner"} />;
1857 case "account":
1858 return <AccountSidebar username={user.username} />;
1859 }
1860 };
1861 // The sidebar's top row: the workspace and its switcher, and the way to fold the sidebar or close the drawer.
1862 const sidebarTop = (inDrawer: boolean) => (
1863 <div className="flex h-14 shrink-0 items-center gap-1 pr-1 pl-1">
1864 {ws ? (
1865 <WorkspaceSwitcher user={user} workspace={ws} />
1866 ) : (
1867 <Link to="/" aria-label="g1t" className="mr-auto flex h-9 items-center rounded-md px-2">
1868 <Logo className="text-[1.125rem]" />
1869 </Link>
1870 )}
1871 {inDrawer ? (
1872 <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">
1873 <X size={16} />
1874 </button>
1875 ) : (
1876 <SidebarToggle open onClick={toggleSidebar} />
1877 )}
1878 </div>
1879 );
1880
1881 // On a phone (below 768px): the bottom bar, and a conversation full screen.
1882 const conversation = isConversation(going ?? pathname);
1883 // Where the page panel starts: 8px past the dock (88px), or right after the sidebar (260px) when it is open.
1884 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";
1885 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";
1886
1887 return (
1888 // The drawer is a sheet: a dialog that holds focus, closes on Escape or
1889 // a tap outside, and gives focus back to the button that opened it.
1890 <Sheet open={drawer} onOpenChange={setDrawer}>
1891 <Progress />
1892 {ws && (
1893 <div className="fixed top-2 bottom-2 left-2 z-40 hidden w-20 md:block">
1894 <Dock
1895 workspace={ws}
1896 pins={shell.pins ?? []}
1897 unread={unread}
1898 account={<AccountMenu user={user} />}
1899 />
1900 </div>
1901 )}
1902 {panel && (
1903 <aside
1904 aria-label={`${MODE_MENU[panel]} sidebar`}
1905 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" : ""}`}
1906 >
1907 {sidebarTop(false)}
1908 <div className="min-h-0 grow">{sidebarNode()}</div>
1909 </aside>
1910 )}
1911 <SheetContent
1912 side="left"
1913 showClose={false}
1914 aria-describedby={undefined}
1915 // Focus would land on the workspace's switcher and open its menu's hint; the sheet itself takes it instead.
1916 onOpenAutoFocus={(event) => {
1917 event.preventDefault();
1918 (event.currentTarget as HTMLElement | null)?.focus();
1919 }}
1920 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"
1921 >
1922 <SheetTitle className="sr-only">{panel ? `${MODE_MENU[panel]} menu` : "Menu"}</SheetTitle>
1923 {sidebarTop(true)}
1924 <div className="min-h-0 grow">{sidebarNode()}</div>
1925 </SheetContent>
1926
1927 <div className={`min-h-dvh px-1.5 pt-(--frame-top) pb-(--tabbar-h) md:pr-2 ${pad}`}>
1928 <div className="flex min-h-[calc(100dvh-var(--frame-top)-var(--tabbar-h))] min-w-0 flex-col rounded-[14px] bg-bg">
1929 <header
1930 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" : ""}`}
1931 >
1932 {panel && (
1933 <SidebarToggle open={drawer} onClick={toggleSidebar} className={inline ? "lg:hidden" : ""} />
1934 )}
1935 {ws && (
1936 <span className={`flex min-w-0 shrink items-center gap-1.5 ${inline ? "lg:hidden" : ""}`}>
1937 <WorkspaceSwitcher user={user} workspace={ws} compact />
1938 <span aria-hidden="true" className="text-line-strong">
1939 /
1940 </span>
1941 </span>
1942 )}
1943 <Breadcrumbs pathname={pathname} missing={missing} repo={shell.repo} workspace={ws?.slug ?? null} />
1944 <div className="ml-auto flex shrink-0 items-center gap-1.5">
1945 <button
1946 type="button"
1947 aria-label="Search or jump to"
1948 onClick={() => setPalette(true)}
1949 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"
1950 >
1951 <Search size={15} className="shrink-0" />
1952 <span className="hidden grow truncate text-left text-[0.8125rem] md:inline">Search or jump to</span>
1953 <PaletteKey className="hidden rounded bg-raised px-1.5 font-mono text-[0.625rem] text-muted ring-1 ring-line md:inline" />
1954 </button>
1955 {ws && <AskG1tButton slug={ws.slug} />}
1956 {/* On a phone, Notifications is in the bottom bar. */}
1957 <span className="max-md:hidden">
1958 <NotificationsBell counts={shell.inbox ? { ...shell.inbox, unread: notificationsUnread } : null} />
1959 </span>
1960 <CreateMenu shell={shell} />
1961 {/* Without a workspace there is no dock: the account is here. */}
1962 {!ws && <AccountMenu user={user} side="bottom" />}
1963 </div>
1964 </header>
1965 {banner}
1966 <main id="content" tabIndex={-1} {...leaving} className={`min-w-0 grow outline-none ${leaving.className}`}>
1967 <InMain.Provider value={true}>{children}</InMain.Provider>
1968 </main>
1969 </div>
1970 </div>
1971 {/* The panel's edge: a rounded frame over the page, with the background beyond it, so what scrolls stays inside. */}
1972 {!conversation && (
1973 <div
1974 aria-hidden="true"
1975 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}`}
1976 />
1977 )}
1978 {ws && <BottomBar user={user} workspace={ws} pins={shell.pins ?? []} unread={unread} onReselect={panel ? () => setDrawer(true) : undefined} />}
1979 <CommandPalette open={palette} onOpenChange={setPalette} commands={commands} repo={shell.repo ? `${shell.repo.namespace}/${shell.repo.name}` : null} />
1980 </Sheet>
1981 );
1982}
1983
1984/** Create new: a project, an issue in the one you are in, a workspace or a team. */
1985function CreateMenu({ shell }: { shell: ShellData }) {
1986 return (
1987 <DropdownMenu>
1988 <Hint label="Create new">
1989 <DropdownMenuTrigger
1990 aria-label="Create new"
1991 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"
1992 >
1993 <Plus size={16} />
1994 <ChevronDown size={13} className="text-muted max-sm:hidden" />
1995 </DropdownMenuTrigger>
1996 </Hint>
1997 <DropdownMenuContent align="end" className="min-w-52">
1998 {shell.repo && (
1999 <>
2000 <DropdownMenuLabel className="truncate">In {shell.repo.name}</DropdownMenuLabel>
2001 <DropdownMenuItem asChild>
2002 <Link to={`/${shell.repo.namespace}/${shell.repo.name}/issues/new`}>
2003 <CircleDot />
2004 New issue
2005 </Link>
2006 </DropdownMenuItem>
2007 {shell.repo.member && (
2008 <DropdownMenuItem asChild>
2009 <Link to={`/${shell.repo.namespace}/${shell.repo.name}/plans`}>
2010 <ListTree />
2011 Plan work
2012 </Link>
2013 </DropdownMenuItem>
2014 )}
2015 <DropdownMenuSeparator />
2016 </>
2017 )}
2018 <DropdownMenuItem asChild>
2019 <Link to="/?agent=new">
2020 <Sparkles />
2021 Put an agent on it
2022 </Link>
2023 </DropdownMenuItem>
2024 <DropdownMenuItem asChild>
2025 <Link to="/new">
2026 <Box />
2027 New project
2028 </Link>
2029 </DropdownMenuItem>
2030 <DropdownMenuItem asChild>
2031 <Link to="/new/github">
2032 <GitBranch />
2033 Import from GitHub
2034 </Link>
2035 </DropdownMenuItem>
2036 <DropdownMenuSeparator />
2037 <DropdownMenuItem asChild>
2038 <Link to="/workspaces/new">
2039 <Users />
2040 New workspace
2041 </Link>
2042 </DropdownMenuItem>
2043 {/* A team in the workspace you are in, for whoever it lets create one. */}
2044 {shell.workspace &&
2045 (mayCreateTeams(shell.workspace.team_creation, shell.workspace.role) ? (
2046 <DropdownMenuItem asChild>
2047 <Link to={`/${shell.workspace.slug}/-/teams/new`}>
2048 <UsersRound />
2049 New team
2050 </Link>
2051 </DropdownMenuItem>
2052 ) : (
2053 <DropdownMenuItem disabled>
2054 <UsersRound />
2055 New team
2056 <span className="ml-auto pl-3 text-xs text-faint">Owners only</span>
2057 </DropdownMenuItem>
2058 ))}
2059 </DropdownMenuContent>
2060 </DropdownMenu>
2061 );
2062}