Official

chat

Built-in chat UI (JavaScript UI plugin).

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/chat@0.2.6

Permissions in 0.2.6

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

Files

panes.test.ts39.8 KB
// Chat panes: a hidden pane waits to render until it shows, transcripts
// outlive a reload of this plugin, and a chat on its way shows a skeleton.
import assert from "node:assert/strict";
import test from "node:test";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import type { AppState, HostEvents } from "divergence";
import type { Layout } from "divergence/protocol";
import { onAgent } from "./events.ts";
import { ensureChat, ensurePane, followApp, prehydratePresentation, removePane } from "./panes.ts";
import { PAGE, loadOlder, loadTranscript } from "./data.ts";
import { HostCallFailed, subscription } from "divergence/effect";
import { initialTranscript } from "./state.ts";
import type { Transcript } from "./state.ts";
import { noteTask } from "./layout.ts";
import { renderCenter, renderCenterPresentation, renderPane } from "./views/panes.tsx";
import { renderTitlePresentation } from "./views/title.tsx";
import { chat, harness, item, nodes } from "./ui-for-tests.test.ts";

// What a composer reads as it is made: no options, commands or skills.
const composerReads = (method: string) =>
  method === "host/chats.options"
    ? Effect.succeed({ options: [] })
    : method === "host/chats.commands"
      ? Effect.succeed({ commands: [] })
      : method === "host/chats.skills"
        ? Effect.succeed({ skills: [] })
        : undefined;

const delta = (chatId: string): HostEvents["agent"] => ({
  event: "agent",
  chatId,
  kind: { event: "text_delta", itemId: `reply-${chatId}`, text: "more", mode: "append" },
});

test("four visible panes render independently while a hidden retained pane waits", async () => {
  const h = harness();
  const rendered = { panes: [] as string[], composers: [] as string[] };
  const visible = ["a", "b", "c", "d"];
  for (const id of [...visible, "hidden"]) {
    h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });
    h.controller.transcript(id);
    h.controller.state.panes[id] = {
      chatId: id,
      view: { id: 1, update: () => rendered.panes.push(id), remove() {} },
      composer: { id: 2, update: () => rendered.composers.push(id), remove() {} },
    };
  }
  const tab = (chatId: string) => ({ kind: "chat" as const, chatId });
  const pane = (id: string): Layout => ({ kind: "pane", id: `pane-${id}`, tabs: [tab(id)], active: tab(id) });
  const root: Layout = {
    kind: "split",
    id: "four-panes",
    direction: "row",
    children: visible.map((id) => ({ share: 1 / visible.length, layout: pane(id) })),
  };
  noteTask(h.controller.state.layouts, {
    id: "task",
    layout: { root, focused: "pane-a" },
    createdAt: "",
    updatedAt: "",
  });
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "a" }));
  for (let i = 0; i < 3; i++) {
    await Effect.runPromise(onAgent(h.controller, delta("hidden")));
    for (const id of visible) await Effect.runPromise(onAgent(h.controller, delta(id)));
  }
  const expected = Array.from({ length: 3 }, () => visible).flat();
  assert.deepEqual(rendered.panes, expected, "every pane on screen follows its events");
  assert.deepEqual(rendered.composers, expected, "every visible Stop control follows its pane");
  assert.equal(h.controller.state.panes.hidden?.stale, true);
  Effect.runSync(h.controller.app.update({ chatId: "hidden" }));
  await Effect.runPromise(ensurePane(h.controller, "hidden"));
  assert.deepEqual(rendered.panes.slice(-1), ["hidden"], "a retained pane renders once when it becomes visible");
  assert.deepEqual(rendered.composers.slice(-1), ["hidden"], "its retained composer renders with it");
  assert.equal(h.controller.state.panes.hidden?.stale, false);
  await h.close();
});

test("a hidden retained transcript reset reloads once when its pane returns", async () => {
  let reads = 0;
  const h = harness((method) => {
    if (method === "host/chats.transcript") {
      reads++;
      return Effect.succeed({
        items: [item({ id: "new", role: "assistant", text: "new history" })],
        pendingApprovals: [],
        pendingQuestions: [],
        plan: null,
        usage: {},
        running: false,
      });
    }
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    return composerReads(method);
  });
  h.controller.state.chats.hidden = chat({ id: "hidden", sessionId: "session-hidden" });
  const transcript = h.controller.transcript("hidden");
  transcript.items = [item({ id: "old", role: "assistant", text: "old history" })];
  transcript.snapshot = { kind: "unread" }; // A transcript_reset received while this retained pane was hidden.
  h.controller.state.panes.hidden = {
    chatId: "hidden",
    view: { id: 1, update() {}, remove() {} },
    composer: { id: 2, update() {}, remove() {} },
  };
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "hidden" }));

  await Effect.runPromise(ensurePane(h.controller, "hidden"));
  await h.settle();
  assert.equal(reads, 1);
  assert.deepEqual(transcript.items.map((row) => row.id), ["new"], "returning replaces the stale retained history");

  await Effect.runPromise(ensurePane(h.controller, "hidden"));
  await h.settle();
  assert.equal(reads, 1, "an ordinary warm return does not read an already loaded transcript again");
  await h.close();
});

