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

  • 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

transcript.test.ts31.1 KB
// Regression coverage for transcript using the real chat modules.
// Fixtures exercise the same behavior and assertions as the JavaScript tests.
import { item as fixtureItem } from "./ui-for-tests.test.ts";
import assert from "node:assert/strict";
import test from "node:test";
import type { TestNode } from "./ui-for-tests.test.ts";
import { harness, tree, nodes, chat as makeChat, transcript as initial } from "./ui-for-tests.test.ts";
import { applyEvent, noteSession, sessionChanges } from "./transcript.ts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import { HostCallFailed } from "divergence/effect";
import { InputLedger, withController } from "./testing.ts";
import { onChatChanged } from "./events.ts";
import {
  renderTool as toolView,
  renderReasoning as reasoningView,
  renderFold as foldView,
  renderUser,
  renderItems,
  renderTranscript,
  keepLineBreaks,
  groupIcon,
} from "./views/rows.tsx";
import type { Transcript, ToolItem, TextItem, UserItem } from "./state.ts";
import type { ToolGroup } from "./grouping.ts";
import type { Chat, TranscriptItem } from "divergence";
const h = harness(),
  renderers = h.renderers;
const renderTool = (t: Transcript, item: ToolItem, chat: Chat, folded?: boolean) =>
  tree(toolView(h.v, t, item, chat, folded));
const renderReasoning = (t: Transcript, item: TextItem, folded?: boolean) => tree(reasoningView(h.v, t, item, folded));
const renderFold = (chat: Chat, t: Transcript, entry: ToolGroup, last?: boolean) =>
  tree(foldView(h.v, chat, t, entry, last));
// A row and what it opens: the activity row, then the body when open.
const header = (node: import("./ui-for-tests.test.ts").TestNode) => node.children[0];
const body = (node: import("./ui-for-tests.test.ts").TestNode) => node.children[1];
const transcript = initial;
const start = (t: Transcript, id = "tool") =>
  applyEvent(t, {
    event: "tool_call_started",
    content: [],
    locations: [],
    id,
    name: "test",
    kind: "execute",
    title: "Run test",
    status: "running",
    input: {},
  });

test("tools default closed and preserve manual expansion across every status", () => {
  for (const status of ["running", "completed", "failed", "cancelled"] as const) {
    for (const manual of [false, true]) {
      const t = transcript();
      start(t);
      assert.equal(body(renderTool(t, t.items[0] as ToolItem, makeChat())), undefined);
      if (manual) header(renderTool(t, t.items[0] as ToolItem, makeChat())).onClick();
      start(t); // A repeated snapshot must not change the user's choice.
      applyEvent(t, { event: "tool_call_updated", id: "tool", status, outputDelta: "output" });
      assert.equal(t.expanded.has("tool"), manual);
      assert.equal(body(renderTool(t, t.items[0] as ToolItem, makeChat())) !== undefined, manual);
    }
  }
});

test("a picture a tool gave back shows as a thumbnail under the closed row and in the card once the row opens", () => {
  const t = transcript();
  applyEvent(t, {
    event: "tool_call_started",
    content: [{ type: "image", mimeType: "image/png", path: "/work/shot.png", width: 40, height: 20 }],
    locations: [],
    id: "read",
    name: "Read",
    kind: "read",
    title: "Read /work/shot.png",
    status: "completed",
    input: { file_path: "/work/shot.png" },
  });
  type Picture = { path: string; maxHeight: number; zoomable: boolean };
  const pictures = () =>
    nodes(renderTool(t, t.items[0] as ToolItem, makeChat())).filter((node) => node.type === "image") as unknown as Picture[];
  const thumbnail = pictures();
  assert.deepEqual(thumbnail.map((node) => node.path), ["/work/shot.png"], "the closed row shows the picture");
  assert.equal(thumbnail[0]!.maxHeight, 72, "as a thumbnail");
  assert.equal(thumbnail[0]!.zoomable, true, "which opens full size on a click");
  header(renderTool(t, t.items[0] as ToolItem, makeChat())).onClick();
  const open = pictures();
  assert.deepEqual(open.map((node) => node.path), ["/work/shot.png"], "the open card shows it once, not twice");
  assert.equal(open[0]!.maxHeight, 240);
});

