Official

chat

Built-in chat 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/chat@0.2.6

Permissions in 0.2.6

  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Send prompts, answer agent questions, and create, change, fork, revert, stop and group chats
  • Run other plugins' commands commands.runHighRuns commands of other plugins.Run the sidebar's New chat command from the title bar
  • Read chats chats.readMediumReads your transcripts and chat lists.Show workspaces, tasks, chats and transcripts, and follow them as agents work
  • Read files fs.readMediumReads files in the listed places.Suggest workspace files for @ mentionsPlaces: the open workspace
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw the chat grid, the title bar, and the Session panel with its rail buttonSlots: centertitlerailright

Files

views/layout.tsx39.5 KB
// The task on screen as panes and tab strips (specs/tasks-and-splits/02-tabs-and-splits.md):
// the panes in the `center` slot, each its own raised surface on the
// ground; the strips of the panes along the top in the title strip, over
// their panes; the strip of a lower pane in a band of ground above it.
import * as kit from "divergence";
import type { DragOverEvent, DropEvent, DropZone, Element, PointerUpEvent } from "divergence";
import type { Layout, Pane, PlaceTarget, SideSplit, Tab, Task } from "divergence/protocol";
import type { ChatView } from "../controller.ts";
import { registeredPane } from "../state.ts";
import {
  MIN_PANE_HEIGHT,
  MIN_PANE_WIDTH,
  PANE_GAP,
  canSplit,
  canCloseTabs,
  chatCount,
  chatOf,
  closeTab,
  focusPane,
  placeTab,
  resizeSplit,
  sameTab,
  showTab,
  splitPane,
  topPanes,
  toggleSideSplit,
  taskOnScreen,
  reportLayoutKeys,
  openTabMenu,
  closeOtherTabs,
  separable,
  separateTab,
  moveAcross,
  panesOf,
  resizeSide,
  sideOnScreen,
  sideHasTabs,
} from "../layout.ts";
import type { PresentationLayout } from "../layout.ts";
import { ensurePane } from "../panes.ts";
import { findTask, isLive } from "../subagents.ts";
import { column, row, fill, full, HOVER, clickable, revealOnHover, markIcon, markOf, leadAnchor } from "./styles.tsx";
import { workspacePicker } from "./composer.tsx";
import { openInControl, renameField } from "./title.tsx";
import { hint } from "../shortcuts.ts";
import { openNewTab } from "../newtab.tsx";
import { SKELETON_AFTER, centerSkeleton } from "./panes.tsx";

const RAISED = kit.RAISED ?? { elevation: "raised" };
const FLAT = kit.FLAT ?? { elevation: "none" };

/** The title strip's height, which the strips of the panes along the top take: its buttons
 * stand on its foot, where the panes start. */
const TITLE_HEIGHT = 35;
/** A lower pane's band of ground, which holds its strip (document 2, Where the tab strips sit):
 * as tall as the title strip, so every strip is the same. */
const BAND = TITLE_HEIGHT;
/** The strip's buttons are the title strip's own size (the reload button's, 2rem), in line with
 * it: they start this far down a strip. */
const BUTTON = 30;
const STRIP_TOP = TITLE_HEIGHT - BUTTON;
/** Tabs are 200px wide (DESIGN.md, Tabs). */
const TAB_MAX = 200;
// A tab is the strip's buttons' box, its mark, title and close mark on their centre line with
// as much room above as below. What is drawn sits 8px from both ends and 8px from the next part.
// The mark's 18px box holds an agent's 16px icon with a pixel to spare each side (a spinner keeps
// to its box's start, its glyph in by a pixel and a half), so the box starts 7px in and the parts
// after it are 7px apart. The close mark's 16px box draws its X 3.5px in, so the box ends 4.5px
// in and is pulled 2.5px towards the title; a title with no close mark ends 8px in.
const TAB_SPACE = 8;
const TAB_HEIGHT = BUTTON;
const TAB_MARK = 18;
const TAB_CLOSE = 16;
const MARK_ROOM = (TAB_MARK - 16) / 2;
const CLOSE_ROOM = 3.5;
const TAB_INSET = TAB_SPACE - MARK_ROOM;
const TAB_GAP = TAB_SPACE - MARK_ROOM;
const TAB_END = TAB_SPACE;
const TAB_CLOSE_END = TAB_SPACE - CLOSE_ROOM;
const TAB_CLOSE_PULL = TAB_SPACE - CLOSE_ROOM - TAB_GAP;
// How far the selected tab reaches down over its pane's top edge, which it hides where the two
// meet; the radius of the reverse curves its sides flare out in to meet the pane; and how far in
// from the pane's side the tabs' row starts, clear of the pane's round corner (17.25px), with
// room for a curve before the first tab.
const TAB_JOIN = 1;
const FLARE = 8;
const STRIP_INSET = 18;

/** Each pane's size as the kernel last laid it out, which the split buttons check. */
const sizes = new Map<string, { width: number; height: number }>();

// --- dropping chats and tabs (document 4) -----------------------------------------

/** What a pane takes (document 4): a chat from a strip or the sidebar, or an item, open in a
 * strip or a plugin's (a file from the Files tree). A whole task row (`divergence/task`) never
 * joins another, so panes do not list it. */
const DROPS = ["divergence/chat", "divergence/item"];
/** The pane a drag is over and the zone in it, which draws the preview. */
let over: { paneId: string; zone: DropZone } | null = null;