test("the pane budget evicts hidden panes before any of more than ten visible panes", async () => {
  const h = harness();
  const visible = Array.from({ length: 12 }, (_, index) => `visible-${index}`);
  const hidden = ["hidden-old", "hidden-new"];
  const removed: string[] = [];
  for (const id of [...visible, ...hidden]) {
    h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });
    h.controller.transcript(id);
    h.controller.state.panes[id] = {
      chatId: id,
      view: { id: 1, update() {}, remove: () => removed.push(id) },
    };
  }
  const tab = (chatId: string) => ({ kind: "chat" as const, chatId });
  const pane = (id: string): Layout => ({ kind: "pane", id: `pane-${id}`, tabs: [tab(id)], active: tab(id) });
  noteTask(h.controller.state.layouts, {
    id: "large-task",
    layout: {
      root: {
        kind: "split",
        id: "twelve-panes",
        direction: "row",
        children: visible.map((id) => ({ share: 1 / visible.length, layout: pane(id) })),
      },
      focused: `pane-${visible[0]}`,
    },
    createdAt: "",
    updatedAt: "",
  });
  h.controller.state.recentPanes = [...visible, ...hidden];
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: visible[0], workspaceId: "w" }));

  await Effect.runPromise(ensurePane(h.controller, visible[0]!));
  assert.deepEqual(removed.sort(), hidden.sort(), "only hidden panes pay the cache budget");
  assert.ok(visible.every((id) => h.controller.state.panes[id]), "every visible pane remains live");
  assert.equal(h.controller.state.recentPanes.length, visible.length, "the total is bounded by the visible count");
  await h.close();
});

test("rapid cold selections keep the pane still serving as the dynamic fallback", async () => {
  const h = harness();
  const removed: string[] = [];
  const ids = ["shown", ...Array.from({ length: 11 }, (_, index) => `cold-${index}`), "replacement"];
  for (const id of ids) {
    h.controller.state.chats[id] = chat({ id });
    h.controller.transcript(id).snapshot = { kind: "ready" };
    h.controller.state.panes[id] = {
      chatId: id,
      view: { id: ids.indexOf(id) + 1, update() {}, remove: () => removed.push(id) },
      drawn: true,
    };
  }
  h.controller.state.onScreen = "shown";
  h.controller.state.recentPanes = ["cold-10", "cold-9", "cold-8", "cold-7", "cold-6", "cold-5", "cold-4", "cold-3", "cold-2", "cold-1", "cold-0", "shown"];
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "cold-10" }));

  await Effect.runPromise(ensurePane(h.controller, "cold-10"));
  assert.ok(h.controller.state.panes.shown, "the pane still painted under the loading fallback stays retained");
  assert.ok(!removed.includes("shown"));

  h.controller.state.onScreen = "cold-10";
  Effect.runSync(h.controller.app.update({ chatId: "replacement" }));
  await Effect.runPromise(ensurePane(h.controller, "replacement"));
  assert.ok(removed.includes("shown"), "the old fallback becomes evictable after another pane replaces it");
  await h.close();
});

test("rapid prehydration uses the bounded pane cache and releases evicted reads once", async () => {
  const ids = Array.from({ length: 12 }, (_, index) => `chat-${index}`);
  const gates = Object.fromEntries(ids.map((id) => [id, Deferred.makeUnsafe<void>()]));
  const closed: string[] = [];
  const h = harness((method, params) => {
    const chatId = (params as { chatId?: string }).chatId;
    if (method === "host/chats.transcript" && chatId)
      return Deferred.await(gates[chatId]!).pipe(
        Effect.as({
          items: [item({ id: `reply-${chatId}`, role: "assistant", text: chatId })],
          pendingApprovals: [],
          pendingQuestions: [],
          plan: null,
          usage: {},
          running: false,
        }),
      );
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    if (method === "host/security.pending") return Effect.succeed({ requests: [] });
    if (method === "host/drafts.get") return Effect.succeed(undefined);
    if (method === "host/chats.close" && chatId)
      return Effect.sync(() => {
        closed.push(chatId);
        return {};
      });
    return composerReads(method);
  });
  for (const id of ids) h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });

  const reads = ids.map((id) => Effect.runPromise(prehydratePresentation(h.controller, id)));
  await new Promise<void>((resolve) => setImmediate(resolve));
  assert.equal(h.controller.state.recentPanes.length, 10);
  assert.ok(ids.slice(2).every((id) => h.controller.state.recentPanes.includes(id)), "the newest panes own the cache");
  assert.ok(h.controller.state.transcripts[ids[0]!], "an evicted in-flight read finishes before release");

  for (const id of ids) Effect.runSync(Deferred.succeed(gates[id]!, undefined));
  await Promise.all(reads);
  assert.deepEqual(Object.keys(h.controller.state.transcripts).sort(), ids.slice(2).sort());
  assert.deepEqual(closed.sort(), ids.slice(0, 2).sort(), "each evicted chat is closed once");
  await h.close();
});

