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

lifecycle.test.ts50.8 KB
// The chat plugin activated against a fake window: a streamed delta updates
// only its pane, and unloading releases everything it registered.
import { fakeLayouts } from "../sdk/ui-testing.ts";
import assert from "node:assert/strict";
import test from "node:test";
import * as z from "zod";
import type {
  Api,
  Chat,
  AppState,
  AppStatePatch,
  HostEvent,
  RenderResult,
  SlotOptions,
  ViewContext,
  AgentEventKind,
  HostMethods,
} from "divergence";
import { testLayer } from "divergence/effect/testing";
import activate from "./main.ts";
import { initialTranscript } from "./state.ts";
import { chat, nodes, fixtureTask, item } from "./ui-for-tests.test.ts";
import type { TestNode } from "./ui-for-tests.test.ts";
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
const stable = (value: unknown) =>
  JSON.stringify(value, (_key, item: unknown) => (typeof item === "function" ? "@handler" : item));
function fake(
  initial: AppState = { route: "chat", chatId: "c1", workspaceId: "w" },
  saved: Record<string, unknown> = {},
  catalog?: {
    chats: Chat[];
    checkpoints?: Promise<HostMethods["host/chats.checkpoints"]["result"]>;
    transcript?: HostMethods["host/chats.transcript"]["result"];
    viewStates?: Record<string, Record<string, unknown>>;
  },
) {
  let state = initial,
    dirty = true,
    nextId = 0;
  const views: {
    slot: string;
    options?: SlotOptions;
    render: (ctx: ViewContext<object>) => RenderResult;
    id: number;
    active: boolean;
    state: Record<string, unknown>;
  }[] = [];
  const listeners = new Map<string, Set<(event: HostEvent) => unknown>>(),
    appListeners = new Set<(state: AppState) => void>();
  const calls: { method: string; params: unknown }[] = [],
    focus: string[] = [],
    notices: string[] = [];
  const commands = new Map<string, (info?: { applied: boolean; phase?: "press" | "release" | "cancel" }) => unknown>(),
    stored: Record<string, unknown> = structuredClone(saved);
  const chats = catalog?.chats ?? [chat({ id: "c1" }), chat({ id: "c2", title: "Second" })];
  let pendingList: Promise<{ chats: Chat[] }> | undefined;
  type Snapshot = HostMethods["host/chats.transcript"]["result"];
  let transcript: Snapshot = catalog?.transcript ?? {
    items: [],
    pendingApprovals: [],
    pendingQuestions: [],
    plan: null,
    usage: {},
    running: false,
  };
  let pendingTranscript: Promise<Snapshot> | undefined;
  const updates: number[] = [];
  const response = (method: string, params: unknown): unknown => {
    // This fixture is the older Alpha host, not a transport failure.
    if (
      method.startsWith("host/inputs.") ||
      method.startsWith("host/drafts.") ||
      method === "host/chats.context_policy"
    )
      throw Object.assign(new Error(`unknown host method ${method}`), { code: -32601 });
    if (method === "host/storage.get") return { value: stored[z.object({ key: z.string() }).parse(params).key] };
    if (method === "host/storage.set") {
      const p = z.object({ key: z.string(), value: z.unknown() }).parse(params);
      stored[p.key] = p.value;
      return {};
    }
    if (method === "host/chats.list") return { chats };
    if (method === "host/workspaces.list")
      return {
        workspaces: [
          { id: "w", name: "Workspace", path: "/fixture", position: 0 },
          { id: "w2", name: "Other", path: "/other", position: 1 },
        ],
      };
    // The chat reads every agent (`agents.all`); one fixture answers the
    // enabled list too.
    if (method === "host/agents.list" || method === "host/agents.all")
      return {
        agents: [
          {
            id: "agent",
            name: "Agent",
            icon: null,
            enabled: true,
            capabilities: { images: true, cancelTask: true, compact: true, fork: true },
          },
        ],
      };
    if (method === "host/chats.options")
      return {
        options: [
          {
            id: "mode",
            name: "Mode",
            kind: "select",
            category: "mode",
            value: "agent",
            choices: [{ value: "agent", name: "Agent" }],
          },
        ],
      };
    if (method === "host/chats.commands") return { commands: [] };
    if (method === "host/chats.skills") return { skills: [] };
    if (method === "host/chats.transcript") return pendingTranscript ?? structuredClone(transcript);
    if (method === "host/chats.checkpoints") return catalog?.checkpoints ?? { checkpoints: [] };
    if (method === "host/security.pending") return { requests: [] };
    // A host whose chats are each a row of their own, with no side split.
    if (method === "host/tasks.list") return { tasks: [] };
    if (method === "host/layouts.side") return { remembered: [], open: false, width: 520 };
    if (method === "host/fs.search") return { paths: ["src/main.ts", "README.md"] };
    // The keys bound now, for the hints beside controls.
    if (method === "commands") return { commands: [], errors: [], file: "" };
    // This machine has no apps to open a workspace in.
    if (method === "open_in.apps") return { apps: [] };
    if (
      method === "host/chats.send" ||
      method === "host/chats.cancel" ||
      method === "host/chats.respond_question" ||
      method === "host/chats.prepare"
    )
      return {};
    throw new Error(`Unexpected method ${method}`);
  };
  const call = async (method: string, params: unknown) => {
    calls.push({ method, params });
    if (method === "host/chats.list" && pendingList) return pendingList;
    return response(method, params);
  };
  const update = (patch: AppStatePatch) => {
    recordShared(patch);
    state = {
      ...state,
      ...patch,
      chatId: patch.chatId === null ? undefined : (patch.chatId ?? state.chatId),
      workspaceId: patch.workspaceId === null ? undefined : (patch.workspaceId ?? state.workspaceId),
      route: patch.route ?? state.route,
      shared: { ...state.shared, ...patch.shared },
    };
    dirty = true;
    for (const listener of appListeners) listener(state);
  };
  const methods = Object.fromEntries(
    ["list", "options", "commands", "skills", "transcript", "checkpoints", "send", "cancel", "respondQuestion"].map(
      (name) => [
        name,
        (params: unknown) => call(`host/chats.${name === "respondQuestion" ? "respond_question" : name}`, params),
      ],
    ),
  );
  const broker = testLayer();
  // A service call or event both sides record in the same shape: the stub
  // bus below logs the new code's real ones, and update() logs the
  // baseline's shared writes as their replacements.
  type ServiceEntry = {
    op: string;
    name: string;
    method?: string;
    event?: string;
    payload?: unknown;
    params?: unknown;
  };
  const serviceLog: ServiceEntry[] = [];
  // Comparison only: each rule mirrors a row of the harness mapping table.
  // openTab/closeTab requests become tabs open/close calls (without the
  // nonce); queuedChats/draftTitles writes become the chat service's events.
  // An empty write where nothing was shared before (the baseline's initial
  // draftTitles) maps to nothing, and the null writes that only consumed a
  // request are dropped with the keys.
  const withoutNonce = (value: unknown) => {
    if (typeof value === "object" && value !== null && "nonce" in value) {
      const { nonce: _nonce, ...rest } = value as Record<string, unknown>;
      return rest;
    }
    return value;
  };
  const recordShared = (patch: AppStatePatch) => {
    const shared = patch.shared as Record<string, unknown> | undefined;
    if (!shared) return;
    const prev = (state.shared ?? {}) as Record<string, unknown>;
    if (shared.openTab != null)
      serviceLog.push({ op: "call", name: "divergence/tabs", method: "open", params: withoutNonce(shared.openTab) });
    if (shared.closeTab != null)
      serviceLog.push({ op: "call", name: "divergence/tabs", method: "close", params: withoutNonce(shared.closeTab) });
    if (
      shared.queuedChats !== undefined &&
      (prev.queuedChats !== undefined || (shared.queuedChats as unknown[]).length > 0)
    )
      serviceLog.push({ op: "emit", name: "divergence/chat", event: "queuedChanged", payload: shared.queuedChats });
    if (
      shared.draftTitles !== undefined &&
      (prev.draftTitles !== undefined || Object.keys(shared.draftTitles as Record<string, unknown>).length > 0)
    )
      serviceLog.push({
        op: "emit",
        name: "divergence/chat",
        event: "draftTitlesChanged",
        payload: shared.draftTitles,
      });
  };
  const serviceSubs = new Map<string, Set<(payload: unknown) => void>>();
  const tabsClient = {
    open: Object.assign(
      async (params: { kind: string; workspaceId: string; path: string }) => ({
        id: `${params.kind}:${params.workspaceId}:${params.path}`,
      }),
      {
        // The Effect adapter calls through `result`, never the direct call.
        result: async (params: { kind: string; workspaceId: string; path: string }) => {
          serviceLog.push({ op: "call", name: "divergence/tabs", method: "open", params });
          return { ok: true as const, value: { id: `${params.kind}:${params.workspaceId}:${params.path}` } };
        },
      },
    ),
    close: Object.assign(async () => null, {
      result: async (params: unknown) => {
        serviceLog.push({ op: "call", name: "divergence/tabs", method: "close", params });
        return { ok: true as const, value: null };
      },
    }),
    active: Object.assign(async () => null, {
      result: async () => {
        serviceLog.push({ op: "call", name: "divergence/tabs", method: "active", params: {} });
        return { ok: true as const, value: null };
      },
    }),
    on: (event: string, fn: (payload: unknown) => void) => {
      const key = `divergence/tabs|${event}`;
      const set = serviceSubs.get(key) ?? new Set<(payload: unknown) => void>();
      serviceSubs.set(key, set);
      set.add(fn);
      return () => {
        set.delete(fn);
      };
    },
  };
  const servicesStub = {
    provide: async (def: { name: string }) => {
      serviceLog.push({ op: "provide", name: def.name });
      return {
        emit: (event: string, payload: unknown) => {
          serviceLog.push({ op: "emit", name: def.name, event, payload });
          for (const fn of serviceSubs.get(`${def.name}|${event}`) ?? []) fn(payload);
        },
        remove: () => {},
      };
    },
    get: (name: string) => {
      if (name === "divergence/tabs") return tabsClient;
      throw new Error(`no provider for ${name}`);
    },
    available: (name: string) => name === "divergence/tabs",
    when: (name: string, fn: (client: unknown) => void) => {
      fn(name === "divergence/tabs" ? tabsClient : undefined);
      return () => {};
    },
  };
  // This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
  const api = new Proxy(
    {
      ...broker.api,
      uiCapabilities: undefined,
      plugin: "chat",
      id: "divergence/chat",
      services: servicesStub,
      host: {
        ...broker.api.host,
        call,
        kernel: call,
        storage: { get: (p: unknown) => call("host/storage.get", p), set: (p: unknown) => call("host/storage.set", p) },
        chats: methods,
        security: { pending: (p: unknown) => call("host/security.pending", p) },
        agents: { list: (p: unknown) => call("host/agents.list", p) },
        workspaces: { list: (p: unknown) => call("host/workspaces.list", p) },
        tasks: { list: (p: unknown) => call("host/tasks.list", p) },
        fs: { search: (p: unknown) => call("host/fs.search", p) },
      },
      app: {
        state: () => state,
        update,
        share: (key: string, value: unknown) => update({ shared: { [key]: value } }),
        select: (chatId: string, workspaceId: string) => update({ chatId, workspaceId, route: "chat" }),
        route: (route: string) => update({ route }),
        onChange: (fn: (state: AppState) => void) => {
          appListeners.add(fn);
          return () => {
            appListeners.delete(fn);
          };
        },
      },
      layouts: fakeLayouts(),
      views: {
        add: (key: string, definition: any) => {
          const { slot: slot, render: render } = definition;
          const options = { ...definition, key };
          const _options = options;
          void slot;
          void _options;
          void options;
          const view = { slot, render, options, id: ++nextId, active: true, state: catalog?.viewStates?.[key] ?? {} };
          views.push(view);
          dirty = true;
          return {
            id: view.id,
            update: () => {
              updates.push(view.id);
              dirty = true;
            },
            remove: () => {
              view.active = false;
              dirty = true;
            },
          };
        },
      },
      on: (name: string, fn: (event: HostEvent) => unknown) => {
        const subscribers = listeners.get(name) ?? new Set();
        listeners.set(name, subscribers);
        subscribers.add(fn);
        return () => {
          subscribers.delete(fn);
        };
      },
      command: ({
        id,
        run,
      }: {
        id: string;
        run: (api: Api, info?: { applied: boolean; phase?: "press" | "release" | "cancel" }) => unknown;
      }) => {
        commands.set(id, (info) => run(api, info));
        return {
          remove: () => {
            commands.delete(id);
          },
        };
      },
      slash: () => ({ remove() {} }),
      slashCommands: () => [],
      mentions: { list: () => [] },
      toolRenderers: () => [],
      focus: (id: string) => {
        focus.push(id);
      },
      notify: (message: string) => {
        notices.push(message);
      },
      sleep: (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
    },
    {
      get(target, key, receiver) {
        if (Reflect.has(target, key)) return Reflect.get(target, key, receiver);
        throw new Error(`Unexpected API ${String(key)}`);
      },
    },
  ) as unknown as Api;
  let trees: { slot: string; options?: SlotOptions; tree: RenderResult }[] = [];
  const render = () => {
    trees = views
      .filter((view) => view.active)
      .map((view) => ({
        slot: view.slot,
        options: view.options,
        tree: view.render({
          state: view.state,
          set: () => {},
          app: state,
          plugin: "chat",
          update: () => {
            dirty = true;
          },
        }),
      }));
  };
  const settle = async () => {
    for (let round = 0; round < 100; round++) {
      await tick();
      if (!dirty) {
        await tick();
        if (!dirty) return;
      }
      dirty = false;
      render();
    }
    throw new Error("Chat did not settle");
  };
  const invoke = (id: string, event = "onClick", payload: unknown = undefined) => {
    const node = trees.flatMap((view) => nodes(view.tree)).find((node) => node.id === id);
    assert.ok(node, `element ${id}`);
    const handler = z
      .custom<(payload: unknown) => unknown>((value) => typeof value === "function")
      .parse(
        event === "onDrop"
          ? z.object({ drop: z.object({ onDrop: z.unknown() }) }).parse(node).drop.onDrop
          : node[event],
      );
    handler(payload);
  };
  const pressText = (text: string) => {
    const target = trees
      .flatMap((view) => nodes(view.tree))
      // A row's text is a text child, or an item's label.
      .filter(
        (node) =>
          typeof node.onClick === "function" &&
          nodes(node).some((child) => child.text === text || child.label === text),
      )
      .at(-1);
    assert.ok(target, text);
    target.onClick();
  };
  return {
    pressText,
    api,
    views,
    listeners,
    appListeners,
    calls,
    updates,
    focus,
    notices,
    commands,
    stored,
    update,
    settle,
    invoke,
    snapshot: () => stable({ trees, state, calls, notices, focus, serviceLog }),
    serviceLog,
    nodes: () => trees.flatMap((view) => nodes(view.tree)),
    renderNow: (slot: string, key?: string) => {
      const view = views.find((view) => view.active && view.slot === slot && (!key || view.options?.key === key));
      assert.ok(view, `registered ${slot} view`);
      return view.render({
        state: view.state,
        set: () => {},
        app: state,
        plugin: "chat",
        update: () => {
          dirty = true;
        },
      });
    },
    holdList: () => {
      const snapshot = chats.map((chat) => ({ ...chat }));
      const pending = Promise.withResolvers<{ chats: Chat[] }>();
      pendingList = pending.promise;
      return () => {
        pendingList = undefined;
        pending.resolve({ chats: snapshot });
      };
    },
    holdTranscript: () => {
      const snapshot = structuredClone(transcript);
      const pending = Promise.withResolvers<Snapshot>();
      pendingTranscript = pending.promise;
      return (next: Snapshot) => {
        transcript = next;
        pendingTranscript = undefined;
        pending.resolve(snapshot);
      };
    },
    emit: (event: HostEvent) => {
      for (const name of [event.event, "*"]) for (const fn of listeners.get(name) ?? []) fn(event);
    },
  };
}
const agent = (kind: AgentEventKind): HostEvent => ({ event: "agent", chatId: "c1", kind });
test("a selected cold chat starts admission before any view renders", async () => {
  const selected = chat({ id: "never-rendered" });
  const current = fake({ route: "chat", chatId: selected.id, shared: { selectedChat: selected } }, {}, { chats: [selected] });
  const dispose = activate(current.api);
  try {
    for (let turn = 0; turn < 100 && current.focus.at(-1) !== `prompt-${selected.id}`; turn++) await tick();
    assert.ok(current.calls.some((call) => call.method === "host/chats.transcript"), "selection starts the newest-page read before the fallback or any retained view renders");
    for (const method of ["host/chats.options", "host/drafts.get"])
      assert.ok(current.calls.some((call) => call.method === method && (call.params as { chatId?: string }).chatId === selected.id), `${method} starts at admission`);
    assert.ok(current.calls.some((call) => call.method === "host/storage.get" && (call.params as { key?: string }).key === `answers:${selected.id}`), "question answers start beside the transcript");
    assert.deepEqual(current.nodes(), [], "the fixture has not rendered a view to admit the chat");
    assert.equal(current.focus.at(-1), `prompt-${selected.id}`);
  } finally {
    await dispose();
  }
});

test("unknown metadata arriving after selection admits the current chat without a render", async () => {
  const current = fake({ route: "chat", chatId: "later" }, {}, { chats: [] });
  const dispose = activate(current.api);
  try {
    for (let turn = 0; turn < 5; turn++) await tick();
    assert.ok(!current.views.some((view) => view.options?.key === "chat:later"));
    current.emit({ event: "chat_changed", chat: chat({ id: "unrelated" }) });
    current.emit({ event: "chat_changed", chat: chat({ id: "later" }) });
    for (let turn = 0; turn < 100 && current.focus.at(-1) !== "prompt-later"; turn++) await tick();
    assert.deepEqual(current.focus, ["prompt-later"]);
    assert.ok(current.calls.some((call) => call.method === "host/chats.transcript" && (call.params as { chatId?: string }).chatId === "later"));
    assert.ok(!current.views.some((view) => view.options?.key === "chat:unrelated"), "unrelated metadata does not admit another chat");
    assert.deepEqual(current.nodes(), []);
  } finally {
    await dispose();
  }
});

test("a metadata response rechecks the latest selection before admitting its pane", async () => {
  const current = fake({ route: "chat", chatId: "a" }, {}, { chats: [chat({ id: "a" }), chat({ id: "c" })] });
  const release = current.holdList();
  const dispose = activate(current.api);
  try {
    await tick();
    current.update({ chatId: "b" });
    current.update({ chatId: "c" });
    release();
    for (let turn = 0; turn < 100 && current.focus.at(-1) !== "prompt-c"; turn++) await tick();
    assert.deepEqual(current.focus, ["prompt-c"]);
    assert.ok(current.views.some((view) => view.options?.key === "chat:c"));
    assert.ok(!current.views.some((view) => view.options?.key === "chat:a" || view.options?.key === "chat:b"));
    assert.deepEqual(current.nodes(), []);
  } finally {
    release();
    await dispose();
  }
});

test("a raw app notification starts known-target admission before a render or scheduler drain", async () => {
  const current = fake();
  const preparation = Promise.withResolvers<unknown>();
  const call = current.api.host.call;
  Object.assign(current.api.host, { call: (method: string, params: unknown) => {
    const response = call(method as keyof HostMethods, params as never);
    return method === "host/chats.prepare" ? preparation.promise : response;
  } });
  const dispose = activate(current.api);
  let releaseList = () => {};
  try {
    await current.settle();
    releaseList = current.holdList();
    current.emit({ event: "agents_changed" });
    await tick();
    const before = current.calls.length;
    current.update({ chatId: "c2" });
    // No render, await or scheduler drain may own this admission.
    assert.ok(current.calls.slice(before).some((call) => call.method === "host/chats.transcript" && (call.params as { chatId?: string }).chatId === "c2"), "the raw notification starts the page request in its own turn");
    const pane = current.views.find((view) => view.options?.key === "chat:c2");
    assert.ok(pane, "the same turn registers the local destination views");
    current.renderNow("center-presentation", "center-fallback");
    assert.equal(current.views.filter((view) => view.options?.key === "chat:c2").length, 1, "an immediate fallback render adopts the existing admission");
  } finally {
    releaseList();
    preparation.resolve({});
    await dispose();
  }
  const calls = current.calls.length;
  current.update({ chatId: "c1" });
  assert.equal(current.appListeners.size, 0);
  assert.equal(current.calls.length, calls, "scope teardown removes the notification owner");
});

test("a known cold selection bypasses unrelated metadata and initial preparation waits", async () => {
  const current = fake();
  const preparation = Promise.withResolvers<unknown>();
  const page = Promise.withResolvers<HostMethods["host/chats.transcript"]["result"]>();
  const call = current.api.host.call;
  Object.assign(current.api.host, { call: (method: string, params: unknown) => {
    const response = call(method as keyof HostMethods, params as never);
    const chatId = (params as { chatId?: string }).chatId;
    if (method === "host/chats.prepare" && chatId === "c1") return preparation.promise;
    if (method === "host/chats.transcript" && chatId === "c2") return page.promise;
    return response;
  } });
  const dispose = activate(current.api);
  let releaseList = () => {};
  const ready = { items: [item({ id: "cold-ready", role: "assistant", text: "The cold destination is ready" })], pendingApprovals: [], pendingQuestions: [], plan: null, usage: {}, running: false };
  try {
    await current.settle();
    assert.ok(current.views.some((view) => view.options?.key === "chat:c1"));
    releaseList = current.holdList();
    current.emit({ event: "agents_changed" });
    await tick();
    current.update({ chatId: "c2" });
    for (let turn = 0; turn < 100 && !current.calls.some((call) => call.method === "host/chats.transcript" && (call.params as { chatId?: string }).chatId === "c2"); turn++) await tick();
    assert.ok(current.calls.some((call) => call.method === "host/chats.transcript" && (call.params as { chatId?: string }).chatId === "c2"), "the cached catalog admits the destination before unrelated list or prepare replies");
    assert.ok(current.views.some((view) => view.options?.key === "chat:c2"), "registration is local and does not await the snapshot");
    page.resolve(ready);
    await current.settle();
    assert.ok(current.nodes().some((node) => node.text === "The cold destination is ready"));
    assert.equal(current.focus.at(-1), "prompt-c2");
  } finally {
    releaseList();
    preparation.resolve({});
    page.resolve(ready);
    await dispose();
  }
});

test("the retained center state is restored before its internal fallback renders", async () => {
  const kept = {
    ...initialTranscript(),
    items: [item({ id: "kept", role: "assistant", text: "Retained before reload" })],
    snapshot: { kind: "ready" },
  };
  const current = fake(
    undefined,
    {},
    {
      chats: [chat({ id: "c1", sessionId: "session-c1" })],
      viewStates: { center: { transcripts: { c1: kept } } },
    },
  );
  const release = current.holdTranscript();
  const snapshot = { items: kept.items, pendingApprovals: [], pendingQuestions: [], plan: null, usage: {}, running: false };
  const dispose = activate(current.api);
  try {
    await current.settle();
    assert.deepEqual(
      current.views.slice(0, 3).map((view) => view.options?.key),
      ["center", "center-fallback", "center-cases"],
      "the reload-state owner registers before any internal center can render",
    );
    assert.ok(
      current.nodes().some((node) => node.text === "Retained before reload"),
      "the cached rows survive while their refresh waits",
    );
    assert.equal(
      Object.hasOwn(current.views.find((view) => view.options?.key === "center-fallback")?.state ?? {}, "transcripts"),
      false,
      "the internal fallback never becomes a second reload-state owner",
    );
    release(snapshot);
    await current.settle();
  } finally {
    release(snapshot);
    await dispose();
  }
});

test("a reload keeps retained rows when eager admission fails before the first render", async () => {
  const kept = { ...initialTranscript(), items: [item({ id: "kept", role: "assistant", text: "Retained through failure" })] };
  const selected = chat({ id: "c1" });
  const current = fake({ route: "chat", chatId: selected.id, shared: { selectedChat: selected } }, {}, {
    chats: [selected], viewStates: { center: { transcripts: { c1: kept } } },
  });
  const call = current.api.host.call;
  Object.assign(current.api.host, { call: (method: string, params: unknown) =>
    method === "host/chats.transcript" ? Promise.reject(new Error("store unavailable")) : call(method as keyof HostMethods, params as never),
  });
  const dispose = activate(current.api);
  try {
    for (let turn = 0; turn < 5; turn++) await tick();
    await current.settle();
    assert.ok(current.nodes().some((node) => node.text === "Retained through failure"));
    assert.ok(current.nodes().some((node) => node.id === "transcript-retry-c1"));
    assert.ok(current.nodes().some((node) => node.text?.includes("store unavailable")));
  } finally {
    await dispose();
  }
});

test("new-chat metadata prepares the composer while its snapshot establishes content readiness", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    const releaseList = current.holdList();
    const releaseTranscript = current.holdTranscript();
    for (const id of ["created", "created-2", "created-3"]) {
      const selected = chat({ id, sessionId: undefined });
      current.update({ chatId: selected.id, shared: { selectedChat: selected } });
      const firstCenter = nodes(current.renderNow("center-presentation", "center-fallback"));
      for (let turn = 0; turn < 100 && !current.views.some((view) => view.active && view.options?.key === `chat:${id}`); turn++) await tick();
      const pane = current.views.find((view) => view.active && view.options?.key === `chat:${id}`);
      assert.ok(pane, "the selection listener makes the retained pane without another render");
      // The new pane has no tree yet: the center keeps what it showed (the
      // last pane, or a skeleton), never an empty view.
      assert.ok(
        !firstCenter.some((node) => node.type === "view" && node.view === pane.id),
        "the center waits for the pane's first tree",
      );
      assert.ok(
        !firstCenter.some((node) => node.id === `prompt-${id}`),
        "no temporary input in a different native cache",
      );
      // The pane places the chat's composer, a view of its own.
      const composer = current.views.find((view) => view.active && view.options?.key === `composer:${id}`);
      assert.ok(composer, "the pane comes with its composer view");
      assert.ok(
        nodes(current.renderNow("pane", `chat:${id}`)).some(
          (node) => node.type === "view" && node.view === composer.id,
        ),
      );
      assert.ok(nodes(current.renderNow("composer", `composer:${id}`)).some((node) => node.id === `prompt-${id}`));
      assert.ok(
        !nodes(current.renderNow("center-presentation", "center-fallback")).some(
          (node) => node.type === "view" && node.view === pane.id,
        ),
        "a drawn pane is not published before its transcript snapshot",
      );
      assert.ok(current.focus.includes(`prompt-${id}`), "pane setup and focus do not wait for host reads");
    }
    await current.settle();
    assert.ok(current.nodes().some((node) => node.id === "prompt-created-3"));
    assert.ok(!current.nodes().some((node) => node.type === "empty" && node.text === "Loading…"));
    releaseList();
    releaseTranscript({ items: [], pendingApprovals: [], pendingQuestions: [], plan: null, usage: {}, running: false });
    await current.settle();
    const admitted = current.views.find((view) => view.active && view.options?.key === "chat:created-3")!;
    assert.ok(nodes(current.renderNow("center-presentation", "center-fallback")).some((node) => node.type === "view" && node.view === admitted.id));
    assert.ok(current.nodes().some((node) => node.id === "prompt-created-3"));
  } finally {
    await dispose();
  }
});