test("a group is open while it is last, closes once something follows it, and keeps the user's choice", () => {
  const t = transcript();
  start(t);
  const entry: ToolGroup = { kind: "tools", id: "group", items: t.items };
  assert.notEqual(body(renderFold(makeChat(), t, entry, true)), undefined);
  assert.equal(body(renderTool(t, t.items[0] as ToolItem, makeChat(), true)), undefined);
  start(t, "second");
  assert.notEqual(body(renderFold(makeChat(), t, entry, true)), undefined);
  // Text after the group ends it.
  assert.equal(body(renderFold(makeChat(), t, entry, false)), undefined);
  header(renderFold(makeChat(), t, entry, false)).onClick();
  assert.notEqual(body(renderFold(makeChat(), t, entry, false)), undefined);
  // A group the user closed while it was active stays closed.
  const other: ToolGroup = { kind: "tools", id: "other", items: t.items };
  header(renderFold(makeChat(), t, other, true)).onClick();
  assert.equal(body(renderFold(makeChat(), t, other, true)), undefined);
  assert.equal(t.expanded.size, 0);
});

test("a long tool group title yields to its edit totals", () => {
  const items = (["read", "edit", "execute", "search"] as const).flatMap((kind) =>
    Array.from({ length: 125 }, (_, i) =>
      fixtureItem({
        id: `${kind}-${i}`,
        role: "tool",
        call: {
          kind,
          content: kind === "edit" && i === 0 ? [{ type: "diff", path: "file", diff: "+new\n-old\n" }] : [],
        },
      }),
    ),
  );
  const entry: ToolGroup = { kind: "tools", id: "group", items };
  const line = header(renderFold(makeChat(), transcript(items), entry, false));
  // The group's icon leads the line, as a single tool row's does.
  const [icon, content] = line.children;
  assert.equal(icon.children[0]?.name, "file-text");
  assert.equal(content.minWidth, 0);
  assert.equal(content.flexShrink, 1);
  assert.equal(content.children[0]?.text, "125 Reads, 125 Edits, 125 Runs, 125 Searches");
  assert.equal(content.children[0]?.truncate, true, "the title ellipsizes in a narrow pane");
  assert.equal(content.children[1]?.flexShrink, 0, "the edit totals keep their width");
  assert.deepEqual(content.children[1]?.children.map((node) => node.text), ["+1", "-1"]);
});

test("a growing tool group keeps one tail-following scroll container", () => {
  const t = transcript();
  start(t);
  const entry: ToolGroup = { kind: "tools", id: "group", items: t.items };
  const first = body(renderFold(makeChat(), t, entry, true));
  assert.equal(first.id, "fold-scroll-group");
  assert.equal(first.followEnd, true);

  start(t, "second");
  entry.items = t.items;
  const second = body(renderFold(makeChat(), t, entry, true));
  assert.equal(second.id, first.id);
  assert.equal(second.followEnd, true);
});

test("grouped thoughts and tools share their horizontal and vertical insets", () => {
  const t = transcript();
  start(t);
  const thought = fixtureItem({ id: "thought", role: "reasoning", text: "Reviewing the output" });
  t.items.push(thought);
  const tool = renderTool(t, t.items[0] as ToolItem, makeChat(), true);
  for (const running of [true, false]) {
    t.running = running;
    const reasoning = renderReasoning(t, thought, true);
    assert.equal(reasoning.padding, tool.padding);
    assert.equal(reasoning.paddingY, tool.paddingY);
    assert.equal(header(reasoning).paddingX, header(tool).paddingX);
    assert.equal(header(reasoning).paddingY, header(tool).paddingY);
  }
  // Opened, a thought and a tool call sit at the same inset.
  t.expanded.add("tool");
  t.expanded.add("thought");
  const openTool = renderTool(t, t.items[0] as ToolItem, makeChat(), true);
  const openThought = renderReasoning(t, thought, true);
  assert.equal(body(openThought).paddingX, body(openTool).paddingX);
  assert.equal(body(openThought).paddingY, body(openTool).paddingY);
});