test("selection adopts a cancelled in-flight prehydration without duplicate views or selection effects", async () => {
  const all = Array.from({ length: 120 }, (_, n) => item({ id: `a${n}`, role: "assistant", text: `reply ${n}` }));
  const firstPage = Deferred.makeUnsafe<void>();
  const calls: { method: string; chatId?: string; before?: number }[] = [];
  const h = harness((method, params) => {
    const { chatId, before } = params as { chatId?: string; before?: number };
    calls.push({ method, chatId, before });
    if (method === "host/chats.transcript" && chatId === "a") {
      if (before === undefined)
        return Deferred.await(firstPage).pipe(
          Effect.as({
            items: all.slice(70),
            start: 70,
            pendingApprovals: [],
            pendingQuestions: [],
            plan: null,
            usage: {},
            running: false,
          }),
        );
      return Effect.sync(() => {
        return {
          items: all.slice(Math.max(0, before! - PAGE), before),
          start: Math.max(0, before! - PAGE),
          pendingApprovals: [],
          pendingQuestions: [],
          plan: null,
          usage: {},
          running: false,
        };
      });
    }
    if (method === "host/chats.transcript" && chatId)
      return Effect.succeed({
        items: [item({ id: `reply-${chatId}`, role: "assistant", text: chatId })],
        start: 0,
        pendingApprovals: [],
        pendingQuestions: [],
        plan: null,
        usage: {},
        running: false,
      });
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    if (method === "host/security.pending") return Effect.succeed({ requests: [] });
    if (method === "host/drafts.get") return Effect.succeed(undefined);
    return composerReads(method);
  });
  h.controller.state.chats.a = chat({ id: "a", sessionId: "session-a" });

  const registration = Deferred.makeUnsafe<void>();
  const registered: { name: string; render: (ctx: typeof h.v.ctx) => unknown }[] = [];
  let nextView = 0;
  (h.controller.views as { add: typeof h.controller.views.add }).add = ((name: string, options: { render: (ctx: typeof h.v.ctx) => unknown }) =>
    Effect.gen(function* () {
      registered.push({ name, render: options.render });
      if (name === "chat:a") yield* Deferred.await(registration);
      return { id: ++nextView, update() {}, remove() {} };
    })) as typeof h.controller.views.add;

  const abort = new AbortController();
  const prefetched = Effect.runPromise(prehydratePresentation(h.controller, "a"), { signal: abort.signal });
  await new Promise<void>((resolve) => setImmediate(resolve));
  abort.abort();
  await assert.rejects(prefetched);
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "a", workspaceId: "w" }));
  const opening = Effect.runPromise(ensurePane(h.controller, "a"));
  await new Promise<void>((resolve) => setImmediate(resolve));
  assert.deepEqual(
    registered.map((view) => view.name).sort(),
    ["center:a", "chat:a", "composer:a", "title:a"],
    "the complete presentation is registered while the pane registration remains held",
  );
  assert.ok(h.controller.state.recentPanes.includes("a"), "the pending pane owns the transcript");
  Effect.runSync(Deferred.succeed(firstPage, undefined));
  Effect.runSync(Deferred.succeed(registration, undefined));
  await opening;
  await new Promise<void>((resolve) => setImmediate(resolve));
  const pane = registered.find((view) => view.name === "chat:a");
  assert.ok(pane);
  assert.ok(!nodes(pane.render(h.v.ctx)).some((node) => node.id === "chat-skeleton"));
  assert.equal(h.controller.state.panes.a?.ready, true);
  assert.equal(h.controller.state.transcripts.a?.items.length, PAGE, "adoption keeps the newest page without reading unrequested history");
  assert.ok(calls.some((call) => call.method === "host/security.pending" && call.chatId === "a"), "prehydration reads requests");
  assert.ok(!calls.some((call) => call.method === "host/chats.transcript" && call.before !== undefined));
  assert.equal(registered.filter((view) => view.name === "chat:a").length, 1, "selection reuses the preparing pane");
  assert.deepEqual(h.focused, [], "prehydration and adoption do not focus before followApp");
  assert.ok(!calls.some((call) => call.method === "host/chats.prepare" || call.method === "host/chats.load_history"));

  Effect.runSync(h.controller.app.update({ chatId: "b" }));
  Effect.runSync(h.controller.app.update({ chatId: "a" }));
  await Effect.runPromise(ensurePane(h.controller, "a"));
  assert.equal(h.controller.state.transcripts.a?.items.length, PAGE, "reselect keeps the completed retained page");
  assert.equal(h.controller.state.panes.a?.ready, true);
  await h.close();
});

