diff --git a/docs/plugin-host.md b/docs/plugin-host.md index 9e2ecd2..34c988c 100644 --- a/docs/plugin-host.md +++ b/docs/plugin-host.md @@ -31,6 +31,9 @@ The service writes `plugin-state.json` to a temporary file, then renames it. It After each change, the service sends the `plugins-changed` event to all windows. A settings write sends `plugin-settings-changed` with the plugin ID. The browser preview (`pnpm dev`) has no installed plugins unless a smoke test supplies a desktop mock. +The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser. +`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it. + ### Scans Each window asks for a new snapshot at these times: @@ -182,7 +185,7 @@ Workers that the app loads from its own files get no policy. Workers from Blob U | --- | --- | --- | --- | | `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands | | `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, backgrounds, completion, browser | -| `browser.json` | `browser-*` | Only the built-in browser (`src/routes/+page.svelte`) | Browser, `plugins_snapshot`, settings, spelling, and window controls | +| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, and window controls | A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this. @@ -192,7 +195,8 @@ The other windows load every enabled plugin. A smaller command set for them woul - Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there. - Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace. - `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal. -- `backgrounds_*`, and `browser_request` without a browser session token, need a plugin lease of the calling window. +- `backgrounds_*` need a plugin lease of the calling window. +- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it. - A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it. ## Modules and checks diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index 5bbd852..7d1339c 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -13,7 +13,6 @@ use tauri::{AppHandle, Emitter, Manager, State}; use crate::error::{Error, Result}; -const PLUGIN: &str = "runestone.browser"; const COMMANDS: &[&str] = &[ "state", "newTab", @@ -571,16 +570,12 @@ pub async fn browser_request( session: Option, ) -> Result { let owner = window.label().to_string(); - // The plugin lease check can wait for the plugin lock, so it also runs on the blocking worker. + // A request can wait for the engine to start or to answer, so it runs on the blocking worker. tauri::async_runtime::spawn_blocking(move || { - if let Some(token) = session { - app.state::().require_session(&owner, &token)?; - } else { - app.state::() - .require_lease(&app, &owner, PLUGIN)?; - } - app.state::() - .request(&app, &owner, &command, args) + let state = app.state::(); + // Only the built-in browser gets a session from `browser_connect`. A request without one fails. + state.require_session(&owner, session.as_deref().unwrap_or_default())?; + state.request(&app, &owner, &command, args) }) .await? } diff --git a/src-tauri/src/plugins.rs b/src-tauri/src/plugins.rs index 42d26c6..4a6b129 100644 --- a/src-tauri/src/plugins.rs +++ b/src-tauri/src/plugins.rs @@ -1365,13 +1365,7 @@ pub async fn plugins_set_enabled( enabled: bool, hash: Option, ) -> Result<()> { - let stop_browser = id == "runestone.browser" && !enabled; PluginState::run(&app, move |service| service.set_enabled(&id, enabled, hash.as_deref())).await?; - if stop_browser { - // Stopping the browser engine waits for its reply. - let browser_app = app.clone(); - tauri::async_runtime::spawn_blocking(move || browser_app.state::().close_all()).await?; - } changed(&app); Ok(()) } diff --git a/src/lib/browser/index.ts b/src/lib/browser/index.ts index e756421..f2329e1 100644 --- a/src/lib/browser/index.ts +++ b/src/lib/browser/index.ts @@ -95,7 +95,7 @@ export async function activate(api: PluginApi) { } }); api.openView(id, options); } - api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run: () => open() }); + api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', icon: 'globe', run: () => open() }); api.contribute('browser', { newTab: () => open(), mountSettings: container => retain(mount(Settings, { target: container })), diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index 4db6d15..06788ef 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -2094,10 +2094,10 @@ export const messageRows: [string, string, string, string][] = [ "插件文件清理完成。" ], [ - "Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.", - "Le navigateur est maintenant intégré. Vous pouvez supprimer cet ancien paquet. Vos profils et signets restent disponibles.", - "ブラウザーは内蔵されました。この古いパッケージは削除できます。プロファイルとブックマークは残ります。", - "浏览器现已内置。可以移除此旧包。浏览器配置文件和书签将保留。" + "RuneStone now includes {name}. You can remove this old package.", + "RuneStone inclut maintenant {name}. Vous pouvez supprimer cet ancien paquet.", + "RuneStone に {name} が含まれるようになりました。この古いパッケージは削除できます。", + "RuneStone 现已包含 {name}。可以移除此旧包。" ], [ "Restart RuneStone to clear all code from plugins that stopped in this window.", diff --git a/src/lib/layout/BrowserWindow.svelte b/src/lib/layout/BrowserWindow.svelte index b03e879..509d141 100644 --- a/src/lib/layout/BrowserWindow.svelte +++ b/src/lib/layout/BrowserWindow.svelte @@ -4,7 +4,7 @@ import { tick, untrack } from "svelte"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { pluginHost } from "$lib/plugins/registry"; - import { pluginEditors, pluginView, pluginSplits, externalErrors, pluginServiceError, selectPluginEditor, closePluginEditor, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external"; + import { browserModule, pluginEditors, pluginView, pluginSplits, externalErrors, pluginServiceError, selectPluginEditor, closePluginEditor, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external"; import PluginEditor from "$lib/plugins/PluginEditor.svelte"; import { containsPane, paneBounds } from "$lib/workspace/splitLayout"; import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions"; @@ -24,7 +24,7 @@ const active = $derived($pluginView?.key ?? null); const split = $derived($pluginSplits.find(tree => active && containsPane(tree, active))); const bounds = $derived(split ? paneBounds(split) : active ? paneBounds(active) : {}); - const message = $derived(error || $externalErrors["runestone.browser"] || $pluginServiceError); + const message = $derived(error || $externalErrors[browserModule] || $pluginServiceError); $effect(() => { if (tabs.length) hadTabs = true; diff --git a/src/lib/plugins/PluginAccessMenu.svelte b/src/lib/plugins/PluginAccessMenu.svelte index bd77bbe..7eaadb9 100644 --- a/src/lib/plugins/PluginAccessMenu.svelte +++ b/src/lib/plugins/PluginAccessMenu.svelte @@ -5,7 +5,7 @@ import { attachTooltip } from "$lib/ui/tooltip"; import ContextMenu from "$lib/layout/ContextMenu.svelte"; import type { MenuItem } from "$lib/layout/menuTypes"; - import { installedPlugins, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external"; + import { installedPlugins, isBuiltInModule, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external"; // `side` places the menu below the button (the header) or at its right (the left ribbon). let { surface, compact = false, side = "bottom" }: { surface: "commands" | "open"; compact?: boolean; side?: "bottom" | "right" } = $props(); let anchor = $state(); @@ -15,13 +15,13 @@ const label = $derived(surface === "open" ? $t("Plug-in views") : $t("Commands")); function tooltip(node: HTMLElement) { return { destroy: attachTooltip(node, () => compact ? label : "") }; } const tools = $derived($pluginTools.filter(tool => tool.surface === surface - && tool.owner !== "runestone.browser" + && !isBuiltInModule(tool.owner) && !(surface === "open" && tool.kind === "view" && $pluginNavigation.some(item => item.owner === tool.owner && item.id === tool.id && item.placement === "sidebar")))); const signature = $derived(JSON.stringify([tools, $installedPlugins.plugins.map(row => [row.manifest.id, row.manifest.name])])); const items: MenuItem[] = $derived.by(() => { void signature; return untrack(() => tools.map(tool => ({ kind: "action" as const, label: `${tool.title} · ${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner}`, - icon: tool.icon === "list" ? "bullet" as const : tool.icon ?? (tool.owner === "runestone.browser" && tool.id === "new-tab" ? "globe" as const : tool.kind === "command" && surface === "commands" ? "code" as const : "plus" as const), + icon: tool.icon === "list" ? "bullet" as const : tool.icon ?? (tool.kind === "command" && surface === "commands" ? "code" as const : "plus" as const), run: () => { error = ""; if (tool.kind === "view") openPluginView(tool.owner, tool.id); diff --git a/src/lib/plugins/PluginManager.svelte b/src/lib/plugins/PluginManager.svelte index 72c6b0c..1927fc9 100644 --- a/src/lib/plugins/PluginManager.svelte +++ b/src/lib/plugins/PluginManager.svelte @@ -142,8 +142,8 @@ {/if} - {#if plugin.manifest.id === "runestone.browser"}