/** What a carried tab is dragged as: a chat as `divergence/chat`, an item as
 * `divergence/item` with its kind and key (and its id, since it is open). */
export function tabDrag(tab: Tab, label: string, onEnd?: () => void) {
  return tab.kind === "chat"
    ? { type: "divergence/chat", data: { chatId: tab.chatId }, label, onEnd }
    : { type: "divergence/item", data: { kind: tab.itemKind, key: tab.key, chatId: tab.chatId ?? null, itemId: tab.id }, label, onEnd };
}

/** Where a carried tab would land in a strip: the gap opens there and the tabs around it glide
 * aside; null closes it. */
function carryOver(v: ChatView, what: Tab | null, gap: { paneId: string; index: number } | null) {
  const c = v.controller;
  const before = c.state.layouts.carried;
  if (!what) {
    if (!before?.gap) return;
    c.state.layouts.carried = { tab: before.tab, gap: null };
  } else {
    if (before && sameTab(before.tab, what) && before.gap?.paneId === gap?.paneId && before.gap?.index === gap?.index) return;
    c.state.layouts.carried = { tab: what, gap };
  }
  c.titleView?.update();
  c.center?.update();
}

/** The drag is over: the gap closes and the carried tab's place comes back. */
function carryEnd(v: ChatView) {
  if (!v.controller.state.layouts.carried) return;
  v.controller.state.layouts.carried = null;
  v.controller.titleView?.update();
  v.controller.center?.update();
}

/** A dropped item no tab shows yet: its owner opens it where it lands. */
type NewItem = { kind: string; key: string; chatId: string | null };

/** Whether a dropped value is a tab already open somewhere, rather than an item to open. */
const isTab = (what: Tab | NewItem): what is Tab => what.kind === "chat" || what.kind === "item";

/** Whether a dropped value is one of this pane's tabs. */
const inPane = (pane: Pane, what: Tab | NewItem | null) => !!what && isTab(what) && pane.tabs.some((t) => sameTab(t, what));

/** The tab a dropped value stands for, or the item to open. */
function dropped(e: { type: string; data: unknown }): Tab | NewItem | null {
  const data = (e.data ?? {}) as { chatId?: string; itemId?: string; kind?: string; key?: string };
  if (e.type === "divergence/chat" && data.chatId) return { kind: "chat", chatId: data.chatId };
  if (e.type !== "divergence/item" || !data.kind || data.key === undefined) return null;
  return data.itemId ? ({ kind: "item", id: data.itemId } as Tab) : { kind: data.kind, key: data.key, chatId: data.chatId ?? null };
}

/** Lands a drop: a tab moves, a new item opens through its owner. */
function land(v: ChatView, what: Tab | NewItem, target: PlaceTarget) {
  if (isTab(what)) return v.ctx.run(placeTab(v.controller, what, target));
  const item = what;
  const onScreen = taskOnScreen(v.controller)?.id ?? null;
  v.ctx.run(v.controller.host.call("host/layouts.drop_item", { item, target, onScreen }));
}

/** A pane as a drop target: an edge puts the tab in a new pane on that side, the middle in its
 * strip. An edge a split has no room for takes nothing, nor does the middle of the pane a tab is
 * already in, or an edge of the pane it is the only tab of: neither would move it. */
export function paneDrop(v: ChatView, task: Task, pane: Pane) {
  const fits = (zone: DropZone, what: Tab | NewItem | null) => {
    const own = inPane(pane, what);
    if (zone === "center" || zone === "into") return !own;
    if (own && pane.tabs.length === 1) return false;
    return canSplit(task, zone === "left" || zone === "right" ? "right" : "down", sizes.get(pane.id));
  };
  return {
    types: DROPS,
    zones: "edges" as const,
    onOver: (e: DragOverEvent) => {
      const next = e.zone && fits(e.zone, dropped(e)) ? { paneId: pane.id, zone: e.zone } : null;
      if (next?.zone === over?.zone && next?.paneId === over?.paneId) return;
      if (!next && over?.paneId !== pane.id) return;
      over = next;
      v.controller.center?.update();
    },
    onDrop: (e: DropEvent) => {
      over = null;
      v.controller.center?.update();
      const what = "data" in e ? dropped(e) : null;
      if (!what || !fits(e.zone, what)) return;
      const target: PlaceTarget =
        e.zone === "center" || e.zone === "into"
          ? { kind: "strip", paneId: pane.id, index: pane.tabs.length }
          : { kind: "edge", paneId: pane.id, edge: e.zone as "left" | "right" | "top" | "bottom" };
      land(v, what, target);
    },
  };
}

/** The half a new pane would take, or the whole pane for its strip, while a drag is over it. */
export function dropPreview(paneId: string): Element | null {
  if (over?.paneId !== paneId) return null;
  const half = { left: { left: 0, width: "50%" }, right: { left: "50%", width: "50%" }, top: { top: 0, height: "50%" }, bottom: { top: "50%", height: "50%" } } as const;
  const place = over.zone in half ? half[over.zone as keyof typeof half] : {};
  // It fades in, and glides to another half as the pointer moves between edges.
  return (
    <div
      id={`drop-preview-${paneId}`}
      position="absolute"
      left={0}
      top={0}
      width="100%"
      height="100%"
      {...place}
      background="accent/20"
      borderRadius="lg"
      layoutMotion
      opacity={0}
      motion={{ to: { opacity: 1 }, duration: 120 }}
    />
  );
}