test("prehydration prepares every chat in a fixed task and side split without selecting it", async () => {
  const calls: { method: string; chatId?: string }[] = [];
  const h = harness((method, params) => {
    const chatId = (params as { chatId?: string }).chatId;
    calls.push({ method, chatId });
    if (method === "host/chats.transcript")
      return Effect.succeed({
        items: [item({ id: `reply-${chatId}`, role: "assistant", text: chatId })],
        pendingApprovals: [],
        pendingQuestions: [],
        plan: null,
        usage: {},
        running: false,
      });
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    if (method === "host/security.pending") return Effect.succeed({ requests: [] });
    if (method === "host/drafts.get") return Effect.succeed(undefined);
    return composerReads(method);
  });
  const tab = (chatId: string) => ({ kind: "chat" as const, chatId });
  for (const id of ["a", "b", "side"]) h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });
  noteTask(h.controller.state.layouts, {
    id: "task",
    layout: {
      root: {
        kind: "split",
        id: "root",
        direction: "row",
        children: [
          { share: 0.5, layout: { kind: "pane", id: "left", tabs: [tab("a")], active: tab("a") } },
          { share: 0.5, layout: { kind: "pane", id: "right", tabs: [tab("b")], active: tab("b") } },
        ],
      },
      focused: "left",
    },
    createdAt: "",
    updatedAt: "",
  });
  h.controller.state.layouts.homes.side = "task";
  h.controller.state.layouts.side = {
    layout: { root: { kind: "pane", id: "side-pane", tabs: [tab("side")], active: tab("side") }, focused: "side-pane" },
    remembered: [],
    open: true,
    width: 400,
  };
  const renders: { name: string; render: (ctx: typeof h.v.ctx) => unknown }[] = [];
  let nextView = 0;
  (h.controller.views as { add: typeof h.controller.views.add }).add = ((name: string, options: { render: (ctx: typeof h.v.ctx) => unknown }) =>
    Effect.sync(() => {
      renders.push({ name, render: options.render });
      return { id: ++nextView, update() {}, remove() {} };
    })) as typeof h.controller.views.add;

  await Effect.runPromise(prehydratePresentation(h.controller, "a"));
  for (const view of renders.filter((view) => view.name.startsWith("chat:"))) view.render(h.v.ctx);
  renders.find((view) => view.name === "center:a")?.render(h.v.ctx);
  renders.find((view) => view.name === "title:a")?.render(h.v.ctx);

  assert.deepEqual(Object.keys(h.controller.state.panes).sort(), ["a", "b", "side"]);
  assert.ok(Object.values(h.controller.state.panes).every((pane) => pane.ready), "every embedded chat is ready");
  assert.equal(h.controller.state.panes.a?.centerPresented, true);
  assert.equal(h.controller.state.panes.a?.titlePresented, true);
  assert.ok(["a", "b", "side"].every((id) => calls.some((call) => call.method === "host/chats.transcript" && call.chatId === id)));
  assert.deepEqual(h.focused, []);
  assert.ok(!calls.some((call) => call.method === "host/chats.prepare" || call.method === "host/chats.load_history"));
  await h.close();
});

test("rapid navigation hydrates before view registration and converges on the last chat", async () => {
  const calls: { method: string; chatId?: string }[] = [];
  const h = harness((method, params) => {
    const chatId = (params as { chatId?: string }).chatId;
    calls.push({ method, chatId });
    if (method === "host/chats.transcript")
      return Effect.succeed({
        items: [item({ id: `reply-${chatId}`, role: "assistant", text: chatId })],
        pendingApprovals: [],
        pendingQuestions: [],
        plan: null,
        usage: {},
        running: false,
      });
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    if (method === "host/security.pending") return Effect.succeed({ requests: [] });
    if (method === "host/drafts.get") return Effect.succeed(undefined);
    if (method === "host/chats.load_history" || method === "host/chats.prepare") return Effect.succeed({});
    return composerReads(method);
  });
  for (const id of ["a", "b", "c"]) h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });

  const appListeners = new Set<(state: AppState) => void>();
  Object.assign(h.controller.api.app, {
    onChange: (listener: (state: AppState) => void) => {
      appListeners.add(listener);
      return () => { appListeners.delete(listener); };
    },
  });
  const update = h.controller.app.update;
  Object.assign(h.controller.app, {
    changes: subscription((emit) => h.controller.api.app.onChange(emit)),
    update: (patch: Parameters<typeof update>[0]) => update(patch).pipe(Effect.tap(() => Effect.sync(() => {
      for (const listener of appListeners) listener(h.controller.api.app.state());
    }))),
  });
  await Effect.runPromise(h.controller.followAppChanges());

  const firstView = Deferred.makeUnsafe<void>();
  const registered: { name: string; render: (ctx: typeof h.v.ctx) => unknown }[] = [];
  let nextView = 0;
  (h.controller.views as { add: typeof h.controller.views.add }).add = ((name: string, options: { render: (ctx: typeof h.v.ctx) => unknown }) =>
    Effect.gen(function* () {
      registered.push({ name, render: options.render });
      if (name === "chat:a") yield* Deferred.await(firstView);
      return { id: ++nextView, update() {}, remove() {} };
    })) as typeof h.controller.views.add;

  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "a", workspaceId: "w" }));
  await new Promise<void>((resolve) => setImmediate(resolve));
  assert.deepEqual(
    registered.map((view) => view.name).sort(),
    ["center:a", "chat:a", "composer:a", "title:a"],
    "the first complete presentation is still waiting for its pane handle",
  );
  for (const method of ["host/chats.transcript", "host/chats.options", "host/drafts.get"])
    assert.ok(calls.some((call) => call.method === method && call.chatId === "a"), `${method} starts before registration finishes`);

  Effect.runSync(h.controller.app.update({ chatId: "b" }));
  Effect.runSync(h.controller.app.update({ chatId: "c" }));
  Effect.runSync(Deferred.succeed(firstView, undefined));
  for (let turn = 0; turn < 100 && h.focused.at(-1) !== "prompt-c"; turn++)
    await new Promise<void>((resolve) => setImmediate(resolve));
  assert.deepEqual(h.focused, ["prompt-c"], "only the latest selection gains focus after registration");

  assert.deepEqual(Object.keys(h.controller.state.panes).sort(), ["a", "c"], "queued navigation skips the superseded chat");
  assert.deepEqual(Object.keys(h.controller.state.transcripts).sort(), ["a", "c"], "every hydrated transcript belongs to a pane");
  const lastPane = registered.find((view) => view.name === "chat:c");
  assert.ok(lastPane);
  assert.ok(!nodes(lastPane.render(h.v.ctx)).some((node) => node.id === "chat-skeleton"), "the last pane's first tree has its rows");
  await h.close();
  assert.equal(appListeners.size, 0, "the selection listener belongs to the plugin scope");
});