test("tool calls show their icon only in a fold; thoughts show none", () => {
  const t = transcript();
  start(t);
  // A finished call: one that runs shows its spinner in the icon's place.
  (t.items[0] as ToolItem).call.status = "completed";
  const thought = fixtureItem({ id: "thought", role: "reasoning", text: "Reviewing the output" });
  t.items.push(thought);
  // The icons of a row's activity line, the chevron that opens it aside.
  const icons = (row: import("./ui-for-tests.test.ts").TestNode) =>
    nodes(header(row))
      .filter((n) => n.type === "icon" && !n.name.startsWith("chevron"))
      .map((n) => n.name);
  for (const folded of [true, false]) {
    assert.deepEqual(icons(renderTool(t, t.items[0] as ToolItem, makeChat(), folded)), folded ? ["square-terminal"] : []);
    assert.deepEqual(icons(renderReasoning(t, thought, folded)), []);
  }
});

test("a group shows the icon its calls show most on their own rows, and thinking's when it holds only thoughts", () => {
  const call = (id: string, kind: string, message?: boolean): TranscriptItem =>
    ({ id, role: "tool", call: { id, kind, title: id, status: "completed", ...(message ? { message: { to: "other" } } : {}) } }) as TranscriptItem;
  const thought = fixtureItem({ id: "thought", role: "reasoning", text: "Thinking" });
  assert.equal(groupIcon([call("a", "read"), call("b", "execute"), call("c", "execute")]), "square-terminal");
  assert.equal(groupIcon([thought, call("a", "read"), call("b", "search")]), "file-text", "a tie goes to the first");
  assert.equal(groupIcon([call("a", "other", true)]), "send");
  assert.equal(groupIcon([thought]), "brain");
});

test("a tool another plugin renders is left to that plugin", () => {
  const t = transcript();
  start(t);
  renderers.push({ plugin: "bash-cards", name: "test", kind: null });
  try {
    const row = renderTool(t, t.items[0] as ToolItem, makeChat());
    assert.deepEqual(row, { type: "tool_view", call: (t.items[0] as ToolItem).call, id: "tool" });
  } finally {
    renderers.length = 0;
  }
  assert.equal(renderTool(t, t.items[0] as ToolItem, makeChat()).type, "div", "without a renderer the chat draws it");
});

assert.equal(typeof applyEvent, "function", "the imported implementation is available");

// Cline sends a command's result only as structured output. The live
// reducer dropped it, and the open row showed the command's input instead.
test("a tool update's output reaches the row", () => {
  const t = transcript();
  start(t);
  applyEvent(t, { event: "tool_call_updated", id: "tool", status: "completed", output: "a.txt\nb.txt" });
  const item = t.items[0] as ToolItem;
  assert.equal(item.call.output, "a.txt\nb.txt");
  header(renderTool(t, item, makeChat())).onClick();
  const shown = JSON.stringify(body(renderTool(t, item, makeChat())));
  assert.ok(shown.includes("a.txt\\nb.txt"), "the text itself, not its JSON form");
  assert.ok(!shown.includes('\\"a.txt'), "not quoted");
});

// A prompt's single line breaks stay line breaks; Markdown alone would join
// them into spaces. Code fences keep their lines untouched.
test("a sent prompt keeps its line breaks", () => {
  assert.equal(keepLineBreaks("one\ntwo\n\nthree"), "one  \ntwo\n\nthree");
  assert.equal(keepLineBreaks("see:\n```\na\nb\n```\nend"), "see:  \n```\na\nb\n```\nend");
  // A reply typed under a quote is not part of the quote; a quote's own
  // lines stay one quote.
  assert.equal(keepLineBreaks("> quoted\nmy reply"), "> quoted\n\nmy reply");
  assert.equal(keepLineBreaks("> one\n> two\nreply"), "> one  \n> two\n\nreply");
  const { v } = harness();
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "first\nsecond" }] };
  const shown = JSON.stringify(tree(renderUser(v, "c", { ...transcript([user]), running: false }, user)));
  assert.ok(shown.includes("first  \\nsecond"));
});