test("a history reset reads again a split pane on screen that is not selected", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    const tab = (chatId: string) => ({ kind: "chat" as const, chatId });
    const side = (id: string, chatId: string) => ({ share: 0.5, layout: { kind: "pane" as const, id, tabs: [tab(chatId)], active: tab(chatId) } });
    current.emit({
      event: "task_changed",
      task: { id: "t", layout: { root: { kind: "split", id: "s", direction: "row", children: [side("p1", "c1"), side("p2", "c2")] }, focused: "p1" }, createdAt: "", updatedAt: "" },
    });
    await current.settle();
    const reads = () => current.calls.filter((call) => call.method === "host/chats.transcript" && (call.params as { chatId: string }).chatId === "c2").length;
    const before = reads();
    assert.ok(before > 0, "the pane beside the selected one is read when it shows");
    current.emit({ event: "transcript_reset", chatId: "c2" });
    await current.settle();
    assert.equal(reads(), before + 1, "its rows are read again at once, not when it is selected");
  } finally {
    await dispose();
  }
});

test("history reset keeps the visible transcript and discards a snapshot overtaken by streamed input", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    current.emit(agent({ event: "text_delta", itemId: "answer", mode: "append", text: "Visible before refresh" }));
    await current.settle();
    const release = current.holdTranscript();
    current.emit({ event: "transcript_reset", chatId: "c1" });
    await current.settle();
    assert.ok(
      current.nodes().some((node) => node.text === "Visible before refresh"),
      "reset never blanks an already visible chat",
    );
    const prompt = {
      id: "user-new",
      role: "user" as const,
      blocks: [{ type: "text" as const, text: "New prompt during history load" }],
    };
    current.emit({ event: "user_message", chatId: "c1", item: prompt });
    current.emit({ event: "user_message", chatId: "c1", item: prompt });
    current.emit(agent({ event: "text_delta", itemId: "new-answer", mode: "append", text: "New streamed response" }));
    await current.settle();
    assert.equal(
      current.nodes().filter((node) => node.text === "New prompt during history load").length,
      1,
      "canonical event is idempotent",
    );
    release({
      items: [
        { id: "answer", role: "assistant", text: "Visible before refresh" },
        prompt,
        { id: "new-answer", role: "assistant", text: "New streamed response" },
      ],
      pendingApprovals: [],
      pendingQuestions: [],
      plan: null,
      usage: {},
      running: true,
    });
    await current.settle();
    assert.equal(current.nodes().filter((node) => node.text === "New prompt during history load").length, 1);
    assert.ok(current.nodes().some((node) => node.text === "New streamed response"));
    // The prompt has no time, so the run counts from when it arrived.
    assert.ok(current.nodes().some((node) => /^Working for \d+s$/.test(String(node.text))));
  } finally {
    await dispose();
  }
});