// --- the center ------------------------------------------------------------------

/** The task's panes: a split of them, or its one pane, and the side split beside them while it
 * is open and holds something that belongs on screen (document 3). */
export function renderTaskCenter(v: ChatView, task: Task, chatId?: string, presentation?: string, layout?: PresentationLayout): Element {
  task = chatId ? taskShowing(task, chatId) : task;
  const found = layout ? layout.side : sideOnScreen(v.controller.state.layouts, task, v.controller.state.chats);
  const side = found && chatId ? { ...found, task: taskShowing(found.task, chatId) } : found;
  const focused = focusedOnScreen(v, task, side);
  const panes = layoutNode(v, task, task.layout.root, true, presentation, 0, focused);
  const key = presentation ?? "";
  const share = side ? sideShare(side.split, task, side.task, roomOf(key)) : 0;
  // The window split stays while the side split is hidden, so showing it slides it in.
  const split = side ? (
    <split
      id="window-split"
      direction="horizontal"
      sizes={[1 - share, share]}
      minSizes={[columnsOf(task.layout.root) * MIN_COLUMN, SIDE_MIN]}
      gap={PANE_GAP}
      onResize={(e: { sizes: readonly number[] }) => v.ctx.run(resizeSide(v.controller, (e.sizes[1] ?? share) * roomOf(key)))}
    >
      {panes}
      {layoutNode(v, side.task, side.task.layout.root, true, presentation, 0, focused)}
    </split>
  ) : (
    <split id="window-split" direction="horizontal" sizes={[1]}>{panes}</split>
  );
  const edge = !side && (layout ? layout.hasSideTabs : sideHasTabs(v.controller.state.layouts, task, v.controller.state.chats));
  // The room is measured around the whole window split, whose width neither a drag of its edge nor showing or hiding
  // the side split changes.
  return (
    <split id="window" direction="horizontal" sizes={[1]}>
      <div {...column} {...fill} {...full} position="relative">
        <canvas position="absolute" left={0} top={0} width="100%" height="100%" commands={[]} onResize={(e: { width: number }) => noteRoom(v, key, e.width, !!side?.split.resized)} />
        {split}
        {edge ? sideEdge(v) : null}
      </div>
    </split>
  );
}

/** The pane that has the focus while more than one is on screen, the task's or the side split's,
 * drawn with a brighter edge; null with a single pane. */
function focusedOnScreen(v: ChatView, task: Task, side: { task: Task } | null): string | null {
  const count = panesOf(task.layout.root).length + (side ? panesOf(side.task.layout.root).length : 0);
  if (count < 2) return null;
  return side && v.controller.state.layouts.sideFocused ? side.task.layout.focused : task.layout.focused;
}

/** A presentation of this task with `chatId` selected in its own pane. */
function taskShowing(task: Task, chatId: string): Task {
  let focused: string | null = null;
  const visit = (layout: Layout): Layout => {
    if (layout.kind === "split") return { ...layout, children: layout.children.map((child) => ({ ...child, layout: visit(child.layout) })) };
    const active = layout.tabs.find((tab) => tab.kind === "chat" && tab.chatId === chatId);
    if (!active) return layout;
    focused = layout.id;
    return { ...layout, active };
  };
  const root = visit(task.layout.root);
  return focused ? { ...task, layout: { root, focused } } : task;
}

// --- the side split (document 3) -----------------------------------------------

/** The window split's width, the room the side split's share is of, as last measured in each retained presentation
 * ("" for the center drawn as it goes), and the newest measured in any: a presentation not measured yet is as wide as
 * the others in the same slot. */
const rooms = new Map<string, number>();
let newestRoom = 0;
const roomOf = (key: string) => rooms.get(key) ?? newestRoom;

/** A presentation's room as measured. A side split that keeps a width is drawn again at once over a new room, so it
 * keeps its pixels rather than the share the old room gave. */
function noteRoom(v: ChatView, key: string, width: number, keepsWidth: boolean) {
  const before = roomOf(key);
  rooms.set(key, width);
  newestRoom = width;
  if (keepsWidth && width !== before) v.ctx.update();
}

/** How many columns a layout lays side by side: a row's children's together, a column's widest. */
const columnsOf = (layout: Layout): number =>
  layout.kind === "pane"
    ? 1
    : layout.direction === "row"
      ? layout.children.reduce((sum, child) => sum + columnsOf(child.layout), 0)
      : Math.max(...layout.children.map((child) => columnsOf(child.layout)));
/** The least room a column of the task's keeps beside a side split the user widened. */
const MIN_COLUMN = 200;
/** The side split's least width. */
const SIDE_MIN = 240;
/** The side split's fraction of the room. Until the user drags its edge it takes its share of the columns, so its panes
 * and the task's are equally wide; after, the width the host keeps, within the same bounds a drag of its edge has (the
 * split's least sizes), so the width a drag leaves is the width it keeps. Before anything measured the room, it takes
 * its share of the columns too. */
function sideShare(side: SideSplit, task: Task, shown: Task, room: number): number {
  const columns = columnsOf(task.layout.root);
  const sideColumns = columnsOf(shown.layout.root);
  if (!side.resized || !room) return sideColumns / (columns + sideColumns);
  return Math.max(SIDE_MIN / room, Math.min(side.width / room, 1 - (columns * MIN_COLUMN) / room));
}

/** The wait before a drag resting on the side edge shows the hidden side split. */
let edgeDwell: ReturnType<typeof setTimeout> | undefined;