test("a sent prompt follows the subagent prompt's rule: Read more only when five lines cut it off", () => {
  const { v } = harness();
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "one\ntwo\nthree\nfour\nfive\nsix" }] };
  const t = { ...transcript([user]), running: false };
  const shown = () => nodes(tree(renderUser(v, "c", t, user)));
  const clamp = () => shown().find((node) => node.clampLines === 5);
  const more = () => shown().find((node) => node.id === "message-more-u1");
  assert.equal(clamp()?.clampOpen, false);
  assert.equal(more(), undefined, "six typed lines alone do not decide it");
  (clamp()?.onClamp as (event: { clamped: boolean }) => void)({ clamped: true });
  assert.equal(more()?.label, "Read more");
  more()?.onClick();
  assert.equal(clamp()?.clampOpen, true);
  assert.deepEqual(t.scrollTo, { id: "transcript-row-u1", revision: 1, inset: 20 });
  assert.equal(more()?.label, "Show less");
  (clamp()?.onClamp as (event: { clamped: boolean }) => void)({ clamped: false });
  assert.equal(more(), undefined, "a prompt that fits is never offered Read more");
});

test("a sent prompt carries the copy that stays at the top while its reply scrolls: its bubble and row, in glass", () => {
  const { v } = harness();
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "one\ntwo\nthree\nfour\nfive\nsix" }], createdAt: new Date().toISOString() };
  const t = { ...transcript([user]), running: false };
  t.checkpoints.add("u1");
  v.controller.state.chats.c = makeChat({ agentId: "acp" });
  v.controller.state.agents.acp = { id: "acp", name: "ACP", capabilities: { rollback: true } } as never;
  const all = (node: unknown, out: TestNode[] = []): TestNode[] => {
    if (!node || typeof node !== "object") return out;
    if (Array.isArray(node)) {
      for (const child of node) all(child, out);
      return out;
    }
    out.push(node as TestNode);
    return all((node as TestNode).children, out);
  };
  const row = () => tree(renderUser(v, "c", t, user)) as TestNode;
  const sticky = () => all(row()).find((node) => node.type === "sticky")!;
  const pinned = () => all(sticky());
  assert.equal(sticky().top, 20, "it rests below the transcript's top fade");
  // Laid out as its row is, so it lands on the row exactly.
  const column = (node: TestNode) => ({ padding: node.padding, paddingY: node.paddingY, alignItems: node.alignItems });
  assert.deepEqual(column((sticky().children as TestNode[])[0].children![0]), column(row()));
  const prompt = pinned().find((node) => node.type === "markdown");
  assert.equal(prompt?.text, nodes(row()).find((node) => node.type === "markdown")?.text, "the same prompt");
  assert.equal(prompt?.id, undefined, "the copy keeps no state of its own");
  assert.ok(pinned().some((node) => node.type === "bubble" && node.backdrop), "the bubble is glass");
  const content = pinned();
  const pinnedBubble = content.find((node) => node.type === "bubble")!;
  const target = all(pinnedBubble).find((node) => node.id === "pinned-prompt-u1")!;
  assert.equal(target.cursor, "default");
  assert.deepEqual(target.hover, { background: "hover" });
  assert.equal(target.borderRadius, "xl");
  const wrapper = content.find((node) => node.maxWidth === 600 && node.alignItems === "end" && all(node.children).includes(pinnedBubble))!;
  assert.equal(wrapper.alignItems, "end");
  assert.equal(wrapper.maxWidth, 600);
  assert.deepEqual(
    pinned().flatMap((node) => (node.id ? [node.id] : [])),
    ["pinned-prompt-u1", "pinned-sent-u1", "pinned-restore-u1", "pinned-edit-u1", "pinned-copy-u1"],
    "it has the row's time and buttons, with ids of its own",
  );
  (pinned().find((node) => node.id === "pinned-edit-u1")?.onClick as () => void)();
  assert.equal(t.editing, "u1", "Edit on the copy edits the message");
  t.editing = null;
  const clamp = pinned().find((node) => node.clampLines === 5);
  assert.ok(clamp?.onClamp, "the pinned copy measures even when the original is unloaded");
  const original = nodes(row()).find((node) => node.clampLines === 5);
  (original?.onClamp as (event: { clamped: boolean }) => void)({ clamped: true });
  assert.equal(pinned().find((node) => node.id === "pinned-more-u1"), undefined);
  assert.ok(pinned().some((node) => node.type === "text" && node.text === "…"));
  assert.equal(pinned().find((node) => node.clampLines === 5)?.clampOpen, undefined);
});

