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.9

Permissions in 0.2.9

  • 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, and its Close Chat and Reopen Closed Chat for Cmd+W and Cmd+Shift+T on a chat's only tab
  • 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/rows.tsx61.2 KB
// Rows rendering preserves the chat's retained tree and interaction keys.
import * as z from "zod";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import { editStats, groupTitle } from "../grouping.ts";
import { entriesOf, stillWorking, withoutSpawnRows } from "../subagents.ts";
import { knownKey, knownTokens, markedMessage } from "../message-text.ts";
import { markingKey, markingOf, markTranscript } from "../find.ts";
import { noticeKind, revision, sessionChanges, stoppedAfter, workedFor, workingFor } from "../transcript.ts";
import type { SessionChange } from "../transcript.ts";
import { sentAt } from "../time.ts";
import type { Element, Chat, Plan, QuoteEvent, SecurityRequest, ToolStatus, TranscriptItem, TurnSummary, ValueEvent } from "divergence";
import type { ProgramCall } from "divergence/protocol";
import type { DrawnRows, KeptItem, KeptRow, Transcript, UserItem, TextItem, ToolItem, ActivityProps } from "../state.ts";
import type { ChatView } from "../controller.ts";
import type { ToolGroup } from "../grouping.ts";
import { renderApproval, renderPublishRow, placeRequests, renderQuestion } from "./questions.tsx";
import { entryId, LONG, moveWindow, noteWindows, shownRange, windowRequests, windows } from "../window.ts";
import { olderLimit, unreadRows } from "../data.ts";
import type { Unsent } from "../window.ts";
import { BACKGROUND, backgroundList, backgroundOpens, backgroundToggle, renderBackground, renderTask, renderTaskGroup, renderWorkflow } from "./tasks.tsx";
import {
  READING_WIDTH,
  FIELD_INSET_X,
  column,
  row,
  fill,
  full,
  HOVER,
  clickable,
  revealOnHover,
  centred,
  ROW_TEXT,
  TOOL_ICONS,
  TOOL_LABELS,
  toolIcon,
  RAISED,
  EDGED,
  corner,
  TOP_FADE_HEIGHT,
  BLOCK_SPACE,
} from "./styles.tsx";
import { changesOpen, turnCard, withTurnEnd } from "./changes.tsx";
import { summariesAt } from "../changes.ts";

/** One block of the transcript with its share of the space between blocks (`BLOCK_SPACE`): every row of the reading
 * column, and the live line that ends it, is placed through this so they all sit the same distance apart. */
export const block = (content: Element | null): Element | null =>
  content && <div {...column} padding={0} paddingY={BLOCK_SPACE / 2}>{content}</div>;
export function activityRow(props: ActivityProps): Element | null {
  const { icon, label, detail, extra, status, open, onClick, tone, compact } = props;
  const gap = "medium";
  // The text sits in a filled row so the detail still truncates; the
  // opacity is on the row because text takes none. No padding of its
  // own, so the label starts on the reply text's line.
  return (
    <div {...row} {...onClick ? clickable : null} gap={gap} padding="small" paddingX={compact ? 6 : 5} paddingY={compact ? 5 : "small"} borderRadius="md" hover={onClick ? HOVER : undefined} onClick={onClick}>
      {icon
                  ? (
                    <div {...row} gap="small" padding="small" width={14} flexShrink={0} height={14} lineHeight={14} justifyContent="center">
                      {typeof icon === "string" ? <icon name={icon} small tone={tone ?? "faint"} /> : icon}
                    </div>
                  )
                  : null}
      <div {...row} {...fill} gap={gap} padding={0} opacity={tone ? undefined : 0.8}>
          {label ? <text style="body" {...ROW_TEXT} tone={tone ?? "foreground"}>{label}</text> : null}
          {detail ? <text style="body" {...ROW_TEXT} tone={tone ?? "foreground"} truncate>{detail}</text> : null}
          {extra ?? null}
        </div>
      {status && compact ? <div {...row} padding={0} marginRight={-6}>{status}</div> : (status ?? null)}
      {onClick
                  ? <div {...column} {...revealOnHover} gap="small" padding={0}><icon name={open ? "chevron-down" : "chevron-right"} small tone="muted" /></div>
                  : null}
    </div>
  );
}

// No vertical padding: a row with the counts is as tall as one without.
export function statsRow(stats: { added: number; removed: number } | null): Element | null {
  if (!stats) return null;
  return (
    <div {...row} gap={6} padding={0} paddingX={3} flexShrink={0}>
      <text style="body" size="xs" weight={620} lineHeight={14.6} tone="success">{`+${stats.added}`}</text>
      <text style="body" size="xs" weight={620} lineHeight={14.6} tone="danger">{`-${stats.removed}`}</text>
    </div>
  );
}

// A prompt is typed with Enter meaning a new line, but Markdown joins a
// single line break into a space: each break between two lines of text
// becomes a hard break, except inside a code fence, which keeps its lines.
// Markdown also carries a line typed right under a quote into the quote,
// as a reply to a quoted selection is typed: the quote ends there instead.
export function keepLineBreaks(text: string): string {
  let fence: string | null = null;
  const lines = text.split("\n");
  const quoted = (line: string) => /^ {0,3}>/.test(line);
  return lines
    .map((line, i) => {
      const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
      const next = lines[i + 1];
      if (marker && (fence === null || (marker[0] === fence[0] && marker.length >= fence.length)))
        fence = fence === null ? marker : null;
      else if (fence === null && line.trim() && next?.trim())
        return quoted(line) && !quoted(next) ? `${line}\n` : `${line}  `;
      return line;
    })
    .join("\n");
}

/** The line a prompt's text takes in its `bubble` (`plugins/ui/components/bubble.tsx`), which the clamp counts in. */
const PROMPT_LINE = 21.3;
const PROMPT_LINES = 5;

/** A prompt in its bubble, five lines at most until Read more opens it. Read more is offered only when the kernel says
 * five lines cut the prompt off as laid out at its width, wrapped lines counted, so a prompt that fits never has it; an
 * older kernel neither clamps nor says, and the whole prompt shows. */
export function clampedPrompt(v: ChatView, t: Transcript, key: string, moreId: string, body: Element, onExpand?: () => void): Element[] {
  const open = t.expanded.has(key);
  const onClamp = (e: { clamped: boolean }) => v.controller.noteClamp(t.clamped, key, e.clamped);
  return [
    <div {...column} minWidth={0} lineHeight={PROMPT_LINE} clampLines={PROMPT_LINES} clampOpen={open} onClamp={onClamp}>{body}</div>,
    // The small button pads its label 8px on each side and about 3px below it (a 22.5px box round a 16.4px line); the row
    // gives that back, so the label starts at the text's edge and the bubble's padding below it is the same as elsewhere.
    t.clamped.has(key) ? <div {...row} marginLeft={-8} marginBottom={-3}><button id={moreId} label={open ? "Show less" : "Read more"} variant="ghost" small onClick={() => { if (!open) onExpand?.(); v.controller.toggle(t.expanded, key); }} /></div> : null,
  ].filter((element): element is Element => element !== null);
}

/** A message as the transcript shows it, in the `bubble` component: what the user wrote (or a subagent was given) at the
 * column's right edge, what another agent sent (`received`) at its left. It is as wide as what it holds, at most 600px
 * and never wider than its column: a list, a quote or a code block measures as wide as it would be unwrapped, and a
 * bubble that kept that width ran off the pane's left edge. */
