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.7
Permissions in 0.2.7
Files
views/rows.tsx48.1 KB
// Rows rendering preserves the chat's retained tree and interaction keys.
import * as z from "zod";
import { editStats, groupTitle, foldItems } from "../grouping.ts";
import { groupTasks, stillWorking, withoutSpawnRows } from "../subagents.ts";
import { knownKey, knownTokens, markedMessage } from "../message-text.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 { 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 type { Unsent } from "../window.ts";
import { 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,
RAISED,
corner,
} from "./styles.tsx";
import { changesOpen, turnCard, withTurnEnd } from "./changes.tsx";
import { summariesAt } from "../changes.ts";
/** The space above and below a group of tool calls, and the live line at the end that is spaced like one. */
const GROUP_SPACE = 4;
/** What the card that ends a turn adds to a reply's own gap ("small", 3.75), so it sits as far below the reply's text
* as a group of tool calls does (the reply's 8 and the group's 4). */
const TURN_END_SPACE = 8 + GROUP_SPACE - 3.75;
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");
}
/** A prompt's type: the user's messages and the prompts agents give subagents read alike. */
export const PROMPT_TEXT = { fontSize: 13.125, lineHeight: 21.3 } as const;
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): Element[] {
const open = t.expanded.has(key);
return [
<div {...column} minWidth={0} lineHeight={PROMPT_TEXT.lineHeight} clampLines={PROMPT_LINES} clampOpen={open} onClamp={(e: { clamped: boolean }) => v.controller.noteClamp(t.clamped, key, e.clamped)}>{body}</div>,
t.clamped.has(key) ? <div {...row}><button id={moreId} label={open ? "Show less" : "Read more"} variant="ghost" small onClick={() => v.controller.toggle(t.expanded, key)} /></div> : null,
].filter((element): element is Element => element !== null);
}
/** What the user wrote, as the transcript shows it: a raised bubble, laid at the column's right edge by its row. */
export function bubble(children: Element[], props: { id?: string; travels?: boolean } = {}): Element {
return <div {...column} {...props} gap="small" padding="small" paddingX={11} paddingY="medium" minWidth={0} maxWidth={600} background="bubble" {...PROMPT_TEXT} borderRadius="xl" {...RAISED}>{children}</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 chat = v.controller.state.chats[chatId];
const running = pending || t.running || !!t.resending || t.loading || v.controller.isRunning(chat);
// The host refuses an edit the agent cannot rewind its own conversation for.
const editable = !!(chat && v.controller.state.agents[chat.agentId]?.capabilities?.rollback);
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);
// 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);
// Under the bubble, the buttons that come and go (Revert, whose space is
// kept so the row does not reflow, and Edit, both offered only while
// nothing runs, since the host refuses them then) sit on the left, so Copy
// stays put on the bubble's edge. There is no Reply: next to Revert it
// read as a second undo.
return (
<div {...column} group="hover" padding="small" paddingY="small" alignItems="end">
{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} />),
...stored.map(
(image) =>
<image path={image.path} pixelWidth={image.width} pixelHeight={image.height} maxHeight={360} radius={MESSAGE_IMAGE_RADIUS} />,
),
].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}
{text ? bubble(clampedPrompt(v, t, item.id, `message-more-${item.id}`, <markdown id={`md-${item.id}`} text={keepLineBreaks(markedMessage(text, item.blocks, knownTokens(v.controller, chatId)))} />), { id: rising ? `rising-${chatId}` : undefined, travels: rising }) : null}
<div {...row} {...full} gap="small" paddingY="small" paddingX={0} marginRight={-5} justifyContent="end">
{sentAtLabel(item, true)}
<div visibility={!running && !departing && t.checkpoints.has(item.id) ? "visible" : "hidden"}>
<button id={`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))} />
</div>
{running || !editable || t.editing
? null
: (
<button id={`edit-${item.id}`} icon="pencil" variant="ghost" small tooltip="Edit this message and run again from here" onClick={() => {
t.editing = item.id;
t.editText = v.controller.plainText(item.blocks);
v.controller.view.update();
}} />
)}
{text ? messageActions(v, chatId, t, item.id, text, { reply: false }) : null}
</div>
</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.
export function renderReceived(v: ChatView, chatId: string, t: Transcript, item: UserItem, from: string): Element {
const text = v.controller.plainText(item.blocks);
return (
<div {...column} group="hover" gap="small" padding="small" paddingY="small" alignItems="start">
<div {...row} padding={0} paddingX={5}>
<text style="body" size="xs" weight={560} lineHeight={14.6} tone="muted">{`From ${from}`}</text>
</div>
<div {...column} gap="small" padding="small" paddingX={11} paddingY="medium" maxWidth={600} background="card" fontSize={13.125} lineHeight={21.3} borderRadius="xl" {...RAISED}><markdown id={`md-${item.id}`} text={keepLineBreaks(text)} /></div>
<div {...row} {...revealOnHover} gap="small" padding={0}>{messageActions(v, chatId, 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.
export function renderAssistant(v: ChatView, chat: Chat, item: TextItem, end?: string | null, turn?: TurnSummary): 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);
// The card with the time of a run that ended here and what the turn
// changed leads the action row and stays in view, so the turn ends in one
// line and the buttons wait for the pointer.
const card = turnCard(v, chat, t, item.id, workedFor(t, item), turn);
return (
<div {...column} group="hover" gap="small" padding="small" paddingX={5} paddingY={8} fontSize={13.125} lineHeight={18.75}>
<markdown id={`md-${item.id}`} text={item.text} onQuote={onQuote} />
{end === undefined && !card
? null
: (
<div {...row} gap={card ? "medium" : "small"} padding={0} marginLeft={-5} marginTop={card ? TURN_END_SPACE : 0}>
{card}
{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>
)}
</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 }: { reply?: boolean; fork?: string | null } = {},
): 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={`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. Under your
// own message the buttons always show, so there the time alone waits for
// the pointer (`reveal`).
function sentAtLabel(item: TranscriptItem, reveal = false): Element | null {
const at = sentAt(item.createdAt);
if (!at) return null;
return <div id={`sent-${item.id}`} {...reveal ? revealOnHover : null} 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") {
parts.push(<text style="body" size="xs" tone="muted">{c.path ? `Image: ${c.path}` : "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;
}
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 ?? 0) > 0 || 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>;
// A command that is still running spins where its terminal icon goes.
const running = call.kind === "execute" && !call.message && (call.status === "pending" || call.status === "running");
const icon = running
? <spinner activity />
: call.message
? "send"
: (TOOL_ICONS[call.kind ?? "other"] ?? "cpu");
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 })}
{body}
</div>
);
}
export function renderPlan(plan: Plan): Element | null {
const icon = { pending: "circle", in_progress: "loader", completed: "circle-check" };
const tone = { pending: "faint", in_progress: "info", completed: "success" };
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,
): Element | null {
switch (item.role) {
case "user":
return (
<div {...column} padding="small">
<div {...row} gap="small" padding="small" height={12} />
{item.from != null ? renderReceived(v, chat.id, t, item, item.from) : renderUser(v, chat.id, t, item, pending)}
</div>
);
case "assistant":
return renderAssistant(v, chat, item, end, turn);
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={8}>{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;
// The title starts on the same line as the reply text (both inset 5).
return (
<div {...column} gap={2} padding="small" paddingX={0} paddingY={GROUP_SPACE}>
{activityRow({
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>
);
}
// 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;
}
// A chat's rows from its last render, by entry id, with what each was drawn
// from. A row drawn from the same inputs is the same element, so unchanged
// subtrees are not rebuilt or diffed; grouping and input checks still scan items.
type KeptItem = { inputs: unknown[]; row: Element | null };
type KeptRow = KeptItem & { children?: Map<string, KeptItem> };
const keptRows = new WeakMap<Transcript, { shared: unknown[]; rows: Map<string, KeptRow> }>();
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),
];
}
// 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 groupTasks>[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 = groupTasks(groupTools ? foldItems(shown) : shown.map((item) => ({ kind: "item", item })));
// 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 shared = keep ? sharedInputs(v, chat, t, shown, groupTools) : [];
const before = keep ? keptRows.get(t) : 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 inputs = keep ? entryInputs(v, t, entry, change, last, end) : null;
inputs?.push(turn, turn && changesOpen(t, turn));
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 = 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, rendered, card, turn);
const row =
entry.kind === "item"
? keyed(withSessionChange(v, change, closed(renderItem(v, chat, t, entry.item, undefined, false, end, turn))), entry.item.id)
: keyed(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) keptRows.set(t, { shared, rows: next });
if (unsent) {
const placed = windowRequests(entries, range, requests, unsent);
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, groupTasks(groupTools ? foldItems(shown) : shown.map((item) => ({ kind: "item", item }))), 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;
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(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.
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(workingRow(background), "working"));
else if (t.resending) rows.push(keyed(live(activityRow({ icon: <spinner />, label: "Sending again…" })), "resending"));
else if (outgoing?.preview) rows.push(keyed(live(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 the scroller asks for the page before it.
const older = t.start > 0 ? () => v.ctx.run(v.controller.loadOlder(chatId)) : 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;
return (
<scroller id={`transcript-${chatId}`} toEnd={sent ? String(sent) : undefined} onReachStart={older} onRange={range} rowsBefore={unsent?.before || undefined} rowsAfter={unsent?.after || undefined}>
{rows.map(readingRow)}
{footer ? <slot name="footer">{footer}</slot> : null}
</scroller>
);
}
/** A live line at the end of a transcript, spaced as a group of tool calls is, so it sits as far below the reply as a
* group would. */
const live = (row: Element | null) => <div {...column} padding={0} paddingY={GROUP_SPACE}>{row}</div>;
/** "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) => live(activityRow({ icon: <spinner activity />, label }));
// A row in the reading column; a kept row keeps its column too.
const readingRows = new WeakMap<Element, Element | null>();
function readingRow(row: Element | null): Element | null {
if (!row) return reading([row]);
let placed = readingRows.get(row);
if (placed === undefined) readingRows.set(row, (placed = reading([row], rowKeys.get(row))));
return placed;
}
// `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): 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} maxWidth={READING_WIDTH}>{children}</div>;
}Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.9latest | Nov 21, 2026 | >=5 <6 | 349 KB | 5 permissions | Listed |
| 0.2.8 | Nov 16, 2026 | >=5 <6 | 348.6 KB | 5 permissions | Listed |
| 0.2.7 | Nov 11, 2026 | >=5 <6 | 314.3 KB | 5 permissions | Listed |
| 0.2.6 | Nov 9, 2026 | >=5 <6 | 306.2 KB | 5 permissions | Listed |
| 0.2.5 | Oct 27, 2026 | >=2 <4 | 178.6 KB | 5 permissions | Listed |
No comments yet.