test("a chat's first row starts below the top fade, and a message opened for editing comes into view", () => {
  const { v } = harness();
  const chat = makeChat();
  v.controller.state.chats[chat.id] = chat;
  const t = v.controller.transcript(chat.id);
  t.items = [{ id: "u1", role: "user", blocks: [{ type: "text", text: "hello" }] }, { id: "a1", role: "assistant", text: "hi" }];
  t.snapshot = { kind: "ready" };
  const scroller = () => nodes(renderTranscript(v, chat)).find((node) => node.type === "scroller")!;
  assert.deepEqual(scroller().items!.map((row) => row.paddingTop), [20, undefined]);
  t.editing = "u1";
  assert.equal(scroller().reveal, "transcript-row-u1");
});

test("clicking a pinned prompt reads older history and goes to its original row on every click", async () => {
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "A long prompt" }] };
  const h = harness((method) => method === "host/chats.transcript"
    ? Effect.succeed({ items: [user], start: 0, userSessions: {}, pendingApprovals: [], pendingQuestions: [] })
    : undefined);
  h.controller.state.chats.c = makeChat();
  const t = h.controller.transcript("c");
  t.items = [{ id: "a1", role: "assistant", text: "reply" }];
  t.start = 1;
  t.snapshot = { kind: "ready" };
  const all = (node: unknown): TestNode[] => {
    if (!node || typeof node !== "object") return [];
    if (Array.isArray(node)) return node.flatMap(all);
    return [node as TestNode, ...all((node as TestNode).children)];
  };
  const click = () => all(all(renderUser(h.v, "c", t, user)).find((node) => node.type === "sticky")).find((node) => node.onClick)?.onClick();
  try {
    click();
    await h.settle();
    assert.equal(t.start, 0);
    assert.deepEqual(t.scrollTo, { id: "transcript-row-u1", revision: 1, inset: 20 });
    click();
    await h.settle();
    assert.deepEqual(t.scrollTo, { id: "transcript-row-u1", revision: 2, inset: 20 });
  } finally { await h.close(); }
});

test("clicking a pinned prompt waits for an older page already being read", async () => {
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "prompt" }] };
  const ready = Deferred.makeUnsafe<void>();
  const h = harness();
  h.controller.state.chats.c = makeChat();
  const t = h.controller.transcript("c");
  t.items = [{ id: "a1", role: "assistant", text: "reply" }];
  t.start = 1;
  t.olderReady = ready;
  const all = (node: unknown): TestNode[] => {
    if (!node || typeof node !== "object") return [];
    if (Array.isArray(node)) return node.flatMap(all);
    return [node as TestNode, ...all((node as TestNode).children)];
  };
  const pinned = all(renderUser(h.v, "c", t, user)).find((node) => node.type === "sticky");
  try {
    all(pinned).find((node) => node.onClick)?.onClick();
    await new Promise<void>((resolve) => setImmediate(resolve));
    assert.equal(t.scrollTo, undefined);
    t.items.unshift(user);
    t.start = 0;
    t.olderReady = undefined;
    Effect.runSync(Deferred.succeed(ready, undefined));
    await h.settle();
    assert.deepEqual(t.scrollTo, { id: "transcript-row-u1", revision: 1, inset: 20 });
  } finally { await h.close(); }
});

test("a message offers Edit only when its agent can rewind its own conversation", () => {
  const { v } = harness();
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "hello" }] };
  const t = { ...transcript([user]), running: false };
  v.controller.state.chats.c = makeChat({ agentId: "acp" });
  for (const [capabilities, shown] of [
    [{}, false],
    [{ rollback: false }, false],
    [{ rollback: true }, true],
  ] as const) {
    v.controller.state.agents.acp = { id: "acp", name: "ACP", capabilities } as never;
    const ids = nodes(tree(renderUser(v, "c", t, user))).map((node) => node.id);
    assert.equal(ids.includes("edit-u1"), shown, JSON.stringify(capabilities));
  }
});

