Official

sidebar

Built-in sidebar UI (JavaScript UI plugin).

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/sidebar@0.2.7

Permissions in 0.2.7

  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Add and remove workspaces, and create, rename, check off and archive chats
  • Run other plugins' commands commands.runHighRuns commands of other plugins.Open the chat search from the search button, and close the tab on screen with Cmd+W when its chat is part of a task
  • Read chats chats.readMediumReads your transcripts and chat lists.List workspaces and chats, and follow them as agents work
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw the sidebar, and its top controls in the title strip after the sidebar toggleSlots: lefttitle

Files

views.tsx66.1 KB
// The left sidebar's trees: search and actions, the workspace picker, the list
// of chats, and the footer with the notice that offers archived rows back. Handlers only run controller effects or mutate
// state and update; the preview hydration fires from rendering, guarded so
// each chat reads once.
// HTM whitespace is significant; keep these templates out of Prettier's
// HTML formatter.
import * as kit from "divergence";
import type { EffectViewContext } from "divergence/effect";
import type { ButtonClickEvent, Chat, ClickEvent, DragOverEvent, DropEvent, Element, Modifiers, PointerMoveEvent, PresetColor, SecondaryClickEvent, Workspace } from "divergence";
import type { Sidebar } from "./controller.ts";
import { CHEVRON_DOWN, CHEVRON_RIGHT, MARK_INSET } from "../sdk/ui/icons.ts";
import { STATUS_TONE } from "../sdk/ui/status.ts";
import { workspaceMarkOf } from "../sdk/ui/workspace.ts";
import {
  DOCK_ROWS,
  pageOf,
  shareDock,
  arrangementOf,
  canPlace,
  chatStatus,
  chatTitleOf,
  completedOf,
  elapsed,
  focusedRows,
  isDraft,
  isSnoozed,
  isTaskRow,
  listedChats,
  openingChat,
  rowStatus,
  rowTitleOf,
  sections,
  shownChats,
  taskChats,
  taskOf,
  stillWorking,
  workspaceLooks,
} from "./sections.ts";
import type { ChatRowStatus, Over, Part, SectionId, SectionOver } from "./sections.ts";

// The shared surface looks from the runtime; an older runtime without them
// gets the same `elevation`, which its kernel already draws.
const RAISED = kit.RAISED ?? { elevation: "raised" };
const EDGED = kit.EDGED ?? { elevation: "edge" };
const FLAT = kit.FLAT ?? { elevation: "none" };
// The chats scroll as a list that opens at its first row and lays out only
// the rows on screen. A runtime without it scrolls a column of every row.
const LIST = kit.LIST;
// The kernel carries a dragged row itself and says where the pointer is, so
// the rows make way for it. An older kernel draws a line where it lands and
// says only where it was dropped.
const LIVE_DRAG = !!kit.LIVE_DRAG;
// The kernel opens the Options menu on the press itself. An older kernel
// leaves the toggle to the button's own click.
const POPOVER_TOGGLE = !!kit.POPOVER_TOGGLE;
// What a section's heading carries when it is dragged up or down the list.
const SECTION_TYPE = "divergence/section";

// Layout for the templates below: a flex column, a row that centres its
// children across, a child that takes the free space (and may shrink below
// its content), the whole of the parent, and the hover wash.
const column = { display: "flex", flexDirection: "column" } as const;
const row = { display: "flex", flexDirection: "row", alignItems: "center" } as const;
// The open chat is raised like the panes (the item's `lift`, which keeps the
// edge's width on every other row, so opening a chat never moves its text).
const fill = { flexGrow: 1, flexShrink: 1, flexBasis: "0%", minWidth: 0, minHeight: 0 } as const;
const full = { width: "100%", height: "100%" } as const;
const HOVER = { background: "hover" } as const;
// A row of the list leaves its selected fill to the one fill that slides from row to row under them
// (`chat-selection`), keeping the selected label's colour; a docked row draws its own.
const UNDER_SELECTION = { background: "transparent", ...FLAT } as const;
// A heading is the text colour stepped back a little: full white on the dark ground glares beside the muted rows.
const HEADING_OPACITY = 0.8;
// The room above a section's heading, which is the same wherever the heading stands: in the list, in the dock, or
// in the sidebar's last row beside Options.
const SECTION_GAP = "0.75rem";
// A label's last letter is drawn about a pixel short of its box's end, so the count of a heading as wide as its
// content stands that much further from the mark, and the label, the mark and the count are drawn evenly apart.
const LABEL_SLACK = 1;
// The profile picture rests on the `muted` fill, which looks almost the same
// as the plain hover wash, so under the pointer it takes the wash at twice its
// strength and its person mark brightens to the text colour.
const OPTIONS_HOVER = { background: "hover/200" } as const;
// The room above the pinned rows, over which the rows passing under them blur
// and fade into the ground, as the chat does above the prompt box; under the
// pinned rows they are gone. `ground` is the fade a kernel that knows it draws;
// an older one draws only the blur.
const DOCK_LEAD = 40;
const LEAD_BACKDROP = { blur: [0, 8], ground: [0, 1] } as const;
const DOCK_BACKDROP = { blur: 20, ground: [1, 1] } as const;
// How tall the dock's edge is, the strip at the foot of that room that drags the docked rows' height.
const EDGE_HEIGHT = 10;
// Heights the kernel measured as it last drew them (`measure`): each docked
// section's first five rows (`page:<id>`) and all its rows (`rows:<id>`), the
// list's room (`list`) and the whole dock under its edge (`dock`).
const sized: Record<string, number> = {};
const measure = (key: string, update: () => void) => (
  <canvas position="absolute" left={0} top={0} bottom={0} width={1} commands={[]} onResize={(e: { height: number }) => {
      if (sized[key] === e.height) return;
      sized[key] = e.height;
      update();
    }} />
);
// A docked section as the dock draws it: its heading, its rows, its "Show
// more" or "Show less" when that stays in the dock, and whether its rows
// scroll in a box of their own.
interface DockPart {
  readonly id: SectionId;
  readonly gap: Element[];
  readonly heading: Element;
  readonly chats: Element[];
  readonly tail: Element | null;
  readonly boxed: boolean;
}
// A row's height until the dock has measured its rows.
const ROW_GUESS = 40;
// The least and most the docked sections' rows can be dragged to, and the height they take now.
let dockSpan = { min: 0, max: 0, shown: 0 };

// The height of each docked section's box of rows, by section id: its first
// five rows, or once the user dragged the dock, its share of the height
// dragged to (`shareDock`). It notes in `dockSpan` that height can go from a
// row of each section to all their rows, as far as the list leaves room for
// the rest of the dock and a row of its own.
function dockLayout(dockHeight: number | null, boxed: ReadonlyArray<{ id: string; rows: number }>): Record<string, number> {
  const total = (heights: readonly number[]) => heights.reduce((sum, height) => sum + height, 0);
  const need = boxed.map(({ id, rows }) => sized[`rows:${id}`] ?? rows * ROW_GUESS);
  const page = boxed.map(({ id, rows }) => sized[`page:${id}`] ?? Math.min(rows, DOCK_ROWS) * ROW_GUESS);
  const min = total(boxed.map(({ rows }, index) => page[index]! / Math.min(rows, DOCK_ROWS)));
  const room = sized.list ? sized.list - ((sized.dock ?? 0) - dockSpan.shown) - DOCK_LEAD - ROW_GUESS : Infinity;
  const max = Math.max(min, Math.min(total(need), room));
  const heights = dockHeight === null ? page : shareDock(Math.min(Math.max(dockHeight, min), max), need);
  dockSpan = { min, max, shown: total(heights.map((height, index) => Math.min(height, need[index]!))) };
  return Object.fromEntries(boxed.map(({ id }, index) => [id, heights[index]!]));
}
// Shown only while the pointer is on a chat's status mark (the mark is the
// hover group `glyph`), or only while it is not: the check shows only
// where a click checks the chat off.
const revealOnGlyph = { visibility: "hidden", groupHover: { group: "glyph", visibility: "visible" } } as const;
const HIDE_ON_GLYPH = { group: "glyph", visibility: "hidden" } as const;
// Shown only while the pointer is on the row (the hover group `item`), or only while it is not.
const revealOnRow = { visibility: "hidden", groupHover: { group: "item", visibility: "visible" } } as const;
const HIDE_ON_ROW = { group: "item", visibility: "hidden" } as const;
// The list's width as last measured, which places a row's popover and menu just past the
// sidebar's edge: their anchor runs from the row's mark to there.
let listWidth = 268;
const besideAnchor = () => <div width={Math.max(listWidth - 22, 1)} height={1} />;
// A popover in a row's leading slot, taking no room there.
const beside = (popover: Element) => <div position="absolute" left={0} top={0}>{popover}</div>;