export function bubble(
  children: Element[],
  { received, navigate, ...props }: { id?: string; travels?: boolean; backdrop?: { blur: number }; background?: string; received?: boolean; navigate?: { id: string; onClick: () => void } } = {},
): Element {
  return (
    <div {...column} alignItems={received ? "start" : "end"} width="100%" maxWidth={600}>
      <bubble {...props} received={received} position={navigate ? "relative" : undefined}>{children}{navigate ? <div id={navigate.id} position="absolute" top={0} left={0} width="100%" height="100%" borderRadius="xl" cursor="default" hover={HOVER} onClick={navigate.onClick} /> : null}</bubble>
    </div>
  );
}

/** The glass of the copy pinned at the top: what passes under it blurs, as under the prompt box, behind its own
 * colour at 90%, so the text passing under it hardly shows through. */
const PINNED_GLASS = { blur: 6 } as const;
const PINNED_BUBBLE = "bubble over stage/90";
const PINNED_ACTIONS = "card over stage/90";

/** The column a message you sent is laid out in: its pictures, its bubble and the row under it. */
const SENT = { ...column, padding: "small", paddingY: "small", alignItems: "end" } as const;

/** A message you sent as it stays at the top of the transcript while its reply scrolls under it: its bubble and the row
 * under it, laid out as its own row lays them out, so the copy lands exactly on the row. They are glass over the rows
 * passing under them, and rest below the transcript's top fade, where the first row of a chat starts too
 * (`renderTranscript`). The kernel draws the copy only while it is away from its own row. */
function pinnedPrompt(bubbled: Element, actions: Element, carried: boolean): Element {
  return <sticky top={TOP_FADE_HEIGHT} carried={carried || undefined}>{reading([<div {...SENT}>{bubbled}{actions}</div>])}</sticky>;
}

type Offers = { offered: boolean; revertable: boolean; editable: boolean };

/** What a message you sent offers under it: Revert and Edit only while nothing runs, Edit where its agent can rewind
 * its own conversation (the host refuses it otherwise) and no other message is being edited. */
function offersOf(v: ChatView, chatId: string, t: Transcript, item: UserItem, pending = false, departing = false): Offers {
  const chat = v.controller.state.chats[chatId];
  const running = pending || t.running || !!t.resending || t.loading || v.controller.isRunning(chat);
  const rewinds = !!(chat && v.controller.state.agents[chat.agentId]?.capabilities?.rollback);
  return { offered: !running && !departing, revertable: t.checkpoints.has(item.id), editable: rewinds && !t.editing };
}

/** The copy of a message you sent that stays at the top while its reply scrolls (`pinnedPrompt`). `carried`, for the
 * first row the list has when the message's own row is not there (`renderTranscript`). */
function pinnedOf(v: ChatView, chatId: string, t: Transcript, item: UserItem, offers: Offers, carried = false): Element | null {
  const text = v.controller.plainText(item.blocks);
  if (!text) return null;
  const prompt = keepLineBreaks(markedMessage(text, item.blocks, knownTokens(v.controller, chatId)));
  return pinnedPrompt(
    bubble([
      <div {...column} minWidth={0} lineHeight={PROMPT_LINE} clampLines={PROMPT_LINES} onClamp={(e: { clamped: boolean }) => v.controller.noteClamp(t.clamped, item.id, e.clamped)}><markdown text={prompt} /></div>,
      ...(t.clamped.has(item.id) ? [<text>…</text>] : []),
    ], { backdrop: PINNED_GLASS, background: PINNED_BUBBLE, navigate: { id: `pinned-prompt-${item.id}`, onClick: () => v.ctx.run(goToPrompt(v, chatId, t, item.id)) } }),
    sentActions(v, chatId, t, item, text, { ...offers, pinned: true }),
    carried,
  );
}

function scrollToPrompt(t: Transcript, id: string) {
  t.scrollTo = { id: `transcript-row-${id}`, revision: (t.scrollTo?.revision ?? 0) + 1, inset: TOP_FADE_HEIGHT };
}

const goToPrompt = Effect.fn("Chat.goToPrompt")(function* (v: ChatView, chatId: string, t: Transcript, id: string) {
  for (let start = -1; !t.items.some((item) => item.id === id) && t.start > 0 && t.start !== start;) {
    if (t.olderReady) { yield* Deferred.await(t.olderReady); continue; }
    start = t.start;
    yield* v.controller.loadOlder(chatId, start);
  }
  const entries = entriesOf(withoutSpawnRows(t.items), v.controller.api.settings.get("groupTools") !== false);
  const at = entries.findIndex((entry) => entry.kind === "item" && entry.item.id === id);
  if (at < 0) return;
  scrollToPrompt(t, id);
  v.controller.view.update();
});

/** Opens a message you sent for editing in its row, bringing the row into the window a long transcript draws. */
function startEdit(v: ChatView, t: Transcript, item: UserItem) {
  t.editing = item.id;
  t.editText = v.controller.plainText(item.blocks);
  if (windows()) {
    const entries = entriesOf(withoutSpawnRows(t.items), v.controller.api.settings.get("groupTools") !== false);
    const at = entries.findIndex((entry) => entry.kind === "item" && entry.item.id === item.id);
    if (at >= 0) moveWindow(t, entries, at, entryId);
  }
  v.controller.view.update();
}

/** The message you sent that the turn at the top of the list began with, when the list has no row for it there: a
 * window that leaves it out, or history not read yet (the page's `lead`). A message from another session pins
 * nothing, so the one before it is the turn's. */
function carriedHead(t: Transcript, first: string | undefined): UserItem | undefined {
  const own = (item: TranscriptItem | undefined): item is UserItem => item?.role === "user" && item.from == null;
  const at = t.items.findIndex((item) => item.id === first);
  if (at < 0 || own(t.items[at])) return undefined;
  for (let i = at - 1; i >= 0; i--) if (own(t.items[i])) return t.items[i] as UserItem;
  return own(t.lead) ? t.lead : undefined;
}

/** The row under a message you sent: when it was sent, then Revert and Edit, which are offered only while nothing runs
 * (the host refuses them then), then Copy on the bubble's edge. Without Revert and Edit the row closes up toward Copy.
 * There is no Reply: next to Revert it read as a second undo. `pinned` names the copy that stays at the top, whose
 * buttons need ids of their own. */
function sentActions(
  v: ChatView,
  chatId: string,
  t: Transcript,
  item: UserItem,
  text: string,
  { offered, revertable, editable, pinned = false }: Offers & { pinned?: boolean },
): Element {
  const prefix = pinned ? "pinned-" : "";
  // The buttons and the time sit in one box, which is glass on the pinned copy and nothing on the row itself.
  return (
    <div {...row} {...full} paddingY="small" paddingX={0} marginRight={-5} justifyContent="end">
      <div {...row} gap="small" {...(pinned ? { background: PINNED_ACTIONS, backdrop: PINNED_GLASS, borderRadius: "md" } : {})}>
      {sentAtLabel(item, prefix)}
      {offered && revertable
        ? <button id={`${prefix}restore-${item.id}`} icon="rotate-ccw" variant="ghost" small tooltip="Revert the workspace files to before this prompt" onClick={() => v.ctx.run(v.controller.revert(chatId, item.id))} />
        : null}
      {offered && editable
        ? <button id={`${prefix}edit-${item.id}`} icon="pencil" variant="ghost" small tooltip="Edit this message and run again from here" onClick={() => startEdit(v, t, item)} />
        : null}
      {text ? messageActions(v, chatId, t, item.id, text, { reply: false, prefix }) : null}
      </div>
    </div>
  );
}