test("a stale list refresh keeps the Stop button while the new turn runs", async () => {
  const current = fake(
    undefined,
    {},
    { chats: [chat({ id: "c1", sessionId: "s", updatedAt: "2026-10-04T17:00:00Z" })] },
  );
  const dispose = activate(current.api);
  try {
    await current.settle();
    const release = current.holdList();
    current.emit({ event: "agents_changed" });
    await current.settle();
    current.emit({
      event: "chat_changed",
      chat: chat({ id: "c1", sessionId: "s", status: "running", updatedAt: "2026-10-04T17:01:00Z" }),
    });
    current.emit(agent({ event: "run_started" }));
    current.emit(
      agent({
        event: "tool_call_started",
        id: "tool",
        name: "Bash",
        kind: "execute",
        title: "Run tests",
        status: "running",
      }),
    );
    await current.settle();
    assert.ok(current.nodes().some((node) => node.id === "stop-c1"));
    release();
    await current.settle();
    assert.ok(
      current.nodes().some((node) => node.id === "stop-c1"),
      "the live turn must retain its Stop button after the older list arrives",
    );
    current.invoke("stop-c1");
    await current.settle();
    assert.ok(current.calls.some((call) => call.method === "host/chats.cancel"));
    current.emit({
      event: "chat_changed",
      chat: chat({ id: "c1", sessionId: "s", status: "idle", updatedAt: "2026-10-04T17:02:00Z" }),
    });
    current.emit(agent({ event: "run_finished", outcome: { status: "cancelled" } }));
    await current.settle();
    assert.ok(!current.nodes().some((node) => node.id === "stop-c1"), "Stop disappears when the run actually ends");
  } finally {
    await dispose();
  }
});
test("a stale running list cannot bring back Stop after completion", async () => {
  const current = fake(
    undefined,
    {},
    { chats: [chat({ id: "c1", sessionId: "s", status: "running", updatedAt: "2026-10-04T17:00:00Z" })] },
  );
  const dispose = activate(current.api);
  try {
    await current.settle();
    assert.ok(current.nodes().some((node) => node.id === "stop-c1"));
    const release = current.holdList();
    current.emit({ event: "agents_changed" });
    await current.settle();
    current.emit({
      event: "chat_changed",
      chat: chat({ id: "c1", sessionId: "s", status: "idle", updatedAt: "2026-10-04T17:01:00Z" }),
    });
    current.emit(agent({ event: "run_finished", outcome: { status: "completed" } }));
    await current.settle();
    release();
    await current.settle();
    assert.ok(!current.nodes().some((node) => node.id === "stop-c1"));
  } finally {
    await dispose();
  }
});
test("chat streaming refreshes its pane and unload releases every registration and stream", async () => {
  const current = fake();
  const dispose = activate(current.api);
  await current.settle();
  current.updates.length = 0;
  current.emit(agent({ event: "text_delta", itemId: "a", text: "Hello", mode: "append" }));
  await current.settle();
  assert.deepEqual(
    current.updates,
    [
      current.views.find((view) => view.slot === "pane")?.id,
      current.views.find((view) => view.slot === "composer")?.id,
    ],
    "a delta updates only the chat's pane and its composer",
  );
  await dispose();
  assert.ok(current.views.every((view) => !view.active));
  assert.equal(current.appListeners.size, 0);
  assert.ok([...current.listeners.values()].every((listeners) => !listeners.size));
  assert.equal(current.commands.size, 0);
});
test("accepting a picker choice updates only the chat's composer", async () => {
  // A titled chat: a draft's title follows its text, in the title strip.
  const current = fake(undefined, {}, { chats: [chat({ id: "c1", title: "Caching" })] });
  const dispose = activate(current.api);
  await current.settle();
  current.invoke("prompt-c1", "onChange", { value: "Read @src" });
  await current.settle();
  current.updates.length = 0;
  current.invoke("file-src/main.ts");
  await current.settle();
  assert.deepEqual(
    current.updates,
    [current.views.find((view) => view.slot === "composer")?.id],
    "the pane with the transcript does not render again",
  );
  assert.throws(() => current.invoke("file-src/main.ts"), "the picker closed");
  await dispose();
});