// The task popover's timers: the second's wait before it opens and the
// fade before it closes (one popover at a time).
const popoverTimers: { open?: ReturnType<typeof setTimeout>; close?: ReturnType<typeof setTimeout> } = {};
// A layer over the whole of its parent that centres what it holds.
const layer = {
  position: "absolute",
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
};
// A row's menu entry: its icon and label, the key its command is bound to, and what it runs;
// one with `submenu` opens those choices beside it and runs with the one chosen.
interface MenuEntry {
  readonly id: string;
  readonly icon: string;
  readonly label: string;
  readonly key?: string;
  readonly submenu?: readonly { value: string; label: string }[];
  readonly run: (choice?: string) => void;
}
// How long Snooze keeps a row away, by its submenu value; null until the user ends it.
const SNOOZES: readonly { value: string; label: string; ms: number | null }[] = [
  { value: "hour", label: "1 Hour", ms: 60 * 60 * 1000 },
  { value: "hours", label: "4 Hours", ms: 4 * 60 * 60 * 1000 },
  { value: "day", label: "1 Day", ms: 24 * 60 * 60 * 1000 },
  { value: "week", label: "1 Week", ms: 7 * 24 * 60 * 60 * 1000 },
  { value: "always", label: "Indefinitely", ms: null },
];
const LIVE_TONE: Record<ChatRowStatus, "warning" | "danger" | "muted"> = {
  blocked: "warning",
  running: "muted",
  failed: "danger",
  review: "muted",
  idle: "muted",
};

// Rows and buttons other plugins add to the sidebar: each publishes the id of
// a view of its own in the app's shared state and clears it when it goes. One
// under a key starting with `sidebarItem.` is a row of the footer; one under
// `sidebarButton.` is a button in the footer's last row, left of Options, in a
// square as big as Options (the settings plugin's update button); one under
// `sidebarMenu.` is a row of the Options menu, above Settings (the market's
// account and Marketplace rows). In the order of their keys, so they keep
// their places. The one under `sidebarPicture` is drawn in Options' circle in
// place of the person mark (the market's picture of the signed-in publisher).
const ITEM_PREFIX = "sidebarItem.";
const BUTTON_PREFIX = "sidebarButton.";
const MENU_PREFIX = "sidebarMenu.";
const PICTURE_KEY = "sidebarPicture";
const BUTTON_SIZE = 22;
// How wide a row's trailing mark is (a workspace's mark, a number's cap, a small icon), and how far Options, which
// is wider, reaches past the line where those marks end so that its centre is on theirs.
const TRAILING_MARK = 14;
const OPTIONS_OVERHANG = (BUTTON_SIZE - TRAILING_MARK) / 2;
export function sidebarItems(shared: Readonly<Record<string, unknown>> | undefined, prefix = ITEM_PREFIX): number[] {
  return Object.entries(shared ?? {})
    .filter((entry): entry is [string, number] => entry[0].startsWith(prefix) && typeof entry[1] === "number")
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([, view]) => view);
}

