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.8
Permissions in 0.2.8
Files
transcript.ts14.8 KB
// Apply agent snapshots and deltas in place without work beyond the affected transcript.
import type { AgentEventKind, Chat, TranscriptItem, UserSession } from "divergence";
import type { Transcript } from "./state.ts";
import { applyTask, findTask, isLive, taskItems } from "./subagents.ts";
import { duration } from "./time.ts";
export type SessionChange = { kind: "handoff" | "session"; from: string; to: string };
// How many times each item changed in place (a delta, a tool's update): a
// row drawn from an item at the same revision is still right (`renderItems`).
const revisions = new WeakMap<TranscriptItem, number>();
export function changed(item: TranscriptItem) {
revisions.set(item, (revisions.get(item) ?? 0) + 1);
}
export function revision(item: TranscriptItem): number {
return revisions.get(item) ?? 0;
}
/// Where the conversation moved to another agent (a handoff) or to a new
/// native session of the same agent, by the id of the first user message
/// sent there. A session id that is not known yet continues the session.
export function sessionChanges(
items: readonly TranscriptItem[],
sessions: Readonly<Record<string, UserSession>>,
): Map<string, SessionChange> {
const changes = new Map<string, SessionChange>();
let previous: UserSession | undefined;
for (const item of items) {
const current = item.role === "user" ? sessions[item.id] : undefined;
if (!current) continue;
if (previous && previous.agentId !== current.agentId)
changes.set(item.id, { kind: "handoff", from: previous.agentId, to: current.agentId });
else if (previous?.sessionId && current.sessionId && previous.sessionId !== current.sessionId)
changes.set(item.id, { kind: "session", from: previous.agentId, to: current.agentId });
previous = current;
}
return changes;
}
/// A user message the host has not archived yet was sent in the chat's
/// current session.
export function noteSession(t: Transcript, item: TranscriptItem, chat: Chat | undefined) {
if (item.role === "user" && chat && !t.sessions[item.id])
t.sessions[item.id] = { agentId: chat.agentId, sessionId: chat.sessionId ?? null };
}
/// A send that creates or recovers its session reports its message
/// before the session exists, so it was noted with the session the chat
/// had then. The change that gives the running chat its new session (same
/// agent) carries the session that message went to. Whether it moved.
export function followSession(t: Transcript, before: Chat | undefined, chat: Chat, running: boolean): boolean {
if (!running || !before || !chat.sessionId || before.agentId !== chat.agentId || before.sessionId === chat.sessionId)
return false;
let last: TranscriptItem | undefined;
for (let i = t.items.length - 1; i >= 0 && !last; i--) if (t.items[i]?.role === "user") last = t.items[i];
const noted = last && t.sessions[last.id];
if (!last || !noted || noted.agentId !== chat.agentId || noted.sessionId !== (before.sessionId ?? null)) return false;
t.sessions[last.id] = { agentId: chat.agentId, sessionId: chat.sessionId };
return true;
}
/// A notice, unless the one above says the same: an agent that reports its
/// error as a notice and again as the turn's failure says it once (as the
/// host's transcript does).
/// Where the compaction the agent is still running sits, or -1.
function runningCompaction(items: TranscriptItem[]): number {
for (let at = items.length - 1; at >= 0; at--) {
const item = items[at];
if (item?.role === "compaction" && item.running) return at;
}
return -1;
}
/// A compaction shows from when it begins, in the row it ends in.
/// An agent reports a compaction as under way more than once (Claude
/// repeats it with the summary's progress): a report while one runs
/// continues that one.
function beginCompaction(items: TranscriptItem[]) {
if (runningCompaction(items) >= 0) return false;
items.push({ id: `compaction-${Date.now()}`, createdAt: new Date().toISOString(), role: "compaction", running: true });
return true;
}
/// Ends the compaction that began, or stands alone when the agent did not
/// say it began.
function endCompaction(items: TranscriptItem[], summary: string | undefined) {
const at = runningCompaction(items);
const begun = at < 0 ? undefined : items[at];
const done = {
id: begun?.id ?? `compaction-${Date.now()}`,
createdAt: begun?.createdAt ?? new Date().toISOString(),
role: "compaction" as const,
...(summary ? { summary } : {}),
};
if (at < 0) items.push(done);
else items[at] = done;
}
/// A compaction its run left unfinished did not happen, so a notice it
/// stood between and its repeat become one.
function dropUnfinishedCompaction(items: TranscriptItem[]) {
const at = runningCompaction(items);
if (at < 0) return;
items.splice(at, 1);
const before = items[at - 1],
after = items[at];
if (before?.role === "notice" && after?.role === "notice" && before.text === after.text) items.splice(at, 1);
}
function pushNotice(t: Transcript, text: string) {
const last = t.items[t.items.length - 1];
if (last?.role === "notice" && last.text === text) return;
t.items.push({ id: `n-${Date.now()}`, createdAt: new Date().toISOString(), role: "notice", text });
}
/// Notices in the host's words, as it stores them (`apply_here` in
/// crates/host/src/model.rs, `run_permit` in crates/host/src/installs.rs):
/// a stopped run, a run that completed right after your message with
/// nothing said, and a message held back while its agent updates.
export const STOPPED = "Stopped.";
const NO_REPLY = "The agent ended the turn without a reply. Check its model and account in Settings.";
const HELD = /^The message is sent once the .+ update finishes\.$/;
/// How a notice reads: a plugin's decision on an approval and a held message
/// are quiet, a stopped run says how long it went, and every other notice is
/// an error (a run that failed, or an error the agent reported).
export function noticeKind(item: Extract<TranscriptItem, { role: "notice" }>): "quiet" | "stopped" | "error" {
if (item.approval || HELD.test(item.text)) return "quiet";
return item.text === STOPPED ? "stopped" : "error";
}
/// An item's time in ms since the epoch, NaN without one. The host stamps an
/// item when it starts (a reply's first words, a tool call's start), so
/// only a notice marks the moment a run ended.
const stamp = (item: TranscriptItem | undefined) => Date.parse(item?.createdAt ?? "");
/// The last message you sent before `index`, the end by default.
function lastMessage(items: readonly TranscriptItem[], index = items.length) {
for (let i = index - 1; i >= 0; i--) {
const item = items[i];
if (item?.role === "user" && item.from == null) return item;
}
return undefined;
}
/// Your message starts a run, which counts from when the host took it; one
/// that joins the run already going (a steer) leaves its start alone.
export function startRun(t: Transcript, item: TranscriptItem) {
if (!t.running) t.started = Number.isNaN(stamp(item)) ? Date.now() : stamp(item);
t.running = true;
}
/// A transcript read from the host: a run still going counts from the first
/// message you sent after the previous run stopped (`previousEnd`, ms; -Infinity
/// when the chat never ran before), unless this plugin saw it start. A steer is
/// stored as a message like any other, so a later one never restarts the
/// count. Without the previous run's end the run counts from your last
/// message, and from nothing without a time.
export function readRun(t: Transcript, previousEnd?: number) {
if (!t.running) {
t.started = undefined;
return;
}
const since = previousEnd === undefined ? undefined : t.items.find((item) => item.role === "user" && item.from == null && stamp(item) > previousEnd);
const at = stamp(since ?? lastMessage(t.items));
t.started ??= Number.isNaN(at) ? undefined : at;
}
export function workingFor(t: Pick<Transcript, "started">, now = Date.now()): string {
return t.started === undefined ? "Working…" : `Working for ${duration(now - t.started)}`;
}
/// How long the run that ended on `item` went, for the row after it: only a
/// run this plugin saw end has one, since nothing stored marks when a run
/// that completed ended.
export function workedFor(t: Transcript, item: TranscriptItem): string | null {
const ms = item.role === "notice" && item.text === STOPPED ? undefined : t.worked.get(item.id);
return ms === undefined ? null : `Worked for ${duration(ms)}`;
}
/// A stopped run, as its notice says it: how long it went, measured while it
/// ran or, read back, from your message to the notice; without both times,
/// only that you stopped it.
export function stoppedAfter(t: Transcript, item: TranscriptItem): string {
const ms = t.worked.get(item.id) ?? stamp(item) - stamp(lastMessage(t.items, t.items.indexOf(item)));
return ms >= 0 ? `You stopped after ${duration(ms)}` : "You stopped the agent.";
}
export function findItem(t: { items: TranscriptItem[] }, id: string | undefined) {
for (let i = t.items.length - 1; i >= 0; i--) if (t.items[i]?.id === id) return t.items[i] ?? null;
return null;
}
export function applyText(
t: { items: TranscriptItem[] },
kind: Extract<AgentEventKind, { event: "text_delta" | "reasoning_delta" }>,
role: "assistant" | "reasoning",
) {
const existing = findItem(t, kind.itemId);
if (existing && (existing.role === "assistant" || existing.role === "reasoning")) {
existing.text = kind.mode === "replace" ? kind.text : existing.text + kind.text;
changed(existing);
} else t.items.push({ id: kind.itemId, createdAt: new Date().toISOString(), role, text: kind.text });
}
export function applyEvent(t: Transcript, kind: AgentEventKind, taskId?: string): boolean {
if (kind.event === "task") {
const { event, ...task } = kind;
const before = task.workflow ? findTask(taskItems(t), task.id)?.task.status : null;
// A task, or a child of one, that started before the loaded rows is
// updated where the page put it, not added again at the end.
const earlier = findTask(t.earlierTasks, task.id) ?? findTask(t.earlierTasks, task.parentTaskId);
applyTask(earlier ? t.earlierTasks : t.items, task);
// A workflow seen finishing gets its burst, once. One read back from
// history has no `before` and stays quiet.
if (before && isLive({ status: before }) && task.status === "completed") (t.finished ??= new Set()).add(task.id);
return true;
}
if (taskId) {
if (kind.event === "approval" || kind.event === "question") kind.taskId ??= taskId;
if (kind.event === "plan" || kind.event === "run_started" || kind.event === "run_finished") return false;
}
// The list the event's items go into.
const task = taskId ? findTask(taskItems(t), taskId) : null;
const scope = task ? { items: (task.items ??= []) } : t;
switch (kind.event) {
case "text_delta":
applyText(scope, kind, "assistant");
return true;
case "reasoning_delta":
applyText(scope, kind, "reasoning");
return true;
case "tool_call_started": {
const { event, ...call } = kind;
call.content ??= [];
call.locations ??= [];
const existing = findItem(scope, call.id);
if (existing?.role === "tool") {
existing.call = call;
changed(existing);
} else scope.items.push({ id: call.id, role: "tool", call });
return true;
}
case "tool_call_updated": {
const item = findItem(scope, kind.id);
if (item?.role !== "tool") return false;
changed(item);
const call = item.call;
if (kind.status !== undefined) call.status = kind.status;
if (kind.title !== undefined) call.title = kind.title;
if (kind.kind !== undefined) call.kind = kind.kind;
if (kind.input !== undefined) call.input = kind.input;
// Some agents (Cline) send a result only here.
if (kind.output !== undefined) call.output = kind.output;
if (kind.content !== undefined) call.content = kind.content;
if (kind.locations !== undefined) call.locations = kind.locations;
// A code mode program's calls so far, replaced whole.
if (kind.calls !== undefined) call.calls = kind.calls;
call.content ??= [];
call.locations ??= [];
if (kind.outputDelta) {
const last = call.content[call.content.length - 1];
if (last?.type === "text") last.text += kind.outputDelta;
else if (last?.type === "terminal") last.output += kind.outputDelta;
else call.content.push({ type: "text", text: kind.outputDelta });
}
return true;
}
// Kept only to place the kernel's card and to know the chat waits.
case "approval": {
const { event, ...req } = kind;
t.approvals = [...t.approvals.filter((a) => a.id !== req.id), req];
return true;
}
case "question": {
const { event, ...req } = kind;
t.questions = [...t.questions.filter((q) => q.id !== req.id), req];
return true;
}
// Answered in another client of the same agent, or withdrawn.
case "approval_resolved": {
const before = t.approvals.length;
t.approvals = t.approvals.filter((a) => a.id !== kind.id);
return t.approvals.length !== before;
}
case "question_resolved": {
const before = t.questions.length;
t.questions = t.questions.filter((q) => q.id !== kind.id);
return t.questions.length !== before;
}
case "plan":
t.plan = { entries: kind.entries };
return true;
// The agent went on by itself, for example after a background task.
case "run_started":
if (!t.running) t.started = Date.now();
t.running = true;
return true;
case "compacting":
return beginCompaction(scope.items);
case "compacted":
endCompaction(scope.items, kind.summary);
return true;
case "run_finished": {
t.running = false;
dropUnfinishedCompaction(t.items);
t.approvals = [];
t.questions = t.questions.filter((q) => q.responseMode === "message");
const outcome = kind.outcome,
last = t.items[t.items.length - 1];
// How the run ended, as the host's copy says it: one that completed
// right after your message is an agent that swallowed its own error.
const said =
outcome.status === "cancelled"
? STOPPED
: outcome.status === "failed"
? outcome.message
: last?.role === "user" && last.from == null
? NO_REPLY
: null;
if (said !== null) pushNotice(t, said);
// How long it went, by the row it ended on (its last reply or tool
// call, or the notice of a stop); a failure and a silent end say enough.
const end = t.items[t.items.length - 1];
if (end && t.started !== undefined && (said === null || said === STOPPED)) t.worked.set(end.id, Date.now() - t.started);
t.started = undefined;
return true;
}
case "notice":
if (kind.level === "error") {
pushNotice(t, kind.message);
return true;
}
return false;
default:
return false;
}
}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.