export function renderUser(
  v: ChatView,
  chatId: string,
  t: Transcript,
  item: UserItem,
  pending = false,
): Element | null {
  // Editing replaces the message: the files go back to the checkpoint
  // taken before it and the turns after it are dropped, so it is offered
  // only while nothing is running.
  if (t.editing === item.id) {
    const cancel = () => {
      t.editing = null;
      v.controller.view.update();
    };
    return (
      <div {...column} gap="small" padding="small" paddingY="medium" alignItems="end">
        <div {...column} {...full} gap="small" padding="small" maxWidth={600}>
              <div {...column} gap="small" padding="small" paddingX={FIELD_INSET_X} paddingY="small" background="card" borderRadius="md" {...RAISED}>
                    <input id={`edit-${item.id}`} value={t.editText} multiline ghost submitOnEnter keys={["escape"]} onKey={cancel} onChange={(e: ValueEvent<string>) => {
                                      t.editText = e.value;
                                    }} onSubmit={() => v.ctx.run(v.controller.submitEdit(chatId, item.id))} />
                  </div>
              <div {...row} gap="small" padding="small">
                    <spacer />
                    <button id={`edit-cancel-${item.id}`} label="Cancel" variant="ghost" small onClick={cancel} />
                    <button id={`edit-send-${item.id}`} label="Send again" variant="primary" small onClick={() => v.ctx.run(v.controller.submitEdit(chatId, item.id))} />
                  </div>
            </div>
      </div>
    );
  }
  const images = pending
    ? (v.controller.composer(chatId).outgoing?.attachments.map((image) => image.id) ?? [])
    : v.controller.imagesOf(item);
  // Stored images (docs/adr/0003): the kernel draws a box of the stored
  // size at once and reads the file only while the row is on screen.
  const stored = pending
    ? []
    : item.blocks.flatMap((block) =>
        block.type === "image" && block.path && block.width && block.height
          ? [{ path: block.path, width: block.width, height: block.height }]
          : [],
      );
  const text = v.controller.plainText(item.blocks);
  const prompt = keepLineBreaks(markedMessage(text, item.blocks, knownTokens(v.controller, chatId)));
  // The chat's first message rises out of the prompt box as the new chat
  // page leaves (views/panes.ts). Only the whole history knows which
  // message is first.
  const first = t.items.find((entry) => entry.role === "user");
  const rising = t.start === 0 && (first ? first.id === item.id : pending);
  const departing = rising && !!v.controller.state.panes[chatId]?.departing;
  // A screenshot takes the message's corner: its frame is `xl` and clips
  // it there, and the picture has the same corner where the frame cannot
  // clip (no rounded clip on the platform).
  const MESSAGE_IMAGE_RADIUS = corner("xl", 15.5);
  const offers = offersOf(v, chatId, t, item, pending, departing);
  const actions = sentActions(v, chatId, t, item, text, offers);
  const pinned = pinnedOf(v, chatId, t, item, offers);
  return (
    <div {...SENT} group="hover">
      {images.length || stored.length
                  ? (
                    <div {...row} width="100%" gap="small" padding="small" paddingY="small" maxWidth={600} justifyContent="end" flexWrap="wrap">
                      {[
                                      ...images.map((id) => <image id={id} maxHeight={360} radius={MESSAGE_IMAGE_RADIUS} zoomable />),
                                      ...stored.map(
                                        (image) =>
                                          <image path={image.path} pixelWidth={image.width} pixelHeight={image.height} maxHeight={360} radius={MESSAGE_IMAGE_RADIUS} zoomable />,
                                      ),
                                    ].map(
                                      (picture) =>
                                        // The shadow on a frame around the clip: a clipped box
                                        // clips its own shadow too.
                                        (
                                          <div maxWidth="100%" minWidth={0} borderRadius="xl" {...RAISED}>
                                            <div maxWidth="100%" borderRadius={MESSAGE_IMAGE_RADIUS} overflow="hidden">{picture}</div>
                                          </div>
                                        ),
                                    )}
                    </div>
                  )
                  : null}
      {pinned}
      {text ? bubble(clampedPrompt(v, t, item.id, `message-more-${item.id}`, <markdown id={`md-${item.id}`} text={prompt} find={markingOf(t, item.id)} />, () => scrollToPrompt(t, item.id)), { id: rising ? `rising-${chatId}` : undefined, travels: rising }) : null}
      {actions}
    </div>
  );
}

// A message another agent (another session) sent: the user bubble's shape
// on the agent's side, under the sender's name. It cannot be edited or
// reverted to, since nobody here sent it. Its edges are a reply's: the
// bubble and the buttons on the transcript's edge, the sender on the reply
// text's. A sender that is a chat here goes by its title, and a click on
// it opens that chat.
export function renderReceived(v: ChatView, chat: Chat, t: Transcript, item: UserItem, from: string): Element {
  const text = v.controller.plainText(item.blocks);
  const sender = item.fromSession
    ? Object.values(v.controller.state.chats).find((c) => c.agentId === chat.agentId && c.sessionId === item.fromSession)
    : undefined;
  const label = <text style="body" size="xs" weight={560} lineHeight={14.6} tone="muted" truncate>{`From ${sender?.title || from}`}</text>;
  return (
    <div {...column} group="hover" gap="small" padding="small" paddingX={0} alignItems="start">
      {sender
        ? (
          <div id={`from-${item.id}`} {...row} cursor="pointer" padding={0} paddingX={5} paddingY={2} marginY={-2} maxWidth={600} borderRadius="md" hover={HOVER} onClick={() => v.ctx.run(v.controller.app.select(sender.id, sender.workspaceId))}>
            {label}
          </div>
        )
        : <div {...row} padding={0} paddingX={5} maxWidth={600}>{label}</div>}
      {bubble([<markdown id={`md-${item.id}`} text={keepLineBreaks(text)} find={markingOf(t, item.id)} />], { received: true })}
      <div {...row} {...revealOnHover} gap="small" padding={0}>{messageActions(v, chat.id, t, item.id, text)}{sentAtLabel(item)}</div>
    </div>
  );
}

// `end`, for the reply that ends a turn: the message after it, where a
// fork from it stops, or null when it is the chat's latest reply. `turn`,
// the summary of the files the turn changed when it ends here. `background`,
// what the turn left running when this reply ends the transcript.
export function renderAssistant(v: ChatView, chat: Chat, item: TextItem, end?: string | null, turn?: TurnSummary, background?: string, detached = false): Element | null {
  // A model sometimes ends a step with a blank line and nothing else;
  // a heading over empty space would look like a lost reply.
  if (!item.text.trim()) return null;
  // A selection in the reply can be quoted into the prompt box.
  const onQuote = (event: QuoteEvent) => v.ctx.run(v.controller.quote(chat.id, event.text));
  const t = v.controller.transcript(chat.id);
  return (
    <reply group="hover">
      <markdown id={`md-${item.id}`} text={item.text} onQuote={onQuote} find={markingOf(t, item.id)} />
      {!detached ? replyActions(v, chat, t, item, end, turn, background) : null}
    </reply>
  );
}

function replyActions(v: ChatView, chat: Chat, t: Transcript, item: TextItem, end?: string | null, turn?: TurnSummary, background?: string, worked?: string | null): Element | null {
  const card = turnCard(v, chat, t, item.id, worked ?? workedFor(t, item), turn);
  const working = background ? backgroundToggle(v, chat, t, background) : null;
  if (end === undefined && !card && !working) return null;
  return <div {...row} gap={card || working ? "medium" : "small"} padding={0} marginLeft={-5} marginTop={card ? BLOCK_SPACE : 0}>
    {card}{working}
    {end === undefined ? null : <div {...row} {...revealOnHover} gap="small" padding={0}>
      {messageActions(v, chat.id, t, item.id, item.text, { fork: end })}{sentAtLabel(item)}
    </div>}
  </div>;
}

