feat(skin): connect v4 runtime prototype to WebClient

This commit is contained in:
illusia committed 2026-10-10 15:53:50 +08:00
1 parent 7993b38eee
commit 7650bd650b
14 files changed
+683 -49

No files matched your search

+20 -10
View File
@@ -7,6 +7,7 @@ import {
parseSkinPluginDocument,
type SkinPluginActionDefinition,
type SkinPluginComponent,
type SkinPluginComponentMode,
type SkinPluginDocument,
type SkinPluginHostWidget,
type SkinPluginNode,
@@ -32,7 +33,10 @@ export default defineComponent({
skinId: { type: String, required: true },
skinVersion: { type: String, required: true },
document: { type: Object as PropType<SkinPluginDocument>, required: true },
extensionOutput: { type: String, default: null },
extensionOutput: { type: String as PropType<string | null>, default: null },
extensionMode: { type: String as PropType<SkinPluginComponentMode | undefined>, default: undefined },
componentNamespace: { type: String, default: "" },
manageSurfaceRecovery: { type: Boolean, default: true },
page: { type: String as PropType<"home" | "voice" | "demo">, required: true },
data: { type: Object as PropType<SafeContext>, required: true },
assets: { type: Object as PropType<Record<string, Blob>>, required: true },
@@ -57,7 +61,10 @@ export default defineComponent({
catch { return { schemaVersion: 2 as const, components: [] }; }
if (!props.extensionOutput || document.schemaVersion !== 3) return document;
try {
const extensionDocument = parseSkinExtensionUiOutput(props.extensionOutput);
const parsedExtensionDocument = parseSkinExtensionUiOutput(props.extensionOutput);
const extensionDocument = props.extensionMode
? { ...parsedExtensionDocument, components: parsedExtensionDocument.components.map((component) => ({ ...component, mode: props.extensionMode })) }
: parsedExtensionDocument;
const ids = new Set(document.components.map((component) => component.id));
if (document.components.length + extensionDocument.components.length > SKIN_PLUGIN_COMPONENT_LIMIT
|| extensionDocument.components.some((component) => ids.has(component.id))) return document;
@@ -84,7 +91,7 @@ export default defineComponent({
const renderedComponents = computed(() => activeComponents.value.filter((component) =>
component.mode !== "surface" || component !== surfaceCandidate.value || !surfaceSuppressed.value));
watch(() => [props.skinId, props.skinVersion, props.document, props.extensionOutput, props.page], () => {
watch(() => [props.skinId, props.skinVersion, props.document, props.extensionOutput, props.extensionMode, props.componentNamespace, props.page], () => {
denied.value = false;
surfaceSuppressed.value = false;
refresh.value += 1;
@@ -185,7 +192,8 @@ export default defineComponent({
|| ["click", "dblclick", "contextmenu", "keydown", "keyup", "pointerdown", "pointerup", "drop"]
.some((eventName) => Boolean(node.events?.[eventName as keyof typeof node.events]));
const part = node.part ? `part-${node.part}` : nodePath;
return `skin.${component.page}.${component.id}.${interactive ? "control-" : ""}${part}`;
const componentPath = props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id;
return `skin.${component.page}.${componentPath}.${interactive ? "control-" : ""}${part}`;
}
function renderNode(component: SkinPluginComponent, node: SkinPluginNode, context: SafeContext, state: Record<string, Scalar>, budget: { remaining: number }, skipRepeat = false, nodePath = "node-root"): VNodeChild {
@@ -235,7 +243,8 @@ export default defineComponent({
if (node.className || attrs.class) {
attrs.class = ["ws-plugin-node", node.className, attrs.class].filter(Boolean).join(" ");
} else attrs.class = "ws-plugin-node";
attrs["data-ws-plugin-part"] = node.part ? `${component.id}.${node.part}` : component.id;
const componentPath = props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id;
attrs["data-ws-plugin-part"] = node.part ? `${componentPath}.${node.part}` : componentPath;
attrs["data-ws-part"] = layoutPart(component, node, nodePath);
if (node.bindValue) attrs.value = state[node.bindValue];
@@ -305,10 +314,11 @@ export default defineComponent({
const nodes: VNodeChild[] = renderedComponents.value.map((component) => h("div", {
key: `${props.skinId}:${component.id}`,
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
"data-ws-plugin-component": component.id,
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
"data-ws-plugin-name": component.name,
"data-ws-plugin-part": component.id,
"data-ws-part": `skin.${component.page}.${component.id}`,
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
"data-ws-part": `skin.${component.page}.${props.componentNamespace ? `${props.componentNamespace}.` : ""}${component.id}`,
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
"aria-label": component.accessibleName,
}, [renderNode(component, component.root, props.data, localState(component), { remaining: SKIN_PLUGIN_RENDER_NODE_LIMIT })]));
@@ -320,13 +330,13 @@ export default defineComponent({
"aria-label": "管理皮肤组件权限 / Manage skin component access",
onClick: openAccessManager,
}, "权限 / Access")]) : null;
const surfaceRecovery = activeSurface.value ? h(Teleport, { to: "body" }, [h("button", {
const surfaceRecovery = activeSurface.value && props.manageSurfaceRecovery ? h(Teleport, { to: "body" }, [h("button", {
type: "button",
class: "ws-plugin-surface-recovery",
"aria-label": "返回 WebSpeak 标准界面 / Return to the built-in interface",
onClick: () => { surfaceSuppressed.value = true; },
}, "标准界面 / Built-in UI")]) : null;
const skinRecovery = activeSurface.value ? h(Teleport, { to: "body" }, [h("button", {
const skinRecovery = activeSurface.value && props.manageSurfaceRecovery ? h(Teleport, { to: "body" }, [h("button", {
type: "button",
class: "ws-plugin-surface-reset",
"aria-label": "恢复内置皮肤 / Restore the built-in skin",
+384
View File
@@ -0,0 +1,384 @@
import { computed, defineComponent, h, onUnmounted, ref, Teleport, watch, type PropType, type VNodeChild } from "vue";
import type { SkinExtensionSessionStatus } from "../../../src/shared/skin-extension.js";
import { computeSkinRuntimePluginDigest, createSkinRuntimePluginApproval, isSkinRuntimePluginApproved, type SkinRuntimePluginApproval } from "../../../src/shared/skin-runtime-plugin-approval.js";
import type { SkinRuntimePlugin, SkinRuntimePluginDocument, SkinRuntimePluginPage } from "../../../src/shared/skin-runtime-plugins.js";
import { parseSkinExtensionUiInput, type SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import SkinPluginOutlet from "./SkinPluginOutlet.js";
import { approveSkinRuntimePlugin, getSkinRuntimePluginApproval, revokeSkinRuntimePluginApprovals } from "../services/skin-runtime-plugin-approval.js";
import { createSkinRuntimePluginSession } from "../services/skin-runtime-plugin-session.js";
import { createSkinRuntimePluginWasmSandboxPrototype } from "../services/skin-runtime-plugin-wasm.js";
import type { SkinExtensionWasmSandboxHandle } from "../services/skin-extension-wasm-sandbox.js";
import { resolveSkinCssAssets } from "../services/skin-pack.js";
const EMPTY_DOCUMENT: SkinPluginDocument = { schemaVersion: 3, components: [] };
const SUPPORTED_PERMISSIONS = new Set(["session.status.read", "ui.surface.replace"]);
type Session = ReturnType<typeof createSkinRuntimePluginSession>;
type RunHandle = { result: Promise<{ uiOutput: string | null }>; close(reason?: string): void };
function isSupported(plugin: SkinRuntimePlugin): boolean {
return import.meta.env.DEV && plugin.runtime === "wasm"
&& plugin.permissions.every((permission) => SUPPORTED_PERMISSIONS.has(permission));
}
function pluginReason(plugin: SkinRuntimePlugin): string {
if (!import.meta.env.DEV) return "The Wasm runtime prototype is disabled in production builds. / Wasm 运行时原型在生产构建中保持关闭。";
if (plugin.runtime !== "wasm") return "JavaScript plugins are not enabled. / JavaScript 插件尚未启用。";
const permission = plugin.permissions.find((candidate) => !SUPPORTED_PERMISSIONS.has(candidate));
return permission
? `This prototype does not implement ${permission}. / 当前原型尚未实现 ${permission}。`
: "";
}
function createRun(
skinId: string,
skinVersion: string,
plugin: SkinRuntimePlugin,
approval: SkinRuntimePluginApproval,
files: Readonly<Record<string, Blob>>,
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>,
input: SkinExtensionUiInput,
): RunHandle {
let sandbox: SkinExtensionWasmSandboxHandle | null = null;
let cancelled = false;
const result = (async () => {
const nextSandbox = await createSkinRuntimePluginWasmSandboxPrototype({
skinId,
skinVersion,
plugin,
approval,
files,
uiInput: input,
readSessionStatus,
prototypeOnly: true,
});
if (cancelled) {
nextSandbox.close("page-or-skin-changed");
throw new Error("Plugin run was closed before startup.");
}
sandbox = nextSandbox;
await nextSandbox.ready;
const outcome = await nextSandbox.result;
return { uiOutput: outcome.uiOutput };
})();
return {
result,
close(reason) {
cancelled = true;
sandbox?.close(reason);
},
};
}
export default defineComponent({
name: "SkinRuntimePluginHost",
props: {
skinId: { type: String, required: true },
skinVersion: { type: String, required: true },
plugins: { type: Object as PropType<SkinRuntimePluginDocument | undefined>, default: undefined },
files: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
styles: { type: Object as PropType<Record<string, string>>, default: () => ({}) },
assets: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
page: { type: String as PropType<SkinRuntimePluginPage>, required: true },
readSessionStatus: { type: Function as PropType<(signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>>, required: true },
},
emits: {
"surface-change": (_active: boolean) => typeof _active === "boolean",
"restore-skin": () => true,
},
setup(props, { emit }) {
const digests = ref<Record<string, string>>({});
const digestErrors = ref<Record<string, string>>({});
const revision = ref(0);
const managerOpen = ref(false);
const denied = ref(new Set<string>());
const inMemoryApprovals = new Map<string, SkinRuntimePluginApproval>();
const sessions = new Map<string, Session>();
const stylesByPlugin = new Map<string, { element: HTMLStyleElement; objectUrls: string[] }>();
const outputs = ref<Record<string, string | null>>({});
const surfaces = ref(new Set<string>());
const suppressedSurfaces = ref(new Set<string>());
let digestRun = 0;
let disposed = false;
const pagePlugins = computed(() => props.plugins?.plugins.filter((plugin) => plugin.page === props.page) ?? []);
const approved = (plugin: SkinRuntimePlugin): SkinRuntimePluginApproval | null => {
const digest = digests.value[plugin.id];
if (!digest) return null;
const memoryGrant = inMemoryApprovals.get(plugin.id);
if (memoryGrant && isSkinRuntimePluginApproved(memoryGrant, props.skinId, props.skinVersion, plugin, digest)) return memoryGrant;
return getSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest);
};
const pending = computed(() => {
revision.value;
return pagePlugins.value.filter((plugin) => isSupported(plugin) && !approved(plugin) && !denied.value.has(plugin.id));
});
const activeSurface = computed(() => pagePlugins.value.some((plugin) => plugin.mode === "surface"
&& surfaces.value.has(plugin.id) && !suppressedSurfaces.value.has(plugin.id)));
function publishSurfaceState(): void {
emit("surface-change", activeSurface.value);
}
function removeStyle(pluginId: string): void {
const style = stylesByPlugin.get(pluginId);
if (!style) return;
style.element.remove();
style.objectUrls.forEach((url) => URL.revokeObjectURL(url));
stylesByPlugin.delete(pluginId);
}
function stopPlugin(pluginId: string, reason: string): void {
sessions.get(pluginId)?.close(reason);
sessions.delete(pluginId);
outputs.value = { ...outputs.value, [pluginId]: null };
surfaces.value.delete(pluginId);
suppressedSurfaces.value.delete(pluginId);
removeStyle(pluginId);
publishSurfaceState();
}
function stopAll(reason: string): void {
for (const pluginId of [...sessions.keys()]) stopPlugin(pluginId, reason);
for (const pluginId of [...stylesByPlugin.keys()]) removeStyle(pluginId);
outputs.value = {};
surfaces.value = new Set();
suppressedSurfaces.value = new Set();
publishSurfaceState();
}
function pluginStyleAssets(plugin: SkinRuntimePlugin): Record<string, Blob> {
const ownPrefix = `plugins/${plugin.id}/assets/`;
return Object.fromEntries(Object.entries(props.assets).filter(([path]) => path.startsWith("assets/") || path.startsWith(ownPrefix)));
}
function installStyle(plugin: SkinRuntimePlugin): void {
removeStyle(plugin.id);
const css = props.styles[plugin.id];
if (!css) return;
const resolved = resolveSkinCssAssets(css, pluginStyleAssets(plugin));
const element = document.createElement("style");
element.dataset.wsRuntimePluginStyle = plugin.id;
element.textContent = resolved.css;
document.head.append(element);
stylesByPlugin.set(plugin.id, { element, objectUrls: resolved.objectUrls });
}
function outputAssets(plugin: SkinRuntimePlugin): Record<string, Blob> {
const result: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
const prefix = `plugins/${plugin.id}/assets/`;
for (const path of plugin.assets) {
const relative = path.slice(prefix.length);
const blob = props.assets[path];
if (blob) result[`assets/${relative}`] = blob;
}
return result;
}
function onRuntimeError(pluginId: string): void {
if (disposed) return;
stopPlugin(pluginId, "runtime-error");
digestErrors.value = { ...digestErrors.value, [pluginId]: "The plugin stopped safely. / 插件已安全停止。" };
}
function startPlugin(plugin: SkinRuntimePlugin, grant: SkinRuntimePluginApproval): void {
if (sessions.has(plugin.id) || !isSupported(plugin)) return;
const session = createSkinRuntimePluginSession({
plugin,
createRun: (input) => createRun(props.skinId, props.skinVersion, plugin, grant, props.files, props.readSessionStatus, input),
onOutput: () => {
installStyle(plugin);
outputs.value = { ...outputs.value, [plugin.id]: session.output };
digestErrors.value = { ...digestErrors.value, [plugin.id]: "" };
},
onError: () => onRuntimeError(plugin.id),
});
sessions.set(plugin.id, session);
void session.start().then((started) => {
if (!started && sessions.get(plugin.id) === session) onRuntimeError(plugin.id);
}).catch(() => onRuntimeError(plugin.id));
}
function reconcile(): void {
if (disposed) return;
const currentIds = new Set(pagePlugins.value.map((plugin) => plugin.id));
for (const pluginId of [...sessions.keys()]) if (!currentIds.has(pluginId)) stopPlugin(pluginId, "page-changed");
for (const plugin of pagePlugins.value) {
const grant = approved(plugin);
if (grant && isSupported(plugin)) startPlugin(plugin, grant);
}
}
function approvePending(): void {
for (const plugin of pending.value) {
const digest = digests.value[plugin.id];
if (!digest) continue;
approveSkinRuntimePlugin(props.skinId, props.skinVersion, plugin, digest);
const stored = getSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest);
inMemoryApprovals.set(plugin.id, stored ?? createSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest));
}
denied.value = new Set([...denied.value].filter((id) => !pending.value.some((plugin) => plugin.id === id)));
managerOpen.value = false;
revision.value += 1;
reconcile();
}
function keepDisabled(): void {
denied.value = new Set([...denied.value, ...pending.value.map((plugin) => plugin.id)]);
managerOpen.value = false;
}
function revokeAll(): void {
revokeSkinRuntimePluginApprovals(props.skinId);
for (const plugin of props.plugins?.plugins ?? []) inMemoryApprovals.delete(plugin.id);
denied.value = new Set((props.plugins?.plugins ?? []).filter(isSupported).map((plugin) => plugin.id));
stopAll("approval-revoked");
managerOpen.value = false;
revision.value += 1;
}
function openManager(): void {
managerOpen.value = true;
}
function dispatch(pluginId: string, value: unknown): void {
if (!value || typeof value !== "object") return;
const input = (value as Record<string, unknown>).input;
const session = sessions.get(pluginId);
if (session && input) void session.dispatch(input);
}
function surfaceChanged(pluginId: string, active: boolean): void {
if (active) surfaces.value.add(pluginId);
else surfaces.value.delete(pluginId);
publishSurfaceState();
}
function toggleSurface(pluginId: string): void {
const next = new Set(suppressedSurfaces.value);
if (next.has(pluginId)) next.delete(pluginId);
else next.add(pluginId);
suppressedSurfaces.value = next;
publishSurfaceState();
}
watch(() => [props.skinId, props.skinVersion, props.plugins, props.files], async () => {
const currentRun = ++digestRun;
stopAll("skin-changed");
inMemoryApprovals.clear();
denied.value = new Set();
managerOpen.value = false;
digests.value = {};
digestErrors.value = {};
const plugins = props.plugins?.plugins ?? [];
const nextDigests: Record<string, string> = Object.create(null) as Record<string, string>;
const nextErrors: Record<string, string> = Object.create(null) as Record<string, string>;
await Promise.all(plugins.map(async (plugin) => {
try { nextDigests[plugin.id] = await computeSkinRuntimePluginDigest(plugin, props.files); }
catch { nextErrors[plugin.id] = "The package files could not be verified. / 无法校验插件文件。"; }
}));
if (disposed || currentRun !== digestRun) return;
digests.value = nextDigests;
digestErrors.value = nextErrors;
revision.value += 1;
reconcile();
}, { immediate: true });
watch(() => [props.page, digests.value, revision.value], reconcile, { deep: true });
watch(activeSurface, publishSurfaceState, { flush: "sync" });
onUnmounted(() => {
disposed = true;
digestRun += 1;
stopAll("host-unmounted");
});
return () => {
const currentPlugins = pagePlugins.value;
const nodes: VNodeChild[] = [];
for (const plugin of currentPlugins) {
const generatedOutput = suppressedSurfaces.value.has(plugin.id) ? null : outputs.value[plugin.id] ?? null;
const pluginAssets = outputAssets(plugin);
nodes.push(h(SkinPluginOutlet, {
key: `${props.skinId}:${plugin.id}:${props.page}`,
skinId: props.skinId,
skinVersion: props.skinVersion,
document: EMPTY_DOCUMENT,
extensionOutput: generatedOutput,
extensionMode: plugin.mode,
componentNamespace: plugin.id,
manageSurfaceRecovery: false,
page: props.page,
data: {},
assets: pluginAssets,
actions: {},
onExtensionEvent: (event: unknown) => dispatch(plugin.id, event),
onSurfaceChange: (active: boolean) => surfaceChanged(plugin.id, active),
onRestoreSkin: () => emit("restore-skin"),
}));
}
const controls: VNodeChild[] = [];
if (currentPlugins.length) {
controls.push(h(Teleport, { to: "body" }, [h("button", {
type: "button",
class: "ws-plugin-access-toggle",
"aria-label": "管理运行时插件权限 / Manage runtime plugin access",
onClick: openManager,
}, "插件权限 / Plugin access")]));
}
for (const plugin of currentPlugins) {
if (plugin.mode !== "surface" || !outputs.value[plugin.id]) continue;
const suppressed = suppressedSurfaces.value.has(plugin.id);
controls.push(h(Teleport, { to: "body" }, [h("button", {
type: "button",
class: "ws-plugin-surface-recovery",
"aria-label": suppressed ? "恢复自定义界面 / Restore custom interface" : "返回 WebSpeak 标准界面 / Return to built-in interface",
onClick: () => toggleSurface(plugin.id),
}, suppressed ? "恢复自定义界面 / Restore custom UI" : "标准界面 / Built-in UI")]));
controls.push(h(Teleport, { to: "body" }, [h("button", {
type: "button",
class: "ws-plugin-surface-reset",
"aria-label": "恢复内置皮肤 / Restore the built-in skin",
onClick: () => emit("restore-skin"),
}, "恢复内置皮肤 / Reset skin")]));
}
const showConsent = pending.value.length > 0 || managerOpen.value;
if (!showConsent) return h("div", { class: "ws-runtime-plugin-host" }, [...nodes, ...controls]);
const showApproval = pending.value.length > 0;
const listed = showApproval ? pending.value : currentPlugins;
const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-runtime-plugin-consent": "true" }, [
h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-runtime-plugin-consent-title" }, [
h("h2", { id: "ws-runtime-plugin-consent-title" }, showApproval ? "运行时插件授权 / Runtime plugin approval" : "运行时插件权限 / Runtime plugin access"),
h("p", null, "插件只在隔离的 Wasm Worker 中运行。每次执行均有时限和内存上限;插件不能访问网络、存储、连接地址、密码或身份材料。/ Plugins run in a bounded Wasm worker and cannot access network, storage, connection targets, passwords, or identity material."),
...listed.map((plugin) => {
const grant = approved(plugin);
const error = digestErrors.value[plugin.id];
const unsupported = pluginReason(plugin);
const status = error || unsupported || (grant ? "已授权 / Approved" : "等待授权 / Approval required");
return h("div", { class: "ws-plugin-consent-item", key: plugin.id }, [
h("strong", null, `${plugin.name} · ${plugin.mode === "surface" ? "整页界面 / surface" : "组件 / widget"}`),
h("ul", null, [
...plugin.permissions.map((permission) => h("li", { key: permission }, permission)),
h("li", { key: "status" }, status),
]),
]);
}),
h("p", { class: "ws-plugin-consent-note" }, "当前开发原型仅支持 Wasm、session.status.read 和 ui.surface.replace;授权绑定到此皮肤版本、插件清单和所有插件文件的 SHA-256。/ This development prototype supports Wasm, session.status.read, and ui.surface.replace only. Approval is bound to this skin version, descriptor, and every plugin file by SHA-256."),
h("div", { class: "ws-plugin-consent-actions" }, showApproval
? [
h("button", { type: "button", class: "secondary", onClick: keepDisabled }, "暂不启用 / Keep disabled"),
h("button", { type: "button", class: "primary", disabled: listed.some((plugin) => !digests.value[plugin.id] || Boolean(digestErrors.value[plugin.id])) || listed.some((plugin) => !isSupported(plugin)), onClick: approvePending }, "批准所列插件 / Approve listed plugins"),
]
: [
h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access"),
h("button", { type: "button", class: "primary", onClick: () => { managerOpen.value = false; } }, "关闭 / Close"),
]),
]),
])]);
return h("div", { class: "ws-runtime-plugin-host" }, [...nodes, ...controls, consent]);
};
},
});
+46 -1
View File
@@ -385,7 +385,9 @@ test("schema version 4 validates and caches isolated plugin package files withou
assert.equal(await skin.runtimePluginFiles?.[entry].text(), "export const render = () => document.createElement('button');");
assert.equal(await skin.runtimePluginFiles?.[style].text(), ".toolbar { color: teal; }");
assert.equal(skin.runtimePluginFiles?.[icon].type, "image/png");
assert.equal(skin.assets[icon], undefined, "plugin assets stay in the isolated plugin file set");
assert.equal(skin.assets[icon]?.type, "image/png", "declared plugin media is available only by its package path for scoped CSS and host remapping");
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /data-ws-runtime-plugin="voice-toolbar".*?\.toolbar/s);
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /color: teal/);
assert.match(skin.css, /position: fixed/);
await assert.rejects(
@@ -402,6 +404,49 @@ test("schema version 4 validates and caches isolated plugin package files withou
);
});
test("a v4 surface cannot compete with a v3 surface on the same public page", async () => {
const components = {
schemaVersion: 2,
components: [{
id: "voice-v3-surface",
name: "Voice v3 surface",
page: "voice",
mode: "surface",
accessibleName: "Voice workspace",
permissions: ["ui.surface.replace"],
actions: {},
root: { tag: "main", children: [{ tag: "p", children: [{ text: "replacement UI" }] }] },
}],
};
const plugins = {
schemaVersion: 1,
plugins: [{
id: "voice-v4-surface",
name: "Voice v4 surface",
version: "1.0.0",
apiVersion: 1,
runtime: "wasm",
page: "voice",
mode: "surface",
entry: "plugins/voice-v4-surface/index.wasm",
assets: [],
permissions: ["ui.surface.replace"],
}],
};
const files = {
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", components: "components.json", plugins: "plugins.json" })),
"skin.css": strToU8('[data-ws-part="app"] { color: teal; }'),
"components.json": strToU8(JSON.stringify(components)),
"plugins.json": strToU8(JSON.stringify(plugins)),
"plugins/voice-v4-surface/index.wasm": createSkinExtensionWasmPrefixByteImmediateProbe(),
};
const archive = zipSync(files);
await assert.rejects(
importSkinPack(new File([archive.slice().buffer as ArrayBuffer], "competing-surfaces.wskin")),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_SURFACE_DUPLICATE",
);
});
test("the distributable KAAK v3 package validates end to end", async () => {
const archive = await readFile(new URL("../../../docs/examples/kaak-voice.wskin", import.meta.url));
const file = new File([archive], "kaak-voice.wskin", { type: "application/octet-stream" });
+47 -8
View File
@@ -109,6 +109,7 @@ export interface InstalledSkin extends SkinManifest {
pluginData?: SkinPluginDocument;
runtimePlugins?: SkinRuntimePluginDocument;
runtimePluginFiles?: Record<string, Blob>;
runtimePluginStyles?: Record<string, string>;
previewBlob?: Blob;
warnings: string[];
installedAt: number;
@@ -177,6 +178,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
}
const runtimePluginFiles: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
const runtimePluginPathSet = new Set(runtimePluginPaths.map((path) => path.toLowerCase()));
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
@@ -213,10 +215,10 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Plugin fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
if (mimeType.startsWith("image/") && bytes.byteLength > MAX_IMAGE_BYTES) throw new SkinPackError("Plugin images must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
runtimePluginFiles[pluginPath] = new Blob([bytes], { type: mimeType });
assets[pluginPath] = runtimePluginFiles[pluginPath];
}
}
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
for (const [path, bytes] of files) {
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins].includes(path)
|| runtimePluginPathSet.has(path.toLowerCase())) continue;
@@ -227,6 +229,20 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
assets[path] = new Blob([bytes], { type: mimeType });
}
const runtimePluginStyles: Record<string, string> = Object.create(null) as Record<string, string>;
const runtimePluginWarnings: string[] = [];
for (const plugin of runtimePlugins?.plugins ?? []) {
if (!plugin.style) continue;
const style = runtimePluginFiles[plugin.style];
if (!style) throw new SkinPackError(`A declared plugin style is missing: ${plugin.style}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING");
const pluginAssetPrefix = `plugins/${plugin.id}/assets/`;
const pluginAssets = Object.fromEntries(Object.entries(assets).filter(([path]) =>
path.startsWith("assets/") || path.startsWith(pluginAssetPrefix)));
const compiledStyle = compileSkinCss(await style.text(), manifest.id, pluginAssets, manifest.schemaVersion, plugin.id);
runtimePluginStyles[plugin.id] = compiledStyle.css;
runtimePluginWarnings.push(...compiledStyle.warnings);
}
let contentData: SkinContent | undefined;
if (manifest.content) {
const contentBytes = files.get(manifest.content);
@@ -264,7 +280,24 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
}
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets, manifest.schemaVersion);
return { ...manifest, css: compiled.css, assets, contentData, layoutData, pluginData, runtimePlugins, runtimePluginFiles, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
const hasConflictingSurface = (pluginData?.components ?? []).some((component) => component.mode === "surface"
&& runtimePlugins?.plugins.some((plugin) => plugin.mode === "surface" && plugin.page === component.page));
if (hasConflictingSurface) throw new SkinPackError("A page cannot declare both a v3 and v4 surface.", "SKIN_PLUGIN_SURFACE_DUPLICATE");
return {
...manifest,
css: compiled.css,
assets,
contentData,
layoutData,
pluginData,
runtimePlugins,
runtimePluginFiles,
runtimePluginStyles,
previewBlob,
warnings: [...compiled.warnings, ...runtimePluginWarnings],
installedAt: Date.now(),
};
}
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
@@ -527,15 +560,18 @@ function parseContent(bytes: Uint8Array): SkinContent {
return { defaultLocale: root.defaultLocale, locales };
}
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"]): { css: string; warnings: string[] } {
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"], pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
let root: postcss.Root;
try { root = postcss.parse(source, { from: undefined }); }
catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
const scope = `.ws-skin-root[data-ws-skin="${id}"]`;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}`;
const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`;
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
const keyframeNames = new Map<string, string>();
@@ -575,7 +611,7 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
if (!selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.");
if (!pluginId && !selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.");
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
try {
rule.selector = selectorParser((selectors) => {
@@ -629,8 +665,11 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)) {
throw declaration.error("Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.`
: "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseSkinRuntimePluginDocument } from "../../../src/shared/skin-runtime-plugins.js";
import { createSkinRuntimePluginSession, SkinRuntimePluginSessionError } from "./skin-runtime-plugin-session.js";
const plugin = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{
id: "voice-surface",
name: "Voice surface",
version: "1.0.0",
apiVersion: 1,
runtime: "wasm",
page: "voice",
mode: "surface",
entry: "plugins/voice-surface/index.wasm",
assets: [],
permissions: ["ui.surface.replace"],
}],
}).plugins[0];
function output(page = "voice", count = 1): string {
return JSON.stringify({
schemaVersion: 5,
components: Array.from({ length: count }, (_, index) => ({
id: `surface-${index}`,
name: "Voice surface",
page,
accessibleName: "Voice workspace",
state: {},
root: { tag: "main", children: [{ text: "custom voice UI" }] },
})),
});
}
function sessionWithOutput(value: string, onError: (error: Error) => void = () => undefined) {
return createSkinRuntimePluginSession({
plugin,
createRun: () => ({ result: Promise.resolve({ uiOutput: value }), close: () => undefined }),
onError,
});
}
test("runtime plugin session accepts one generated root for its declared surface", async () => {
const session = sessionWithOutput(output());
assert.equal(await session.start(), true);
assert.equal(session.output, output());
assert.equal(session.closed, false);
session.close();
assert.equal(session.closed, true);
});
test("runtime plugin session rejects output targeting a different page", async () => {
const errors: Error[] = [];
const session = sessionWithOutput(output("home"), (error) => errors.push(error));
assert.equal(await session.start(), false);
assert.equal(errors[0] instanceof SkinRuntimePluginSessionError, true);
assert.equal((errors[0] as SkinRuntimePluginSessionError).code, "SKIN_RUNTIME_PLUGIN_PAGE_MISMATCH");
assert.equal(session.output, null);
});
test("runtime surface plugins cannot emit competing roots", async () => {
const errors: Error[] = [];
const session = sessionWithOutput(output("voice", 2), (error) => errors.push(error));
assert.equal(await session.start(), false);
assert.ok(errors[0] instanceof SkinRuntimePluginSessionError);
assert.equal((errors[0] as SkinRuntimePluginSessionError).code, "SKIN_RUNTIME_PLUGIN_SURFACE_OUTPUT_INVALID");
assert.equal(session.output, null);
});
@@ -0,0 +1,49 @@
import type { SkinRuntimePlugin } from "../../../src/shared/skin-runtime-plugins.js";
import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
createSkinExtensionWasmUiLoopPrototype,
type SkinExtensionWasmUiLoopRunHandle,
} from "./skin-extension-wasm-ui-loop.js";
export class SkinRuntimePluginSessionError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinRuntimePluginSessionError";
}
}
export interface SkinRuntimePluginSessionOptions {
plugin: SkinRuntimePlugin;
createRun(input: SkinExtensionUiInput): SkinExtensionWasmUiLoopRunHandle;
onOutput?(output: string, document: SkinPluginDocument): void | Promise<void>;
onError?(error: Error): void;
}
/** Binds one authorized v4 descriptor to its page and surface contract. */
export function createSkinRuntimePluginSession(options: SkinRuntimePluginSessionOptions) {
let output: string | null = null;
const loop = createSkinExtensionWasmUiLoopPrototype({
createRun: options.createRun,
onOutput: async (nextOutput, document) => {
if (document.components.some((component) => component.page !== options.plugin.page)) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_PAGE_MISMATCH", "Generated UI must stay on the page declared by its plugin.");
}
if (options.plugin.mode === "surface" && document.components.length !== 1) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_SURFACE_OUTPUT_INVALID", "A surface plugin must generate exactly one root component.");
}
output = nextOutput;
await options.onOutput?.(nextOutput, document);
},
onError: options.onError,
});
return {
get output() { return output; },
get closed() { return loop.closed; },
get running() { return loop.running; },
start: () => loop.start(),
dispatch: (input: unknown) => loop.dispatch(input),
close: (reason?: string) => loop.close(reason),
};
}
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import "./skin-runtime-plugin-session.test.js";
import {
computeSkinRuntimePluginDigest,
createSkinRuntimePluginApproval,
+2 -2
View File
@@ -33,7 +33,7 @@ export interface SkinRuntimePluginWasmOptions {
prototypeOnly: true;
}
const WASM_PROTOTYPE_PERMISSIONS = new Set(["session.status.read"]);
const WASM_PROTOTYPE_PERMISSIONS = new Set(["session.status.read", "ui.surface.replace"]);
/** Starts a Wasm entry only after rechecking the exact package digest and local approval. */
export async function createSkinRuntimePluginWasmSandboxPrototype(
@@ -66,7 +66,7 @@ export async function createSkinRuntimePluginWasmSandboxPrototype(
name: plugin.name,
version: plugin.version,
apiVersion: plugin.apiVersion,
permissions: [...plugin.permissions],
permissions: plugin.permissions.filter((permission) => permission === "session.status.read"),
});
// This legacy approval object is created only after the v4 digest-bound host approval above.
+27 -3
View File
@@ -24,9 +24,22 @@
@surface-change="skinPluginSurfaceActive = $event"
@restore-skin="switchToBuiltIn"
/>
<SkinRuntimePluginHost
v-if="activeSkin?.runtimePlugins"
:skin-id="activeSkin.id"
:skin-version="activeSkin.version"
:plugins="activeSkin.runtimePlugins"
:files="activeSkin.runtimePluginFiles ?? {}"
:styles="activeSkin.runtimePluginStyles ?? {}"
:assets="activeSkin.assets"
:page="showVoiceShell ? 'voice' : 'home'"
:read-session-status="readSkinRuntimeSessionStatus"
@surface-change="skinRuntimePluginSurfaceActive = $event"
@restore-skin="switchToBuiltIn"
/>
<!-- Connection / welcome screen -->
<section
v-if="!showVoiceShell && !skinPluginSurfaceActive"
v-if="!showVoiceShell && !skinPluginSurfaceActive && !skinRuntimePluginSurfaceActive"
class="join-page"
data-ws-part="home"
>
@@ -301,7 +314,7 @@
<!-- Connected application shell -->
<div
v-else-if="showVoiceShell && !skinPluginSurfaceActive"
v-else-if="showVoiceShell && !skinPluginSurfaceActive && !skinRuntimePluginSurfaceActive"
:class="['app-shell', `mobile-view-${mobileSection}`]"
:data-performance-open="performancePanelOpen ? 'true' : 'false'"
:data-favorite-rail="accessMode === 'open' ? 'true' : 'false'"
@@ -930,6 +943,7 @@ import { observeMobileViewport } from "../services/mobile-viewport.js";
import { computed, h, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
import Icon from "../components/Icon.vue";
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
import SkinRuntimePluginHost from "../components/SkinRuntimePluginHost.js";
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
import VoiceMemberCards from "../components/web-client/VoiceMemberCards.vue";
import VoicePerformancePanel from "../components/web-client/VoicePerformancePanel.vue";
@@ -1097,7 +1111,11 @@ let toastTimer: ReturnType<typeof setTimeout> | undefined;
const language = ref<Language>(getInitialLanguage());
const activeSkin = shallowRef<InstalledSkin | null>(null);
const skinPluginSurfaceActive = ref(false);
watch(activeSkin, () => { skinPluginSurfaceActive.value = false; }, { flush: "sync" });
const skinRuntimePluginSurfaceActive = ref(false);
watch(activeSkin, () => {
skinPluginSurfaceActive.value = false;
skinRuntimePluginSurfaceActive.value = false;
}, { flush: "sync" });
const skinMessageOverrides = computed(() => resolveSkinMessages(activeSkin.value, language.value));
const { t: translate, localizedMessage, localizedAudioNotice, visibleErrorCode } = useWebClientI18n(language);
function t(key: string, variables: Record<string, string | number> = {}) {
@@ -1542,6 +1560,12 @@ const skinPluginContext = computed(() => ({
},
}));
const readSkinRuntimeSessionStatus = (_signal: AbortSignal) => ({
connected: voiceState.connected,
channelName: voiceState.connected ? currentChannelName.value : null,
memberCount: skinPluginMembers.value.length,
});
const skinPluginActions = {
"voice.joinChannel": (args: Record<string, string | number | boolean>) => {
if (!voiceState.connected || typeof args.channelId !== "string") return;