test("Revert and Edit wait for the run to end, and no other message offers Edit while one is being edited", () => {
  const { v } = harness();
  const user: UserItem = { id: "u1", role: "user", blocks: [{ type: "text", text: "hello" }] };
  const t = { ...transcript([user]), running: true };
  t.checkpoints.add("u1");
  v.controller.state.chats.c = makeChat({ agentId: "acp" });
  v.controller.state.agents.acp = { id: "acp", name: "ACP", capabilities: { rollback: true } } as never;
  const shown = () => nodes(tree(renderUser(v, "c", t, user))).flatMap((node) => (node.id ? [node.id] : []));
  const revert = () => shown().includes("restore-u1");
  const edit = () => shown().includes("edit-u1");
  assert.deepEqual([revert(), edit()], [false, false], "the host would refuse both while the agent works");
  const row = nodes(tree(renderUser(v, "c", t, user))).find((node) => node.children?.some((child) => child?.id === "copy-u1"));
  assert.deepEqual(row?.children?.filter(Boolean).map((child) => child.id), ["copy-u1"], "the row closes up toward Copy, keeping no room for them");
  t.running = false;
  assert.deepEqual([revert(), edit()], [true, true]);
  t.editing = "u0";
  assert.equal(edit(), false, "another message's half-typed edit is not thrown away");
});

// A divider sits above the first message sent to another agent (a handoff)
// or to a new native session of the same agent, and nowhere else.
const say = (id: string): UserItem => ({ id, role: "user", blocks: [{ type: "text", text: id }] });
const at = (agentId: string, sessionId: string | null) => ({ agentId, sessionId });
test("dividers mark handoffs and new sessions between user messages only", () => {
  const items = [
    say("u1"),
    { id: "r1", role: "assistant", text: "reply" },
    say("u2"),
    say("u3"),
    { id: "r3", role: "assistant", text: "reply" },
    say("u4"),
    say("u5"),
    say("u6"),
    say("u7"),
  ] as TranscriptItem[];
  const changes = sessionChanges(items, {
    u1: at("a", "s1"),
    u2: at("a", "s1"),
    u3: at("b", "sb"),
    u4: at("b", "sb2"),
    // Not known yet (a first send that creates its session): the same session.
    u5: at("b", null),
    u6: at("b", "sb2"),
    u7: at("a", "s1"),
  });
  assert.deepEqual(Object.fromEntries(changes), {
    u3: { kind: "handoff", from: "a", to: "b" },
    u4: { kind: "session", from: "b", to: "b" },
    u7: { kind: "handoff", from: "b", to: "a" },
  });
  // An older host reports no sessions: no dividers.
  assert.equal(sessionChanges(items, {}).size, 0);
});

test("the divider shows the old and new agent above the message, and a live message after a handoff gets one", () => {
  const t = initial([say("u1"), { id: "r1", role: "assistant", text: "reply" } as TranscriptItem]);
  t.running = false;
  t.sessions = { u1: at("a", "s1") };
  h.controller.state.agents.a = { id: "a", name: "A", icon: "<svg id='a'/>" } as never;
  h.controller.state.agents.b = { id: "b", name: "B", icon: "<svg id='b'/>" } as never;
  const handedOff = makeChat({ agentId: "b", sessionId: "sb" });
  const u2 = say("u2");
  t.items.push(u2);
  noteSession(t, u2, handedOff);
  const rows = renderItems(h.v, handedOff, t, t.items);
  const texts = (row: unknown) => nodes(row).flatMap((node) => (typeof node.text === "string" ? [node.text] : []));
  assert.equal(rows.length, 3);
  assert.ok(!texts(rows[0]).includes("Handed off"));
  const divider = nodes(rows[2]);
  assert.deepEqual(
    divider.filter((node) => node.type === "icon" && node.svg).map((node) => node.svg),
    ["<svg id='a'/>", "<svg id='b'/>"],
  );
  const shown = texts(rows[2]);
  assert.ok(shown.indexOf("Handed off") < shown.indexOf("u2"), "the divider is above the message");
  // The same agent in a new session.
  const u3 = say("u3");
  t.items.push(u3);
  noteSession(t, u3, makeChat({ agentId: "b", sessionId: "sb2" }));
  const again = renderItems(h.v, handedOff, t, t.items);
  assert.ok(texts(again[3]).includes("New session"));
  assert.equal(texts(again).filter((text) => text === "Handed off").length, 1);
});

