Files
RuneStone/tests/unit/plugins/pluginNativeApis.spec.ts
T
Knotty Wyvern a6d6e96d6d Give plugins SDK APIs for terminals, granted folders, and plugin services
Plugins can now do through the SDK what they did with direct native calls.
The SDK checks plugin shutdown, so these APIs can move to an isolated
plugin context later.

- api.pty opens shell sessions. pty_open accepts an optional channel.
  A channel session sends its output as raw bytes to its own webview
  and sends no pty-data or pty-exit events. Without a channel, the
  events stay, so the released Terminal plugin keeps working. The host
  closes the open sessions of a plugin when the plugin stops.
- api.files gives folder grants. The user selects the folder, the
  host keeps the grants of each plugin in its retained data, and the
  plugin uses an opaque grant ID. The host rejects names with folder
  parts, links, and files over the size limit. Sidecar JSON files
  replace the per-image settings commands.
- api.services lets one plugin offer data to another plugin in the
  same window. The host copies arguments and results.
- The folder methods of api.backgrounds are deprecated. They stay for
  released Background Slideshow versions.
- The plugin reference lists the native calls of each plugin and the
  SDK member that replaces each call.
2026-10-28 01:46:55 -07:00

157 lines
9.0 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import { ServiceHub } from "../../../src/lib/plugins/services.ts";
import type { FilesTransport, PluginApi, PtyTransport } from "../../../src/lib/plugins/sdk.ts";
const base: SessionServices = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
};
async function start(id: string, services: Partial<SessionServices>) {
let api!: PluginApi;
const session = new ExternalSession(id, { ...base, ...services }, () => {}, () => {}, new ContributionRegistry());
await session.start({ activate(value) { api = value; } });
return { api, session };
}
function fakePty() {
const calls: unknown[][] = [];
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
let release: (() => void) | undefined;
const transport: PtyTransport & { hold(): void } = {
hold() { let done!: () => void; const wait = new Promise<void>(resolve => { done = resolve; }); release = done; holding = wait; },
open: async (request, data, exit) => { calls.push(["open", request]); outputs.set(request.id, { data, exit }); await holding; },
write: async (id, data) => { calls.push(["write", id, data]); },
resize: async (id, cols, rows) => { calls.push(["resize", id, cols, rows]); },
close: async id => { calls.push(["close", id]); },
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
openWindow: async () => { calls.push(["window"]); },
dictation: async () => { calls.push(["dictation"]); },
};
let holding: Promise<void> = Promise.resolve();
return { transport, calls, outputs, release: () => release?.() };
}
test("terminal sessions deliver their own output and close when the plugin stops", async () => {
const pty = fakePty();
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
assert.equal(api.pty!.version, 1);
assert.deepEqual(await api.pty!.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
const received: string[] = [];
const exits: (number | null)[] = [];
const first = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh", onData: data => received.push(new TextDecoder().decode(data)), onExit: code => exits.push(code) });
const second = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
assert.notEqual(first.id, second.id);
assert.deepEqual(pty.calls[0], ["open", { id: first.id, cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh" }]);
pty.outputs.get(first.id)!.data(new TextEncoder().encode("ready"));
await first.write("dir\r");
await first.resize(100, 30);
assert.deepEqual(received, ["ready"]);
assert.deepEqual(pty.calls.slice(-2), [["write", first.id, "dir\r"], ["resize", first.id, 100, 30]]);
assert.throws(() => first.resize(0, 30), /positive integers/);
// An exited session needs no close at shutdown.
pty.outputs.get(first.id)!.exit(0);
assert.deepEqual(exits, [0]);
await session.stop();
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", second.id]]);
pty.outputs.get(second.id)!.data(new TextEncoder().encode("late"));
assert.deepEqual(received, ["ready"]);
assert.throws(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }), /disabled/);
assert.throws(() => api.pty!.openWindow(), /disabled/);
assert.throws(() => second.write("x"), /disabled/);
// Close stays safe after shutdown and is not repeated.
await second.close();
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
});
test("a terminal session that starts after shutdown is closed", async () => {
const pty = fakePty();
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
pty.transport.hold();
const opening = api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
const stopping = session.stop();
pty.release();
await assert.rejects(opening, /disabled/);
await stopping;
const id = (pty.calls[0][1] as { id: string }).id;
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", id]]);
});
test("a closed terminal session rejects input and closes once", async () => {
const pty = fakePty();
const { api } = await start("org.test.terminal", { pty: pty.transport });
const output: string[] = [];
const terminal = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: data => output.push(String(data.length)) });
await Promise.all([terminal.close(), terminal.close()]);
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
assert.throws(() => terminal.write("x"), /closed/);
pty.outputs.get(terminal.id)!.data(new Uint8Array([1]));
assert.deepEqual(output, []);
await assert.rejects(Promise.resolve().then(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24 } as never)), /onData/);
});
test("folder grant calls check shutdown before and after the native request", async () => {
const calls: unknown[][] = [];
let finish: ((value: unknown) => void) | undefined;
const grant = { id: "7f1b6f6e-3c39-4b55-9f3e-4a3a6d1d7c11", path: "C:/Pictures/RuneStone Backgrounds", name: "RuneStone Backgrounds" };
const files: FilesTransport = {
chooseFolder: async options => { calls.push(["choose", options]); return grant; },
pictureFolder: async name => { calls.push(["picture", name]); return grant; },
grants: async () => [grant],
revoke: async id => { calls.push(["revoke", id]); return true; },
list: () => new Promise(resolve => { finish = resolve as (value: unknown) => void; }),
readBytes: async (id, name) => { calls.push(["read", id, name]); return new Uint8Array([1, 2]); },
readSidecar: async () => null,
writeSidecar: async (id, name, contents, expected) => { calls.push(["write", id, name, contents, expected]); },
};
const { api, session } = await start("org.test.slides", { files });
assert.deepEqual(await api.files!.chooseFolder({ title: "Images" }), grant);
assert.deepEqual(await api.files!.pictureFolder("Backgrounds"), grant);
assert.deepEqual(await api.files!.readBytes(grant.id, "a.png"), new Uint8Array([1, 2]));
await api.files!.writeSidecar(grant.id, ".runestone-backgrounds.json", "{}", null);
assert.equal(await api.files!.revoke(grant.id), true);
assert.deepEqual(calls, [["choose", { title: "Images" }], ["picture", "Backgrounds"], ["read", grant.id, "a.png"], ["write", grant.id, ".runestone-backgrounds.json", "{}", null], ["revoke", grant.id]]);
assert.throws(() => api.files!.readBytes("", "a.png"), /grant ID/);
assert.throws(() => api.files!.writeSidecar(grant.id, ".runestone-a.json", "{}", undefined as never), /expected/);
const pending = api.files!.list(grant.id);
await session.stop();
finish!([{ name: "a.png", size: 2 }]);
await assert.rejects(pending, /disabled/);
assert.throws(() => api.files!.grants(), /disabled/);
});
test("plugin services copy data, stop with their provider, and stop for a stopped consumer", async () => {
const serviceHub = new ServiceHub();
const boards = [{ id: "b1", name: "Roadmap" }];
const provider = await start("org.test.boards", { serviceHub });
const consumer = await start("org.test.slides", { serviceHub });
const changes: string[] = [];
consumer.api.services!.subscribe((plugin, name) => changes.push(`${plugin}/${name}`));
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
const handle = provider.api.services!.provide("boards", { list: () => boards });
assert.throws(() => provider.api.services!.provide("boards", { list: () => boards }), /already/);
assert.throws(() => provider.api.services!.provide("Bad Name", { list: () => boards }), /service name/);
const service = consumer.api.services!.get("org.test.boards", "boards")!;
const result = await service.list() as typeof boards;
assert.deepEqual(result, boards);
result[0].name = "Changed";
assert.equal(boards[0].name, "Roadmap", "the consumer receives a copy");
handle.notify();
assert.deepEqual(changes, ["org.test.boards/boards", "org.test.boards/boards"]);
await provider.session.stop();
assert.deepEqual(changes.at(-1), "org.test.boards/boards");
await assert.rejects(service.list(), /no longer available/);
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
const again = await start("org.test.boards", { serviceHub });
again.api.services!.provide("boards", { list: () => boards });
const fresh = consumer.api.services!.get("org.test.boards", "boards")!;
await consumer.session.stop();
await assert.rejects(fresh.list(), /disabled/);
const count = changes.length;
await again.session.stop();
assert.equal(changes.length, count, "a stopped consumer receives no notifications");
});