export function renderSidebar(ctx: EffectViewContext<{ cmd?: boolean }>, sidebar: Sidebar["Service"]): Element | null {
  const { state } = sidebar;
  const app = ctx.app;
  // A row of the Options menu changes the route, which closes the menu.
  if (state.options !== null && state.options !== (app.route ?? "chat")) state.options = null;
  // Settings takes the window: its own list of sections is the sidebar.
  if (app.route === "settings") return null;
  if (!state.loaded) {
    return (
      <div {...column} gap="small" padding="medium">
        {state.failed ? <text style="body" size="xs" tone="danger">{`The chats could not be read: ${state.failed}`}</text> : <text style="muted">Loading…</text>}
      </div>
    );
  }

  // Only a multi-chat task can change which child rows belong in this flat list.
  // Ordinary rows and members of the same task share one projected output.
  const taskCases = Object.fromEntries(Object.entries(state.homes).filter(([id]) => isTaskRow(state, { id })));
  const activeTask = sidebar.nativeApp?.project
    ? sidebar.nativeApp.project({ key: "chatId", cases: taskCases, default: null })
    : app.chatId ? taskCases[app.chatId] ?? null : null;

  // Latest model activity; status is the fallback for an empty transcript.
  function liveLine(chat: Chat): string {
    if (chat.status !== "running") {
      const { agents, commands } = stillWorking(state, chat);
      const count = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
      if (agents && commands) return `${count(agents, "agent")} and ${count(commands, "command")} working`;
      if (agents) return `${count(agents, "agent")} working`;
      if (commands) return `${count(commands, "command")} running`;
    }
    // The transcript is read once per chat, when a row first shows it. The
    // check runs here, synchronously: a forked check could run after the
    // chat was removed and resurrect its preview with a stray read.
    const preview = state.previews[chat.id];
    if (!preview?.loading && !preview?.revision) ctx.run(sidebar.ensurePreview(chat.id));
    const status = chatStatus(state, chat);
    // A failed turn says so before anything it said.
    if (status === "failed") {
      const ago = elapsed(Date.now(), chat.updatedAt);
      return ago ? `Failed · ${ago}` : "Failed";
    }
    if (chat.status !== "running" && preview?.assistantLine) return preview.assistantLine;
    if (preview?.line) return preview.line;
    const base =
      status === "blocked"
        ? "Waiting on you"
        : status === "running"
          ? "Working…"
          : status === "review"
            ? "Finished"
            : chat.sessionId
              ? "Idle"
              : "Not started";
    // A review always stamped its finish when the run ended; an idle chat
    // shows how long ago it was touched.
    const finishedAt = state.finished[chat.id];
    const since =
      status === "review" && finishedAt
        ? new Date(finishedAt).toISOString()
        : status === "idle" && chat.sessionId
          ? chat.updatedAt
          : null;
    const ago = since ? elapsed(Date.now(), since) : "";
    return ago ? `${base} · ${ago}` : base;
  }

  // --- rows -----------------------------------------------------------------

  // Each workspace's mark (its project icon, the app's mark, or its
  // coloured folder), for the rows of its chats.
  const workspaceMarks = new Map<string, Workspace>(state.workspaces.map((w) => [w.id, w]));
  const workspaceMark = (w: Workspace | undefined) => {
    if (!w) return null;
    const mark = workspaceMarkOf(w);
    return mark.image
      ? <image path={mark.image} width={14} height={14} radius={3} />
      : <icon name={mark.icon ?? "folder"} color={mark.color} small tone="faint" />;
  };

  // Enter or leaving the field saves what is typed; Escape closes the field
  // and keeps the title. A kernel without `onBlur` keeps the field open.
  function renameField(editing: { id: string; title: string }) {
    return (
      <input id={`rename-${editing.id}`} value={editing.title} keys={["escape"]} onKey={(e: { key: string }) => {
            if (e.key === "escape") ctx.run(sidebar.cancelRename());
          }} onChange={(e: { value: string }) => {
            editing.title = e.value;
          }} onSubmit={() => ctx.run(sidebar.commitRename())} onBlur={() => ctx.run(sidebar.commitRename(editing.id))} />
    );
  }

  // The row's mark: the workspace's mark, which turns into the status
  // circle while the pointer is on the row, a spinner while the chat runs,
  // or `number` while Cmd is held, and a check while the pointer is on the
  // mark; clicking the check checks the chat off (or opens it again).
  function glyph(chat: Chat, status: ChatRowStatus, number: Element | null) {
    const done = !!completedOf(state, chat);
    if (!done && isDraft(state, chat)) return <button id={`play-${chat.id}`} icon={ctx.state.cmd ? "list-plus" : "play"} variant="ghost" small muted disabled={!state.chat || state.submitting.has(chat.id)} loading={state.submitting.has(chat.id)} tooltip={ctx.state.cmd ? "Queue draft" : "Send draft (⌘ or Ctrl click to queue)"} onClick={(event?: ButtonClickEvent) => ctx.run(sidebar.submitDraft(chat.id, event ? (event.modifiers.secondary ?? event.modifiers.meta) : !!ctx.state.cmd))} />;
    if (!done && state.queued.has(chat.id)) return <button id={`unqueue-${chat.id}`} icon="list-minus" variant="ghost" small muted disabled={!state.chat} tooltip="Remove from queue" onClick={() => ctx.run(sidebar.unqueue(chat.id))} />;
    // A checked-off chat shows the ticked circle.
    const circle = <icon name="circle" small tone={STATUS_TONE[status]} />;
    const workspace = done || number || status === "running" ? null : workspaceMark(workspaceMarks.get(chat.workspaceId));
    const mark = done ? <icon name="circle-check" small tone="muted" /> : (number ?? (status === "running" ? <spinner activity /> : (workspace ?? circle)));
    return checkable(`glyph-${chat.id}`, mark, done, () => ctx.run(sidebar.toggleCompleted(chat)), workspace ? circle : null);
  }

  // A status mark and the check that lie over each other: the pointer on
  // the mark swaps them, and a click runs `check`. With `onRow`, the mark
  // gives its place to `onRow` while the pointer is anywhere on the row.
  function checkable(id: string, mark: Element, done: boolean, check: () => void, onRow: Element | null = null) {
    return (
      <div {...column} group="glyph" id={id} width={17} height={17} flexShrink={0} borderRadius="full" hover={HOVER} position="relative" stopPropagation onClick={check}>
        <div {...layer}><div {...column} groupHover={done ? undefined : HIDE_ON_GLYPH}>{onRow ? <div {...column} groupHover={HIDE_ON_ROW}>{mark}</div> : mark}</div></div>
        {onRow
          ? (
            <div {...layer}>
              <div {...column} groupHover={HIDE_ON_GLYPH}><div {...column} {...revealOnRow}>{onRow}</div></div>
            </div>
          )
          : null}
        {done
                    ? null
                    : (
                      <div {...layer}>
                        <div {...column} {...revealOnGlyph}><icon name="circle-check" small tone="muted" /></div>
                      </div>
                    )}
      </div>
    );
  }

  // Every row, heading and the list itself take a dragged chat. A carried
  // row of the list (a chat row, a task row, or the tab of a chat that is a
  // row of its own) moves its place to where the pointer is, and the drop
  // lands it there: over a row, before it in its upper half and after it in
  // its lower half; over a heading, at the top of that section. A chat that
  // shares its task with others has no row to move: on the middle of another
  // row it joins that row's task (document 4), and dropped anywhere else in
  // the list it leaves its task for a row of its own there.
  function dropTarget(over: (zone: string) => Over, row?: string, section?: SectionId) {
    // The task the row stands for, which a carried chat's drop on its middle joins.
    const rowTask = row ? taskOf(state, row) : undefined;
    // Rows the dock floats over still hear the pointer; the model hears only the part it is over.
    const part: Part = section && arrangementOf(state).dock.includes(section) ? "dock" : "list";
    return {
      // A heading carried over a row goes after the row's section.
      types: ["divergence/chat", "divergence/task", ...(section ? [SECTION_TYPE] : [])],
      // While a row is carried a row has two halves; otherwise its middle takes a chat that joins.
      ...(row ? (state.dragging ? { reorder: "vertical" as const } : { zones: "bands" as const }) : {}),
      onOver: (e: DragOverEvent) => {
        if (e.type === SECTION_TYPE) {
          if (e.zone) ctx.run(sidebar.moveSection(carriedSection(e), { section: section!, zone: "after" }));
          return;
        }
        const carried = carriedChat(e);
        if (movesRow(e)) {
          if (e.zone) ctx.run(sidebar.dragChat(carried, over(e.zone), part));
          return;
        }
        // Leaving one row must not clear the mark the row it went onto just took.
        if (e.zone === null) {
          if (state.joining === row) ctx.run(sidebar.markJoining(null));
          return;
        }
        const joins = e.zone === "into" && !!rowTask && state.homes[carried] !== rowTask.id;
        ctx.run(sidebar.markJoining(joins ? row! : null));
      },
      // The kernel that tells where the pointer is has already moved the
      // chat's place there; an older one tells only the drop.
      onDrop: (e: DropEvent) => {
        if (!("data" in e)) return;
        if (e.type === SECTION_TYPE) return ctx.run(sidebar.landSection(carriedSection(e)));
        const carried = carriedChat(e);
        if (movesRow(e)) return ctx.run(sidebar.dropChat(carried, LIVE_DRAG ? undefined : over(e.zone)));
        if (e.zone === "into" && rowTask) {
          if (state.homes[carried] !== rowTask.id) ctx.run(sidebar.placeChat(carried, { kind: "join", taskId: rowTask.id }));
          return;
        }
        ctx.run(sidebar.placeChat(carried, { kind: "alone" }, over(e.zone)));
      },
    };
  }

  // Whether a drag carries a row of the list, which moves its place, rather
  // than a chat that shares its task with others.
  function movesRow(e: { type: string; data: unknown }): boolean {
    return e.type === "divergence/task" || !inTaskOfSeveral(carriedChat(e));
  }

  // The chat a drag carries: a chat's own, or the first chat of a carried task row.
  function carriedChat(e: { data: unknown }): string {
    const data = (e.data ?? {}) as { chatId?: string };
    return String(data.chatId ?? "");
  }

  // The section a carried heading stands for.
  function carriedSection(e: { data: unknown }): SectionId {
    return ((e.data ?? {}) as { sectionId: SectionId }).sectionId;
  }

  // A heading, or the room at the end of the list or the dock that shows
  // while a heading is carried and that part has no other: the carried
  // heading's place moves to where the pointer is, and the drop lands it.
  function sectionTarget(over: (zone: "before" | "after") => SectionOver) {
    return {
      types: [SECTION_TYPE],
      reorder: "vertical" as const,
      onOver: (e: DragOverEvent) => {
        if (e.zone) ctx.run(sidebar.moveSection(carriedSection(e), over(e.zone as "before" | "after")));
      },
      onDrop: (e: DropEvent) => {
        if ("data" in e) ctx.run(sidebar.landSection(carriedSection(e)));
      },
    };
  }
  const emptyArea = (area: "list" | "dock") => <div id={`${area}-area`} height={28} flexShrink={0} borderRadius="md" background="hover" drop={sectionTarget(() => ({ area }))} />;

  // Whether a chat shares its task with others, so dropping it in the list takes it out.
  function inTaskOfSeveral(chatId: string): boolean {
    const task = taskOf(state, chatId);
    return !!task && taskChats(state, task).length > 1;
  }

  // A chat: its mark (the workspace's, which turns into the check) and its
  // title across the whole row, and under them its live line from the row's
  // left edge, with pin, rename and archive over the line's end while the
  // pointer is on it. A running chat shows the spinner as its mark and the
  // workspace's mark at the live line's end. A chat being renamed is the
  // rename field. While Cmd is held, the first nine rows show the number
  // that opens them with Cmd in place of their mark (a draft's, a queued
  // or a checked-off chat's at the title's end), in a cap the mark's size
  // so holding Cmd moves nothing.
  function chatRow(chat: Chat, position: number, section: SectionId, slides: boolean) {
    const task = taskOf(state, chat.id);
    const taskRow = isTaskRow(state, chat);
    const onScreen = taskRow && activeTask === task?.id;
    // While a task's chats are listed under it, its active child is selected.
    const listed = taskRow && (onScreen || state.expanded.has(task!.id));
    // A new host resolves this component prop from native app state. The
    // right side of `??` stays unread there, so a one-chat row does not
    // subscribe the whole sidebar view to a selection it can draw itself.
    const selected = taskRow ? false : (sidebar.nativeApp?.bind?.("chatId", chat.id) ?? app.chatId === chat.id);
    const status = rowStatus(state, chat);
    const editing = state.editing?.id === chat.id ? state.editing : null;
    // A checked-off chat is one struck line that runs to the row's end, with
    // no workspace mark and no hover actions (its menu has them),
    // and a draft or a queued chat one plain line: no live line under any of
    // them. A task row is always one line: each chat's status shows on its
    // own child row and tab.
    const done = !!completedOf(state, chat);
    const compact = taskRow || done || isDraft(state, chat) || state.queued.has(chat.id);
    const title = rowTitleOf(state, chat);
    const rename = () => ctx.run(sidebar.startRename({ id: chat.id, title, ...(taskRow ? { task: task!.id } : {}) }));
    const opens = openingChat(state, chat);
    // A row drags to another place in the list; where it may land is the
    // model's (`dropTargets`).
    const movable = canPlace(section) && !editing;
    // Pinning is for a chat that has started and is not checked off.
    const pinned = section === "pinned";
    // A task row that does not list its chats offers them in a popover
    // beside it after the pointer rests on it a second (document 1).
    const pops = taskRow && !listed && !editing && !state.dragging;
    // The row's menu (document 8), whose entries are the row's hover actions, Snooze and Mark Done.
    const menuOpen = state.rowMenu?.chatId === chat.id && !state.rowMenu.child;
    const snoozed = isSnoozed(state, chat);
    const entries: MenuEntry[] = [
      ...(taskRow && !onScreen
        ? [{ id: "row-menu-chats", icon: state.expanded.has(task!.id) ? "chevrons-down-up" : "chevrons-up-down", label: state.expanded.has(task!.id) ? "Hide Chats" : "Show Chats", run: () => ctx.run(sidebar.toggleExpanded(task!.id)) }]
        : []),
      ...(!compact || (taskRow && !done) ? [{ id: "row-menu-pin", icon: pinned ? "pin-off" : "pin", label: pinned ? "Unpin" : "Pin", key: state.keys["sidebar.togglePin"], run: () => ctx.run(sidebar.togglePin(chat)) }] : []),
      ...(done
        ? []
        : snoozed
          ? [{ id: "row-menu-unsnooze", icon: "alarm-clock-off", label: "Unsnooze", run: () => ctx.run(sidebar.unsnoozeRow(chat)) }]
          : [{
              id: "row-menu-snooze",
              icon: "alarm-clock",
              label: "Snooze",
              submenu: SNOOZES,
              run: (choice?: string) => {
                const ms = SNOOZES.find((s) => s.value === choice)?.ms;
                if (ms !== undefined) ctx.run(sidebar.snoozeRow(chat, ms === null ? null : Date.now() + ms));
              },
            }]),
      { id: "row-menu-rename", icon: "pencil", label: "Rename", run: rename },
      { id: "row-menu-done", icon: done ? "rotate-ccw" : "circle-check", label: done ? "Open Again" : "Mark Done", key: state.keys["sidebar.toggleChatCompleted"], run: () => ctx.run(sidebar.toggleCompleted(chat)) },
      { id: "row-menu-archive", icon: "archive", label: "Archive", key: state.keys["sidebar.archiveRow"], run: () => ctx.run(taskRow ? sidebar.archiveTask(task!.id) : sidebar.archive(chat)) },
    ];
    const menu = menuOpen ? rowMenu(chat.id, false, entries) : null;
    // The menu's list closes on its own (Escape, a click away) without a
    // word to the plugin, so the hover popover never waits on it: the
    // right click only stops the popover's wait.
    const popover = pops
      ? beside(
          <popover id={`task-popover-${task!.id}`} open={state.popover === task!.id} side="right" width={300} onDismiss={closePopover}>
            {besideAnchor()}
            {popoverContent(task!.id)}
          </popover>,
        )
      : null;
    const number = ctx.state.cmd && position < 9
      ? (
        <div {...row} justifyContent="center" width={14} height={14} flexShrink={0} background="muted" borderRadius={4}>
          <text size={10} weight={500} lineHeight={14} tone="muted">{String(position + 1)}</text>
        </div>
      )
      : null;
    // A draft's, a queued chat's and a checked-off chat's mark is its button
    // or its tick, so their number and a draft's or a queued chat's
    // workspace mark end the title's line.
    const leads = !done && !isDraft(state, chat) && !state.queued.has(chat.id);
    const running = status === "running";
    const workspace = workspaceMark(workspaceMarks.get(chat.workspaceId));
    const trailing = !leads
      ? (done ? number : (number ?? workspace))
      : taskRow
        ? <div {...row} gap={6}>{running ? workspace : null}<icon name="layers" small tone="muted" /></div>
        : (running ? workspace : null);
    const rowNode = (
      <item opens id={`row-${chat.id}`} onSecondaryClick={(e: SecondaryClickEvent) => {
          clearTimeout(popoverTimers.open);
          ctx.run(sidebar.openRowMenu(chat.id, false, { x: e.x, y: e.y }));
        }} label={editing ? "" : title} selected={selected} onClickAction={{ chatId: opens.id, workspaceId: opens.workspaceId, route: "chat" }} lift {...(slides ? FLAT : {})} background={state.joining === chat.id ? "accent" : slides ? UNDER_SELECTION.background : undefined} layoutMotion drag={movable
              ? { type: taskRow ? "divergence/task" : "divergence/chat", data: taskRow ? { taskId: task!.id, chatId: chat.id } : { chatId: chat.id }, label: title, onEnd: () => ctx.run(sidebar.endDragging()) }
              : undefined} drop={dropTarget((zone) => ({ row: chat.id, zone }), chat.id, section)} sublabel={editing || compact ? undefined : liveLine(chat)} sublabelTone={LIVE_TONE[status]} stacked={!taskRow} actions={editing || done
              ? undefined
              : [
                  ...(taskRow && !onScreen
                    ? [{ icon: state.expanded.has(task!.id) ? "chevron-down" : "chevron-right", tooltip: state.expanded.has(task!.id) ? "Hide chats" : "Show chats", onClick: () => ctx.run(sidebar.toggleExpanded(task!.id)) }]
                    : []),
                  ...(!compact || (taskRow && !done)
                    ? [{ icon: pinned ? "pin-off" : "pin", tooltip: pinned ? "Unpin" : "Pin", onClick: () => ctx.run(sidebar.togglePin(chat)) }]
                    : []),
                  { icon: "pencil", tooltip: "Rename", onClick: rename },
                  { icon: "archive", tooltip: "Archive", onClick: () => ctx.run(taskRow ? sidebar.archiveTask(task!.id) : sidebar.archive(chat)) },
                ]} onClick={(event?: ClickEvent) => {
          closePopover();
          if (!event?.applied) ctx.run(sidebar.select(opens.id, opens.workspaceId));
        }} onPointerEnter={() => {
          if (!taskRow || !onScreen) ctx.run(sidebar.restOn(opens.id));
          if (pops) waitForPopover(task!.id);
        }} onPointerLeave={() => {
          ctx.run(sidebar.leaveRow(opens.id));
          if (pops) leavePopover();
        }}>
        <slot name="leading">
          {glyph(chat, status, leads ? number : null)}
          {state.rowMenu?.at ? null : menu}
          {popover}
        </slot>
        {editing ? renameField(editing) : trailing}
        {state.rowMenu?.at ? menu : null}
      </item>
    );
    return rowNode;
  }

  // A row's menu (document 8): its own entries with their icons, as in the + menu of the tabs,
  // then the plugins' after a line. The kernel's list opens where the row was right-clicked, from
  // a trigger with no height, which the list's corner sits on; opened by its command, under the
  // row's mark. Up, down, Right into Snooze's choices, Enter and Escape work in it.
  function rowMenu(chatId: string, child: boolean, entries: readonly MenuEntry[]): Element {
    const plugins = state.rowMenu?.entries ?? [];
    const at = state.rowMenu?.at;
    const list = (
      <combobox
        id="row-menu"
        value=""
        width={240}
        options={entries.map((e) => ({
          value: e.id,
          icon: e.icon,
          label: e.label,
          detail: e.key,
          ...(e.submenu ? { submenu: { value: "", width: 160, options: e.submenu } } : {}),
        }))}
        actions={plugins.map((e) => ({ label: e.title, onClick: () => ctx.run(sidebar.runRowEntry(e.id, chatId, child)) }))}
        onChange={(e: { value?: string; option?: string }) => {
          ctx.run(sidebar.closeRowMenu());
          if (e.option) entries.find((entry) => entry.id === e.option)?.run(e.value);
          else entries.find((entry) => entry.id === e.value)?.run();
        }}
      >
        <div width={1} height={at ? 0 : 1} />
      </combobox>
    );
    return at
      ? <slot name="menu"><div position="absolute" left={at.x} top={at.y}>{list}</div></slot>
      : <div position="absolute" left={0} bottom={0}>{list}</div>;
  }

  // The popover's wait, its fade on leaving, and its rows. The second's wait
  // starts when the pointer comes to rest on the row; leaving both the row
  // and the popover closes it after 220ms, and coming back keeps it.
  function waitForPopover(taskId: string) {
    clearTimeout(popoverTimers.close);
    if (state.popover === taskId) {
      // Back before the fade ended: it comes back from where the fade got to.
      if (state.popoverClosing) {
        state.popoverClosing = false;
        ctx.update();
      }
      return;
    }
    clearTimeout(popoverTimers.open);
    popoverTimers.open = setTimeout(() => {
      state.popover = taskId;
      ctx.update();
    }, 1000);
  }
  function leavePopover() {
    clearTimeout(popoverTimers.open);
    clearTimeout(popoverTimers.close);
    if (state.popover === null) return;
    state.popoverClosing = true;
    ctx.update();
    popoverTimers.close = setTimeout(closePopover, 220);
  }
  function closePopover() {
    clearTimeout(popoverTimers.open);
    clearTimeout(popoverTimers.close);
    if (state.popover === null) return;
    state.popover = null;
    state.popoverClosing = false;
    ctx.update();
  }
  function popoverContent(taskId: string): Element {
    const task = state.tasks[taskId];
    const chats = task ? taskChats(state, task) : [];
    const workspaces = new Set(chats.map((c) => c.workspaceId));
    return (
      <div id="task-popover" {...column} gap={2} padding={4} borderRadius="md" background="card/40" backdrop={{ blur: 6 }} {...RAISED} opacity={0} motion={{ to: { opacity: state.popoverClosing ? 0 : 1 }, duration: state.popoverClosing ? 220 : 150 }} onPointerEnter={() => waitForPopover(taskId)} onPointerLeave={leavePopover}>
        {chats.map((member) => {
          const status = chatStatus(state, member);
          return (
            <item opens id={`popover-chat-${member.id}`} label={chatTitleOf(state, member)} onClickAction={{ chatId: member.id, workspaceId: member.workspaceId, route: "chat" }} {...FLAT} drag={{ type: "divergence/chat", data: { chatId: member.id }, label: chatTitleOf(state, member), onEnd: () => {
                closePopover();
                ctx.run(sidebar.endDragging());
              } }} onClick={(event?: ClickEvent) => {
                closePopover();
                if (!event?.applied) ctx.run(sidebar.select(member.id, member.workspaceId));
              }}>
              <slot name="leading">{status === "running" ? <spinner activity /> : <icon name="circle" small tone={STATUS_TONE[status]} />}</slot>
              {workspaces.size > 1 ? workspaceMark(workspaceMarks.get(member.workspaceId)) : null}
            </item>
          );
        })}
      </div>
    );
  }

  // A task's chats under its row (document 1, Child rows): while the task is
  // on screen, and when the user listed them. Each opens the task on that chat.
  function childRows(chat: Chat, slides: boolean): Element[] {
    if (!isTaskRow(state, chat)) return [];
    const task = taskOf(state, chat.id)!;
    const onScreen = activeTask === task.id;
    if (!onScreen && !state.expanded.has(task.id)) return [];
    const chats = taskChats(state, task);
    const workspaces = new Set(taskChats(state, task).map((c) => c.workspaceId));
    return chats.map((member) => {
      const status = chatStatus(state, member);
      const editing = state.editing?.id === member.id ? state.editing : null;
      const menuOpen = state.rowMenu?.chatId === member.id && state.rowMenu.child;
      const separate = () => ctx.run(sidebar.placeChat(member.id, { kind: "alone" }));
      // Its status mark. A started chat's checks it off on its own: as
      // closing its tab does, the chat leaves the task for a row of its own
      // in Complete.
      const mark = status === "running" ? <spinner activity /> : <icon name="circle" small tone={STATUS_TONE[status]} />;
      const menu = menuOpen
        ? rowMenu(member.id, true, [
            { id: "row-menu-rename", icon: "pencil", label: "Rename", run: () => ctx.run(sidebar.startRename({ id: member.id, title: chatTitleOf(state, member) })) },
            { id: "row-menu-separate", icon: "ungroup", label: "Separate from Task", run: separate },
            { id: "row-menu-archive", icon: "archive", label: "Archive", run: () => ctx.run(sidebar.archive(member)) },
            { id: "row-menu-close", icon: "x", label: "Close", run: () => ctx.run(sidebar.closeChild(member.id)) },
          ])
        : null;
      return (
        <item opens id={`child-${member.id}`} onSecondaryClick={(e: SecondaryClickEvent) => ctx.run(sidebar.openRowMenu(member.id, true, { x: e.x, y: e.y }))} label={editing ? "" : chatTitleOf(state, member)} selected={sidebar.nativeApp?.bind?.("chatId", member.id) ?? member.id === app.chatId} onClickAction={{ chatId: member.id, workspaceId: member.workspaceId, route: "chat" }} lift {...(slides ? UNDER_SELECTION : {})} paddingLeft={17 + 8} layoutMotion drag={{ type: "divergence/chat", data: { chatId: member.id }, label: chatTitleOf(state, member), onEnd: () => ctx.run(sidebar.endDragging()) }} actions={editing
              ? undefined
              : [
                  { icon: "pencil", tooltip: "Rename", onClick: () => ctx.run(sidebar.startRename({ id: member.id, title: chatTitleOf(state, member) })) },
                  { icon: "archive", tooltip: "Archive", onClick: () => ctx.run(sidebar.archive(member)) },
                ]} onClick={(event?: ClickEvent) => {
          if (!event?.applied) ctx.run(sidebar.select(member.id, member.workspaceId));
        }} onPointerEnter={() => ctx.run(sidebar.restOn(member.id))} onPointerLeave={() => ctx.run(sidebar.leaveRow(member.id))}>
          <slot name="leading">
            {isDraft(state, member) || state.queued.has(member.id)
              ? <div {...column} alignItems="center" justifyContent="center" width={17} height={17} flexShrink={0}>{mark}</div>
              : checkable(`glyph-child-${member.id}`, mark, false, () => ctx.run(sidebar.closeChild(member.id)))}
            {state.rowMenu?.at ? null : menu}
          </slot>
          {editing ? renameField(editing) : workspaces.size > 1 ? workspaceMark(workspaceMarks.get(member.workspaceId)) : null}
          {state.rowMenu?.at ? menu : null}
        </item>
      );
    });
  }

  // The sections in the order the user left them, each a heading (with the
  // room between sections above it), then its chats and its "Show more".
  // Drafts and Complete show a page, then "Show more". One flat run of rows,
  // so the list draws only the ones on screen. With `docked`, the docked
  // sections (Running and Complete at first) are pinned at the foot of the
  // list (`dock`), each scrolling its rows in a box of its own (`dockRows`);
  // once one of them is shown whole they end the list instead. The last docked section's "Show more" or "Show less"
  // (`toggle`) leads the sidebar's last row, before Options; `continues` says
  // the toggle is that "Show more" or "Show less", which belongs to the rows
  // above it, rather than a folded heading that starts a section of its own. While a heading
  // is carried, a part with no section shows room to take it (`dockArea`
  // under the list).
  function renderRows(docked: boolean): { rows: Element[]; dock: Element[]; toggle: Element | null; continues: boolean; dockArea: Element | null; resizable: boolean } {
    let position = 0;
    const lastPosition = listedChats(state).length - 1;
    const rows: Element[] = [];
    let dock: Element[] = [];
    let toggle: Element | null = null;
    let tuckedHeading: Element | null = null;
    const parts: DockPart[] = [];
    const all = sections(state);
    // Once a docked section is shown whole, every docked section ends the list instead.
    const flows = docked && all.some((s) => s.docked && !state.collapsed[s.id] && state.movingSection?.id !== s.id && !!state.showAll[s.id] && s.chats.length > pageOf(s));
    const lastDocked = docked ? all.filter((section) => section.docked).at(-1) : undefined;
    // The dock's edge is the room above its first heading, which takes none of its own.
    const firstDocked = docked && !flows ? all.find((section) => section.docked) : undefined;
    // A folded section still shows the row of the chat on screen. A newer
    // host projects it from native app state, so switching chats redraws the
    // sidebar only when that row changes.
    const folds = focusedRows(state, all);
    const focused = (sidebar.nativeApp?.project
      ? sidebar.nativeApp.project({ key: "chatId", cases: folds, default: null })
      : app.chatId ? folds[app.chatId] ?? null : null) as string | null;
    all.forEach((section, index) => {
      const folded = !!state.collapsed[section.id];
      const carried = state.movingSection?.id === section.id;
      const shown = shownChats(state, section, focused);
      const more = folded || carried ? 0 : section.chats.length - shown.length;
      // The last docked section folded is its heading alone, which takes the
      // sidebar's last row, level with Options, instead of a row of its own (the
      // footer leaves the room above it). It is as wide as its label, count and
      // chevron, as "Show more" is there: stretched to Options, its count and
      // chevron stood on no column of the rows above.
      const tucked = section === lastDocked && folded && !shown.length;
      // In the dock the room above a heading is its own; in the list it is a row of its own, so a heading that comes to
      // have room above it (a section opened before it) glides with the rows instead of growing at once under them.
      const inDock = docked && section.docked && !flows;
      const spaced = !!index && !tucked && section !== firstDocked;
      const gap = spaced && !inDock ? [<div id={`gap-${section.id}`} height={SECTION_GAP} flexShrink={0} layoutMotion />] : [];
      // Folded into the sidebar's last row, the heading shows there at once rather than gliding from the dock across
      // the rows, and opened again it fades in in the dock.
      const heading = (
        <div {...column} id={`heading-${section.id}`} layoutMotion={!tucked} paddingTop={spaced && inDock ? SECTION_GAP : 0} drop={LIVE_DRAG ? dropTarget(() => ({ heading: section.id })) : undefined}>
            <item heading id={`section-${section.id}`} iconSvg={section.mark} busy={!section.mark} iconTone="foreground" label={section.label} tone="foreground" opacity={HEADING_OPACITY} onClick={() => ctx.run(sidebar.toggleSection(section.id))} drag={LIVE_DRAG ? { type: SECTION_TYPE, data: { sectionId: section.id }, label: section.label, onEnd: () => ctx.run(sidebar.endSectionDrag()) } : undefined} drop={LIVE_DRAG ? sectionTarget((zone) => ({ section: section.id, zone })) : undefined}>
                      {/* The count, which the pointer on the heading turns into the fold's chevron. At the
                          end of a heading as wide as the list both are centred in a box as wide as a row's
                          trailing mark, so the counts, those marks and Options stand on one centre line
                          however many digits a count has. In a heading as wide as its content (`tucked`)
                          the chevron's box reaches past its drawing, so both step back to end where the
                          count ends and to stand as far from the heading's mark as that mark stands from
                          the label. */}
                      <div {...row} position="relative" {...(tucked ? { marginLeft: LABEL_SLACK - MARK_INSET } : { width: TRAILING_MARK, justifyContent: "center" })}>
                                <div {...row} flexShrink={0} groupHover={{ group: "item", visibility: "hidden" }}><text style="body" size={10.72} weight={600} tone="foreground">{String(section.chats.length)}</text></div>
                                <div {...row} position="absolute" top={0} bottom={0} right={tucked ? -MARK_INSET : 0} visibility="hidden" groupHover={{ group: "item", visibility: "visible" }}><icon name="chevron-down" small tone="foreground" svg={folded || carried ? CHEVRON_RIGHT : CHEVRON_DOWN} /></div>
                              </div>
                    </item>
          </div>
      );
      // The row a folded section shows for the chat on screen takes no number:
      // Number keys keep to the rows listed whatever chat is open.
      const chats = shown.flatMap((chat) => {
        const index = folded && chat.id !== state.dragging?.id ? Infinity : position++;
        return [chatRow(chat, index === lastPosition && index >= 8 ? 8 : index < 8 ? index : Infinity, section.id, docked && !inDock), ...childRows(chat, docked && !inDock)];
      });
      const moreRow = more > 0
        ? (
          <item id={`more-${section.id}`} icon="chevron-down" label="Show more" layoutMotion onClick={() => {
              state.showAll[section.id] = true;
              ctx.update();
            }} />
        )
        : null;
      const lessRow = !folded && !carried && state.showAll[section.id] && section.chats.length > pageOf(section)
        ? (
          <item id={`less-${section.id}`} icon="chevron-up" label="Show less" layoutMotion onClick={() => {
              state.showAll[section.id] = false;
              ctx.update();
            }} />
        )
        : null;
      if (tucked) {
        toggle = heading;
        tuckedHeading = heading;
        return;
      }
      const tail = moreRow ?? lessRow;
      if (section === lastDocked) toggle = tail;
      if (docked && section.docked) {
        parts.push({ id: section.id, gap, heading, chats, tail: tail && section !== lastDocked ? tail : null, boxed: !flows && !folded && !carried && chats.length > 0 });
        return;
      }
      rows.push(...gap, heading, ...chats, ...(tail ? [tail] : []));
    });
    if (flows) rows.push(...parts.flatMap((part) => [...part.gap, part.heading, ...part.chats, ...(part.tail ? [part.tail] : [])]));
    else dock = dockRows(parts);
    const placing = docked && !!state.movingSection;
    if (placing && !all.some((section) => !section.docked)) rows.unshift(emptyArea("list"));
    const dockArea = placing && !all.some((section) => section.docked) ? emptyArea("dock") : null;
    if (!all.length) {
      rows.push(
        (
          <div {...column} gap="small" padding="medium">
            <text style="body" size="xs" tone="muted">No chats yet</text>
          </div>
        ),
      );
    }
    return { rows, dock, toggle, continues: !!toggle && toggle !== tuckedHeading, dockArea, resizable: parts.some((part) => part.boxed && !flows) };
  }

  // The docked sections, each its heading and then its rows in a box of their
  // own that scrolls past five rows, or past its share of the height the user
  // dragged the dock to. A folded section's row of the chat on screen stands
  // under its heading without a box.
  function dockRows(parts: readonly DockPart[]): Element[] {
    const boxed = parts.filter((part) => part.boxed);
    const heights = dockLayout(state.dockHeight, boxed.map((part) => ({ id: part.id, rows: part.chats.length })));
    return parts.flatMap((part) => [part.heading, ...(part.boxed ? [dockBox(part, heights[part.id]!)] : part.chats), ...(part.tail ? [part.tail] : [])]);
  }

  function dockBox(part: DockPart, height: number): Element {
    return (
      <div {...column} id={`dock-rows-${part.id}`} overflowY="scroll" maxHeight={height}>
        <div {...column} position="relative" flexShrink={0}>
          {measure(`rows:${part.id}`, ctx.update)}
          <div {...column} position="relative" flexShrink={0}>
            {measure(`page:${part.id}`, ctx.update)}
            {part.chats.slice(0, DOCK_ROWS)}
          </div>
          {part.chats.slice(DOCK_ROWS)}
        </div>
      </div>
    );
  }

  // The room over which the dock's blur grows, and at its foot, right above
  // the first docked heading, the dock's edge: pressed, it follows the pointer
  // over the whole sidebar (`resizeLayer`), and the docked rows take the
  // height it is dragged to. Like the panes' handles it shows only the kit's
  // pill, while the pointer is on it or drags it.
  function dockEdge(resizable: boolean): Element {
    const dragging = !!state.resizingDock;
    return (
      <div id="dock-lead" height={DOCK_LEAD} backdrop={LEAD_BACKDROP} {...column} justifyContent="flex-end">
        {resizable
          ? (
            <div id="dock-edge" {...row} height={EDGE_HEIGHT} justifyContent="center" group="dock-edge" cursor="ns-resize" onPress={() => {
                state.resizingDock = { from: dockSpan.shown, anchor: null };
                ctx.update();
              }}>
              <div width={dragging ? 44 : 20} height={3} borderRadius="full" background="mutedForeground" opacity={dragging ? 0.9 : 0.35} visibility={dragging ? "visible" : "hidden"} groupHover={{ group: "dock-edge", visibility: "visible" }} />
            </div>
          )
          : null}
      </div>
    );
  }

  // While the dock's edge is dragged, a layer over the sidebar hears the
  // pointer wherever it goes on it. Its first move marks where the drag
  // starts; a move with no button held (it was let go off the sidebar) ends it.
  function resizeLayer(): Element | null {
    const drag = state.resizingDock;
    if (!drag) return null;
    return (
      <div id="dock-resize" position="absolute" top={0} right={0} bottom={0} left={0} cursor="ns-resize" onPointerMove={(e: PointerMoveEvent) => {
          if (e.button === null) return ctx.run(sidebar.endDockResize());
          if (drag.anchor === null) drag.anchor = e.y;
          state.dockHeight = Math.min(Math.max(drag.from + drag.anchor - e.y, dockSpan.min), dockSpan.max);
          ctx.update();
        }} onPointerUp={() => ctx.run(sidebar.endDockResize())} />
    );
  }

  // Remove takes the workspace and every chat in it, archived ones too, so
  // the first click only says so and the second removes it.
  function removeRow(workspace: Workspace) {
    const armed = state.removing === workspace.id;
    return (
      <item id="remove-workspace" icon="folder-x" label={armed ? `Click again to remove ${workspace.name}${goesWith(sidebar, workspace)}` : `Remove ${workspace.name}`} onClick={() => ctx.run(armed ? sidebar.removeWorkspace(workspace) : sidebar.armRemove(workspace.id))} onPointerLeave={() => ctx.run(sidebar.armRemove(null))} />
    );
  }

  // --- chips and top actions ---------------------------------------------------

  // Options at the end of the sidebar's last row, drawn as the profile
  // picture another plugin publishes, else a stand-in: a press opens the rows
  // other plugins publish for its menu (the account, the Marketplace) and
  // Settings. Under the pointer a picture takes the wash over it.
  function renderOptions() {
    const set = (open: boolean) => {
      state.options = open ? (app.route ?? "chat") : null;
      ctx.update();
    };
    const picture = app.shared?.[PICTURE_KEY];
    const mark = typeof picture === "number"
      ? [<div {...layer}><view view={picture} fit /></div>, <div {...layer} borderRadius="full" groupHover={{ group: "options", ...OPTIONS_HOVER }} />]
      : [<div {...layer} groupHover={{ group: "options", visibility: "hidden" }}><icon name="user-round" small tone="muted" /></div>, <div {...layer} visibility="hidden" groupHover={{ group: "options", visibility: "visible" }}><icon name="user-round" small tone="foreground" /></div>];
    return (
      <popover id="sidebar-options" open={state.options !== null} align="end" width={240} onToggle={(e: { open: boolean }) => set(e.open)} onDismiss={() => set(false)}>
        <div id="sidebar-options-button" role="button" label="Options" tooltip="Options" group="options" position="relative" width={BUTTON_SIZE} height={BUTTON_SIZE} flexShrink={0} borderRadius="full" background="muted" hover={OPTIONS_HOVER} onClick={POPOVER_TOGGLE ? undefined : () => set(state.options === null)}>
          {mark}
        </div>
        {/* A dropdown list's look: its inset, its rows (`list`) and their spacing. */}
        <div id="sidebar-options-menu" {...column} gap="0.125rem" padding="small" background="card/40" backdrop={{ blur: 6 }} borderRadius="md" {...RAISED}>
          {sidebarItems(app.shared, MENU_PREFIX).map((view) => <view view={view} fit />)}
          <list id="sidebar-settings-list" items={[{ id: "sidebar-settings", icon: "settings", label: "Settings", onClick: () => ctx.run(sidebar.route("settings")) }]} />
        </div>
      </popover>
    );
  }

  // The whole sidebar, not just its list: a drop between rows lands the chat
  // in its place, a drop above or below the list (the search field, New chat,
  // the footer) lands it as a drop in the list does, so a tab carried left out
  // of the title strip lands as soon as it is over the sidebar. A pointer that
  // leaves the sidebar takes the chat back where it was.
  const listTarget = LIVE_DRAG
    ? {
        types: ["divergence/chat", "divergence/task", SECTION_TYPE],
        // A chat of a task of several, a tab carried from the title strip
        // among them, has no row to move until it lands. Leaving the list
        // ends the list's part of the drag: a drag that started in a pane
        // never tells the sidebar it ended.
        onOver: (e: DragOverEvent) => {
          if (e.type === SECTION_TYPE) return ctx.run(sidebar.moveSection(carriedSection(e), { inside: e.zone !== null }));
          if (e.zone === null) return ctx.run(sidebar.endDragging());
          if (movesRow(e)) ctx.run(sidebar.dragChat(carriedChat(e), { inside: true }));
        },
        onDrop: (e: DropEvent) => {
          if (!("data" in e)) return;
          if (e.type === SECTION_TYPE) return ctx.run(sidebar.landSection(carriedSection(e)));
          const carried = carriedChat(e);
          if (!movesRow(e)) return ctx.run(sidebar.placeChat(carried, { kind: "alone" }));
          ctx.run(sidebar.dropChat(carried));
        },
      }
    : undefined;
  // The dock floating over the list's foot: while the pointer is on it, the
  // rows of the list it covers are not heard. A drop on it outside its rows
  // lands as one on the list does.
  const dockTarget = listTarget && {
    types: ["divergence/chat", "divergence/task"],
    onOver: (e: DragOverEvent) => {
      if (movesRow(e)) ctx.run(sidebar.dragOverDock(carriedChat(e), e.zone !== null));
    },
    onDrop: listTarget.onDrop,
  };

  // A list that draws only the rows on screen pins the docked sections at its foot; a
  // kernel without one keeps every section in the flow.
  const { rows, dock, toggle, continues, dockArea, resizable } = renderRows(!!LIST);
  const revealCases = Object.fromEntries(rows.flatMap((row) => {
    const id = "id" in row ? row.id : undefined;
    return typeof id === "string" && (id.startsWith("row-") || id.startsWith("child-"))
      ? [[id.slice(id.startsWith("child-") ? 6 : 4), id]] : [];
  }));
  const reveal = sidebar.nativeApp?.project && sidebar.nativeApp.bind
    ? sidebar.nativeApp.bind({ key: "chatId", cases: revealCases, default: null })
    : app.chatId ? revealCases[app.chatId] : undefined;
  // The row the selection's fill is under; an id no row has while the open chat has no row in the list.
  const selection = sidebar.nativeApp?.project && sidebar.nativeApp.bind
    ? sidebar.nativeApp.bind({ key: "chatId", cases: revealCases, default: "" })
    : (app.chatId && revealCases[app.chatId]) || "";

  const [onlyId] = state.filter;
  const filtered = state.filter.length === 1 ? (state.workspaces.find((w) => w.id === onlyId) ?? null) : null;
  return (
    <div id="sidebar" {...column} {...fill} {...full} position="relative" padding="small" paddingX="small" paddingTop={0} drop={listTarget} onModifiersChanged={({ modifiers }: { modifiers: Modifiers }) => {
            // A kernel from before `secondary` reports only `meta`, the Mac's Command key.
            const held = modifiers.secondary ?? modifiers.meta;
            if (!!ctx.state.cmd === held) return;
            ctx.state.cmd = held;
            ctx.update();
            if (held) ctx.run(sidebar.readAhead());
          }}>
      <canvas position="absolute" left={0} top={0} width="100%" height={1} commands={[]} onResize={(e: { width: number }) => (listWidth = e.width)} />
      {inTitle(app) ? null : <div {...column} padding="small" paddingY="small" paddingTop={0}>{topControls(ctx, sidebar, false)}</div>}
      {LIST
                  ? (
                    <div {...column} {...fill} paddingX="small" position="relative">
                      {measure("list", ctx.update)}
                      <scroller id="chat-list" {...LIST} reveal={reveal}>
                          {/* The open chat's fill, one box under the rows that slides to the row chosen. */}
                          <div id="chat-selection" follows={selection} width="100%" height="100%" background="accent" borderRadius="sm" {...RAISED} layoutMotion />
                          {rows}
                          {dock.length
                                        ? (
                                          // The list's rows pass under the pinned rows, which blur them
                                          // away with no fill of their own: over the bare ground the
                                          // blur changes nothing, so no box shows at rest. Above the
                                          // pinned rows the blur grows row by row from nothing, so the
                                          // rows going under them soften on their way instead of
                                          // meeting a hard edge, as the chat does under the prompt box.
                                          <slot name="footer">
                                            <div {...column} drop={dockTarget}>
                                              {dockEdge(resizable)}
                                              <div {...column} position="relative" backdrop={DOCK_BACKDROP}>{measure("dock", ctx.update)}{dock}</div>
                                            </div>
                                          </slot>
                                        )
                                        : null}
                        </scroller>
                      {dockArea}
                    </div>
                  )
                  : <div {...column} {...fill} paddingX="small" paddingY="medium" overflowY="scroll">{rows}</div>}
      {/* Below the last row there is as much room as to the left of what leads it: under Complete's label (which
          ends 5px above the row's foot, half of the 4px the 22px row has over the 18px heading plus the heading's
          3px padding) when the row has one, and under Options when Options is alone, which has as much room below
          it as to its right. Above, Complete's folded heading keeps the room every section's heading has above it,
          so the folded headings at the sidebar's foot stand evenly apart; "Show more" and "Show less" follow the
          rows they belong to as a row follows a row, with no room between; and Options alone keeps as much room as
          it has to its right.
          footer-geometry.test.ts holds these margins. */}
      <div {...column} padding="small" paddingTop={continues ? 0 : toggle ? SECTION_GAP : `density.rowPaddingX + ${8 - OPTIONS_OVERHANG}`} paddingBottom={toggle ? "density.rowPaddingX + type.baseSize * 0.25 - 5" : `density.rowPaddingX + ${4 - OPTIONS_OVERHANG}`}>
          {filtered ? removeRow(filtered) : null}
          {sidebarItems(app.shared).map((view) => <view view={view} fit />)}
          {/* Options stands on the centre line of the rows' trailing marks and the headings' counts, so being
              wider than they are it reaches past the line where they end by half the difference;
              footer-geometry.test.ts holds this. */}
          <div {...row} gap={4} paddingRight={`density.rowPaddingX - ${OPTIONS_OVERHANG}`}>
            <div {...column} {...fill} alignItems="flex-start">{toggle}</div>
            {sidebarItems(app.shared, BUTTON_PREFIX).map((view) => <div width={BUTTON_SIZE} height={BUTTON_SIZE} flexShrink={0}><view view={view} fit /></div>)}
            {renderOptions()}
          </div>
        </div>
      {resizeLayer()}
    </div>
  );
}