/** The 24px band along the main area's right edge while the side split is hidden (document 4):
 * a chat or an item carried onto it for 400ms shows the side split, to aim at its panes. */
function sideEdge(v: ChatView): Element {
  const leave = () => {
    clearTimeout(edgeDwell);
    edgeDwell = undefined;
  };
  return (
    <div
      id="side-edge"
      position="absolute"
      top={0}
      right={0}
      width={24}
      height="100%"
      drop={{
        types: DROPS,
        onOver: (e: DragOverEvent) => {
          if (e.zone === null) return leave();
          if (edgeDwell) return;
          edgeDwell = setTimeout(() => {
            edgeDwell = undefined;
            v.ctx.run(toggleSideSplit(v.controller));
          }, 400);
        },
        onDrop: leave,
      }}
    />
  );
}

/** Whether the task on screen draws its own panes: more than one chat, or the side split beside it. */
/** Every task draws its panes and strips, a chat row's one pane and tab too (document 2). */
export function drawsPanes(_v: ChatView, _task: Task): boolean {
  return true;
}

/** The first pane of a layout, top left. */
const firstPane = (layout: Layout): string => (layout.kind === "pane" ? layout.id : firstPane(layout.children[0]!.layout));

/** A pane, or a split of panes. Every place in the tree is a split named for its first pane and its
 * depth, a lone pane a split of one: when that pane splits, the new split has the same name, so the
 * kernel slides the new pane in from nothing rather than drawing the halves at once, and a pane
 * that closes slides out the same way. */
function layoutNode(v: ChatView, task: Task, layout: Layout, top: boolean, presentation: string | undefined, depth: number, focused: string | null): Element {
  const id = `split-${task.id}-${firstPane(layout)}-${depth}`;
  if (layout.kind === "pane")
    return <split id={id} direction="horizontal" sizes={[1]}>{paneNode(v, task, layout, top, presentation, focused === layout.id)}</split>;
  const across = layout.direction === "row";
  return (
    <split
      id={id}
      direction={across ? "horizontal" : "vertical"}
      sizes={layout.children.map((child) => child.share)}
      minSizes={layout.children.map(() => (across ? MIN_PANE_WIDTH : MIN_PANE_HEIGHT))}
      gap={across ? PANE_GAP : 0}
      onResize={(e: { sizes: readonly number[] }) => v.ctx.run(resizeSplit(v.controller, layout.id, e.sizes))}
    >
      {layout.children.map((child, index) => layoutNode(v, task, child.layout, top && (across || index === 0), presentation, depth + 1, focused))}
    </split>
  );
}

/** One pane: its active tab's view on a raised surface; a lower pane has its strip in a band above it. */
function paneNode(v: ChatView, task: Task, pane: Pane, top: boolean, presentation: string | undefined, focused: boolean): Element {
  const surface = (
    <pane focused={focused}>
      <div
        {...column}
        {...fill}
        {...full}
        id={`task-pane-${pane.id}`}
        measured
        position="relative"
        onPointerDown={() => v.ctx.run(focusPane(v.controller, task, pane))}
      >
        {paneBody(v, pane, presentation)}
        {measure(v, task, pane)}
        {dropPreview(pane.id)}
        {closeQuestion(v, pane)}
      </div>
    </pane>
  );
  if (top) return surface;
  return (
    // The band is laid out above the pane but painted after it, so its selected tab covers the
    // pane's edge where they meet.
    <div {...column} {...fill} {...full} flexDirection="column-reverse">
      {surface}
      {strip(v, task, pane, BAND, null, focused)}
    </div>
  );
}

/** The question a tab of this pane asked before closing (its kind's `beforeClose`): Close goes
 * on with the close, Cancel and Escape keep the tab. */
function closeQuestion(v: ChatView, pane: Pane): Element | null {
  const c = v.controller;
  const asking = c.state.layouts.asking;
  if (!asking || !pane.tabs.some((t) => sameTab(t, asking.tab))) return null;
  const cancel = () => {
    c.state.layouts.asking = null;
    v.ctx.update();
  };
  return (
    <overlay id="close-ask" open width={380} onDismiss={cancel}>
      <column padding="medium" gap="medium">
        <text style="body">{asking.question}</text>
        <row gap="small" justifyContent="end">
          <button id="close-ask-cancel" label="Cancel" variant="ghost" small onClick={cancel} />
          <button id="close-ask-confirm" label="Close" variant="danger" small onClick={() => v.ctx.run(closeTab(c, asking.tab, true))} />
        </row>
      </column>
    </overlay>
  );
}

/** The chat each pane last showed, and the chat a pane is switching to since when. */
const shownIn = new Map<string, string>();
const paneSwitch = new Map<string, { chatId: string; at: number }>();

