Official
settings
Built-in settings 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/settings@0.2.8
Permissions in 0.2.8
Files
service.test.ts66.5 KB
// The divergence/settings service: showShortcuts routes to settings and
// opens Keyboard Shortcuts searched for the command. Real activation
// against a fake host and kernel; calls go through the provided method.
import assert from "node:assert/strict";
import { test } from "node:test";
import type {
Api,
AppState,
Chat,
AppStatePatch,
HostEvent,
InputSnapshot,
PluginSummary,
RenderResult,
SettingValue,
SlotOptions,
ViewContext,
Workspace,
} from "divergence";
import { testLayer } from "divergence/effect/testing";
import activate from "./main.ts";
import { nodes } from "../sdk/ui-testing.ts";
import type { AgentEntry } from "./controller.ts";
import { APP_SECTIONS } from "./model.ts";
import manifest from "./plugin.json" with { type: "json" };
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
const stable = (value: unknown) =>
JSON.stringify(value, (_key, item: unknown) => (typeof item === "function" ? "@handler" : item));
type ServiceImpl = Record<string, (params: never, ctx: unknown) => Promise<unknown>>;
/// Another plugin's service the way the runtime hands its client out: each
/// method answers through `result` (a thrown value is the method's error),
/// and `on` follows the events `emit` sends.
function fakeService(methods: Record<string, (params: any) => unknown>) {
const listeners = new Map<string, Set<(payload: unknown) => void>>();
const client: Record<string, unknown> = {
on: (event: string, fn: (payload: unknown) => void) => {
const set = listeners.get(event) ?? new Set();
listeners.set(event, set);
set.add(fn);
return () => set.delete(fn);
},
};
for (const [name, run] of Object.entries(methods)) {
const result = async (params: unknown) => {
try {
return { ok: true, value: await run(params) };
} catch (error) {
return { ok: false, error };
}
};
client[name] = Object.assign(async (params: unknown) => run(params), { result });
}
return { client, emit: (event: string, payload: unknown) => listeners.get(event)?.forEach((fn) => fn(payload)) };
}
function fakeApi(options: { progress?: unknown; agents?: AgentEntry[]; workspaces?: Workspace[]; plugins?: PluginSummary[]; hasChats?: boolean; chats?: Chat[]; route?: string; onAgentUpdate?: (agentId: string) => void; updates?: unknown; tools?: unknown; disabledRules?: string[]; services?: Record<string, unknown>; inputs?: Record<string, InputSnapshot>; stored?: Record<string, unknown>; shared?: Record<string, unknown> } = {}) {
let state: AppState = { route: options.route, shared: options.shared };
let progress: unknown = "progress" in options ? options.progress : { done: true, step: 0, workspaceId: null };
let agents = options.agents ?? [];
const workspaces = options.workspaces ?? [];
let plugins = options.plugins ?? [];
const ownSettings: Record<string, SettingValue> = {};
const settingsListeners = new Set<(values: Record<string, SettingValue>) => unknown>();
let appearance = "system";
let drafted = 0;
let pickedPath: string | null = null;
let failure: string | null = null;
let waitFor: { method: string; promise: Promise<void> } | null = null;
const appListeners = new Set<(state: AppState) => void>();
const views: { render: (ctx: ViewContext<object>) => RenderResult; active: boolean }[] = [];
const listeners = new Map<string, Set<(event: HostEvent) => unknown>>();
const hostCalls: { method: string; params: unknown }[] = [];
const kernelCalls: { method: string; params: unknown }[] = [];
const notices: string[] = [];
let dirty = true;
const provided = new Map<string, ServiceImpl>();
const emitted: { event: string; payload: unknown }[] = [];
const registered = new Map<string, () => void>();
const commands = {
commands: [
{
id: "a.open",
title: "Open",
category: "A",
plugin: "a",
pluginTitle: "A",
official: true,
key: "cmd+x",
defaultKey: "cmd+x",
keys: ["cmd+x"],
labels: ["⌘X"],
source: "default",
conflict: null,
problem: null,
kernel: false,
enabled: true,
registered: true,
},
{
id: "b.close",
title: "Close",
category: "B",
plugin: "b",
pluginTitle: "B",
official: false,
key: null,
defaultKey: "cmd-x",
keys: [],
labels: [],
source: "none",
conflict: { key: "cmd-x", label: "⌘X", with: "a.open", withTitle: "Open" },
problem: null,
kernel: false,
enabled: true,
registered: true,
},
],
errors: [],
};
// The kernel's recorder: a new recording answers the one that waits with no key.
let recording: ((answer: unknown) => void) | null = null;
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 hostCall = async (method: string, params: unknown) => {
hostCalls.push({ method, params });
if (waitFor?.method === method) await waitFor.promise;
if (failure === method) throw new Error("Test service is unavailable");
switch (method) {
case "host/storage.get":
return { value: progress };
case "host/storage.set":
progress = (params as { value: unknown }).value;
return {};
case "host/settings.get":
return { appearance, tools: { mode: "code", disabled: [], disabledRules: options.disabledRules ?? [] } };
case "host/settings.update":
appearance = (params as { appearance: string }).appearance;
return { appearance };
case "host/agents.all":
return { agents };
case "host/agents.set_enabled": {
const patch = params as { agentId: string; enabled: boolean };
agents = agents.map((a) => a.id === patch.agentId ? { ...a, enabled: patch.enabled } : a);
return {};
}
case "host/agents.authenticate":
agents = agents.map((a) => a.id === (params as { agentId: string }).agentId ? { ...a, status: { state: "ready" } } : a);
return {};
case "host/agents.update":
options.onAgentUpdate?.((params as { agentId: string }).agentId);
return {};
case "host/plugins.list":
return { plugins };
case "host/plugins.set_enabled": {
const patch = params as { name: string; enabled: boolean };
plugins = plugins.map((p) => p.name === patch.name ? { ...p, enabled: patch.enabled } : p);
return {};
}
case "host/plugins.request_enable":
return { requestId: "native-approval" };
case "host/workspaces.list":
return { workspaces };
case "host/workspaces.remove": {
const at = workspaces.findIndex((w) => w.id === (params as { workspaceId: string }).workspaceId);
if (at >= 0) workspaces.splice(at, 1);
return {};
}
case "host/drafts.get":
return { chatId: (params as { chatId: string }).chatId, revision: 3, blocks: [] };
case "host/drafts.update":
return { ...(params as object) };
case "host/plugins.set_setting":
return { value: (params as { value: unknown }).value, requestId: null };
case "host/workspaces.add": {
const workspace = { id: "project", name: "Project", path: (params as { path: string }).path, position: workspaces.length };
workspaces.push(workspace);
return workspace;
}
case "host/chats.list":
return { chats: [...(options.hasChats ? [{ id: "existing" }] : []), ...(options.chats ?? [])] };
case "host/chats.update": {
const { chatId, archived } = params as { chatId: string; archived: boolean };
const at = options.chats!.findIndex((c) => c.id === chatId);
options.chats![at] = { ...options.chats![at]!, archived };
return options.chats![at];
}
case "host/chats.delete":
options.chats!.splice(options.chats!.findIndex((c) => c.id === (params as { chatId: string }).chatId), 1);
return {};
case "host/chats.create":
// A titled chat is a change saved in the guide; the untitled one is the first chat.
return { id: (params as { title?: string }).title ? `draft-${++drafted}` : "first", ...(params as object) };
case "host/updates.status":
return options.updates ?? {};
case "host/updates.install_app":
return { restart: true };
case "host/updates.apply_plugins":
return { report: { updated: ["chat"], added: [], removed: [] }, chatId: null };
case "host/inputs.list": {
const { chatId } = params as { chatId: string };
return options.inputs?.[chatId] ?? { chatId, inputs: [] };
}
case "host/tools.list":
return options.tools ?? null;
case "host/plugins.settings":
return { name: "x", error: null, properties: [], notices: [] };
default:
throw new Error(`Unexpected host method ${method}`);
}
};
const kernelCall = async (method: string, params: unknown) => {
kernelCalls.push({ method, params });
if (method === "commands") return commands;
if (method === "keys.record") {
recording?.({ key: null });
return new Promise((resolve) => { recording = resolve; });
}
if (method === "themes") return { themes: [] };
if (method === "settings_view") return { view: null };
if (method === "theme") return {};
if (method === "quit") return {};
throw new Error(`Unexpected kernel method ${method}`);
};
const broker = testLayer({ storage: options.stored });
// This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
const api = new Proxy(
{
...broker.api,
plugin: "settings",
id: "divergence/settings",
services: {
provide: async (def: { name: string }, impl: ServiceImpl) => {
provided.set(def.name, impl);
return {
emit: (event: string, payload: unknown) => {
emitted.push({ event, payload });
},
remove: () => {
provided.delete(def.name);
},
};
},
get: (name: string) => {
const client = options.services?.[name];
if (!client) throw new Error(`no provider for ${name}`);
return client;
},
available: (name: string) => !!options.services?.[name],
when: (name: string, fn: (client: unknown) => void) => {
fn(options.services?.[name]);
return () => {};
},
},
host: { ...broker.api.host, call: hostCall, kernel: kernelCall },
settings: {
...broker.api.settings,
get: ((key?: string) => key === undefined ? ownSettings : ownSettings[key] ?? null) as Api["settings"]["get"],
set: async (key: string, value: SettingValue) => {
ownSettings[key] = value;
for (const listener of settingsListeners) listener(ownSettings);
return value;
},
onChange: (fn: (values: Record<string, SettingValue>) => unknown) => {
settingsListeners.add(fn);
return () => { settingsListeners.delete(fn); };
},
},
app: {
state: () => state,
update,
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);
};
},
},
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 };
views.push(view);
dirty = true;
return {
id: views.length,
update: () => {
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: (definition: { id: string; run: () => void }) => {
registered.set(definition.id, definition.run);
return { remove() { registered.delete(definition.id); } };
},
pickFolder: async () => ({ path: pickedPath }),
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: {},
set: () => {},
app: state,
plugin: "settings",
update: () => {
dirty = true;
},
}),
);
let trees: RenderResult[] = [];
const settle = async () => {
for (let round = 0; round < 50; round++) {
await tick();
if (!dirty) {
await tick();
if (!dirty) return;
}
dirty = false;
trees = render();
}
throw new Error("settings did not settle");
};
const ctx = { caller: { plugin: "test/client", id: "test/client" }, signal: AbortSignal.timeout(5000) };
return {
api,
hostCalls,
kernelCalls,
notices,
provided,
settle,
trees: () => stable(trees),
state: () => state,
progress: () => progress,
settings: () => ({ ...ownSettings }),
plugins: (next: PluginSummary[]) => { plugins = next; },
route: (route: string) => update({ route }),
node: (id: string) => {
const node = nodes(trees).find((node) => node.id === id);
assert.ok(node, `Missing control ${id}`);
return node;
},
click: async (id: string) => {
const node = nodes(trees).find((node) => node.id === id);
assert.ok(node && typeof node.onClick === "function", `Missing action ${id}`);
assert.ok(!node.disabled, `${id} is disabled`);
node.onClick();
await settle();
},
change: async (id: string, value: unknown) => {
const node = nodes(trees).find((node) => node.id === id);
assert.ok(node && typeof node.onChange === "function", `Missing input ${id}`);
assert.ok(!node.disabled, `${id} is disabled`);
node.onChange({ value });
await settle();
},
press: async (id: string) => {
const node = nodes(trees).find((node) => node.id === id);
assert.ok(node && typeof node.onPress === "function", `Missing trigger ${id}`);
node.onPress();
await settle();
},
has: (id: string) => nodes(trees).some((node) => node.id === id),
// What the plugin saved through its Storage service.
stored: () => Object.fromEntries(broker.storage),
pick: (path: string | null) => { pickedPath = path; },
fail: (method: string | null) => { failure = method; },
block: (method: string) => {
const { promise, resolve } = Promise.withResolvers<void>();
waitFor = { method, promise };
return () => { waitFor = null; resolve(); };
},
emit: async (event: HostEvent) => {
for (const fn of listeners.get(event.event) ?? []) fn(event);
await settle();
},
agents: (next: AgentEntry[]) => { agents = next; },
pressKey: async (key: string, label: string) => {
const answer = recording;
recording = null;
answer?.({ key, label });
await settle();
},
command: async (id: string) => { registered.get(id)?.(); await settle(); },
callService: (method: string, params: unknown) =>
provided.get("divergence/settings")?.[method]?.(params as never, ctx),
};
}
test("showShortcuts routes to settings and searches Keyboard Shortcuts", async () => {
const fake = fakeApi();
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.provided.has("divergence/settings"));
// The page loaded at activation, so Settings opens on its section at once.
const loads = fake.kernelCalls.filter((call) => call.method === "commands").length;
assert.equal(loads, 1);
assert.deepEqual(await fake.callService("showShortcuts", { query: "assign-me" }), null);
assert.equal(fake.state().route, "settings");
assert.equal(fake.state().shared?.showShortcuts, undefined);
await fake.settle();
// The keys are read again for the request.
assert.equal(fake.kernelCalls.filter((call) => call.method === "commands").length, loads + 1);
assert.ok(fake.trees().includes("Keyboard Shortcuts"));
assert.ok(fake.trees().includes("assign-me"));
assert.ok(!fake.trees().includes("Loading settings"));
assert.equal(fake.notices.length, 0);
} finally {
await dispose();
}
});
test("Settings takes the sidebar's place and opens on its section without a loading state", async () => {
const fake = fakeApi();
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(!fake.has("settings-sidebar") && !fake.has("settings-page"), "nothing draws off the route");
fake.route("settings");
await fake.settle();
// Its list of sections, in the sidebar's place, and the open section.
assert.ok(fake.has("settings-sidebar") && fake.has("nav-general") && fake.has("settings-back"));
assert.ok(fake.has("settings-page") && fake.has("appearance"));
assert.ok(!fake.trees().includes("Loading"));
await fake.click("settings-back");
assert.equal(fake.state().route, "chat");
assert.ok(!fake.has("settings-sidebar") && !fake.has("settings-page"));
} finally {
await dispose();
}
});
test("each of the app's sections has a command that opens Settings on it", async () => {
const fake = fakeApi();
const dispose = activate(fake.api);
try {
await fake.settle();
const declared = (manifest.contributes.commands as { id: string; title: string; category: string }[]);
for (const section of APP_SECTIONS) {
const id = `settings.${section.id}`;
assert.ok(declared.some((command) => command.id === id && command.title === section.label && command.category === "Settings"), `${id} is declared`);
fake.route("chat");
await fake.settle();
await fake.command(id);
assert.equal(fake.state().route, "settings", `${id} opens Settings`);
assert.equal(fake.node(`nav-${section.id}`).selected, true, `${id} opens ${section.label}`);
}
assert.equal(fake.notices.length, 0);
} finally {
await dispose();
}
});
const pluginsWorkspace: Workspace = { id: "plugins", name: "Divergence", path: "/plugins", mark: "divergence", position: 0 };
const available: AgentEntry = { id: "test-agent", name: "Test Agent", enabled: true, status: { state: "ready" }, capabilities: { sessionList: true } };
const optionals: PluginSummary[] = ["files", "git", "terminal", "market", "visuals"].map((name) => ({
name, id: `divergence/${name}`, version: "1.0.0", description: name, official: true, claimsOfficial: false,
source: "official-bundle", enabled: true, state: "loaded", ui: true, sandboxed: null, permissions: [], pending: [], commands: 0,
}));
test("first-run guide teaches plugins, makes every choice real, and Start opens the first chat and the saved changes", async () => {
const fake = fakeApi({ progress: null, agents: [available], workspaces: [pluginsWorkspace], plugins: optionals });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.equal(fake.state().route, "onboarding");
assert.ok(fake.trees().includes("One window for every coding agent"));
for (const plugin of ["sidebar", "chat", "files", "git", "terminal", "market", "settings", "themes"])
assert.ok(fake.trees().includes(`"${plugin}"`), `the example window labels ${plugin}`);
assert.equal((fake.progress() as { step: number }).step, 0);
assert.equal(fake.node("onboarding-step-2").onClick, undefined, "later steps cannot be skipped to");
await fake.click("onboarding-next");
assert.ok(fake.trees().includes("Test Agent") && fake.trees().includes("First chat"));
await fake.change("agent-test-agent", false);
assert.equal(fake.node("agent-test-agent").checked, false);
assert.equal(fake.node("onboarding-next").label, "Continue without an agent");
await fake.change("agent-test-agent", true);
await fake.click("onboarding-next");
assert.ok(fake.trees().includes("Divergence’s own plugins"));
fake.pick(null);
await fake.click("onboarding-folder");
assert.ok(!fake.hostCalls.some((c) => c.method === "host/workspaces.add"));
fake.pick("/project");
await fake.click("onboarding-folder");
assert.ok(fake.trees().includes("/project"));
assert.equal(fake.node("onboarding-next").label, "Continue");
await fake.click("onboarding-next");
await fake.change("onboarding-plugin-terminal", false);
assert.ok(fake.hostCalls.some((c) => c.method === "host/plugins.set_enabled" && stable(c.params) === stable({ name: "terminal", enabled: false })));
assert.ok(fake.trees().includes("terminal is off"), "the window loses what was switched off");
await fake.click("onboarding-theme-vscode");
assert.deepEqual(fake.hostCalls.find((c) => c.method === "host/plugins.set_setting")?.params, {
name: "themes", key: "active", value: { light: "vscode-light", dark: "vscode-dark" },
});
await fake.change("onboarding-appearance", "dark");
assert.ok(fake.kernelCalls.some((c) => c.method === "theme" && stable(c.params) === stable({ mode: "dark" })));
await fake.change("onboarding-change", "Show a word count under the prompt");
await fake.click("onboarding-save-change");
assert.ok(fake.trees().includes("Waiting in Divergence for you to send it"));
await fake.click("onboarding-next");
assert.ok(fake.has("onboarding-visual-chart"), "a real reply with a chart");
await fake.click("onboarding-visual-diagram");
assert.ok(fake.has("onboarding-visual-diagram"));
await fake.click("onboarding-next");
assert.equal(fake.node("onboarding-next").label, "Start in Project");
for (const line of ["Project, Divergence", "VS Code Modern, without Terminal", "1 change waiting in Divergence", "Test Agent starts the first chat"])
assert.ok(fake.trees().includes(line), line);
await fake.click("onboarding-next");
assert.equal(fake.state().route, "chat");
assert.equal(fake.state().workspaceId, "project");
assert.equal(fake.state().chatId, "first");
const created = fake.hostCalls.filter((c) => c.method === "host/chats.create").map((c) => c.params);
assert.deepEqual(created, [
{ workspaceId: "plugins", agentId: "test-agent", title: "Show a word count under the prompt", inUse: [] },
{ workspaceId: "project", agentId: "test-agent", inUse: ["draft-1"] },
]);
assert.deepEqual(fake.hostCalls.find((c) => c.method === "host/drafts.update")?.params, {
chatId: "draft-1", revision: 3, blocks: [{ type: "text", text: "Show a word count under the prompt" }],
});
assert.deepEqual(fake.progress(), { done: true, step: 5, workspaceId: "project", firstAgent: "test-agent", saved: [] });
assert.equal(fake.notices.length, 0);
} finally { await dispose(); }
});
test("existing users and completed setup retain their route; the command reopens the guide", async () => {
for (const options of [
{ progress: null, hasChats: true },
{ progress: null, workspaces: [{ id: "project", name: "Project", path: "/project", position: 0 }] },
{},
{ progress: null, route: "market" },
]) {
const fake = fakeApi(options);
const dispose = activate(fake.api);
try {
await fake.settle();
assert.notEqual(fake.state().route, "onboarding");
await fake.command("settings.onboarding");
assert.equal(fake.state().route, "onboarding");
assert.ok(fake.trees().includes("One window for every coding agent"));
} finally { await dispose(); }
}
});
test("interrupted setup resumes its step from older progress, goes back, and Skip still opens a chat", async () => {
const fake = fakeApi({ progress: { done: false, step: 2, workspaceId: "plugins", returning: true }, agents: [available], workspaces: [pluginsWorkspace] });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.equal(fake.state().route, "onboarding");
assert.ok(fake.trees().includes("Add the folders you work in"));
await fake.click("onboarding-back");
assert.ok(fake.trees().includes("Choose your agents"));
await fake.click("onboarding-step-0");
assert.ok(fake.trees().includes("One window for every coding agent"));
await fake.click("onboarding-skip");
assert.equal(fake.state().route, "chat");
assert.equal(fake.state().chatId, "first", "skipping never ends on an empty window");
assert.equal((fake.progress() as { done: boolean }).done, true);
assert.deepEqual(fake.hostCalls.find((c) => c.method === "host/chats.create")?.params, { workspaceId: "plugins", agentId: "test-agent", inUse: [] });
} finally { await dispose(); }
});
test("agent setup shows starting, unavailable and sign-in states, guards duplicate requests, and recovers", async () => {
const auth: AgentEntry = { ...available, status: { state: "auth_required", message: "Sign in to continue" }, authMethods: [{ id: "login", name: "Sign in" }] };
const fake = fakeApi({ progress: { done: false, step: 1, workspaceId: null }, agents: [auth] });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.trees().includes("Sign in to continue"));
fake.fail("host/agents.authenticate");
await fake.click("auth-test-agent-login");
assert.ok(fake.trees().includes("Test service is unavailable"));
assert.equal(fake.node("onboarding-next").disabled, false);
fake.fail(null);
const release = fake.block("host/agents.authenticate");
await fake.click("auth-test-agent-login");
assert.equal(fake.node("auth-test-agent-login").loading, true);
assert.equal(fake.node("onboarding-next").disabled, true);
const handler = fake.node("auth-test-agent-login").onClick;
if (typeof handler === "function") handler();
await fake.settle();
assert.equal(fake.hostCalls.filter((c) => c.method === "host/agents.authenticate").length, 2);
release();
await fake.settle();
assert.ok(fake.trees().includes("Ready"));
assert.ok(!fake.trees().includes("Test service is unavailable"));
fake.agents([{ ...available, status: { state: "starting" } }]);
await fake.emit({ event: "agents_changed" });
assert.ok(fake.trees().includes("Checking…"));
fake.agents([{ ...available, status: { state: "unavailable", message: "Install the agent first" } }]);
await fake.emit({ event: "agents_changed" });
assert.ok(fake.trees().includes("Install the agent first"));
assert.equal(fake.node("onboarding-next").label, "Continue without an agent");
for (let step = 1; step < 5; step++) await fake.click("onboarding-next");
assert.equal(fake.node("onboarding-next").label, "Open Divergence");
await fake.click("onboarding-next");
assert.equal(fake.state().route, "chat");
assert.ok(!fake.hostCalls.some((c) => c.method === "host/chats.create"));
} finally { await dispose(); }
});
test("loading and completion failures remain on setup and can be retried without a false completion", async () => {
const fake = fakeApi({ progress: { done: false, step: 5, workspaceId: "plugins" }, agents: [available], workspaces: [pluginsWorkspace] });
fake.fail("host/settings.get");
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.trees().includes("Test service is unavailable"));
assert.equal(fake.node("onboarding-next").disabled, true);
fake.fail(null);
await fake.click("onboarding-retry");
assert.equal(fake.node("onboarding-next").disabled, false);
fake.fail("host/chats.create");
await fake.click("onboarding-next");
assert.equal(fake.state().route, "onboarding");
assert.equal((fake.progress() as { done: boolean }).done, false);
fake.fail("host/storage.set");
const before = fake.hostCalls.length;
await fake.click("onboarding-next");
assert.equal(fake.state().route, "onboarding");
assert.equal((fake.progress() as { done: boolean }).done, false);
fake.fail(null);
await fake.click("onboarding-next");
assert.equal(fake.state().route, "chat");
const made = fake.hostCalls.slice(before).filter((c) => c.method === "host/chats.create");
assert.equal(made.length, 1, "Start again after a failed save opens the chat the first press made");
} finally { await dispose(); }
});
const projectWorkspace: Workspace = { id: "project", name: "Project", path: "/project", position: 1 };
test("Projects lists every workspace with the Divergence one last, and the chosen one is where the first chat opens", async () => {
const fake = fakeApi({ progress: { done: false, step: 2, workspaceId: "project" }, agents: [available], workspaces: [pluginsWorkspace, projectWorkspace] });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.trees().includes("/project") && fake.trees().includes("Divergence’s own plugins"));
assert.ok(fake.has("onboarding-remove-project") && !fake.has("onboarding-remove-plugins"), "only a project folder can be removed");
await fake.click("onboarding-project-plugins");
assert.equal((fake.progress() as { workspaceId: string }).workspaceId, "plugins");
await fake.click("onboarding-remove-project");
assert.ok(fake.hostCalls.some((c) => c.method === "host/workspaces.remove" && stable(c.params) === stable({ workspaceId: "project" })));
assert.ok(!fake.trees().includes("/project"));
for (let i = 0; i < 3; i++) await fake.click("onboarding-next");
assert.equal(fake.node("onboarding-next").label, "Start in Divergence");
assert.ok(fake.trees().includes("Your first chat opens in Divergence with Test Agent."));
} finally { await dispose(); }
});
/// Chats started outside the app come in through the host, always: the
/// settings plugin offers no switch or button for it and never imports.
test("Settings and the first-run guide neither import chats nor offer a way to", async () => {
const fake = fakeApi({ progress: { done: false, step: 2, workspaceId: null }, agents: [available], workspaces: [pluginsWorkspace, projectWorkspace] });
const dispose = activate(fake.api);
try {
await fake.settle();
fake.pick("/other");
await fake.click("onboarding-folder");
await fake.emit({ event: "agents_changed" });
fake.route("settings");
await fake.settle();
assert.ok(!fake.has("auto-import-chats") && !fake.has("import-sessions") && !fake.has("onboarding-import-row"));
assert.ok(!fake.hostCalls.some((c) => c.method === "host/chats.import"));
} finally { await dispose(); }
});
// --- the update button in the sidebar ---------------------------------------------------
const behind = (id: string, name: string, maintenance: AgentEntry["maintenance"]): AgentEntry => ({
id,
name,
description: "",
capabilities: {},
authMethods: [],
status: { state: "ready" },
enabled: true,
maintenance,
});
const chat = (id: string, agentId: string, status: Chat["status"]) =>
({ id, agentId, workspaceId: "w", status, title: id.toUpperCase(), createdAt: "", updatedAt: "" }) as unknown as Chat;
test("an update asked for while its agent runs waits, then installs once the chat stops", async () => {
const fake = fakeApi({
agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
chats: [chat("c1", "codex", "running")],
onAgentUpdate: () => fake.agents([behind("codex", "Codex", { installedVersion: "0.50.1", manager: "npm", canUpdate: true })]),
});
const dispose = activate(fake.api);
try {
await fake.settle();
// The sidebar draws the published view left of Options, only while something is behind.
assert.equal(typeof fake.state().shared?.["sidebarButton.updates"], "number");
assert.ok(fake.trees().includes("Update Codex"));
await fake.click("sidebar-updates");
assert.equal(fake.node("updates").open, true);
assert.ok(fake.trees().includes("0.48.0 → 0.50.1"));
// The button works at once; the install waits for the run.
await fake.click("update-codex");
assert.ok(!fake.hostCalls.some((call) => call.method === "host/agents.update"));
assert.ok(fake.trees().includes("Updates when “C1” finishes"));
// Another agent's chat ending changes nothing.
await fake.emit({ event: "chat_changed", chat: chat("c2", "claude", "idle") });
assert.ok(!fake.hostCalls.some((call) => call.method === "host/agents.update"));
await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
await fake.settle();
assert.deepEqual(
fake.hostCalls.filter((call) => call.method === "host/agents.update").map((call) => call.params),
[{ agentId: "codex" }],
);
assert.ok(!fake.has("sidebar-updates"), "nothing is behind any more");
assert.equal(fake.state().shared?.["sidebarButton.updates"], null, "so the sidebar keeps no room for the button");
assert.ok(fake.notices.includes("Codex updated to 0.50.1."));
// The next update shows the row, closed.
fake.agents([behind("codex", "Codex", { installedVersion: "0.50.1", latestVersion: "0.51.0", manager: "npm", canUpdate: true })]);
await fake.emit({ event: "agents_changed" });
assert.ok(fake.has("sidebar-updates"));
assert.equal(typeof fake.state().shared?.["sidebarButton.updates"], "number");
assert.equal(fake.node("updates").open, false, "the list stays closed");
} finally {
await dispose();
}
});
test("Settings > Agents disables Sign in, Update and the switch while a sign-in runs", async () => {
const fake = fakeApi({
route: "settings",
agents: [
{
...behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true }),
status: { state: "auth_required", message: "Sign in to continue" },
authMethods: [{ id: "chatgpt", name: "Sign in with ChatGPT" }],
},
],
});
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-agents");
const signIn = fake.block("host/agents.authenticate");
await fake.click("auth-codex-chatgpt");
assert.equal(fake.node("auth-codex-chatgpt").loading, true);
assert.equal(fake.node("auth-codex-chatgpt").disabled, true);
assert.equal(fake.node("agent-codex").disabled, true);
assert.equal(fake.node("update-codex").disabled, true);
signIn();
await fake.settle();
assert.ok(fake.notices.includes("Codex: signed in."));
assert.equal(fake.hostCalls.filter((call) => call.method === "host/agents.authenticate").length, 1);
} finally {
await dispose();
}
});
test("Update in Settings > Agents waits for the agent's running chat, like the update button", async () => {
const fake = fakeApi({
route: "settings",
agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
chats: [chat("c1", "codex", "running")],
});
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-agents");
await fake.click("update-codex");
assert.ok(!fake.hostCalls.some((call) => call.method === "host/agents.update"));
assert.ok(fake.trees().includes("Updates when Codex is idle."));
assert.equal(fake.node("update-codex").disabled, true);
await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
await fake.settle();
assert.equal(fake.hostCalls.filter((call) => call.method === "host/agents.update").length, 1);
} finally {
await dispose();
}
});
test("Install and restart in Settings > Updates waits for the running chats before it quits", async () => {
const fake = fakeApi({
route: "settings",
chats: [chat("c1", "codex", "running")],
updates: {
enabled: true,
appVersion: "1.0.0",
appUpdate: { version: "1.1.0", releaseNotes: "" },
plugins: null,
pluginUpdate: null,
lastChecked: null,
checking: false,
error: null,
busy: null,
},
});
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-updates");
await fake.click("install-app");
assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
assert.ok(!fake.kernelCalls.some((call) => call.method === "quit"));
assert.ok(fake.trees().includes("restarts when every chat is idle"));
assert.equal(fake.node("install-app").disabled, true);
await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
await fake.settle();
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
assert.ok(fake.kernelCalls.some((call) => call.method === "quit"));
} finally {
await dispose();
}
});
test("while the downloaded app waits for every chat, the row says it restarts when they are idle", async () => {
const updates = { enabled: true, appVersion: "1.0.0", appUpdate: { version: "1.1.0", releaseNotes: "" }, pluginUpdate: null, busy: null as string | null };
const fake = fakeApi({ updates });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("sidebar-updates");
const download = fake.block("host/updates.install_app");
await fake.click("update-app");
updates.busy = "restarting when every chat is idle";
await fake.emit({ event: "updates_changed" });
assert.ok(fake.trees().includes("Restarts when every chat is idle"));
assert.ok(!fake.kernelCalls.some((call) => call.method === "quit"));
download();
await fake.settle();
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
assert.ok(fake.kernelCalls.some((call) => call.method === "quit"));
} finally {
await dispose();
}
});
test("an update queued behind another install waits for a chat that started meanwhile", async () => {
const fake = fakeApi({
agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
updates: { enabled: true, appVersion: "1.0.0", appUpdate: { version: "1.1.0", releaseNotes: "" }, pluginUpdate: null },
});
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("sidebar-updates");
const install = fake.block("host/agents.update");
await fake.click("update-codex");
await fake.click("update-app");
await fake.emit({ event: "chat_changed", chat: chat("c1", "claude", "running") });
install();
await fake.settle();
assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
assert.ok(fake.trees().includes("Updates when “C1” finishes"));
await fake.emit({ event: "chat_changed", chat: chat("c1", "claude", "idle") });
await fake.settle();
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
} finally {
await dispose();
}
});
test("pressing the update button opens the list and pressing it again closes it", async () => {
const fake = fakeApi({
agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
});
const dispose = activate(fake.api);
try {
await fake.settle();
assert.equal(fake.node("updates").open, false, "passing over the row opens nothing");
await fake.click("sidebar-updates");
assert.equal(fake.node("updates").open, true);
await fake.click("sidebar-updates");
assert.equal(fake.node("updates").open, false);
} finally {
await dispose();
}
});
test("a skipped version stays away, a newer one comes back, and tomorrow puts off the row", async () => {
const fake = fakeApi({
agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
});
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("sidebar-updates");
await fake.click("update-skip-codex");
assert.ok(!fake.has("sidebar-updates"));
assert.deepEqual(fake.stored()["upkeep"], { skipped: { codex: "0.50.1" }, snoozedUntil: null });
fake.agents([behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.51.0", manager: "npm", canUpdate: true })]);
await fake.emit({ event: "agents_changed" });
assert.ok(fake.trees().includes("Update Codex"));
await fake.click("sidebar-updates");
await fake.click("updates-snooze");
assert.ok(!fake.has("sidebar-updates"));
const until = (fake.stored()["upkeep"] as { snoozedUntil: number }).snoozedUntil;
assert.ok(until > Date.now() + 23 * 60 * 60 * 1000);
} finally {
await dispose();
}
});
test("a host event whose handler fails is logged with its cause, not dropped", async () => {
const fake = fakeApi();
const logged: string[] = [];
const methods = ["log", "info", "warn", "error", "debug"] as const;
const originals = methods.map((name) => console[name]);
for (const name of methods) console[name] = (...args: unknown[]) => void logged.push(args.map(String).join(" "));
const dispose = activate(fake.api);
try {
await fake.settle();
fake.fail("host/updates.status");
await fake.emit({ event: "updates_changed" });
await fake.settle();
} finally {
methods.forEach((name, i) => (console[name] = originals[i] as (typeof console)[typeof name]));
await dispose?.();
}
const line = logged.find((text) => text.includes("settings: handling updates_changed failed"));
assert.ok(line, `nothing logged: ${JSON.stringify(logged)}`);
assert.match(line, /Test service is unavailable/);
});
test("Archived Chats lists them by workspace, restores one, and deletes one only after asking", async () => {
const archived = (id: string, workspaceId: string, day: number): Chat =>
({ ...chat(id, "codex", "idle"), title: id.toUpperCase(), workspaceId, archived: true, updatedAt: `2026-10-0${day}T00:00:00.000Z` }) as Chat;
const live = { ...chat("live", "codex", "idle"), workspaceId: "w1", archived: false } as Chat;
const chats = [archived("a", "w1", 1), archived("b", "w1", 2), archived("c", "w2", 3), live];
const fake = fakeApi({
route: "settings",
agents: [{ id: "codex", name: "Codex", enabled: true }],
workspaces: [
{ id: "w1", name: "Alpha", path: "/alpha", position: 0 },
{ id: "w2", name: "Beta", path: "/beta", position: 1 },
],
chats,
});
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-archived");
// Each workspace's chats, the most recently archived first; a chat that is not archived is not listed.
const order = ["Alpha", "restore-b", "restore-a", "Beta", "restore-c"].map((mark) => fake.trees().indexOf(mark));
assert.ok(order.every((at, n) => at > (order[n - 1] ?? -1)), `in order: ${order}`);
assert.ok(!fake.has("restore-live"));
assert.ok(fake.trees().includes("Codex · Archived"));
await fake.click("restore-a");
assert.deepEqual(fake.hostCalls.at(-1), { method: "host/chats.update", params: { chatId: "a", archived: false } });
assert.ok(!fake.has("restore-a"));
// Delete asks first; Cancel deletes nothing.
await fake.click("delete-b");
assert.ok(fake.trees().includes("Delete “B”? This cannot be undone."));
await fake.click("delete-ask-cancel");
assert.ok(!fake.has("delete-ask"));
assert.ok(!fake.hostCalls.some((call) => call.method === "host/chats.delete"));
await fake.click("delete-b");
await fake.click("delete-ask-confirm");
assert.deepEqual(fake.hostCalls.at(-1), { method: "host/chats.delete", params: { chatId: "b" } });
assert.ok(!fake.has("delete-b") && !fake.has("delete-ask"));
// A failure says so, and the chat stays listed.
fake.fail("host/chats.update");
await fake.click("restore-c");
assert.deepEqual(fake.notices, ["Could not restore “C”: Test service is unavailable"]);
assert.ok(fake.has("restore-c"));
fake.fail(null);
// A chat archived elsewhere joins the list, and one brought back elsewhere leaves it.
await fake.emit({ event: "chat_changed", chat: { ...live, archived: true, updatedAt: "2026-10-05T00:00:00.000Z" } });
assert.ok(fake.has("restore-live"));
await fake.emit({ event: "chat_changed", chat: { ...archived("c", "w2", 3), archived: false } });
assert.ok(!fake.has("restore-c"));
assert.ok(fake.has("restore-live"));
} finally {
await dispose();
}
});
test("Archived Chats says when there are none", async () => {
const fake = fakeApi({ route: "settings", workspaces: [{ id: "w1", name: "Alpha", path: "/alpha", position: 0 }], chats: [] });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-archived");
assert.ok(fake.trees().includes("No archived chats."));
} finally {
await dispose();
}
});
// --- regressions from the settings scan ----------------------------------------
test("Assign… on a row that already records keeps the recorder, and the key shows as key caps", async () => {
const fake = fakeApi({ route: "settings" });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-keys");
await fake.click("assign-b-close");
assert.ok(fake.trees().includes("Press the keys…"));
// Assign… stays on screen while its row records; pressing it again starts over.
await fake.click("assign-b-close");
assert.ok(fake.trees().includes("Press the keys…"), "the recorder is still open");
await fake.pressKey("shift-cmd-k", "⇧⌘K");
assert.ok(fake.has("save-key-b-close"), "the key pressed after Assign… is recorded");
assert.ok(fake.trees().includes("⇧⌘K") && !fake.trees().includes("shift-cmd-k"), "as key caps");
} finally {
await dispose();
}
});
test("a first load that fails says why and loads again on Try again", async () => {
const fake = fakeApi({ route: "settings" });
fake.fail("host/settings.get");
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.trees().includes("Settings could not load"));
assert.ok(fake.trees().includes("Test service is unavailable"));
fake.fail(null);
await fake.click("settings-retry");
assert.ok(fake.has("appearance") && !fake.has("settings-retry"));
} finally {
await dispose();
}
});
test("Archived Chats says why a read failed and reads again on Try again", async () => {
const fake = fakeApi({ route: "settings", workspaces: [{ id: "w1", name: "Alpha", path: "/alpha", position: 0 }], chats: [] });
const dispose = activate(fake.api);
try {
await fake.settle();
fake.fail("host/chats.list");
await fake.click("nav-archived");
assert.ok(fake.trees().includes("Could not read the archived chats"));
fake.fail(null);
await fake.click("archived-retry");
assert.ok(fake.trees().includes("No archived chats.") && !fake.has("archived-retry"));
} finally {
await dispose();
}
});
test("a refused agent switch says what failed in words", async () => {
const fake = fakeApi({ route: "settings", agents: [available] });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-agents");
fake.fail("host/agents.set_enabled");
await fake.change("agent-test-agent", false);
assert.deepEqual(fake.notices, ["Could not turn off Test Agent: Test service is unavailable"]);
assert.equal(fake.node("agent-test-agent").checked, true);
} finally {
await dispose();
}
});
test("Check now stays while an update is known, and a page before the first check says so", async () => {
const fake = fakeApi({ route: "settings", updates: { enabled: true, appVersion: "1.0.0", lastChecked: null, appUpdate: { version: "1.1.0", releaseNotes: null } } });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-updates");
assert.ok(fake.has("check-updates") && fake.has("install-app"));
assert.ok(fake.trees().includes("Not checked yet.") && !fake.trees().includes("Checked never"));
} finally {
await dispose();
}
});
test("each rule file has its own switch, and a plugin turned off before keeps its other files off", async () => {
// Settings from before rules were switched per file turn the whole plugin off.
const rule = (file: string) => ({ plugin: "style", file, text: `${file} text`, enabled: false });
const fake = fakeApi({ route: "settings", disabledRules: ["style"], tools: { mode: "code", tools: [], rules: [rule("a.md"), rule("b.md")] } });
const dispose = activate(fake.api);
try {
await fake.settle();
await fake.click("nav-tools");
assert.ok(fake.has("rules-style-a.md") && fake.has("rules-style-b.md") && !fake.has("rules-style"));
await fake.change("rules-style-a.md", true);
const update = fake.hostCalls.findLast((c) => c.method === "host/settings.update")?.params as { tools: { disabledRules: string[] } };
assert.deepEqual(update.tools.disabledRules, ["style/b.md"], "only the file turned on comes back on");
} finally {
await dispose();
}
});
test("Start without a ready agent keeps the saved changes for the next run of the guide", async () => {
const signedOut: AgentEntry = { ...available, status: { state: "auth_required" } };
const fake = fakeApi({ progress: { done: false, step: 5, workspaceId: "plugins", saved: ["Show a word count"] }, agents: [signedOut], workspaces: [pluginsWorkspace] });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.ok(fake.trees().includes("1 change kept until an agent is ready"));
await fake.click("onboarding-next");
assert.equal(fake.state().route, "chat");
assert.deepEqual((fake.progress() as { saved: string[] }).saved, ["Show a word count"]);
assert.ok(fake.notices.some((n) => n.startsWith("Your saved change waits for a ready agent.")));
} finally {
await dispose();
}
});
// --- plugin updates in the update button's list ------------------------------
const offered = (folder: string, installed: string, latest: string, direct = false) => ({ id: `pub/${folder}`, folder, installed, latest, direct });
const installed = (name: string, provides: boolean) =>
({ name, permissions: provides ? [{ permission: "agents.provide", reason: "", risk: "low", granted: true }] : [] }) as unknown as PluginSummary;
const held = (chatId: string, pauseReason?: string) =>
({ chatId, inputs: [{ id: "i1", chatId, state: "held", intent: "queue", ...(pauseReason ? { pauseReason } : {}) }] }) as unknown as InputSnapshot;
// The other plugins' services answer a few scheduler turns after the views settle.
async function until(fake: { settle: () => Promise<void> }, done: () => boolean, ms = 2000) {
const end = Date.now() + ms;
while (!done() && Date.now() < end) {
await new Promise((resolve) => setTimeout(resolve, 5));
await fake.settle();
}
assert.ok(done(), "the condition never held");
}
// What the runtime fails a service call with while its provider starts: an
// Error named for the tag, with no `_tag` field.
const notRunning = () => Object.assign(new Error("market, which provides divergence/market, is not running"), { name: "Interrupted", tag: "Interrupted" });
const appUpdate = { enabled: true, appVersion: "1.0.0", appUpdate: { version: "1.1.0", releaseNotes: "" }, pluginUpdate: null };
// The market plugin's service, recording each Update in `calls` in the order they ran.
function fakeMarket(updates: ReturnType<typeof offered>[], calls: { method: string; params: unknown }[], fail?: string) {
const market = fakeService({
updates: () => updates,
check: () => updates,
update: ({ folder }: { folder: string }) => {
calls.push({ method: "market.update", params: { folder } });
if (folder === fail) throw { _tag: "UpdateFailed", message: `Could not update ${folder}: offline` };
return null;
},
});
return market;
}
test("the update button lists each plugin update the marketplace offers, beside the app's", async () => {
const calls: { method: string; params: unknown }[] = [];
const market = fakeMarket([offered("codex", "1.0.0", "1.1.0"), offered("word-count", "0.2.0", "0.3.0")], calls);
const fake = fakeApi({ updates: appUpdate, plugins: [installed("codex", true), installed("word-count", false)], services: { "divergence/market": market.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => fake.trees().includes("3 updates"));
await fake.click("sidebar-updates");
for (const id of ["update-plugin:codex", "update-plugin:word-count", "update-app", "updates-all"]) assert.ok(fake.has(id), id);
assert.ok(fake.trees().includes("1.0.0 → 1.1.0") && fake.trees().includes("0.2.0 → 0.3.0"));
// The marketplace's list changes: the row goes with its update.
market.emit("updatesChanged", [offered("word-count", "0.2.0", "0.3.0")]);
await until(fake, () => !fake.has("update-plugin:codex"));
assert.ok(fake.has("update-plugin:word-count"));
// With nothing left in the marketplace's list, the plugin rows go.
market.emit("updatesChanged", []);
await until(fake, () => !fake.has("update-plugin:word-count"));
} finally {
await dispose();
}
});
test("Update all updates the agents, the default plugins, every plugin and then the app", async () => {
const fake = fakeApi({
agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
updates: { ...appUpdate, plugins: { build: 41 }, pluginUpdate: { build: 42 } },
plugins: [installed("claude", true), installed("word-count", false)],
services: { "divergence/market": fakeMarket([offered("claude", "1.0.0", "1.1.0"), offered("word-count", "0.2.0", "0.3.0")], []).client },
});
const order: string[] = [];
const dispose = activate(fake.api);
try {
await until(fake, () => fake.trees().includes("5 updates"));
await fake.click("sidebar-updates");
await fake.click("updates-all");
await fake.settle();
for (const call of fake.hostCalls) if (["host/agents.update", "host/updates.apply_plugins", "host/updates.install_app"].includes(call.method)) order.push(call.method);
assert.deepEqual(order, ["host/agents.update", "host/updates.apply_plugins", "host/updates.install_app"]);
assert.ok(fake.kernelCalls.some((call) => call.method === "quit"), "the app restarts last");
} finally {
await dispose();
}
});
test("Update all runs each plugin's Update before the app restarts", async () => {
const calls: { method: string; params: unknown }[] = [];
const market = fakeMarket([offered("claude", "1.0.0", "1.1.0"), offered("word-count", "0.2.0", "0.3.0")], calls);
const fake = fakeApi({ updates: appUpdate, plugins: [installed("claude", true), installed("word-count", false)], services: { "divergence/market": market.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => fake.trees().includes("3 updates"));
await fake.click("sidebar-updates");
// Before Update all, the kernel's quit records itself among the plugin updates.
const quit = fake.kernelCalls.length;
await fake.click("updates-all");
await fake.settle();
assert.deepEqual(calls.map((call) => call.params), [{ folder: "claude" }, { folder: "word-count" }]);
assert.equal(fake.kernelCalls.slice(quit).filter((call) => call.method === "quit").length, 1);
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
} finally {
await dispose();
}
});
test("a running chat holds the app and the agent plugins, not a plugin without agents, and they go once it ends", async () => {
const calls: { method: string; params: unknown }[] = [];
const market = fakeMarket([offered("claude", "1.0.0", "1.1.0"), offered("word-count", "0.2.0", "0.3.0")], calls);
const fake = fakeApi({
updates: appUpdate,
plugins: [installed("claude", true), installed("word-count", false)],
chats: [chat("c1", "codex", "running")],
services: { "divergence/market": market.client },
});
const dispose = activate(fake.api);
try {
await until(fake, () => fake.trees().includes("3 updates"));
await fake.click("sidebar-updates");
await fake.click("updates-all");
await fake.settle();
// The plugin without agents cuts off no chat, so it updates at once.
assert.deepEqual(calls.map((call) => call.params), [{ folder: "word-count" }]);
assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
// The others say which chat they wait for and offer Cancel.
assert.equal(stable(fake.trees()).split("Updates when “C1” finishes").length - 1, 2);
assert.ok(fake.has("update-cancel-plugin:claude") && fake.has("update-cancel-app"));
await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
await fake.settle();
assert.deepEqual(calls.map((call) => call.params), [{ folder: "word-count" }, { folder: "claude" }]);
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
} finally {
await dispose();
}
});
test("queued messages hold the app until they are sent; a paused queue and a plugin without agents do not wait", async () => {
const calls: { method: string; params: unknown }[] = [];
const market = fakeMarket([offered("claude", "1.0.0", "1.1.0")], calls);
const fake = fakeApi({
updates: appUpdate,
plugins: [installed("claude", true)],
chats: [chat("c1", "codex", "idle"), chat("c2", "claude", "idle")],
services: { "divergence/market": market.client },
});
const dispose = activate(fake.api);
try {
await until(fake, () => fake.trees().includes("2 updates"));
// A message the host paused after a restart sends nothing by itself.
await fake.emit({ event: "inputs_changed", chatId: "c1", snapshot: held("c1", "interrupted by restart") });
await fake.emit({ event: "inputs_changed", chatId: "c2", snapshot: held("c2") });
await fake.click("sidebar-updates");
await fake.click("update-app");
await fake.click("update-plugin:claude");
assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
assert.equal(calls.length, 0);
assert.ok(fake.trees().includes("Updates when “C2” sends its queued messages"));
// The message goes out: it is handed to the agent, the chat runs, and
// it ends with nothing queued.
const sending = { chatId: "c2", inputs: [{ id: "i1", chatId: "c2", state: "dispatching", intent: "queue" }] } as unknown as InputSnapshot;
await fake.emit({ event: "inputs_changed", chatId: "c2", snapshot: sending });
assert.ok(fake.trees().includes("Updates when “C2” sends its queued messages"));
await fake.emit({ event: "chat_changed", chat: chat("c2", "claude", "running") });
await fake.emit({ event: "inputs_changed", chatId: "c2", snapshot: { chatId: "c2", inputs: [] } as unknown as InputSnapshot });
assert.ok(fake.trees().includes("Updates when “C2” finishes"));
assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
await fake.emit({ event: "chat_changed", chat: chat("c2", "claude", "idle") });
await fake.settle();
assert.deepEqual(calls.map((call) => call.params), [{ folder: "claude" }]);
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
} finally {
await dispose();
}
});
test("a queued draft chat holds the app until the chat plugin starts it", async () => {
let read = false;
const chatService = fakeService({
queued: () => {
read = true;
return ["c3"];
},
});
const fake = fakeApi({ updates: appUpdate, chats: [chat("c3", "codex", "idle")], services: { "divergence/chat": chatService.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => read && fake.has("sidebar-updates"));
await fake.click("sidebar-updates");
await fake.click("update-app");
assert.ok(fake.trees().includes("Updates when “C3” sends its queued messages"));
assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
chatService.emit("queuedChanged", []);
await until(fake, () => fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
} finally {
await dispose();
}
});
test("a plugin update that fails says why on its row and offers Retry", async () => {
const calls: { method: string; params: unknown }[] = [];
const market = fakeMarket([offered("word-count", "0.2.0", "0.3.0")], calls, "word-count");
const fake = fakeApi({ plugins: [installed("word-count", false)], services: { "divergence/market": market.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => fake.has("sidebar-updates"));
await fake.click("sidebar-updates");
await fake.click("update-plugin:word-count");
await until(fake, () => fake.trees().includes("Could not update word-count: offline"));
assert.ok(fake.notices.includes("word-count: Could not update word-count: offline"));
assert.ok(fake.trees().includes("Retry"));
} finally {
await dispose();
}
});
test("a market plugin still starting when first read is read again, and its changes still arrive", async () => {
let reads = 0;
const market = fakeService({
updates: () => {
reads++;
if (reads === 1) throw notRunning();
return [offered("git", "0.2.0", "0.3.0")];
},
});
const fake = fakeApi({ plugins: [installed("git", false)], services: { "divergence/market": market.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => fake.has("sidebar-updates"));
assert.equal(reads, 2);
await fake.click("sidebar-updates");
assert.ok(fake.has("update-plugin:git"));
market.emit("updatesChanged", [offered("word-count", "0.2.0", "0.3.0")]);
await until(fake, () => fake.has("update-plugin:word-count"));
} finally {
await dispose();
}
});
test("the first start of a new app installs each plugin update that replaces in place, once per version", async () => {
const calls: { method: string; params: unknown }[] = [];
// git and claude replace in place; mine was changed, so an agent merges it; skipped is skipped at 0.3.0.
const updates = [offered("git", "0.2.0", "0.3.0", true), offered("claude", "1.0.0", "1.1.0", true), offered("mine", "0.1.0", "0.2.0"), offered("skipped", "0.2.0", "0.3.0", true)];
const plugins = [installed("git", false), installed("claude", true), installed("mine", false), installed("skipped", false)];
const stored = { pluginsUpdatedFor: "0.9.0", upkeep: { skipped: { "plugin:skipped": "0.3.0" }, snoozedUntil: null } };
// The market is still starting when it is first asked to check.
const market = fakeMarket(updates, calls);
let checks = 0;
const check = market.client.check as (params: unknown) => unknown;
market.client.check = Object.assign(async (params: unknown) => (++checks === 1 ? Promise.reject(notRunning()) : check(params)), {
result: async (params: unknown) => (++checks === 1 ? { ok: false, error: notRunning() } : { ok: true, value: await check(params) }),
});
const fake = fakeApi({ updates: appUpdate, plugins, chats: [chat("c1", "codex", "running")], stored, services: { "divergence/market": market.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => fake.stored()["pluginsUpdatedFor"] === "1.0.0");
assert.equal(checks, 2, "a check the starting market interrupted is tried again");
// The plugin without agents installs at once; the one with agents waits for the running chat.
assert.deepEqual(calls.map((call) => call.params), [{ folder: "git" }]);
await fake.click("sidebar-updates");
assert.ok(fake.trees().includes("Updates when “C1” finishes"));
assert.ok(fake.has("update-plugin:mine"), "an update an agent merges stays for you");
await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
await until(fake, () => calls.some((call) => (call.params as { folder?: string }).folder === "claude"));
assert.deepEqual(calls.map((call) => call.params), [{ folder: "git" }, { folder: "claude" }]);
assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 0, "the app is not updated by itself");
} finally {
await dispose();
}
// The same version again: nothing is checked or installed.
let checksAgain = 0;
const again: string[] = [];
const nextMarket = fakeService({ updates: () => updates, check: () => (checksAgain++, updates), update: ({ folder }: { folder: string }) => (again.push(folder), {}) });
const next = fakeApi({ updates: appUpdate, plugins, stored: { pluginsUpdatedFor: "1.0.0" }, services: { "divergence/market": nextMarket.client } });
const disposeNext = activate(next.api);
try {
await until(next, () => next.has("sidebar-updates"));
await new Promise((resolve) => setTimeout(resolve, 50));
await next.settle();
assert.equal(checksAgain, 0);
assert.deepEqual(again, []);
} finally {
await disposeNext();
}
});
test("an app that runs its plugins from a source tree never updates them by itself", async () => {
const calls: { method: string; params: unknown }[] = [];
const market = fakeMarket([offered("git", "0.2.0", "0.3.0", true)], calls);
const fake = fakeApi({ updates: { ...appUpdate, enabled: false }, plugins: [installed("git", false)], services: { "divergence/market": market.client } });
const dispose = activate(fake.api);
try {
await until(fake, () => fake.has("sidebar-updates"));
await new Promise((resolve) => setTimeout(resolve, 50));
await fake.settle();
assert.deepEqual(calls, []);
assert.equal(fake.stored()["pluginsUpdatedFor"], undefined);
} finally {
await dispose();
}
});
test("an update footer row an older settings plugin left in the saved app state is cleared", async () => {
const fake = fakeApi({ shared: { "sidebarItem.updates": 218103812, "sidebarItem.other": 7 } });
const dispose = activate(fake.api);
try {
await fake.settle();
assert.equal(fake.state().shared?.["sidebarItem.updates"], null);
assert.equal(fake.state().shared?.["sidebarItem.other"], 7, "another plugin's row is left alone");
} finally {
await dispose();
}
});Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.8latest | Nov 21, 2026 | >=5 <6 | 68.5 KB | 7 permissions | Listed |
| 0.2.7 | Nov 18, 2026 | >=5 <6 | 68 KB | 7 permissions | Listed |
| 0.2.6 | Nov 16, 2026 | >=5 <6 | 66.3 KB | 7 permissions | Listed |
| 0.2.5 | Nov 11, 2026 | >=5 <6 | 63.6 KB | 7 permissions | Listed |
| 0.2.4 | Nov 9, 2026 | >=5 <6 | 61.6 KB | 7 permissions | Listed |
| 0.2.3 | Oct 27, 2026 | >=2 <4 | 46.8 KB | 7 permissions | Listed |
No comments yet.