/** Whether Revert shows under a message. */
const revertShown = (rendered: TestNode[], itemId: string) => rendered.some((node) => node.id === `restore-${itemId}`);

test("a fresh chat keeps its prompt and progress while checkpoint metadata loads", async () => {
  const checkpoints = Promise.withResolvers<HostMethods["host/chats.checkpoints"]["result"]>();
  const current = fake(undefined, {}, { chats: [chat({ id: "c1" })], checkpoints: checkpoints.promise });
  const dispose = activate(current.api);
  try {
    await current.settle();
    assert.ok(current.calls.some((call) => call.method === "host/chats.transcript"));
    current.invoke("prompt-c1", "onChange", { value: "Inspect README.md" });
    await current.settle();
    current.invoke("prompt-c1", "onSubmit");
    await current.settle();
    assert.ok(current.calls.some((call) => call.method === "host/chats.send"));
    current.emit({
      event: "user_message",
      chatId: "c1",
      item: item({ id: "u", role: "user", text: "Inspect README.md" }),
    });
    current.emit({
      event: "chat_changed",
      chat: chat({ id: "c1", title: "Inspect README.md", status: "running", sessionId: "s" }),
    });
    current.emit(
      agent({ event: "text_delta", itemId: "a", text: "I’m reading the project instructions.", mode: "append" }),
    );
    await current.settle();
    current.emit(
      agent({
        event: "tool_call_started",
        id: "read",
        name: "read_file",
        kind: "read",
        title: "Read README.md",
        status: "running",
        content: [],
        locations: [],
      }),
    );
    current.emit(agent({ event: "run_finished", outcome: { status: "completed" } }));
    current.emit({ event: "chat_changed", chat: chat({ id: "c1", title: "Inspect README.md", status: "idle", sessionId: "s" }) });
    await current.settle();
    // The host took the prompt's checkpoint when it dispatched it.
    checkpoints.resolve({ checkpoints: [{ itemId: "u", createdAt: "2026-11-11T12:00:00Z" }] });
    await current.settle();
    const rendered = current.nodes();
    assert.ok(
      rendered.some((node) => node.id === "transcript-c1"),
      "the center shows the transcript, not the new-chat page",
    );
    assert.ok(
      rendered.some((node) => node.text === "Inspect README.md"),
      "the sent prompt remains visible",
    );
    assert.ok(
      rendered.some((node) => node.text === "I’m reading the project instructions."),
      "live progress remains visible",
    );
    assert.ok(
      rendered.some((node) => node.text === "Read README.md"),
      "tool activity remains visible",
    );
    assert.ok(revertShown(rendered, "u"), "the run over, Revert shows under the prompt the host holds a checkpoint for");
    assert.deepEqual(current.notices, []);
  } finally {
    checkpoints.resolve({ checkpoints: [] });
    await dispose();
  }
});