/** What a pane shows: its active chat's pane view, or the view of the item's owner. */
function paneBody(v: ChatView, pane: Pane, presentation?: string): Element {
  const tab = pane.tabs.find((t) => sameTab(t, pane.active)) ?? pane.tabs[0];
  if (!tab) return <empty>Nothing is open here.</empty>;
  if (tab.kind === "item") {
    const prefix = `${tab.owner}.`;
    const kind = tab.itemKind.startsWith(prefix) ? tab.itemKind.slice(prefix.length) : tab.itemKind;
    // While the plugin that draws the tab is off, the tab stays and says so.
    return (
      <view plugin={tab.owner} name={v.controller.api.layouts.viewName(kind, tab.chatId, tab.key)}>
        <column id={`item-placeholder-${tab.id}`} {...fill} justifyContent="center" alignItems="center" gap="medium">
          <text style="body" tone="muted">{`${tab.title} shows again when its plugin is on.`}</text>
          <button
            id={`item-placeholder-turn-on-${tab.id}`}
            label="Turn On"
            small
            onClick={() => v.ctx.run(v.controller.host.call("host/plugins.request_enable", { name: tab.owner }))}
          />
        </column>
      </view>
    );
  }
  const c = v.controller;
  const chat = c.state.chats[tab.chatId];
  if (chat) v.ctx.run(ensurePane(c, chat.id));
  else v.ctx.run(c.loadChat(tab.chatId));
  // The pane keeps the chat it showed until the new one is ready, so a switch is one step
  // with nothing between; only one slower than SKELETON_AFTER shows its skeleton.
  const view = chat ? registeredPane(c.state.panes[chat.id]) : undefined;
  // Each retained presentation has its own transition state. Hidden trees
  // never replace the dynamic fallback's last active tab, or one another's.
  const key = presentation ? `${presentation}:${pane.id}` : pane.id;
  const before = shownIn.get(key);
  if (view?.ready) {
    shownIn.set(key, tab.chatId);
    paneSwitch.delete(key);
    return <view view={view.view.id} />;
  }
  const held = before && before !== tab.chatId ? registeredPane(c.state.panes[before]) : undefined;
  const since = paneSwitch.get(key);
  if (since?.chatId !== tab.chatId) {
    paneSwitch.set(key, { chatId: tab.chatId, at: Date.now() });
    setTimeout(() => c.center?.update(), SKELETON_AFTER);
  }
  const waited = Date.now() - (paneSwitch.get(key)?.at ?? 0);
  if (held?.ready && waited < SKELETON_AFTER) return <view view={held.view.id} />;
  return centerSkeleton(v);
}

// --- the title strip -------------------------------------------------------------

/** The strips of the panes along the top, in a region over the center, laid out as the panes are. */
/** The side split's toggle, for the task on screen (document 3). */
export function sideToggle(v: ChatView, task: Task, layout?: PresentationLayout): Element | null {
  // With nothing in it for this task, the side split opens on a New tab page.
  const open = !!(layout ? layout.side : sideOnScreen(v.controller.state.layouts, task, v.controller.state.chats));
  return (
    <button
      id="side-split-toggle"
      icon={open ? "panel-right-close" : "panel-right-dashed"}
      variant="ghost"
      tooltip={hint(v.controller, open ? "Hide the side split" : "Show the side split", "chat.toggleSideSplit")}
      onClick={() => v.ctx.run(toggleSideSplit(v.controller))}
    />
  );
}


export function renderTaskTitle(
  v: ChatView,
  task: Task,
  extra: Element | null,
  chatId = v.ctx.app.chatId ?? undefined,
  report = true,
  layout?: PresentationLayout,
): Element {
  if (report) v.ctx.run(reportLayoutKeys(v.controller));
  task = chatId ? taskShowing(task, chatId) : task;
  const found = layout ? layout.side : sideOnScreen(v.controller.state.layouts, task, v.controller.state.chats);
  const side = found && chatId ? { ...found, task: taskShowing(found.task, chatId) } : found;
  const focused = focusedOnScreen(v, task, side);
  // Every top pane's strip, of the task and of the side split, placed by the kernel over its
  // pane's box as last painted: a dragged divider or a sliding pane carries its strip in the
  // next frame, with nothing between. The side split's toggle ends the rightmost strip.
  const panes = [...topPanes(task.layout.root).map((pane) => ({ owner: task, pane }))];
  if (side) panes.push(...topPanes(side.task.layout.root).map((pane) => ({ owner: side.task, pane })));
  const last = panes.length - 1;
  // The strip that ends the row also ends with what belongs to the chat on screen and the window: Open in and the side
  // split's toggle.
  const chat = chatId ? v.controller.state.chats[chatId] : undefined;
  const trailing = [openInControl(v, chat), sideToggle(v, task, layout)];
  // The chat's workspace leads the row, after the sidebar toggle: the kernel lays its box out over the room the
  // sidebar leaves before the panes, one control wide when it is hidden. An older kernel has no such box and leaves
  // it out.
  const lead = chat ? <div {...row} alignTo="title-lead" height={TITLE_HEIGHT}>{workspacePicker(v, chat, "lead", leadAnchor)}</div> : null;
  return (
    <region over="center">
      {lead}
      <div id="title-strips" measured position="relative" width="100%" height={TITLE_HEIGHT}>
        {panes.map(({ owner, pane }, index) => (
          <div key={pane.id} {...row} alignTo={`task-pane-${pane.id}`} alignToEnd={index === last} height={TITLE_HEIGHT}>
            {strip(v, owner, pane, TITLE_HEIGHT, index === last ? trailing : null, focused === pane.id)}
          </div>
        ))}
      </div>
      {extra}
    </region>
  );
}


// --- strips and tabs -----------------------------------------------------------


