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