test("Revert never shows under a message the host took no checkpoint for, such as a steer or a prompt with the setting off", async () => {
  const current = fake(undefined, {}, { chats: [chat({ id: "c1" })] });
  const dispose = activate(current.api);
  try {
    await current.settle();
    current.emit({ event: "user_message", chatId: "c1", item: item({ id: "u", role: "user", text: "Inspect README.md" }) });
    current.emit({ event: "user_message", chatId: "c1", item: item({ id: "steer", role: "user", text: "Look at the tests too" }) });
    current.emit(agent({ event: "run_finished", outcome: { status: "completed" } }));
    await current.settle();
    const rendered = current.nodes();
    assert.ok(rendered.some((node) => node.text === "Look at the tests too"));
    assert.deepEqual([revertShown(rendered, "u"), revertShown(rendered, "steer")], [false, false]);
    const reads = current.calls.filter((call) => call.method === "host/chats.checkpoints").length;
    assert.ok(reads >= 2, "the checkpoints are read again once the run ends");
  } finally {
    await dispose();
  }
});

test("checkpoint loading errors leave the transcript usable and surface the error", async () => {
  const checkpoints = Promise.withResolvers<HostMethods["host/chats.checkpoints"]["result"]>();
  const current = fake(undefined, {}, { chats: [chat({ id: "c1" })], checkpoints: checkpoints.promise });
  const dispose = activate(current.api);
  try {
    await current.settle();
    current.emit({
      event: "user_message",
      chatId: "c1",
      item: item({ id: "u", role: "user", text: "Inspect README.md" }),
    });
    await current.settle();
    checkpoints.reject(new Error("checkpoint store unavailable"));
    await current.settle();
    assert.ok(current.nodes().some((node) => node.id === "transcript-c1"));
    assert.ok(current.nodes().some((node) => node.text === "Inspect README.md"));
    assert.deepEqual(current.notices, ["Checkpoints unavailable: checkpoint store unavailable"]);
  } finally {
    checkpoints.resolve({ checkpoints: [] });
    await dispose();
  }
});