/** The tabs with the glass slot a carried tab would land in, growing from nothing. */
function withGap(tabs: Element[], index: number | null): Element[] {
  if (index === null) return tabs;
  const slot = (
    <div
      key="tab-gap"
      id="tab-gap"
      flexShrink={0}
      height={BUTTON}
      width={0}
      // As wide as the tab that lands in it, so nothing moves when it lands.
      motion={{ to: { width: TAB_MAX }, duration: 160, easing: "easeOut" }}
      borderRadius="sm"
      background="card/40"
      backdrop={{ blur: 6 }}
      {...kit.EDGED}
    />
  );
  return [...tabs.slice(0, index), slot, ...tabs.slice(index)];
}

/** A pane's strip: its tabs, +, and the split buttons at its right end. */
/** The selected tab's surface: the top of its pane, the pane's colour and edge open at the
 * bottom, reaching over the pane's edge. One per strip, drawn under the tabs and following the
 * selected one: it moves at once to the tab the user picks, as switching tabs happens all day,
 * and glides only while a carried tab makes the tabs glide. */
function selectedSurface(pane: Pane, carrying: boolean, focused: boolean): Element {
  return (
    <div
      id={`tab-surface-${pane.id}`}
      follows={`tab-${tabKey(pane.active)}`}
      width="100%"
      height="100%"
      tabShape={{ radius: 8, flare: FLARE, join: TAB_JOIN, focused }}
      layoutMotion={carrying}
    />
  );
}

function strip(v: ChatView, task: Task, pane: Pane, height: number, trailing: readonly (Element | null)[] | null, focused: boolean): Element {
  const c = v.controller;
  const at = Math.max(0, pane.tabs.findIndex((tab) => sameTab(tab, pane.active)));
  // The only tab of a chat row has nothing to be taken out of.
  const closable = canCloseTabs(task);
  const right = canSplit(task, "right", sizes.get(pane.id));
  const down = canSplit(task, "down", sizes.get(pane.id));
  // Chats of more than one workspace side by side: each chat's tab shows its workspace's mark.
  const workspaces = new Set(
    panesOf(task.layout.root).flatMap((p) => p.tabs.map((t) => (t.kind === "chat" ? c.state.chats[t.chatId]?.workspaceId : undefined)).filter(Boolean)),
  );
  const mixed = workspaces.size > 1;
  return (
    <div {...row} id={`strip-${pane.id}`} group="strip" width="100%" height={height} flexShrink={0} alignItems="start" paddingTop={STRIP_TOP} gap={4} paddingLeft={STRIP_INSET} paddingRight={4}>
      <div
        {...row}
        {...fill}
        alignItems="start"
        // The scroller clips what it holds, and the + stands higher than the tabs: the scroller
        // starts as high as the + and keeps the tabs where they were with as much padding.
        height={TAB_HEIGHT + TAB_JOIN + STRIP_TOP / 2}
        marginTop={-STRIP_TOP / 2}
        paddingTop={STRIP_TOP / 2}
        paddingLeft={FLARE}
        gap="small"
        overflowX="scroll"
        reveal={at}
        drop={{ types: DROPS, onOver: (e: DragOverEvent) => (e.zone === null ? carryOver(v, null, null) : undefined), onDrop: (e: DropEvent) => stripDrop(v, pane, e) }}
      >
        {selectedSurface(pane, !!c.state.layouts.carried, focused)}
        {withGap(
          pane.tabs.map((tab) => tabNode(v, pane, tab, sameTab(tab, pane.active), closable, mixed)),
          c.state.layouts.carried?.gap?.paneId === pane.id ? c.state.layouts.carried.gap.index : null,
        )}
        {/* The + is one of the strip's buttons: on their centre line, not on the tabs' foot. */}
        <div {...row} height={BUTTON} flexShrink={0} marginTop={-STRIP_TOP / 2}>
          <button id={`strip-new-${pane.id}`} icon="plus-large" variant="ghost" tooltip="New tab" onClick={() => v.ctx.run(openNewTab(c, pane.id))} />
        </div>
      </div>
      <div {...row} height={height} marginTop={-STRIP_TOP} flexShrink={0} gap={4}>
        <button id={`strip-split-right-${pane.id}`} icon="columns-2" variant="ghost" disabled={!right} tooltip={hint(c, "Split right", "chat.splitRight")} onClick={() => v.ctx.run(splitPane(c, pane.id, "right"))} />
        <button id={`strip-split-down-${pane.id}`} icon="rows-2" variant="ghost" disabled={!down} tooltip={hint(c, "Split down", "chat.splitDown")} onClick={() => v.ctx.run(splitPane(c, pane.id, "down"))} />
        {trailing}
      </div>
    </div>
  );
}

/** A drop on a strip outside its tabs: on the slot a carried tab opened, where the slot is, or past the tabs, at the
 * end. A tab let go over its own strip before any slot opened stays where it was. */
function stripDrop(v: ChatView, pane: Pane, e: DropEvent) {
  const gap = v.controller.state.layouts.carried?.gap;
  carryEnd(v);
  const what = "data" in e ? dropped(e) : null;
  if (!what) return;
  if (gap?.paneId === pane.id) return land(v, what, { kind: "strip", paneId: pane.id, index: gap.index });
  if (inPane(pane, what)) return;
  land(v, what, { kind: "strip", paneId: pane.id, index: pane.tabs.length });
}

/** A stable id for a tab, for its element ids. */
const tabKey = (tab: Tab) => (tab.kind === "chat" ? `chat-${tab.chatId}` : `item-${tab.id}`);

