Remove the special cases for the old Browser package

A browser request now needs the session token of its window. Disabling
an old runestone.browser package no longer stops the engine. One list of
built-in modules starts the browser and the theme editor, and the plugin
menus skip their tools. The access rules no longer treat the browser ID
in a special way.
This commit is contained in:
Knotty Wyvern
2026-10-29 00:48:37 -07:00
parent 5dc53e4a5e
commit 48b8249ba6
13 changed files with 55 additions and 52 deletions
+6 -2
View File
@@ -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
+5 -10
View File
@@ -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<String>,
) -> Result<Value> {
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::<BrowserState>().require_session(&owner, &token)?;
} else {
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
}
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
let state = app.state::<BrowserState>();
// 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?
}
-6
View File
@@ -1365,13 +1365,7 @@ pub async fn plugins_set_enabled(
enabled: bool,
hash: Option<String>,
) -> 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::<crate::browser::BrowserState>().close_all()).await?;
}
changed(&app);
Ok(())
}
+1 -1
View File
@@ -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 })),
+4 -4
View File
@@ -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.",
+2 -2
View File
@@ -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;
+3 -3
View File
@@ -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<HTMLButtonElement>();
@@ -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);
+2 -2
View File
@@ -142,8 +142,8 @@
{/if}
</div>
</div>
{#if plugin.manifest.id === "runestone.browser"}<p class="note">{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}</p>{/if}
{#if plugin.manifest.id === "runestone.table-formulas"}<p class="note">{$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.")}</p>{/if}
{#if plugin.manifest.id === "runestone.table-formulas"}<p class="note">{$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.")}</p>
{:else if builtInPackages.includes(plugin.manifest.id)}<p class="note">{$t("RuneStone now includes {name}. You can remove this old package.", { name: plugin.manifest.name })}</p>{/if}
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
</div>
{/each}
+2 -3
View File
@@ -9,12 +9,11 @@ export type PluginTool = {
export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, views: Iterable<PluginView>): 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;
+19 -14
View File
@@ -79,6 +79,13 @@ export const pluginServiceError = writable("");
export const restartPlugins = writable<string[]>([]);
/** 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<PluginModule> }[] = [
{ 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<string, { hash: string; session: ExternalSession }>();
const failures = new Map<string, string>();
const errors: Record<string, string> = {};
@@ -86,7 +93,7 @@ const restarted = new Set<string>();
let queue: Promise<void> = 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<void> {
}
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)));
for (const builtIn of builtInModules) {
if (browserWindow && !builtIn.browserWindow) continue;
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));
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(); };
+1 -1
View File
@@ -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);
+6 -2
View File
@@ -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", () => {
@@ -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\(\)\);/);
});