// A question with a free-form field and a choice the user may answer in
// their own words, as a running chat holds it on the host.
const asking: HostMethods["host/chats.transcript"]["result"] = {
  items: [],
  pendingApprovals: [],
  pendingQuestions: [
    {
      id: "q1",
      message: "Which database?",
      fields: [
        { id: "name", label: "Name", kind: "text", options: [] },
        {
          id: "db",
          label: "Database",
          kind: "select",
          options: [{ value: "pg", label: "Postgres" }],
          allowOther: true,
        },
      ],
    },
  ],
  plan: null,
  usage: {},
  running: true,
};
const typeAnswers = async (current: ReturnType<typeof fake>) => {
  current.invoke("q-q1-name", "onChange", { value: "Ada" });
  current.invoke("q-q1-db-other", "onChange", { value: "SQLite, embedded" });
  await current.settle();
};
test("answers typed into a question survive a plugin reload", async () => {
  const before = fake(undefined, {}, { chats: [chat({ id: "c1" })], transcript: asking });
  const unload = activate(before.api);
  await before.settle();
  await typeAnswers(before);
  await unload();
  const after = fake(undefined, before.stored, { chats: [chat({ id: "c1" })], transcript: asking });
  const dispose = activate(after.api);
  try {
    await after.settle();
    const value = (id: string) => after.nodes().find((node) => node.id === id)?.value;
    assert.equal(value("q-q1-name"), "Ada");
    assert.equal(value("q-q1-db-other"), "SQLite, embedded");
    after.invoke("q-submit-q1");
    await after.settle();
    assert.deepEqual(
      after.calls.find((call) => call.method === "host/chats.respond_question")?.params,
      { chatId: "c1", questionId: "q1", answer: { values: { name: "Ada", db: "SQLite, embedded" }, cancelled: false } },
      "the restored answers are the ones sent",
    );
    assert.deepEqual(after.stored["answers:c1"], {}, "an answered question keeps nothing");
  } finally {
    await dispose();
  }
});
test("a question resolved elsewhere drops its typed answers", async () => {
  const current = fake(undefined, {}, { chats: [chat({ id: "c1" })], transcript: asking });
  const dispose = activate(current.api);
  try {
    await current.settle();
    await typeAnswers(current);
    assert.deepEqual(current.stored["answers:c1"], { q1: { name: "Ada", db: "SQLite, embedded" } });
    current.emit(agent({ event: "question_resolved", id: "q1" }));
    await current.settle();
    assert.deepEqual(current.stored["answers:c1"], {});
  } finally {
    await dispose();
  }
});
test("stored answers for a question that is no longer pending are not restored", async () => {
  const current = fake(
    undefined,
    { "answers:c1": { gone: { name: "Stale" } } },
    { chats: [chat({ id: "c1" })], transcript: asking },
  );
  const dispose = activate(current.api);
  try {
    await current.settle();
    assert.equal(current.nodes().find((node) => node.id === "q-q1-name")?.value, "");
    assert.deepEqual(current.stored["answers:c1"], {});
  } finally {
    await dispose();
  }
});
// The sidebar hands over the chat it selects, so the center draws it
// without reading the list; the Ctrl+Tab switcher still needs every chat.
test("the switcher lists every chat when the center never had to read the list", async () => {
  const first = chat({ id: "c1", title: "First" });
  const current = fake(
    { route: "chat", chatId: "c1", workspaceId: "w", shared: { selectedChat: first } },
    {},
    {
      chats: [first, chat({ id: "c2", title: "Second" }), chat({ id: "c3", title: "Third" })],
    },
  );
  const dispose = activate(current.api);
  try {
    await current.settle();
    await current.commands.get("chat.switchNext")?.();
    const rows = nodes(current.renderNow("title-presentation", "title-fallback")).filter(
      (node) => typeof node.id === "string" && node.id.startsWith("switch-"),
    );
    assert.deepEqual(
      rows.map((node) => node.id),
      ["switch-c1", "switch-c2", "switch-c3"],
    );
  } finally {
    await dispose();
  }
});