test("moving the main prompt box to another chat renders the two composers, not the panes", async () => {
  const h = harness();
  const rendered: string[] = [];
  const handle = (name: string) => ({ id: 1, update: () => rendered.push(name), remove() {} });
  for (const id of ["a", "b"]) {
    h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });
    h.controller.transcript(id);
    h.controller.state.panes[id] = { chatId: id, view: handle(`pane ${id}`), composer: handle(`composer ${id}`) };
  }
  h.controller.state.mainPrompt = "a";
  renderCenter({ ...h.v, ctx: { ...h.v.ctx, app: { route: "chat", chatId: "b" } } });
  // A pane carries the whole transcript: rendering the one the user left
  // made the switch to a new chat wait for its tree to be applied.
  assert.deepEqual(rendered.sort(), ["composer a", "composer b"]);
  assert.equal(h.controller.state.mainPrompt, "b");
  await h.close();
});

test("a retained presentation fixes its task tab and side-split layout to its own chat", async () => {
  const h = harness();
  const tab = (chatId: string) => ({ kind: "chat" as const, chatId });
  for (const [index, id] of ["a", "a2", "b"].entries()) {
    h.controller.state.chats[id] = chat({ id });
    h.controller.state.panes[id] = {
      chatId: id,
      view: { id: 20 + index, update() {}, remove() {} },
      drawn: true,
      ready: true,
    };
  }
  const root: Layout = {
    kind: "split",
    id: "main",
    direction: "row",
    children: [
      { share: 0.5, layout: { kind: "pane", id: "p1", tabs: [tab("a"), tab("a2")], active: tab("a") } },
      { share: 0.5, layout: { kind: "pane", id: "p2", tabs: [tab("b")], active: tab("b") } },
    ],
  };
  noteTask(h.controller.state.layouts, {
    id: "task",
    layout: { root, focused: "p2" },
    createdAt: "",
    updatedAt: "",
  });
  h.controller.state.layouts.side = {
    layout: {
      root: {
        kind: "pane",
        id: "side-pane",
        tabs: [{ kind: "item", id: "file", owner: "files", itemKind: "files.file", key: "/a.ts", title: "a.ts" }],
        active: { kind: "item", id: "file", owner: "files", itemKind: "files.file", key: "/a.ts", title: "a.ts" },
      },
      focused: "side-pane",
    },
    remembered: [],
    open: true,
    width: 400,
  };
  const v = { ...h.v, ctx: { ...h.v.ctx, app: { route: "chat" as const, chatId: "b" } } };

  const center = nodes(renderCenterPresentation(v, "a2"));
  const embedded = center.filter((node) => node.type === "view" && typeof node.view === "number").map((node) => node.view);
  assert.ok(embedded.includes(21), "the retained center embeds its own active tab");
  assert.ok(!embedded.includes(20), "it does not inherit the task's mutable active tab");
  assert.ok(center.some((node) => node.id === "task-pane-side-pane"), "the complete side-split geometry is retained too");

  const title = nodes(renderTitlePresentation(v, "a2"));
  assert.equal(title.find((node) => node.id === "tab-surface-p1")?.follows, "tab-chat-a2");
  assert.equal(title.find((node) => node.id === "tab-surface-p1")?.layoutMotion, false, "switching tabs moves the selected surface at once");
  assert.ok(title.some((node) => node.id === "strip-side-pane"), "the retained title matches the side split");
  await h.close();
});

