diff --git a/crates/fctl-control/src/api/sessions.rs b/crates/fctl-control/src/api/sessions.rs index a49ddca0..5b57a976 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -356,6 +356,12 @@ pub async fn list(ctx: &Ctx, req: &Request) -> AppResult { if http::query(req, "mine").is_some_and(|v| v == "1" || v == "true") { sql.push_str(" AND s.created_by = ?1"); } + // The sessions the caller started or follows (`session_followers`, + // joined for the caller in SESSION_SELECT): what the web app's Needs + // you looks through. + if http::query(req, "yours").is_some_and(|v| v == "1" || v == "true") { + sql.push_str(" AND (s.created_by = ?1 OR f.user_id IS NOT NULL)"); + } // The sessions that list a pull request, in a state, for the pull // requests page and the sidebar: among those `pull_request_sessions` // has, those whose own list (what their pages show, from their agents' diff --git a/docs/api.md b/docs/api.md index fd9bab83..244a4a34 100644 --- a/docs/api.md +++ b/docs/api.md @@ -110,7 +110,8 @@ It answers with the session, `queued`. A session is: `?status=active` (queued to stopping), `?status=ended` (stopped or failed) or one status, `?active_since=` (a time in milliseconds: those that haven't ended, and those that ended since, as the app's sidebar - lists the last hour's), `?mine=1` (started by the caller), `?reviews=1`, + lists the last hour's), `?mine=1` (started by the caller), `?yours=1` + (started or followed by the caller, as the app's Needs you lists them), `?reviews=1`, `?archived=1`, `?hidden=1`, `?pulls=open|merged|closed|any` (those that list a pull request in that state in their `pull_requests`, as their agents and GitHub last said; one nobody looked up counts as open: the diff --git a/docs/architecture.md b/docs/architecture.md index 0ead8a49..850ca374 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -554,7 +554,9 @@ five or more. Anyone on the instance creates one, as its primary admin. lists of workspaces and projects come in it (`model::WORKSPACE_ORDER`, `PROJECT_ORDER`): what someone hasn't placed follows, oldest first, so nothing moves unless they move it. Which workspaces they fold in the - sidebar stays in their browser, and so does a copy of what the sidebar + sidebar stays in their browser, with how wide they dragged it, whether + they folded it into its rail and whether Needs you is open + (`web/src/lib/sidebar-layout.ts`), and so does a copy of what the sidebar last showed them (names, colors and avatars, their role, each project's icon, description and active sessions; `web/src/lib/sidebar.ts`): when the app opens, the sidebar shows it at once, until the lists of workspaces and projects @@ -3549,12 +3551,9 @@ in `firecracker/` in the host's data directory. goes, and lets the states of stopped sandboxes go first while the disk is low. One another Firecracker release saved, or one that doesn't load, goes too, and the sandbox boots from its disk. A VM that runs through - the jailer saves its state at the root of its chroot, as the jail's - user, and the host takes it out to `saved/` before the jail goes; it - resumes in a new jail (below). A state saved in the jailer resumes - only in one, and one saved without it only without, so turning - `jailer` on or off lets the states kept before go. Image builders save - none: they boot afresh for each build. + the jailer saves none yet: Firecracker would write it in the jail's + chroot, which goes as the VM stops, so it boots from its disk. Image + builders save none either: they boot afresh for each build. - **The VM's init** is fctl-agent, from an initramfs the host makes of its own static fctl-agent (`crates/fctl-agent/src/vm`). It mounts the root, copies itself to `/opt/fctl/bin/fctl-agent`, sets up what images don't @@ -3612,23 +3611,9 @@ checked to be a socket. Its writable disk is lent to the jail's user while it runs, noted in `jail.json` beside the chroot, and given back to root as the VM stops, so that a later jail with the same uid owns nothing; jails of VMs that don't run, which a host that stopped -or crashed left, go before the next VM starts. The host keeps the VM's -configuration with its own paths in the sandbox's directory, for its -size and its disks. A jailed VM's saved state goes through its chroot: -Firecracker writes `vmstate` and `memory` at its root, as the jail's -user, and the host takes each out to `saved/` by what it opened without -following a link, checked to be a regular file of that user's with no -other name (so that the jail can't hand it a host's file, or the disk it -was lent), then gives it to root, readable by root alone. A resume makes -a new jail as a start does, but with no configuration: hard links of the -disks the VM booted with, at the same paths in the chroot, and of the -saved state, lent to the jail's user, who must read it. The host starts -Firecracker in it, has it load the state, and only then links the -vsock's socket out, since Firecracker makes it as the state loads; the -state's links in the chroot go once it is loaded. The jailer needs -cgroup v2 and a filesystem that allows device files (it makes `/dev/kvm` -in the chroot): without either, the driver isn't ready and says what to -change. +or crashed left, go before the next VM starts. The jailer needs cgroup v2 +and a filesystem that allows device files (it makes `/dev/kvm` in the +chroot): without either, the driver isn't ready and says what to change. `passt` runs outside the jail and drops to `nobody` itself; its pid's file goes in `/tmp` under a name with a random part. A jailed VM's cache server listens in the VM's socket directory, whose path stays short, and diff --git a/docs/development.md b/docs/development.md index 1f41632b..8e843d84 100644 --- a/docs/development.md +++ b/docs/development.md @@ -605,10 +605,11 @@ workspace chips or a page's tabs, scrolls in a row of its own whatever still sticks out. A card whose buttons go under its text when it is narrow, like Home's invitations, goes by its own width rather than the screen's, with a container query (`@container` on the card, `@xl:` and -`@max-xl:` inside): from 768 px the sidebar takes 244 px of the screen, so -a card is narrower at 768 px than at 767. When you change a page, look at -it 320 to 430 px wide, with long names in its data, and beside the sidebar -at 768 px. +`@max-xl:` inside): from 768 px the sidebar takes 288 px of the screen +unless someone dragged it wider (up to 420) or narrower (240), or 60 folded +into its rail, so a card is narrower at 768 px than at 767. When you change +a page, look at it 320 to 430 px wide, with long names in its data, and +beside the sidebar at 768 px. ## Other repositories diff --git a/docs/getting-started.md b/docs/getting-started.md index 0b02768e..95413856 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -435,7 +435,12 @@ started. project's sessions under it, in all your workspaces: those that haven't ended (starting, at work, waiting or paused), and for an hour those that stopped or failed, dimmer, the one you are on marked, so a click switches - to another. On a phone, tap the session's title for its + to another. Above them, **Needs you** gathers what waits on you in the + sessions you started or follow, most pressing first: what an agent asks + you, a failure, failed checks, a pull request an agent finished, a reply + it waits for. Its count shows in the browser's tab, and on fctl's icon + where you installed it. **Pull requests** opens every pull request agents + opened, sorted by what each needs next. On a phone, tap the session's title for its details: its pull requests, the files changed, its branch and who else is watching. Type below to message the agent, with files attached if you like; it reads your message at its next step. **Interrupt** stops the diff --git a/docs/llms.txt b/docs/llms.txt index 95916634..7be21e6c 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -202,7 +202,8 @@ Each recipe says who does what: some steps take a person with a role in the proj ## Web app - **Agent Floor** (`/`): the task box (project, model, effort, GitHub access, files; ⌘Enter starts, **Schedule** turns the task into a schedule), sessions **Working now** and **Recently** (choosing one of your workspaces above them lists only its sessions and moves the task box to its first project where you can start sessions, in your sidebar order), plan usage, invitations. ⌘K searches sessions, projects, workspaces and what sessions said. -- **Sidebar**: your workspaces and their projects in your order, and under each project, on every page, its sessions that haven't ended and, for an hour, those that stopped or failed. +- **Sidebar**: the Agent Floor; **Needs you** (what your sessions and those you follow wait on you for, most pressing first: an agent's question, a failure, failed checks, a pull request its agent finished, a reply, a pause; its count shows in the tab's title and on the installed app's icon); **Pull requests** (`/pulls`, with how many are ready for review); then your workspaces and their projects in your order, each project with its icon, and under each, on every page, its sessions that haven't ended and, for an hour, those that stopped or failed. The project a page is about shows its own pull requests and tickets too. Drag its edge to make it wider (a double click puts it back) and ⌘\ (Ctrl+\) folds it into a rail of icons. +- **Pull requests** (`/pulls`): the pull requests agents opened, each once with its sessions; open ones sorted by what each needs next (ready for review, checks failing, agents at work, merge queue, drafts), merged and closed ones by day; a filter, a workspace or project, Mine; `j`/`k`, Enter, `o` for GitHub, `/` to filter. - **Session page** (`/s/`): the live transcript (tool calls fold into lines, edits show highlighted; the images the agent read show small under them for 7 days), the composer to message the agent (with its owner's lists for the model and effort level it works at from its next step: a new model, which reads the conversation again without Claude's prompt cache, asks first), Interrupt, Stop and Resume, Share, the follow bell, Changes (the files the branch changed; a file opens every file's diff, highlighted, one after the other at that file, with the list of files beside them marking the one in view: `j`/`k` or the arrow keys in the list go from file to file, `n`/`p` from change to change, ⌘F finds in all the diffs (Enter and Shift+Enter, ⌘G, Alt+C/W/R for case, whole words and regular expressions), `s` lays them out side by side, `w` wraps lines; as the agent changes the files, its changes come in where the reader looks while the lines in view stay put, and a button goes to those out of sight), pull requests with checks, context and usage, retrospectives, ⌘F to find in the transcript, Open in Claude. - **Project page** (`/p/`): Sessions, Tickets, Schedules, Reviews, Memory, Retrospectives, Repositories and Members tabs; maintainers and owners also see Settings (agents, sandbox, GitHub, follow-ups…) and Secrets. - **Workspace page** (`/w/`): Projects, People, Runners (with the command and token that add one, the runners that wait for your approval, and the enrollment tokens: every one for admins, members' own for members), GitHub, Linear, Settings, and the Audit log for admins. diff --git a/web/src/components/shell/app-shell.test.tsx b/web/src/components/shell/app-shell.test.tsx index 54ca18fb..3f4cea4a 100644 --- a/web/src/components/shell/app-shell.test.tsx +++ b/web/src/components/shell/app-shell.test.tsx @@ -85,7 +85,11 @@ const projects: G.ProjectList = { projects: [project("web", acme, 2), project("a * The sidebar as a reload shows it, for Ada, on the page at `path`: the control plane's lists come * when the test says, and `cached` is in the cache already. */ -function reload(path = "/", cached: (client: QueryClient) => void = () => {}) { +function reload( + path = "/", + cached: (client: QueryClient) => void = () => {}, + more: { folded?: boolean; onFold?: (f: boolean) => void; scope?: string } = {}, +) { const client = new QueryClient(); client.setQueryData(keys.me, { user: { id: "usr_ada", name: "Ada Lovelace", role: "member" }, @@ -98,7 +102,7 @@ function reload(path = "/", cached: (client: QueryClient) => void = () => {}) { act(() => root.render( - {}} onNavigate={() => {}} onClose={() => {}} path={path} /> + {}} onNavigate={() => {}} onClose={() => {}} path={path} {...more} /> , ), ); @@ -120,11 +124,12 @@ function reload(path = "/", cached: (client: QueryClient) => void = () => {}) { /** The sessions listed under each project, with their statuses. */ sessions: () => Object.fromEntries( - [...container.querySelectorAll("ul[aria-label]")].map((ul) => [ + [...container.querySelectorAll("section ul[aria-label]")].map((ul) => [ ul.getAttribute("aria-label"), [...ul.querySelectorAll("a")].map((a) => [a.getAttribute("href"), a.textContent]), ]), ), + container, come: (lists: { workspaces?: G.WorkspaceList; projects?: G.ProjectList; @@ -198,6 +203,8 @@ const session = ( const recent = { since: "1h", limit: 100 }; const working = { status: "active", limit: 50 }; const ended = { status: "ended", limit: 12 }; +/** What Needs you looks through: the sessions Ada started or follows, from the last day. */ +const yours = { yours: true, since: "1d", limit: 200 }; describe("the sidebar's sessions", () => { // The sidebar's clock, which moves on every minute. @@ -235,7 +242,7 @@ describe("the sidebar's sessions", () => { }); } // Those the control plane has from an hour back. - expect(asked.sessions.at(-1)).toEqual({ activeSince: NOW - HOUR, limit: 100 }); + expect(asked.sessions).toContainEqual({ activeSince: NOW - HOUR, limit: 100 }); }); it("goes on listing one that ended for an hour", async () => { @@ -300,6 +307,177 @@ describe("the sidebar's sessions", () => { }); }); +describe("what needs you", () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date", "setInterval", "clearInterval"] }); + vi.setSystemTime(NOW); + }); + afterEach(() => vi.useRealTimers()); + + const ada = { id: "usr_ada", name: "Ada Lovelace" }; + const pr = (number: number): G.PullRequestRef => ({ + number, + url: `https://github.com/acme/web/pull/${number}`, + state: "open", + }); + + it("lists what its agents ask first, then pull requests they finished and replies they wait for", async () => { + const asks = session(7, "Round the prices", "idle", "prj_web", { + created_by: ada, + updated_at: 7, + question: { text: "Whole kroner, or øre?", options: ["Whole kroner", "Øre"], asked_at: NOW - MINUTE }, + }); + const finished = session(8, "Add Danish", "stopped", "prj_web", { + created_by: ada, + updated_at: 8, + ended_at: NOW - HOUR, + pull_requests: [pr(12)], + }); + const waits = session(9, "Fix the build", "idle", "prj_api", { + created_by: ada, + updated_at: 9, + status_reason: "Waiting for a message", + }); + const theirs = session(10, "Grace's", "idle", "prj_api", { + created_by: { id: "usr_grace", name: "Grace" }, + updated_at: 10, + status_reason: "Waiting for a message", + }); + const sidebar = reload("/"); + await sidebar.come({ workspaces, projects, sessions: [working, [asks, waits, theirs]] }); + await sidebar.come({ sessions: [ended, [finished]] }); + const needs = () => + [...sidebar.container.querySelectorAll('ul[aria-label="What needs you"] a')].map((a) => + a.getAttribute("title"), + ); + expect(needs()).toEqual([ + "Round the prices\nWhole kroner, or øre?", + "Add Danish\n#12 is ready for you", + "Fix the build\nWaiting for your reply", + ]); + // Its count is in the tab's title too. + expect(document.title).toBe("(3) fctl"); + }); + + it("counts the pull requests ready for review", async () => { + const sidebar = reload("/"); + await sidebar.come({ + workspaces, + projects, + sessions: [ + { pulls: "open", limit: 200 }, + [ + session(3, "Ready", "stopped", "prj_web", { pull_requests: [pr(3)] }), + session(4, "At work", "running", "prj_web", { pull_requests: [pr(4)] }), + ], + ], + }); + const link = sidebar.container.querySelector('a[href="/pulls"]'); + expect(link?.textContent).toBe("Pull requests1"); + expect(link?.getAttribute("title")).toBe("1 ready for review, of 2 open"); + }); + + it("looks through every session you started or follow from the last day", async () => { + const failed = session(11, "Migrate the orders", "failed", "prj_api", { + created_by: ada, + updated_at: 11, + ended_at: NOW - 5 * HOUR, + }); + const sidebar = reload("/"); + // Twelve others ended since: the Agent Floor's list of ended sessions no longer has it. + await sidebar.come({ workspaces, projects, sessions: [yours, [failed]] }); + expect(asked.sessions).toContainEqual({ yours: true, activeSince: NOW - 24 * HOUR, limit: 200 }); + const needs = [...sidebar.container.querySelectorAll('ul[aria-label="What needs you"] a')]; + expect(needs.map((a) => a.getAttribute("title"))).toEqual(["Migrate the orders\nFailed"]); + }); + + it("keeps its links out of Tab's way while it is closed", async () => { + const waits = session(9, "Fix the build", "idle", "prj_api", { + created_by: ada, + updated_at: 9, + status_reason: "Waiting for a message", + }); + const sidebar = reload("/"); + await sidebar.come({ workspaces, projects, sessions: [working, [waits]] }); + const list = () => sidebar.container.querySelector('ul[aria-label="What needs you"]'); + expect(list()?.closest("[inert]")).toBeNull(); + const toggle = [...sidebar.container.querySelectorAll("button")].find((b) => + b.textContent?.startsWith("Needs you"), + ); + act(() => toggle?.click()); + expect(toggle?.getAttribute("aria-expanded")).toBe("false"); + expect(list()?.closest("[inert]")).not.toBeNull(); + }); + + it("folds into a rail of the projects' icons, and unfolds from it", async () => { + const onFold = vi.fn(); + const sidebar = reload("/", () => {}, { folded: true, onFold }); + await sidebar.come({ workspaces, projects }); + const names = [...sidebar.container.querySelectorAll('a[href^="/p/"]')].map((a) => + a.getAttribute("aria-label"), + ); + expect(names).toEqual(["web", "api"]); + act(() => sidebar.container.querySelector('button[aria-label^="Unfold"]')?.click()); + expect(onFold).toHaveBeenCalledWith(false); + }); + + it("keeps Settings in the rail, and Admin for admins", async () => { + const member = reload("/", () => {}, { folded: true }); + await member.come({ workspaces, projects }); + const links = (c: HTMLElement) => + [...c.querySelectorAll('a[href="/settings"], a[href="/admin"]')].map((a) => + a.getAttribute("aria-label"), + ); + expect(links(member.container)).toEqual(["Settings"]); + const admin = reload( + "/admin", + (client) => + client.setQueryData(keys.me, { + user: { id: "usr_ada", name: "Ada Lovelace", role: "admin" }, + claude: [], + } as unknown as G.Me), + { folded: true }, + ); + await admin.come({ workspaces, projects }); + expect(links(admin.container)).toEqual(["Admin", "Settings"]); + expect(admin.container.querySelector('a[href="/admin"]')?.getAttribute("aria-current")).toBe("page"); + }); +}); + +describe("the project a page is about", () => { + /** The links under each project: its own pages, and its sessions. */ + const links = (c: HTMLElement) => + [...c.querySelectorAll("section a[aria-current]")].map((a) => a.textContent?.trim()); + + it("keeps its own links on its pull requests page, the one it is on lit", async () => { + const sidebar = reload("/pulls", () => {}, { scope: "p:api" }); + await sidebar.come({ workspaces, projects }); + const pulls = [...sidebar.container.querySelectorAll('a[href="/pulls"]')]; + // The one at the top, and the project's own. + expect(pulls).toHaveLength(2); + expect(pulls[0]?.getAttribute("aria-current")).toBeNull(); + expect(links(sidebar.container)).toEqual(["Pull requests"]); + expect(sidebar.container.textContent).toContain("Tickets"); + }); + + it("lights the pull requests at the top when the page lists every one", async () => { + const sidebar = reload("/pulls"); + await sidebar.come({ workspaces, projects }); + const pulls = [...sidebar.container.querySelectorAll('a[href="/pulls"]')]; + expect(pulls).toHaveLength(1); + expect(pulls[0]?.getAttribute("aria-current")).toBe("page"); + }); + + it("is the project of a session no list has, as its page loaded it", async () => { + const old = session(40, "Last month's", "stopped", "prj_api", { ended_at: NOW - 30 * 24 * HOUR }); + const sidebar = reload(`/s/${old.id}`); + await sidebar.come({ workspaces, projects, session: old }); + expect(sidebar.container.textContent).toContain("Tickets"); + const open = [...sidebar.container.querySelectorAll('a[href="/pulls"]')]; + expect(open).toHaveLength(2); + }); +}); + /** The shell at a phone's width, where the sidebar is a drawer (or `wide`, from 768 px, beside the page). */ function phone({ wide = false } = {}) { vi.stubGlobal("matchMedia", (query: string) => ({ @@ -404,6 +582,29 @@ function phone({ wide = false } = {}) { }; } +describe("folding the sidebar", () => { + const fold = () => + act(() => { + document.body.dispatchEvent( + new KeyboardEvent("keydown", { key: "\\", metaKey: true, ctrlKey: true, bubbles: true }), + ); + }); + + it("folds and unfolds it with ⌘\\ beside the page", () => { + phone({ wide: true }); + fold(); + expect(localStorage.getItem("fctl:sidebar-folded")).toBe("1"); + fold(); + expect(localStorage.getItem("fctl:sidebar-folded")).toBeNull(); + }); + + it("leaves it as it was where it is a drawer, which doesn't fold", () => { + phone(); + fold(); + expect(localStorage.getItem("fctl:sidebar-folded")).toBeNull(); + }); +}); + describe("the drawer", () => { it("slides in, and away when its close button or the shade closes it", () => { const shell = phone(); diff --git a/web/src/components/shell/app-shell.tsx b/web/src/components/shell/app-shell.tsx index 9c242439..6b4aee42 100644 --- a/web/src/components/shell/app-shell.tsx +++ b/web/src/components/shell/app-shell.tsx @@ -1,70 +1,21 @@ -// The signed-in layout: a quiet sidebar, the page, and the command palette. +// The signed-in layout: the sidebar (./sidebar.tsx), the page, and the command palette. -import { useQuery } from "@tanstack/react-query"; -import { Link, Outlet, useNavigate, useRouter, useRouterState } from "@tanstack/react-router"; -import { - ChevronRight, - ChevronsUpDown, - Cpu, - FolderPlus, - Lock, - LogOut, - MessageCircleQuestion, - Moon, - Plus, - Search, - Settings, - Shield, - Sun, - X, -} from "lucide-react"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { ProjectMark } from "@/components/project/project-icon"; -import { - Avatar, - Kbd, - Logo, - Menu, - MenuItem, - MenuSeparator, - StatusDot, - statusLabel, - toast, -} from "@/components/ui"; -import { WorkspaceAvatar } from "@/components/workspace/avatar"; -import type * as G from "@/gen"; -import { api } from "@/lib/api"; +import { Outlet, useRouter, useRouterState } from "@tanstack/react-router"; +import { type CSSProperties, useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { Logo, toast } from "@/components/ui"; import { cn } from "@/lib/cn"; -import { forgetDraft } from "@/lib/draft"; import { useFeed } from "@/lib/feed"; import { gravatarNews, gravatarPicture } from "@/lib/gravatar"; -import { forgetPush, onPushOpen, syncPush } from "@/lib/push"; -import { - keys, - queryClient, - recentSessions, - useInstance, - useMe, - useProjects, - useSidebarSessions, - useWorkspaces, -} from "@/lib/queries"; -import { forgetSidebar, type SidebarProject, type SidebarWorkspace, useSidebarLists } from "@/lib/sidebar"; -import { type Sortable, useSortable } from "@/lib/sortable"; -import { useTheme } from "@/lib/theme"; -import { - createsProjects, - groupProjects, - reorderProjects, - reorderWorkspaces, - roomForAnother, - useFactorsWatch, - useFolded, -} from "@/lib/workspaces"; +import { useHotkey } from "@/lib/hotkeys"; +import { onPushOpen, syncPush } from "@/lib/push"; +import { useMe } from "@/lib/queries"; +import { RAIL_WIDTH, SIDEBAR_WIDTH, useSidebarFolded, useSidebarWidth } from "@/lib/sidebar-layout"; +import { useFactorsWatch } from "@/lib/workspaces"; import { CommandPalette, usePaletteKeys } from "./command-palette"; import { useDrawerDrag } from "./drawer-drag"; -import { FloorLink } from "./floor-link"; import { MenuButton, ShellContext, useHeaderButtons } from "./menu-button"; +import { Sidebar } from "./sidebar"; +import { ResizeHandle } from "./sidebar-parts"; /** * The sidebar on phones: open, closed with its button or the shade (it slides away), or @@ -100,8 +51,28 @@ export function AppShell() { useGravatarNews(); useFactorsWatch(); const path = useRouterState({ select: (s) => s.location.pathname }); + const tab = useRouterState({ select: (s) => (s.location.search as { tab?: string } | undefined)?.tab }); + const scope = useRouterState({ + select: (s) => (s.location.search as { scope?: string } | undefined)?.scope, + }); + // How wide the sidebar is, and whether it is folded into its rail: as each person leaves it. + const [width, setWidth] = useSidebarWidth(); + const [folded, setFolded] = useSidebarFolded(); + const [resizing, setResizing] = useState(false); + const wide = useWide(); + // Only where it shows: on a narrow screen the sidebar is a drawer, which doesn't fold. + useHotkey( + "mod+\\", + useCallback(() => { + if (wide) setFolded(!folded); + }, [wide, folded, setFolded]), + ); return ( -
+
{/* On phones the sidebar is a drawer over the page: opaque, and out of the page once it has slid away (display: none), so that it is drawn anew each time it opens. Kept off screen with a blur, it sometimes stopped showing properly in Safari on iOS @@ -113,13 +84,34 @@ export function AppShell() { {/* The shade fades in and out with the drawer's slide (and goes with it at once). */} -
-
- -
- - -
- {isAdmin && ( - } - active={path === "/admin"} - onClick={onNavigate} - badge={{ - n: asking, - label: - asking === 1 ? "1 person waits for early access" : `${asking} people wait for early access`, - }} - > - Admin - - )} - } active={path === "/settings"} onClick={onNavigate}> - Settings - - {me && ( - // At the bottom of the window: the menu opens upward. - ( - - )} - > - {(close) => ( - <> - : } - onClick={() => { - setTheme(theme === "dark" ? "light" : "dark"); - close(); - }} - > - {theme === "dark" ? "Light theme" : "Dark theme"} - - } - onClick={() => { - close(); - onNavigate(); - void navigate({ to: "/settings", search: { linked: undefined, error: undefined } }); - }} - > - Claude and tokens - - - } - onClick={async () => { - close(); - await forgetPush(); - await forgetDraft(); - await api.logout().catch(() => {}); - queryClient.clear(); - forgetSidebar(); // last, so that no list that comes is kept again - window.location.assign("/login"); - }} - > - Sign out - - - )} - - )} -
-
- ); -} - -// The text that says how to move workspaces and projects, for screen readers. -const ORDER_HELP = "sidebar-order-help"; - -/** The time, again every minute: a session leaves the sidebar an hour after it ended. */ -function useMinute(): number { - const [now, setNow] = useState(Date.now); - useEffect(() => { - const t = setInterval(() => setNow(Date.now()), 60_000); - return () => clearInterval(t); - }, []); - return now; -} - -/** Sessions by their project's id, in the order they come. */ -function byProject(sessions: G.Session[]): Map { - const by = new Map(); - for (const s of sessions) { - const list = by.get(s.project_id); - if (list) list.push(s); - else by.set(s.project_id, [s]); - } - return by; -} - -const notSaved = (e: unknown) => - toast(`The new order wasn't saved: ${e instanceof Error ? e.message : "try again"}`, "error"); - -// Rows people drag: a held finger lifts one instead of opening the link's menu. -const DRAGGABLE = "touch-manipulation select-none [-webkit-touch-callout:none]"; -// A row or workspace lifted to be dragged, and settling into its place: a -// little larger, over the others. -const LIFTED = - "relative z-10 scale-[1.02] bg-raised shadow-[inset_0_0_0_1px_var(--c-line-strong),0_16px_32px_-8px_rgb(0_0_0/0.55),0_3px_8px_-2px_rgb(0_0_0/0.22)]"; - -/** A workspace in the sidebar: its name (its page) and its projects, which fold away. */ -function WorkspaceGroup({ - workspace, - projects, - path, - loading, - kept, - folded, - onFold, - onNavigate, - sort, - sessions, -}: { - workspace: SidebarWorkspace; - projects: SidebarProject[]; - path: string; - /** Its projects haven't come yet. */ - loading: boolean; - /** The workspace and its projects are as this browser kept them. */ - kept: boolean; - folded: boolean; - onFold: () => void; - onNavigate: () => void; - /** The sidebar's workspaces, which people drag by their headers. */ - sort: Sortable; - /** The sessions to show under each project, by its id. */ - sessions: Map; -}) { - const here = path === `/w/${workspace.slug}`; - const active = projects.reduce((n, p) => n + p.active_sessions, 0); - const sortProjects = useSortable({ - ids: kept ? [] : projects.map((p) => p.id), - onReorder: (ids) => reorderProjects(workspace.id, ids, notSaved), - label: (id) => projects.find((p) => p.id === id)?.name ?? "", - describedBy: ORDER_HELP, - }); - const lifted = sort.lifted === workspace.id; - // Its link, which gets the focus, says how to move it. - const { "aria-describedby": describedBy, ...handle } = sort.handleProps(workspace.id); - return ( -
-
- - - - - {workspace.name} - - {workspace.blocked ? ( - - ) : ( - folded && active > 0 && {active} - )} - - {createsProjects(workspace) && ( - - - - )} -
- {!folded && ( -
- {workspace.blocked ? ( - - Set up two-factor sign-in to open it - - ) : ( - <> - {projects.map((p) => ( - - ))} - {projects.length === 0 && !loading && createsProjects(workspace) && ( - - Create a project - - )} - - )} -
- )} -
+/** Whether the window is wide enough for the sidebar beside the page (md, 768 px). */ +function useWide(): boolean { + return useSyncExternalStore( + (fn) => { + const q = window.matchMedia?.("(min-width: 48rem)"); + q?.addEventListener?.("change", fn); + return () => q?.removeEventListener?.("change", fn); + }, + () => window.matchMedia?.("(min-width: 48rem)").matches ?? true, + () => true, ); } -/** - * A project in the sidebar, which people drag by its row (the sessions under it move with it): its - * icon, and how many of its sessions are at work. - */ -function ProjectRow({ - project: p, - path, - sort, - sessions, - onNavigate, -}: { - project: SidebarProject; - path: string; - /** Its workspace's projects. */ - sort: Sortable; - /** Its sessions to show under it. */ - sessions?: G.Session[]; - onNavigate: () => void; -}) { - const lifted = sort.lifted === p.id; - return ( -
- - - {p.name} - {p.active_sessions > 0 && ( - - - {p.active_sessions} - - )} - - {sessions && sessions.length > 0 && ( - - )} -
- ); -} - -/** - * A project's sessions under it in the sidebar, those that ended dimmer and the one whose page - * shows marked: a line runs down beside them from the project's dot. - */ -function ProjectSessions({ - project, - sessions, - path, - lifted, - onNavigate, -}: { - project: SidebarProject; - sessions: G.Session[]; - path: string; - /** The project is being dragged, with them. */ - lifted: boolean; - onNavigate: () => void; -}) { - return ( -
    - {sessions.map((s) => { - const here = path === `/s/${s.id}`; - const ended = s.status === "stopped" || s.status === "failed"; - return ( -
  • - - - {s.title} - : {s.question ? "asks you something" : statusLabel(s.status)} - {s.question && ( -
  • - ); - })} -
- ); -} +export { Sidebar }; diff --git a/web/src/components/shell/sidebar-parts.tsx b/web/src/components/shell/sidebar-parts.tsx new file mode 100644 index 00000000..50ec2b38 --- /dev/null +++ b/web/src/components/shell/sidebar-parts.tsx @@ -0,0 +1,337 @@ +// The sidebar's parts: the search that opens ⌘K, a session's line, a count, the rows at its foot, +// the person's menu, and the handle that makes it wider or narrower. + +import { Link, useNavigate } from "@tanstack/react-router"; +import { + ChevronsUpDown, + Cpu, + LogOut, + MessageCircleQuestion, + Moon, + Search, + Settings, + Shield, + Sun, +} from "lucide-react"; +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { PullRequestChecksIcon, PullRequestStateIcon } from "@/components/session/pull-request"; +import { Avatar, Kbd, Menu, MenuItem, MenuSeparator, StatusDot, statusLabel } from "@/components/ui"; +import type * as G from "@/gen"; +import { api } from "@/lib/api"; +import { clearAttention } from "@/lib/attention"; +import { cn } from "@/lib/cn"; +import { forgetDraft } from "@/lib/draft"; +import { apple } from "@/lib/hotkeys"; +import { pullRequests } from "@/lib/pulls"; +import { forgetPush } from "@/lib/push"; +import { queryClient } from "@/lib/queries"; +import { forgetSidebar } from "@/lib/sidebar"; +import { useTheme } from "@/lib/theme"; + +/** The time, again every minute: a session leaves the sidebar an hour after it ended. */ +export function useMinute(): number { + const [now, setNow] = useState(Date.now); + useEffect(() => { + const t = setInterval(() => setNow(Date.now()), 60_000); + return () => clearInterval(t); + }, []); + return now; +} + +/** The search field that opens the command palette. */ +export function SearchButton({ onPalette }: { onPalette: () => void }) { + return ( + + ); +} + +/** How many of something, beside a row; what it counts on hover. */ +export function Count({ n, label }: { n: number; label: string }) { + if (n <= 0) return null; + return ( + + {n} + + ); +} + +/** + * A session under its project: its status, its title, and what it waits on: its question, or its + * pull request's state and checks. Those that ended are dimmer, the one whose page shows marked. + */ +export function SessionLine({ + s, + here, + lifted, + onNavigate, +}: { + s: G.Session; + here: boolean; + /** Its project is being dragged, with it. */ + lifted?: boolean; + onNavigate: () => void; +}) { + const ended = s.status === "stopped" || s.status === "failed"; + const [pr] = pullRequests(s); + return ( + + + {s.title} + : {s.question ? "asks you something" : statusLabel(s.status)} + {s.question ? ( +