// Copy and Reply act on the whole message as they do on a selection in it;
// the user's own prompts leave Reply out (`reply: false`). Fork, given
// where the copy stops (`fork`), is offered only where the agent can fork:
// at the latest reply, or at any reply with `forkAt`.
export function messageActions(
  v: ChatView,
  chatId: string,
  t: Transcript,
  itemId: string,
  text: string,
  { reply = true, fork, prefix = "" }: { reply?: boolean; fork?: string | null; prefix?: string } = {},
): Element[] {
  const chat = v.controller.state.chats[chatId];
  const can = chat ? v.controller.state.agents[chat.agentId]?.capabilities : undefined;
  const forkable = fork !== undefined && !!can?.fork && (fork === null || !!can.forkAt);
  const copied = t.copied === itemId;
  return [
    <button id={`${prefix}copy-${itemId}`} icon={copied ? "check" : "copy"} variant="ghost" small tooltip={copied ? "Copied" : "Copy"} onClick={() => v.ctx.run(v.controller.copyMessage(chatId, itemId, text))} />,
    ...(reply
      ? [
          <button id={`reply-${itemId}`} icon="corner-up-left" variant="ghost" small tooltip="Reply" onClick={() => v.ctx.run(v.controller.quote(chatId, text))} />,
        ]
      : []),
    ...(forkable
      ? [
          <button id={`fork-${itemId}`} icon="git-branch" variant="ghost" small tooltip="Fork from here" onClick={() => v.ctx.run(v.controller.fork(chatId, fork))} />,
        ]
      : []),
  ];
}

// When a message was sent, with the full date and time on hover. `prefix`
// keeps the id of a pinned copy's apart.
function sentAtLabel(item: TranscriptItem, prefix = ""): Element | null {
  const at = sentAt(item.createdAt);
  if (!at) return null;
  return <div id={`${prefix}sent-${item.id}`} padding={0} paddingX={4} tooltip={at.full}>{turnText(at.label)}</div>;
}

// When a message was sent reads as the "Working for" line does.
function turnText(text: string): Element {
  return <div {...row} padding={0} opacity={0.8}><text style="body" {...ROW_TEXT} tone="foreground">{text}</text></div>;
}

// The replies that end a turn, each with the message that followed it, or
// null for the reply that ends the chat so far. A turn still running has
// no end yet: more of it may follow.
export function turnEnds(items: readonly TranscriptItem[], running: boolean): Map<string, string | null> {
  const ends = new Map<string, string | null>();
  let reply: string | null = null;
  for (const item of items) {
    // A message from another agent goes on with the turn: nobody can fork
    // or edit from it.
    if (item.role === "user" && item.from == null) {
      if (reply !== null) ends.set(reply, item.id);
      reply = null;
    } else if (item.role === "assistant" && item.text.trim()) reply = item.id;
  }
  if (reply !== null && !running) ends.set(reply, null);
  return ends;
}

export function renderArtifact(
  v: ChatView,
  t: Transcript,
  item: Extract<TranscriptItem, { role: "artifact" }>,
  chatId: string,
): Element {
  const open = t.expanded.has(item.id);
  const fallback = (
    <div {...column} gap="small" padding={0}>
      <text weight={600}>{item.artifact.title}</text>
      <text>{item.artifact.summary}</text>
      <text tone="muted" size="xs">
          {`The ${item.artifact.owner} renderer is unavailable. The saved data remains readable.`}
        </text>
      <button id={`source-${item.id}`} label={open ? "Hide source" : "Show source"} variant="ghost" small onClick={() => v.controller.toggle(t.expanded, item.id)} />
      {open ? <code text={JSON.stringify(item.artifact, null, 2)} language="json" /> : null}
    </div>
  );
  if (typeof v.controller.api.artifactRenderers !== "function") return fallback;
  return <artifact_view id={item.id} artifact={item.artifact} chat={chatId}>{fallback}</artifact_view>;
}

export function bodyInset(folded?: boolean): { paddingX: number; paddingY: string } {
  return { paddingX: folded ? 6 : 5, paddingY: "small" };
}

