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.4
Permissions in 0.2.4
Files
controller.ts9.6 KB
// Palette effects load catalogs and run selections in their owning plugins.
// Search tickets preserve the baseline's rule that an older response cannot replace a newer one.
import * as Effect from "effect/Effect";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as z from "zod";
import type { KeyConflict, PaletteProviderInfo } from "divergence";
import { Host, Kernel, Notify, Services, Views } from "divergence/effect";
import type { HostError, KernelCallFailed } from "divergence/effect";
import type { Settings } from "../settings/contract.ts";
import type { Mode } from "./model.ts";
import type { ChatRowMarks } from "../sdk/ui/chat-row.ts";
import { KEEP_FOR_MS, commandLabel, keptWhileSame, modeOf, rankCommands, remember } from "./model.ts";
import { PaletteState } from "./state.ts";
import { chats } from "./chats.ts";
export interface Row {
kind: "command" | "item" | "chat";
id: string;
title: string;
positions: readonly number[];
key: string | null;
detail: string;
conflict?: KeyConflict | null;
// A chat's row also shows its status, when it was last active (`updatedAt`, put in words only for the rows drawn) and its workspace's mark.
chat?: ChatRowMarks;
run: Effect.Effect<unknown, HostError | KernelCallFailed>;
}
export const controller = Effect.fn("Palette.controller")(function* () {
const state = yield* PaletteState;
const host = yield* Host;
const kernel = yield* Kernel;
const notify = yield* Notify;
const views = yield* Views;
const services = yield* Services;
const scope = yield* Scope.Scope;
const chatList = yield* chats();
const update = () => state.view?.update();
// The chat search keeps what was typed when it closes or gives way to the commands.
const keep = () => {
if (state.open === "chats") state.kept = { query: state.query, at: Date.now() };
};
// Closing also drops a press whose lists are still on their way.
const close = () => {
state.opening++;
state.pending = null;
keep();
if (state.open) {
state.open = null;
update();
}
};
// The chat search opened again within KEEP_FOR_MS of closing shows what
// was typed in it, with a plugin mode's last results until its search
// answers again; later, and the commands always, it opens empty.
const show = Effect.fn("Palette.show")(function* (kind: "commands" | "chats") {
const kept = kind === "chats" && state.kept && Date.now() - state.kept.at < KEEP_FOR_MS ? state.kept.query : "";
keep();
Object.assign(state, { open: kind, query: kept, selected: 0, top: 0 });
if (!kept) state.found = { key: "", items: [] };
update();
yield* views.focus("palette-input");
const mode = modeOf(kept, state.providers);
if (mode.mode === "provider") yield* Effect.forkIn(search(mode.provider, mode.query), scope, { startImmediately: true });
});
const readCommands = Effect.all([kernel.call("commands", {}), kernel.call("palette.providers", {})], {
concurrency: "unbounded",
}).pipe(
Effect.tap(([commands, providers]) =>
Effect.sync(() => {
state.commands = commands.commands;
state.providers = providers.providers;
}),
),
);
// Each press of a key takes a ticket: the lists of an older press, or of
// one closed since, open nothing, so the last key pressed decides what
// opens. A press of the key whose palette is open or on its way closes it.
const open = Effect.fn("Palette.open")(function* (
kind: "commands" | "chats",
read: Effect.Effect<unknown, HostError | KernelCallFailed>,
) {
if (state.open === kind || state.pending === kind) return close();
const ticket = ++state.opening;
state.pending = kind;
const failed = (error: { message: string }) => notify.error(`The palette could not open: ${error.message}`).pipe(Effect.as(false));
const loaded = yield* read.pipe(Effect.as(true), Effect.catch(failed));
if (ticket !== state.opening) return false;
state.pending = null;
if (loaded) yield* show(kind);
return loaded;
});
const openCommands = Effect.fn("Palette.openCommands")(function* () {
yield* open("commands", readCommands);
});
const openChats = Effect.fn("Palette.openChats")(function* () {
// Only a first read that failed or has not answered yet is waited for.
if (yield* open("chats", state.chatsLoaded ? Effect.void : chatList.load())) yield* refresh();
});
// A list opened while the plugins load lacks the commands of those not
// loaded yet: it is read again as they come.
const refresh = Effect.fn("Palette.refresh")(function* () {
if (!state.open) return;
yield* readCommands;
update();
});
const runCommand = Effect.fn("Palette.runCommand")(function* (id: string) {
state.recent = remember(state.recent, id);
// The baseline launches persistence before running the command, without waiting for it.
yield* Effect.forkIn(host.call("host/storage.set", { key: "recentCommands", value: state.recent }), scope, {
startImmediately: true,
});
const { ran } = yield* kernel.call("run_command", { id });
if (!ran) yield* notify.warning(`${id} did not run: its plugin is not running.`);
});
const rank = (): Row[] => {
if (!state.open) return [];
const mode: Mode<PaletteProviderInfo> =
state.open === "commands" ? { mode: "commands", query: state.query } : modeOf(state.query, state.providers);
if (mode.mode === "commands")
return rankCommands(state.commands, mode.query, state.recent).map(({ command, positions }) => ({
kind: "command",
id: command.id,
title: commandLabel(command),
positions,
key: command.labels?.[0] ?? null,
conflict: command.conflict ?? null,
detail: command.pluginTitle ?? command.plugin,
run: runCommand(command.id),
}));
if (mode.mode === "provider") {
const provider = mode.provider;
// The provider's last answer stays until the answer for this text
// lands, so a keystroke never empties the list.
const found = state.found.key.startsWith(searchKey(provider, "")) ? state.found.items : [];
return found.map((item) => ({
kind: "item",
id: `${provider.plugin}/${item.id}`,
title: String(item.title ?? item.id),
positions: [],
key: null,
detail: item.detail ?? provider.title ?? provider.plugin,
run: kernel.call("palette.run", { plugin: provider.plugin, id: provider.id, item }),
}));
}
return chatList.rows(mode.query);
};
// An arrow key only moves the selection: the rows are ranked again only when what they come from changed.
const rows = keptWhileSame(() => [state.open, state.query, state.chatsRevision, state.workspaces, state.commands, state.providers, state.found, state.recent], rank);
const search = Effect.fn("Palette.search")(function* (provider: PaletteProviderInfo, query: string) {
const key = searchKey(provider, query);
const ticket = ++state.searching;
yield* kernel.call("palette.search", { plugin: provider.plugin, id: provider.id, query }).pipe(
Effect.matchEffect({
onSuccess: (answer) =>
Effect.sync(() => {
if (ticket !== state.searching) return;
state.found = { key, items: answer.items };
update();
}),
onFailure: Effect.fn("Palette.searchFailed")(function* (error) {
if (ticket !== state.searching) return;
state.found = { key, items: [] };
yield* notify.error(`${provider.title ?? provider.plugin}: ${error.message}`);
update();
}),
}),
);
});
const pick = Effect.fn("Palette.pick")(function* (list: readonly Row[], selected: number) {
const chosen = list[selected];
close();
if (chosen)
yield* chosen.run.pipe(
Effect.catchTag(["HostCallFailed", "KernelCallFailed", "PermissionNotGranted", "NeedsReview"], (error) =>
notify.error(`${chosen.title}: ${error.message}`),
),
);
});
const assign = Effect.fn("Palette.assign")(function* (id: string) {
close();
const client = state.settings;
// Without the settings plugin there is no Keyboard Shortcuts page; the
// shared request the baseline wrote would have had no reader either.
if (!client) return;
yield* client.showShortcuts({ query: id }).pipe(
// A call that loses its provider on the way behaves like no reader,
// and the failure is logged.
Effect.ignore({ log: "Warn", message: "Could not open Keyboard Shortcuts" }),
);
});
const loadRecent = Effect.fn("Palette.loadRecent")(function* () {
const { value } = yield* host.call("host/storage.get", { key: "recentCommands" });
// Invalid saved entries were ignored by the JavaScript palette as well.
const saved = z.array(z.unknown()).safeParse(value);
if (saved.success) state.recent = saved.data.filter((id): id is string => typeof id === "string");
});
// Assign needs the settings plugin; the client is kept while it runs.
const followSettings = Effect.fn("Palette.followSettings")(function* () {
yield* services.when<typeof Settings>("divergence/settings").pipe(
Stream.runForEach((option) =>
Effect.sync(() => {
state.settings = option._tag === "Some" ? option.value : undefined;
}),
),
Effect.forkIn(scope, { startImmediately: true }),
);
});
yield* followSettings();
return { state, rows, close, openCommands, openChats, chats: chatList, refresh, search, pick, assign, loadRecent };
});
const searchKey = (provider: PaletteProviderInfo, query: string) => `${provider.plugin}/${provider.id}/${query}`;
export type Controller = Effect.Success<ReturnType<typeof controller>>;
No comments yet.