// --- the top controls ---------------------------------------------------------

// New chat, the workspace picker and the search button share one row. It sits in
// the title strip after the sidebar toggle while the room the sidebar leaves
// there holds the three as title controls, and at the top of the sidebar
// otherwise. The kernel measures that room every frame, zero wide while the
// sidebar is hidden or peeked; an older kernel does not, so the row stays in
// the sidebar there.
const MEASURES_LEAD = !!kit.TITLE_LEAD_ROOM;
const TITLE_CONTROL = 30;
const TITLE_GAP = 4;
const LEAD_HOLDS = 3 * TITLE_CONTROL + 2 * TITLE_GAP;
const top = { room: 0 };
const inTitle = (app: { route?: string | null }) => MEASURES_LEAD && top.room >= LEAD_HOLDS && app.route !== "settings";

// The search button opens the chat search (Cmd+P), which the palette plugin draws.
function topControls(ctx: EffectViewContext<{ cmd?: boolean }>, sidebar: Sidebar["Service"], title: boolean): Element {
  const newChat = () => ctx.run(sidebar.runCommand("sidebar.newChat"));
  const searchKey = sidebar.state.keys["palette.chats"];
  return (
    <div {...row} {...fill} gap={TITLE_GAP}>
      {title
        ? <button id="new-chat" icon="plus-large" variant="ghost" muted tooltip="New chat" onClick={newChat} />
        : (
          // A row like the chats under it, with the N key cap while the shortcut key is held.
          <div {...row} {...fill}><item opens id="new-chat" icon="plus-large" label="New chat" onClick={newChat}>{ctx.state.cmd ? <text keys>N</text> : null}</item></div>
        )}
      {workspacePicker(ctx, sidebar, title ? TITLE_CONTROL : 28)}
      <button id="chat-search-open" icon="search" variant="ghost" muted tooltip={searchKey ? `Search chats (${searchKey})` : "Search chats"} onClick={() => ctx.run(sidebar.runCommand("palette.chats"))} />
    </div>
  );
}