{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}

{/if} - {#if plugin.manifest.id === "runestone.table-formulas"}

{$t("Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.")}

{/if} + {#if plugin.manifest.id === "runestone.table-formulas"}

{$t("Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.")}

+ {:else if builtInPackages.includes(plugin.manifest.id)}

{$t("RuneStone now includes {name}. You can remove this old package.", { name: plugin.manifest.name })}

{/if} {#if plugin.error || $externalErrors[plugin.manifest.id]}{/if} {/each} diff --git a/src/lib/plugins/access.ts b/src/lib/plugins/access.ts index e43e2ed..8cc291a 100644 --- a/src/lib/plugins/access.ts +++ b/src/lib/plugins/access.ts @@ -9,12 +9,11 @@ export type PluginTool = { export function pluginAccess(owner: string, commands: Iterable, views: Iterable): PluginTool[] { const result: PluginTool[] = []; for (const command of commands) { - const legacyOpen = owner === "runestone.browser" && command.id === "new-tab"; - result.push({ owner, id: command.id, title: command.title, kind: "command", surface: command.category === "open" || (command.category === undefined && legacyOpen) ? "open" : "commands", icon: command.icon }); + result.push({ owner, id: command.id, title: command.title, kind: "command", surface: command.category === "open" ? "open" : "commands", icon: command.icon }); } for (const view of views) { const settings = view.settings ?? (owner === "runestone.local-autocomplete" && view.id === "settings"); - if (!settings && (view.launcher === false || (view.launcher === undefined && owner === "runestone.browser"))) continue; + if (!settings && view.launcher === false) continue; result.push({ owner, id: view.id, title: view.title, kind: "view", surface: settings ? "settings" : "open", icon: view.icon }); } return result; diff --git a/src/lib/plugins/external.ts b/src/lib/plugins/external.ts index 2d99cf4..8fd08e2 100644 --- a/src/lib/plugins/external.ts +++ b/src/lib/plugins/external.ts @@ -79,6 +79,13 @@ export const pluginServiceError = writable(""); export const restartPlugins = writable([]); /** Old packages of features that RuneStone now includes. The host never loads their code. */ export const builtInPackages: readonly string[] = ["runestone.browser", "runestone.table-formulas", "runestone.theme-editor"]; +export const browserModule = "runestone.browser"; +/** Features of RuneStone that use the plugin API. They are not installed packages, and the plugin menus do not list their tools. */ +export const builtInModules: readonly { id: string; name: string; browserWindow: boolean; load: () => Promise }[] = [ + { id: browserModule, name: "Browser", browserWindow: true, load: () => import("../browser/index") }, + { id: "runestone.theme-editor", name: "Theme editor", browserWindow: false, load: () => import("../theme/editorView") }, +]; +export const isBuiltInModule = (id: string) => builtInModules.some(module => module.id === id); const sessions = new Map(); const failures = new Map(); const errors: Record = {}; @@ -86,7 +93,7 @@ const restarted = new Set(); let queue: Promise = Promise.resolve(); export function waitForPluginStartup() { return queue; } let started = false; -let allowedPlugins: string[] | undefined; +let browserWindow = false; let generation = 0; let documentOpenVersion = 0; export function cancelPluginDocumentOpen() { documentOpenVersion++; } @@ -340,8 +347,7 @@ export function refreshPlugins(): Promise { } for (const row of snapshot.plugins) { const id = row.manifest.id; - if (builtInPackages.includes(id)) continue; - if (allowedPlugins && !allowedPlugins.includes(id)) continue; + if (builtInPackages.includes(id) || browserWindow) continue; if (!row.enabled) { failures.delete(id); continue; } if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row); } @@ -365,23 +371,22 @@ export async function mountPluginView(owner: string, id: string, element: HTMLEl if (!session) throw new Error("The plugin is disabled."); return session.mount(id, element, document, surface); } -export function startExternalPlugins(allowed?: string[]): () => void { +/** A browser window starts only the built-in modules for browser windows, and no installed plugin. */ +export function startExternalPlugins(options: { browserWindow?: boolean } = {}): () => void { if (!isTauri() || started) return () => {}; started = true; - allowedPlugins = allowed; + browserWindow = options.browserWindow === true; let disposed = false; let off: (() => void) | undefined; void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason))); - queue = queue.then(async () => { - if (disposed || (allowed && !allowed.includes("runestone.browser"))) return; - const module = await import("../browser/index"); - await activate({ manifest: { schemaVersion: 1, id: "runestone.browser", name: "Browser", author: "RuneStone", description: "Built-in browser", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module); - }).catch(reason => report("runestone.browser", reason)); - queue = queue.then(async () => { - if (disposed || (allowed && !allowed.includes("runestone.theme-editor"))) return; - const module = await import("../theme/editorView"); - await activate({ manifest: { schemaVersion: 1, id: "runestone.theme-editor", name: "Theme editor", author: "RuneStone", description: "Built-in theme editor", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module); - }).catch(reason => report("runestone.theme-editor", reason)); + for (const builtIn of builtInModules) { + if (browserWindow && !builtIn.browserWindow) continue; + queue = queue.then(async () => { + if (disposed) return; + const module = await builtIn.load(); + await activate({ manifest: { schemaVersion: 1, id: builtIn.id, name: builtIn.name, author: "RuneStone", description: `Built-in ${builtIn.name.toLowerCase()}`, version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module); + }).catch(reason => report(builtIn.id, reason)); + } void refreshPlugins(); // Scans run at start, on window focus, on Refresh, and on `plugins-changed`. There is no timed scan. const focus = () => { void refreshPlugins(); }; diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 347f499..2b7f358 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -13,7 +13,7 @@ let dock: TerminalSlot | undefined = $state(); let error = $state(""); const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); }); - onMount(() => startExternalPlugins(browserWindow ? ["runestone.browser"] : undefined)); + onMount(() => startExternalPlugins({ browserWindow })); function keydown(event: KeyboardEvent) { if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return; const action = terminal?.shortcut(event); diff --git a/tests/unit/plugins/pluginAccess.spec.ts b/tests/unit/plugins/pluginAccess.spec.ts index b85961e..a45e324 100644 --- a/tests/unit/plugins/pluginAccess.spec.ts +++ b/tests/unit/plugins/pluginAccess.spec.ts @@ -15,10 +15,14 @@ test("plugin access separates settings, launchers, and commands without reading test("installed RuneStone packages retain access before their next package update", () => { assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings"); - assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "open"]]); assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open"); assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open"); - assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands"); +}); + +test("the browser ID gets the same access rules as any other owner", () => { + // The built-in browser sets `category` and `launcher` itself. The old Browser package had no special rules left. + assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "commands"], ["tab-123", "open"]]); + assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab", { category: "open", icon: "globe" })], [view("tab-123", { launcher: false })]).map(({ id, surface, icon }) => [id, surface, icon]), [["new-tab", "open", "globe"]]); }); test("command launchers retain the plugin action icon", () => { diff --git a/tests/unit/plugins/windowCapabilities.spec.ts b/tests/unit/plugins/windowCapabilities.spec.ts index a2d35dd..004f257 100644 --- a/tests/unit/plugins/windowCapabilities.spec.ts +++ b/tests/unit/plugins/windowCapabilities.spec.ts @@ -19,6 +19,8 @@ test("browser windows have their own capability, a subset of the main window com test("browser windows start only the built-in browser", () => { // The capability split depends on this: a browser window never loads an installed plugin. - assert.match(read("src/routes/+page.svelte"), /startExternalPlugins\(browserWindow \? \["runestone\.browser"\] : undefined\)/); + assert.match(read("src/routes/+page.svelte"), /startExternalPlugins\(\{ browserWindow \}\)/); + assert.match(read("src/lib/plugins/external.ts"), /if \(builtInPackages\.includes\(id\) \|\| browserWindow\) continue;/); + assert.match(read("src/lib/plugins/external.ts"), /if \(browserWindow && !builtIn\.browserWindow\) continue;/); assert.match(read("src-tauri/src/browser.rs"), /let label = format!\("browser-\{\}", uuid::Uuid::new_v4\(\)\);/); });