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.
This commit is contained in:
Knotty Wyvern
2026-10-28 01:46:55 -07:00
parent eb2adf6a11
commit a6d6e96d6d
20 changed files with 1325 additions and 48 deletions
+102 -3
View File
@@ -3,8 +3,16 @@ import { completionHub } from "../completion/hub.ts";
import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts";
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts";
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles;
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
};
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
let timer: ReturnType<typeof setTimeout>;
@@ -27,8 +35,11 @@ export class ExternalSession {
private registry: ContributionRegistry;
private backgroundOwner = Symbol('plugin backgrounds');
private backgroundSubscriptions = new Set<() => void>();
private serviceOwner = Symbol('plugin services');
private serviceSubscriptions = new Set<() => void>();
private ptySessions = new Map<string, () => Promise<void>>();
readonly id: string;
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private services: SessionServices;
private changed: () => void;
private show: PluginApi["openView"];
private close?: PluginApi["closeView"];
@@ -37,7 +48,7 @@ export class ExternalSession {
private receiveTab?: (data: string) => void | Promise<void>;
private openDocument: (path: string) => Promise<void>;
private renameDocument?: PluginApi["renameDocument"];
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
constructor(id: string, services: SessionServices, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
this.openDocument = openDocument;
this.renameDocument = renameDocument;
this.close = close;
@@ -54,6 +65,9 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
...(this.services.pty ? { pty: this.ptyApi(this.services.pty) } : {}),
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
...(this.services.backgrounds ? { backgrounds: {
version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
@@ -180,6 +194,85 @@ export class ExternalSession {
this.check();
return request().then(value => { this.check(); return value; });
}
private ptyApi(pty: PtyTransport): PtyApi {
const size = (cols: unknown, rows: unknown) => {
if (![cols, rows].every(value => Number.isInteger(value) && (value as number) > 0 && (value as number) <= 10_000)) throw new Error("Terminal columns and rows must be positive integers.");
};
const validate = (options: PtyOpenOptions) => {
this.check();
if (!options || typeof options.onData !== "function" || (options.onExit !== undefined && typeof options.onExit !== "function")) throw new Error("A terminal session needs an onData function.");
if (typeof options.cwd !== "string") throw new Error("Supply the workspace folder as cwd.");
size(options.cols, options.rows);
};
const open = async (options: PtyOpenOptions): Promise<PtySession> => {
const id = crypto.randomUUID();
let closed = false, exited = false, closing: Promise<void> | undefined;
const exit = (code: number | null) => {
if (exited) return;
exited = true; this.ptySessions.delete(id);
if (!closed && !this.stopped) options.onExit?.(code);
};
const opening = pty.open({ id, cwd: options.cwd, cols: options.cols, rows: options.rows, ...(options.profile === undefined ? {} : { profile: options.profile }), ...(options.directory === undefined ? {} : { directory: options.directory }) },
data => { if (!closed && !this.stopped) options.onData(data); }, exit);
// Wait for the start, so that a close cannot leave a late shell running.
const close = () => closing ??= (async () => {
closed = true;
try { await opening; } catch { this.ptySessions.delete(id); return; }
this.ptySessions.delete(id);
await pty.close(id);
})();
this.ptySessions.set(id, close);
try { await opening; } catch (error) { this.ptySessions.delete(id); closed = true; throw error; }
if (this.stopped) { await close(); this.check(); }
const live = () => { this.check(); if (closed) throw new Error("This terminal is closed."); };
return {
id,
write: data => { live(); if (typeof data !== "string") throw new Error("Terminal input must be text."); return pty.write(id, data); },
resize: (cols, rows) => { live(); size(cols, rows); return pty.resize(id, cols, rows); },
close,
};
};
return {
version: 1,
profiles: () => this.backgroundRequest(() => pty.profiles()),
open: options => { validate(options); return open(options); },
openWindow: () => { this.check(); return pty.openWindow(); },
dictation: () => { this.check(); return pty.dictation(); },
};
}
private filesApi(files: FilesTransport): FilesApi {
const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); };
return {
version: 1,
chooseFolder: options => this.backgroundRequest(() => files.chooseFolder(options?.title === undefined ? undefined : { title: String(options.title) })),
pictureFolder: name => { text(name, "folder name"); return this.backgroundRequest(() => files.pictureFolder(name)); },
grants: () => this.backgroundRequest(() => files.grants()),
revoke: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.revoke(grant)); },
list: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.list(grant)); },
readBytes: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readBytes(grant, name)); },
readSidecar: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readSidecar(grant, name)); },
writeSidecar: (grant, name, contents, expected) => {
text(grant, "grant ID"); text(name, "file name");
if (typeof contents !== "string" || (expected !== null && typeof expected !== "string")) throw new Error("Supply the sidecar text and the expected text or null.");
return this.backgroundRequest(() => files.writeSidecar(grant, name, contents, expected));
},
};
}
private servicesApi(hub: ServiceHub): NonNullable<PluginApi["services"]> {
return {
version: 1,
provide: (name, methods) => { this.check(); return hub.provide(this.serviceOwner, this.id, name, methods); },
get: (plugin, name) => { this.check(); return hub.get(plugin, name, () => !this.stopped); },
subscribe: listener => {
this.check();
if (typeof listener !== "function") throw new Error("A service listener must be a function.");
const off = hub.subscribe((plugin, name) => { if (!this.stopped) listener(plugin, name); });
const cleanup = () => { off(); this.serviceSubscriptions.delete(cleanup); };
this.serviceSubscriptions.add(cleanup);
return cleanup;
},
};
}
async dropTab(data: string) {
this.check();
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
@@ -207,6 +300,8 @@ export class ExternalSession {
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
for (const off of this.backgroundSubscriptions) off();
backgroundHub.removeOwner(this.backgroundOwner);
for (const off of this.serviceSubscriptions) off();
(this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner);
for (const remove of this.contributions.splice(0)) remove();
this.stopping = (async () => {
const errors: unknown[] = [];
@@ -217,6 +312,10 @@ export class ExternalSession {
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
}
this.cleanups = [];
// Stop the terminal sessions that the plugin cleanup left open.
for (const close of [...this.ptySessions.values()]) {
try { await deadline(close()); } catch (error) { errors.push(error); }
}
if (errors.length) throw new Error(errors.map(String).join("\n"));
})();
return this.stopping;
+37
View File
@@ -0,0 +1,37 @@
import { Channel, invoke } from "@tauri-apps/api/core";
import type { FilesTransport, FolderEntry, FolderGrant, PtyProfile, PtyTransport } from "./sdk.ts";
/**
* Terminal sessions over a channel to this webview. The output arrives as raw bytes, and no
* `pty-data` or `pty-exit` event goes to other windows. The released Terminal plugin uses the
* events instead, and the host keeps them for sessions without a channel.
*/
export const ptyTransport: PtyTransport = {
open: (request, onData, onExit) => {
const channel = new Channel<ArrayBuffer | { exit: number | null }>(message => {
if (message instanceof ArrayBuffer) onData(new Uint8Array(message));
else if (message && typeof message === "object" && "exit" in message) onExit(message.exit);
});
return invoke<void>("pty_open", { ...request, channel });
},
write: (id, data) => invoke<void>("pty_write", { id, data }),
resize: (id, cols, rows) => invoke<void>("pty_resize", { id, cols, rows }),
close: id => invoke<void>("pty_close", { id }),
profiles: () => invoke<PtyProfile[]>("pty_profiles"),
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
dictation: () => invoke<void>("pty_dictation"),
};
/** Folder grants of one plugin. The plugin ID comes from the host, not from the plugin. */
export function filesTransport(plugin: string): FilesTransport {
return {
chooseFolder: options => invoke<FolderGrant | null>("folders_choose", { plugin, title: options?.title ?? null }),
pictureFolder: name => invoke<FolderGrant>("folders_picture", { plugin, name }),
grants: () => invoke<FolderGrant[]>("folders_grants", { plugin }),
revoke: grant => invoke<boolean>("folders_revoke", { plugin, grant }),
list: grant => invoke<FolderEntry[]>("folders_list", { plugin, grant }),
readBytes: async (grant, name) => new Uint8Array(await invoke<ArrayBuffer>("folders_read", { plugin, grant, name })),
readSidecar: (grant, name) => invoke<string | null>("folders_read_sidecar", { plugin, grant, name }),
writeSidecar: (grant, name, contents, expected) => invoke<void>("folders_write_sidecar", { plugin, grant, name, contents, expected }),
};
}
+65
View File
@@ -19,7 +19,72 @@ export interface PluginDocumentType {
create?: { label: string; defaultName: string; extension: string; contents(): string };
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PtyProfile { id: string; title: string; kind: string }
export interface PtyOpenOptions {
/** The workspace root of the window. The host rejects the request when the workspace changed. */
cwd: string;
cols: number;
rows: number;
profile?: string;
/** A start folder other than the workspace root. */
directory?: string;
/** Receives raw terminal output. UTF-8 characters can be split between two calls. */
onData(data: Uint8Array): void;
onExit?(code: number | null): void;
}
export interface PtySession {
readonly id: string;
write(data: string): Promise<void>;
resize(cols: number, rows: number): Promise<void>;
/** Stops the shell. Repeated calls return the same promise. */
close(): Promise<void>;
}
/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */
export interface PtyApi {
readonly version: 1;
profiles(): Promise<PtyProfile[]>;
open(options: PtyOpenOptions): Promise<PtySession>;
openWindow(): Promise<void>;
dictation(): Promise<void>;
}
/** The native side of `PtyApi`. `onData` and `onExit` receive the output of this session only. */
export interface PtyTransport {
open(request: { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise<void>;
write(id: string, data: string): Promise<void>;
resize(id: string, cols: number, rows: number): Promise<void>;
close(id: string): Promise<void>;
profiles(): Promise<PtyProfile[]>;
openWindow(): Promise<void>;
dictation(): Promise<void>;
}
export interface FolderGrant { id: string; path: string; name: string }
export interface FolderEntry { name: string; size: number }
/** Folders outside the workspace that the user granted to this plugin. */
export interface FilesApi {
readonly version: 1;
chooseFolder(options?: { title?: string }): Promise<FolderGrant | null>;
pictureFolder(name: string): Promise<FolderGrant>;
grants(): Promise<FolderGrant[]>;
revoke(grant: string): Promise<boolean>;
list(grant: string): Promise<FolderEntry[]>;
readBytes(grant: string, name: string): Promise<Uint8Array>;
readSidecar(grant: string, name: string): Promise<string | null>;
writeSidecar(grant: string, name: string, contents: string, expected: string | null): Promise<void>;
}
/** The native side of `FilesApi`, bound to one plugin ID by the host. */
export type FilesTransport = Omit<FilesApi, "version">;
export type ServiceMethods = Record<string, (...args: never[]) => unknown>;
/** Data that one plugin offers to other plugins in the same window. */
export interface ServicesApi {
readonly version: 1;
provide(name: string, methods: ServiceMethods): { notify(): void; dispose(): void };
get(plugin: string, name: string): Record<string, (...args: unknown[]) => Promise<unknown>> | null;
subscribe(listener: (plugin: string, name: string) => void): Dispose;
}
export interface PluginApi {
pty?: PtyApi;
files?: FilesApi;
services?: ServicesApi;
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi;
+76
View File
@@ -0,0 +1,76 @@
import type { ServiceMethods } from "./sdk.ts";
const namePattern = /^[a-z][a-z0-9.-]{0,63}$/;
/**
* Plugin services in one window. A provider plugin offers named methods, and other plugins call
* them through the host. Arguments and results are copied with `structuredClone`, so a later
* message-based SDK can keep the same contract. Calls always return promises.
*/
export class ServiceHub {
private services = new Map<string, { owner: symbol; methods: ServiceMethods }>();
private listeners = new Set<(plugin: string, name: string) => void>();
provide(owner: symbol, plugin: string, name: string, methods: ServiceMethods): { notify(): void; dispose(): void } {
if (!namePattern.test(name)) throw new Error("A service name uses lowercase letters, digits, dots, and hyphens, and starts with a letter.");
if (!methods || typeof methods !== "object" || !Object.keys(methods).length || Object.values(methods).some(method => typeof method !== "function")) {
throw new Error("A service needs an object of functions.");
}
const key = plugin + "/" + name;
if (this.services.has(key)) throw new Error("This plugin already provides the service.");
const entry = { owner, methods: { ...methods } };
this.services.set(key, entry);
this.changed(plugin, name);
let active = true;
return {
notify: () => { if (active) this.changed(plugin, name); },
dispose: () => {
if (!active) return;
active = false;
if (this.services.get(key) === entry) { this.services.delete(key); this.changed(plugin, name); }
},
};
}
/** Return callable copies of the methods, or `null` when the service is not available. */
get(plugin: string, name: string, alive: () => boolean): Record<string, (...args: unknown[]) => Promise<unknown>> | null {
const key = plugin + "/" + name;
const entry = this.services.get(key);
if (!entry) return null;
const result: Record<string, (...args: unknown[]) => Promise<unknown>> = {};
for (const method of Object.keys(entry.methods)) {
result[method] = async (...args: unknown[]) => {
const current = this.services.get(key);
if (!alive()) throw new Error("This plugin is disabled.");
if (current !== entry) throw new Error("The service is no longer available.");
const value = await (entry.methods[method] as (...values: unknown[]) => unknown)(...structuredClone(args));
if (!alive()) throw new Error("This plugin is disabled.");
if (this.services.get(key) !== entry) throw new Error("The service is no longer available.");
return structuredClone(value);
};
}
return result;
}
subscribe(listener: (plugin: string, name: string) => void): () => void {
this.listeners.add(listener);
return () => { this.listeners.delete(listener); };
}
removeOwner(owner: symbol) {
for (const [key, entry] of [...this.services]) {
if (entry.owner !== owner) continue;
this.services.delete(key);
const [plugin, name] = key.split("/");
this.changed(plugin, name);
}
}
private changed(plugin: string, name: string) {
for (const listener of [...this.listeners]) {
try { listener(plugin, name); } catch { /* One subscriber must not stop the others. */ }
}
}
}
export const serviceHub = new ServiceHub();