/// A send that creates or recovers its session reports its message before
/// the session exists; the chat's change to the new session moves the
/// message there, so the "New session" divider shows live, not only after
/// a reload. A change of a chat that is not running moves nothing.
test("a send that recovers its session shows the New session divider live", async () => {
  await withController(new InputLedger(), (c) =>
    Effect.gen(function* () {
      const before = makeChat({ id: "c1", agentId: "a", sessionId: "s1", status: "running" });
      c.state.chats.c1 = before;
      const t = initial([say("u1"), { id: "r1", role: "assistant", text: "reply" } as TranscriptItem]);
      t.sessions = { u1: at("a", "s1") };
      c.state.transcripts.c1 = t;
      const u2 = say("u2");
      t.items.push(u2);
      noteSession(t, u2, before);
      assert.equal(sessionChanges(t.items, t.sessions).size, 0);
      yield* onChatChanged(c, { event: "chat_changed", chat: { ...before, sessionId: "s2" } });
      assert.deepEqual(Object.fromEntries(sessionChanges(t.items, t.sessions)), {
        u2: { kind: "session", from: "a", to: "a" },
      });
      yield* onChatChanged(c, { event: "chat_changed", chat: { ...before, sessionId: "s3", status: "idle" } });
      assert.deepEqual(t.sessions.u2, at("a", "s2"));
    }),
  );
});

/// A code mode program's calls come with the updates of its `execute`
/// call; opened, the row shows one row per call, its input and how it
/// ended, in a card above the program.
test("an execute row shows the calls its program made", () => {
  const t = transcript();
  applyEvent(t, {
    event: "tool_call_started",
    content: [],
    locations: [],
    id: "x",
    name: "execute",
    kind: "other",
    title: "Run plugin tools",
    status: "running",
    input: { code: "return await tools.weather.forecast({ city: 'Oslo' })" },
  });
  applyEvent(t, {
    event: "tool_call_updated",
    id: "x",
    calls: [
      { tool: "weather.forecast", status: "completed", input: { city: "Oslo" } },
      { tool: "my-db.search-rows", status: "failed" },
    ],
  });
  const item = t.items[0] as ToolItem;
  assert.equal(item.call.calls?.length, 2);
  const texts = (node: unknown) => nodes(node).flatMap((n) => (typeof n.text === "string" ? [n.text] : []));
  const closed = renderTool(t, item, makeChat());
  assert.ok(texts(closed).includes("2 calls"), "the row counts the calls");
  assert.ok(!texts(closed).includes("weather.forecast"), "a row opens only on click");
  t.expanded.add("x");
  const open = renderTool(t, item, makeChat());
  const shown = texts(open);
  assert.ok(shown.includes("weather.forecast") && shown.includes("city: Oslo") && shown.includes("my-db.search-rows"));
  assert.ok(nodes(open).some((n) => n.type === "icon" && n.name === "circle-alert"), "the failed call says so");
  assert.ok(nodes(open).some((n) => n.type === "code"), "the program follows the calls");
});

test("an error reported as a notice and as the turn's failure shows once", () => {
  const t = initial();
  const expired = "This API key has expired.";
  applyEvent(t, { event: "run_started" });
  applyEvent(t, { event: "notice", level: "error", message: expired });
  applyEvent(t, { event: "notice", level: "error", message: expired });
  applyEvent(t, { event: "run_finished", outcome: { status: "failed", message: expired } });
  assert.deepEqual(
    t.items.filter((item) => item.role === "notice").map((item) => item.role === "notice" && item.text),
    [expired],
  );
});

