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.4
Permissions in 0.2.4
Files
chat.test.ts34.3 KB
// The sidebar follows the chat plugin's queue and draft titles through
// the divergence/chat service. Real activation with a canned chat
// client: the initial read fills the rows, events update them, and without
// a provider the rows show the stored titles.
import assert from "node:assert/strict";
import { afterEach, mock, test } from "node:test";
import type { Api, AppState, AppStatePatch, Chat, HostEvent, RenderResult, SlotOptions, ViewContext } from "divergence";
import { testLayer } from "divergence/effect/testing";
import activate from "./main.ts";
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
// The sidebar draws a burst of events once its throttle's time is up;
// `settle` moves a mocked clock past it instead of waiting.
afterEach(() => mock.timers.reset());
const stable = (value: unknown) =>
JSON.stringify(value, (_key, item: unknown) => (typeof item === "function" ? "@handler" : item));
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>;
// A scroller's rows are its items.
return node.id === id ? node : (findNode(node.children, id) ?? findNode(node.items, id));
}
function fakeApi(withChat: boolean, nativeBindings = false) {
mock.timers.enable({ apis: ["setTimeout", "Date"] });
let state: AppState = { workspaceId: "w1" };
const appListeners = new Set<(state: AppState) => void>();
const views: { render: (ctx: ViewContext<object>) => RenderResult; active: boolean; state: object }[] = [];
const listeners = new Map<string, Set<(event: HostEvent) => unknown>>();
const chatCalls: { method: string; params: unknown }[] = [];
const creates: unknown[] = [];
const chatSubs = new Map<string, Set<(payload: unknown) => void>>();
let dirty = true;
let draws = 0;
let pendingDefaultSave: Promise<object> | undefined;
let queued: string[] = ["c1"];
let drafts: Record<string, string> = { c1: "Typed!" };
let pendingSubmit: Promise<null> | undefined;
const notices: string[] = [];
const update = (patch: AppStatePatch) => {
state = {
...state,
...patch,
workspaceId: patch.workspaceId === null ? undefined : (patch.workspaceId ?? state.workspaceId),
chatId: patch.chatId === null ? undefined : (patch.chatId ?? state.chatId),
route: patch.route ?? state.route,
shared: { ...state.shared, ...patch.shared },
};
dirty = true;
for (const listener of appListeners) listener(state);
};
const chatClient = {
queued: Object.assign(async () => [...queued], {
// The Effect adapter calls through `result`, never the direct call.
result: async () => {
chatCalls.push({ method: "queued", params: {} });
return { ok: true as const, value: [...queued] };
},
}),
draftTitles: Object.assign(async () => ({ ...drafts }), {
result: async () => {
chatCalls.push({ method: "draftTitles", params: {} });
return { ok: true as const, value: { ...drafts } };
},
}),
starting: Object.assign(async () => [], {
result: async () => {
chatCalls.push({ method: "starting", params: {} });
return { ok: true as const, value: [] };
},
}),
submitDraft: Object.assign(async () => null, {
result: async (params: { chatId: string; queue: boolean }) => {
chatCalls.push({ method: "submitDraft", params });
return { ok: true as const, value: await (pendingSubmit ?? Promise.resolve(null)) };
},
}),
unqueue: Object.assign(async () => null, {
result: async (params: { chatId: string }) => {
chatCalls.push({ method: "unqueue", params });
return { ok: true as const, value: null };
},
}),
on: (event: string, fn: (payload: unknown) => void) => {
const key = `divergence/chat|${event}`;
const set = chatSubs.get(key) ?? new Set<(payload: unknown) => void>();
chatSubs.set(key, set);
set.add(fn);
return () => {
set.delete(fn);
};
},
};
const updates: unknown[] = [];
const failing = new Map<string, string>();
const hostCall = async (method: string, params: unknown) => {
const failure = failing.get(method);
if (failure) throw new Error(failure);
if (method === "host/chats.update") {
updates.push(params);
const { chatId, completed } = params as { chatId: string; completed?: boolean };
if (completed === true) done[chatId] = new Date().toISOString();
if (completed === false) delete done[chatId];
return {};
}
if (method === "host/storage.get") return { value: undefined };
if (method === "host/storage.set") return pendingDefaultSave ?? {};
if (method === "host/workspaces.add") {
const { path } = params as { path: string };
const workspace = {
id: `w${workspaces.length + 1}`,
name: path.split("/").pop()!,
path,
position: workspaces.length,
};
workspaces.push(workspace);
return workspace;
}
if (method === "host/workspaces.remove") {
const { workspaceId } = params as { workspaceId: string };
workspaces.splice(
workspaces.findIndex((w) => w.id === workspaceId),
1,
);
return {};
}
// One task per chat, as the host keeps for every chat; a chat checked
// off through chats.update checks its task off.
if (method === "host/tasks.list")
return {
tasks: chats.map((chat) => ({
id: chat.id,
layout: {
root: { kind: "pane", id: `pane-${chat.id}`, tabs: [{ kind: "chat", chatId: chat.id }], active: { kind: "chat", chatId: chat.id } },
focused: `pane-${chat.id}`,
},
completedAt: done[chat.id] ?? null,
createdAt: chat.createdAt,
updatedAt: chat.updatedAt,
})),
};
if (method === "host/chats.create") {
creates.push(params);
const { workspaceId, agentId } = params as { workspaceId: string; agentId: string };
const chat: Chat = { ...chats[0]!, id: `c${chats.length + 1}`, workspaceId, agentId };
chats.push(chat);
return chat;
}
throw new Error(`Unexpected host method ${method} ${JSON.stringify(params)}`);
};
const commands = new Map<string, (api: Api) => unknown>();
const actions = new Map<string, unknown>();
const kernelCall = async (method: string, params: unknown) => {
throw new Error(`Unexpected kernel method ${method} ${JSON.stringify(params)}`);
};
const broker = testLayer();
const workspaces = [{ id: "w1", name: "Workspace", path: "/fixture", position: 0 }];
const chats: Chat[] = [
{
id: "c1",
workspaceId: "w1",
agentId: "a",
title: "New Chat",
createdAt: "",
updatedAt: "",
archived: false,
options: {},
status: "idle",
},
];
// When each checked-off chat's task was checked off.
const done: Record<string, string> = {};
let pendingList: Promise<{ chats: Chat[] }> | undefined;
let pendingWorkspaces: Promise<{ workspaces: typeof workspaces }> | undefined;
const tasks = [
{
id: "t1",
workspaceId: "w1",
kind: "chat",
userTitle: false,
completed: false,
pinned: false,
createdAt: "",
updatedAt: "",
sortOrder: 0,
chatIds: ["c1"],
},
];
const promiseApi = {
workspaces: {
list: async () => {
const pending = pendingWorkspaces;
pendingWorkspaces = undefined;
return pending ?? { workspaces: [...workspaces] };
},
},
chats: {
list: async () => {
const pending = pendingList;
pendingList = undefined;
return pending ?? { chats: chats.map((chat) => ({ ...chat })) };
},
transcript: async () => ({ items: [] }),
},
tasks: { list: async () => ({ tasks }) },
agents: { list: async () => ({ agents: [{ id: "a", name: "A" }] }) },
};
// This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
const api = new Proxy(
{
...broker.api,
plugin: "sidebar",
id: "divergence/sidebar",
services: {
provide: async () => ({ emit: () => {}, remove: () => {} }),
get: (name: string) => {
if (name === "divergence/chat" && withChat) return chatClient;
throw new Error(`no provider for ${name}`);
},
available: (name: string) => name === "divergence/chat" && withChat,
when: (name: string, fn: (client: unknown) => void) => {
fn(name === "divergence/chat" && withChat ? chatClient : undefined);
return () => {};
},
},
host: { ...broker.api.host, ...promiseApi, call: hostCall, kernel: kernelCall },
app: {
state: () => state,
update,
...(nativeBindings ? { bind: (key: string, value: string) => ({ $appState: { key, value } }) } : {}),
share: (key: string, value: unknown) => update({ shared: { [key]: value } }),
select: (chatId: string, workspaceId: string) => update({ chatId, workspaceId }),
route: (route: string) => update({ route }),
onChange: (fn: (state: AppState) => void) => {
appListeners.add(fn);
return () => {
appListeners.delete(fn);
};
},
},
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 = { render, active: true, state: {} };
views.push(view);
dirty = true;
return {
id: views.length,
update: () => {
draws++;
dirty = true;
},
remove: () => {
view.active = false;
},
};
} },
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: (command: { id: string; run: (api: Api) => unknown }) => {
commands.set(command.id, command.run);
return { remove() {} };
},
commandAction: (id: string, action: unknown) => {
if (!commands.has(id)) return false;
actions.set(id, action);
return true;
},
pickFolder: async () => ({ path: "/fixture/tide-pool" }),
notify: (message: string) => {
notices.push(message);
},
focus: () => {},
},
{
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;
const render = () =>
views
.filter((view) => view.active)
.map((view) =>
view.render({
state: view.state,
set: () => {},
app: state,
plugin: "sidebar",
update: () => {
dirty = true;
},
}),
);
let trees: RenderResult[] = [];
const settle = async () => {
for (let round = 0; round < 50; round++) {
mock.timers.tick(1000);
await tick();
if (!dirty) {
await tick();
if (!dirty) return;
}
dirty = false;
trees = render();
}
throw new Error("sidebar did not settle");
};
return {
api,
actions,
app: () => state,
run: (id: string) => commands.get(id)!(api),
chatCalls,
creates,
updates,
notices,
node: (id: string) => findNode(trees, id),
invoke: (id: string, event: string, payload: unknown) => {
const node = findNode(trees, id);
assert.ok(node, id);
const handler = node[event];
assert.equal(typeof handler, "function", event);
(handler as (payload: unknown) => void)(payload);
},
holdSubmit: () => {
const gate = Promise.withResolvers<null>();
pendingSubmit = gate.promise;
return () => {
pendingSubmit = undefined;
gate.resolve(null);
};
},
update,
settle,
trees: () => stable(trees),
draws: () => draws,
chats,
hostEvent: (event: HostEvent) => {
for (const fn of listeners.get(event.event) ?? []) fn(event);
},
holdList: () => {
const snapshot = chats.map((chat) => ({ ...chat }));
let release!: () => void;
pendingList = new Promise((resolve) => {
release = () => {
pendingList = undefined;
resolve({ chats: snapshot });
};
});
return release;
},
// The next workspace list answers what the host holds now, but only
// when released.
holdWorkspaces: () => {
const gate = Promise.withResolvers<{ workspaces: typeof workspaces }>();
const snapshot = [...workspaces];
pendingWorkspaces = gate.promise;
return () => gate.resolve({ workspaces: snapshot });
},
fail: (method: string, message: string) => failing.set(method, message),
holdDefaultSave: () => {
const pending = Promise.withResolvers<object>();
pendingDefaultSave = pending.promise;
return () => {
pendingDefaultSave = undefined;
pending.resolve({});
};
},
chatEvent: (event: string, payload: unknown) => {
for (const fn of chatSubs.get(`divergence/chat|${event}`) ?? []) fn(payload);
},
providerData: (next: { queued?: string[]; drafts?: Record<string, string> }) => {
if (next.queued) queued = next.queued;
if (next.drafts) drafts = next.drafts;
},
};
}
test("row clicks declare native navigation and an acknowledged callback never selects again", async () => {
const native = fakeApi(false, true);
native.update({ chatId: "elsewhere" });
const dispose = activate(native.api);
try {
await native.settle();
assert.deepEqual(native.node("row-c1")?.selected, { $appState: { key: "chatId", value: "c1" } });
assert.deepEqual(native.node("row-c1")?.onClickAction, { chatId: "c1", workspaceId: "w1", route: "chat" });
native.invoke("row-c1", "onClick", { applied: true });
await native.settle();
assert.equal(native.app().chatId, "elsewhere", "the callback does not repeat native selection");
} finally {
await dispose();
}
mock.timers.reset();
const legacy = fakeApi(false);
legacy.update({ chatId: "elsewhere" });
const disposeLegacy = activate(legacy.api);
try {
await legacy.settle();
assert.equal(legacy.node("row-c1")?.selected, false, "an older host receives the static boolean");
legacy.invoke("row-c1", "onClick", {});
await legacy.settle();
assert.equal(legacy.app().chatId, "c1", "an older host selects through the callback once");
} finally {
await disposeLegacy();
}
});
test("New chat shows its N key cap only while the shortcut key is held", async () => {
const fake = fakeApi(true);
const dispose = activate(fake.api);
const held = (secondary: boolean, meta: boolean) => ({ modifiers: { secondary, meta, ctrl: secondary && !meta, alt: false, shift: false } });
const cap = () => stable(fake.node("new-chat")?.children ?? []);
try {
await fake.settle();
assert.doesNotMatch(cap(), /"N"/, "no key cap at rest");
// Off the Mac the shortcut key is Ctrl, which is not `meta`.
fake.invoke("sidebar", "onModifiersChanged", held(true, false));
await fake.settle();
assert.match(cap(), /"N"/);
// The Super key alone is not the shortcut key there.
fake.invoke("sidebar", "onModifiersChanged", held(false, true));
await fake.settle();
assert.doesNotMatch(cap(), /"N"/);
} finally {
dispose();
}
});
test("draft Play swaps with Cmd, submits the clicked chat without selecting it, and blocks repeat clicks", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: [] });
fake.update({ chatId: "elsewhere" });
const dispose = activate(fake.api);
const modifiers = (meta: boolean) => ({ modifiers: { meta, ctrl: false, alt: false, shift: false } });
try {
await fake.settle();
assert.equal(fake.node("play-c1")?.icon, "play");
assert.equal(fake.node("glyph-c1"), undefined, "a draft has no completion checkbox");
fake.invoke("sidebar", "onModifiersChanged", modifiers(true));
await fake.settle();
assert.equal(fake.node("play-c1")?.icon, "list-plus");
fake.invoke("sidebar", "onModifiersChanged", modifiers(false));
await fake.settle();
assert.equal(fake.node("play-c1")?.icon, "play");
const release = fake.holdSubmit();
// Click-time modifiers decide intent even before the icon redraw arrives.
fake.invoke("play-c1", "onClick", modifiers(true));
fake.invoke("play-c1", "onClick", modifiers(true));
await fake.settle();
assert.equal(fake.node("play-c1")?.disabled, true);
assert.equal(fake.node("play-c1")?.loading, true);
assert.deepEqual(
fake.chatCalls.filter((call) => call.method === "submitDraft"),
[{ method: "submitDraft", params: { chatId: "c1", queue: true } }],
);
assert.equal(fake.app().chatId, "elsewhere");
release();
await fake.settle();
assert.equal(fake.node("play-c1")?.disabled, false);
fake.invoke("play-c1", "onClick", modifiers(false));
await fake.settle();
assert.deepEqual(fake.chatCalls.at(-1), { method: "submitDraft", params: { chatId: "c1", queue: false } });
assert.equal(fake.app().chatId, "elsewhere");
assert.deepEqual(fake.notices, []);
fake.chats[0] = { ...fake.chats[0], sessionId: "started" };
fake.hostEvent({ event: "chat_changed", chat: { ...fake.chats[0] } });
await fake.settle();
assert.ok(fake.node("glyph-c1"), "started chats keep their completion action");
assert.equal(fake.node("play-c1"), undefined);
} finally {
await dispose();
}
});
test("New chat selects the returned draft before settings/list reads and survives an older list", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
const releaseSave = fake.holdDefaultSave();
const releaseList = fake.holdList();
fake.hostEvent({ event: "agents_changed" });
await fake.settle();
fake.run("sidebar.newChat");
await fake.settle();
assert.equal(fake.app().chatId, "c2", "settings and list latency must not block selection");
assert.deepEqual(
fake.app().shared?.selectedChat,
fake.chats[1],
"selection includes metadata for the first chat frame",
);
assert.ok(fake.trees().includes('"id":"row-c2"'), "returned draft is already in the sidebar");
releaseSave();
releaseList();
await fake.settle();
assert.ok(fake.trees().includes('"id":"row-c2"'), "an old list cannot erase the newly created draft");
} finally {
await dispose();
}
});
test("the queued chats and draft titles come from the chat service", async () => {
const fake = fakeApi(true);
const dispose = activate(fake.api);
try {
await fake.settle();
// The initial read fills the rows: c1 is queued with a typed title.
assert.ok(fake.chatCalls.some((call) => call.method === "queued"));
assert.ok(fake.chatCalls.some((call) => call.method === "draftTitles"));
assert.ok(fake.trees().includes("Typed!"));
assert.ok(fake.trees().includes("Queued"));
// A queued chat is one line with a button that takes it out of the queue.
assert.equal(fake.node("unqueue-c1")?.icon, "list-minus");
assert.equal(fake.node("glyph-c1"), undefined);
assert.equal(fake.node("row-c1")?.sublabel, undefined);
fake.invoke("unqueue-c1", "onClick", undefined);
await fake.settle();
assert.deepEqual(fake.chatCalls.at(-1), { method: "unqueue", params: { chatId: "c1" } });
// Events update the rows without shared state.
fake.providerData({ queued: [], drafts: {} });
fake.chatEvent("queuedChanged", []);
fake.chatEvent("draftTitlesChanged", {});
await fake.settle();
assert.ok(!fake.trees().includes("Typed!"));
assert.ok(!fake.trees().includes("Queued"));
assert.equal(fake.node("unqueue-c1"), undefined);
assert.ok(fake.trees().includes("New Chat"));
} finally {
await dispose();
}
});
test("a draft whose prompt was sent shows running at once, before the host reports it", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: [], drafts: {} });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.trees().includes('"label":"Drafts"'));
// The chat plugin reports the send in the same step that animates the
// prompt box; the sidebar draws then, not after its event throttle.
const before = fake.draws();
fake.chatEvent("startingChanged", ["c1"]);
await tick();
assert.equal(fake.draws(), before + 1);
await fake.settle();
assert.ok(fake.trees().includes('"label":"Running"'));
assert.ok(!fake.trees().includes('"label":"Drafts"'));
// The host takes over; the chat stays running when the plugin lets go.
fake.hostEvent({ event: "chat_changed", chat: { ...fake.chats[0]!, status: "running" } });
fake.chatEvent("startingChanged", []);
await fake.settle();
assert.ok(fake.trees().includes('"label":"Running"'));
} finally {
await dispose();
}
});
test("a send that never started a run puts the chat back in Drafts", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: [], drafts: {} });
const dispose = activate(fake.api);
try {
await fake.settle();
fake.chatEvent("startingChanged", ["c1"]);
await fake.settle();
assert.ok(fake.trees().includes('"label":"Running"'));
fake.chatEvent("startingChanged", []);
await fake.settle();
assert.ok(fake.trees().includes('"label":"Drafts"'));
assert.ok(!fake.trees().includes('"label":"Running"'));
} finally {
await dispose();
}
});
test("without the chat plugin the rows show the stored titles", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
assert.deepEqual(fake.chatCalls, []);
assert.ok(fake.trees().includes("New Chat"));
assert.ok(!fake.trees().includes("Queued"));
} finally {
await dispose();
}
});
test("a list refresh cannot mark a new running turn finished", async () => {
const fake = fakeApi(false);
fake.chats[0] = { ...fake.chats[0]!, sessionId: "session", updatedAt: "2026-10-04T17:00:00Z" };
const dispose = activate(fake.api);
try {
await fake.settle();
fake.hostEvent({ event: "agent", chatId: "c1", kind: { event: "run_finished", outcome: { status: "completed" } } });
await fake.settle();
assert.ok(fake.trees().includes('"label":"Finished"'));
const release = fake.holdList();
fake.hostEvent({ event: "agents_changed" });
await fake.settle();
const running: Chat = { ...fake.chats[0]!, status: "running", updatedAt: "2026-10-04T17:01:00Z" };
fake.hostEvent({ event: "chat_changed", chat: running });
fake.hostEvent({
event: "agent",
chatId: "c1",
kind: {
event: "tool_call_started",
id: "tool",
name: "Bash",
kind: "execute",
title: "Run tests",
status: "running",
},
});
await fake.settle();
assert.ok(fake.trees().includes('"label":"Running"'));
release();
await fake.settle();
assert.ok(
fake.trees().includes('"label":"Running"'),
"a stale idle snapshot must not replace the live running state",
);
assert.ok(!fake.trees().includes('"label":"Finished"'));
} finally {
await dispose();
}
});
test("a burst of host events draws the sidebar once more, with the last of them", async () => {
const fake = fakeApi(false);
fake.chats[0] = { ...fake.chats[0]!, sessionId: "session" };
const dispose = activate(fake.api);
try {
await fake.settle();
const before = fake.draws();
for (const title of ["One", "Two", "Three", "Four"]) {
fake.hostEvent({ event: "chat_changed", chat: { ...fake.chats[0]!, title } });
}
await tick();
assert.equal(fake.draws(), before + 1, "the first event of a quiet sidebar draws at once");
await fake.settle();
assert.equal(fake.draws(), before + 2, "the rest of the burst draws once");
assert.ok(fake.trees().includes('"label":"Four"'));
} finally {
await dispose();
}
});
for (const status of ["idle", "failed", "waiting_approval", "waiting_question"] as const) {
test(`a stale running list cannot overwrite ${status}`, async () => {
const fake = fakeApi(false);
fake.chats[0] = { ...fake.chats[0]!, sessionId: "s", status: "running", updatedAt: "2026-10-04T17:00:00Z" };
const dispose = activate(fake.api);
try {
await fake.settle();
const release = fake.holdList();
fake.hostEvent({ event: "agents_changed" });
await fake.settle();
const current: Chat = { ...fake.chats[0]!, status, updatedAt: "2026-10-04T17:01:00Z" };
fake.hostEvent({ event: "chat_changed", chat: current });
if (status === "idle" || status === "failed")
fake.hostEvent({
event: "agent",
chatId: "c1",
kind: { event: "run_finished", outcome: { status: "completed" } },
});
release();
await fake.settle();
const label = status.startsWith("waiting_") ? "Needs you" : "Finished";
assert.ok(fake.trees().includes(`"label":"${label}"`));
assert.ok(!fake.trees().includes('"label":"Running"'));
} finally {
await dispose();
}
});
}
test("a newer list still updates a chat, including metadata at the same timestamp", async () => {
const fake = fakeApi(false);
fake.chats[0] = { ...fake.chats[0]!, sessionId: "s", status: "running", updatedAt: "2026-10-04T17:00:00Z" };
const dispose = activate(fake.api);
try {
await fake.settle();
fake.chats[0] = { ...fake.chats[0]!, title: "Updated title", status: "idle", updatedAt: "2026-10-04T17:01:00Z" };
fake.hostEvent({ event: "agents_changed" });
await fake.settle();
assert.ok(fake.trees().includes("Updated title"));
assert.ok(!fake.trees().includes('"label":"Running"'));
fake.chats[0] = { ...fake.chats[0]!, title: "Same time metadata" };
fake.hostEvent({ event: "agents_changed" });
await fake.settle();
assert.ok(fake.trees().includes("Same time metadata"));
} finally {
await dispose();
}
});
test("adding a folder shows it alone and opens a draft there", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.run("sidebar.addWorkspace");
await fake.settle();
const draft = fake.chats.find((chat) => chat.workspaceId === "w2");
assert.ok(draft, "a draft was created in the new workspace");
assert.equal(fake.app().workspaceId, "w2");
assert.equal(fake.app().chatId, draft.id);
} finally {
await dispose();
}
});
test("a folder that cannot be added says so, from Cmd+O as from the picker", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.fail("host/workspaces.add", "the folder is gone");
await fake.run("sidebar.addWorkspace");
await fake.settle();
assert.deepEqual(fake.notices, ["Could not add the workspace folder: the folder is gone"]);
} finally {
await dispose();
}
});
test("a list read that answers after a newer one does not bring a removed workspace back", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.run("sidebar.addWorkspace");
await fake.settle();
// The add's read is slow; the remove's read answers first.
const releaseOlder = fake.holdWorkspaces();
fake.hostEvent({ event: "workspaces_changed" } as HostEvent);
fake.invoke("remove-workspace", "onClick", {});
await fake.settle();
fake.hostEvent({ event: "workspaces_changed" } as HostEvent);
await fake.settle();
releaseOlder();
await fake.settle();
const options = fake.node("workspace-filter")?.options as { value: string }[];
assert.deepEqual(
options.map((option) => option.value),
["w1"],
);
} finally {
await dispose();
}
});
test("New chat from a draft with a typed or queued prompt opens another draft", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: ["c1"], drafts: { c2: "Typed!" } });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.run("sidebar.newChat");
await fake.settle();
assert.deepEqual(fake.creates, [{ workspaceId: "w1", agentId: "a", inUse: ["c2", "c1"] }]);
} finally {
await dispose();
}
});
test("a chat whose turn failed says Failed, not Finished, on its row", async () => {
const fake = fakeApi(false);
fake.chats[0] = { ...fake.chats[0]!, sessionId: "session", status: "running", updatedAt: "2026-10-04T17:00:00Z" };
const dispose = activate(fake.api);
try {
await fake.settle();
fake.hostEvent({
event: "chat_changed",
chat: { ...fake.chats[0]!, status: "failed", updatedAt: "2026-10-04T17:01:00Z" },
});
fake.hostEvent({
event: "agent",
chatId: "c1",
kind: { event: "run_finished", outcome: { status: "failed", message: "This API key has expired." } },
});
await fake.settle();
assert.ok(fake.trees().includes('"label":"Finished"'), "it is in Finished");
assert.ok(fake.trees().includes('"sublabel":"Failed'), fake.trees());
assert.ok(!fake.trees().includes('"sublabel":"Finished'));
} finally {
await dispose();
}
});
test("Cmd+1…9 declare the chat each opens, and follow the list", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
assert.deepEqual(fake.actions.get("sidebar.openChat1"), { chatId: "c1", workspaceId: "w1", route: "chat" });
assert.equal(fake.actions.get("sidebar.openChat2"), null);
await fake.run("sidebar.newChat");
await fake.settle();
const listed = [fake.actions.get("sidebar.openChat1"), fake.actions.get("sidebar.openChat2")];
assert.ok(
listed.every((action) => action && typeof action === "object"),
JSON.stringify(listed),
);
} finally {
await dispose();
}
});
test("Cmd+W archives a draft, dequeues and archives a queued chat, otherwise marks the chat complete, and moves to the next open chat", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: ["c2"], drafts: {} });
fake.chats.push(
{ ...fake.chats[0]!, id: "c2" },
{ ...fake.chats[0]!, id: "c3", sessionId: "session", updatedAt: "2026-10-04T17:00:00Z" },
{ ...fake.chats[0]!, id: "c4", sessionId: "session", updatedAt: "2026-10-04T16:00:00Z" },
);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.update({ chatId: "c1" });
await fake.run("sidebar.closeChat");
await fake.settle();
assert.deepEqual(fake.updates, [{ chatId: "c1", archived: true }]);
assert.equal(fake.app().chatId, "c2", "the archived draft gives the screen to the next chat");
fake.hostEvent({ event: "chat_changed", chat: { ...fake.chats[0]!, archived: true } });
await fake.run("sidebar.closeChat");
await fake.settle();
assert.deepEqual(fake.chatCalls.at(-1), { method: "unqueue", params: { chatId: "c2" } });
assert.deepEqual(fake.updates.at(-1), { chatId: "c2", archived: true });
assert.equal(fake.app().chatId, "c3");
fake.hostEvent({ event: "chat_changed", chat: { ...fake.chats[1]!, archived: true } });
await fake.run("sidebar.closeChat");
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c3", completed: true });
assert.equal(fake.app().chatId, "c4", "a completed chat gives the screen to the next open chat");
await fake.run("sidebar.closeChat");
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c4", completed: true });
assert.equal(fake.app().chatId, "c4", "with no open chat left the screen stays");
fake.update({ chatId: "c3" });
await fake.run("sidebar.closeChat");
await fake.settle();
assert.equal(fake.updates.length, 4, "a complete chat is not unchecked");
} finally {
await dispose();
}
});
test("checking off the chat on screen moves to the next open chat; other chats and unchecking leave the screen", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: [], drafts: {} });
fake.chats[0] = { ...fake.chats[0]!, sessionId: "session", updatedAt: "2026-10-04T18:00:00Z" };
fake.chats.push(
{ ...fake.chats[0]!, id: "c2", updatedAt: "2026-10-04T17:00:00Z" },
{ ...fake.chats[0]!, id: "c3", updatedAt: "2026-10-04T16:00:00Z" },
);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.update({ chatId: "c1" });
fake.invoke("glyph-c3", "onClick", {});
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c3", completed: true });
assert.equal(fake.app().chatId, "c1", "checking off another chat leaves the screen");
fake.invoke("glyph-c1", "onClick", {});
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c1", completed: true });
assert.equal(fake.app().chatId, "c2", "the checked-off chat gives the screen to the next open chat");
await fake.run("sidebar.toggleChatCompleted");
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c2", completed: true });
assert.equal(fake.app().chatId, "c2", "with no open chat left the screen stays");
await fake.run("sidebar.toggleChatCompleted");
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c2", completed: false });
assert.equal(fake.app().chatId, "c2", "unchecking stays");
} finally {
await dispose();
}
});
test("Undo puts a queued chat that Cmd+W archived back in the queue", async () => {
const fake = fakeApi(true);
fake.providerData({ queued: ["c2"], drafts: {} });
fake.chats.push({ ...fake.chats[0]!, id: "c2" });
const dispose = activate(fake.api);
try {
await fake.settle();
fake.update({ chatId: "c2" });
await fake.run("sidebar.closeChat");
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c2", archived: true });
fake.invoke("undo-archive-button", "onClick", {});
await fake.settle();
assert.deepEqual(fake.updates.at(-1), { chatId: "c2", archived: false });
assert.deepEqual(fake.chatCalls.at(-1), { method: "submitDraft", params: { chatId: "c2", queue: true } });
} finally {
await dispose();
}
});
No comments yet.