test("transcripts kept across a reload show at once and are read again", async () => {
  const before = harness();
  const kept: Transcript = {
    ...initialTranscript(),
    items: [item({ id: "u1", role: "user", text: "hello" })],
    snapshot: { kind: "ready" },
    // A read of the code that unloaded: it never ends now.
    loading: Deferred.makeUnsafe<void>(),
  };
  kept.expanded.add("u1");
  before.controller.state.transcripts.a = kept;
  // The center view's `ctx.state`, which the reload keeps.
  const state: { transcripts?: Record<string, Transcript> } = {};
  before.controller.keepTranscripts(state);
  await before.close();

  const asked: string[] = [];
  const after = harness((method) => {
    asked.push(method);
    if (method === "host/chats.transcript")
      return Effect.succeed({
        items: [item({ id: "u1", role: "user", text: "hello" }), item({ id: "a1", role: "assistant", text: "hi" })],
        pendingApprovals: [],
        pendingQuestions: [],
        plan: null,
        usage: {},
        running: false,
      });
    if (method === "host/security.pending") return Effect.succeed({ requests: [] });
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    return composerReads(method);
  });
  after.controller.state.chats.a = chat({ id: "a", sessionId: "session-a" });
  after.controller.keepTranscripts(state);
  const carried = after.controller.state.transcripts.a;
  assert.ok(carried);
  assert.deepEqual(
    carried.items.map((row) => row.id),
    ["u1"],
    "the rows show before any read",
  );
  assert.ok(carried.expanded.has("u1"), "what the user opened stays open");
  assert.equal(carried.loading, undefined, "a read of the old code is not waited for");
  assert.equal(carried.snapshot.kind, "unread");
  assert.ok(nodes(renderPane(after.v, "a")).every((node) => node.type !== "empty"));
  await Effect.runPromise(ensureChat(after.controller, "a"));
  await after.settle();
  assert.ok(asked.includes("host/security.pending"), "its security requests are read again");
  assert.ok(asked.includes("host/chats.transcript"), "its transcript is read again");
  assert.deepEqual(
    after.controller.state.transcripts.a?.items.map((row) => row.id),
    ["u1", "a1"],
  );
  assert.equal(after.controller.state.transcripts.a?.carried, false);
  await after.close();
});

test("reload hydration preserves the admitted read owner and rechecks its retained row coverage", async () => {
  const rows = Array.from({ length: 80 }, (_, index) => item({ id: `retained-${index}`, role: "assistant", text: `${index}` }));
  const page = (items: typeof rows) => ({ items, start: 0, pendingApprovals: [], pendingQuestions: [], plan: null, usage: {}, running: false });
  const first = Deferred.makeUnsafe<ReturnType<typeof page>>();
  const limits: (number | undefined)[] = [];
  const h = harness((method, params) => {
    if (method === "host/chats.transcript") {
      limits.push((params as { limit?: number }).limit);
      return limits.length === 1 ? Deferred.await(first) : Effect.succeed(page(rows));
    }
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    if (method === "host/security.pending") return Effect.succeed({ requests: [] });
    return composerReads(method);
  });
  h.controller.state.chats.a = chat({ id: "a" });
  await Effect.runPromise(ensureChat(h.controller, "a"));
  const current = h.controller.transcript("a");
  const loading = current.loading!;
  const { answers, requests, checkpoints } = current;
  answers.q = { typed: "new answer" };
  checkpoints.add("current");
  current.editing = "editing";
  current.editText = "current edit";
  current.copied = "copied";
  current.older = true;
  h.controller.keepTranscripts({ transcripts: { a: { ...initialTranscript(), items: rows, checkpoints: new Set(["carried"]) } } });
  assert.equal(h.controller.transcript("a"), current);
  assert.equal(current.loading, loading);
  assert.equal(current.snapshot.kind, "unread", "retained display rows do not complete a snapshot");
  assert.equal(current.answers, answers);
  assert.deepEqual(current.answers, { q: { typed: "new answer" } });
  assert.equal(current.requests, requests);
  assert.equal(current.checkpoints, checkpoints);
  assert.deepEqual([...checkpoints].sort(), ["carried", "current"]);
  assert.deepEqual([current.editing, current.editText, current.copied, current.older], ["editing", "current edit", "copied", true]);
  assert.equal(current.items.length, 80);
  await Effect.runPromise(Deferred.succeed(first, page(rows.slice(-50))));
  await Effect.runPromise(Deferred.await(loading));
  assert.deepEqual(limits, [50, 80], "the original owner retries only its bounded newest page at the restored coverage");
  assert.equal(current.items.length, 80, "an earlier 50-row reply cannot shrink retained history");
  await Effect.runPromise(ensureChat(h.controller, "a"));
  assert.deepEqual(limits, [50, 80], "hydration does not start a second loader");
  await h.close();
});