function tabNode(v: ChatView, pane: Pane, tab: Tab, active: boolean, closable: boolean, mixed: boolean): Element {
  const c = v.controller;
  const key = tabKey(tab);
  const chatId = chatOf(tab);
  const chat = chatId ? c.state.chats[chatId] : undefined;
  const title = tab.kind === "item" ? tab.title : chat ? c.titleOf(chat) : "Chat";
  // A selected tab has the selected text whether or not its pane has the focus.
  const tone = active ? "foreground" : "muted";
  const close = (
    <div
      id={`tab-close-${key}`}
      {...row}
      {...clickable}
      justifyContent="center"
      width={TAB_CLOSE}
      height={TAB_CLOSE}
      flexShrink={0}
      borderRadius={4}
      hover={HOVER}
      stopPropagation
      tooltip={hint(c, "Close tab", "chat.closeTab")}
      onClick={() => v.ctx.run(closeTab(c, tab))}
    >
      <icon name="x" tone={tone} />
    </div>
  );
  const menu = c.state.layouts.menu;
  const menuOpen = !!menu && sameTab(menu.tab, tab) && menu.paneId === pane.id;
  // While a tab is carried the tabs glide to make way, and its own place closes once a gap
  // opens for it; otherwise they move at once (a dragged divider carries them).
  const carried = c.state.layouts.carried;
  const away = !!carried?.gap && sameTab(carried.tab, tab);
  const node = (
    <div
      key={key}
      {...row}
      {...clickable}
      cursor="pointer"
      id={`tab-${key}`}
      position="relative"
      opacity={0}
      motion={{ to: { opacity: 1 }, duration: 150 }}
      onSecondaryClick={() => v.ctx.run(openTabMenu(c, pane.id, tab))}
      gap={TAB_GAP}
      // The active tab reaches over the pane's edge, where the strip's selected surface
      // (`selectedSurface`) draws it as the top of its pane; the others have no surface until the
      // pointer is on them.
      height={active ? TAB_HEIGHT + TAB_JOIN : TAB_HEIGHT}
      paddingBottom={active ? TAB_JOIN : 0}
      paddingLeft={away ? 0 : TAB_INSET}
      paddingRight={away ? 0 : closable ? TAB_CLOSE_END : TAB_END}
      borderRadius="sm"
      // Every tab, chat or file, keeps one width; more tabs than fit scroll the strip.
      width={away ? 0 : TAB_MAX}
      flexShrink={0}
      layoutMotion={!!carried}
      overflow={away ? "hidden" : undefined}
      hover={active ? undefined : HOVER}
      {...FLAT}
      drag={tabDrag(tab, title, () => carryEnd(v))}
      drop={{
        types: DROPS,
        reorder: "horizontal",
        // The tabs make way: the gap opens on the side of this tab the pointer is on.
        onOver: (e: DragOverEvent) => {
          const what = e.zone ? dropped(e) : null;
          if (!what || !isTab(what)) return;
          const at = pane.tabs.findIndex((t) => sameTab(t, tab));
          carryOver(v, what, { paneId: pane.id, index: at + (e.zone === "after" ? 1 : 0) });
        },
        onDrop: (e: DropEvent) => {
          const what = "data" in e ? dropped(e) : null;
          const gap = c.state.layouts.carried?.gap;
          carryEnd(v);
          if (!what) return;
          const at = pane.tabs.findIndex((t) => sameTab(t, tab));
          land(v, what, { kind: "strip", paneId: pane.id, index: gap?.paneId === pane.id ? gap.index : at + (e.zone === "after" ? 1 : 0) });
        },
      }}
      onClick={() => v.ctx.run(showTab(c, pane.id, tab))}
      onPointerUp={(e: PointerUpEvent) => {
        if (e.button === 1 && closable) v.ctx.run(closeTab(c, tab));
      }}
    >
      <div {...row} justifyContent="center" width={TAB_MARK} height={TAB_MARK} flexShrink={0}>{mark(v, tab)}</div>
      {mixed && chat ? <div {...row} flexShrink={0}>{markIcon(markOf(c.state.workspaces[chat.workspaceId]), 14, true)}</div> : null}
      {/* The title takes the tab's free room, so the close mark keeps to the tab's right end. */}
      <div {...row} flexGrow={1} minWidth={0}>
        {chatId && c.state.renaming?.chatId === chatId ? renameField(v, chatId) : <text style="body" size="sm" weight={500} tone={tone} truncate>{title}</text>}
      </div>
      {tab.kind === "item" && tab.unseen && !active ? dot("info") : null}
      {menuOpen ? tabMenu(v, pane, tab, closable) : null}
      {closable ? <div {...row} marginLeft={TAB_CLOSE_PULL} {...active ? null : revealOnHover}>{close}</div> : null}
    </div>
  );
  return node;
}

/** A tab's menu (document 8): the kernel's list, opened under the tab, with the tab's own
 * entries, then the plugins' as action rows after a line. Its keys are the list's: up, down,
 * Enter and Escape. */
