Official
palette
Built-in command palette (⌘⇧P) and chat search (⌘P).
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/palette@0.2.5
Permissions in 0.2.5
Files
settings.test.ts20.6 KB
// Real activation with a canned host and settings client. Assign opens
// Keyboard Shortcuts through the divergence/settings service, and without a
// provider it only closes the palette. The chat search keeps the chats
// current through the host's events.
import assert from "node:assert/strict";
import { test } from "node:test";
import * as z from "zod";
import type {
Api,
AppState,
AppStatePatch,
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));
const stable = (value: unknown) =>
JSON.stringify(value, (_key, item: unknown) => (typeof item === "function" ? "@handler" : item));
function fakeApi(withSettings: boolean) {
let state: AppState = {};
const appListeners = new Set<(state: AppState) => void>();
const views: { render: (ctx: ViewContext<object>) => RenderResult; active: boolean }[] = [];
const settingsCalls: { method: string; params: unknown }[] = [];
const focused: string[] = [];
const notices: string[] = [];
let dirty = true;
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 commands = [
{
id: "a.open",
title: "Open",
category: "A",
plugin: "a",
pluginTitle: "A",
official: true,
labels: [],
source: "default",
conflict: { key: "cmd+x", label: "⌘X", with: "b.other", withTitle: "Other" },
problem: null,
kernel: false,
enabled: true,
registered: true,
},
];
// While set, the commands list answers only once it resolves.
let commandsGate: Promise<void> | null = null;
let commandsFail = false;
const providers = [{ plugin: "p", id: "issues", prefix: "#", title: "Issues" }];
// Each search answers only when the test releases it.
const searches: { query: string; answer: () => void }[] = [];
const kernelCall = async (method: string, params: unknown) => {
if (method === "commands") {
await commandsGate;
if (commandsFail) throw new Error("the kernel is gone");
return { commands };
}
if (method === "palette.providers") return { providers };
if (method === "palette.search") {
const { query } = z.object({ query: z.string() }).parse(params);
await new Promise<void>((answer) => searches.push({ query, answer }));
return { items: [{ id: query, title: `Issue ${query}` }] };
}
throw new Error(`Unexpected kernel method ${method} ${JSON.stringify(params)}`);
};
let chats = [
{ id: "c1", workspaceId: "w", title: "Fix the parser", updatedAt: "2026-01-02T00:00:00Z", archived: false },
{ id: "c2", workspaceId: "w", title: "Plugin search", updatedAt: "2026-01-01T00:00:00Z", archived: false, task: "t2" },
{ id: "c3", workspaceId: "w2", title: "🚀 Landing hero", updatedAt: "2025-12-01T00:00:00Z", archived: false },
];
let workspaces = [
{ id: "w", name: "nexus" },
{ id: "w2", name: "landing" },
];
// The user checked off c2's task.
const tasks = [{ id: "t2", completedAt: "2026-01-03T00:00:00Z" }];
const hostCalls: string[] = [];
const hostCall = async (method: string, params: unknown) => {
hostCalls.push(method);
if (method === "host/chats.list") return { chats };
if (method === "host/workspaces.list") return { workspaces };
if (method === "host/tasks.list") return { tasks };
if (method === "host/storage.get") return { value: null };
if (method === "host/storage.set") return {};
throw new Error(`Unexpected host method ${method} ${JSON.stringify(params)}`);
};
const settingsClient = {
showShortcuts: Object.assign(async () => null, {
// The Effect adapter calls through `result`, never the direct call.
result: async (params: unknown) => {
settingsCalls.push({ method: "showShortcuts", params });
return { ok: true as const, value: null };
},
}),
on: () => () => {},
};
const eventListeners = new Map<string, Set<(event: HostEvent) => void>>();
const emit = (event: HostEvent) => {
for (const listener of eventListeners.get(event.event) ?? []) listener(event);
};
const broker = testLayer();
const registered = new Map<string, () => unknown>();
// This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
const api = new Proxy(
{
...broker.api,
plugin: "palette",
id: "divergence/palette",
services: {
provide: async () => ({ emit: () => {}, remove: () => {} }),
get: (name: string) => {
if (name === "divergence/settings" && withSettings) return settingsClient;
throw new Error(`no provider for ${name}`);
},
available: (name: string) => name === "divergence/settings" && withSettings,
when: (name: string, fn: (client: unknown) => void) => {
fn(name === "divergence/settings" && withSettings ? settingsClient : undefined);
return () => {};
},
},
host: { ...broker.api.host, call: hostCall, kernel: kernelCall },
app: {
state: () => state,
update,
share: (key: string, value: unknown) => update({ shared: { [key]: value } }),
select: (chatId: string, workspaceId: string) => update({ chatId, workspaceId, route: "chat" }),
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) => void) => {
const listeners = eventListeners.get(name) ?? new Set();
eventListeners.set(name, listeners.add(fn));
return () => listeners.delete(fn);
},
command: ({ id, run }: { id: string; run: () => unknown }) => {
registered.set(id, run);
return { remove: () => {} };
},
notify: (...args: unknown[]) => {
notices.push(stable(args));
},
focus: (id: string) => {
focused.push(id);
},
},
{
get(target, key, receiver) {
if (Reflect.has(target, key)) return Reflect.get(target, key, receiver);
throw new Error(`Unexpected API ${String(key)}`);
},
},
) as unknown as Api;
const render = () =>
views
.filter((view) => view.active)
.map((view) =>
view.render({
state: {},
set: () => {},
app: state,
plugin: "palette",
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("palette did not settle");
};
const nodeSchema = z.object({ id: z.string().optional(), children: z.array(z.unknown()).optional() }).passthrough();
function found(tree: unknown): Record<string, unknown>[] {
if (Array.isArray(tree)) return tree.flatMap(found);
const parsed = nodeSchema.safeParse(tree);
if (!parsed.success) return [];
return [
parsed.data,
...(parsed.data.children ?? []).flatMap(found),
...(Array.isArray(parsed.data.items) ? parsed.data.items.flatMap(found) : []),
];
}
const invoke = (id: string, event = "onClick", payload: unknown = {}) => {
const node = trees.flatMap((view) => found(view)).find((node) => node.id === id);
assert.ok(node, `Missing ${id}`);
const handler = z.custom<(payload: unknown) => unknown>((value) => typeof value === "function").parse(node[event]);
handler(payload);
};
return {
api,
hostCalls,
holdCommands: () => {
let release = () => {};
commandsGate = new Promise<void>((resolve) => (release = resolve));
return () => {
commandsGate = null;
release();
};
},
failCommands: () => {
commandsFail = true;
},
answerSearch: (query: string) => searches.find((search) => search.query === query)?.answer(),
notices,
removeWorkspace: (id: string) => {
workspaces = workspaces.filter((workspace) => workspace.id !== id);
chats = chats.filter((chat) => chat.workspaceId !== id);
},
nodes: () => trees.flatMap((view) => found(view)),
emit,
registered,
settingsCalls,
settle,
invoke,
trees: () => stable(trees),
state: () => state,
};
}
test("Assign on a conflicting key calls the settings service", async () => {
const fake = fakeApi(true);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.registered.get("palette.commands")?.();
await fake.settle();
assert.ok(fake.trees().includes("palette-assign-a.open"));
fake.invoke("palette-assign-a.open");
await fake.settle();
assert.deepEqual(fake.settingsCalls, [{ method: "showShortcuts", params: { query: "a.open" } }]);
assert.equal(fake.state().shared?.showShortcuts, undefined);
} finally {
await dispose();
}
});
test("without the settings plugin Assign only closes the palette", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.registered.get("palette.commands")?.();
await fake.settle();
assert.ok(fake.trees().includes("palette-assign-a.open"));
fake.invoke("palette-assign-a.open");
await fake.settle();
assert.deepEqual(fake.settingsCalls, []);
assert.equal(fake.state().shared?.showShortcuts, undefined);
assert.ok(!fake.trees().includes("palette-assign-a.open"));
} finally {
await dispose();
}
});
// The chats used to be read each time the search opened, so it waited for
// the host and then showed a snapshot: a chat archived while it was open
// stayed listed, and picking it opened an archived chat.
test("the chat search opens without reading the chats and lists what the host has now", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
const listed = () => fake.hostCalls.filter((method) => method === "host/chats.list").length;
try {
await fake.settle();
assert.equal(listed(), 1, "read once, when the plugin starts");
fake.emit({
event: "chat_changed",
chat: { id: "c2", workspaceId: "w", title: "Plugin search", updatedAt: "2026-01-03T00:00:00Z", archived: true },
} as HostEvent);
fake.registered.get("palette.chats")?.();
await fake.settle();
assert.equal(listed(), 1, "opening does not read them again");
assert.ok(fake.trees().includes("Fix the parser"));
assert.ok(!fake.trees().includes("Plugin search"), "a chat archived elsewhere is not listed");
// While it is open.
fake.emit({
event: "chat_changed",
chat: { id: "c3", workspaceId: "w", title: "Plugin docs", updatedAt: "2026-01-04T00:00:00Z", archived: false },
} as HostEvent);
fake.emit({ event: "chat_removed", chatId: "c1" } as HostEvent);
await fake.settle();
assert.ok(fake.trees().includes("Plugin docs"));
assert.ok(!fake.trees().includes("Fix the parser"));
} finally {
await dispose();
}
});
// The host deletes a removed workspace's chats with it and reports only that
// the workspaces changed; the search used to keep listing them, and picking
// one opened a chat that no longer existed.
test("the chat search drops the chats of a removed workspace", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
assert.ok(fake.trees().includes("Landing hero"));
fake.removeWorkspace("w2");
fake.emit({ event: "workspaces_changed" } as HostEvent);
await fake.settle();
assert.ok(!fake.trees().includes("Landing hero"));
assert.ok(fake.trees().includes("Fix the parser"));
} finally {
await dispose();
}
});
// Cmd+Shift+P then Cmd+P: the commands' slower lists used to open the
// command palette over the chat search the user asked for last.
test("the last key pressed decides what the palette shows", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
const release = fake.holdCommands();
fake.registered.get("palette.commands")?.();
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
assert.ok(fake.trees().includes("Search chats"));
release();
await fake.settle();
assert.ok(fake.trees().includes("Search chats"), "the earlier press does not take over");
assert.ok(!fake.trees().includes("Type a command"));
} finally {
await dispose();
}
});
// A failed read used to fail only the command's handler, which the runtime
// logs: the key did nothing and nothing said why.
test("a palette that cannot read its lists says so", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.failCommands();
fake.registered.get("palette.commands")?.();
await fake.settle();
assert.ok(!fake.trees().includes("Type a command"));
assert.ok(fake.notices.some((notice) => notice.includes("The palette could not open: the kernel is gone")), fake.notices.join("\n"));
} finally {
await dispose();
}
});
// Each keystroke in a provider's mode used to empty the list and say
// "Nothing matches." until the provider answered.
test("a provider's mode keeps its last items while the next search runs", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
fake.invoke("palette-input", "onChange", { value: "#1" });
await fake.settle();
fake.answerSearch("1");
await fake.settle();
assert.ok(fake.trees().includes("Issue 1"));
fake.invoke("palette-input", "onChange", { value: "#12" });
await fake.settle();
assert.ok(fake.trees().includes("Issue 1"), "the list keeps the last answer while the next one runs");
assert.ok(!fake.trees().includes("Nothing matches."));
fake.answerSearch("12");
await fake.settle();
assert.ok(fake.trees().includes("Issue 12"));
} finally {
await dispose();
}
});
// The matcher counts UTF-16 units, so an emoji before the match used to
// shift the bold letters one place to the right.
test("the letters a search matched are the ones drawn bold, after an emoji too", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
fake.invoke("palette-input", "onChange", { value: "hero" });
await fake.settle();
const bold = fake
.nodes()
.filter((node) => node.weight === 650)
.map((node) => node.text)
.join("");
assert.equal(bold, "hero");
} finally {
await dispose();
}
});
// The chat search used to open empty every time, so a chat looked for a
// moment ago had to be typed for again.
test("the chat search keeps what was typed for half a minute after it closes", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
const realNow = Date.now;
let now = realNow();
Date.now = () => now;
const typed = () => fake.nodes().find((node) => node.id === "palette-input")?.value;
try {
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
fake.invoke("palette-input", "onChange", { value: "parser" });
await fake.settle();
fake.invoke("palette", "onDismiss");
await fake.settle();
now += 29_000;
fake.registered.get("palette.chats")?.();
await fake.settle();
assert.equal(typed(), "parser", "opened again within half a minute, it shows the same text");
assert.ok(fake.trees().includes("Fix the "), "and its matches");
assert.ok(!fake.trees().includes("Plugin search"));
fake.registered.get("palette.chats")?.();
await fake.settle();
fake.registered.get("palette.commands")?.();
await fake.settle();
assert.equal(typed(), "", "the commands never take the chat search's text");
fake.registered.get("palette.commands")?.();
await fake.settle();
now += 30_000;
fake.registered.get("palette.chats")?.();
await fake.settle();
assert.equal(typed(), "", "after half a minute closed, it opens empty");
} finally {
Date.now = realNow;
await dispose();
}
});
test("a chat's row shows its status, when it was last active and its workspace's mark", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.emit({
event: "chat_changed",
chat: { id: "c1", workspaceId: "w", title: "Fix the parser", status: "running", updatedAt: "2026-01-02T00:00:00Z", archived: false },
} as HostEvent);
fake.registered.get("palette.chats")?.();
await fake.settle();
fake.invoke("palette-input", "onChange", { value: "parser" });
await fake.settle();
const nodes = fake.nodes();
assert.ok(nodes.some((node) => node.type === "spinner"), "a chat at work shows the spinner");
assert.ok(nodes.some((node) => node.type === "icon" && node.name === "folder"), "its workspace's mark beside the workspace's name");
assert.ok(fake.trees().includes("nexus"));
assert.ok(fake.trees().includes("2026") || fake.trees().includes("Jan"), "and when it was last active");
} finally {
await dispose();
}
});
test("a checked-off chat shows a check, and loses it once opened again", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
const checks = () => fake.nodes().filter((node) => node.type === "icon" && node.name === "circle-check").length;
try {
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
fake.invoke("palette-input", "onChange", { value: "plugin search" });
await fake.settle();
assert.equal(checks(), 1, "the chat whose task is checked off");
fake.emit({ event: "task_changed", task: { id: "t2", completedAt: null } } as HostEvent);
await fake.settle();
assert.equal(checks(), 0, "its task opened again");
fake.emit({ event: "task_changed", task: { id: "t2", completedAt: "2026-01-04T00:00:00Z" } } as HostEvent);
await fake.settle();
assert.equal(checks(), 1, "and checked off again");
fake.emit({ event: "task_removed", taskId: "t2" } as HostEvent);
await fake.settle();
assert.equal(checks(), 0, "its task gone");
} finally {
await dispose();
}
});
// The rows were drawn again for every arrow key, and only eight of them
// were drawn at all, so the wheel had nothing to scroll.
test("the rows scroll in the kernel's list, and an arrow key moves only the selection's fill", async () => {
const fake = fakeApi(false);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.registered.get("palette.chats")?.();
await fake.settle();
const scroller = () => fake.nodes().find((node) => node.id === "palette-rows")!;
const items = () => (scroller().items ?? scroller().children) as { follows?: string }[];
const rows = () => items().slice(1);
const before = rows();
assert.equal(scroller().type, "scroller");
assert.equal(scroller().reveal, "palette-row-chat-c1");
assert.equal(items()[0]!.follows, "palette-row-chat-c1");
const overlay = fake.nodes().find((node) => node.id === "palette") as { keys: Record<string, () => void> };
overlay.keys.down();
await fake.settle();
assert.equal(scroller().reveal, "palette-row-chat-c2", "the list brings the selected row into view");
assert.equal(items()[0]!.follows, "palette-row-chat-c2");
rows().forEach((row, i) => assert.equal(row, before[i], "each row is the element drawn before"));
} finally {
await dispose();
}
});
No comments yet.