test("completed snapshots and newer live events take precedence over retained reload presentation", async () => {
  const h = harness();
  const retained = { ...initialTranscript(), items: [item({ id: "old", role: "assistant", text: "old" })] };
  for (const id of ["ready", "empty", "live"]) h.controller.state.chats[id] = chat({ id });
  const ready = h.controller.transcript("ready");
  ready.items = [item({ id: "new", role: "assistant", text: "new" })];
  ready.snapshot = { kind: "ready" };
  h.controller.transcript("empty").snapshot = { kind: "ready" };
  h.controller.transcript("live");
  await Effect.runPromise(onAgent(h.controller, delta("live")));
  const live = h.controller.transcript("live");
  const items = live.items;
  h.controller.keepTranscripts({ transcripts: { ready: retained, empty: retained, live: retained, absent: retained } });
  assert.deepEqual(ready.items.map((item) => item.id), ["new"]);
  assert.equal(ready.snapshot.kind, "ready");
  assert.deepEqual(h.controller.transcript("empty").items, [], "an authoritative empty snapshot is not repopulated");
  assert.equal(live.items, items);
  assert.equal(live.version, 1);
  assert.equal(h.controller.transcript("absent").carried, true);
  assert.deepEqual(h.controller.transcript("absent").items.map((item) => item.id), ["old"]);
  await h.close();
});

test("a chat whose history is on its way shows a skeleton and its composer", async () => {
  // The transcript's read does not come back while the pane shows.
  const h = harness((method) => (method === "host/chats.transcript" ? Effect.never : composerReads(method)));
  h.controller.state.chats.a = chat({ id: "a", sessionId: "session-a" });
  await Effect.runPromise(ensureChat(h.controller, "a"));
  await Effect.runPromise(h.controller.ensureComposer("a"));
  const shown = nodes(renderPane(h.v, "a"));
  assert.ok(!shown.some((node) => node.type === "empty"), "no line of loading text");
  assert.ok(shown.some((node) => node.background === "muted" && node.borderRadius === "xl"), "the skeleton's message");
  assert.ok(shown.some((node) => node.id === "prompt-a"), "the composer takes typing at once");
  await h.close();
});

test("the host prepares a chat once each time it shows, and a failure is a notice", async () => {
  let fail = false;
  const prepared: unknown[] = [];
  const h = harness((method, params) => {
    if (method !== "host/chats.prepare") return composerReads(method);
    prepared.push(params);
    return fail ? Effect.fail(new HostCallFailed({ method, code: -32000, message: "no session" })) : Effect.succeed({});
  });
  for (const id of ["a", "b"]) {
    h.controller.state.chats[id] = chat({ id, sessionId: `session-${id}` });
    h.controller.transcript(id);
  }
  const prepares = () => prepared;
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "a" }));
  for (let i = 0; i < 3; i++) await Effect.runPromise(followApp(h.controller));
  await h.settle();
  assert.deepEqual(prepares(), [{ chatId: "a" }], "renders of the same chat prepare once");
  Effect.runSync(h.controller.app.update({ chatId: "b" }));
  fail = true;
  await Effect.runPromise(followApp(h.controller));
  await h.settle();
  assert.deepEqual(prepares(), [{ chatId: "a" }, { chatId: "b" }]);
  assert.ok(h.notices.some((notice) => notice.includes("no session")));
  await h.close();
});

// A host holding `all` that answers transcript reads by `limit` and `before`.
function pagedHost(all: ReturnType<typeof item>[], asked: { method: string; params: unknown }[]) {
  return harness((method, params) => {
    asked.push({ method, params });
    if (method === "host/chats.transcript") {
      const { limit, before } = params as { limit?: number; before?: number };
      const end = before ?? all.length;
      const start = limit === undefined ? 0 : Math.max(0, end - limit);
      return Effect.succeed({
        items: all.slice(start, end),
        start,
        total: all.length,
        pendingApprovals: [],
        pendingQuestions: [],
        plan: null,
        usage: {},
        running: false,
      });
    }
    if (method === "host/chats.close") return Effect.succeed({});
    if (method === "host/chats.checkpoints") return Effect.succeed({ checkpoints: [] });
    return composerReads(method);
  });
}

test("a transcript opens on its newest page without eager history and is dropped when its pane goes", async () => {
  const all = Array.from({ length: 120 }, (_, n) => item({ id: `a${n}`, role: "assistant", text: `reply ${n}` }));
  const asked: { method: string; params: unknown }[] = [];
  const h = pagedHost(all, asked);
  h.controller.state.chats.a = chat({ id: "a", sessionId: "session-a" });
  await Effect.runPromise(loadTranscript(h.controller, "a"));
  await h.settle();
  const ids = () => h.controller.state.transcripts.a?.items.map((row) => row.id) ?? [];
  const reads = asked.filter((call) => call.method === "host/chats.transcript").map((call) => call.params);
  assert.deepEqual(
    reads,
    [{ chatId: "a", limit: PAGE }],
    "only the newest page is needed to open the transcript",
  );
  assert.deepEqual([ids().length, ids()[0], ids().at(-1)], [PAGE, "a70", "a119"]);
  assert.equal(typeof nodes(renderPane(h.v, "a")).find((node) => node.type === "scroller")?.onReachStart, "function");

  // Another chat on screen, the pane goes: its transcript goes with it.
  Effect.runSync(h.controller.app.update({ route: "chat", chatId: "b" }));
  removePane(h.controller, "a");
  assert.equal(h.controller.state.transcripts.a, undefined);
  await new Promise((resolve) => setTimeout(resolve, 0));
  assert.ok(asked.some((call) => call.method === "host/chats.close"), "the host is told it closed");
  await h.close();
});

