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