Official
sidebar
Built-in sidebar 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/sidebar@0.2.5
Permissions in 0.2.5
Files
testing.ts15.2 KB
// The sidebar plugin run against a fake host that keeps chats and tasks
// the way the host does (every chat that is not archived has a task; an
// archived chat leaves its task, and one brought back gets a task of its
// own) and sends its events after it answers, the order the sidebar cannot
// count on. Its timers are Node's mocked ones.
import assert from "node:assert/strict";
import { mock } from "node:test";
import type { Api, AppState, AppStatePatch, Chat, HostEvent, RenderResult, ViewContext } from "divergence";
import type { Layout, Task } from "divergence/protocol";
import { testLayer } from "divergence/effect/testing";
// A service client over plain functions: each method answers with what its
// function returns, and events never come.
const serviceClient = (methods: FakeChat) => ({
on: () => () => {},
...Object.fromEntries(
Object.entries(methods).map(([name, method]) => [
name,
Object.assign(async (params: unknown) => method(params), { result: async (params: unknown) => ({ ok: true, value: await method(params) }) }),
]),
),
});
export const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
export type Pane = Extract<Layout, { kind: "pane" }>;
export const chatTab = (chatId: string) => ({ kind: "chat" as const, chatId });
// The node that holds the node `id` among its children.
function parentOf(value: unknown, id: string): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return;
if (Array.isArray(value)) return value.map((child) => parentOf(child, id)).find(Boolean);
const node = value as Record<string, unknown>;
const children = [node.children, node.items].flat().filter(Boolean) as Record<string, unknown>[];
return children.some((child) => child?.id === id) ? node : (parentOf(node.children, id) ?? parentOf(node.items, id));
}
function findNode(value: unknown, id: string): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return;
if (Array.isArray(value)) return value.map((child) => findNode(child, id)).find(Boolean);
const node = value as Record<string, unknown>;
return node.id === id ? node : (findNode(node.children, id) ?? findNode(node.items, id));
}
// The list top to bottom: each section's heading, then its rows and child rows.
function listOf(value: unknown, out: string[] = []): string[] {
if (!value || typeof value !== "object") return out;
if (Array.isArray(value)) {
for (const child of value) listOf(child, out);
return out;
}
const node = value as Record<string, unknown>;
if (typeof node.id === "string" && /^(heading|row|child)-/.test(node.id)) out.push(node.id);
listOf(node.children, out);
listOf(node.items, out);
return out;
}
export interface Seed {
readonly id: string;
readonly title: string;
readonly at: string;
readonly done?: string;
}
// The chat plugin's service as the sidebar sees it, when a test gives one.
export type FakeChat = Record<string, (params: unknown) => unknown>;
export function fakeHost(seeds: readonly Seed[], groups: readonly { id: string; chats: readonly string[]; title?: string }[] = [], chatService?: FakeChat) {
mock.timers.enable({ apis: ["setTimeout", "Date"] });
let clock = Date.parse("2026-11-01T00:00:00Z");
const stamp = () => new Date((clock += 1000)).toISOString();
let ids = 0;
let app: AppState = { workspaceId: "w1", route: "chat" };
const views: { render: (ctx: ViewContext<object>) => RenderResult; state: object }[] = [];
const listeners = new Map<string, Set<(event: HostEvent) => unknown>>();
const calls: { method: string; params: unknown }[] = [];
const notices: string[] = [];
const focused: string[] = [];
const commands = new Map<string, () => unknown>();
let peeks = 0;
const failing = new Map<string, string>();
// Calls to a held method answer only once the test releases them.
const held = new Map<string, Promise<void>>();
let dirty = true;
const chats: Chat[] = seeds.map((seed) => ({
id: seed.id,
workspaceId: "w1",
agentId: "a",
sessionId: "s",
title: seed.title,
createdAt: seed.at,
updatedAt: seed.at,
archived: false,
options: {},
status: "idle",
}));
const tasks = new Map<string, Task>();
const paneOf = (task: Task) => task.layout.root as Pane;
const makeTask = (id: string, members: readonly string[], title: string | null, completedAt: string | null) => {
const pane: Pane = { kind: "pane", id: `pane-${id}`, tabs: members.map(chatTab), active: chatTab(members[0]!) };
tasks.set(id, { id, title, layout: { root: pane, focused: pane.id }, completedAt, createdAt: "", updatedAt: "" });
};
for (const group of groups) makeTask(group.id, group.chats, group.title ?? null, null);
for (const seed of seeds)
if (![...tasks.values()].some((task) => paneOf(task).tabs.some((tab) => tab.kind === "chat" && tab.chatId === seed.id)))
makeTask(`t-${seed.id}`, [seed.id], null, seed.done ?? null);
const homeOf = (chatId: string) =>
[...tasks.values()].find((task) => paneOf(task).tabs.some((tab) => tab.kind === "chat" && tab.chatId === chatId));
const chat = (chatId: string) => chats.find((c) => c.id === chatId)!;
// What one call changed, sent once it has answered.
let batch: HostEvent[] = [];
const emitChat = (chatId: string) => batch.push({ event: "chat_changed", chat: { ...chat(chatId), task: homeOf(chatId)?.id } });
const emitTask = (id: string) => batch.push({ event: "task_changed", task: structuredClone(tasks.get(id)!) });
const takeOut = (chatId: string) => {
const task = homeOf(chatId);
if (!task) return;
const pane = paneOf(task);
const tabs = pane.tabs.filter((tab) => !(tab.kind === "chat" && tab.chatId === chatId));
if (!tabs.length) {
tasks.delete(task.id);
batch.push({ event: "task_removed", taskId: task.id });
return;
}
const root: Pane = { ...pane, tabs, active: tabs[0]! };
tasks.set(task.id, { ...task, title: tabs.length < 2 ? null : task.title, layout: { ...task.layout, root } });
emitTask(task.id);
};
const putIn = (taskId: string, chatId: string, index?: number) => {
const task = tasks.get(taskId);
if (!task) throw new Error("That task is gone");
takeOut(chatId);
const pane = paneOf(tasks.get(taskId)!);
const tabs = [...pane.tabs];
tabs.splice(index ?? tabs.length, 0, chatTab(chatId));
tasks.set(taskId, { ...tasks.get(taskId)!, layout: { root: { ...pane, tabs }, focused: pane.id } });
emitTask(taskId);
emitChat(chatId);
};
const setArchived = (chatId: string, archived: boolean) => {
const index = chats.findIndex((c) => c.id === chatId);
if (index < 0) throw new Error(`unknown chat ${chatId}`);
chats[index] = { ...chats[index]!, archived, updatedAt: stamp() };
emitChat(chatId);
if (archived) return takeOut(chatId);
const id = `t${++ids}`;
makeTask(id, [chatId], null, null);
emitTask(id);
emitChat(chatId);
};
const answer = (method: string, params: Record<string, unknown>): unknown => {
if (method === "host/storage.get") return { value: undefined };
if (method === "host/storage.set") return {};
if (method === "host/chats.peek") return { items: [] };
if (method === "host/tasks.list") return { tasks: [...tasks.values()].map((task) => structuredClone(task)) };
if (method === "host/chats.update") {
const chatId = params.chatId as string;
if (typeof params.archived === "boolean") setArchived(chatId, params.archived);
if (typeof params.completed === "boolean") {
const home = homeOf(chatId)!;
tasks.set(home.id, { ...home, completedAt: params.completed ? stamp() : null });
emitTask(home.id);
}
return { ...chat(chatId), task: homeOf(chatId)?.id };
}
if (method === "host/tasks.archive") {
for (const tab of paneOf(tasks.get(params.taskId as string)!).tabs) if (tab.kind === "chat") setArchived(tab.chatId, true);
return {};
}
if (method === "host/tasks.update") {
const task = tasks.get(params.taskId as string)!;
tasks.set(task.id, { ...task, title: params.title as string });
emitTask(task.id);
return { changed: {} };
}
if (method === "host/layouts.close_tab") {
// A started chat's tab closed: it leaves its task, checked off.
const chatId = (params.tab as { chatId: string }).chatId;
takeOut(chatId);
const id = `t${++ids}`;
makeTask(id, [chatId], null, stamp());
emitTask(id);
emitChat(chatId);
return { changed: {}, closed: null };
}
if (method === "host/layouts.place") {
const chatId = (params.tab as { chatId: string }).chatId;
const target = params.target as { kind: string; taskId?: string; paneId?: string; index?: number };
if (target.kind === "join") putIn(target.taskId!, chatId);
else if (target.kind === "strip") putIn([...tasks.values()].find((t) => paneOf(t).id === target.paneId)!.id, chatId, target.index);
else if (target.kind === "alone") {
takeOut(chatId);
const id = `t${++ids}`;
makeTask(id, [chatId], null, null);
emitTask(id);
emitChat(chatId);
}
else throw new Error(`Unexpected target ${target.kind}`);
return { changed: {} };
}
throw new Error(`Unexpected host method ${method} ${JSON.stringify(params)}`);
};
const deliver = (events: HostEvent[]) => {
for (const event of events) for (const fn of listeners.get(event.event) ?? []) fn(event);
};
const hostCall = async (method: string, params: Record<string, unknown>) => {
if (method === "host/chats.peek") peeks++;
if (!["host/storage.get", "host/storage.set", "host/chats.peek"].includes(method)) calls.push({ method, params });
const gate = held.get(method);
if (gate) await gate;
const failure = failing.get(method);
if (failure) throw new Error(failure);
const result = answer(method, params);
const events = batch;
batch = [];
setImmediate(() => deliver(events));
return result;
};
const broker = testLayer();
const update = (patch: AppStatePatch) => {
app = { ...app, ...patch, chatId: patch.chatId === null ? undefined : (patch.chatId ?? app.chatId) } as AppState;
dirty = true;
};
const api = new Proxy(
{
...broker.api,
plugin: "sidebar",
id: "divergence/sidebar",
services: {
provide: async () => ({ emit: () => {}, remove: () => {} }),
get: (name: string) => {
throw new Error(`no provider for ${name}`);
},
available: () => false,
when: (name: string, fn: (client: unknown) => void) => {
fn(name === "divergence/chat" && chatService ? serviceClient(chatService) : undefined);
return () => {};
},
},
host: {
...broker.api.host,
workspaces: { list: async () => ({ workspaces: [{ id: "w1", name: "Workspace", path: "/fixture", position: 0 }] }) },
chats: {
list: async () => {
const failure = failing.get("host/chats.list");
if (failure) throw new Error(failure);
return { chats: chats.map((c) => ({ ...c, task: homeOf(c.id)?.id })) };
},
},
agents: { list: async () => ({ agents: [{ id: "a", name: "A" }] }) },
call: hostCall,
kernel: async (method: string) => {
if (method === "menu.entries") return { entries: [] };
if (method === "commands") return { commands: [{ id: "sidebar.toggleChatCompleted", labels: ["⇧⌘M"] }] };
throw new Error(`Unexpected kernel method ${method}`);
},
},
app: {
state: () => app,
update,
select: (chatId: string, workspaceId: string) => update({ chatId, workspaceId }),
route: (route: string) => update({ route }),
onChange: () => () => {},
},
views: {
add: (_key: string, definition: { render: (ctx: ViewContext<object>) => RenderResult }) => {
views.push({ render: definition.render, state: {} });
return { id: views.length, update: () => (dirty = true), remove: () => {} };
},
},
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: () => unknown }) => {
commands.set(id, run);
return { remove() {} };
},
commandAction: () => true,
notify: (message: string) => notices.push(message),
focus: (id: string) => focused.push(id),
},
{
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: RenderResult[] = [];
// Past the sidebar's redraw throttle, well short of the notice's time.
const settle = async () => {
for (let round = 0; round < 50; round++) {
mock.timers.tick(150);
await tick();
await tick();
if (!dirty) return;
dirty = false;
trees = views.map((view) => view.render({ state: view.state, set: () => {}, app, plugin: "sidebar", update: () => (dirty = true) }));
}
throw new Error("sidebar did not settle");
};
const node = (id: string) => findNode(trees, id);
return {
api,
calls,
notices,
focused,
tasks,
// A host event, delivered as the host sends one.
emit: (event: HostEvent) => {
for (const fn of listeners.get(event.event) ?? []) fn(event);
},
// A chat the host reports changed, with a newer stamp.
touch: (chatId: string) => {
const index = chats.findIndex((c) => c.id === chatId);
chats[index] = { ...chats[index]!, updatedAt: stamp() };
for (const fn of listeners.get("chat_changed") ?? []) fn({ event: "chat_changed", chat: { ...chats[index]!, task: homeOf(chatId)?.id } });
},
pass: (method: string) => failing.delete(method),
hold: (method: string) => {
let release = () => {};
held.set(method, new Promise<void>((resolve) => (release = resolve)));
return () => {
held.delete(method);
release();
};
},
// Runs a command the sidebar registered, as its key would.
run: async (id: string) => {
await commands.get(id)?.();
},
peeks: () => peeks,
text: () => JSON.stringify(trees),
settle,
node,
update,
list: () => listOf(trees),
// The drop target around the chat list, which takes a chat let go between its rows.
listDrop: () => parentOf(trees, "chat-list")?.drop as { onOver: (e: unknown) => void; onDrop: (e: unknown) => void },
fail: (method: string, message: string) => failing.set(method, message),
// A row's hover action, by its tooltip.
action: (id: string, tooltip: string) => {
const actions = node(id)?.actions as { tooltip: string; onClick: () => void }[] | undefined;
const found = actions?.find((a) => a.tooltip === tooltip);
assert.ok(found, `${id} has ${tooltip}`);
found.onClick();
},
click: (id: string, event = "onClick") => {
const handler = node(id)?.[event];
assert.equal(typeof handler, "function", `${id} ${event}`);
(handler as (payload: unknown) => void)({});
},
};
}
No comments yet.