function tabMenu(v: ChatView, pane: Pane, tab: Tab, closable: boolean): Element {
  const c = v.controller;
  const side = c.state.layouts.side?.layout;
  const inSide = !!side && panesOf(side.root).some((p) => p.id === pane.id);
  const keys = c.state.shortcuts.keys;
  const entries: { value: string; label: string; key: string | undefined; run: () => void }[] = [
    ...(closable ? [{ value: "close", label: "Close", key: keys["chat.closeTab"], run: () => v.ctx.run(closeTab(c, tab)) }] : []),
    ...(pane.tabs.length > 1 ? [{ value: "close-others", label: "Close Other Tabs", key: keys["chat.closeOtherTabs"], run: () => v.ctx.run(closeOtherTabs(c, pane.id, tab)) }] : []),
    { value: "split-right", label: "Split Right", key: keys["chat.splitRight"], run: () => v.ctx.run(splitPane(c, pane.id, "right")) },
    { value: "split-down", label: "Split Down", key: keys["chat.splitDown"], run: () => v.ctx.run(splitPane(c, pane.id, "down")) },
    ...(!inSide && separable(c, tab) ? [{ value: "separate", label: "Separate from Task", key: undefined, run: () => v.ctx.run(separateTab(c, tab)) }] : []),
    ...(inSide || side ? [{ value: "move", label: inSide ? "Move into the Task" : "Move to the Side Split", key: keys["chat.moveTab"], run: () => v.ctx.run(moveAcross(c, pane.id, tab)) }] : []),
  ];
  const plugins = c.state.layouts.menu?.entries ?? [];
  return (
    <div position="absolute" left={0} bottom={0}>
      <combobox
        id="tab-menu"
        value=""
        width={220}
        options={entries.map((e) => ({ value: e.value, label: e.label, detail: e.key }))}
        actions={plugins.map((e) => ({
          label: e.title,
          onClick: () => v.ctx.run(c.kernel.call("run_command", { id: e.id, target: { kind: "tab", tab, paneId: pane.id } })),
        }))}
        onChange={(e: { value?: string }) => entries.find((entry) => entry.value === e.value)?.run()}
      >
        <div width={1} height={1} />
      </combobox>
    </div>
  );
}

/** The tab's 14px mark: the chat's status at a glance, a subagent's the same way, or the item's icon. */
function mark(v: ChatView, tab: Tab): Element {
  if (tab.kind === "item")
    return subagentMark(v, tab) ?? (tab.file ? <icon name="file" file={tab.file} /> : <icon name={tab.icon ?? "file"} tone="muted" />);
  const c = v.controller;
  const chat = c.state.chats[tab.chatId];
  if (!chat) return <icon name="bot" tone="muted" />;
  if (chat.status === "running" || c.state.starting.has(chat.id)) return busy();
  if (chat.status === "waiting_approval" || chat.status === "waiting_question") return dot("warning");
  // A subagent or a background command that outlived the turn is the chat still at work.
  if (chat.working && chat.working.agents + chat.working.commands > 0) return busy();
  if (chat.status === "failed") return dot("danger");
  return <icon name="bot" svg={c.state.agents[chat.agentId]?.icon} tone="muted" />;
}

/** A subagent's tab reads like a chat's: a spinner while it works, a dot while it needs you or after it failed, and
 * otherwise its mark in the chat, the agent's icon or the terminal's for a background command. Null for any other
 * item, or while the chat's transcript that holds the subagent is not read yet. */
function subagentMark(v: ChatView, tab: Extract<Tab, { kind: "item" }>): Element | null {
  if (tab.itemKind !== `${v.ctx.plugin}.subagent` || !tab.chatId) return null;
  const c = v.controller;
  const chat = c.state.chats[tab.chatId];
  const task = findTask(c.state.transcripts[tab.chatId]?.items ?? [], tab.key)?.task;
  if (!chat || !task) return null;
  if (task.status === "waiting") return dot("warning");
  if (isLive(task)) return busy();
  if (task.status === "failed") return dot("danger");
  return task.kind === "terminal" ? <icon name="square-terminal" tone="muted" /> : <icon name="bot" svg={c.state.agents[chat.agentId]?.icon} tone="muted" />;
}

// A spinner's glyph is smaller than an agent's icon: it keeps to the start of the mark's box, so it
// begins where the icon does.
const busy = () => (
  <div {...row} width={TAB_MARK} justifyContent="start">
    <spinner activity />
  </div>
);

const dot = (tone: "warning" | "danger" | "info") => (
  <div {...column} width={14} height={14} justifyContent="center" alignItems="center" flexShrink={0}>
    <div width={6} height={6} borderRadius="full" background={tone} />
  </div>
);

/** The transparent drop surface sits above content, including the floating composer
 * which masks transcript input. Its size also determines whether a split fits. */
function measure(v: ChatView, task: Task, pane: Pane): Element {
  return (
    <canvas
      id={`pane-drop-${pane.id}`}
      drop={paneDrop(v, task, pane)}
      position="absolute"
      left={0}
      top={0}
      width="100%"
      height="100%"
      commands={[]}
      onResize={(e: { width: number; height: number }) => {
        const before = sizes.get(pane.id);
        sizes.set(pane.id, e);
        // The split buttons say whether a split has room.
        const fits = (size?: { width: number; height: number }) =>
          size ? [size.width >= 2 * MIN_PANE_WIDTH, size.height >= 2 * MIN_PANE_HEIGHT].join() : "";
        if (fits(before) !== fits(e)) v.controller.titleView?.update();
      }}
    />
  );
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.9latestNov 21, 2026>=5 <6349 KB5 permissionsListed
0.2.8Nov 16, 2026>=5 <6348.6 KB5 permissionsListed
0.2.7Nov 11, 2026>=5 <6314.3 KB5 permissionsListed
0.2.6Nov 9, 2026>=5 <6306.2 KB5 permissionsListed
0.2.5Oct 27, 2026>=2 <4178.6 KB5 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.