// Which workspaces the list shows, as a square with the folders mark while it
// shows them all and the first chosen workspace's mark otherwise; its tooltip
// names the choice.
// The chats that go when a workspace is removed, as the end of the sentence that asks first.
function goesWith(sidebar: Sidebar["Service"], workspace: Workspace): string {
  const count = sidebar.state.chats.filter((chat) => chat.workspaceId === workspace.id).length;
  return count === 0 ? "" : count === 1 ? " and its chat" : ` and its ${count} chats`;
}

// A workspace's remove button in a list of workspaces: one press removes an empty workspace, and one with chats asks
// first, since they go with it.
function removeButton(sidebar: Sidebar["Service"], workspace: Workspace) {
  const chats = goesWith(sidebar, workspace);
  return { tooltip: "Remove workspace", confirm: chats ? `Click again to remove it${chats}` : undefined };
}

function workspacePicker(ctx: EffectViewContext<{ cmd?: boolean }>, sidebar: Sidebar["Service"], size: number): Element {
  const { state } = sidebar;
  const chosen = state.workspaces.filter((w: Workspace) => state.filter.includes(w.id));
  const mark = chosen.length ? workspaceMarkOf(chosen[0]) : { icon: "folders" };
  return (
    <combobox id="workspace-filter" look="toolbar" multiple width={320} values={state.filter} all="All workspaces" search={state.workspaces.length > 6 ? "Search workspaces…" : undefined} options={state.workspaces.map((w: Workspace) => ({
          value: w.id,
          label: w.name,
          description: w.path,
          ...workspaceMarkOf(w),
          remove: removeButton(sidebar, w),
          submenu: state.colors.length ? { context: true, ...workspaceLooks(w, state.colors) } : undefined,
        }))} actions={[{ label: "Add workspace folder…", icon: "folder-plus", onClick: () => ctx.run(sidebar.addWorkspace()) }]} onRemove={(e: { value: string }) => {
          const workspace = state.workspaces.find((w: Workspace) => w.id === e.value);
          if (workspace) ctx.run(sidebar.removeWorkspace(workspace));
        }} onChange={(e: { values?: readonly string[]; value?: string; option?: string }) =>
          // A choice in a workspace's right-click menu is its look; any
          // other change is which workspaces show.
          e.option
            ? ctx.run(sidebar.setColor(e.option, e.value === "icon" ? null : (e.value as PresetColor)))
            : ctx.run(sidebar.setFilter([...(e.values ?? [])]))}>
      <div {...row} justifyContent="center" width={size} height={size} flexShrink={0} borderRadius="field" hover={HOVER} tooltip={chosen.length ? chosen.map((w: Workspace) => w.name).join(", ") : "All workspaces"}>
        {mark.image ? <image path={mark.image} width={16} height={16} radius={3} /> : <icon name={mark.icon ?? "folder"} color={mark.color} small tone="muted" />}
      </div>
    </combobox>
  );
}

