perf(plugins): dock open latency and tab strip UX fixes
This commit is contained in:
1 parent
46cc9be7d9
commit
ccfb108aa1
7 files changed
+367
-117
No files matched your search
+10
-7
@@ -13,25 +13,28 @@ describe("pluginBottomDock", () => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("numbers same-command entries beyond the highest live suffix, never duplicating after a close", async () => {
|
||||
it("suffixes only on a title collision, taking the lowest free number; distinct titles stay verbatim", async () => {
|
||||
const dock = await loadModule();
|
||||
// Distinct titles (e.g. named connections) never get a number.
|
||||
dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "connection", commandId: "open-connection", title: "Prod" });
|
||||
dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "connection", commandId: "open-connection", title: "Staging" });
|
||||
const first = dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "command", commandId: "local.terminal", title: "Local terminal" });
|
||||
const second = dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "command", commandId: "local.terminal", title: "Local terminal" });
|
||||
dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "command", commandId: "local.terminal", title: "Local terminal" });
|
||||
expect(dock.usePluginBottomDock().entries.value.map((entry) => entry.title)).toEqual(["Local terminal", "Local terminal 2", "Local terminal 3"]);
|
||||
expect(dock.usePluginBottomDock().entries.value.map((entry) => entry.title)).toEqual(["Prod", "Staging", "Local terminal", "Local terminal 2", "Local terminal 3"]);
|
||||
|
||||
// Close the middle entry, then open another: the new title must not
|
||||
// collide with the surviving "Local terminal 3".
|
||||
// Close the middle entry, then open another: "Local terminal 2" is the
|
||||
// lowest free slot again (numbers belong to no entry once closed); the
|
||||
// reopened entry appends at the strip's end.
|
||||
dock.closePluginDockEntry(second);
|
||||
const fourth = dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "command", commandId: "local.terminal", title: "Local terminal" });
|
||||
expect(dock.usePluginBottomDock().entries.value.map((entry) => entry.title)).toEqual(["Local terminal", "Local terminal 3", "Local terminal 4"]);
|
||||
dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "command", commandId: "local.terminal", title: "Local terminal" });
|
||||
expect(dock.usePluginBottomDock().entries.value.map((entry) => entry.title)).toEqual(["Prod", "Staging", "Local terminal", "Local terminal 3", "Local terminal 2"]);
|
||||
|
||||
// Different commands number independently.
|
||||
dock.addPluginDockEntry({ pluginId: "io.dbx.ssh", workbenchContributionId: "local", kind: "command", commandId: "other.command", title: "Other" });
|
||||
const titles = dock.usePluginBottomDock().entries.value.map((entry) => entry.title);
|
||||
expect(titles[titles.length - 1]).toBe("Other");
|
||||
dock.closePluginDockEntry(first);
|
||||
dock.closePluginDockEntry(fourth);
|
||||
});
|
||||
|
||||
it("finds singleton reuse candidates only inside the same plugin+command+instance-key group (§4.1)", async () => {
|
||||
|
||||
@@ -51,17 +51,20 @@ export interface AddPluginDockEntryPayload {
|
||||
/** Creates (and activates) a dock terminal entry; returns its stable id. */
|
||||
export function addPluginDockEntry(payload: AddPluginDockEntryPayload): string {
|
||||
const id = uuid();
|
||||
// Same-command entries get a sequence suffix in the title (generic: "Local terminal 1 / 2 ..."),
|
||||
// keeps multi-instance panels distinguishable in the tab strip. Numbers are assigned at creation
|
||||
// and advance beyond the highest live suffix — never backfilled after a close, so titles stay
|
||||
// unique and stable (same convention as the plugin tabs in queryStore).
|
||||
// A sequence suffix is only added on a title collision within the same
|
||||
// command family ("Local terminal", "Local terminal 2", ...). Distinct
|
||||
// titles — e.g. named SSH connections — keep their name verbatim. Numbers
|
||||
// pick the lowest free slot, so a closed entry's number is reused instead
|
||||
// of climbing forever (titles stay unique among live entries, which is all
|
||||
// the tab strip needs to keep panels distinguishable).
|
||||
const siblings = dockEntries.value.filter((entry) => entry.pluginId === payload.pluginId && entry.commandId === payload.commandId);
|
||||
const nextNumber =
|
||||
siblings.reduce((highest, entry) => {
|
||||
const suffix = / (\d+)$/.exec(entry.title);
|
||||
return suffix ? Math.max(highest, Number(suffix[1])) : highest;
|
||||
}, 1) + 1;
|
||||
const title = siblings.length ? `${payload.title} ${nextNumber}` : payload.title;
|
||||
const taken = new Set(siblings.map((entry) => entry.title));
|
||||
let title = payload.title;
|
||||
if (taken.has(title)) {
|
||||
let suffix = 2;
|
||||
while (taken.has(`${payload.title} ${suffix}`)) suffix += 1;
|
||||
title = `${payload.title} ${suffix}`;
|
||||
}
|
||||
dockEntries.value.push({
|
||||
id,
|
||||
pluginId: payload.pluginId,
|
||||
|
||||
+51
-2
@@ -1,9 +1,26 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { clearPluginUiHtmlCache, getCachedPluginUiHtml, setCachedPluginUiHtml } from "./pluginUiHtmlCache";
|
||||
// @vitest-environment happy-dom
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readPluginUiEntry: vi.fn(),
|
||||
readPluginUiAsset: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
readPluginUiEntry: mocks.readPluginUiEntry,
|
||||
readPluginUiAsset: mocks.readPluginUiAsset,
|
||||
}));
|
||||
|
||||
import { clearPluginUiHtmlCache, getCachedPluginUiHtml, getOrLoadPluginUiHtml, setCachedPluginUiHtml } from "./pluginUiHtmlCache";
|
||||
|
||||
function uiEntryPayload(html: string): { dataBase64: string } {
|
||||
return { dataBase64: btoa(html) };
|
||||
}
|
||||
|
||||
describe("pluginUiHtmlCache", () => {
|
||||
beforeEach(() => {
|
||||
clearPluginUiHtmlCache();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("returns the stored document for the same plugin id+version key", () => {
|
||||
@@ -33,4 +50,36 @@ describe("pluginUiHtmlCache", () => {
|
||||
setCachedPluginUiHtml("io.dbx.ssh@0.4.88", { html: "old", entryDirectory: "" });
|
||||
expect(getCachedPluginUiHtml("io.dbx.ssh@0.4.89")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("getOrLoad resolves from the cache without touching the bridge", async () => {
|
||||
setCachedPluginUiHtml("io.dbx.ssh@0.4.88", { html: "cached", entryDirectory: "" });
|
||||
await expect(getOrLoadPluginUiHtml("io.dbx.ssh@0.4.88", "io.dbx.ssh")).resolves.toEqual({ html: "cached", entryDirectory: "" });
|
||||
expect(mocks.readPluginUiEntry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("coalesces concurrent misses into one pipeline run and caches the document", async () => {
|
||||
let release!: (value: { dataBase64: string }) => void;
|
||||
mocks.readPluginUiEntry.mockReturnValue(new Promise((resolve) => (release = resolve)));
|
||||
const first = getOrLoadPluginUiHtml("io.dbx.ssh@0.4.88", "io.dbx.ssh");
|
||||
const second = getOrLoadPluginUiHtml("io.dbx.ssh@0.4.88", "io.dbx.ssh");
|
||||
release(uiEntryPayload("<html>doc</html>"));
|
||||
await expect(first).resolves.toEqual({ html: "<html>doc</html>", entryDirectory: "" });
|
||||
await expect(second).resolves.toEqual({ html: "<html>doc</html>", entryDirectory: "" });
|
||||
// One bridge read served both callers (dock warm + panel mount).
|
||||
expect(mocks.readPluginUiEntry).toHaveBeenCalledTimes(1);
|
||||
// Subsequent callers hit the LRU without a new read.
|
||||
await expect(getOrLoadPluginUiHtml("io.dbx.ssh@0.4.88", "io.dbx.ssh")).resolves.toEqual({ html: "<html>doc</html>", entryDirectory: "" });
|
||||
expect(mocks.readPluginUiEntry).toHaveBeenCalledTimes(1);
|
||||
expect(getCachedPluginUiHtml("io.dbx.ssh@0.4.88")).toEqual({ html: "<html>doc</html>", entryDirectory: "" });
|
||||
});
|
||||
|
||||
it("keeps the cache untouched on failure and lets the next caller retry", async () => {
|
||||
mocks.readPluginUiEntry.mockRejectedValueOnce(new Error("bridge down"));
|
||||
await expect(getOrLoadPluginUiHtml("io.dbx.ssh@0.4.88", "io.dbx.ssh")).rejects.toThrow("bridge down");
|
||||
expect(getCachedPluginUiHtml("io.dbx.ssh@0.4.88")).toBeUndefined();
|
||||
// The failed in-flight slot is cleared, so a retry re-runs the pipeline.
|
||||
mocks.readPluginUiEntry.mockResolvedValueOnce(uiEntryPayload("<html>retry</html>"));
|
||||
await expect(getOrLoadPluginUiHtml("io.dbx.ssh@0.4.88", "io.dbx.ssh")).resolves.toEqual({ html: "<html>retry</html>", entryDirectory: "" });
|
||||
expect(mocks.readPluginUiEntry).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -3,10 +3,22 @@
|
||||
// the bridge and re-parses it each time. Module scope is the point: the cache
|
||||
// is shared by every PluginWorkbenchHost instance, so only the first boot of a
|
||||
// plugin version pays the read/decode/inline pipeline.
|
||||
const cache = new Map<string, { html: string; entryDirectory: string }>();
|
||||
import * as api from "@/lib/backend/api";
|
||||
|
||||
export interface PluginUiHtml {
|
||||
html: string;
|
||||
entryDirectory: string;
|
||||
/** Final sandbox document (html + CSP/SDK/theme injection); built lazily once
|
||||
* per plugin version — regenerating it re-runs megabyte-scale string surgery
|
||||
* on every panel/tab boot. The embedded appearance only affects the pre-init
|
||||
* first paint; the init message pushes the live theme right after. */
|
||||
sandboxDoc?: string;
|
||||
}
|
||||
|
||||
const cache = new Map<string, PluginUiHtml>();
|
||||
const LIMIT = 4;
|
||||
|
||||
export function getCachedPluginUiHtml(key: string): { html: string; entryDirectory: string } | undefined {
|
||||
export function getCachedPluginUiHtml(key: string): PluginUiHtml | undefined {
|
||||
const hit = cache.get(key);
|
||||
if (!hit) return undefined;
|
||||
// Map iterates oldest-first; re-inserting makes the just-read entry the
|
||||
@@ -16,7 +28,7 @@ export function getCachedPluginUiHtml(key: string): { html: string; entryDirecto
|
||||
return hit;
|
||||
}
|
||||
|
||||
export function setCachedPluginUiHtml(key: string, value: { html: string; entryDirectory: string }): void {
|
||||
export function setCachedPluginUiHtml(key: string, value: PluginUiHtml): void {
|
||||
cache.delete(key);
|
||||
cache.set(key, value);
|
||||
while (cache.size > LIMIT) cache.delete(cache.keys().next().value as string);
|
||||
@@ -25,4 +37,103 @@ export function setCachedPluginUiHtml(key: string, value: { html: string; entryD
|
||||
/** Test and plugin-uninstall escape hatch. */
|
||||
export function clearPluginUiHtmlCache(): void {
|
||||
cache.clear();
|
||||
inFlight.clear();
|
||||
}
|
||||
|
||||
// --- First-boot pipeline (read → decode → inline local assets) -------------
|
||||
|
||||
function localUiAssetPath(source: string): string | undefined {
|
||||
const trimmed = source.trim();
|
||||
if (!trimmed || /^(?:blob:|data:|https?:|\/\/)/i.test(trimmed)) return undefined;
|
||||
try {
|
||||
const resolved = new URL(trimmed, "https://dbx-plugin.invalid/");
|
||||
if (resolved.origin !== "https://dbx-plugin.invalid") return undefined;
|
||||
const path = decodeURIComponent(resolved.pathname).replace(/^\/+/, "");
|
||||
if (!path || path.split("/").some((segment) => segment === "..")) return undefined;
|
||||
return path;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function inlineLocalUiAssets(html: string, pluginId: string): Promise<PluginUiHtml> {
|
||||
// Shipped ui builds usually inline every asset into one HTML document.
|
||||
// Parsing and re-serializing a multi-megabyte document is pure overhead when
|
||||
// there is nothing local to inline — pre-check before touching DOMParser.
|
||||
if (!/<script\b[^>]*\bsrc=/i.test(html) && !/<link\b[^>]*rel=["']?stylesheet/i.test(html)) {
|
||||
return { html, entryDirectory: "" };
|
||||
}
|
||||
const document = new DOMParser().parseFromString(html, "text/html");
|
||||
const resources = [...document.querySelectorAll("script[src], link[rel='stylesheet'][href]")];
|
||||
// Dynamic-import chunks and CSS url() references live next to the entry
|
||||
// script; its directory is the <base> the sandbox document needs to resolve
|
||||
// them through the dbx-plugin scheme.
|
||||
let entryDirectory = "";
|
||||
// Fetch every referenced asset concurrently — these are bridge round-trips
|
||||
// into the sidecar, and panels reopen this path on every workbench (re)load.
|
||||
const fetched = await Promise.all(
|
||||
resources.map((resource) => {
|
||||
const source = resource.getAttribute(resource.tagName === "SCRIPT" ? "src" : "href");
|
||||
const path = source ? localUiAssetPath(source) : undefined;
|
||||
if (!path) return Promise.resolve({ resource, content: null });
|
||||
if (!entryDirectory) entryDirectory = path.split("/").slice(0, -1).join("/");
|
||||
return api.readPluginUiAsset(pluginId, path).then((asset) => ({
|
||||
resource,
|
||||
content: new TextDecoder().decode(Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0))),
|
||||
}));
|
||||
}),
|
||||
);
|
||||
for (const { resource, content } of fetched) {
|
||||
if (content === null) continue;
|
||||
if (resource.tagName === "SCRIPT") {
|
||||
const script = document.createElement("script");
|
||||
for (const attribute of [...resource.attributes]) {
|
||||
if (attribute.name !== "src") script.setAttribute(attribute.name, attribute.value);
|
||||
}
|
||||
script.textContent = content;
|
||||
resource.replaceWith(script);
|
||||
} else {
|
||||
const style = document.createElement("style");
|
||||
style.textContent = content;
|
||||
resource.replaceWith(style);
|
||||
}
|
||||
}
|
||||
return { html: document.documentElement.outerHTML, entryDirectory };
|
||||
}
|
||||
|
||||
/** Full first-boot pipeline: read the ui entry through the bridge, decode, inline local assets. */
|
||||
export async function loadPluginUiHtml(pluginId: string): Promise<PluginUiHtml> {
|
||||
const asset = await api.readPluginUiEntry(pluginId);
|
||||
const bytes = Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0));
|
||||
return inlineLocalUiAssets(new TextDecoder().decode(bytes), pluginId);
|
||||
}
|
||||
|
||||
// --- In-flight coalescing ---------------------------------------------------
|
||||
|
||||
const inFlight = new Map<string, Promise<PluginUiHtml>>();
|
||||
|
||||
/**
|
||||
* Cache-or-coalesced-load: a hit resolves synchronously-ish from the LRU;
|
||||
* a miss starts (or JOINS) the single in-flight pipeline for the key. Callers
|
||||
* that warm ahead of user intent (the dock "+" picker) and the panel mounting
|
||||
* moments later share one bridge read instead of racing duplicate
|
||||
* multi-megabyte pipelines. A failed load settles the cache untouched and
|
||||
* clears its in-flight slot, so the next caller retries cleanly.
|
||||
*/
|
||||
export function getOrLoadPluginUiHtml(key: string, pluginId: string): Promise<PluginUiHtml> {
|
||||
const hit = getCachedPluginUiHtml(key);
|
||||
if (hit) return Promise.resolve(hit);
|
||||
let load = inFlight.get(key);
|
||||
if (!load) {
|
||||
load = loadPluginUiHtml(pluginId)
|
||||
.then((value) => {
|
||||
setCachedPluginUiHtml(key, value);
|
||||
return value;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight.delete(key);
|
||||
});
|
||||
inFlight.set(key, load);
|
||||
}
|
||||
return load;
|
||||
}
|
||||
Reference in new issue
Block a user