test("Send again shows the edited text and a busy chat until the host has it, and a failed edit puts the old text back and keeps what was typed", async () => {
  const { renderTranscript: transcriptOf } = await import("./views/rows.tsx");
  let release: (fail: boolean) => void = () => {};
  const held = harness((method) =>
    method === "host/chats.edit_message"
      ? Effect.callback<unknown, HostCallFailed>((resume) => {
          release = (fail) =>
            resume(
              fail
                ? Effect.fail(new HostCallFailed({ method, code: -32000, message: "the agent cannot rewind" }))
                : Effect.succeed({}),
            );
        })
      : undefined,
  );
  const chat = makeChat({ id: "c", agentId: "codex", sessionId: "s" });
  held.controller.state.chats.c = chat;
  const t = held.controller.transcript("c");
  t.items = [say("old text"), { id: "r1", role: "assistant", text: "reply" } as TranscriptItem];
  t.snapshot = { kind: "ready" };
  const texts = () => nodes(tree(transcriptOf(held.v, chat))).flatMap((node) => (typeof node.text === "string" ? [node.text] : []));
  const markdown = () =>
    nodes(tree(transcriptOf(held.v, chat))).flatMap((node) => (node.type === "markdown" ? [String(node.text ?? "")] : []));

  for (const fail of [false, true]) {
    t.editing = "old text";
    t.editText = "new text";
    const sent = Effect.runPromise(held.controller.submitEdit("c", "old text").pipe(Effect.exit));
    await new Promise((resolve) => setTimeout(resolve, 0));
    const shown = [...texts(), ...markdown()].join("\n");
    assert.ok(shown.includes("new text") && !shown.includes("old text"), `the edited text shows at once: ${shown}`);
    assert.ok(texts().includes("Sending again…"), "the chat is busy");
    release(fail);
    await sent;
    assert.ok(!texts().includes("Sending again…"));
    if (fail) {
      const field = nodes(tree(transcriptOf(held.v, chat))).find((node) => node.type === "input" && node.id === "edit-old text");
      assert.equal(field?.value, "new text", "a failed edit opens the field again with the text as typed");
      (field?.onKey as (event: { key: string }) => void)({ key: "escape" });
      const after = [...texts(), ...markdown()].join("\n");
      assert.ok(after.includes("old text") && !after.includes("new text"), `Escape closes it on the old text: ${after}`);
    }
    // The host's reset replaces the items after a successful edit.
    t.items = [say("old text"), { id: "r1", role: "assistant", text: "reply" } as TranscriptItem];
  }
});

test("the first row the transcript sends carries the copy of the message its turn began with, when that message has no row", () => {
  const { v } = harness();
  const chat = makeChat();
  v.controller.state.chats[chat.id] = chat;
  const t = v.controller.transcript(chat.id);
  const asked: UserItem = { id: "u0", role: "user", blocks: [{ type: "text", text: "the question" }] };
  t.items = [{ id: "a1", role: "assistant", text: "a step" }, { id: "a2", role: "assistant", text: "the answer" }];
  t.snapshot = { kind: "ready" };
  t.start = 40;
  const scroller = () => nodes(renderTranscript(v, chat)).find((node) => node.type === "scroller")!;
  const carried = () => (scroller().items![0].children as TestNode[]).find((node) => node?.type === "sticky");
  assert.equal(carried(), undefined, "without the page's lead there is nothing to carry");
  t.lead = asked;
  assert.equal(carried()?.carried, true, "the first row carries the lead the host read with the page");
  const texts = (node: TestNode | undefined): string[] => [
    ...(node?.text ? [node.text] : []),
    ...((node?.children ?? []) as TestNode[]).flatMap((child) => (child ? texts(child) : [])),
  ];
  assert.ok(texts(carried()).some((text) => text.includes("the question")));
  assert.equal(scroller().items!.slice(1).some((row) => (row.children as TestNode[]).some((node) => node?.type === "sticky")), false, "and only the first row");
  // A message the transcript has pins itself in its own row.
  t.items = [asked, ...t.items];
  assert.equal(carried(), undefined);
});

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.