Compare commits

...
25 changed files with 1158 additions and 5 deletions

No files matched your search

@@ -218,3 +218,52 @@ test('portForward.start surfaces live error status and message when tunnel start
restore();
}
});
test('views.open resolves visible contribution, triggers open without polluting context, and rejects missing/hidden views', async () => {
const opened: Array<{ viewId: string; context?: Record<string, unknown>; params?: unknown }> = [];
const queries: unknown[] = [];
const ctx: PluginVaultDataContext = {
...makeContext({}),
viewOpenRuntime: {
getPluginContributions: async (query) => {
queries.push(query);
return {
locale: 'en',
plugins: [{
id: 'com.example.db',
version: '1.0.0',
displayName: 'Database',
commands: [],
keybindings: [],
menus: [],
settings: [],
views: [
{ id: 'com.example.db.workbench', title: 'Database', location: 'vault-page', visible: true },
{ id: 'com.example.db.hidden', title: 'Hidden', location: 'vault-page', visible: false },
],
}],
};
},
requestOpenPluginView: (detail) => { opened.push(detail); },
},
};
const result = await handlePluginVaultDataRequest(
'views.open',
{ viewId: 'com.example.db.workbench', location: 'vault-page' },
ctx,
);
assert.deepEqual(result, { opened: true, focused: true, location: 'vault-page' });
assert.deepEqual(queries[0], { context: { 'netcatty.surface': 'vault-page' } });
assert.deepEqual(opened, [{ viewId: 'com.example.db.workbench' }]);
await assert.rejects(
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.hidden', location: 'vault-page' }, ctx),
/not available/,
);
await assert.rejects(
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.missing', location: 'vault-page' }, ctx),
/not available/,
);
assert.equal(opened.length, 1);
});
@@ -27,6 +27,7 @@ import {
applyPortForwardingRuntimeStatus,
getPortForwardingRuntimeRules,
} from './usePortForwardingState';
import { requestOpenPluginView } from './usePluginViewLifecycle';
export interface PluginPortForwardRuntimeDeps {
startPortForward?: typeof startPortForward;
@@ -36,10 +37,16 @@ export interface PluginPortForwardRuntimeDeps {
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
}
export interface PluginViewOpenRuntimeDeps {
getPluginContributions?: NonNullable<ReturnType<typeof netcattyBridge.get>>['getPluginContributions'];
requestOpenPluginView?: typeof requestOpenPluginView;
}
export type PluginVaultDataContext = {
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
resources: PluginHostActionResources;
portForwardRuntime?: PluginPortForwardRuntimeDeps;
viewOpenRuntime?: PluginViewOpenRuntimeDeps;
};
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
@@ -472,6 +479,42 @@ export async function handlePluginVaultDataRequest(
return { focused: true };
}
case 'views.open': {
const viewId = typeof payload.viewId === 'string' ? payload.viewId : '';
const location = typeof payload.location === 'string' ? payload.location : '';
if (!viewId) throw new Error('Plugin view ID is required');
const queryContext = location === 'vault-page'
? { 'netcatty.surface': 'vault-page' }
: location === 'terminal-sidebar'
? { 'netcatty.surface': 'terminal-sidebar' }
: { 'netcatty.surface': 'view' };
const getContributions = ctx.viewOpenRuntime?.getPluginContributions ?? netcattyBridge.get()?.getPluginContributions;
if (!getContributions) {
throw new Error('Plugin contributions are unavailable');
}
const snapshot = await getContributions({ context: queryContext });
const resolved = snapshot.plugins
.flatMap((plugin) => plugin.views)
.find((view) => view.id === viewId && view.visible);
if (!resolved) {
throw new Error(`Plugin view is not available: ${viewId}`);
}
if (resolved.location === 'terminal-sidebar') {
const sessionRuntime = getAppSessionRuntime();
const activeTabId = activeTabStore.getActiveTabId();
const isTerminalTab = Boolean(
sessionRuntime?.sessions.some((s) => s.id === activeTabId)
|| sessionRuntime?.workspaces.some((w) => w.id === activeTabId),
);
if (!isTerminalTab) {
throw new Error('An active terminal tab is required to open a terminal sidebar view');
}
}
const openView = ctx.viewOpenRuntime?.requestOpenPluginView ?? requestOpenPluginView;
openView({ viewId: resolved.id });
return { opened: true, focused: true, location: resolved.location };
}
default:
throw new Error(`Unsupported Vault data request: ${kind}`);
}
@@ -26,6 +26,7 @@ export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
export interface OpenPluginViewDetail {
viewId: string;
context?: Record<string, unknown>;
params?: unknown;
}
export type ResolvedPluginView = {
+5 -1
View File
@@ -73,8 +73,12 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
await act(async () => { selectSection('plugin-vault:missing'); await settle(); });
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); });
await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); });
await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); });
assert.equal(activeTabStore.getActiveTabId(), 'terminal:synthetic');
await act(async () => { requestOpenPluginView({ viewId: page.id, params: { connectionId: 'db-1' } }); await settle(); });
assert.equal(activeTabStore.getActiveTabId(), 'vault', 'opening a vault-page switches the active tab to vault');
assert.equal(opens.length, 2);
assert.deepEqual(opens[1].context, { 'netcatty.surface': 'vault-page' }, 'activation params must not be merged into contribution context');
await act(async () => { selectSection('hosts'); await settle(); });
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
} finally {
+1 -1
View File
@@ -13,7 +13,7 @@ mean complete. Existing APIs remain available.
| --- | --- | --- | --- | --- | --- | --- | --- |
| Authorization management | Engine `listGrants`, `revokeAll`, database audit | Manager shows declarations only | Host-only grant list, bounded audit summary, disable and revoke | Paths, session IDs, grant metadata are sensitive | Exact plugin ID, trusted app sender | Serialized manager mutation, disable before revoke, runtime teardown, retained audit | Batch 1 limited acceptance complete on ff3734d: independent review fixes, host/manager/UI tests, exact test/packaging CI, parent native own-views Application grant/revoke/disable/runtime-stop check. Visible view was manually closed beforehand. No plugin RPC for managing grants |
| Network and credential leases | `network.request`, `credentials.createLease`, single-use host redemption | SDK request omits lease and authorization fields | Canonical request types matching broker | Network mutation and credentials | Exact origin plus secret reference and operation | Existing timeout, redirects, byte quotas, runtime checks, lease TTL | Batch 1 contract/SDK consistency complete: canonical types, synthetic fixture/lease tests, feature discovery and exact CI. No live network or credential acceptance claimed. No plaintext secret API |
| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, UI contributions | No editor or SFTP menu slots | Existing contribution system | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits | Existing tests. New context menu slots planned with bounded context DTOs |
| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, `views.open` (own contributed view + `host-ui.activate`), UI contributions | No editor or SFTP menu slots | Existing contribution system and capability-gated `views.open` for own views | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits; 16 KiB UTF-8 cap on `views.open` params | Existing tests plus unit tests for `views.open` (no live Electron/CI acceptance claimed). New context menu slots planned with bounded context DTOs |
| Terminal providers | Decorations, links, completion, snapshots through provider requests | Session change delivery follows prior provider request and non-once grant | Preserve providers. Standalone selected-session watch planned | Hostnames, session state, endpoint identity | Host-selected session, runtime identity | Session-close and revoke cleanup, bounded event rate | Existing provider tests. Ordinary views cannot independently subscribe today |
| Current context and host picker | Host context keys are boolean state | `vault.metadata` enumeration is not generic SDK | Selected host/session DTO from an explicit whitelist | Labels and endpoint metadata are sensitive | Host-owned user-action context, selected host/session | TTL, runtime and session invalidation, redacted audit | Planned. Never reuse agent `sanitizeHostForAgent` as plugin DTO |
| Terminal selection and input draft | Provider-supplied snapshots, completion suggestions | No explicit selection-share or draft API | User shares selection, plugin proposes a visible editable draft | Terminal plaintext, accidental execution | Host action token plus exact live session/endpoint | Single-use token, size cap, no plaintext audit, active identity before commit | Planned. Reject Enter/control characters for draft insertion. No full history or direct shell |
+11
View File
@@ -87,6 +87,17 @@ stores only the plugin's own data, not host records or credentials. State scopes
separate placements and terminal sessions but are not an authorization boundary
against other code in the same plugin.
A plugin can open or focus one of its own contributed views with
`context.views.open({ viewId, params? })` (permission `views`; gated by
`views.vault-pages` for `vault-page`, `views.terminal-sidebar` for
`terminal-sidebar`, and `views.host-drawn` for `tab`, `aside`, `panel`, and
`modal`). Once the view is visible and focused in the main window, the host
delivers `{ kind: "host-ui.activate", instanceId, params? }` over
`context.views.onDidReceiveMessage(viewId, listener)` for both newly created
and retained instances without remounting an existing view. `params` is
optional plugin-defined JSON (at most 16 KiB UTF-8 serialized), never host
records or credentials, and is not merged into contribution `context`.
The main process binds each instance to its actual owner window and exact
plugin/runtime version. Close during activation, owner navigation/crash, plugin
disable/replacement/uninstall, runtime failure and App Lock invalidate it.
+7
View File
@@ -10,6 +10,13 @@ normal stacking. The plugin receives only the `netcatty.surface: vault-page`
context and its own interactions. Selection shares no Vault or session records.
Leaving and returning retains the view within the bounded lifecycle policy.
A plugin with `views` and negotiated `views.vault-pages` may also open or focus
its own `vault-page` via `context.views.open({ viewId, params? })`, switching
to the Vault tab and selecting that page while delivering
`{ kind: "host-ui.activate", instanceId, params? }` to the live instance
(retained or newly mounted). Listing still does not auto-activate pages, and
`params` is bounded plugin-defined JSON (not host records, credentials, or
contribution `context`).
Missing/disabled entries, invalid context or failed activation return to Hosts.
Late failure from an older selection cannot replace a newer page. App Lock,
disable and runtime termination clear the associated content and authority.
@@ -4078,6 +4078,45 @@
},
"additionalProperties": false
},
"ViewOpenLimits": {
"const": {
"maxParamsBytes": 16384
}
},
"ViewOpenParams": {
"type": "object",
"required": [
"viewId"
],
"properties": {
"viewId": {
"$ref": "#/$defs/ContributionId"
},
"params": {
"$ref": "#/$defs/JsonValue"
}
},
"additionalProperties": false
},
"ViewOpenResult": {
"type": "object",
"required": [
"opened",
"focused"
],
"properties": {
"opened": {
"type": "boolean"
},
"focused": {
"type": "boolean"
},
"location": {
"$ref": "#/$defs/ViewLocation"
}
},
"additionalProperties": false
},
"PluginViewBadge": {
"type": "object",
"required": [
@@ -4261,6 +4300,27 @@
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"kind",
"instanceId"
],
"properties": {
"kind": {
"const": "host-ui.activate"
},
"instanceId": {
"type": "string",
"minLength": 1,
"maxLength": 128
},
"params": {
"$ref": "#/$defs/JsonValue"
}
},
"additionalProperties": false
}
]
},
+90 -3
View File
@@ -17,7 +17,7 @@ class HostDrawnViewHost {
this.permissionEngine = permissionEngine ?? null;
this.runtimePool = runtimePool ?? null;
this.electron = electron; this.contributions = contributionService; this.isLocked = isLocked;
this.instances = new Map(); this.opening = new Map(); this.closed = false;
this.instances = new Map(); this.opening = new Map(); this.activationWaiters = new Set(); this.closed = false;
this.messageSubscription = contributionService.onDidPostViewMessage((event) => this.receive(event));
this.changeSubscription = contributionService.onDidChange?.((event) => {
for (const instance of [...this.instances.values()]) {
@@ -31,6 +31,7 @@ class HostDrawnViewHost {
});
this.unsubscribeLock = subscribeLock?.((state) => {
if (!state.locked) return;
this.#rejectActivationWaiters(new Error("Application is locked"));
for (const opening of this.opening.values()) opening.cancelled = true;
for (const id of [...this.instances.keys()]) void this.close(id, undefined, "app-locked");
});
@@ -68,7 +69,7 @@ class HostDrawnViewHost {
const activation = { pluginId: plugin.id, pluginVersion: plugin.activeVersion, viewId: view.id, runtimeId: identity.runtimeId };
this.contributions.assertViewActivationCurrent(activation, { context: payload.context });
const instance = { id, sender, owner, pluginId: plugin.id, viewId: view.id, activation,
context: structuredClone(payload.context ?? {}), identity, sequence: 0, lastRawCss: null, lastCanonicalCss: "", rateStart: Date.now(), rateCount: 0, ownerClosed: () => { void this.close(id, undefined, "owner-closed"); },
context: structuredClone(payload.context ?? {}), identity, ready: false, sequence: 0, lastRawCss: null, lastCanonicalCss: "", rateStart: Date.now(), rateCount: 0, ownerClosed: () => { void this.close(id, undefined, "owner-closed"); },
rendererGone: () => { void this.close(id, undefined, "renderer-gone"); }, navigating: null };
instance.navigating = (details, _url, isInPlace, isMainFrame) => {
if ((details?.isMainFrame ?? isMainFrame) !== false && (details?.isSameDocument ?? isInPlace) !== true) instance.rendererGone();
@@ -80,6 +81,8 @@ class HostDrawnViewHost {
ensure();
this.contributions.assertViewActivationCurrent(activation, { context: payload.context });
if (this.instances.get(id) !== instance) throw new Error("Plugin view opening was cancelled");
instance.ready = true;
this.#notifyInstanceReady(instance);
return { instanceId: id };
} catch (error) {
await this.close(id, undefined, "open-failed");
@@ -200,8 +203,92 @@ class HostDrawnViewHost {
message: { kind: "host-ui.close", instanceId: id } }, { expectedIdentity: instance.identity });
} catch { /* runtime may already have stopped */ }
}
#notifyInstanceReady(instance) {
for (const waiter of [...this.activationWaiters]) {
if (
waiter.pluginId === instance.pluginId
&& waiter.viewId === instance.viewId
&& (!waiter.sender || waiter.sender === instance.sender)
) {
waiter.finish(null, instance);
}
}
}
#rejectActivationWaiters(error) {
for (const waiter of [...this.activationWaiters]) {
waiter.finish(error);
}
}
#waitForInstanceReady({ pluginId, viewId, sender, timeoutMs, signal }) {
if (this.closed || this.isLocked()) return Promise.reject(new Error("Plugin view host is unavailable"));
if (signal?.aborted) return Promise.reject(signal.reason ?? new Error("Plugin view activation was cancelled"));
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.resolve(null);
return new Promise((resolve, reject) => {
const waiter = {
pluginId,
viewId,
sender,
timer: null,
onAbort: null,
finish(error, value) {
if (!this.active) return;
this.active = false;
if (this.timer) clearTimeout(this.timer);
if (this.onAbort) signal?.removeEventListener("abort", this.onAbort);
host.activationWaiters.delete(this);
if (error) reject(error);
else resolve(value);
},
active: true,
};
const host = this;
waiter.onAbort = () => waiter.finish(signal?.reason ?? new Error("Plugin view activation was cancelled"));
signal?.addEventListener("abort", waiter.onAbort, { once: true });
waiter.timer = setTimeout(() => waiter.finish(null, null), timeoutMs);
this.activationWaiters.add(waiter);
});
}
async activateViewInstances({ pluginId, viewId, sender = null, params, hasParams = false, timeoutMs = 10_000, signal } = {}) {
if (this.closed || this.isLocked()) throw new Error("Plugin view host is unavailable");
if (typeof pluginId !== "string" || typeof viewId !== "string" || !viewId.startsWith(`${pluginId}.`)) {
throw new TypeError("Invalid plugin view activation target");
}
const matchingReady = () => [...this.instances.values()].filter((instance) => (
instance.ready
&& instance.pluginId === pluginId
&& instance.viewId === viewId
&& (!sender || instance.sender === sender)
));
let targets = matchingReady();
if (targets.length === 0) {
const instance = await this.#waitForInstanceReady({ pluginId, viewId, sender, timeoutMs, signal });
if (instance) targets = [instance];
}
if (targets.length === 0) return { activated: 0 };
let activated = 0;
for (const instance of targets) {
if (this.closed || this.isLocked() || this.instances.get(instance.id) !== instance) continue;
this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
const message = {
kind: "host-ui.activate",
instanceId: instance.id,
...(hasParams ? { params: structuredClone(params) } : {}),
};
if (!validateMessage(message)) throw new TypeError("Invalid plugin view activate message");
await this.contributions.runtimeSupervisor.notify(
instance.pluginId,
"plugin.view.message",
{ viewId: instance.viewId, message },
{ expectedIdentity: instance.identity },
);
activated += 1;
}
return { activated };
}
async shutdown() {
this.closed = true; for (const opening of this.opening.values()) opening.cancelled = true;
this.closed = true;
this.#rejectActivationWaiters(new Error("Plugin view host shutting down"));
for (const opening of this.opening.values()) opening.cancelled = true;
await Promise.all([...this.instances.keys()].map((id) => this.close(id, undefined, "shutdown")));
this.messageSubscription?.dispose(); this.changeSubscription?.dispose(); this.unsubscribeLock?.();
this.resources?.dispose?.();
@@ -239,3 +239,69 @@ test("transient resource decode failures are evicted so retries can succeed", as
assert.equal(calls, 2);
await f.host.shutdown();
});
test("activateViewInstances delivers host-ui.activate to reused and newly created instances without changing host-ui.open", async () => {
// 1. Existing retained instance receives host-ui.activate with and without params
const f1 = fixture();
await open(f1);
assert.equal(f1.notifications.length, 1);
assert.equal(f1.notifications[0][2].message.kind, "host-ui.open");
assert.equal("params" in f1.notifications[0][2].message, false);
const reusedWithParams = await f1.host.activateViewInstances({
pluginId: "com.test.plugin",
viewId: "com.test.plugin.view",
sender: f1.sender,
hasParams: true,
params: { connectionId: "db-1" },
});
assert.deepEqual(reusedWithParams, { activated: 1 });
assert.deepEqual(f1.notifications.at(-1)[2], {
viewId: "com.test.plugin.view",
message: { kind: "host-ui.activate", instanceId: "instance-1", params: { connectionId: "db-1" } },
});
const reusedWithoutParams = await f1.host.activateViewInstances({
pluginId: "com.test.plugin",
viewId: "com.test.plugin.view",
sender: f1.sender,
hasParams: false,
});
assert.deepEqual(reusedWithoutParams, { activated: 1 });
assert.deepEqual(f1.notifications.at(-1)[2], {
viewId: "com.test.plugin.view",
message: { kind: "host-ui.activate", instanceId: "instance-1" },
});
// Wrong window sender receives 0 activations after bounded wait
const wrongWindow = await f1.host.activateViewInstances({
pluginId: "com.test.plugin",
viewId: "com.test.plugin.view",
sender: f1.other,
hasParams: false,
timeoutMs: 20,
});
assert.deepEqual(wrongWindow, { activated: 0 });
await f1.host.shutdown();
// 2. Newly created instance opened asynchronously receives host-ui.open followed by host-ui.activate
const f2 = fixture();
const pendingActivation = f2.host.activateViewInstances({
pluginId: "com.test.plugin",
viewId: "com.test.plugin.view",
sender: f2.sender,
hasParams: true,
params: { connectionId: "db-2" },
timeoutMs: 500,
});
setTimeout(() => { void open(f2); }, 15);
const freshResult = await pendingActivation;
assert.deepEqual(freshResult, { activated: 1 });
assert.equal(f2.notifications.length, 2);
assert.equal(f2.notifications[0][2].message.kind, "host-ui.open");
assert.deepEqual(f2.notifications[1][2], {
viewId: "com.test.plugin.view",
message: { kind: "host-ui.activate", instanceId: "instance-1", params: { connectionId: "db-2" } },
});
await f2.host.shutdown();
});
+13
View File
@@ -17,6 +17,7 @@ const { PluginCredentialBroker, assertLeaseParams } = require("./credentialBroke
const { PluginCredentialCatalog } = require("./credentialCatalog.cjs");
const { PluginContributionService } = require("./contributionService.cjs");
const { PluginViewBadgeService } = require("./viewBadgeService.cjs");
const { PluginViewOpenService } = require("./viewOpenService.cjs");
const { PluginViewResources } = require("./viewResourceService.cjs");
const { HostDrawnViewHost } = require("./hostDrawnViewHost.cjs");
const { createPooledContributionIconRasterizer } = require("./contributionIconRasterizer.cjs");
@@ -137,6 +138,7 @@ function createPluginHostService(options) {
let permissionDecisionHost;
let browserRuntimePool;
let viewBadgeService;
let viewOpenService;
let aiSidebarService;
let manager;
const logService = new PluginLogService({ paths, electron: options.electron, resolveProvenance: options.resolvePluginProvenance ?? createPluginLogProvenanceResolver(database) });
@@ -604,6 +606,14 @@ function createPluginHostService(options) {
subscribeLock: options.subscribeAppLock,
})
: null;
viewOpenService = new PluginViewOpenService({
vaultDataBridge,
hostDrawnViewHost,
supportedFeatures,
getWindow: options.getInteractionWindow,
isLocked: options.isAppLocked,
});
viewOpenService.registerRpcCapabilities(rpcRegistry);
const themeService = new PluginThemeService({database,packageStore,contributionService});
manager = new PluginManager({
secretStore,
@@ -615,6 +625,7 @@ function createPluginHostService(options) {
beforeClose: async () => {
try {
viewBadgeService?.shutdown();
viewOpenService?.shutdown();
aiSidebarService?.shutdown();
themeService.shutdown();
capabilitiesService?.shutdown();
@@ -682,10 +693,12 @@ function createPluginHostService(options) {
terminalDataPipelineService,
hostDrawnViewHost,
viewBadgeService,
viewOpenService,
aiSidebarService,
};
} catch (error) {
try { viewBadgeService?.shutdown(); } catch {}
try { viewOpenService?.shutdown(); } catch {}
try { aiSidebarService?.shutdown(); } catch {}
try { browserRuntimePool?.dispose(); } catch {}
try { permissionDecisionHost?.shutdown(); } catch {}
+1
View File
@@ -35,6 +35,7 @@ const ALLOWED_KINDS = new Set([
"terminals.openLocal",
"workspace.listTabs",
"workspace.focusTab",
"views.open",
]);
/**
+43
View File
@@ -349,6 +349,12 @@ function createEmitter() {
const FILE_CHUNK_BYTES = 2 * 1024 * 1024;
const FILE_DIALOG_DEADLINE_MS = 300_000;
const VIEW_OPEN_FEATURES = Object.freeze([
"views.host-drawn",
"views.vault-pages",
"views.terminal-sidebar",
]);
const VIEW_OPEN_MAX_PARAMS_BYTES = 16_384;
function bytesToBase64(bytes) {
if (typeof Buffer === "function") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
@@ -912,6 +918,43 @@ function createPluginContext(config, client, runtimeApi) {
}
return client.request("views.setBadge", params).then(() => undefined);
},
async open(options) {
if (!VIEW_OPEN_FEATURES.some((feature) => config.enabledFeatures?.includes(feature))) {
throw new PluginError(
"unsupported",
"Required view feature is not enabled: views.host-drawn, views.vault-pages, or views.terminal-sidebar",
);
}
if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new PluginError("invalid_argument", "Plugin view open parameters must be an object");
}
for (const key of Object.keys(options)) {
if (key !== "viewId" && key !== "params") {
throw new PluginError("invalid_argument", `Unknown plugin view open parameter: ${key}`);
}
}
const viewId = assertOwnedContributionId(config.pluginId, options.viewId, "Plugin view");
const hasParams = Object.hasOwn(options, "params") && options.params !== undefined;
if (hasParams) {
let serialized;
try {
serialized = JSON.stringify(options.params);
} catch {
throw new PluginError("invalid_argument", "Plugin view open params must be valid JSON");
}
if (serialized === undefined) {
throw new PluginError("invalid_argument", "Plugin view open params must be valid JSON");
}
if (new TextEncoder().encode(serialized).byteLength > VIEW_OPEN_MAX_PARAMS_BYTES) {
throw new PluginError("invalid_argument", `Plugin view open params exceed ${VIEW_OPEN_MAX_PARAMS_BYTES} bytes`);
}
}
const result = await client.request("views.open", {
viewId,
...(hasParams ? { params: options.params } : {}),
});
return Object.freeze(result);
},
};
const providers = {
register(providerId, kind, handler) {
+99
View File
@@ -645,3 +645,102 @@ test("actual SDK directory call rejects an unnegotiated feature without sending
await host.request("plugin.activate", {});
assert.equal(requests, 0);
});
test("runtime peer views.open enforces view feature gating, ownership, and payload bounds", async (context) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
// 1. Rejects when no view location feature is enabled without sending host RPC
{
const { port1, port2 } = new MessageChannel();
let rpcCalls = 0;
const host = new PluginRpcRouter({
pluginId: "com.example.db",
send: (message) => port1.postMessage(message),
handlers: {
"views.open": async () => { rpcCalls += 1; return { opened: true, focused: true, location: "vault-page" }; },
},
});
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({
port: port2,
config: { pluginId: "com.example.db", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: [] },
async loadPlugin() {
return {
default: {
async activate(pluginContext) {
await assert.rejects(
() => pluginContext.views.open({ viewId: "com.example.db.workbench" }),
(error) => error?.code === "unsupported" && /views\./.test(error.message),
);
},
},
};
},
});
context.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: [] });
await host.request("plugin.activate", {});
assert.equal(rpcCalls, 0);
}
// 2. Happy path forwards params, rejects foreign view ids and oversize payloads
{
const { port1, port2 } = new MessageChannel();
const received = [];
const host = new PluginRpcRouter({
pluginId: "com.example.db",
send: (message) => port1.postMessage(message),
handlers: {
"views.open": async (params) => {
received.push(params);
return { opened: true, focused: true, location: "vault-page" };
},
},
});
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({
port: port2,
config: {
pluginId: "com.example.db",
pluginVersion: "1.0.0",
netcattyVersion: "1.0.0",
apiVersion: "0.1.0-internal",
enabledFeatures: ["views.vault-pages"],
},
async loadPlugin() {
return {
default: {
async activate(pluginContext) {
const result = await pluginContext.views.open({
viewId: "com.example.db.workbench",
params: { connectionId: "conn-42", autoConnect: true },
});
assert.deepEqual(result, { opened: true, focused: true, location: "vault-page" });
assert.equal(Object.isFrozen(result), true);
await assert.rejects(
() => pluginContext.views.open({ viewId: "com.other.db.workbench" }),
(error) => error?.code === "invalid_argument",
);
await assert.rejects(
() => pluginContext.views.open({ viewId: "com.example.db.workbench", params: { blob: "x".repeat(17_000) } }),
(error) => error?.code === "invalid_argument",
);
await assert.rejects(
() => pluginContext.views.open({ viewId: "com.example.db.workbench", unknownKey: 1 }),
(error) => error?.code === "invalid_argument",
);
},
},
};
},
});
context.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: ["views.vault-pages"] });
await host.request("plugin.activate", {});
assert.deepEqual(received, [{
viewId: "com.example.db.workbench",
params: { connectionId: "conn-42", autoConnect: true },
}]);
}
});
+214
View File
@@ -0,0 +1,214 @@
"use strict";
const contractSchema = require("./generated/plugin-contract.schema.json");
const { createDefinitionValidator } = require("./contractValidator.cjs");
const { assertPluginJsonValue } = require("./jsonBoundary.cjs");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const { invalidArgument, freezeJson } = require("./validationUtils.cjs");
const VIEW_OPEN_MAX_PARAMS_BYTES = contractSchema.$defs.ViewOpenLimits.const.maxParamsBytes;
const VAULT_PAGES_FEATURE = contractSchema.$defs.VaultPagesFeature.const;
const TERMINAL_SIDEBAR_FEATURE = contractSchema.$defs.TerminalSidebarFeature.const;
const HOST_DRAWN_VIEWS_FEATURE = contractSchema.$defs.HostDrawnViewsFeature.const;
const HOST_DRAWN_LOCATIONS = new Set(["tab", "aside", "panel", "modal"]);
const DEFAULT_ACTIVATE_TIMEOUT_MS = 10_000;
const MAX_ACTIVATE_TIMEOUT_MS = 15_000;
const validateViewOpenParamsSchema = createDefinitionValidator("ViewOpenParams");
function isPlainObject(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function requiredFeatureForViewLocation(location) {
if (location === "vault-page") return VAULT_PAGES_FEATURE;
if (location === "terminal-sidebar") return TERMINAL_SIDEBAR_FEATURE;
if (HOST_DRAWN_LOCATIONS.has(location)) return HOST_DRAWN_VIEWS_FEATURE;
return null;
}
function validateViewOpenParams(rawParams) {
if (!isPlainObject(rawParams)) {
throw invalidArgument("Plugin view open parameters must be an object");
}
if (!validateViewOpenParamsSchema(rawParams)) {
throw invalidArgument("Invalid parameters for ViewOpenParams");
}
const hasParams = Object.hasOwn(rawParams, "params") && rawParams.params !== undefined;
if (hasParams) {
try {
assertPluginJsonValue(rawParams.params, { maxBytes: VIEW_OPEN_MAX_PARAMS_BYTES });
} catch (error) {
throw invalidArgument(
error instanceof Error && error.message
? error.message
: `Plugin view open params exceed ${VIEW_OPEN_MAX_PARAMS_BYTES} bytes`,
);
}
}
return Object.freeze({
viewId: rawParams.viewId,
...(hasParams ? { params: freezeJson(rawParams.params) } : {}),
});
}
function resolveOwnedView(manifest, viewId, pluginId) {
if (typeof viewId !== "string" || !viewId.startsWith(`${pluginId}.`) || viewId.length > 256) {
throw new PluginRpcError(RPC_ERRORS.notFound, `Plugin view contribution was not found: ${viewId}`);
}
const view = manifest?.contributes?.views?.find((item) => item?.id === viewId) ?? null;
if (!view) {
throw new PluginRpcError(RPC_ERRORS.notFound, `Plugin view contribution was not found: ${viewId}`);
}
return view;
}
class PluginViewOpenService {
constructor(options = {}) {
this.getVaultDataBridge = typeof options.getVaultDataBridge === "function"
? options.getVaultDataBridge
: () => options.vaultDataBridge ?? null;
this.getHostDrawnViewHost = typeof options.getHostDrawnViewHost === "function"
? options.getHostDrawnViewHost
: () => options.hostDrawnViewHost ?? null;
this.getWindow = options.getWindow ?? null;
this.supportedFeatures = Array.isArray(options.supportedFeatures)
? [...options.supportedFeatures]
: null;
this.isLocked = options.isLocked ?? (() => false);
this.activateTimeoutMs = Math.min(
Math.max(1, options.activateTimeoutMs ?? DEFAULT_ACTIVATE_TIMEOUT_MS),
MAX_ACTIVATE_TIMEOUT_MS,
);
this.closed = false;
}
#requireFeature(context, feature) {
const required = context?.manifest?.features?.required;
const optional = context?.manifest?.features?.optional;
const declared = (Array.isArray(required) && required.includes(feature))
|| (Array.isArray(optional) && optional.includes(feature));
if (!declared || (this.supportedFeatures && !this.supportedFeatures.includes(feature))) {
throw new PluginRpcError(RPC_ERRORS.unsupported, `Required feature was not negotiated: ${feature}`);
}
}
registerRpcCapabilities(registry) {
registry.registerRequest("views.open", (params, context) => this.open(params, context), {
metadata: { capability: "views", mutating: true, permission: "views" },
validateParams: (params) => validateViewOpenParams(params),
authorization: (params, context) => {
if (this.isLocked()) {
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
}
const view = resolveOwnedView(context.manifest, params.viewId, context.pluginId);
const feature = requiredFeatureForViewLocation(view.location);
if (!feature) {
throw new PluginRpcError(RPC_ERRORS.unsupported, `Unsupported plugin view location: ${String(view.location)}`);
}
this.#requireFeature(context, feature);
return {
permission: "views",
resources: ["*"],
reason: "Open and focus a plugin view",
operationId: "views.open",
};
},
});
}
async open(params, context) {
await context?.assertActive?.();
if (this.closed) {
throw new PluginRpcError(RPC_ERRORS.unavailable, "Plugin view open service is closed");
}
if (this.isLocked()) {
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
}
const validated = validateViewOpenParams(params);
const view = resolveOwnedView(context?.manifest, validated.viewId, context?.pluginId);
const feature = requiredFeatureForViewLocation(view.location);
if (!feature) {
throw new PluginRpcError(RPC_ERRORS.unsupported, `Unsupported plugin view location: ${String(view.location)}`);
}
this.#requireFeature(context, feature);
const vaultDataBridge = this.getVaultDataBridge();
const hostDrawnViewHost = this.getHostDrawnViewHost();
if (!vaultDataBridge || !hostDrawnViewHost) {
throw new PluginRpcError(RPC_ERRORS.unavailable, "Plugin view host is unavailable");
}
const shown = await vaultDataBridge.request(
"views.open",
{ viewId: view.id, location: view.location },
context?.signal,
);
await context?.assertActive?.();
if (this.isLocked()) {
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
}
if (!shown || shown.opened !== true || shown.focused !== true) {
throw new PluginRpcError(RPC_ERRORS.unavailable, `Plugin view could not be opened: ${view.id}`);
}
const ownerWindow = this.getWindow?.() ?? vaultDataBridge.getWindow?.() ?? null;
const sender = ownerWindow && !ownerWindow.isDestroyed?.()
? (ownerWindow.webContents ?? null)
: (vaultDataBridge.owner ?? null);
const hasParams = Object.hasOwn(validated, "params") && validated.params !== undefined;
let activation;
try {
activation = await hostDrawnViewHost.activateViewInstances({
pluginId: context.pluginId,
viewId: view.id,
sender,
hasParams,
...(hasParams ? { params: validated.params } : {}),
timeoutMs: this.activateTimeoutMs,
signal: context?.signal,
});
} catch (error) {
if (error instanceof PluginRpcError) throw error;
if (context?.signal?.aborted) {
throw new PluginRpcError(RPC_ERRORS.cancelled, "Plugin view open was cancelled");
}
if (this.isLocked()) {
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
}
throw new PluginRpcError(
RPC_ERRORS.unavailable,
error instanceof Error && error.message
? error.message.slice(0, 256)
: `Plugin view could not be activated: ${view.id}`,
);
}
await context?.assertActive?.();
if (!activation || !(activation.activated >= 1)) {
throw new PluginRpcError(RPC_ERRORS.unavailable, `Plugin view did not open in the main window: ${view.id}`);
}
return Object.freeze({
opened: true,
focused: true,
location: view.location,
});
}
shutdown() {
this.closed = true;
}
}
module.exports = {
DEFAULT_ACTIVATE_TIMEOUT_MS,
HOST_DRAWN_LOCATIONS,
PluginViewOpenService,
VIEW_OPEN_MAX_PARAMS_BYTES,
requiredFeatureForViewLocation,
resolveOwnedView,
validateViewOpenParams,
};
+217
View File
@@ -0,0 +1,217 @@
"use strict";
const assert = require("node:assert/strict");
const test = require("node:test");
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
const { PluginViewOpenService, VIEW_OPEN_MAX_PARAMS_BYTES } = require("./viewOpenService.cjs");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
function makeContext(overrides = {}) {
const pluginId = overrides.pluginId ?? "com.example.database";
return {
pluginId,
pluginVersion: "1.0.0",
runtimeId: overrides.runtimeId ?? "runtime-1",
signal: overrides.signal,
assertActive: overrides.assertActive ?? (async () => {}),
manifest: overrides.manifest ?? {
id: pluginId,
features: {
required: overrides.requiredFeatures ?? ["views.host-drawn", "views.vault-pages", "views.terminal-sidebar"],
optional: overrides.optionalFeatures ?? [],
},
contributes: {
views: [
{ id: `${pluginId}.workbench`, title: "Database", location: "vault-page" },
{ id: `${pluginId}.connection`, title: "Connection", location: "modal" },
{ id: `${pluginId}.sidebar`, title: "Sidebar", location: "terminal-sidebar" },
{ id: `${pluginId}.tab`, title: "Tab", location: "tab" },
],
},
},
};
}
function makeHarness(options = {}) {
const bridgeCalls = [];
const activateCalls = [];
let locked = Boolean(options.locked);
const sender = { isDestroyed: () => false };
const win = { webContents: sender, isDestroyed: () => false };
const vaultDataBridge = options.vaultDataBridge ?? {
owner: sender,
getWindow: () => win,
async request(kind, payload) {
bridgeCalls.push({ kind, payload });
if (options.bridgeError) throw options.bridgeError;
return options.bridgeResult ?? { opened: true, focused: true, location: payload.location };
},
};
const hostDrawnViewHost = options.hostDrawnViewHost ?? {
async activateViewInstances(call) {
activateCalls.push(call);
if (options.activateError) throw options.activateError;
return options.activateResult ?? { activated: 1 };
},
};
const service = new PluginViewOpenService({
vaultDataBridge,
hostDrawnViewHost,
supportedFeatures: options.supportedFeatures ?? ["views.host-drawn", "views.vault-pages", "views.terminal-sidebar"],
getWindow: () => win,
isLocked: () => locked,
activateTimeoutMs: options.activateTimeoutMs ?? 50,
});
return {
service,
bridgeCalls,
activateCalls,
sender,
setLocked(next) { locked = next; },
};
}
test("PluginViewOpenService opens own vault-page, delivers activation params, and returns honest result", async () => {
const h = makeHarness();
const ctx = makeContext();
const withParams = await h.service.open({
viewId: "com.example.database.workbench",
params: { connectionId: "conn-1", action: "connect" },
}, ctx);
assert.deepEqual(withParams, { opened: true, focused: true, location: "vault-page" });
assert.deepEqual(h.bridgeCalls, [
{ kind: "views.open", payload: { viewId: "com.example.database.workbench", location: "vault-page" } },
]);
assert.equal(h.activateCalls.length, 1);
assert.equal(h.activateCalls[0].pluginId, "com.example.database");
assert.equal(h.activateCalls[0].viewId, "com.example.database.workbench");
assert.equal(h.activateCalls[0].sender, h.sender);
assert.equal(h.activateCalls[0].hasParams, true);
assert.deepEqual(h.activateCalls[0].params, { connectionId: "conn-1", action: "connect" });
// Omitting params sets hasParams=false and still delivers host-ui.activate
const withoutParams = await h.service.open({ viewId: "com.example.database.connection" }, ctx);
assert.deepEqual(withoutParams, { opened: true, focused: true, location: "modal" });
assert.equal(h.activateCalls[1].hasParams, false);
assert.equal("params" in h.activateCalls[1], false);
});
test("PluginViewOpenService rejects other plugin's view and undeclared own view with notFound", async () => {
const h = makeHarness();
const ctx = makeContext();
await assert.rejects(
() => h.service.open({ viewId: "com.other.plugin.workbench" }, ctx),
(err) => err?.code === RPC_ERRORS.notFound,
);
await assert.rejects(
() => h.service.open({ viewId: "com.example.database.nonexistent" }, ctx),
(err) => err?.code === RPC_ERRORS.notFound,
);
assert.equal(h.bridgeCalls.length, 0);
assert.equal(h.activateCalls.length, 0);
});
test("PluginViewOpenService enforces location-specific feature negotiation", async () => {
const h = makeHarness();
// vault-page requires views.vault-pages
await assert.rejects(
() => h.service.open({ viewId: "com.example.database.workbench" }, makeContext({ requiredFeatures: ["views.host-drawn"] })),
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.vault-pages"),
);
// terminal-sidebar requires views.terminal-sidebar
await assert.rejects(
() => h.service.open({ viewId: "com.example.database.sidebar" }, makeContext({ requiredFeatures: ["views.host-drawn", "views.vault-pages"] })),
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.terminal-sidebar"),
);
// modal / tab require views.host-drawn
await assert.rejects(
() => h.service.open({ viewId: "com.example.database.connection" }, makeContext({ requiredFeatures: ["views.vault-pages"] })),
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.host-drawn"),
);
// Host without views.vault-pages supported also rejects even if manifest lists it as optional
const unsupportedHost = makeHarness({ supportedFeatures: ["views.host-drawn"] });
await assert.rejects(
() => unsupportedHost.service.open(
{ viewId: "com.example.database.workbench" },
makeContext({ requiredFeatures: ["views.host-drawn"], optionalFeatures: ["views.vault-pages"] }),
),
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.vault-pages"),
);
assert.equal(h.bridgeCalls.length, 0);
});
test("PluginViewOpenService rejects locked app with failedPrecondition and malformed/oversize params with invalidArgument", async () => {
const h = makeHarness({ locked: true });
const ctx = makeContext();
await assert.rejects(
() => h.service.open({ viewId: "com.example.database.workbench" }, ctx),
(err) => err?.code === RPC_ERRORS.failedPrecondition && /locked/i.test(err.message),
);
h.setLocked(false);
for (const invalid of [
null,
{},
{ viewId: "" },
{ viewId: "com.example.database.workbench", extra: true },
{ viewId: "com.example.database.workbench", params: { blob: "x".repeat(VIEW_OPEN_MAX_PARAMS_BYTES + 1) } },
]) {
await assert.rejects(
() => h.service.open(invalid, ctx),
(err) => err?.code === RPC_ERRORS.invalidArgument,
);
}
assert.equal(h.bridgeCalls.length, 0);
});
test("PluginViewOpenService fails honestly with unavailable when surface or live instance does not appear", async () => {
const noInstance = makeHarness({ activateResult: { activated: 0 } });
await assert.rejects(
() => noInstance.service.open({ viewId: "com.example.database.workbench" }, makeContext()),
(err) => err?.code === RPC_ERRORS.unavailable,
);
const bridgeFailed = makeHarness({
bridgeError: new PluginRpcError(RPC_ERRORS.unavailable, "Vault data host is unavailable"),
});
await assert.rejects(
() => bridgeFailed.service.open({ viewId: "com.example.database.workbench" }, makeContext()),
(err) => err?.code === RPC_ERRORS.unavailable,
);
});
test("PluginViewOpenService registers views.open under views permission without requiring workspace permissions", async () => {
const h = makeHarness();
const registry = new PluginHostRpcRegistry();
const authRequests = [];
registry.use(async (ctx, next) => {
authRequests.push(ctx.authorization);
return next();
});
h.service.registerRpcCapabilities(registry);
const ctx = makeContext({ requiredFeatures: ["views.vault-pages"] });
const routes = registry.createRoutes({
pluginId: ctx.pluginId,
pluginVersion: ctx.pluginVersion,
runtimeId: ctx.runtimeId,
runtimeKind: "browser",
manifest: ctx.manifest,
});
const result = await routes.requestHandlers["views.open"](
{ viewId: "com.example.database.workbench", params: { connectionId: "db-1" } },
{},
);
assert.deepEqual(result, { opened: true, focused: true, location: "vault-page" });
assert.equal(authRequests.length, 1);
assert.equal(authRequests[0].permission, "views");
});
@@ -3475,6 +3475,45 @@
},
"additionalProperties": false
},
"ViewOpenLimits": {
"const": {
"maxParamsBytes": 16384
}
},
"ViewOpenParams": {
"type": "object",
"required": [
"viewId"
],
"properties": {
"viewId": {
"$ref": "#/$defs/ContributionId"
},
"params": {
"$ref": "#/$defs/JsonValue"
}
},
"additionalProperties": false
},
"ViewOpenResult": {
"type": "object",
"required": [
"opened",
"focused"
],
"properties": {
"opened": {
"type": "boolean"
},
"focused": {
"type": "boolean"
},
"location": {
"$ref": "#/$defs/ViewLocation"
}
},
"additionalProperties": false
},
"PluginViewBadge": {
"type": "object",
"required": [
@@ -3658,6 +3697,27 @@
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"kind",
"instanceId"
],
"properties": {
"kind": {
"const": "host-ui.activate"
},
"instanceId": {
"type": "string",
"minLength": 1,
"maxLength": 128
},
"params": {
"$ref": "#/$defs/JsonValue"
}
},
"additionalProperties": false
}
]
},
@@ -1515,3 +1515,67 @@ test("HostDrawnViewEvent accepts pointer and wheel fields while rejecting out-of
assert.equal(validate(invalid), false, JSON.stringify(invalid));
}
});
test("ViewOpenParams, ViewOpenResult, and HostDrawnViewMessage host-ui.activate schemas enforce bounds and reject unknown keys", async () => {
const { PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES, serializeJsonValue } = await import("./index.ts");
assert.equal(PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES, 16384);
const validateOpenParams = validator("ViewOpenParams");
for (const valid of [
{ viewId: "com.example.db.workbench" },
{ viewId: "com.example.db.workbench", params: { connectionId: "conn-1", focus: true } },
{ viewId: "com.example.db.workbench", params: null },
]) {
assert.equal(validateOpenParams(valid), true, JSON.stringify(validateOpenParams.errors));
}
for (const invalid of [
{},
{ viewId: "" },
{ viewId: "bad" },
{ viewId: "com.example.db.workbench", extra: true },
{ viewId: "com.example.db.workbench", context: { "netcatty.surface": "vault-page" } },
]) {
assert.equal(validateOpenParams(invalid), false, JSON.stringify(invalid));
}
const atLimit = { payload: "a".repeat(PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES - 14) };
assert.equal(Buffer.byteLength(serializeJsonValue(atLimit), "utf8"), PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES);
const overLimit = { payload: "a".repeat(PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES) };
assert.ok(Buffer.byteLength(serializeJsonValue(overLimit), "utf8") > PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES);
const validateOpenResult = validator("ViewOpenResult");
for (const valid of [
{ opened: true, focused: true },
{ opened: true, focused: true, location: "vault-page" },
{ opened: true, focused: true, location: "terminal-sidebar" },
{ opened: true, focused: true, location: "modal" },
]) {
assert.equal(validateOpenResult(valid), true, JSON.stringify(validateOpenResult.errors));
}
for (const invalid of [
{ opened: true },
{ focused: true },
{ opened: true, focused: true, location: "settings" },
{ opened: true, focused: true, location: "vault-page", extra: 1 },
]) {
assert.equal(validateOpenResult(invalid), false, JSON.stringify(invalid));
}
const validateViewMessage = validator("HostDrawnViewMessage");
for (const valid of [
{ kind: "host-ui.open", instanceId: "inst-1" },
{ kind: "host-ui.open", instanceId: "inst-1", stateScope: "scope-hash" },
{ kind: "host-ui.activate", instanceId: "inst-1" },
{ kind: "host-ui.activate", instanceId: "inst-1", params: { connectionId: "conn-1" } },
{ kind: "host-ui.activate", instanceId: "inst-1", params: null },
]) {
assert.equal(validateViewMessage(valid), true, JSON.stringify(validateViewMessage.errors));
}
for (const invalid of [
{ kind: "host-ui.activate" },
{ kind: "host-ui.activate", instanceId: "" },
{ kind: "host-ui.activate", instanceId: "inst-1", extra: true },
{ kind: "host-ui.open", instanceId: "inst-1", extra: true },
]) {
assert.equal(validateViewMessage(invalid), false, JSON.stringify(invalid));
}
});
@@ -25,3 +25,4 @@ export const PLUGIN_SYNC_MAX_OBJECT_BYTES = 67108864 as const;
export const PLUGIN_SYNC_MAX_OBJECT_KEY_LENGTH = 1024 as const;
export const PLUGIN_SYNC_MAX_REVISION_LENGTH = 256 as const;
export const PLUGIN_SYNC_INLINE_OBJECT_BYTES = 92160 as const;
export const PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES = 16384 as const;
@@ -320,6 +320,10 @@ export type HostDrawnViewMessage = ({
kind: "host-ui.event";
instanceId: string;
event: HostDrawnViewEvent;
}) | ({
kind: "host-ui.activate";
instanceId: string;
params?: JsonValue;
});
export type HostDrawnViewOpenRequest = {
@@ -2336,6 +2340,19 @@ export type ViewContribution = {
export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "vault-page" | "terminal-sidebar";
export type ViewOpenLimits = {"maxParamsBytes":16384};
export type ViewOpenParams = {
viewId: ContributionId;
params?: JsonValue;
};
export type ViewOpenResult = {
opened: boolean;
focused: boolean;
location?: ViewLocation;
};
export type WireIntegerLimits = {"maxSafeInteger":9007199254740991};
export type WorkspaceFocusTabParams = {
+1
View File
@@ -24,6 +24,7 @@ export {
PLUGIN_SYNC_MAX_REVISION_LENGTH,
PLUGIN_TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES,
PLUGIN_TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES,
PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES,
PLUGIN_WIRE_MAX_SAFE_INTEGER,
} from "./generated/plugin-contract-limits.js";
export {
@@ -865,3 +865,78 @@ test('hostDom dispatches pointer drag, pan, cancel, and wheel zoom events into a
dom.window.close();
}
});
test('registerHostReactView ignores host-ui.activate without remounting or dropping the mounted view', async () => {
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
const { act, useEffect, useState } = await import('react');
const { registerHostReactView } = await import('./hostReact.js');
const listeners = new Set<(value: JsonValue) => void>();
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
const views = {
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) {
listeners.add(listener);
return { dispose() { listeners.delete(listener); } };
},
postMessage(_id: string, value: JsonValue) {
messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>);
},
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
open: async () => ({ opened: true, focused: true }),
};
const deliver = (value: JsonValue) => { for (const listener of listeners) listener(value); };
let mountCount = 0;
let unmountCount = 0;
const activatedPayloads: JsonValue[] = [];
const pluginListener = views.onDidReceiveMessage('com.example.workbench', (msg) => {
if (msg && typeof msg === 'object' && !Array.isArray(msg) && msg.kind === 'host-ui.activate') {
activatedPayloads.push(msg);
}
});
function Workbench() {
const [count] = useState(() => ++mountCount);
useEffect(() => () => { unmountCount += 1; }, []);
return <div id="workbench-root">Mount #{count}</div>;
}
const registration = registerHostReactView(views, 'com.example.workbench', () => <Workbench />);
try {
await act(async () => {
deliver({ kind: 'host-ui.open', instanceId: 'wb-1' });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(mountCount, 1);
assert.equal(unmountCount, 0);
assert.equal(document.querySelectorAll('#workbench-root').length, 1);
assert.equal(document.getElementById('workbench-root')?.textContent, 'Mount #1');
// Sending host-ui.activate must neither remount nor drop the existing view.
await act(async () => {
deliver({ kind: 'host-ui.activate', instanceId: 'wb-1', params: { connectionId: 'db-42' } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(mountCount, 1, 'host-ui.activate must not remount the view');
assert.equal(unmountCount, 0, 'host-ui.activate must not unmount the view');
assert.equal(document.querySelectorAll('#workbench-root').length, 1, 'host-ui.activate must not create a second instance');
assert.deepEqual(activatedPayloads, [{ kind: 'host-ui.activate', instanceId: 'wb-1', params: { connectionId: 'db-42' } }]);
await act(async () => { deliver({ kind: 'host-ui.close', instanceId: 'wb-1' }); });
assert.equal(unmountCount, 1);
} finally {
pluginListener.dispose();
await act(async () => { registration.dispose(); });
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});
+13
View File
@@ -38,6 +38,15 @@ test("byte streams and AI/context clients expose only canonical requests", () =>
await context.ai.readTurn({ turnHandle: turn.turnHandle });
const selected = await context.selectedContext.list({});
await context.selectedContext.read({ handle: selected.items[0].handle, version: selected.items[0].version });
const opened = await context.views.open({ viewId: "com.example.plugin.workbench", params: { connectionId: "db-1" } });
const _openedFlag: boolean = opened.opened;
const _focusedFlag: boolean = opened.focused;
void _openedFlag;
void _focusedFlag;
// @ts-expect-error views.open result is readonly
opened.focused = false;
// @ts-expect-error views.open rejects unknown properties
await context.views.open({ viewId: "com.example.plugin.workbench", context: {} });
// @ts-expect-error source identity is host-owned
await context.network.connect({ endpoint: "tcp://example.test:22", sourceOwner: "spoofed" });
// @ts-expect-error TLS validation cannot be disabled
@@ -72,9 +81,13 @@ function assertSdkTypeChecks(source: string) {
const fixturePath = join(sdkDirectory, "__provider-overload-fixture.ts");
const compilerOptions: ts.CompilerOptions = {
allowImportingTsExtensions: true,
baseUrl: sdkDirectory,
module: ts.ModuleKind.NodeNext,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
noEmit: true,
paths: {
"@netcatty/plugin-contract": ["../../plugin-contract/src/index.ts"],
},
skipLibCheck: true,
strict: true,
target: ts.ScriptTarget.ES2022,
+2
View File
@@ -256,6 +256,8 @@ export interface PluginViews {
/** Sets or clears a notification badge on one of this plugin's declared vault-page or terminal-sidebar views. */
setBadge(badge: import("@netcatty/plugin-contract").ViewBadgeParams): Promise<void>;
setBadge(viewId: string, badge: Omit<import("@netcatty/plugin-contract").ViewBadgeParams, "viewId"> | null): Promise<void>;
/** Opens or focuses one of this plugin's contributed views and delivers an optional activation payload. */
open(params: import("@netcatty/plugin-contract").ViewOpenParams): Promise<Readonly<import("@netcatty/plugin-contract").ViewOpenResult>>;
}
export interface PluginProviderInvocation<TPayload extends JsonValue = JsonValue> {
+5
View File
@@ -308,12 +308,16 @@ function schemaTypeToTs(node, level = 0) {
const hostInteractionLimits = schema.$defs.HostInteractionLimits?.const;
const byteStreamLimits = schema.$defs.ByteStreamLimits?.const;
const viewOpenLimits = schema.$defs.ViewOpenLimits?.const;
if (!byteStreamLimits || Object.values(byteStreamLimits).some((value) => !Number.isSafeInteger(value) || value < 1)) {
throw new Error("ByteStreamLimits must contain positive bounded integers");
}
if (!hostInteractionLimits || Object.values(hostInteractionLimits).some((value) => !Number.isSafeInteger(value) || value < 1)) {
throw new Error("HostInteractionLimits must contain positive bounded integers");
}
if (!Number.isSafeInteger(viewOpenLimits?.maxParamsBytes) || viewOpenLimits.maxParamsBytes < 1) {
throw new Error("ViewOpenLimits.maxParamsBytes must be a positive safe integer");
}
const definitionNames = Object.keys(schema.$defs).sort((left, right) =>
left.localeCompare(right, "en"),
@@ -356,6 +360,7 @@ const generatedLimits = [
`export const PLUGIN_SYNC_MAX_OBJECT_KEY_LENGTH = ${syncLimits.maxObjectKeyLength} as const;`,
`export const PLUGIN_SYNC_MAX_REVISION_LENGTH = ${syncLimits.maxRevisionLength} as const;`,
`export const PLUGIN_SYNC_INLINE_OBJECT_BYTES = ${syncLimits.inlineObjectBytes} as const;`,
`export const PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES = ${viewOpenLimits.maxParamsBytes} as const;`,
"",
].join("\n");
const normalizedSchema = `${JSON.stringify(schema, null, 2)}\n`;