/** The sidebar's view in the title strip: the box after the sidebar toggle, which measures its room and holds the top
 * controls while they fit there. */
export function renderTitleLead(ctx: EffectViewContext<{ cmd?: boolean }>, sidebar: Sidebar["Service"]): Element | null {
  if (!MEASURES_LEAD) return null;
  const measure = (e: { width: number }) => {
    const before = inTitle(ctx.app);
    top.room = e.width;
    if (inTitle(ctx.app) === before) return;
    for (const view of sidebar.views) view.update();
  };
  return (
    <region over="center">
      {/* The aligned box takes no room and starts where its place in the flow does: this place is the strip's top,
          and gives the view the strip's height, without which it is not drawn. */}
      <div {...column} width={0} height={35} alignItems="flex-start" justifyContent="flex-start">
        <div {...row} alignTo="title-lead" width="100%" height={35} overflow="hidden" position="relative">
          <canvas position="absolute" left={0} top={0} width="100%" height={1} commands={[]} onResize={measure} />
          {inTitle(ctx.app) ? topControls(ctx, sidebar, true) : null}
        </div>
      </div>
    </region>
  );
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.7latestNov 21, 2026>=5 <6100.9 KB4 permissionsListed
0.2.6Nov 16, 2026>=5 <6100.6 KB4 permissionsListed
0.2.5Nov 11, 2026>=5 <665.1 KB4 permissionsListed
0.2.4Nov 9, 2026>=5 <660.4 KB4 permissionsListed
0.2.3Oct 27, 2026>=2 <426.1 KB3 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.