test("keyboard switcher selection prehydrates its fixed presentation without selecting or focusing it", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    const focused = [...current.focus];
    await current.commands.get("chat.switchNext")?.();
    await current.settle();

    assert.equal(current.api.app.state().chatId, "c1", "holding the switcher does not commit its selection");
    for (const key of ["chat:c2", "composer:c2", "center:c2", "title:c2"])
      assert.ok(
        current.views.some((view) => view.active && view.options?.key === key),
        `${key} is prepared`,
      );
    assert.deepEqual(current.focus, focused, "prehydration does not move the keyboard");
    assert.ok(
      !current.calls.some(
        (call) =>
          (call.params as { chatId?: string }).chatId === "c2" &&
          (call.method === "host/chats.prepare" || call.method === "host/chats.load_history"),
      ),
      "selection-only work waits for commit",
    );
  } finally {
    await dispose();
  }
});

test("the native held lifecycle commits once on release and cancels without selecting", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    const next = current.commands.get("chat.switchNext");
    assert.ok(next);
    await next({ applied: false, phase: "press" });
    assert.equal(current.api.app.state().chatId, "c1", "a press only moves the cycle selection");
    await next({ applied: false, phase: "release" });
    assert.equal(current.api.app.state().chatId, "c2", "release commits the selected chat");
    await next({ applied: false, phase: "release" });
    assert.equal(current.api.app.state().chatId, "c2", "a duplicate terminal event cannot switch again");

    await next({ applied: false, phase: "press" });
    await next({ applied: false, phase: "cancel" });
    assert.equal(current.api.app.state().chatId, "c2", "cancellation closes the cycle without selection");
  } finally {
    await dispose();
  }
});