export function renderReasoning(v: ChatView, t: Transcript, item: TextItem, folded?: boolean): Element | null {
  const streaming = t.running && t.items[t.items.length - 1]?.id === item.id;
  const open = t.expanded.has(item.id) || streaming;
  const first =
    item.text
      .split("\n")
      .find((l) => l.trim())
      ?.replace(/^#+\s*|\*\*/g, "") ?? "";
  const title = streaming ? "Thinking" : open || !first ? "Thought" : first;
  return (
    <div {...column} padding={0}>
      {activityRow({ compact: folded, detail: title, open, onClick: () => v.controller.toggle(t.expanded, item.id) })}
      {open
                  ? <div {...column} gap="small" padding="small" {...bodyInset(folded)} opacity={0.85} fontSize={11.25} lineHeight={14.6}><markdown id={`md-${item.id}`} text={item.text} /></div>
                  : null}
    </div>
  );
}

export function renderToolBody(v: ChatView, call: import("divergence").ToolCall, chat: Chat): Element | null {
  const parts = [];
  const diffPaths = new Set<string>();
  const code = (text: string, language?: string) => <code text={text} language={language} />;
  // Code mode: the program the agent ran, then what it gave back.
  const parsed = z.object({ code: z.string() }).strict().safeParse(call.input);
  const program = parsed.success ? parsed.data.code : null;
  if (program) parts.push(code(program, "javascript"));
  if (call.message) parts.push(<markdown id={`md-${call.id}`} text={keepLineBreaks(call.message.text)} />);
  for (const c of call.content ?? []) {
    if (c.type === "terminal") {
      // The command column shrinks so a long command wraps inside the
      // card instead of running past its edge.
      parts.push(
        (
          <div {...column} gap="small" padding="small">
            <div {...row} gap="small" padding="small" alignItems="start">
                      <text style="mono" tone="muted">{"$"}</text>
                      <div {...column} {...fill} gap="small" padding="small"><text style="mono" text={String(c.command ?? "")} /></div>
                    </div>
            {c.output ? code(clip(c.output)) : null}
            {c.exitCode ? <text style="body" size="xs" tone="muted">{`exit ${c.exitCode}`}</text> : null}
          </div>
        ),
      );
    } else if (c.type === "diff") {
      diffPaths.add(c.path);
      parts.push(
        <diff path={inWorkspace(v, c.path, chat)} diff={c.diff} oldText={c.oldText} newText={c.newText} maxLines={200} />,
      );
    } else if (c.type === "text") {
      parts.push(code(clip(c.text)));
    } else if (c.type === "image") {
      // A picture a tool gave back is part of the agent's work: a closed row
      // shows it as a thumbnail and its card at a readable size; an agent that
      // wants you to see it shows it in its reply. An older host kept only the
      // bytes, which the card names.
      parts.push(c.path ? renderToolPicture(c, TOOL_PICTURE) : <text style="body" size="xs" tone="muted">Image</text>);
    }
  }
  // Some agents report the whole result as structured output and send no
  // content at all, which used to render an empty card.
  // A text result (a command's output) reads as text, not as one quoted line.
  if (!call.content?.length && call.output != null)
    parts.push(
      typeof call.output === "string"
        ? code(clip(call.output))
        : code(clip(JSON.stringify(call.output, null, 2)), "json"),
    );
  if (!parts.length && call.input != null) parts.push(code(JSON.stringify(call.input, null, 2), "json"));
  const locations = (call.locations ?? [])
    .filter((l) => !diffPaths.has(l.path))
    .map((l) => inWorkspace(v, l.line ? `${l.path}:${l.line}` : l.path, chat));
  if (locations.length) parts.push(<text style="body" size="xs" tone="muted">{locations.join("  ")}</text>);
  return <div {...column} gap="small" padding="medium" background="card" fontSize={11.25} lineHeight={14.6} borderRadius="sm">{parts}</div>;
}

export function clip(text: string): string {
  const MAX = 20000;
  return text.length > MAX ? `…\n${text.slice(-MAX)}` : text;
}

export function inWorkspace(v: ChatView, text: string, chat: Chat): string {
  const root = v.controller.state.workspaces[chat?.workspaceId]?.path;
  return root ? text.split(`${root}/`).join("") : text;
}

export function toolStatus(status: ToolStatus | undefined): Element | null {
  return status === "failed"
    ? <icon name="circle-alert" small tone="muted" />
    : status === "cancelled"
      ? <text style="body" size="xs" tone="muted">cancelled</text>
      : status === "completed"
        ? null
        : <spinner activity />;
}

/// One call a code mode program made: a compact activity row, its tool's
/// path and the short form of its input the host sent.
function renderProgramCall(v: ChatView, call: ProgramCall): Element | null {
  const input = call.input;
  const shown = (value: unknown) => (typeof value === "string" ? value : JSON.stringify(value));
  const detail =
    input && typeof input === "object" && !Array.isArray(input)
      ? Object.entries(input)
          .map(([key, value]) => `${key}: ${shown(value)}`)
          .join("  ")
      : input === undefined
        ? ""
        : shown(input);
  return activityRow({
    compact: true,
    icon: TOOL_ICONS.other,
    label: call.tool,
    detail: detail.split("\n")[0] ?? "",
    status: toolStatus(call.status),
  });
}

export function renderTool(v: ChatView, t: Transcript, item: ToolItem, chat: Chat, folded?: boolean): Element | null {
  const call = item.call;
  // A plugin that registered a renderer for this tool draws it, in its
  // own runtime; the kernel places its view here.
  const owned = v.controller.api
    .toolRenderers()
    .some((r) => (r.name && r.name === call.name) || (r.kind && r.kind === call.kind));
  if (owned) return <tool_view call={call} id={String(call.id ?? "")} />;
  const calls = call.calls ?? [];
  const hasBody = !!call.content?.length || call.output != null || call.input != null || calls.length > 0;
  const open = hasBody && t.expanded.has(call.id);
  const label = TOOL_LABELS[call.kind ?? "other"] ?? "";
  const stats = call.kind === "edit" && call.status === "completed" ? statsRow(editStats([item])) : null;
  const count = calls.length
    ? <text style="body" {...ROW_TEXT} tone="muted">{calls.length === 1 ? "1 call" : `${calls.length} calls`}</text>
    : null;
  // A multi-line command (a heredoc, say) shows its first line in the row;
  // the whole command is in the body.
  const detail =
    inWorkspace(v, call.title, chat)
      .split("\n")
      .find((l) => l.trim()) ?? "";
  // A code mode program opens like a fold of tool calls: one raised card
  // with a row per call it made, then the program and its result.
  const body = !open ? null : calls.length
    ? (
      <div {...column} id={`program-scroll-${call.id}`} followEnd gap={2} padding={5} maxHeight={400} background="card" borderRadius="md" {...RAISED} overflowY="scroll">
        {calls.map((programCall) => renderProgramCall(v, programCall))}
        <div {...column} gap="small" padding="small" {...bodyInset(true)}>{renderToolBody(v, call, chat)}</div>
      </div>
    )
    : <div {...column} gap="small" padding="small" {...bodyInset(folded)}>{renderToolBody(v, call, chat)}</div>;
  // An MCP App shows under its call whether or not the call is open: it is
  // what the tool gave the user. It hears the tool's end when the revision
  // moves.
  const ended = call.status === "completed" || call.status === "failed" || call.status === "cancelled";
  const apps = (call.content ?? []).flatMap((c, index) =>
    c.type === "mcp_app"
      ? [
          <div {...column} padding="small" {...bodyInset(folded)}>
            <web_document id={`mcp-app-${call.id}-${index}`} height={160} mcpApp={{ chatId: chat.id, toolCallId: call.id, index }} revision={ended ? 1 : 0} />
          </div>,
        ]
      : [],
  );
  // While the row is closed, the pictures it gave back show under it as thumbnails, which open full size on a click;
  // once it opens they are in its card at their own size instead.
  const thumbnails = open
    ? []
    : (call.content ?? []).flatMap((c) => (c.type === "image" && c.path ? [renderToolPicture(c, THUMBNAIL)] : []));
  // Read calls keep their file or image icon outside groups too. In a group a command that is still running spins
  // where its terminal icon goes; on its own row it spins at the end, as any running call does.
  const running = !!folded && call.kind === "execute" && !call.message && (call.status === "pending" || call.status === "running");
  const icon = !folded && call.kind !== "read"
    ? undefined
    : running
      ? <spinner activity />
      : toolIcon(call);
  return (
    <div {...column} gap={calls.length && open ? 2 : undefined} padding={0}>
      {activityRow({ compact: folded, icon, label, detail, extra: count ?? stats, status: running ? null : toolStatus(call.status), open, onClick: hasBody ? () => v.controller.toggle(t.expanded, call.id) : undefined })}
      {thumbnails.length ? <div {...row} gap="small" padding="small" {...bodyInset(folded)} flexWrap="wrap">{thumbnails}</div> : null}
      {apps}
      {body}
    </div>
  );
}

/// A picture a tool gave back: a file the host stored or one the tool named, at its own shape within `box` (the
/// kernel draws a picture of known size within the height cap and shrinks it to the wrapper's width); a click opens it
/// full size. A closed row shows it as a thumbnail, its open card at `TOOL_PICTURE`.
function renderToolPicture(picture: { path?: string; width?: number; height?: number }, box: PictureBox): Element {
  return (
    <div maxWidth={box.width} minWidth={0} borderRadius={box.radius} {...EDGED}>
      {picture.width && picture.height
        ? <image path={picture.path} pixelWidth={picture.width} pixelHeight={picture.height} maxHeight={box.height} radius={box.radius} zoomable />
        : <image path={picture.path} maxHeight={box.height} radius={box.radius} zoomable />}
    </div>
  );
}

type PictureBox = { width: number | "100%"; height: number; radius: "sm" | "md" };
const THUMBNAIL: PictureBox = { width: 120, height: 72, radius: "sm" };
/** A tool's pictures are smaller than a reply's (360): a run of screenshots should not bury the turn. */
const TOOL_PICTURE: PictureBox = { width: "100%", height: 240, radius: "md" };

export function renderPlan(plan: Plan): Element | null {
  const icon = { pending: "circle", in_progress: "loader", completed: "circle-check", cancelled: "circle-x" };
  const tone = { pending: "faint", in_progress: "info", completed: "success", cancelled: "faint" };
  return (
    <div {...column} gap="small" padding="medium" background="card" borderRadius="md">
      {(plan.entries ?? []).map(
                (e) =>
                  (
                    <div {...row} gap="small" padding="small">
                      <icon name={icon[e.status ?? "pending"] ?? "circle"} small tone={tone[e.status ?? "pending"] ?? "muted"} />
                      <text style="body" size="sm" text={String(e.content ?? "")} />
                    </div>
                  ),
              )}
    </div>
  );
}

// While the agent summarizes, the row says so; once it is done, the summary it wrote opens under it.
export function renderCompaction(v: ChatView, t: Transcript, item: Extract<TranscriptItem, { role: "compaction" }>): Element | null {
  if (item.running) return activityRow({ icon: <spinner activity />, label: "Compacting the conversation…" });
  const open = !!item.summary && t.expanded.has(item.id);
  return (
    <div {...column} padding={0}>
      {activityRow({
        icon: "fold-vertical",
        label: "Compacted the conversation",
        open,
        onClick: item.summary ? () => v.controller.toggle(t.expanded, item.id) : undefined,
      })}
      {open ? <div {...column} gap="small" padding="small" {...bodyInset(false)} opacity={0.85} fontSize={11.25} lineHeight={14.6}><markdown id={`md-${item.id}`} text={item.summary ?? ""} /></div> : null}
    </div>
  );
}

export function renderItem(
  v: ChatView,
  chat: Chat,
  t: Transcript,
  item: TranscriptItem,
  folded?: boolean,
  pending = false,
  end?: string | null,
  turn?: TurnSummary,
  background?: string,
  detached = false,
): Element | null {
  switch (item.role) {
    case "user":
      return (
        <div {...column} padding="small" paddingX={item.from != null ? 0 : "small"}>
          <div {...row} gap="small" padding="small" height={12} />
          {item.from != null ? renderReceived(v, chat, t, item, item.from) : renderUser(v, chat.id, t, item, pending)}
        </div>
      );
    case "assistant":
      return renderAssistant(v, chat, item, end, turn, background, detached);
    case "reasoning":
      return renderReasoning(v, t, item, folded);
    case "tool":
      return renderTool(v, t, item, chat, folded);
    case "artifact":
      // Inset like the reply text, so a page or visual lines up with it.
      return <div {...column} padding="small" paddingX={5} paddingY="small">{renderArtifact(v, t, item, chat.id)}</div>;
    case "plan":
      return renderPlan(item.plan);
    case "notice":
      return renderNotice(t, item);
    case "task":
      return item.task.workflow ? renderWorkflow(v, chat, t, item) : renderTask(v, chat, t, item);
    case "compaction":
      return renderCompaction(v, t, item);
    default:
      return null;
  }
}

// A notice: a decision on an approval or a held message is a quiet line, as
// is a stopped run, which says how long it went; anything else is an error.
function renderNotice(t: Transcript, item: Extract<TranscriptItem, { role: "notice" }>): Element | null {
  const kind = noticeKind(item);
  if (kind === "error") return <div {...column} padding={0} paddingY={4}><callout tone="danger" text={item.text} /></div>;
  return activityRow({ label: kind === "stopped" ? stoppedAfter(t, item) : item.text, tone: "muted" });
}

// A line across the reading column with the agents in its middle, above the
// first message sent after a handoff or in a new native session.
export function renderSessionChange(v: ChatView, change: SessionChange): Element {
  const agents = v.controller.state.agents;
  const mark = (agentId: string) => <icon name="bot" small tone="muted" svg={agents[agentId]?.icon} />;
  const line = <div {...fill} height={1} background="border/60" />;
  const caption = (text: string) =>
    <text style="body" size="xs" weight={560} lineHeight={14.6} tone="muted">{text}</text>;
  const handoff = change.kind === "handoff";
  return (
    <div {...column} group="hover" gap={2} padding={0} paddingTop={14} alignItems="center">
      <div {...row} width="100%" gap="medium" padding={0}>
          {line}
          <div {...row} gap={6} padding={0} flexShrink={0}>
              {handoff
                              ? (
                                <>
                                  {mark(change.from)}
                                  <icon name="arrow-right" small tone="faint" />
                                  {mark(change.to)}
                                  {caption("Handed off")}
                                </>
                              )
                              : (
                                <>
                                  {mark(change.to)}
                                  {caption("New session")}
                                </>
                              )}
            </div>
          {line}
        </div>
      {handoff
                  ? null
                  : (
                    <div {...revealOnHover} padding={0}>
                      <text style="body" size="xs" lineHeight={14.6} tone="faint">
                                    The previous session was unavailable. The conversation so far went to a new one.
                                  </text>
                    </div>
                  )}
    </div>
  );
}

function withSessionChange(v: ChatView, change: SessionChange | undefined, rendered: Element | null): Element | null {
  if (!change) return rendered;
  return <div {...column} padding={0}>{renderSessionChange(v, change)}{rendered}</div>;
}

const itemId = (item: TranscriptItem) => item.id;
const boundedRows = (v: ChatView) => v.controller.api.uiCapabilities?.includes("boundedDivRows") === true;

export function renderFold(v: ChatView, chat: Chat, t: Transcript, entry: ToolGroup, last?: boolean, kept?: KeptRow): Element | null {
  const calls = entry.items.filter((item) => item.role === "tool").map((item) => item.call);
  const running = calls.some((call) => call.status === "pending" || call.status === "running");
  const open = t.folds.get(entry.id) ?? last;
  const bounded = boundedRows(v);
  const [lo, hi] = bounded ? shownRange(t, entry.items, itemId, entry.id) : [0, entry.items.length];
  const range = bounded && entry.items.length > LONG ? ({ first }: { first: number }) => {
    if (moveWindow(t, entry.items, first, itemId, entry.id)) v.ctx.update();
  } : undefined;
  const before = kept?.children;
  const children = kept && open ? new Map<string, KeptItem>() : undefined;
  if (kept) kept.children = children;
  const stats = editStats(entry.items);
  // A failed call shows its own mark inside; the fold only says it runs.
  const status = running ? <spinner activity /> : null;
  return (
    <div {...column} gap={2} padding={0}>
      {activityRow({
                icon: groupIcon(entry.items),
                detail: groupTitle(entry.items),
                extra: statsRow(stats),
                status,
                open,
                onClick: () => {
                  t.folds.set(entry.id, !open);
                  // A subagent's tab draws its folds too.
                  v.controller.redraw(chat.id);
                },
              })}
      {open
                  ? (
                    <div {...column} id={`fold-scroll-${entry.id}`} layoutMotion followEnd gap={2} padding={5} maxHeight={400} background="card" borderRadius="md" {...RAISED} overflowY="scroll" rowsBefore={lo || undefined} rowsAfter={entry.items.length - hi || undefined} onRange={range}>
                      {entry.items.slice(lo, hi).map((item) => {
                        const inputs = children ? itemInputs(v, t, item) : null;
                        const held = inputs ? before?.get(item.id) : undefined;
                        if (children && inputs && held && sameInputs(held.inputs, inputs)) {
                          children.set(item.id, held);
                          return held.row;
                        }
                        // Retaining the whole wrapper also retains its motion and native row identity.
                        const row = <div id={`fold-item-${item.id}`} layoutMotion display="flex" flexDirection="column">{renderItem(v, chat, t, item, true)}</div>;
                        if (children && inputs) children.set(item.id, { inputs, row });
                        return row;
                      })}
                    </div>
                  )
                  : null}
    </div>
  );
}

/** A group's icon is the kind's icon its calls have most often, so a group of commands looks like a command; a group
 * of only reasoning shows thinking's. */
export function groupIcon(items: readonly TranscriptItem[]): string {
  const counts = new Map<string, number>();
  for (const item of items) {
    if (item.role !== "tool") continue;
    const icon = toolIcon(item.call);
    counts.set(icon, (counts.get(icon) ?? 0) + 1);
  }
  let best: string = TOOL_ICONS.think;
  let most = 0;
  for (const [icon, n] of counts) if (n > most) [best, most] = [icon, n];
  return best;
}

// Each transcript row is keyed by what it shows, so the kernel can tell a
// row that has just arrived (it fades in) from one it has drawn before.
const rowKeys = new WeakMap<object, string>();
function keyed(row: Element | null, key: string): Element | null {
  if (row) rowKeys.set(row, key);
  return row;
}

function sameInputs(a: readonly unknown[], b: readonly unknown[]) {
  return a.length === b.length && a.every((value, i) => value === b[i]);
}

// What a row reads beyond its items, the same for every row of the chat.
function sharedInputs(v: ChatView, chat: Chat, t: Transcript, shown: TranscriptItem[], groupTools: boolean): unknown[] {
  const c = v.controller;
  // Which tools another plugin draws, read only by tool rows.
  const renderers = shown.some((item) => item.role === "tool")
    ? c.api
        .toolRenderers()
        .map((r) => `${r.name ?? ""}:${r.kind ?? ""}`)
        .join(" ")
    : "";
  return [
    chat.id,
    c.state.workspaces[chat.workspaceId]?.path,
    c.state.agents[chat.agentId]?.capabilities?.rollback,
    c.state.agents[chat.agentId]?.capabilities?.fork,
    c.state.agents[chat.agentId]?.capabilities?.forkAt,
    c.isRunning(chat),
    t.running,
    !!t.loading,
    t.resending,
    // While one message is being edited the others offer no Edit, which would throw its text away.
    !!t.editing,
    groupTools,
    boundedRows(v),
    renderers,
    c.state.panes[chat.id]?.departing,
    // Which commands, skills and agents a message's words name.
    knownKey(knownTokens(c, chat.id)),
    // A message's time says "Yesterday" from the next day on.
    new Date().toDateString(),
  ];
}

// What one item's row reads of it and of the chat's state about it.
function itemInputs(v: ChatView, t: Transcript, item: TranscriptItem): unknown[] {
  const id = item.role === "tool" ? item.call.id : item.id;
  return [
    item,
    revision(item),
    t.expanded.has(id),
    t.clamped.has(id),
    t.checkpoints.has(item.id),
    v.controller.state.itemImages[item.id],
    t.editing === item.id ? t.editText : null,
    t.running && t.items[t.items.length - 1] === item,
    t.copied === item.id,
    t.worked.get(item.id),
    markingKey(markingOf(t, item.id)),
  ];
}

// The inputs of an entry whose row can be kept, or null: a subagent's row
// shows its live state and time, and a session change shows the agents.
function entryInputs(
  v: ChatView,
  t: Transcript,
  entry: ReturnType<typeof entriesOf>[number],
  change: SessionChange | undefined,
  last: boolean,
  end: string | null | undefined,
): unknown[] | null {
  if (entry.kind === "tasks" || change) return null;
  if (entry.kind === "item") return entry.item.role === "task" ? null : [...itemInputs(v, t, entry.item), end];
  if (entry.items.some((item) => item.role === "task")) return null;
  const range = boundedRows(v) ? shownRange(t, entry.items, itemId, entry.id) : [];
  return [t.folds.get(entry.id), last, ...range, entry.items.length, ...entry.items.flatMap((item) => itemInputs(v, t, item))];
}

export function renderItems(
  v: ChatView,
  chat: Chat,
  t: Transcript,
  items: TranscriptItem[],
  requests: readonly SecurityRequest[] = [],
  keep = false,
  unsent?: Unsent,
): (Element | null)[] {
  // "Group tool calls" is the plugin's own setting (plugin.json).
  const groupTools = v.controller.api.settings.get("groupTools") !== false;
  const shown = withoutSpawnRows(items);
  const entries = entriesOf(shown, groupTools);
  // A long transcript draws the window around the reader (`../window.ts`);
  // `unsent` takes what it leaves out.
  const range = unsent ? shownRange(t, entries, entryId) : ([0, entries.length] as const);
  const changes = sessionChanges(shown, t.sessions);
  // Only the chat's own turns end where a fork can start, not a subagent's
  // transcript drawn inside it.
  const running = t.running || v.controller.isRunning(chat);
  const ends = items === t.items ? turnEnds(shown, running) : new Map<string, string | null>();
  // A turn of the chat's own that changed files ends with their summary
  // (`../changes.ts`) in its closing card; a subagent's transcript drawn
  // inside it has none.
  const turns = items === t.items ? summariesAt(entries, t.turnFiles, running) : undefined;
  const detached = new Map<number, { item: TextItem; end: string | null }>();
  const detachedIds = new Set<string>();
  const entryIndex = new Map(entries.flatMap((entry, i) => entry.kind === "item" ? [[entry.item.id, i] as const] : []));
  const shownById = new Map(shown.map((item) => [item.id, item]));
  for (const [id, end] of ends) {
    const replyIndex = entryIndex.get(id) ?? -1;
    const nextIndex = end === null ? entries.length : entryIndex.get(end) ?? -1;
    const item = shownById.get(id);
    if (replyIndex >= 0 && nextIndex > replyIndex + 1 && item?.role === "assistant") {
      detached.set(nextIndex - 1, { item, end });
      detachedIds.add(id);
    }
  }
  const holder = items === t.items ? backgroundReply(v, chat, t) : null;
  const working = holder ? stillWorking(chat, t.items) : null;
  const shared = keep ? sharedInputs(v, chat, t, shown, groupTools) : [];
  // The chat's rows from its last render, by entry id, with what each was drawn from (`DrawnRows`); grouping and input
  // checks still scan items.
  const before = keep ? t.drawn : undefined;
  const kept = before && sameInputs(before.shared, shared) ? before.rows : undefined;
  const next = new Map<string, KeptRow>();
  const rows = entries.slice(...range).map((entry, j) => {
    const i = range[0] + j;
    const id = entry.kind === "item" ? entry.item.id : entry.id;
    const change = entry.kind === "item" ? changes.get(entry.item.id) : undefined;
    const last = i === entries.length - 1;
    const end = entry.kind === "item" ? ends.get(entry.item.id) : undefined;
    const turn = turns?.get(i);
    const tail = detached.get(i);
    const inputs = keep ? entryInputs(v, t, entry, change, last, end) : null;
    const background = (tail?.item.id ?? id) === holder ? (working ?? undefined) : undefined;
    inputs?.push(detachedIds.has(id), ...(tail ? itemInputs(v, t, tail.item) : []), tail?.end, turn, turn && changesOpen(t, turn), background, background && t.folds.get(BACKGROUND), background && backgroundOpens(t));
    const held = inputs ? kept?.get(id) : undefined;
    if (inputs && held && sameInputs(held.inputs, inputs)) {
      next.set(id, held);
      return held.row;
    }
    const record: KeptRow | undefined = inputs ? { inputs, row: null, children: held?.children } : undefined;
    // A run that ended on the entry's last item says how long it went in the
    // card after it, with what the turn changed, unless that item is a
    // reply, which says it itself. A reply of its own draws the whole card in
    // its action row.
    const ended = entry.kind === "item" ? entry.item : entry.items[entry.items.length - 1]!;
    const reply = ended.role === "assistant" && !!ended.text.trim();
    const card = tail || (reply && entry.kind === "item") ? null : turnCard(v, chat, t, ended.id, reply ? null : workedFor(t, ended), turn);
    const closed = (rendered: Element | null) => withTurnEnd(v, chat, t, tail ? <div {...column} padding={0} group="hover">{rendered}{replyActions(v, chat, t, tail.item, tail.end, turn, background, workedFor(t, tail.item) ?? workedFor(t, ended))}</div> : rendered, card, turn);
    const row =
      entry.kind === "item"
        ? keyed(block(withSessionChange(v, change, closed(renderItem(v, chat, t, entry.item, undefined, false, end, turn, background, detachedIds.has(id))))), entry.item.id)
        : keyed(block(closed(entry.kind === "tasks" ? renderTaskGroup(v, chat, t, entry) : renderFold(v, chat, t, entry, last, record))), entry.id);
    if (record) { record.row = row; next.set(id, record); }
    return row;
  });
  if (keep) t.drawn = { shared, rows: next, placed: before?.placed ?? new Map() };
  if (unsent) {
    const top = entries[range[0]];
    unsent.first = top && (top.kind === "item" ? top.item.id : top.items[0]?.id);
    const placed = windowRequests(entries, range, requests, unsent, t.scrollTo?.id.replace(/^transcript-row-/, ""));
    return placed.length ? placeRequests(v, entries.slice(...range), rows, placed) : rows;
  }
  return requests.length ? placeRequests(v, entries, rows, requests) : rows;
}

// Range reports move the render window within loaded history. Only the
// scroller's reach-start callback asks the host for an older page.
function transcriptRange(v: ChatView, chat: Chat, first: number) {
  const c = v.controller;
  const t = c.transcript(chat.id);
  const groupTools = c.api.settings.get("groupTools") !== false;
  const shown = withoutSpawnRows(t.items);
  noteWindows();
  moveWindow(t, entriesOf(shown, groupTools), first, entryId);
  c.refresh(chat.id);
}

// `footer` floats over the bottom of the transcript, which scrolls under it.
export function renderTranscript(v: ChatView, chat: Chat, footer?: Element | null): Element | null {
  const chatId = chat.id;
  const t = v.controller.transcript(chatId);
  // The publish row, or in a chat that fixes a bug report the attach
  // row, ends the transcript (§10.6, §14.2).
  const endRow = (r: SecurityRequest) => r.kind === "publish" || r.kind === "attach_fix";
  const publish = t.requests.filter(endRow);
  const unsent: Unsent | undefined = windows() ? { before: 0, after: 0, end: true } : undefined;
  markTranscript(v.controller, t);
  const rows = renderItems(
    v,
    chat,
    t,
    t.items,
    t.requests.filter((r) => !endRow(r)),
    true,
    unsent,
  );
  const entryRows = rows.length;
  const outgoing = v.controller.composer(chatId).outgoing;
  if (outgoing?.preview && !t.items.some((item) => item.id === outgoing.id)) {
    const preview: UserItem = {
      id: outgoing.id,
      role: "user",
      blocks: outgoing.blocks ?? [{ type: "text", text: outgoing.text }],
    };
    // The message goes to the chat's current session: a handoff shows its
    // divider before the host has the message.
    const last = [...t.items].reverse().find((item) => item.role === "user");
    const sessions = { [preview.id]: { agentId: chat.agentId, sessionId: chat.sessionId ?? null } };
    if (last && t.sessions[last.id]) sessions[last.id] = t.sessions[last.id]!;
    const change = sessionChanges(last ? [last, preview] : [preview], sessions).get(preview.id);
    rows.push(keyed(block(withSessionChange(v, change, renderItem(v, chat, t, preview, undefined, true))), preview.id));
  }
  if (t.plan?.entries?.length) rows.push(keyed(renderPlan(t.plan), "plan"));
  if (!t.running) for (const req of publish) rows.push(keyed(renderPublishRow(chatId, req), req.id));
  for (const a of t.approvals) rows.push(keyed(renderApproval(chatId, a), a.id));
  for (const q of t.questions) rows.push(keyed(renderQuestion(v, chatId, t, q), q.id));
  // While the new chat page leaves, the sent message rising into place is
  // all that moves; the activity under it shows once it is there.
  if (!v.controller.state.panes[chatId]?.departing) {
    // After the turn, a subagent or a background command it left running keeps the chat at work: the reply that ends
    // the transcript says so in its action row, and its list opens under it.
    const background = t.running ? null : stillWorking(chat, t.items);
    if (t.running && !t.approvals.length && !t.questions.some((q) => q.responseMode !== "message"))
      rows.push(keyed(workingRow(workingFor(t)), "working"));
    else if (background)
      rows.push(keyed(block(backgroundReply(v, chat, t) ? backgroundList(v, chat, t) : renderBackground(v, chat, t, background)), "working"));
    else if (t.resending) rows.push(keyed(block(activityRow({ icon: <spinner />, label: "Sending again…" })), "resending"));
    else if (outgoing?.preview) rows.push(keyed(block(activityRow({ icon: <spinner />, label: "Submitting…" })), "submitting"));
  }
  // A window short of the end leaves out the rows that end the transcript.
  if (unsent && !unsent.end) unsent.after += rows.splice(entryRows).length;
  // Near the first row read the scroller asks for the page before it, and
  // holds room for the history not read yet (`unreadRows`).
  const older = t.start > 0 ? (e?: { missing?: number }) => v.ctx.run(v.controller.loadOlder(chatId, olderLimit(t, e?.missing))) : undefined;
  const range = (e: { first: number }) => transcriptRange(v, chat, e.first);
  // A message sent takes the reader to the end, where it shows.
  const sent = v.controller.composer(chatId).sent;
  // The chat's first row starts below the top fade, where a message pinned at the top rests (`pinnedPrompt`), so the
  // copy lands on it there too.
  const atStart = t.start === 0 && !unsent?.before;
  const head = carriedHead(t, unsent ? unsent.first : withoutSpawnRows(t.items)[0]?.id);
  const carried = head ? pinnedOf(v, chatId, t, head, { ...offersOf(v, chatId, t, head), editable: false }, true) : null;
  // A message opened for editing comes into view: Edit on the copy pinned at the top is pressed far from its row.
  const reveal = t.find?.current?.id ?? (t.editing ? `transcript-row-${t.editing}` : t.scrollTo?.id);
  // A row in the reading column; a kept row keeps its column too, while the room above it stays the same (a chat's
  // first row has the top fade's).
  const placedBefore = t.drawn!.placed;
  const placed: DrawnRows["placed"] = new Map();
  const place = (row: Element | null, top: number) => {
    if (!row) return reading([row]);
    const held = placedBefore.get(row);
    const kept = held && held.top === top ? held : { top, element: reading([row], rowKeys.get(row), top) };
    placed.set(row, kept);
    return kept.element;
  };
  const readingColumn = rows.map((row, i) => (i === 0 && carried ? reading([carried, row], row ? rowKeys.get(row) : undefined) : place(row, i === 0 && atStart ? TOP_FADE_HEIGHT : 0)));
  t.drawn!.placed = placed;
  return (
    <scroller id={`transcript-${chatId}`} toEnd={sent ? String(sent) : undefined} reveal={reveal} scrollTo={t.scrollTo && { ...t.scrollTo, index: unsent?.target }} onReachStart={older} onRange={range} rowsUnloaded={unreadRows(t)} rowsBefore={unsent?.before || undefined} rowsAfter={unsent?.after || undefined}>
      {readingColumn}
      {footer ? <slot name="footer">{footer}</slot> : null}
    </scroller>
  );
}

/** "Working for 42s" with the activity spinner: what ends a chat's transcript, and a subagent's tab, while it works. */
export const workingRow = (label: string) => block(activityRow({ icon: <spinner activity />, label }));

/** The latest reply of the settled turn tells in its action row what it left running. Without one the transcript
 * ends with a working row of its own. */
function backgroundReply(v: ChatView, chat: Chat, t: Transcript): string | null {
  if (t.running || v.controller.isRunning(chat)) return null;
  for (let i = t.items.length - 1; i >= 0; i--) {
    const item = t.items[i]!;
    if (item.role === "user" && item.from == null) break;
    if (item.role === "assistant" && item.text.trim()) return item.id;
  }
  return null;
}

// `key` names a transcript row, for the kernel to fade it in as it arrives. The column keeps a
// small inset at its sides in every pane, about the room under the prompt box.
export function reading(children: readonly (Element | null)[], key?: string, top = 0): Element | null {
  // A keyed row glides when the rows above it grow or shrink (a group of
  // tool calls opening or folding up).
  return <div id={key === undefined ? undefined : `transcript-row-${key}`} layoutMotion={key !== undefined} {...column} {...centred} gap="small" padding="small" paddingX={8} paddingY={0} paddingTop={top || undefined} maxWidth={READING_WIDTH}>{children}</div>;
}

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.