Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(plugins): the editor writes a plugin, shows what it contributes, and ships it as one file

yhh859178dccd25
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 446b6efbe..6e177e1c2 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -44,7 +44,16 @@ import { installCrashCapture, logsDir } from './resilience';
import { mcpMode, startMcpEndpoint } from './mcpEndpoint';
import {
discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,
+ PROJECT_PLUGIN_DIR, USER_PLUGIN_DIR,
} from './pluginHost';
+// Every OS file dialog goes through here, so a screenshot run can script what the
+// user would have picked instead of blocking on a modal it cannot reach.
+import { showOpenDialog, showSaveDialog } from './shotDialogs';
+import { scaffoldPlugin, type ScaffoldPluginOptions } from './pluginScaffold';
+import {
+ packPlugin, packageFileName, inspectPluginPackage, installPluginPackage, writePackage,
+ PLUGIN_PACKAGE_EXT,
+} from './pluginPackage';
import { checkForUpdate } from './updateCheck';
import {
listPlatforms, loadProjectPlatform, createProjectPlatform, setPlatformTrustGate,
@@ -173,6 +182,11 @@ let win: BrowserWindow | null = null;
* Screenshot / visual-regression capture (gated on ESTELLA_SHOT=out.png). Drives the
* renderer's `?automation=1` hook to open ESTELLA_SHOT_PROJECT (+ optional
* ESTELLA_SHOT_SCENE), lets the panels + WebGL viewport settle, writes a PNG, and quits.
+ *
+ * Flows that open a native FILE DIALOG are reachable too: ESTELLA_SHOT_PICK_FILE and
+ * ESTELLA_SHOT_SAVE_FILE script what the user would have chosen (see shotDialogs.ts).
+ * Unscripted, a dialog cancels rather than opening — a modal in a headless run is a
+ * hang, not a failure.
*/
async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {
const exec = (code: string): Promise<unknown> =>
@@ -632,7 +646,7 @@ async function ensureTwinsForOpen(root: string): Promise<void> {
ipcMain.handle('project:openDialog', async () => {
if (!win) return null;
- const res = await dialog.showOpenDialog(win, {
+ const res = await showOpenDialog(win, {
title: 'Open Estella Project',
properties: ['openDirectory'],
});
@@ -651,7 +665,7 @@ ipcMain.handle('project:open', async (_e, root: string) => {
// Import: OS file picker → copy the chosen files into `destDir` + write `.meta`.
ipcMain.handle('project:importAssets', async (_e, destDir: string) => {
if (!win) return null;
- const res = await dialog.showOpenDialog(win, {
+ const res = await showOpenDialog(win, {
title: 'Import Assets',
properties: ['openFile', 'multiSelections'],
filters: [
@@ -997,12 +1011,84 @@ ipcMain.handle('plugins:reveal', async (_e, id: string) => {
if (dir) shell.openPath(dir);
});
+/** The folder a scope means. Project scope needs an open project; user scope never does. */
+function pluginsRootFor(scope: 'project' | 'user'): string {
+ if (scope === 'user') return path.join(userData(), USER_PLUGIN_DIR);
+ return path.join(requireRoot(), PROJECT_PLUGIN_DIR);
+}
+
+// Scaffold a plugin — manifest, entry, tsconfig, and the typings sidecar the
+// tsconfig points at. The renderer supplies `editorVersion` and `apiTypes` rather
+// than main reading them: the renderer holds the constant that ENFORCES the
+// `engines.editor` check and the types.ts text the editor is itself typed by, so
+// what gets written can never disagree with what gets checked.
+ipcMain.handle('plugins:scaffold', async (_e, scope: 'project' | 'user', opts: ScaffoldPluginOptions) => {
+ try {
+ return await scaffoldPlugin(pluginsRootFor(scope), opts);
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+});
+
+// Pack a plugin into one `.esplugin` file. Main owns the save dialog; the default
+// name carries the id and version, so a folder of these stays readable.
+ipcMain.handle('plugins:export', async (_e, id: string) => {
+ if (!win) return { ok: false, error: 'no window' };
+ const found = await discoverPlugins(projectRoot, userData());
+ const entry = found.find((p) => p.id === id && p.kind === 'plugin');
+ if (!entry?.manifest) return { ok: false, error: `plugin "${id}" not found` };
+
+ const packed = await packPlugin(entry.dir);
+ if (!packed.ok || !packed.data) return { ok: false, error: packed.error };
+
+ const res = await showSaveDialog(win, {
+ title: 'Export plugin',
+ defaultPath: packageFileName(entry.manifest),
+ filters: [{ name: 'Estella plugin', extensions: [PLUGIN_PACKAGE_EXT] }],
+ });
+ if (res.canceled || !res.filePath) return { ok: false, canceled: true };
+ try {
+ await writePackage(res.filePath, packed.data);
+ return { ok: true, file: res.filePath };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+});
+
+// Two-step import, and the split is the design: the renderer shows what is inside
+// before anything is written, and only asks to install once the user has seen it.
+ipcMain.handle('plugins:pickPackage', async () => {
+ if (!win) return { ok: false, error: 'no window' };
+ const res = await showOpenDialog(win, {
+ title: 'Install plugin from file',
+ filters: [{ name: 'Estella plugin', extensions: [PLUGIN_PACKAGE_EXT, 'zip'] }],
+ properties: ['openFile'],
+ });
+ if (res.canceled || res.filePaths.length === 0) return { ok: false, canceled: true };
+ const file = res.filePaths[0];
+ try {
+ return { ...inspectPluginPackage(await readFile(file)), file };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err), file };
+ }
+});
+
+// Install a package the user already previewed. It lands UNTRUSTED — installing is
+// not approving, and the trust gate is the user's decision to make afterwards.
+ipcMain.handle('plugins:install', async (_e, file: string, scope: 'project' | 'user') => {
+ try {
+ return await installPluginPackage(await readFile(file), pluginsRootFor(scope));
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+});
+
// — Native runtime templates. The prebuilt engine a mobile target is assembled
// around: the editor never compiles one, it installs the release's artifact. —
ipcMain.handle('nativeTemplates:list', () => listNativeTemplates(app.getVersion()));
ipcMain.handle('nativeTemplates:install', async () => {
if (!win) return { ok: false, error: 'no window' };
- const res = await dialog.showOpenDialog(win, {
+ const res = await showOpenDialog(win, {
title: 'Install a runtime template',
filters: [{ name: 'Estella runtime template', extensions: ['zip'] }],
properties: ['openFile'],
@@ -1028,7 +1114,7 @@ ipcMain.handle('project:createFromTemplate', (_e, templateDir: string, location:
);
ipcMain.handle('project:chooseDirectory', async () => {
if (!win) return null;
- const res = await dialog.showOpenDialog(win, {
+ const res = await showOpenDialog(win, {
title: 'Choose a location for the new project',
properties: ['openDirectory', 'createDirectory'],
});
@@ -1040,7 +1126,7 @@ ipcMain.handle('project:chooseDirectory', async () => {
ipcMain.handle('project:saveDialog', async (_e, defaultRel?: string) => {
const root = requireRoot();
if (!win) return null;
- const res = await dialog.showSaveDialog(win, {
+ const res = await showSaveDialog(win, {
title: 'Save Scene As',
defaultPath: defaultRel ? path.join(root, defaultRel) : path.join(root, 'assets/scenes'),
filters: [{ name: 'Estella Scene', extensions: ['esscene'] }],
diff --git a/desktop/electron/pluginPackage.ts b/desktop/electron/pluginPackage.ts
new file mode 100644
index 000000000..1ace5cfce
--- /dev/null
+++ b/desktop/electron/pluginPackage.ts
@@ -0,0 +1,208 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pluginPackage.ts — a plugin as one file you can hand to someone.
+ *
+ * `.esplugin` is a ZIP, written through the repo's own zip module (the same one
+ * that writes runtime templates and playable bundles) rather than a second
+ * implementation. Renaming one to `.zip` opens it in any tool, which is the point:
+ * a package format nobody but us can read is a format nobody audits.
+ *
+ * IMPORT IS THE DANGEROUS DIRECTION. A `.esplugin` is a file someone was handed,
+ * so the order here is deliberate and the whole design:
+ *
+ * 1. INSPECT from the central directory alone — nothing is inflated, nothing is
+ * written. That is what lets the UI show what is inside before the user
+ * commits, and what makes the size check meaningful (a small archive that
+ * claims to expand to gigabytes is refused before it can).
+ * 2. EXTRACT only after they say yes. `extractZip` verifies every CRC and rejects
+ * `../` names, so a corrupt or hostile archive fails instead of landing.
+ * 3. LAND UNTRUSTED. Installing is not approving. The plugin appears in the panel
+ * needing trust, exactly as a folder someone copied in by hand would — the one
+ * thing an import must never do is decide the trust question for the user.
+ */
+import { existsSync } from 'node:fs';
+import { readFile, writeFile, mkdir, rm } from 'node:fs/promises';
+import path from 'node:path';
+import { makeZip, zipTree, listZip, readZip, extractZip } from '../../build-tools/utils/zip.js';
+import { validateManifest, resolveLocalized, type PluginManifest } from '../src/plugins/manifest';
+import { PLUGIN_TYPES_DIR } from '../src/plugins/paths';
+
+/** The extension, spelled once. */
+export const PLUGIN_PACKAGE_EXT = 'esplugin';
+
+/**
+ * Never packed. `node_modules` is vendored input that esbuild already bundles at
+ * load time, `dist` is build output, `.types` is regenerated by the editor on every
+ * open, and `.git` is somebody's whole history. Shipping any of them makes the
+ * package big and the diff meaningless.
+ */
+const EXCLUDED_DIRS = new Set(['node_modules', 'dist', 'out', '.git', PLUGIN_TYPES_DIR]);
+
+/**
+ * Refused before inflating. A plugin is source: the biggest legitimate one is a few
+ * megabytes of icons. This is a bomb guard, not a quality judgement, so it sits far
+ * above anything real rather than at a tasteful limit.
+ */
+const MAX_UNPACKED_BYTES = 128 * 1024 * 1024;
+
+export interface PluginPackageEntry {
+ name: string;
+ size: number;
+}
+
+/** What an `.esplugin` says it is, read without extracting a byte of it. */
+export interface PluginPackageInfo {
+ ok: boolean;
+ /** Why it cannot be installed. Set whenever `ok` is false. */
+ error?: string;
+ manifest?: PluginManifest;
+ /** Display name for the manifest's locale-agnostic name field. */
+ name?: string;
+ /** Every file the archive claims to contain, for the pre-install preview. */
+ files?: PluginPackageEntry[];
+ /** Declared capabilities — shown BEFORE installing, not only at the trust gate. */
+ capabilities?: string[];
+}
+
+export interface InstallPluginResult {
+ ok: boolean;
+ error?: string;
+ id?: string;
+ /** Absolute folder written. */
+ dir?: string;
+}
+
+// =============================================================================
+// Export
+// =============================================================================
+
+/**
+ * Pack a plugin folder into `.esplugin` bytes.
+ *
+ * The manifest is re-validated on the way out: exporting a plugin whose plugin.json
+ * has drifted into invalid would produce a file that cannot be installed anywhere,
+ * and the moment to say so is while the author still has it open.
+ */
+export async function packPlugin(dir: string): Promise<{ ok: boolean; error?: string; data?: Buffer }> {
+ const manifestFile = path.join(dir, 'plugin.json');
+ if (!existsSync(manifestFile)) return { ok: false, error: 'folder has no plugin.json' };
+ try {
+ const parsed: unknown = JSON.parse(await readFile(manifestFile, 'utf8'));
+ const result = validateManifest(parsed);
+ if ('error' in result) return { ok: false, error: `plugin.json is not valid: ${result.error}` };
+
+ const entries = zipTree(dir, '', (name, isDirectory) => {
+ const base = name.split('/').pop() ?? name;
+ return !(isDirectory && EXCLUDED_DIRS.has(base));
+ });
+ if (entries.length === 0) return { ok: false, error: 'nothing to pack' };
+ return { ok: true, data: makeZip(entries) };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/** A filename that is recognizably this plugin at this version. */
+export function packageFileName(manifest: PluginManifest): string {
+ return `${manifest.id}-${manifest.version}.${PLUGIN_PACKAGE_EXT}`;
+}
+
+// =============================================================================
+// Import
+// =============================================================================
+
+/**
+ * Read what an `.esplugin` contains WITHOUT extracting it — the preview the user
+ * decides on. Never throws: a file that is not an archive at all is reported the
+ * same way a bad manifest is, because from the user's side those are one question
+ * ("can I install this?") with one answer.
+ */
+export function inspectPluginPackage(buf: Buffer): PluginPackageInfo {
+ let listing;
+ try {
+ listing = listZip(buf);
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+
+ const unpacked = listing.reduce((n, e) => n + e.size, 0);
+ if (unpacked > MAX_UNPACKED_BYTES) {
+ return { ok: false, error: `package expands to ${Math.round(unpacked / 1e6)} MB — refusing to unpack it` };
+ }
+ // Checked here as well as in extractZip: this runs first, and a file list shown
+ // with `../` in it would be a preview of an attack presented as a manifest.
+ const unsafe = listing.find((e) => e.name.startsWith('/') || e.name.includes('\\') || e.name.split('/').includes('..'));
+ if (unsafe) return { ok: false, error: `unsafe entry name in package: ${unsafe.name}` };
+
+ const files = listing.map((e) => ({ name: e.name, size: e.size }));
+ const manifestEntry = listing.find((e) => e.name === 'plugin.json');
+ if (!manifestEntry) return { ok: false, error: 'package has no plugin.json at its root', files };
+
+ // Only the manifest is inflated — one small entry, after the size guard.
+ let parsed: unknown;
+ try {
+ const entry = readOne(buf, 'plugin.json');
+ parsed = JSON.parse(entry.toString('utf8'));
+ } catch (err) {
+ return { ok: false, error: `plugin.json could not be read: ${String(err)}`, files };
+ }
+ const result = validateManifest(parsed);
+ if ('error' in result) return { ok: false, error: result.error, files };
+
+ return {
+ ok: true,
+ manifest: result.manifest,
+ name: resolveLocalized(result.manifest.name, 'en'),
+ capabilities: result.manifest.capabilities ?? [],
+ files,
+ };
+}
+
+/**
+ * Inflate one entry. Goes through `readZip`, which inflates everything — wasteful
+ * for a single small file, but it is also the only path that verifies CRCs, and a
+ * manifest read from an entry whose checksum was never checked is one we cannot act
+ * on. The size guard has already run, so "everything" is bounded.
+ */
+function readOne(buf: Buffer, name: string): Buffer {
+ const entry = readZip(buf).find((e) => e.name === name);
+ if (!entry) throw new Error(`${name} is not in the package`);
+ return entry.data;
+}
+
+/**
+ * Install a package into `pluginsRoot`, under the id its own manifest declares.
+ *
+ * Refuses to overwrite: an existing folder is somebody's plugin — possibly one they
+ * are editing — and "install" must never mean "replace what was there". Updating is
+ * a separate decision the caller makes by removing the old one first.
+ *
+ * A failure mid-extract removes the partial folder, so a broken package cannot leave
+ * a half-plugin behind for the panel to report as corrupt.
+ */
+export async function installPluginPackage(
+ buf: Buffer,
+ pluginsRoot: string,
+): Promise<InstallPluginResult> {
+ const info = inspectPluginPackage(buf);
+ if (!info.ok || !info.manifest) return { ok: false, error: info.error ?? 'not a valid plugin package' };
+
+ const id = info.manifest.id;
+ const dir = path.join(pluginsRoot, id);
+ if (existsSync(dir)) return { ok: false, error: `${id} is already installed here`, id };
+
+ try {
+ await mkdir(pluginsRoot, { recursive: true });
+ extractZip(buf, dir);
+ return { ok: true, id, dir };
+ } catch (err) {
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
+ return { ok: false, error: err instanceof Error ? err.message : String(err), id };
+ }
+}
+
+/** Write packed bytes to a file the user chose. */
+export async function writePackage(file: string, data: Buffer): Promise<void> {
+ await writeFile(file, data);
+}
diff --git a/desktop/electron/pluginScaffold.ts b/desktop/electron/pluginScaffold.ts
new file mode 100644
index 000000000..0b9409789
--- /dev/null
+++ b/desktop/electron/pluginScaffold.ts
@@ -0,0 +1,305 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pluginScaffold.ts — write a new editor plugin, ready to run.
+ *
+ * The shape of a plugin (a folder whose name need not be its id, a manifest whose
+ * `engines.editor` range must match THIS editor, a tsconfig pointing at generated
+ * typings one directory up) is exactly the part that is hard to know before you
+ * have seen one. So the editor writes it, the same way it writes a project
+ * platform's two halves — see platformCatalog.ts, whose posture this mirrors:
+ * validate first, never clobber, and hand back paths rather than throwing.
+ *
+ * One rule worth stating: the generated `engines.editor` pins to the RUNNING
+ * editor's minor. Below 1.0 the minor is the breaking-change axis, so a template
+ * carrying a hard-coded range goes stale the moment the editor's minor moves — and
+ * a plugin scaffolded from it would be born `incompatible`.
+ *
+ * Pure Node: the caller resolves which folder a scope means.
+ */
+import { existsSync } from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { pluginIdProblem } from '../src/plugins/manifest';
+import { PLUGIN_TYPES_DIR } from '../src/plugins/paths';
+
+/** Sample contributions the scaffold can write into the entry file. */
+export type ScaffoldContribution = 'command' | 'panel' | 'inspector' | 'overlay' | 'tool';
+
+export const SCAFFOLD_CONTRIBUTIONS: readonly ScaffoldContribution[] = [
+ 'command',
+ 'panel',
+ 'inspector',
+ 'overlay',
+ 'tool',
+];
+
+export interface ScaffoldPluginOptions {
+ /** Dotted, lowercase — also the folder name. */
+ id: string;
+ /** Display name, written into the manifest as-is. */
+ name: string;
+ /** Which samples to write. An empty list still produces a valid, loadable plugin. */
+ contributions?: readonly ScaffoldContribution[];
+ /** The running editor's version — what `engines.editor` is pinned to. */
+ editorVersion: string;
+ /**
+ * Text of the plugin API typings (`src/plugins/types.ts`). Written as the scope's
+ * `.types/editor-api.d.ts` sidecar so the generated tsconfig resolves on the first
+ * open — including for a user-scoped plugin, which lives outside the project the
+ * renderer's type sync can reach.
+ */
+ apiTypes?: string;
+}
+
+export interface ScaffoldPluginResult {
+ ok: boolean;
+ error?: string;
+ /** Absolute plugin folder — what "Reveal" opens. */
+ dir?: string;
+ /** Files written, relative to the plugin folder. */
+ files?: string[];
+}
+
+/** `0.34.1` → `^0.34`: the range that means "this editor's line". */
+export function editorRangeFor(version: string): string {
+ const m = /^(\d+)\.(\d+)/.exec(version.trim());
+ return m ? `^${m[1]}.${m[2]}` : '*';
+}
+
+// =============================================================================
+// Templates
+// =============================================================================
+
+function manifestTemplate(id: string, name: string, editorVersion: string): string {
+ // No `description` key: the manifest reader requires a non-empty string when the
+ // field is PRESENT, so scaffolding an empty one would write a plugin that fails
+ // its own validation. An absent optional field is the honest spelling.
+ return `${JSON.stringify(
+ {
+ id,
+ name,
+ version: '0.1.0',
+ engines: { editor: editorRangeFor(editorVersion) },
+ main: { editor: 'src/editor.ts' },
+ },
+ null,
+ 2,
+ )}\n`;
+}
+
+/** Points `@estella/editor-api` at the typings the editor regenerates on open. */
+function tsconfigTemplate(): string {
+ return `${JSON.stringify(
+ {
+ compilerOptions: {
+ strict: true,
+ target: 'ES2020',
+ module: 'ESNext',
+ moduleResolution: 'bundler',
+ jsx: 'react-jsx',
+ noEmit: true,
+ skipLibCheck: true,
+ paths: { '@estella/editor-api': [`../${PLUGIN_TYPES_DIR}/editor-api.d.ts`] },
+ },
+ include: ['src'],
+ },
+ null,
+ 2,
+ )}\n`;
+}
+
+/** Type-only imports each sample needs, so the entry file compiles as written. */
+const SAMPLE_TYPES: Record<ScaffoldContribution, readonly string[]> = {
+ command: [],
+ panel: [],
+ inspector: ['EntityId', 'InspectorSectionBuilder'],
+ overlay: ['OverlayGraphics'],
+ tool: ['PointerInput'],
+};
+
+function sampleBody(kind: ScaffoldContribution, id: string, name: string): string {
+ switch (kind) {
+ case 'command':
+ return ` // A command. It appears in the command palette and — because \`menu\` is set —
+ // under Tools in the menu bar. Every register() returns a disposable that is
+ // retracted automatically when the plugin unloads, so you rarely keep it.
+ ctx.commands.register({
+ id: '${id}.hello',
+ title: { en: 'Say hello', 'zh-CN': '打个招呼' },
+ menu: 'tools',
+ run() {
+ ctx.ui.toast(\`Hello from ${name}! \${ctx.scene.getSelectionIds().length} selected.\`);
+ },
+ });`;
+
+ case 'panel':
+ return ` // A dock panel. The host element sits inside the editor's own frame, so the
+ // theme variables are in scope — style against those and it matches the editor
+ // in both light and dark. Open it with ctx.panels.open('${id}.panel').
+ ctx.panels.register({
+ id: '${id}.panel',
+ title: { en: '${name}', 'zh-CN': '${name}' },
+ placement: 'side-right',
+ width: 260,
+ mount(host) {
+ const body = document.createElement('div');
+ body.style.cssText = 'padding:8px;color:var(--text);font:12px var(--font-ui,sans-serif)';
+ const paint = () => {
+ body.textContent = \`\${ctx.scene.getSelectionIds().length} entity(ies) selected\`;
+ };
+ paint();
+ host.appendChild(body);
+ const sub = ctx.events.on('selectionChanged', paint);
+ // Return teardown: called when the panel closes OR the plugin unloads.
+ return () => {
+ sub.dispose();
+ body.remove();
+ };
+ },
+ });`;
+
+ case 'inspector':
+ return ` // An extra Inspector section, shown for any entity carrying a Sprite. The host
+ // renders these rows as the editor's own property UI, so there is nothing to
+ // style — and \`write\` receives edits back by row key.
+ ctx.inspector.register({
+ kind: 'component',
+ id: 'notes',
+ component: 'Sprite',
+ title: { en: '${name}', 'zh-CN': '${name}' },
+ build(entity: EntityId, ui: InspectorSectionBuilder) {
+ ui.info({ en: 'Entity', 'zh-CN': '实体' }, String(entity));
+ ui.bool('flagged', { en: 'Needs art pass', 'zh-CN': '需要美术检查' },
+ ctx.state.get(\`flagged.\${entity}\`, false));
+ },
+ write(entity: EntityId, key, value) {
+ if (key === 'flagged') ctx.state.set(\`flagged.\${entity}\`, value);
+ },
+ });`;
+
+ case 'overlay':
+ return ` // A viewport gizmo, redrawn every frame. Primitives take WORLD coordinates and
+ // the host projects them, so this tracks the scene through pan and zoom with no
+ // camera math. Keep it cheap — it runs on every frame.
+ ctx.overlays.register({
+ id: '${id}.gizmo',
+ render(g: OverlayGraphics) {
+ for (const entity of ctx.scene.getSelectionIds()) {
+ const p = ctx.scene.getFieldValue(entity, 'Transform', 'position');
+ if (!Array.isArray(p)) continue;
+ const at = { x: p[0] as number, y: p[1] as number };
+ // Radius is in world units; stroke width is in screen pixels.
+ g.circle(at, 48, { color: 'var(--acc)', width: 1, dashed: true });
+ }
+ },
+ });`;
+
+ case 'tool':
+ return ` // A viewport tool. Arm it with ctx.tools.activate('${id}.measure'); it then gets
+ // first refusal on every pointer-down. Returning true claims the stroke (and its
+ // move/up); false lets the click fall through. Choosing any built-in tool
+ // disarms it, so the user can never get stuck in here.
+ let from: { x: number; y: number } | null = null;
+ ctx.tools.register({
+ id: '${id}.measure',
+ title: { en: 'Measure', 'zh-CN': '测距' },
+ onPointerDown(p: PointerInput, tool) {
+ from = ctx.viewport.viewportToWorld(p.x, p.y);
+ tool.capture(p.pointerId);
+ return true;
+ },
+ onPointerMove() {},
+ onPointerUp(p: PointerInput, tool) {
+ tool.release(p.pointerId);
+ const to = ctx.viewport.viewportToWorld(p.x, p.y);
+ if (from && to) {
+ const d = Math.hypot(to.x - from.x, to.y - from.y);
+ ctx.ui.toast(\`\${d.toFixed(1)} units\`);
+ }
+ from = null;
+ },
+ cancel() {
+ from = null;
+ },
+ });`;
+ }
+}
+
+function entryTemplate(id: string, name: string, contributions: readonly ScaffoldContribution[]): string {
+ const typeImports = [...new Set(contributions.flatMap((c) => SAMPLE_TYPES[c]))].sort();
+ const imports = ['definePlugin', 'type PluginContext', ...typeImports.map((t) => `type ${t}`)];
+ const bodies = contributions.map((c) => sampleBody(c, id, name));
+ const body =
+ bodies.length > 0
+ ? bodies.join('\n\n')
+ : ` // Nothing contributed yet. Reach for ctx.commands / panels / inspector /
+ // overlays / tools / assets / entities / contextMenus — each register() is
+ // retracted for you when this plugin unloads.
+ ctx.log.info('${name} activated');`;
+
+ return `// ${name} — an Estella editor plugin.
+//
+// This runs in the editor's own realm, with the editor's access. Saving any file in
+// this folder recompiles and re-activates the plugin, and everything it registered
+// is retracted first — so the edit loop is just "save".
+import { ${imports.join(', ')} } from '@estella/editor-api';
+
+export default definePlugin({
+ activate(ctx: PluginContext) {
+${body}
+ },
+
+ // Optional. Contributions retract themselves; this is for anything else you own
+ // (a timer, a socket, a file watcher).
+ deactivate() {},
+});
+`;
+}
+
+// =============================================================================
+// Scaffolding
+// =============================================================================
+
+/**
+ * Write a new plugin into `pluginsRoot` (the scope's folder — a project's
+ * `.esengine/plugins/` or the per-user one). Never clobbers: an existing folder is
+ * an error, because the alternative is overwriting work with a template.
+ */
+export async function scaffoldPlugin(
+ pluginsRoot: string,
+ opts: ScaffoldPluginOptions,
+): Promise<ScaffoldPluginResult> {
+ const bad = pluginIdProblem(opts.id);
+ if (bad) return { ok: false, error: bad };
+ const name = opts.name.trim();
+ if (!name) return { ok: false, error: 'plugin needs a name' };
+
+ const dir = path.join(pluginsRoot, opts.id);
+ if (existsSync(dir)) return { ok: false, error: `${opts.id} already exists here` };
+
+ const contributions = opts.contributions ?? ['command'];
+ const files: Record<string, string> = {
+ 'plugin.json': manifestTemplate(opts.id, name, opts.editorVersion),
+ 'tsconfig.json': tsconfigTemplate(),
+ [path.join('src', 'editor.ts')]: entryTemplate(opts.id, name, contributions),
+ };
+
+ try {
+ await mkdir(path.join(dir, 'src'), { recursive: true });
+ for (const [rel, content] of Object.entries(files)) {
+ await writeFile(path.join(dir, rel), content, 'utf8');
+ }
+ // The typings sidecar the generated tsconfig points at. Overwritten rather than
+ // preserved: it is generated, and matching the RUNNING editor is its whole job —
+ // the same posture init.ts takes when it rewrites this on every project open.
+ if (opts.apiTypes) {
+ const typesDir = path.join(pluginsRoot, PLUGIN_TYPES_DIR);
+ await mkdir(typesDir, { recursive: true });
+ await writeFile(path.join(typesDir, 'editor-api.d.ts'), opts.apiTypes, 'utf8');
+ }
+ return { ok: true, dir, files: Object.keys(files).map((f) => f.split(path.sep).join('/')) };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index c784b9e9e..a3806f463 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -13,6 +13,8 @@ import type {
import type { PlayRealmResult } from './buildPlayRealm';
import type { LatestRelease } from './updateCheck';
import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';
+import type { ScaffoldPluginOptions, ScaffoldPluginResult } from './pluginScaffold';
+import type { PluginPackageInfo, InstallPluginResult } from './pluginPackage';
import type { NativeTemplateEntry, InstallResult } from './nativeTemplates';
// The privileged bridge the renderer is allowed to touch. Keep this surface small
@@ -221,6 +223,21 @@ const api = {
ipcRenderer.invoke('plugins:setEnabled', id, enabled),
/** Reveal the plugin's folder in Finder / Explorer. */
reveal: (id: string): Promise<void> => ipcRenderer.invoke('plugins:reveal', id),
+ /** Write a new plugin — manifest, entry, tsconfig, typings sidecar — into the
+ * chosen scope's folder. The caller passes the editor version and the API
+ * typings text, so what is generated matches the editor doing the generating. */
+ scaffold: (scope: 'project' | 'user', opts: ScaffoldPluginOptions): Promise<ScaffoldPluginResult> =>
+ ipcRenderer.invoke('plugins:scaffold', scope, opts),
+ /** Pack a plugin into one `.esplugin` file the user picks a location for. */
+ exportPackage: (id: string): Promise<{ ok: boolean; error?: string; canceled?: boolean; file?: string }> =>
+ ipcRenderer.invoke('plugins:export', id),
+ /** Pick an `.esplugin` and report what is INSIDE it — nothing is written yet.
+ * The two-step exists so the user sees the contents before committing. */
+ pickPackage: (): Promise<PluginPackageInfo & { canceled?: boolean; file?: string }> =>
+ ipcRenderer.invoke('plugins:pickPackage'),
+ /** Install a previewed package. It lands untrusted; approving is separate. */
+ installPackage: (file: string, scope: 'project' | 'user'): Promise<InstallPluginResult> =>
+ ipcRenderer.invoke('plugins:install', file, scope),
},
// The prebuilt engine a mobile target is assembled around. The editor installs
// one; it never compiles one (see electron/nativeTemplates.ts).
diff --git a/desktop/electron/shotDialogs.ts b/desktop/electron/shotDialogs.ts
new file mode 100644
index 000000000..0412febcf
--- /dev/null
+++ b/desktop/electron/shotDialogs.ts
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file shotDialogs.ts — the editor's ONE door to an OS file dialog.
+ *
+ * A native dialog is the one thing a screenshot run cannot get past: it is modal,
+ * it is drawn by the OS, and the shot harness only evaluates JavaScript in the
+ * renderer. Any flow that opens one was simply unreachable from automation — which
+ * is why import/export flows went unverified while everything around them did not.
+ *
+ * So under `ESTELLA_SHOT` the answer comes from the script instead:
+ *
+ * ESTELLA_SHOT_PICK_FILE what the next open dialog returns
+ * ESTELLA_SHOT_SAVE_FILE what the next save dialog returns
+ *
+ * Each is a path, or a JSON array of paths to hand back to successive dialogs (so
+ * one shot can export and then import). An entry may itself be an array of paths,
+ * for a multi-selection picker.
+ *
+ * THE IMPORTANT RULE IS THE EMPTY CASE. In shot mode with nothing scripted, this
+ * returns "cancelled" and says so loudly — it does NOT fall through to a real
+ * dialog. A headless run that opened one would block until the harness timed out,
+ * and the failure would look like a hang rather than like the missing script it is.
+ *
+ * Outside shot mode this is a straight delegation with no behaviour of its own.
+ */
+import { dialog, type BrowserWindow, type OpenDialogOptions, type SaveDialogOptions } from 'electron';
+
+const shotMode = (): boolean => !!process.env.ESTELLA_SHOT;
+
+/**
+ * Parse a scripted queue. A bare path is the one-entry case, which is what almost
+ * every shot wants; JSON is there for the ones that drive more than one dialog.
+ */
+function parseQueue(raw: string | undefined): (string | string[])[] {
+ if (!raw) return [];
+ const text = raw.trim();
+ if (text.startsWith('[')) {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (Array.isArray(parsed)) return parsed as (string | string[])[];
+ } catch {
+ // Fall through: a path that merely starts with '[' is not our problem to
+ // guess at, and treating it as one literal path is the harmless reading.
+ }
+ }
+ return [text];
+}
+
+// Consumed per call, so a shot scripts dialogs in the order its flow opens them.
+let openQueue: (string | string[])[] | null = null;
+let saveQueue: (string | string[])[] | null = null;
+
+const nextOpen = (): (string | string[]) | undefined => {
+ openQueue ??= parseQueue(process.env.ESTELLA_SHOT_PICK_FILE);
+ return openQueue.shift();
+};
+
+const nextSave = (): (string | string[]) | undefined => {
+ saveQueue ??= parseQueue(process.env.ESTELLA_SHOT_SAVE_FILE);
+ return saveQueue.shift();
+};
+
+/**
+ * Show an open dialog, or hand back what the shot scripted.
+ * `win` may be null — the caller has already decided a dialog is possible.
+ */
+export async function showOpenDialog(
+ win: BrowserWindow,
+ options: OpenDialogOptions,
+): Promise<{ canceled: boolean; filePaths: string[] }> {
+ if (shotMode()) {
+ const scripted = nextOpen();
+ if (scripted === undefined) {
+ console.log(`[shotDialog] open "${options.title ?? ''}" — nothing scripted (set ESTELLA_SHOT_PICK_FILE); returning cancelled`);
+ return { canceled: true, filePaths: [] };
+ }
+ const filePaths = Array.isArray(scripted) ? scripted : [scripted];
+ console.log(`[shotDialog] open "${options.title ?? ''}" →`, filePaths.join(', '));
+ return { canceled: false, filePaths };
+ }
+ return dialog.showOpenDialog(win, options);
+}
+
+/** Show a save dialog, or hand back what the shot scripted. */
+export async function showSaveDialog(
+ win: BrowserWindow,
+ options: SaveDialogOptions,
+): Promise<{ canceled: boolean; filePath?: string }> {
+ if (shotMode()) {
+ const scripted = nextSave();
+ if (scripted === undefined) {
+ console.log(`[shotDialog] save "${options.title ?? ''}" — nothing scripted (set ESTELLA_SHOT_SAVE_FILE); returning cancelled`);
+ return { canceled: true };
+ }
+ const filePath = Array.isArray(scripted) ? scripted[0] : scripted;
+ console.log(`[shotDialog] save "${options.title ?? ''}" →`, filePath);
+ return { canceled: false, filePath };
+ }
+ return dialog.showSaveDialog(win, options);
+}
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index ec4c5caa9..bc0d6eeb9 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -31,6 +31,7 @@ import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
import { Toasts } from '@/store/Toasts';
import { confirm } from '@/components/confirm';
+import { requestPluginPanelAction } from '@/plugins/panelActions';
import { t } from '@/i18n';
import type { ToolMode } from '@/types';
@@ -361,6 +362,26 @@ commands.register({
// command is how it's reached — palette, Window menu, and rebindable like any other.
run: () => dockApi.openPanel('plugins'),
});
+commands.register({
+ id: 'plugins.new',
+ label: t('plug.new'),
+ category: t('cat.view'),
+ // Opens the panel first: the dialog belongs to it, and a request with nothing
+ // listening is dropped rather than queued.
+ run: () => {
+ dockApi.openPanel('plugins');
+ requestPluginPanelAction('new');
+ },
+});
+commands.register({
+ id: 'plugins.import',
+ label: t('plug.importTitle'),
+ category: t('cat.view'),
+ run: () => {
+ dockApi.openPanel('plugins');
+ requestPluginPanelAction('import');
+ },
+});
commands.register({
id: 'view.resetLayout',
label: t('menu.resetLayout'),
diff --git a/desktop/src/components/ImportPluginDialog.tsx b/desktop/src/components/ImportPluginDialog.tsx
new file mode 100644
index 000000000..fd2251384
--- /dev/null
+++ b/desktop/src/components/ImportPluginDialog.tsx
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ImportPluginDialog — see what is in a `.esplugin` before it lands.
+ *
+ * The whole reason this is a dialog and not a one-click action: a package is a file
+ * someone handed you, and the moment to look at it is BEFORE it is on disk. Main
+ * reads the archive's central directory without inflating anything, so what is
+ * shown here — the manifest, the declared capabilities, the file list — costs
+ * nothing and commits to nothing.
+ *
+ * Installing does NOT approve. The plugin lands needing trust, exactly as a folder
+ * copied in by hand would; deciding it is safe stays one separate, deliberate act
+ * in the panel.
+ */
+import { useEffect, useRef, useState } from 'react';
+import { AlertCircle, Download, FileArchive, ShieldAlert } from 'lucide-react';
+import { Modal } from '@/components/Modal';
+import { Button } from '@/components/Button';
+import { Segmented } from '@/components/Segmented';
+import { PluginHost } from '@/plugins/PluginHost';
+import { ProjectStore } from '@/project/ProjectStore';
+import { Toasts } from '@/store/Toasts';
+import { t, type MsgKey } from '@/i18n';
+
+type Scope = 'project' | 'user';
+
+const CAPABILITY_LABEL: Record<string, MsgKey> = {
+ 'fs:project': 'plug.cap.fsProject',
+ net: 'plug.cap.net',
+ shell: 'plug.cap.shell',
+ process: 'plug.cap.process',
+};
+
+type Picked = Awaited<ReturnType<typeof window.estella.plugins.pickPackage>>;
+
+const kb = (n: number): string => (n < 1024 ? `${n} B` : `${Math.round(n / 1024)} KB`);
+
+export function ImportPluginDialog({ onClose }: { onClose: () => void }) {
+ const hasProject = ProjectStore.getSnapshot() !== null;
+ const [scope, setScope] = useState<Scope>(hasProject ? 'project' : 'user');
+ const [picked, setPicked] = useState<Picked | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Held in a ref so the picker effect below can depend on NOTHING. `onClose` is a
+ // fresh closure on every parent render, and listing it as a dependency re-ran the
+ // effect — which opened a second OS file dialog behind the first one.
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
+
+ // Opening this dialog IS the file picker — there is nothing to show until one is
+ // chosen, and a dialog whose only content is a "Choose file" button is a step.
+ // Runs exactly once per mount: showing a native dialog is not a repeatable effect.
+ useEffect(() => {
+ let alive = true;
+ void (async () => {
+ const result = await window.estella.plugins.pickPackage();
+ if (!alive) return;
+ if (result.canceled) {
+ onCloseRef.current();
+ return;
+ }
+ setPicked(result);
+ })();
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ const install = async () => {
+ if (!picked?.file) return;
+ setBusy(true);
+ setError(null);
+ const result = await window.estella.plugins.installPackage(picked.file, scope);
+ if (!result.ok) {
+ setError(result.error ?? 'could not install the package');
+ setBusy(false);
+ return;
+ }
+ await PluginHost.refresh();
+ Toasts.push(t('plug.installed', { name: picked.name ?? result.id ?? '' }), 'success');
+ onClose();
+ };
+
+ if (!picked) return null;
+
+ const canInstall = picked.ok && !busy && (scope === 'user' || hasProject);
+
+ return (
+ <Modal
+ title={t('plug.importTitle')}
+ onClose={onClose}
+ width={500}
+ footer={(
+ <>
+ <Button onClick={onClose}>{t('ui.cancel')}</Button>
+ <Button variant="primary" disabled={!canInstall} onClick={() => void install()}>
+ <Download size={13} /> {t('plug.install')}
+ </Button>
+ </>
+ )}
+ >
+ <div className="npl">
+ {!picked.ok ? (
+ <div className="npl__hint is-error">
+ <AlertCircle size={12} strokeWidth={2} />
+ <span className="selectable">{picked.error}</span>
+ </div>
+ ) : (
+ <>
+ <div className="plug-pkg__head">
+ <FileArchive size={16} strokeWidth={2} />
+ <span className="plug-pkg__name">{picked.name}</span>
+ <span className="plug-row__version">{picked.manifest?.version}</span>
+ </div>
+
+ {/* Capabilities shown HERE, not only at the trust gate — the decision to
+ put something on disk deserves the same disclosure as running it. */}
+ <div className="plug-trust__caps">
+ <span className="plug-trust__capsLabel">{t('plug.capabilities')}:</span>
+ {picked.capabilities?.length === 0 ? (
+ <span className="plug-muted">{t('plug.noCapabilities')}</span>
+ ) : (
+ picked.capabilities?.map((c) => (
+ <span key={c} className="plug-cap">{CAPABILITY_LABEL[c] ? t(CAPABILITY_LABEL[c]) : c}</span>
+ ))
+ )}
+ </div>
+
+ <div className="npl__row">
+ <span className="npl__label">{t('plug.field.scope')}</span>
+ <Segmented
+ value={scope}
+ onChange={setScope}
+ ariaLabel={t('plug.field.scope')}
+ options={[
+ { value: 'project', label: t('plug.scope.project') },
+ { value: 'user', label: t('plug.scope.user') },
+ ]}
+ />
+ </div>
+ {scope === 'project' && !hasProject && (
+ <div className="npl__hint is-error">{t('plug.needProject')}</div>
+ )}
+
+ <div className="plug-pkg__files">
+ <span className="npl__label">{t('plug.packageContents', { n: picked.files?.length ?? 0 })}</span>
+ <ul className="plug-pkg__list">
+ {picked.files?.map((f) => (
+ <li key={f.name}>
+ <span className="plug-pkg__file selectable">{f.name}</span>
+ <span className="plug-pkg__size">{kb(f.size)}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+
+ <div className="npl__hint">
+ <ShieldAlert size={12} strokeWidth={2} />
+ {t('plug.installUntrusted')}
+ </div>
+ </>
+ )}
+
+ {error && (
+ <div className="npl__hint is-error">
+ <AlertCircle size={12} strokeWidth={2} /> <span className="selectable">{error}</span>
+ </div>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/desktop/src/components/NewPluginDialog.tsx b/desktop/src/components/NewPluginDialog.tsx
new file mode 100644
index 000000000..99aa981be
--- /dev/null
+++ b/desktop/src/components/NewPluginDialog.tsx
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NewPluginDialog — create a plugin the editor can already run.
+ *
+ * The id is validated HERE with the same function the manifest reader uses, so the
+ * dialog can never accept a name the loader would later reject — the failure a
+ * scaffolder exists to prevent.
+ *
+ * Two things this hands main that main deliberately does not read for itself: the
+ * editor version (the constant that ENFORCES the `engines.editor` check) and the
+ * plugin API typings text. Both come from the renderer because the renderer is
+ * where the enforcing copy lives — generating against anything else is how a
+ * scaffold ends up born `incompatible`.
+ *
+ * The result is TRUSTED on creation. Trust exists to gate code you did not write;
+ * this is code the editor just wrote at your request, and leaving it sitting behind
+ * a "needs trust" prompt would ask the user to vouch for the editor's own template.
+ */
+import { useState } from 'react';
+import { Plus, AlertCircle } from 'lucide-react';
+import { Modal } from '@/components/Modal';
+import { Button } from '@/components/Button';
+import { Segmented } from '@/components/Segmented';
+import { PluginHost } from '@/plugins/PluginHost';
+import { pluginIdProblem } from '@/plugins/manifest';
+import { ProjectStore } from '@/project/ProjectStore';
+import { Toasts } from '@/store/Toasts';
+import { version as EDITOR_VERSION } from '../../package.json';
+// The same text init.ts writes as the project's typings sidecar — see types.ts,
+// which is import-free precisely so it can double as the shipped `.d.ts`.
+import editorApiTypes from '@/plugins/types.ts?raw';
+import { t, type MsgKey } from '@/i18n';
+
+type Scope = 'project' | 'user';
+type Sample = 'command' | 'panel' | 'inspector' | 'overlay' | 'tool';
+
+const SAMPLES: { id: Sample; label: MsgKey }[] = [
+ { id: 'command', label: 'plug.contrib.command' },
+ { id: 'panel', label: 'plug.contrib.panel' },
+ { id: 'inspector', label: 'plug.contrib.inspector' },
+ { id: 'overlay', label: 'plug.contrib.overlay' },
+ { id: 'tool', label: 'plug.contrib.tool' },
+];
+
+/** `Level Tools` → `level-tools`: a sensible id half, so most users type one field. */
+const slug = (s: string): string =>
+ s.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
+
+export function NewPluginDialog({ onClose }: { onClose: () => void }) {
+ const hasProject = ProjectStore.getSnapshot() !== null;
+ const [scope, setScope] = useState<Scope>(hasProject ? 'project' : 'user');
+ const [name, setName] = useState('');
+ // Kept separately from `name` so typing a name suggests an id, but editing the id
+ // stops the suggestion from overwriting the user's own choice.
+ const [id, setId] = useState('');
+ const [idTouched, setIdTouched] = useState(false);
+ const [samples, setSamples] = useState<Sample[]>(['command']);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const effectiveId = idTouched ? id : name.trim() ? `my.${slug(name)}` : '';
+ const idProblem = effectiveId ? pluginIdProblem(effectiveId) : null;
+ const canCreate =
+ !busy && name.trim() !== '' && !!effectiveId && !idProblem && (scope === 'user' || hasProject);
+
+ const toggle = (s: Sample) =>
+ setSamples((prev) => (prev.includes(s) ? prev.filter((x) => x !== s) : [...prev, s]));
+
+ const create = async () => {
+ setBusy(true);
+ setError(null);
+ const result = await window.estella.plugins.scaffold(scope, {
+ id: effectiveId,
+ name: name.trim(),
+ contributions: samples,
+ editorVersion: EDITOR_VERSION,
+ apiTypes: editorApiTypes,
+ });
+ if (!result.ok) {
+ setError(result.error ?? 'could not create the plugin');
+ setBusy(false);
+ return;
+ }
+ // Approve before the first scan, so it comes up running rather than asking the
+ // user to vouch for a template the editor authored a moment ago.
+ await window.estella.plugins.trust(effectiveId);
+ await PluginHost.refresh();
+ Toasts.push(t('plug.created', { name: name.trim() }), 'success');
+ onClose();
+ };
+
+ return (
+ <Modal
+ title={t('plug.newTitle')}
+ onClose={onClose}
+ width={480}
+ footer={(
+ <>
+ <Button onClick={onClose}>{t('ui.cancel')}</Button>
+ <Button variant="primary" disabled={!canCreate} onClick={() => void create()}>
+ <Plus size={13} /> {t('plug.create')}
+ </Button>
+ </>
+ )}
+ >
+ <div className="npl">
+ <p className="npl__blurb">{t('plug.newBlurb')}</p>
+
+ <div className="npl__row">
+ <span className="npl__label">{t('plug.field.name')}</span>
+ <input
+ value={name}
+ spellCheck={false}
+ autoFocus
+ onChange={(e) => setName(e.target.value)}
+ />
+ </div>
+
+ <div className="npl__row">
+ <span className="npl__label" title={t('plug.field.idTip')}>{t('plug.field.id')}</span>
+ <input
+ value={effectiveId}
+ spellCheck={false}
+ onChange={(e) => {
+ setIdTouched(true);
+ setId(e.target.value);
+ }}
+ />
+ </div>
+ {idProblem && <div className="npl__hint is-error">{idProblem}</div>}
+
+ <div className="npl__row">
+ <span className="npl__label">{t('plug.field.scope')}</span>
+ <Segmented
+ value={scope}
+ onChange={setScope}
+ ariaLabel={t('plug.field.scope')}
+ options={[
+ { value: 'project', label: t('plug.scope.project') },
+ { value: 'user', label: t('plug.scope.user') },
+ ]}
+ />
+ </div>
+ <div className="npl__hint">
+ {scope === 'project' ? t('plug.scope.projectHint') : t('plug.scope.userHint')}
+ </div>
+ {scope === 'project' && !hasProject && (
+ <div className="npl__hint is-error">{t('plug.needProject')}</div>
+ )}
+
+ <div className="npl__samples">
+ <span className="npl__label">{t('plug.samples')}</span>
+ <div className="npl__checks">
+ {SAMPLES.map((s) => (
+ <label key={s.id} className="npl__check">
+ <input type="checkbox" checked={samples.includes(s.id)} onChange={() => toggle(s.id)} />
+ {t(s.label)}
+ </label>
+ ))}
+ </div>
+ <div className="npl__hint">{t('plug.samplesHint')}</div>
+ </div>
+
+ {error && (
+ <div className="npl__hint is-error">
+ <AlertCircle size={12} strokeWidth={2} /> <span className="selectable">{error}</span>
+ </div>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/desktop/src/i18n/messages/plugins.ts b/desktop/src/i18n/messages/plugins.ts
index 76fe9b1d6..2bee747a8 100644
--- a/desktop/src/i18n/messages/plugins.ts
+++ b/desktop/src/i18n/messages/plugins.ts
@@ -12,8 +12,8 @@ export const pluginMessages = defineMessages({
'plug.panelTitle': { en: 'Plugins', zh: '插件' },
'plug.emptyTitle': { en: 'No plugins', zh: '没有插件' },
'plug.emptyHint': {
- en: 'Drop a plugin folder into .esengine/plugins/ in this project, then Refresh.',
- zh: '把插件文件夹放进本项目的 .esengine/plugins/,然后点刷新。',
+ en: 'Create one, or import an .esplugin you were sent. A folder dropped into .esengine/plugins/ shows up on Refresh.',
+ zh: '新建一个,或导入别人给你的 .esplugin。手动放进 .esengine/plugins/ 的文件夹,点刷新也会出现。',
},
'plug.noProjectHint': { en: 'Open a project to see its plugins.', zh: '打开一个项目以查看它的插件。' },
'plug.refresh': { en: 'Refresh', zh: '刷新' },
@@ -62,4 +62,68 @@ export const pluginMessages = defineMessages({
},
'plug.errorCount': { en: '{n} error(s) this session', zh: '本次会话 {n} 个错误' },
'plug.contributes': { en: 'Contributes', zh: '贡献' },
+ 'plug.contributesNone': {
+ en: 'Nothing registered — this plugin is running but added no commands, panels or tools.',
+ zh: '什么都没注册 —— 插件在运行,但没有添加任何命令、面板或工具。',
+ },
+ 'plug.kind.command': { en: 'Command', zh: '命令' },
+ 'plug.kind.panel': { en: 'Panel', zh: '面板' },
+ 'plug.kind.setting': { en: 'Setting', zh: '设置项' },
+ 'plug.kind.tool': { en: 'Tool', zh: '工具' },
+ 'plug.kind.overlay': { en: 'Gizmo', zh: 'Gizmo' },
+ 'plug.kind.inspector': { en: 'Inspector', zh: '检视器' },
+ 'plug.kind.assetType': { en: 'Asset type', zh: '资产类型' },
+ 'plug.kind.entityTemplate': { en: 'Entity', zh: '实体' },
+ 'plug.kind.contextMenu': { en: 'Menu item', zh: '菜单项' },
+
+ // — New plugin. The editor writes the folder because the SHAPE of a plugin is
+ // the part that is hard to know before you have seen one. —
+ 'plug.new': { en: 'New plugin', zh: '新建插件' },
+ 'plug.newTitle': { en: 'New plugin', zh: '新建插件' },
+ 'plug.newBlurb': {
+ en: 'Writes the manifest, an entry file, and a tsconfig that already resolves the editor API.',
+ zh: '写好清单、入口文件,以及一份已经能解析编辑器 API 的 tsconfig。',
+ },
+ 'plug.field.id': { en: 'Id', zh: '标识' },
+ 'plug.field.idTip': {
+ en: 'Dotted and lowercase, e.g. acme.level-tools — also the folder name.',
+ zh: '点分小写,如 acme.level-tools —— 同时也是文件夹名。',
+ },
+ 'plug.field.name': { en: 'Name', zh: '名称' },
+ 'plug.field.scope': { en: 'Install to', zh: '安装到' },
+ 'plug.scope.projectHint': {
+ en: 'In this project, versioned with it and shared by the team.',
+ zh: '放在本项目里,随项目版本管理,团队共享。',
+ },
+ 'plug.scope.userHint': {
+ en: 'Personal, available across every project you open.',
+ zh: '个人插件,在你打开的每个项目里都可用。',
+ },
+ 'plug.needProject': { en: 'Open a project to install into it.', zh: '打开一个项目才能装进项目里。' },
+ 'plug.samples': { en: 'Start from', zh: '起始样例' },
+ 'plug.samplesHint': {
+ en: 'Each one is a working example you can edit or delete.',
+ zh: '每一项都是可运行的例子,可以随意修改或删掉。',
+ },
+ 'plug.contrib.command': { en: 'Command', zh: '命令' },
+ 'plug.contrib.panel': { en: 'Panel', zh: '面板' },
+ 'plug.contrib.inspector': { en: 'Inspector section', zh: '检视器分区' },
+ 'plug.contrib.overlay': { en: 'Viewport gizmo', zh: '视口 gizmo' },
+ 'plug.contrib.tool': { en: 'Viewport tool', zh: '视口工具' },
+ 'plug.create': { en: 'Create', zh: '创建' },
+ 'plug.created': { en: 'Created {name} — it is running now.', zh: '已创建 {name} —— 现在已在运行。' },
+
+ // — Packaging. One `.esplugin` file (a ZIP) you can hand to someone. —
+ 'plug.export': { en: 'Export', zh: '导出' },
+ 'plug.exportTip': { en: 'Pack this plugin into one .esplugin file', zh: '把这个插件打包成一个 .esplugin 文件' },
+ 'plug.exported': { en: 'Exported to {file}', zh: '已导出到 {file}' },
+ 'plug.import': { en: 'Import', zh: '导入' },
+ 'plug.importTitle': { en: 'Install plugin', zh: '安装插件' },
+ 'plug.install': { en: 'Install', zh: '安装' },
+ 'plug.installed': { en: 'Installed {name}. Trust it to load it.', zh: '已安装 {name}。信任后才会加载。' },
+ 'plug.packageContents': { en: 'Contents ({n} files)', zh: '包内文件({n} 个)' },
+ 'plug.installUntrusted': {
+ en: 'Installing does not run it — it will wait for your approval.',
+ zh: '安装不等于运行 —— 它会等待你的批准。',
+ },
});
diff --git a/desktop/src/panels/PluginsPanel.tsx b/desktop/src/panels/PluginsPanel.tsx
index 59519779e..ed6695f7e 100644
--- a/desktop/src/panels/PluginsPanel.tsx
+++ b/desktop/src/panels/PluginsPanel.tsx
@@ -12,10 +12,18 @@
* realm, so nothing loads until the user has approved it — the row states that
* plainly rather than dressing it up as a formality.
*/
-import { useEffect, useSyncExternalStore } from 'react';
-import { AlertTriangle, FolderOpen, Plug, Power, RefreshCw, RotateCw, ShieldCheck, ShieldX } from 'lucide-react';
+import { useEffect, useState, useSyncExternalStore } from 'react';
+import {
+ AlertTriangle, ChevronDown, ChevronRight, Download, FolderOpen, Plug, Plus, Power, RefreshCw,
+ RotateCw, ShieldCheck, ShieldX, Upload,
+} from 'lucide-react';
import { EmptyState } from '@/components/EmptyState';
+import { NewPluginDialog } from '@/components/NewPluginDialog';
+import { ImportPluginDialog } from '@/components/ImportPluginDialog';
+import { Toasts } from '@/store/Toasts';
import { PluginHost, type PluginPhase, type PluginRecord } from '@/plugins/PluginHost';
+import type { ContributionKind } from '@/plugins/context';
+import { subscribePluginPanelActions } from '@/plugins/panelActions';
import { ProjectStore } from '@/project/ProjectStore';
import { t, type MsgKey } from '@/i18n';
@@ -38,10 +46,59 @@ const CAPABILITY_LABEL: Record<string, MsgKey> = {
process: 'plug.cap.process',
};
+const KIND_LABEL: Record<ContributionKind, MsgKey> = {
+ command: 'plug.kind.command',
+ panel: 'plug.kind.panel',
+ setting: 'plug.kind.setting',
+ tool: 'plug.kind.tool',
+ overlay: 'plug.kind.overlay',
+ inspector: 'plug.kind.inspector',
+ assetType: 'plug.kind.assetType',
+ entityTemplate: 'plug.kind.entityTemplate',
+ contextMenu: 'plug.kind.contextMenu',
+};
+
function PhaseChip({ phase }: { phase: PluginPhase }) {
return <span className={`plug-chip is-${phase}`}>{t(PHASE_LABEL[phase])}</span>;
}
+/**
+ * What a plugin actually added. Read on expand rather than held on the record, so
+ * it reflects the moment you asked — including registrations a plugin made long
+ * after activating. This is the panel's answer to "why isn't my panel showing up?",
+ * so an ACTIVE plugin that contributed nothing says so explicitly rather than
+ * rendering an empty box that reads like a loading state.
+ */
+function Contributes({ record }: { record: PluginRecord }) {
+ const [open, setOpen] = useState(false);
+ if (record.phase !== 'active' || record.kind !== 'plugin') return null;
+ const items = open ? PluginHost.contributionsOf(record.id) : [];
+ const Chevron = open ? ChevronDown : ChevronRight;
+ return (
+ <div className="plug-contrib">
+ <button type="button" className="plug-contrib__toggle" onClick={() => setOpen((v) => !v)}>
+ <Chevron size={12} strokeWidth={2} />
+ {t('plug.contributes')}
+ </button>
+ {open && (
+ items.length === 0 ? (
+ <div className="plug-muted plug-contrib__empty">{t('plug.contributesNone')}</div>
+ ) : (
+ <ul className="plug-contrib__list">
+ {items.map((c) => (
+ <li key={`${c.kind}:${c.id}`} className="plug-contrib__item">
+ <span className="plug-contrib__kind">{t(KIND_LABEL[c.kind])}</span>
+ {c.label && <span className="plug-contrib__label">{c.label}</span>}
+ <span className="plug-contrib__id selectable">{c.id}</span>
+ </li>
+ ))}
+ </ul>
+ )
+ )}
+ </div>
+ );
+}
+
/** The trust gate: what loading means, what the plugin declared, and one decision. */
function TrustGate({ record }: { record: PluginRecord }) {
return (
@@ -72,6 +129,18 @@ function TrustGate({ record }: { record: PluginRecord }) {
);
}
+/** Pack one plugin into a file. Cancelling the save dialog is not a failure and
+ * must not toast — the user changed their mind, which is not news. */
+async function exportPlugin(id: string): Promise<void> {
+ const result = await window.estella.plugins.exportPackage(id);
+ if (result.canceled) return;
+ if (!result.ok) {
+ Toasts.push(result.error ?? 'export failed', 'error');
+ return;
+ }
+ Toasts.push(t('plug.exported', { file: result.file ?? '' }), 'success');
+}
+
function PluginRow({ record }: { record: PluginRecord }) {
const canToggle = record.phase !== 'shadowed';
const isDisabled = record.phase === 'disabled';
@@ -101,6 +170,7 @@ function PluginRow({ record }: { record: PluginRecord }) {
<div className="plug-row__detail">{t('plug.errorCount', { n: record.errorCount })}</div>
)}
{record.phase === 'needs-trust' && <TrustGate record={record} />}
+ <Contributes record={record} />
<div className="plug-row__actions">
<button type="button" className="btn-soft" title={t('plug.reloadTip')} onClick={() => void PluginHost.reload(record.id)}>
<RotateCw size={12} strokeWidth={2} />
@@ -122,6 +192,12 @@ function PluginRow({ record }: { record: PluginRecord }) {
{t('plug.revokeTrust')}
</button>
)}
+ {record.kind === 'plugin' && (
+ <button type="button" className="btn-soft" title={t('plug.exportTip')} onClick={() => void exportPlugin(record.id)}>
+ <Upload size={12} strokeWidth={2} />
+ {t('plug.export')}
+ </button>
+ )}
<button type="button" className="btn-soft" onClick={() => void window.estella.plugins.reveal(record.id)}>
<FolderOpen size={12} strokeWidth={2} />
{t('plug.reveal')}
@@ -134,6 +210,8 @@ function PluginRow({ record }: { record: PluginRecord }) {
export function PluginsPanel() {
const records = useSyncExternalStore(PluginHost.subscribe, PluginHost.getSnapshot);
const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);
+ const [creating, setCreating] = useState(false);
+ const [importing, setImporting] = useState(false);
// The panel may be opened before anything scanned (a fresh layout), so make
// opening it a scan — the list is never mysteriously empty.
@@ -141,34 +219,67 @@ export function PluginsPanel() {
void PluginHost.refresh();
}, []);
- if (records.length === 0) {
- return (
- <EmptyState
- icon={Plug}
- title={t('plug.emptyTitle')}
- hint={project ? t('plug.emptyHint') : t('plug.noProjectHint')}
- >
- <button type="button" className="btn-soft" onClick={() => void PluginHost.refresh()}>
- <RefreshCw size={12} strokeWidth={2} />
- {t('plug.refresh')}
- </button>
- </EmptyState>
- );
- }
+ // The New / Import commands open this panel and then ask it for the dialog.
+ useEffect(() => subscribePluginPanelActions((action) => {
+ if (action === 'new') setCreating(true);
+ else setImporting(true);
+ }), []);
+ // ONE root, and the dialogs always mount at the SAME position in it. An earlier
+ // version returned a separate tree for the empty state, which meant installing the
+ // first plugin (0 → 1 rows) swapped branches and REMOUNTED the open dialog — and a
+ // dialog whose mount effect opens a native file picker opened a second one.
+ const empty = records.length === 0;
return (
<div className="plug-panel">
- <div className="plug-toolbar">
- <button type="button" className="btn-soft" onClick={() => void PluginHost.refresh()}>
- <RefreshCw size={12} strokeWidth={2} />
- {t('plug.refresh')}
- </button>
- </div>
- <div className="plug-list">
- {records.map((r) => (
- <PluginRow key={r.id} record={r} />
- ))}
- </div>
+ {/* In the empty state the buttons live in the EmptyState itself, where the
+ eye already is; a toolbar above an empty box is a second place to look. */}
+ {!empty && (
+ <div className="plug-toolbar">
+ <button type="button" className="btn-soft" onClick={() => setCreating(true)}>
+ <Plus size={12} strokeWidth={2} />
+ {t('plug.new')}
+ </button>
+ <button type="button" className="btn-soft" onClick={() => setImporting(true)}>
+ <Download size={12} strokeWidth={2} />
+ {t('plug.import')}
+ </button>
+ <button type="button" className="btn-soft" onClick={() => void PluginHost.refresh()}>
+ <RefreshCw size={12} strokeWidth={2} />
+ {t('plug.refresh')}
+ </button>
+ </div>
+ )}
+
+ {empty ? (
+ <EmptyState
+ icon={Plug}
+ title={t('plug.emptyTitle')}
+ hint={project ? t('plug.emptyHint') : t('plug.noProjectHint')}
+ >
+ <button type="button" className="btn-soft is-primary" onClick={() => setCreating(true)}>
+ <Plus size={12} strokeWidth={2} />
+ {t('plug.new')}
+ </button>
+ <button type="button" className="btn-soft" onClick={() => setImporting(true)}>
+ <Download size={12} strokeWidth={2} />
+ {t('plug.import')}
+ </button>
+ <button type="button" className="btn-soft" onClick={() => void PluginHost.refresh()}>
+ <RefreshCw size={12} strokeWidth={2} />
+ {t('plug.refresh')}
+ </button>
+ </EmptyState>
+ ) : (
+ <div className="plug-list">
+ {records.map((r) => (
+ <PluginRow key={r.id} record={r} />
+ ))}
+ </div>
+ )}
+
+ {creating && <NewPluginDialog onClose={() => setCreating(false)} />}
+ {importing && <ImportPluginDialog onClose={() => setImporting(false)} />}
</div>
);
}
diff --git a/desktop/src/plugins/PluginHost.ts b/desktop/src/plugins/PluginHost.ts
index 1fdf9eab1..9c5fd6f2c 100644
--- a/desktop/src/plugins/PluginHost.ts
+++ b/desktop/src/plugins/PluginHost.ts
@@ -44,7 +44,7 @@ import { version as EDITOR_VERSION } from '../../package.json';
import type { Owner } from '@/contrib/ContributionRegistry';
import { resolveLocalized, satisfiesEditorRange, type PluginManifest } from './manifest';
import { evaluatePlugin } from './loader';
-import { buildPluginContext, type BuiltContext } from './context';
+import { buildPluginContext, type BuiltContext, type PluginContribution } from './context';
import type { EditorPlugin } from './types';
/** Where a plugin sits in its lifecycle — what the Plugins panel shows. */
@@ -393,6 +393,19 @@ class PluginHostImpl {
this.restorePanels(reopen);
}
+ /**
+ * What this plugin has registered, right now — the panel's answer to "my panel
+ * isn't showing up". Read live from the context rather than stored on the record:
+ * a plugin may register from a command or a timer well after activation, and a
+ * list that silently stopped tracking would mislead exactly when it's consulted.
+ *
+ * Empty for a plugin that isn't loaded (needs trust, failed, disabled) — which is
+ * itself the answer in those cases.
+ */
+ contributionsOf(id: string): PluginContribution[] {
+ return this.loaded.get(id)?.context.contributions() ?? [];
+ }
+
/** Unload everything (project close). Records are dropped with the project. */
async unloadAll(): Promise<void> {
for (const id of [...this.loaded.keys()]) await this.unload(id);
diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.ts
index f48db4ccc..25c6ae863 100644
--- a/desktop/src/plugins/context.ts
+++ b/desktop/src/plugins/context.ts
@@ -185,9 +185,37 @@ function editorEvents(track: (d: Disposable) => Disposable): EditorEvents {
};
}
+/** The contribution kinds a plugin can be listed as having made. */
+export type ContributionKind =
+ | 'command'
+ | 'panel'
+ | 'setting'
+ | 'tool'
+ | 'overlay'
+ | 'inspector'
+ | 'assetType'
+ | 'entityTemplate'
+ | 'contextMenu';
+
+/** One thing a plugin added, as the Plugins panel shows it. */
+export interface PluginContribution {
+ kind: ContributionKind;
+ /** The id it registered under — what appears in the command palette, the dock, … */
+ id: string;
+ /** Already localized, because the registries were handed a localized label too. */
+ label: string;
+}
+
/** What PluginHost needs back to tear a plugin down. */
export interface BuiltContext {
ctx: PluginContext;
+ /**
+ * What this plugin has contributed, RIGHT NOW. Read live rather than snapshotted
+ * because a plugin may register from a command or a timer long after `activate`
+ * returned, and a list that quietly stopped tracking would be worse than none —
+ * this panel's whole job is answering "why isn't my panel showing up?".
+ */
+ contributions(): PluginContribution[];
/** Retract everything this plugin registered, in reverse order. */
dispose(): void;
}
@@ -212,6 +240,24 @@ export function buildPluginContext(
};
const adopt = (d: CoreDisposable): Disposable => track({ dispose: () => d.dispose() });
+ // Every register() below goes through `noted`, which is what makes the panel's
+ // "Contributes" list complete by construction: there is no way to register
+ // something here without listing it, because listing IS the tracking.
+ // Takes an already-made registration, exactly as `adopt` does — so a call site
+ // reads the same and cannot accidentally defer the registration itself.
+ const contributions: PluginContribution[] = [];
+ const noted = (kind: ContributionKind, cid: string, label: string, d: CoreDisposable): Disposable => {
+ const entry: PluginContribution = { kind, id: cid, label };
+ contributions.push(entry);
+ return track({
+ dispose: () => {
+ const i = contributions.indexOf(entry);
+ if (i >= 0) contributions.splice(i, 1);
+ d.dispose();
+ },
+ });
+ };
+
const log = {
info: (...args: unknown[]) => LogStore.push('info', `plugin:${id}`, args.map(String).join(' ')),
warn: (...args: unknown[]) => LogStore.push('warn', `plugin:${id}`, args.map(String).join(' ')),
@@ -240,11 +286,14 @@ export function buildPluginContext(
registerMenuItem({ id: `${c.menu}/${c.id}`, location: c.menu, group: c.menu === 'tools' ? 'tools' : 'plugins', command: c.id }, owner),
);
}
- return track({ dispose: () => disposals.forEach((d) => d.dispose()) });
+ return noted('command', c.id, localize(c.title), { dispose: () => disposals.forEach((d) => d.dispose()) });
};
const registerPluginPanel = (p: PanelContribution): Disposable =>
- adopt(
+ noted(
+ 'panel',
+ p.id,
+ localize(p.title),
registerPanel(
{
id: p.id,
@@ -274,11 +323,14 @@ export function buildPluginContext(
: s.type === 'string'
? { ...base, type: 'string' as const, default: s.default, placeholder: s.placeholder }
: { ...base, type: 'boolean' as const, default: s.default };
- return adopt(settingsRegistry.register(descriptor, owner));
+ return noted('setting', s.id, localize(s.label), settingsRegistry.register(descriptor, owner));
};
const registerTool = (tool: ToolContribution): Disposable =>
- adopt(
+ noted(
+ 'tool',
+ tool.id,
+ localize(tool.title),
toolRegistry.register(owner, {
id: tool.id,
title: localize(tool.title),
@@ -302,13 +354,23 @@ export function buildPluginContext(
const registerOverlay = (overlay: OverlayContribution): Disposable =>
// Not guarded here: the overlay renderer's rAF calls PluginHost.guardOverlay
// itself, so a per-frame throw is attributed once, at the frame boundary.
- adopt(overlayRegistry.register(owner, overlay));
+ // No label: an overlay has no title of its own, and repeating the id in the
+ // label column would just print it twice on the same row.
+ noted('overlay', overlay.id, '', overlayRegistry.register(owner, overlay));
const registerInspector = (section: InspectorContribution): Disposable =>
- adopt(inspectorRegistry.register(owner, { ...section, id: `${id}.${section.id}` }));
+ noted(
+ 'inspector',
+ `${id}.${section.id}`,
+ localize(section.title),
+ inspectorRegistry.register(owner, { ...section, id: `${id}.${section.id}` }),
+ );
const registerAssetType = (type: AssetTypeContribution): Disposable =>
- adopt(
+ noted(
+ 'assetType',
+ type.id,
+ type.extensions.map((e) => `.${e}`).join(' '),
assetTypeRegistry.register(owner, {
id: type.id,
extensions: type.extensions,
@@ -326,7 +388,10 @@ export function buildPluginContext(
);
const registerTemplate = (template: EntityTemplateContribution): Disposable =>
- adopt(
+ noted(
+ 'entityTemplate',
+ template.id,
+ localize(template.label),
entitySourceRegistry.register(owner, {
id: template.id,
label: localize(template.label),
@@ -340,7 +405,10 @@ export function buildPluginContext(
);
const registerContextMenuItem = (item: ContextMenuContribution): Disposable =>
- adopt(
+ noted(
+ 'contextMenu',
+ item.id,
+ localize(item.label),
contextMenuRegistry.register(owner, {
...item,
// A plain string is itself a LocalizedString, so resolving it here means
@@ -386,6 +454,7 @@ export function buildPluginContext(
return {
ctx,
+ contributions: () => [...contributions],
dispose() {
// The plugin's own subscriptions first (they may reference contributions),
// then ours in reverse registration order.
diff --git a/desktop/src/plugins/manifest.ts b/desktop/src/plugins/manifest.ts
index 0cfe8f936..3803bb2d0 100644
--- a/desktop/src/plugins/manifest.ts
+++ b/desktop/src/plugins/manifest.ts
@@ -51,6 +51,18 @@ export function resolveLocalized(value: LocalizedString | undefined, locale: str
/** Ids must be filesystem- and namespace-safe, and readable in a command palette. */
const ID_RE = /^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/;
+/**
+ * Why this id is unusable, or null if it is fine. Exported because the scaffolder
+ * must reject a bad id BEFORE writing a folder — validating with the same function
+ * that later reads the manifest is what keeps "the editor let me create it" and
+ * "the editor accepts it" from ever disagreeing.
+ */
+export function pluginIdProblem(id: unknown): string | null {
+ if (typeof id !== 'string' || id.length === 0) return 'plugin needs an `id`';
+ if (!ID_RE.test(id)) return '`id` must be a dotted, lowercase name like "acme.level-tools"';
+ return null;
+}
+
const isLocalized = (v: unknown): boolean =>
typeof v === 'string'
? v.length > 0
@@ -64,9 +76,8 @@ export function validateManifest(raw: unknown): { manifest: PluginManifest } | {
if (!raw || typeof raw !== 'object') return { error: 'plugin.json must contain a JSON object' };
const m = raw as Record<string, unknown>;
- if (typeof m.id !== 'string' || !ID_RE.test(m.id)) {
- return { error: '`id` must be a dotted, lowercase name like "acme.level-tools"' };
- }
+ const idBad = pluginIdProblem(m.id);
+ if (idBad) return { error: idBad };
if (!isLocalized(m.name)) {
return { error: '`name` must be a non-empty string, or an object with an `en` string' };
}
diff --git a/desktop/src/plugins/panelActions.ts b/desktop/src/plugins/panelActions.ts
new file mode 100644
index 000000000..1b53f38b6
--- /dev/null
+++ b/desktop/src/plugins/panelActions.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file panelActions.ts — a way for a command to ask the Plugins panel to open one
+ * of its dialogs.
+ *
+ * The dialogs are the panel's own UI state, and hoisting them into a store just so
+ * a command could reach them would put editor-wide state behind two booleans that
+ * only one component reads. This is the smaller shape: the command names an intent,
+ * the panel performs it.
+ *
+ * A request made with nothing listening is HELD, not dropped. The commands open the
+ * panel and then ask — but `openPanel` only schedules the dock change, so on the
+ * first invocation the panel mounts a render later and a dropped request means the
+ * command visibly does nothing. The held request is consumed by the next subscriber
+ * and cleared, and it expires, so a panel mounted much later for its own reasons
+ * never inherits a dialog nobody asked for.
+ */
+export type PluginPanelAction = 'new' | 'import';
+
+/** How long a request waits for the panel to mount. Generous next to a React
+ * render, far short of "the user opened this panel themselves later". */
+const PENDING_TTL_MS = 5000;
+
+const listeners = new Set<(action: PluginPanelAction) => void>();
+let pending: { action: PluginPanelAction; at: number } | null = null;
+
+export function subscribePluginPanelActions(fn: (action: PluginPanelAction) => void): () => void {
+ listeners.add(fn);
+ if (pending && Date.now() - pending.at < PENDING_TTL_MS) {
+ const { action } = pending;
+ pending = null;
+ fn(action);
+ } else {
+ pending = null;
+ }
+ return () => listeners.delete(fn);
+}
+
+export function requestPluginPanelAction(action: PluginPanelAction): void {
+ if (listeners.size === 0) {
+ pending = { action, at: Date.now() };
+ return;
+ }
+ for (const fn of listeners) fn(action);
+}
diff --git a/desktop/src/theme/plugins.css b/desktop/src/theme/plugins.css
index 9d6594e72..7a5831e1e 100644
--- a/desktop/src/theme/plugins.css
+++ b/desktop/src/theme/plugins.css
@@ -37,6 +37,61 @@
.plug-muted { font-size: var(--fs-2xs); color: var(--text-faint); line-height: 1.5; margin: 0; }
.plug-trust .btn-soft { align-self: flex-start; margin-top: 2px; }
+/* Contribution inventory — what this plugin actually added. Collapsed by default:
+ it is a debugging answer, not a description, so it stays out of the way until
+ asked for. The id is monospaced and selectable because copying it into the
+ command palette is the usual next step. */
+.plug-contrib { display: flex; flex-direction: column; gap: 4px; }
+.plug-contrib__toggle {
+ display: flex; align-items: center; gap: 4px; align-self: flex-start;
+ padding: 0; background: none; border: 0; cursor: pointer;
+ font-size: var(--fs-2xs); color: var(--text-dim);
+}
+.plug-contrib__toggle:hover { color: var(--text-hi); }
+.plug-contrib__empty { padding-left: 16px; }
+.plug-contrib__list { display: flex; flex-direction: column; gap: 3px; margin: 0; padding: 2px 0 2px 16px; list-style: none; }
+.plug-contrib__item { display: flex; align-items: baseline; gap: 7px; font-size: var(--fs-2xs); }
+.plug-contrib__kind { flex: none; min-width: 66px; color: var(--text-faint); }
+.plug-contrib__label { color: var(--text); }
+.plug-contrib__id { margin-left: auto; font-family: var(--mono); color: var(--text-faint); }
+
+/* Package preview. The file list is bounded and scrolls: a package with a hundred
+ entries must not push the install button off the dialog. */
+.plug-pkg__head { display: flex; align-items: center; gap: 7px; }
+.plug-pkg__name { font-size: var(--fs-sm); font-weight: 600; color: var(--text-hi); }
+.plug-pkg__files { display: flex; flex-direction: column; gap: 4px; }
+.plug-pkg__list {
+ display: flex; flex-direction: column; gap: 2px;
+ max-height: 168px; overflow-y: auto;
+ margin: 0; padding: 6px 8px; list-style: none;
+ background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-sm);
+}
+.plug-pkg__list li { display: flex; align-items: baseline; gap: 10px; font-size: var(--fs-2xs); }
+.plug-pkg__file { font-family: var(--mono); color: var(--text-dim); word-break: break-all; }
+.plug-pkg__size { margin-left: auto; flex: none; color: var(--text-faint); }
+
+/* New-plugin dialog. Label/field rows on one column so the hints sit directly
+ under the control they qualify, rather than in a second column that would push
+ the fields around as the text changes length. */
+.npl { display: flex; flex-direction: column; gap: 10px; }
+.npl__blurb { font-size: var(--fs-2xs); color: var(--text-dim); line-height: 1.55; margin: 0; }
+.npl__row { display: grid; grid-template-columns: 84px 1fr; align-items: center; gap: 8px; }
+.npl__label { font-size: var(--fs-xs); color: var(--text-dim); }
+.npl__row input[type='text'], .npl__row input:not([type]) {
+ width: 100%; padding: 4px 7px;
+ background: var(--srf-2); color: var(--text);
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ font-size: var(--fs-xs); font-family: var(--font-ui);
+}
+.npl__row input:focus { outline: none; border-color: var(--acc); }
+.npl__hint { display: flex; align-items: center; gap: 5px; font-size: var(--fs-2xs); color: var(--text-faint); line-height: 1.5; margin-left: 92px; }
+.npl__hint.is-error { color: #e0736a; }
+.npl__samples { display: flex; flex-direction: column; gap: 6px; padding-top: 4px; border-top: 1px solid var(--border); }
+.npl__samples .npl__hint { margin-left: 0; }
+.npl__checks { display: flex; flex-wrap: wrap; gap: 6px 14px; }
+.npl__check { display: flex; align-items: center; gap: 5px; font-size: var(--fs-xs); color: var(--text); cursor: pointer; }
+.npl__check input { accent-color: var(--acc); }
+
/* A contributed panel's host element. The plugin owns everything inside; the frame
only guarantees it fills the tab and scrolls, and that the theme tokens are in
scope so a plugin styling against them matches the editor. */
diff --git a/desktop/tests/plugin-inventory.test.ts b/desktop/tests/plugin-inventory.test.ts
new file mode 100644
index 000000000..e44f7e748
--- /dev/null
+++ b/desktop/tests/plugin-inventory.test.ts
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The contribution inventory the Plugins panel shows.
+ *
+ * The claim being tested is "complete by construction": a plugin cannot register
+ * something without it appearing in the list, because listing happens at the same
+ * single door the registration goes through. A kind that grows a new register()
+ * path and forgets to list it is exactly the regression this catches — the panel
+ * would keep answering "why isn't my panel showing up?" with a lie of omission.
+ *
+ * The other half is retraction. A disposed contribution has to leave the list, or
+ * the panel advertises something the editor no longer has.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { buildPluginContext, type ContributionKind } from '@/plugins/context';
+import type { PluginManifest } from '@/plugins/manifest';
+import type { PluginContext } from '@/plugins/types';
+
+const MANIFEST: PluginManifest = {
+ id: 'acme.tools',
+ name: 'Acme Tools',
+ version: '1.0.0',
+ main: { editor: 'src/editor.ts' },
+};
+
+const OWNER = 'plugin:acme.tools' as const;
+
+// The context's `guard` is PluginHost's policy; here it only has to call through.
+const guard = <T,>(_what: string, fn: () => T): T => fn();
+
+let built: ReturnType<typeof buildPluginContext> | null = null;
+
+const build = () => {
+ built = buildPluginContext(MANIFEST, '/tmp/acme.tools', OWNER, guard);
+ return built;
+};
+
+afterEach(() => {
+ built?.dispose();
+ built = null;
+});
+
+/** Register one of every kind, and hand back the disposables by kind. */
+function registerAll(ctx: PluginContext): Record<string, { dispose(): void }> {
+ return {
+ command: ctx.commands.register({ id: 'acme.hello', title: 'Say hello', run() {} }),
+ panel: ctx.panels.register({ id: 'acme.panel', title: 'Acme', mount: () => () => {} }),
+ setting: ctx.settings.register({ id: 'acme.warn', type: 'boolean', label: 'Warn', default: true }),
+ tool: ctx.tools.register({
+ id: 'acme.measure',
+ title: 'Measure',
+ onPointerDown: () => true,
+ onPointerMove: () => {},
+ onPointerUp: () => {},
+ }),
+ overlay: ctx.overlays.register({ id: 'acme.gizmo', render: () => {} }),
+ inspector: ctx.inspector.register({
+ kind: 'component',
+ id: 'audit',
+ component: 'Sprite',
+ title: 'Audit',
+ build: () => {},
+ }),
+ assetType: ctx.assets.registerType({ id: 'acme.dialogue', extensions: ['dlg'] }),
+ entityTemplate: ctx.entities.registerTemplate({ id: 'acme.turret', label: 'Turret', components: [] }),
+ contextMenu: ctx.contextMenus.register({
+ id: 'acme.reveal',
+ location: 'outliner/item',
+ label: 'Reveal',
+ run: () => {},
+ }),
+ };
+}
+
+describe('contribution inventory', () => {
+ it('starts empty — a plugin that registers nothing lists nothing', () => {
+ const b = build();
+ expect(b.contributions()).toEqual([]);
+ });
+
+ it('lists every contribution kind the context can register', () => {
+ const b = build();
+ registerAll(b.ctx);
+ const kinds = b.contributions().map((c) => c.kind);
+ const expected: ContributionKind[] = [
+ 'command', 'panel', 'setting', 'tool', 'overlay',
+ 'inspector', 'assetType', 'entityTemplate', 'contextMenu',
+ ];
+ // Every kind present, and nothing registered twice.
+ expect([...kinds].sort()).toEqual([...expected].sort());
+ });
+
+ it('carries the id and a localized label for each', () => {
+ const b = build();
+ registerAll(b.ctx);
+ const byKind = new Map(b.contributions().map((c) => [c.kind, c]));
+ expect(byKind.get('command')).toMatchObject({ id: 'acme.hello', label: 'Say hello' });
+ expect(byKind.get('panel')).toMatchObject({ id: 'acme.panel', label: 'Acme' });
+ expect(byKind.get('tool')).toMatchObject({ id: 'acme.measure', label: 'Measure' });
+ // Inspector ids are namespaced by the host, and the list must show the id that
+ // actually landed in the registry — not the one the plugin asked for.
+ expect(byKind.get('inspector')?.id).toBe('acme.tools.audit');
+ // An asset type has no title of its own; its extensions are the useful label.
+ expect(byKind.get('assetType')?.label).toBe('.dlg');
+ // An overlay has neither — and must NOT fall back to its id, or the panel row
+ // prints the same string in the label column and the id column.
+ expect(byKind.get('overlay')).toMatchObject({ id: 'acme.gizmo', label: '' });
+ });
+
+ it('resolves a localized label rather than listing the object', () => {
+ const b = build();
+ b.ctx.commands.register({ id: 'acme.l10n', title: { en: 'Bake', 'zh-CN': '烘焙' }, run() {} });
+ expect(b.contributions()[0].label).toBe('Bake');
+ });
+
+ it('drops a contribution from the list when it is retracted', () => {
+ const b = build();
+ const handles = registerAll(b.ctx);
+ expect(b.contributions()).toHaveLength(9);
+
+ handles.panel.dispose();
+ const after = b.contributions();
+ expect(after).toHaveLength(8);
+ expect(after.some((c) => c.kind === 'panel')).toBe(false);
+ // The others are untouched — retraction is per contribution, not per plugin.
+ expect(after.some((c) => c.kind === 'command')).toBe(true);
+ });
+
+ it('empties on dispose, so a reloaded plugin never inherits the old build`s list', () => {
+ const b = build();
+ registerAll(b.ctx);
+ b.dispose();
+ expect(b.contributions()).toEqual([]);
+ });
+
+ it('hands back a copy — a caller cannot mutate the live list', () => {
+ const b = build();
+ registerAll(b.ctx);
+ b.contributions().length = 0;
+ expect(b.contributions()).toHaveLength(9);
+ });
+});
diff --git a/desktop/tests/plugin-package.test.ts b/desktop/tests/plugin-package.test.ts
new file mode 100644
index 000000000..fc9db1007
--- /dev/null
+++ b/desktop/tests/plugin-package.test.ts
@@ -0,0 +1,191 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// `.esplugin` packaging. Export is the easy direction; the tests that matter are on
+// IMPORT, because a package is a file someone was handed.
+//
+// Three rules, in the order they run:
+// 1. Inspect writes nothing and inflates nothing — so a hostile archive is refused
+// before it can cost anything.
+// 2. Install refuses to overwrite, and cleans up after itself if it fails partway.
+// 3. Install never approves. That decision stays with the user, in the panel.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { makeZip } from '../../build-tools/utils/zip.js';
+import {
+ packPlugin, packageFileName, inspectPluginPackage, installPluginPackage, PLUGIN_PACKAGE_EXT,
+} from '../electron/pluginPackage';
+import { scaffoldPlugin } from '../electron/pluginScaffold';
+
+let root: string;
+/** Where plugins get installed to, distinct from where they are authored. */
+let dest: string;
+
+const MANIFEST = {
+ id: 'acme.tools',
+ name: 'Acme Tools',
+ version: '1.2.0',
+ main: { editor: 'src/editor.ts' },
+};
+
+/** A package built entry-by-entry, so a test can make one that is subtly wrong. */
+const pack = (entries: Record<string, string>): Buffer =>
+ makeZip(Object.entries(entries).map(([name, data]) => ({ name, data: Buffer.from(data, 'utf8') })));
+
+const validPackage = (over: Record<string, unknown> = {}): Buffer =>
+ pack({
+ 'plugin.json': JSON.stringify({ ...MANIFEST, ...over }),
+ 'src/editor.ts': 'export default { activate() {} };\n',
+ });
+
+beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'es-plugpkg-'));
+ dest = path.join(root, 'installed');
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('packPlugin', () => {
+ it('round-trips a scaffolded plugin: what it writes, it can read back', async () => {
+ const authored = path.join(root, 'authored');
+ mkdirSync(authored, { recursive: true });
+ await scaffoldPlugin(authored, { id: 'acme.tools', name: 'Acme Tools', editorVersion: '0.34.1' });
+
+ const packed = await packPlugin(path.join(authored, 'acme.tools'));
+ expect(packed.ok).toBe(true);
+
+ const info = inspectPluginPackage(packed.data!);
+ expect(info.ok).toBe(true);
+ expect(info.manifest?.id).toBe('acme.tools');
+ expect(info.files?.map((f) => f.name)).toEqual(
+ expect.arrayContaining(['plugin.json', 'tsconfig.json', 'src/editor.ts']),
+ );
+ });
+
+ it('leaves out build output and vendored dependencies', async () => {
+ const dir = path.join(root, 'acme.tools');
+ mkdirSync(path.join(dir, 'node_modules', 'left-pad'), { recursive: true });
+ mkdirSync(path.join(dir, 'dist'), { recursive: true });
+ mkdirSync(path.join(dir, 'src'), { recursive: true });
+ writeFileSync(path.join(dir, 'plugin.json'), JSON.stringify(MANIFEST));
+ writeFileSync(path.join(dir, 'src', 'editor.ts'), 'export default {};');
+ writeFileSync(path.join(dir, 'node_modules', 'left-pad', 'index.js'), 'module.exports = 1;');
+ writeFileSync(path.join(dir, 'dist', 'bundle.js'), 'nope');
+
+ const packed = await packPlugin(dir);
+ const names = inspectPluginPackage(packed.data!).files!.map((f) => f.name);
+ expect(names).toContain('src/editor.ts');
+ expect(names.some((n) => n.startsWith('node_modules/'))).toBe(false);
+ expect(names.some((n) => n.startsWith('dist/'))).toBe(false);
+ });
+
+ it('refuses to export a folder whose manifest has drifted invalid', async () => {
+ const dir = path.join(root, 'broken');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, 'plugin.json'), JSON.stringify({ ...MANIFEST, id: 'NotDotted' }));
+ const packed = await packPlugin(dir);
+ expect(packed.ok).toBe(false);
+ expect(packed.error).toMatch(/not valid/);
+ });
+
+ it('names the file after the id and version', () => {
+ expect(packageFileName(MANIFEST)).toBe(`acme.tools-1.2.0.${PLUGIN_PACKAGE_EXT}`);
+ });
+});
+
+describe('inspectPluginPackage', () => {
+ it('reports the manifest, capabilities and file list without extracting', () => {
+ const info = inspectPluginPackage(validPackage({ capabilities: ['fs:project', 'net'] }));
+ expect(info.ok).toBe(true);
+ expect(info.name).toBe('Acme Tools');
+ expect(info.capabilities).toEqual(['fs:project', 'net']);
+ expect(info.files).toHaveLength(2);
+ });
+
+ it('reports a file that is not an archive instead of throwing', () => {
+ const info = inspectPluginPackage(Buffer.from('this is a text file, not a zip'));
+ expect(info.ok).toBe(false);
+ expect(info.error).toBeTruthy();
+ });
+
+ it('refuses a package with no manifest, but still lists what is inside', () => {
+ const info = inspectPluginPackage(pack({ 'readme.txt': 'hi' }));
+ expect(info.ok).toBe(false);
+ expect(info.error).toMatch(/no plugin.json/);
+ // The listing survives the rejection: "what IS this file, then?" is the next
+ // question, and answering it costs nothing.
+ expect(info.files?.map((f) => f.name)).toEqual(['readme.txt']);
+ });
+
+ it('refuses an entry that would escape the install folder', () => {
+ const info = inspectPluginPackage(pack({
+ 'plugin.json': JSON.stringify(MANIFEST),
+ '../../evil.js': 'pwned',
+ }));
+ expect(info.ok).toBe(false);
+ expect(info.error).toMatch(/unsafe entry name/);
+ });
+
+ it('refuses an absolute entry name', () => {
+ const info = inspectPluginPackage(pack({ '/etc/passwd': 'x' }));
+ expect(info.ok).toBe(false);
+ expect(info.error).toMatch(/unsafe entry name/);
+ });
+
+ it('names the manifest problem rather than a generic failure', () => {
+ const info = inspectPluginPackage(validPackage({ version: 'one' }));
+ expect(info.ok).toBe(false);
+ expect(info.error).toMatch(/`version`/);
+ });
+});
+
+describe('installPluginPackage', () => {
+ it('installs under the id the manifest declares, not the file name', async () => {
+ const r = await installPluginPackage(validPackage(), dest);
+ expect(r.ok).toBe(true);
+ expect(r.id).toBe('acme.tools');
+ expect(existsSync(path.join(dest, 'acme.tools', 'plugin.json'))).toBe(true);
+ expect(readFileSync(path.join(dest, 'acme.tools', 'src', 'editor.ts'), 'utf8'))
+ .toContain('activate');
+ });
+
+ it('refuses to overwrite a plugin that is already there', async () => {
+ expect((await installPluginPackage(validPackage(), dest)).ok).toBe(true);
+ const before = readFileSync(path.join(dest, 'acme.tools', 'src', 'editor.ts'), 'utf8');
+
+ const second = await installPluginPackage(
+ pack({ 'plugin.json': JSON.stringify(MANIFEST), 'src/editor.ts': 'REPLACED' }),
+ dest,
+ );
+ expect(second.ok).toBe(false);
+ expect(second.error).toMatch(/already installed/);
+ expect(readFileSync(path.join(dest, 'acme.tools', 'src', 'editor.ts'), 'utf8')).toBe(before);
+ });
+
+ it('writes nothing at all when the package is rejected', async () => {
+ const r = await installPluginPackage(pack({ 'readme.txt': 'hi' }), dest);
+ expect(r.ok).toBe(false);
+ expect(existsSync(dest)).toBe(false);
+ });
+
+ it('leaves no half-plugin behind when extraction fails', async () => {
+ // A corrupt PAYLOAD: the central directory still reads cleanly (so inspect
+ // passes and the user is shown a sane preview), but the entry's CRC no longer
+ // matches — which readZip only discovers partway through extracting.
+ const corrupt = Buffer.from(validPackage());
+ // Locate the first entry's compressed data from its own local header, rather
+ // than guessing an offset: a guess that lands in the name corrupts nothing.
+ const nameLen = corrupt.readUInt16LE(26);
+ const extraLen = corrupt.readUInt16LE(28);
+ const dataAt = 30 + nameLen + extraLen;
+ corrupt[dataAt + 2] ^= 0xff;
+
+ const r = await installPluginPackage(corrupt, dest);
+ expect(r.ok).toBe(false);
+ expect(existsSync(path.join(dest, 'acme.tools'))).toBe(false);
+ });
+});
diff --git a/desktop/tests/plugin-scaffold.test.ts b/desktop/tests/plugin-scaffold.test.ts
new file mode 100644
index 000000000..17c14f981
--- /dev/null
+++ b/desktop/tests/plugin-scaffold.test.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The plugin scaffolder. The point of it is that what it writes LOADS — so the
+// tests assert against the same validators the loader uses rather than against the
+// template's text, which would only pin the template to itself.
+//
+// The version pin is the one that actually bit: `engines.editor` below 1.0 treats
+// the MINOR as the breaking axis, so a template carrying a hard-coded range makes
+// every plugin scaffolded from it born `incompatible` the moment the editor's minor
+// moves. That is not hypothetical — the guide's sample said `^0.33` against a 0.34
+// editor.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scaffoldPlugin, editorRangeFor, SCAFFOLD_CONTRIBUTIONS } from '../electron/pluginScaffold';
+import { validateManifest, satisfiesEditorRange } from '@/plugins/manifest';
+
+let root: string;
+
+const EDITOR = '0.34.1';
+
+const create = (opts: Partial<Parameters<typeof scaffoldPlugin>[1]> = {}) =>
+ scaffoldPlugin(root, {
+ id: 'acme.level-tools',
+ name: 'Level Tools',
+ editorVersion: EDITOR,
+ ...opts,
+ });
+
+const manifestOf = (id = 'acme.level-tools'): unknown =>
+ JSON.parse(readFileSync(path.join(root, id, 'plugin.json'), 'utf8'));
+
+const entryOf = (id = 'acme.level-tools'): string =>
+ readFileSync(path.join(root, id, 'src', 'editor.ts'), 'utf8');
+
+beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'es-plugscaffold-'));
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('scaffoldPlugin', () => {
+ it('writes a plugin whose manifest the loader accepts', async () => {
+ const r = await create();
+ expect(r.ok).toBe(true);
+ expect(r.files).toEqual(expect.arrayContaining(['plugin.json', 'tsconfig.json', 'src/editor.ts']));
+
+ const parsed = validateManifest(manifestOf());
+ if ('error' in parsed) throw new Error(`scaffold wrote an invalid manifest: ${parsed.error}`);
+ expect(parsed.manifest.id).toBe('acme.level-tools');
+ expect(parsed.manifest.main?.editor).toBe('src/editor.ts');
+ });
+
+ it('pins engines.editor to the RUNNING editor, so the plugin is not born incompatible', async () => {
+ await create();
+ const parsed = validateManifest(manifestOf());
+ if ('error' in parsed) throw new Error(parsed.error);
+ const range = parsed.manifest.engines?.editor;
+ expect(range).toBe('^0.34');
+ expect(satisfiesEditorRange(EDITOR, range!).ok).toBe(true);
+ // The bug this guards: a range from an older line refuses the running editor.
+ expect(satisfiesEditorRange(EDITOR, '^0.33').ok).toBe(false);
+ });
+
+ it('derives the range from any version, and degrades to * rather than guessing', () => {
+ expect(editorRangeFor('1.2.3')).toBe('^1.2');
+ expect(editorRangeFor('0.34.1-beta.2')).toBe('^0.34');
+ expect(editorRangeFor('nonsense')).toBe('*');
+ });
+
+ it('refuses an id the loader would later reject, before writing anything', async () => {
+ const r = await scaffoldPlugin(root, { id: 'Tools', name: 'Tools', editorVersion: EDITOR });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/dotted, lowercase/);
+ expect(existsSync(path.join(root, 'Tools'))).toBe(false);
+ });
+
+ it('refuses a nameless plugin', async () => {
+ const r = await create({ name: ' ' });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/name/);
+ });
+
+ it('never clobbers an existing folder', async () => {
+ expect((await create()).ok).toBe(true);
+ const before = entryOf();
+ const second = await create({ name: 'Something Else' });
+ expect(second.ok).toBe(false);
+ expect(second.error).toMatch(/already exists/);
+ expect(entryOf()).toBe(before);
+ });
+
+ it('writes only the samples asked for, with the types each one needs', async () => {
+ await create({ contributions: ['overlay', 'tool'] });
+ const src = entryOf();
+ expect(src).toContain('ctx.overlays.register');
+ expect(src).toContain('ctx.tools.register');
+ expect(src).not.toContain('ctx.panels.register');
+ // A sample that names a type must import it, or the file it wrote does not
+ // compile in the author's editor — the first thing they would see.
+ expect(src).toContain('type OverlayGraphics');
+ expect(src).toContain('type PointerInput');
+ expect(src).not.toContain('type InspectorSectionBuilder');
+ });
+
+ it('produces a valid, loadable plugin even with no samples at all', async () => {
+ const r = await create({ contributions: [] });
+ expect(r.ok).toBe(true);
+ expect('error' in validateManifest(manifestOf())).toBe(false);
+ const src = entryOf();
+ expect(src).toContain('definePlugin');
+ expect(src).toContain('activate(ctx: PluginContext)');
+ });
+
+ it('offers every sample kind, and each writes something', async () => {
+ await create({ contributions: SCAFFOLD_CONTRIBUTIONS });
+ const src = entryOf();
+ for (const marker of ['ctx.commands.register', 'ctx.panels.register', 'ctx.inspector.register',
+ 'ctx.overlays.register', 'ctx.tools.register']) {
+ expect(src).toContain(marker);
+ }
+ });
+
+ it('writes the typings sidecar the generated tsconfig points at', async () => {
+ await create({ apiTypes: '// editor api types\n' });
+ const tsconfig = JSON.parse(readFileSync(path.join(root, 'acme.level-tools', 'tsconfig.json'), 'utf8')) as {
+ compilerOptions: { paths: Record<string, string[]> };
+ };
+ const rel = tsconfig.compilerOptions.paths['@estella/editor-api'][0];
+ // Resolve the tsconfig's own path claim rather than restating it — that is the
+ // link that breaks silently if either half moves.
+ const resolved = path.resolve(path.join(root, 'acme.level-tools'), rel);
+ expect(existsSync(resolved)).toBe(true);
+ expect(readFileSync(resolved, 'utf8')).toBe('// editor api types\n');
+ });
+
+ it('leaves no sidecar when the caller supplies no typings', async () => {
+ await create();
+ expect(existsSync(path.join(root, '.types'))).toBe(false);
+ });
+});
diff --git a/desktop/tests/shot-dialogs.test.ts b/desktop/tests/shot-dialogs.test.ts
new file mode 100644
index 000000000..eee772b53
--- /dev/null
+++ b/desktop/tests/shot-dialogs.test.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The scripted file-dialog seam. Two properties carry the whole design:
+//
+// 1. Outside shot mode it must be a pure delegation — an automation hook that
+// changed real behaviour would be worse than no hook.
+// 2. Inside shot mode with nothing scripted it must CANCEL, never open a real
+// dialog. A headless run that opened one would block until the harness timed
+// out, and the failure would read as a hang rather than a missing script.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const showOpen = vi.fn();
+const showSave = vi.fn();
+
+vi.mock('electron', () => ({
+ dialog: {
+ showOpenDialog: (...args: unknown[]) => showOpen(...args),
+ showSaveDialog: (...args: unknown[]) => showSave(...args),
+ },
+}));
+
+// Imported after the mock, and re-imported per test because the queues are module
+// state consumed once — which is the behaviour under test.
+async function load() {
+ vi.resetModules();
+ return import('../electron/shotDialogs');
+}
+
+const win = {} as never;
+
+beforeEach(() => {
+ showOpen.mockReset().mockResolvedValue({ canceled: false, filePaths: ['/real/pick'] });
+ showSave.mockReset().mockResolvedValue({ canceled: false, filePath: '/real/save' });
+ delete process.env.ESTELLA_SHOT;
+ delete process.env.ESTELLA_SHOT_PICK_FILE;
+ delete process.env.ESTELLA_SHOT_SAVE_FILE;
+});
+
+afterEach(() => {
+ delete process.env.ESTELLA_SHOT;
+ delete process.env.ESTELLA_SHOT_PICK_FILE;
+ delete process.env.ESTELLA_SHOT_SAVE_FILE;
+});
+
+describe('outside shot mode', () => {
+ it('delegates to the real dialog, unchanged', async () => {
+ const { showOpenDialog, showSaveDialog } = await load();
+ expect(await showOpenDialog(win, { title: 'Open' })).toEqual({ canceled: false, filePaths: ['/real/pick'] });
+ expect(await showSaveDialog(win, { title: 'Save' })).toEqual({ canceled: false, filePath: '/real/save' });
+ expect(showOpen).toHaveBeenCalledOnce();
+ expect(showSave).toHaveBeenCalledOnce();
+ });
+
+ it('ignores a scripted path when not in shot mode', async () => {
+ process.env.ESTELLA_SHOT_PICK_FILE = '/scripted/a.esplugin';
+ const { showOpenDialog } = await load();
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['/real/pick']);
+ });
+});
+
+describe('in shot mode', () => {
+ beforeEach(() => {
+ process.env.ESTELLA_SHOT = 'out.png';
+ });
+
+ it('cancels rather than opening a real dialog when nothing is scripted', async () => {
+ const { showOpenDialog, showSaveDialog } = await load();
+ expect(await showOpenDialog(win, { title: 'Open' })).toEqual({ canceled: true, filePaths: [] });
+ expect(await showSaveDialog(win, { title: 'Save' })).toEqual({ canceled: true });
+ // The point of the whole file: a headless run must never block on a modal.
+ expect(showOpen).not.toHaveBeenCalled();
+ expect(showSave).not.toHaveBeenCalled();
+ });
+
+ it('hands back a single scripted path', async () => {
+ process.env.ESTELLA_SHOT_PICK_FILE = 'C:/tmp/a.esplugin';
+ process.env.ESTELLA_SHOT_SAVE_FILE = 'C:/tmp/out.esplugin';
+ const { showOpenDialog, showSaveDialog } = await load();
+ expect(await showOpenDialog(win, {})).toEqual({ canceled: false, filePaths: ['C:/tmp/a.esplugin'] });
+ expect(await showSaveDialog(win, {})).toEqual({ canceled: false, filePath: 'C:/tmp/out.esplugin' });
+ });
+
+ it('feeds successive dialogs from a JSON queue, then cancels', async () => {
+ process.env.ESTELLA_SHOT_PICK_FILE = JSON.stringify(['/one', '/two']);
+ const { showOpenDialog } = await load();
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['/one']);
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['/two']);
+ // Exhausted — and still no real dialog.
+ expect(await showOpenDialog(win, {})).toEqual({ canceled: true, filePaths: [] });
+ expect(showOpen).not.toHaveBeenCalled();
+ });
+
+ it('supports a multi-selection entry', async () => {
+ process.env.ESTELLA_SHOT_PICK_FILE = JSON.stringify([['/a.png', '/b.png'], '/c.png']);
+ const { showOpenDialog } = await load();
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['/a.png', '/b.png']);
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['/c.png']);
+ });
+
+ it('treats an unparseable value as one literal path rather than guessing', async () => {
+ process.env.ESTELLA_SHOT_PICK_FILE = '[not json';
+ const { showOpenDialog } = await load();
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['[not json']);
+ });
+
+ it('keeps the open and save queues independent', async () => {
+ process.env.ESTELLA_SHOT_PICK_FILE = '/in';
+ process.env.ESTELLA_SHOT_SAVE_FILE = '/out';
+ const { showOpenDialog, showSaveDialog } = await load();
+ // Consuming one must not drain the other — a shot that exports then imports
+ // scripts both, and an interleaved queue would hand back the wrong file.
+ expect((await showOpenDialog(win, {})).filePaths).toEqual(['/in']);
+ expect((await showSaveDialog(win, {})).filePath).toBe('/out');
+ });
+});
diff --git a/docs/astro/src/content/docs/guides/editor-plugins.mdx b/docs/astro/src/content/docs/guides/editor-plugins.mdx
index 332231a33..4e5a20f39 100644
--- a/docs/astro/src/content/docs/guides/editor-plugins.mdx
+++ b/docs/astro/src/content/docs/guides/editor-plugins.mdx
@@ -19,54 +19,87 @@ of anything.
<Steps>
-1. Create the folder — the id is `<publisher>.<name>`:
-
- <FileTree>
- - .esengine/
- - plugins/
- - acme.level-tools/
- - plugin.json
- - src/
- - editor.ts
- </FileTree>
-
-2. Write `plugin.json`:
-
- ```json
- {
- "id": "acme.level-tools",
- "name": { "en": "Level Tools", "zh-CN": "关卡工具" },
- "version": "1.0.0",
- "engines": { "editor": "^0.33" },
- "main": { "editor": "src/editor.ts" }
- }
- ```
-
-3. Write `src/editor.ts`:
-
- ```ts
- import { definePlugin, type PluginContext } from '@estella/editor-api';
-
- export default definePlugin({
- activate(ctx: PluginContext) {
- ctx.commands.register({
- id: 'acme.level-tools.countEntities',
- title: { en: 'Count Entities', 'zh-CN': '统计实体' },
- menu: 'tools',
- run: () => ctx.ui.toast(`${ctx.scene.getSceneTree().length} root entities`),
- });
- },
- });
- ```
-
-4. Open **Window ▸ Plugins**, find your plugin, and choose **Trust and load**.
+1. Open **Window ▸ Plugins** and choose **New plugin** (or search the command
+ palette for it).
+
+2. Give it a name. The id is derived from it and can be edited — dotted and
+ lowercase, like `acme.level-tools`. Choose whether it installs into the
+ **project** (versioned with it, shared by the team) or into your **user**
+ folder (personal, available in every project).
+
+3. Tick the samples you want — command, panel, inspector section, viewport gizmo,
+ viewport tool — and choose **Create**.
</Steps>
+The editor writes a plugin that already runs, and loads it:
+
+<FileTree>
+- .esengine/
+ - plugins/
+ - acme.level-tools/
+ - plugin.json
+ - tsconfig.json
+ - src/
+ - editor.ts
+</FileTree>
+
+```json title="plugin.json"
+{
+ "id": "acme.level-tools",
+ "name": "Level Tools",
+ "version": "0.1.0",
+ "engines": { "editor": "^0.34" },
+ "main": { "editor": "src/editor.ts" }
+}
+```
+
+```ts title="src/editor.ts"
+import { definePlugin, type PluginContext } from '@estella/editor-api';
+
+export default definePlugin({
+ activate(ctx: PluginContext) {
+ ctx.commands.register({
+ id: 'acme.level-tools.hello',
+ title: { en: 'Say hello', 'zh-CN': '打个招呼' },
+ menu: 'tools',
+ run: () => ctx.ui.toast(`${ctx.scene.getSelectionIds().length} selected`),
+ });
+ },
+});
+```
+
Your command is now in the Tools menu and the command palette. Edit `editor.ts`
and save: the editor recompiles and re-activates it, and any panel it contributed
reopens on the new build.
+<Aside type="tip" title="Let the editor write engines.editor">
+`engines.editor` is the editor range a plugin claims to work with. Below 1.0 the
+**minor is the breaking-change axis** — `^0.34` does not match `0.35`. Creating a
+plugin pins it to the editor doing the creating, so copying an older range in from
+somewhere else is how a plugin arrives already marked *incompatible*.
+</Aside>
+
+## Seeing what a plugin contributed
+
+Every running plugin has a **Contributes** row in the Plugins panel. Expand it for
+everything it has registered right now — commands, panels, settings, tools, gizmos,
+inspector sections, asset types, entity templates, menu items — each with its id.
+
+"Why isn't my panel showing up?" is usually answered here: either it isn't in the
+list (`activate` never reached that line), or it is, under an id you didn't expect.
+
+## Sharing a plugin
+
+**Export** in the Plugins panel packs one plugin into a single `.esplugin` file —
+a ZIP, so renaming it to `.zip` opens it anywhere. `node_modules`, `dist`, and the
+generated typings are left out.
+
+The other side installs it with **Import**, which first lists what is inside — the
+manifest, the declared capabilities, every file — without unpacking or writing
+anything. Only after that does it land on disk, and **installing is not running**:
+it arrives needing trust, so loading it stays a separate decision.
+
<Aside type="caution" title="Trust">
A plugin runs with the same access the editor has — your project files and
anything the editor can reach. That is why nothing loads until you approve it, and
@@ -82,8 +115,9 @@ folder claiming the same id, asks again.
The editor writes `@estella/editor-api`'s typings into your project at
`.esengine/plugins/.types/editor-api.d.ts` every time it opens the project, so they
-always match the editor you're running. Point your plugin's `tsconfig.json` at
-them:
+always match the editor you're running. Your plugin's `tsconfig.json` points at
+them — **New plugin writes this for you**; it is spelled out here for anyone
+authoring one by hand:
```json
{
diff --git a/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx b/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx
index a93f81142..2676c0536 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx
@@ -16,53 +16,80 @@ import { Aside, Steps, FileTree } from '@astrojs/starlight/components';
<Steps>
-1. 建目录——id 形如 `<发布者>.<名字>`:
-
- <FileTree>
- - .esengine/
- - plugins/
- - acme.level-tools/
- - plugin.json
- - src/
- - editor.ts
- </FileTree>
-
-2. 写 `plugin.json`:
-
- ```json
- {
- "id": "acme.level-tools",
- "name": { "en": "Level Tools", "zh-CN": "关卡工具" },
- "version": "1.0.0",
- "engines": { "editor": "^0.33" },
- "main": { "editor": "src/editor.ts" }
- }
- ```
-
-3. 写 `src/editor.ts`:
-
- ```ts
- import { definePlugin, type PluginContext } from '@estella/editor-api';
-
- export default definePlugin({
- activate(ctx: PluginContext) {
- ctx.commands.register({
- id: 'acme.level-tools.countEntities',
- title: { en: 'Count Entities', 'zh-CN': '统计实体' },
- menu: 'tools',
- run: () => ctx.ui.toast(`${ctx.scene.getSceneTree().length} 个根实体`),
- });
- },
- });
- ```
-
-4. 打开**窗口 ▸ 插件**,找到你的插件,点**信任并加载**。
+1. 打开**窗口 ▸ 插件**,点**新建插件**(命令面板里搜"新建插件"也行)。
+
+2. 填名称。id 会按名称自动生成,也可以自己改——点分小写,形如
+ `acme.level-tools`。选装到**项目**(随项目版本管理,团队共享)还是
+ **用户**(个人插件,每个项目里都可用)。
+
+3. 勾选想要的起始样例(命令、面板、检视器分区、视口 gizmo、视口工具),点**创建**。
</Steps>
+编辑器写出一个已经能跑的插件,并立刻加载它:
+
+<FileTree>
+- .esengine/
+ - plugins/
+ - acme.level-tools/
+ - plugin.json
+ - tsconfig.json
+ - src/
+ - editor.ts
+</FileTree>
+
+```json title="plugin.json"
+{
+ "id": "acme.level-tools",
+ "name": "Level Tools",
+ "version": "0.1.0",
+ "engines": { "editor": "^0.34" },
+ "main": { "editor": "src/editor.ts" }
+}
+```
+
+```ts title="src/editor.ts"
+import { definePlugin, type PluginContext } from '@estella/editor-api';
+
+export default definePlugin({
+ activate(ctx: PluginContext) {
+ ctx.commands.register({
+ id: 'acme.level-tools.hello',
+ title: { en: 'Say hello', 'zh-CN': '打个招呼' },
+ menu: 'tools',
+ run: () => ctx.ui.toast(`${ctx.scene.getSelectionIds().length} 个实体被选中`),
+ });
+ },
+});
+```
+
你的命令现在出现在工具菜单和命令面板里。改一下 `editor.ts` 再保存:编辑器会
重新编译并重新激活它,它贡献的面板也会以新构建重新打开。
+<Aside type="tip" title="engines.editor 由编辑器写,别照抄">
+`engines.editor` 是插件声称适配的编辑器版本区间。1.0 之前,**次版本号是破坏性
+变更的轴**——`^0.34` 不匹配 `0.35`。新建插件时编辑器按**当前自己的版本**写这一行,
+所以从别处抄一个旧区间过来,插件一装上就是"版本不兼容"。
+</Aside>
+
+## 看插件贡献了什么
+
+插件面板里每个运行中的插件都有一条**贡献**,展开就是它此刻注册的全部东西——
+命令、面板、设置项、工具、gizmo、检视器分区、资产类型、实体模板、菜单项——
+连同各自的 id。
+
+"我的面板怎么没出来"通常在这里就有答案:它要么不在列表里(`activate` 没跑到那一行),
+要么在列表里但 id 和你以为的不一样。
+
+## 分享插件
+
+插件面板上的**导出**把一个插件打包成单个 `.esplugin` 文件(就是 ZIP,改名成
+`.zip` 任何工具都能打开)。`node_modules`、`dist` 和生成的类型不会进包。
+
+对面用**导入**装:装之前会先列出包里的清单——manifest、声明的能力、每个文件——
+这一步不解压、不落盘。确认后才写入,且**装上不等于运行**:它会以"待信任"状态
+出现,加载与否仍然是你单独的一个决定。
+
<Aside type="caution" title="信任">
插件与编辑器拥有同等权限——你的项目文件,以及编辑器能触及的一切。所以在你批准
之前什么都不会加载,也所以你只应加载来源可信的插件。提示框会列出插件声明的能力,
@@ -75,7 +102,8 @@ import { Aside, Steps, FileTree } from '@astrojs/starlight/components';
编辑器每次打开项目时,都会把 `@estella/editor-api` 的类型写进
`.esengine/plugins/.types/editor-api.d.ts`,因此它永远与你正在运行的编辑器一致。
-在插件的 `tsconfig.json` 里指过去:
+插件的 `tsconfig.json` 指过去——**新建插件时这份已经写好了**,这里列出来是给
+手写插件的人参考:
```json
{