test("a phase-less command retains the older host overlay release fallback", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    await current.commands.get("chat.switchNext")?.();
    await current.settle();
    current.invoke("chat-switcher", "onRelease");
    await current.settle();
    assert.equal(current.api.app.state().chatId, "c2");
  } finally {
    await dispose();
  }
});

test("the shell routes warm chats to complete retained center and title presentations", async () => {
  const current = fake();
  const dispose = activate(current.api);
  try {
    await current.settle();
    const byKey = (key: string) => current.views.find((view) => view.active && view.options?.key === key);
    const centerFallback = byKey("center-fallback");
    const centerCases = byKey("center-cases");
    const centerChat = byKey("center:c1");
    const titleFallback = byKey("title-fallback");
    const titleCases = byKey("title-cases");
    const titleOffRoute = byKey("title-off-route");
    const titleChat = byKey("title:c1");
    assert.ok(centerFallback && centerCases && centerChat && titleFallback && titleCases && titleOffRoute && titleChat);

    const centerRoute = nodes(current.renderNow("center"))[0];
    assert.equal(centerRoute?.view, centerFallback.id, "older hosts keep the complete dynamic fallback");
    assert.deepEqual(centerRoute?.select, {
      key: "route",
      cases: { chat: { view: centerCases.id } },
      default: { view: 0 },
    });
    const centerSelector = nodes(current.renderNow("center-presentation", "center-cases"))[0];
    assert.deepEqual((centerSelector?.select as { cases: Record<string, unknown> }).cases.c1, {
      view: centerChat.id,
      focus: "prompt-c1",
    });

    const titleRoute = nodes(current.renderNow("title"))[0];
    assert.equal(titleRoute?.view, titleFallback.id);
    assert.deepEqual(titleRoute?.select, {
      key: "route",
      cases: { chat: { view: titleCases.id } },
      default: { view: titleOffRoute.id },
    });
    const titleSelector = nodes(current.renderNow("title-presentation", "title-cases"))[0];
    assert.deepEqual((titleSelector?.select as { cases: Record<string, unknown> }).cases.c1, { view: titleChat.id });
  } finally {
    await dispose();
  }
});

test("a drawn pane stays on the dynamic fallback until its content is ready", async () => {
  const current = fake(undefined, {}, { chats: [chat({ id: "c1", sessionId: "session-c1" })] });
  const release = current.holdTranscript();
  const dispose = activate(current.api);
  try {
    await current.settle();
    const selector = () =>
      nodes(current.renderNow("center-presentation", "center-cases"))[0]?.select as {
        cases: Record<string, unknown>;
      };
    assert.equal(selector().cases.c1, undefined, "a skeleton tree is not advertised as a warm destination");

    release({
      items: [item({ id: "answer", role: "assistant", text: "Ready" })],
      pendingApprovals: [],
      pendingQuestions: [],
      plan: null,
      usage: {},
      running: false,
    });
    await current.settle();
    assert.ok(selector().cases.c1, "the same retained presentation becomes selectable when its pane is ready");
  } finally {
    await dispose();
  }
});

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.