test("a long transcript exposes its complete history one viewport-requested page at a time", async () => {
  const all = Array.from({ length: 2120 }, (_, n) => item({ id: `a${n}`, role: "assistant", text: `reply ${n}` }));
  const asked: { method: string; params: unknown }[] = [];
  const h = pagedHost(all, asked);
  h.controller.state.chats.a = chat({ id: "a", sessionId: "session-a" });
  await Effect.runPromise(loadTranscript(h.controller, "a"));
  await h.settle();
  const transcript = () => h.controller.state.transcripts.a!;
  assert.deepEqual([transcript().items.length, transcript().start], [PAGE, all.length - PAGE]);

  const scroller = nodes(renderPane(h.v, "a")).find((node) => node.type === "scroller");
  assert.equal(typeof scroller?.onReachStart, "function", "the list asks for older rows near its top");
  await Effect.runPromise(loadOlder(h.controller, "a"));
  assert.deepEqual([transcript().items[0]?.id, transcript().start], ["a2020", 2020], "one requested page goes before the existing rows");
  while (transcript().start > 0) await Effect.runPromise(loadOlder(h.controller, "a"));
  assert.deepEqual(transcript().items.map((row) => row.id), all.map((row) => row.id), "the complete history remains available in order");
  assert.equal(asked.filter((call) => call.method === "host/chats.transcript").length, Math.ceil(all.length / PAGE), "one bounded read serves each demand");
  assert.equal(nodes(renderPane(h.v, "a")).find((node) => node.type === "scroller")?.onReachStart, undefined);
  await h.close();
});

test("the new chat page leaves as its prompt goes: its background fades and the text rises into its message", async () => {
  const h = harness(composerReads);
  const updates: string[] = [];
  h.controller.state.chats.a = chat({ id: "a" });
  h.controller.transcript("a").snapshot = { kind: "ready" };
  h.controller.state.panes.a = { chatId: "a", view: { id: 1, update: () => updates.push("a"), remove() {} } };
  h.controller.state.onScreen = "a";
  const page = nodes(renderPane(h.v, "a"));
  assert.ok(page.some((node) => node.id === "landing-stage" && node.ambient === "caustics" && !node.motion));
  for (const id of ["dock-a", "rising-a", "landing-headline-a", "landing-chip-a"])
    assert.equal(page.find((node) => node.id === id)?.travels, true, `${id} travels`);

  h.controller.composer("a").submitting = true;
  h.controller.state.transcripts.a = {
    ...initialTranscript(),
    snapshot: { kind: "ready" },
    items: [item({ id: "u1", role: "user", blocks: [{ type: "text", text: "Hello" }] })],
  };
  const leaving = nodes(renderPane(h.v, "a"));
  const stage = leaving.find((node) => node.id === "landing-stage");
  assert.equal((stage?.motion as { to?: unknown } | undefined)?.to && JSON.stringify((stage?.motion as { to: unknown }).to), '{"opacity":0}', "the background fades");
  assert.ok(leaving.find((node) => node.id === "landing-headline-a")?.motion, "the headline rides down as it fades");
  assert.equal(leaving.filter((node) => node.id === "rising-a").length, 1, "only the message carries the sent text's id");
  assert.equal(leaving.find((node) => node.id === "rising-a")?.background, "bubble");
  assert.equal(leaving.find((node) => node.id === "dock-a")?.travels, true);

  (stage?.motion as { onDone: () => void }).onDone();
  assert.deepEqual(updates, ["a"]);
  const settled = nodes(renderPane(h.v, "a"));
  assert.ok(!settled.some((node) => node.id === "landing-stage" || node.id === "landing-headline-a"), "the departure is over");
  assert.ok(settled.some((node) => node.id === "rising-a"), "the message keeps its id");
  await h.close();
});

test("a reply arriving on the new chat page without a send just shows the transcript", async () => {
  const h = harness(composerReads);
  h.controller.state.chats.a = chat({ id: "a" });
  h.controller.state.panes.a = { chatId: "a", view: { id: 1, update() {}, remove() {} } };
  h.controller.state.onScreen = "a";
  renderPane(h.v, "a");
  h.controller.state.transcripts.a = {
    ...initialTranscript(),
    snapshot: { kind: "ready" },
    running: true,
    items: [item({ id: "r1", role: "assistant", text: "Hi" })],
  };
  const shown = nodes(renderPane(h.v, "a"));
  assert.ok(!shown.some((node) => node.id === "landing-stage"), "no departure");
  assert.ok(shown.some((node) => node.text === "Working…"));
  await h.close();
});

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.