diff --git a/docs/plugin-platform/host-interactions.md b/docs/plugin-platform/host-interactions.md index 3c0b91220..560cc16b9 100644 --- a/docs/plugin-platform/host-interactions.md +++ b/docs/plugin-platform/host-interactions.md @@ -86,6 +86,22 @@ host UI. Runtime teardown clears rate accounting. The broker checks runtime activity, owner readiness/focus, and app lock again immediately before native read/write or disclosure. A revoked operation cannot resume from a late reply. +Commands normally retain the existing 30-second RPC deadline. A command that +declares `interactive: true` must require `commands.interactive`; the host gives +only that command a fixed 180-second total budget. This is not a global timeout +increase or a UI/clipboard permission. Each individual host interaction still +has its own 60-second deadline, including permission approval time. + +When an outer command fails, times out or is cancelled, the host cancels pending +interactions and pre-prompt admissions for its captured runtime. On successful +completion it closes orphan interactions once the last concurrent command ends. +This cleanup does not reset rate/byte quotas and cannot affect a replacement +runtime. A failure conservatively closes that runtime's single shared pending +dialog even if another command is active. Late action tokens cannot commit a +clipboard effect. Cancellation does not forcibly terminate arbitrary plugin +JavaScript; ignored errors remain subject to permission, focus, rate and runtime +limits. Do not start independent interactive workflows concurrently. + Audit records contain only fixed event/action/kind fields. They contain no prompt, choices, user text, clipboard bytes, action tokens, or hashes derived from those values. A failed consent-audit write prevents the native action; diff --git a/electron/plugins/contributionService.cjs b/electron/plugins/contributionService.cjs index 8cfc6460c..9c8ab6046 100644 --- a/electron/plugins/contributionService.cjs +++ b/electron/plugins/contributionService.cjs @@ -6,6 +6,7 @@ const { assertPluginContextKey, evaluateContextKeyExpression } = require("./cont const { assertPluginJsonValue } = require("./jsonBoundary.cjs"); const { compileRestrictedJsonSchema } = require("./restrictedJsonSchema.cjs"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); +const { InteractiveCommandFeature, InteractiveCommandLimits } = require("./generated/plugin-contract.schema.json").$defs; const MAX_SETTING_BYTES = 128 * 1024; const MAX_PATTERN_LENGTH = 512; @@ -149,6 +150,8 @@ class PluginContributionService { constructor(options) { this.database = options.database; this.runtimeSupervisor = options.runtimeSupervisor; + this.onCommandFinished = options.onCommandFinished; + this.activeCommandCalls = new Map(); this.secretStore = options.secretStore; this.getLocale = options.getLocale ?? (() => "en"); this.contextKeys = new Map(); @@ -336,12 +339,31 @@ class PluginContributionService { throw new PluginRpcError(RPC_ERRORS.failedPrecondition, `Plugin command is disabled: ${commandId}`); } assertJsonValue(args ?? null, "command arguments"); - await this.#ensureActivated(plugin, `onCommand:${commandId}`); - return this.runtimeSupervisor.request(plugin.id, "plugin.command.execute", { - command: commandId, - ...(args === undefined ? {} : { args }), - invocation: freezeJson({ source: invocation.source ?? "host", context: invocation.context ?? {} }), - }); + if (contribution.interactive && !plugin.manifest.features?.required?.includes(InteractiveCommandFeature.const)) { + throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Interactive command feature is required"); + } + const identity = await this.#ensureActivated(plugin, `onCommand:${commandId}`); + const runtimeId = identity?.runtimeId; + if (runtimeId) this.activeCommandCalls.set(runtimeId, (this.activeCommandCalls.get(runtimeId) ?? 0) + 1); + let failed = true; + try { + const result = await this.runtimeSupervisor.request(plugin.id, "plugin.command.execute", { + command: commandId, + ...(args === undefined ? {} : { args }), + invocation: freezeJson({ source: invocation.source ?? "host", context: invocation.context ?? {} }), + }, contribution.interactive ? { timeoutMs: InteractiveCommandLimits.const.timeoutMs, expectedIdentity: identity } : undefined); + failed = false; + return result; + } finally { + if (runtimeId) { + const remaining = Math.max(0, (this.activeCommandCalls.get(runtimeId) ?? 1) - 1); + if (remaining) this.activeCommandCalls.set(runtimeId, remaining); + else this.activeCommandCalls.delete(runtimeId); + // A failed command must not leave a live native consent prompt. On + // success wait for other concurrent commands before closing orphans. + if (failed || remaining === 0) this.onCommandFinished?.(runtimeId); + } + } } async activateView(viewId, params = {}) { diff --git a/electron/plugins/contributionService.test.cjs b/electron/plugins/contributionService.test.cjs index a1f4f03b8..b38468e69 100644 --- a/electron/plugins/contributionService.test.cjs +++ b/electron/plugins/contributionService.test.cjs @@ -87,6 +87,7 @@ function setup(context, pluginManifest, options = {}) { runtimeSupervisor, secretStore, getLocale: () => "zh-CN", + onCommandFinished: options.onCommandFinished, }); return { calls, database, secretStore, service, secrets }; } @@ -100,6 +101,47 @@ test("plugin contribution values enforce the exact JSON value boundary", () => { } }); +test("only explicitly declared interactive commands receive the fixed budget and command completion is runtime-bound", async (t) => { + const pluginManifest = manifest(); + delete pluginManifest.contributes.commands[0].enablement; + pluginManifest.features = { required: ["commands.interactive"] }; + pluginManifest.contributes.commands.push({ id: `${pluginManifest.id}.interactive`, title: "Interactive", interactive: true }); + const optionsSeen = [], finished = []; + const runtimeId = "runtime-budget"; + const { service } = setup(t, pluginManifest, { + onCommandFinished: (id) => finished.push(id), + runtimeSupervisor: { + async start() { return { runtimeId, pluginVersion: pluginManifest.version }; }, + async request(_id, _method, _params, options) { optionsSeen.push(options); return null; }, + }, + }); + await service.executeCommand(`${pluginManifest.id}.hello`); + await service.executeCommand(`${pluginManifest.id}.interactive`); + assert.equal(optionsSeen[0], undefined, "ordinary commands retain the existing router deadline"); + assert.equal(optionsSeen[1].timeoutMs, 180_000); + assert.equal(optionsSeen[1].expectedIdentity.runtimeId, runtimeId); + assert.deepEqual(finished, [runtimeId, runtimeId]); + assert.equal(service.activeCommandCalls.size, 0); +}); + +test("concurrent successful commands retain the runtime interaction until the last ends, while a failed command cancels it", async (t) => { + const pluginManifest = manifest(); delete pluginManifest.contributes.commands[0].enablement; + const pending = [], finished = []; + const { service } = setup(t, pluginManifest, { onCommandFinished: (id) => finished.push(id), + runtimeSupervisor: { async start() { return { runtimeId: "runtime-concurrent" }; }, + request() { return new Promise((resolve, reject) => pending.push({ resolve, reject })); } }, + }); + const first = service.executeCommand(`${pluginManifest.id}.hello`); + const second = service.executeCommand(`${pluginManifest.id}.hello`); + await new Promise((resolve) => setImmediate(resolve)); + pending[0].resolve(null); await first; + assert.deepEqual(finished, []); + pending[1].reject(new Error("synthetic timeout")); + await assert.rejects(second, /synthetic timeout/); + assert.deepEqual(finished, ["runtime-concurrent"]); + assert.equal(service.activeCommandCalls.size, 0); +}); + test("only onStartupFinished plugins activate during contribution initialization", async (context) => { const pluginManifest = manifest("com.example.startup", ["onStartupFinished"]); const { calls, service } = setup(context, pluginManifest); diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json index c2b15b0b1..71fa8134b 100644 --- a/electron/plugins/generated/plugin-contract.schema.json +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -245,6 +245,14 @@ "HostInteractionFeature": { "const": "host.interactions" }, + "InteractiveCommandFeature": { + "const": "commands.interactive" + }, + "InteractiveCommandLimits": { + "const": { + "timeoutMs": 180000 + } + }, "HostQuickPickItem": { "type": "object", "required": [ @@ -1174,6 +1182,11 @@ }, "enablement": { "$ref": "#/$defs/ContextKeyExpression" + }, + "interactive": { + "type": "boolean", + "default": false, + "description": "Require commands.interactive for this command's fixed bounded host interaction budget. Does not grant UI or clipboard permissions." } }, "additionalProperties": false diff --git a/electron/plugins/hostInteractionExample.test.cjs b/electron/plugins/hostInteractionExample.test.cjs index 540283f0d..57f1749db 100644 --- a/electron/plugins/hostInteractionExample.test.cjs +++ b/electron/plugins/hostInteractionExample.test.cjs @@ -9,6 +9,7 @@ const { PluginRpcRouter } = require("./rpcRouter.cjs"); const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs"); const { PluginPermissionEngine } = require("./permissionEngine.cjs"); const { PluginHostInteractionService } = require("./hostInteractionService.cjs"); +const { PluginContributionService } = require("./contributionService.cjs"); for (const source of ["compose", "share"]) test(`normal browser example completes the ${source} text workflow through permission middleware`, async () => { const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs"); @@ -63,3 +64,54 @@ for (const source of ["compose", "share"]) test(`normal browser example complete assert.equal(service.pending.size, 0); } finally { active = false; await peer.dispose(); host.close(); port1.close(); service.shutdown(); permissionEngine.shutdown(); } }); + +test("outer command deadline closes its real browser clipboard confirmation and rejects late commit", async () => { + const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs"); + const plugin = await import("../../examples/plugins/host-interactions/browser.js"); + const manifest = JSON.parse(await readFile(new URL("../../examples/plugins/host-interactions/netcatty.plugin.json", pathToFileURL(__filename)), "utf8")); + const identity = { pluginId: manifest.id, pluginVersion: manifest.version, runtimeId: "runtime-deadline", runtimeKind: "browser" }; + const writes = [], messages = []; + const database = { listPermissionGrants: () => [], recordSecurityAudit() {}, + listPlugins: () => [{ id: manifest.id, activeVersion: manifest.version, manifest, enabled: true, runtime: { status: "running" } }], + }; + const engine = new PluginPermissionEngine({ database, requestDecision: async (request) => ({ requestId: request.requestId, decision: "allow", scope: "once" }) }); + let service, confirm; + const copyPrompt = new Promise((resolve) => { confirm = resolve; }); + const sender = Object.assign(new EventEmitter(), { id: 8, isDestroyed: () => false, send(_channel, message) { + messages.push(message); if (message.closed) return; + if (message.request.kind === "clipboard.write") { confirm(message); return; } + const value = message.request.kind === "quickPick" ? "compose" : "synthetic pending copy"; + queueMicrotask(() => { void service.respond(sender, { requestId: message.requestId, actionToken: message.actionToken, action: "submit", value }).catch(() => {}); }); + } }); + const owner = Object.assign(new EventEmitter(), { webContents: sender, isFocused: () => true, isVisible: () => true, isDestroyed: () => false }); + service = new PluginHostInteractionService({ database, permissionEngine: engine, getWindow: () => owner, isLocked: () => false, + quotaManager: { chargeBytes() {} }, clipboard: { writeText(text) { writes.push(text); } } }); + service.setReady(sender, true); + const registry = new PluginHostRpcRegistry(); registry.use(engine.createMiddleware()); service.registerRpcCapabilities(registry); + const routes = registry.createRoutes({ ...identity, manifest, assertCurrent() {} }); + const { port1, port2 } = new MessageChannel(); + const host = new PluginRpcRouter({ pluginId: manifest.id, send: (message) => port1.postMessage(message), handlers: routes.requestHandlers }); + port1.on("message", (message) => { void host.accept(message); }); + const features = manifest.features.required; + const peer = await startPluginRuntime({ port: port2, config: { ...identity, netcattyVersion: "0.0.0", apiVersion: "0.1.0-internal.1", enabledFeatures: features }, loadPlugin: async () => plugin }); + try { + await host.request("plugin.initialize", { netcattyVersion: "0.0.0", apiVersion: "0.1.0-internal.1", supportedFeatures: features }); + await host.request("plugin.activate", {}); + const contributions = new PluginContributionService({ database, onCommandFinished: (runtimeId) => service.cancelRuntimeRequests(runtimeId), + runtimeSupervisor: { async start() { return identity; }, request(_pluginId, method, params, options) { + assert.equal(options.timeoutMs, 180_000, "host chooses the fixed declared budget"); + return host.request(method, params, { timeoutMs: 500 }); // bounded synthetic timer, no production timeout change + } }, + }); + const command = contributions.executeCommand("com.netcatty.host-interactions.text"); + const prompt = await Promise.race([copyPrompt, command.then(() => { throw new Error("command finished before confirmation"); })]); + const attempts = service.rates.get(identity.runtimeId).count; + await assert.rejects(command, /timed out/); + assert.equal(service.pending.size, 0); + assert.equal(service.rates.get(identity.runtimeId).count, attempts); + assert.ok(messages.some((message) => message.closed && message.requestId === prompt.requestId)); + assert.equal(await service.respond(sender, { requestId: prompt.requestId, actionToken: prompt.actionToken, action: "submit" }), false); + assert.deepEqual(writes, []); + assert.equal(contributions.activeCommandCalls.size, 0); + } finally { await peer.dispose(); host.close(); port1.close(); service.shutdown(); engine.shutdown(); } +}); diff --git a/electron/plugins/hostInteractionService.cjs b/electron/plugins/hostInteractionService.cjs index 0467c6560..2d4c36dbb 100644 --- a/electron/plugins/hostInteractionService.cjs +++ b/electron/plugins/hostInteractionService.cjs @@ -57,6 +57,7 @@ class PluginHostInteractionService { this.pending = new Map(); this.rates = new Map(); this.admissions = new WeakMap(); + this.admissionGuards = new Map(); this.admissionRevision = 0; this.focusRestoreMs = Math.min(options.focusRestoreMs ?? 1_000, 1_000); this.owner = null; @@ -72,7 +73,9 @@ class PluginHostInteractionService { validateParams: assertInteractionRequest, authorization: (params, context) => { const sender = this.#admit(params, context); - this.admissions.set(params, { sender, runtimeId: context.runtimeId, revision: this.admissionRevision }); + let guard = this.admissionGuards.get(context.runtimeId); + if (!guard) { guard = { active: true }; this.admissionGuards.set(context.runtimeId, guard); } + this.admissions.set(params, { sender, runtimeId: context.runtimeId, revision: this.admissionRevision, guard }); return interactionAuthorization(params); }, }); @@ -200,7 +203,7 @@ class PluginHostInteractionService { const deadline = Date.now() + this.focusRestoreMs; for (;;) { context.signal?.throwIfAborted(); - if (admission.revision !== this.admissionRevision || admission.sender !== this.owner) { + if (!admission.guard.active || admission.revision !== this.admissionRevision || admission.sender !== this.owner) { throw fail("cancelled", "Host interaction admission was revoked"); } const window = this.getWindow(); @@ -213,7 +216,7 @@ class PluginHostInteractionService { await new Promise((resolve) => setTimeout(resolve, Math.min(20, Math.max(1, deadline - Date.now())))); } await context.assertActive(); - if (admission.revision !== this.admissionRevision) throw fail("cancelled", "Host interaction admission was revoked"); + if (!admission.guard.active || admission.revision !== this.admissionRevision) throw fail("cancelled", "Host interaction admission was revoked"); sender = this.#assertWindow(admission.sender); } else sender = this.#admit(params, context); if (this.pending.size >= LIMITS.pendingTotal || [...this.pending.values()].some((entry) => entry.context.runtimeId === context.runtimeId || entry.sender === sender)) { @@ -308,12 +311,17 @@ class PluginHostInteractionService { } } releaseRuntime(runtimeId) { - this.admissionRevision++; - for (const entry of [...this.pending.values()]) { - if (entry.context.runtimeId === runtimeId) this.#finish(entry, null, fail("cancelled", "Plugin runtime stopped")); - } + this.cancelRuntimeRequests(runtimeId, "Plugin runtime stopped"); this.rates.delete(runtimeId); } + cancelRuntimeRequests(runtimeId, reason = "Host command finished") { + const guard = this.admissionGuards.get(runtimeId); + if (guard) guard.active = false; + this.admissionGuards.delete(runtimeId); + for (const entry of [...this.pending.values()]) { + if (entry.context.runtimeId === runtimeId) this.#finish(entry, null, fail("cancelled", reason)); + } + } cancelAll(invalidateAdmission = true) { if (invalidateAdmission) this.admissionRevision++; for (const entry of [...this.pending.values()]) this.#finish(entry, null, fail("cancelled", "Host interaction was cancelled")); @@ -322,7 +330,7 @@ class PluginHostInteractionService { if (this.closed) return; this.closed = true; if (this.owner) this.releaseWindow(this.owner); - this.cancelAll(); this.rates.clear(); + this.cancelAll(); this.rates.clear(); this.admissionGuards.clear(); this.revocation.dispose(); this.unsubscribeLock?.(); this.key.fill(0); } diff --git a/electron/plugins/hostInteractionService.test.cjs b/electron/plugins/hostInteractionService.test.cjs index d16872dc5..084bffdc0 100644 --- a/electron/plugins/hostInteractionService.test.cjs +++ b/electron/plugins/hostInteractionService.test.cjs @@ -50,6 +50,37 @@ test("normal input and quick pick return only an approved bounded value", async assert.equal(f.reads, 0); assert.deepEqual(f.writes, []); }); +test("ending a host command cancels pending native actions without resetting its quota", async (t) => { + const f = fixture(t); + const request = await f.begin({ kind: "clipboard.write", title: "Synthetic", text: "must not copy" }); + const count = f.service.rates.get(f.context.runtimeId).count; + f.service.cancelRuntimeRequests(f.context.runtimeId); + await assert.rejects(request.promise, /command finished/); + assert.equal(await f.respond(request.prompt, "submit"), false); + assert.deepEqual(f.writes, []); + assert.equal(f.service.rates.get(f.context.runtimeId).count, count); +}); + +test("old command completion cannot invalidate a replacement runtime's host-owned admission", async (t) => { + const f = fixture(t); + let authorize; + f.service.registerRpcCapabilities({ registerRequest(_name, _handler, options) { authorize = options.authorization; } }); + const old = assertInteractionRequest({ kind: "input", title: "Old" }); + authorize(old, f.context); + f.service.cancelRuntimeRequests(f.context.runtimeId); + await assert.rejects(f.service.request(old, f.context), /revoked/); + const nextContext = { ...f.context, runtimeId: "runtime-replacement" }; + const next = assertInteractionRequest({ kind: "input", title: "New" }); + authorize(next, nextContext); + f.service.cancelRuntimeRequests(f.context.runtimeId); + const request = f.service.request(next, nextContext); + await new Promise((resolve) => setImmediate(resolve)); + const prompt = f.messages.find((message) => !message.closed); + assert.ok(prompt); + await f.respond(prompt, "submit", "synthetic new input"); + assert.deepEqual(await request, { cancelled: false, value: "synthetic new input" }); +}); + test("Once permission dialog may restore the same owner's focus after its decision resolves", async (t) => { const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs"); const { PluginPermissionEngine } = require("./permissionEngine.cjs"); diff --git a/electron/plugins/hostService.cjs b/electron/plugins/hostService.cjs index d69323189..abf1200fc 100644 --- a/electron/plugins/hostService.cjs +++ b/electron/plugins/hostService.cjs @@ -2,6 +2,7 @@ const path = require("node:path"); const NETWORK_CREDENTIAL_LEASE_FEATURE = require("./generated/plugin-contract.schema.json").$defs.NetworkCredentialLeaseFeature.const; +const INTERACTIVE_COMMAND_FEATURE = require("./generated/plugin-contract.schema.json").$defs.InteractiveCommandFeature.const; const { assertBrowserOnlyPlugin } = require("../../domain/pluginRuntimePolicy.cjs"); const { isPluginDevelopmentEnabled, PLUGIN_API_VERSION } = require("./constants.cjs"); @@ -95,7 +96,7 @@ function createPluginHostService(options) { database, netcattyVersion: options.app.getVersion(), apiVersion: PLUGIN_API_VERSION, - supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, ...(options.supportedFeatures ?? [])])], + supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])], }); const contributionIconService = new PluginContributionIconService({ database, @@ -167,6 +168,7 @@ function createPluginHostService(options) { runtimeSupervisor: runtimeAccess, secretStore, getLocale: options.getLocale, + onCommandFinished: (runtimeId) => interactionService?.cancelRuntimeRequests(runtimeId), }); contributionService.registerRpcCapabilities(rpcRegistry); registerSecurePluginCapabilities(rpcRegistry, { @@ -234,7 +236,7 @@ function createPluginHostService(options) { paths, netcattyVersion: options.app.getVersion(), apiVersion: PLUGIN_API_VERSION, - supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, ...(options.supportedFeatures ?? [])])], + supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])], runtimeDirectory, appRoot, rpcRegistry, diff --git a/examples/plugins/host-interactions/README.md b/examples/plugins/host-interactions/README.md index e111d7929..8763ac6e4 100644 --- a/examples/plugins/host-interactions/README.md +++ b/examples/plugins/host-interactions/README.md @@ -5,6 +5,13 @@ copy/share. It has no network, filesystem, host/session, credential, Node, or shell permission. Shared text stays in the current operation's memory and is not returned in the command result or written to plugin storage/logs. +Version 0.1.1 requires `host.interactions` and `commands.interactive`. Its one +command explicitly declares the fixed 180-second interactive budget; ordinary +commands keep 30 seconds and each dialog keeps 60 seconds. The host closes +pending confirmations when the command fails or ends, without resetting quotas. +These features add no new data permission. The permission list remains +required `commands`/`menus`, optional `ui.interact`/`clipboard.read`/`clipboard.write`. + Pack the source after building the plugin packages: ```sh diff --git a/examples/plugins/host-interactions/netcatty.plugin.json b/examples/plugins/host-interactions/netcatty.plugin.json index 3694bf752..08d24d74c 100644 --- a/examples/plugins/host-interactions/netcatty.plugin.json +++ b/examples/plugins/host-interactions/netcatty.plugin.json @@ -4,19 +4,49 @@ "name": "host-interactions", "displayName": "Host text interactions", "description": "Synthetic host choice, input and explicit clipboard sharing workflow.", - "version": "0.1.0", + "version": "0.1.1", "publisher": "netcatty", "license": "GPL-3.0-or-later", - "engines": { "netcatty": ">=0.0.0", "api": ">=0.1.0-internal <0.2.0" }, - "features": { "required": ["host.interactions"] }, - "main": { "browser": "browser.js" }, - "activationEvents": ["onCommand:com.netcatty.host-interactions.text"], + "engines": { + "netcatty": ">=0.0.0", + "api": ">=0.1.0-internal <0.2.0" + }, + "features": { + "required": [ + "host.interactions", + "commands.interactive" + ] + }, + "main": { + "browser": "browser.js" + }, + "activationEvents": [ + "onCommand:com.netcatty.host-interactions.text" + ], "permissions": { - "required": ["commands", "menus"], - "optional": ["ui.interact", "clipboard.read", "clipboard.write"] + "required": [ + "commands", + "menus" + ], + "optional": [ + "ui.interact", + "clipboard.read", + "clipboard.write" + ] }, "contributes": { - "commands": [{ "id": "com.netcatty.host-interactions.text", "title": "Host text workflow" }], - "menus": [{ "command": "com.netcatty.host-interactions.text", "location": "commandPalette" }] + "commands": [ + { + "id": "com.netcatty.host-interactions.text", + "title": "Host text workflow", + "interactive": true + } + ], + "menus": [ + { + "command": "com.netcatty.host-interactions.text", + "location": "commandPalette" + } + ] } } diff --git a/packages/plugin-cli/src/interactiveCommands.test.ts b/packages/plugin-cli/src/interactiveCommands.test.ts new file mode 100644 index 000000000..b8124feb9 --- /dev/null +++ b/packages/plugin-cli/src/interactiveCommands.test.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readFile } from 'node:fs/promises'; +import { validateManifestValue } from './manifest.js'; +import { checkPluginCompatibility } from './compatibility.js'; + +const manifest = JSON.parse(await readFile(new URL('../../../examples/plugins/host-interactions/netcatty.plugin.json', import.meta.url), 'utf8')); +test('interactive command budget requires feature negotiation without changing ordinary command admission', () => { + assert.equal(validateManifestValue(manifest).valid, true); + assert.equal(validateManifestValue({ ...manifest, features: { required: ['host.interactions'] } }).valid, false); + assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: '1.0.0', features: ['host.interactions'] }).compatible, false); + assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: '1.0.0', features: ['host.interactions', 'commands.interactive'] }).compatible, true); + const legacy = structuredClone(manifest); delete legacy.contributes.commands[0].interactive; legacy.features.required = ['host.interactions']; + assert.equal(validateManifestValue(legacy).valid, true); +}); diff --git a/packages/plugin-cli/src/manifest.ts b/packages/plugin-cli/src/manifest.ts index 21cf80fab..3876dd32f 100644 --- a/packages/plugin-cli/src/manifest.ts +++ b/packages/plugin-cli/src/manifest.ts @@ -367,6 +367,8 @@ function validateSemantics(manifest: PluginManifest): string[] { } const requiredFeatures = new Set(manifest.features?.required ?? []); + if (manifest.contributes?.commands?.some((command) => command.interactive) + && !requiredFeatures.has('commands.interactive')) errors.push('Interactive commands require commands.interactive'); if (manifest.icon) { if (!requiredFeatures.has('metadata.brand-icon')) errors.push('Brand icons require metadata.brand-icon'); if (!validRange(manifest.engines.api) || !satisfies('0.1.0-internal.1', manifest.engines.api) || satisfies('0.1.0-internal', manifest.engines.api)) errors.push('Brand icons require API >=0.1.0-internal.1 excluding the legacy revision'); diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index 9eb6f8737..68e0f8d7b 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -192,6 +192,12 @@ "HostInteractionFeature": { "const": "host.interactions" }, + "InteractiveCommandFeature": { + "const": "commands.interactive" + }, + "InteractiveCommandLimits": { + "const": { "timeoutMs": 180000 } + }, "HostQuickPickItem": { "type": "object", "required": [ @@ -949,7 +955,8 @@ "category": { "$ref": "#/$defs/LocalizedText" }, "description": { "$ref": "#/$defs/LocalizedText" }, "icon": { "$ref": "#/$defs/IconReference" }, - "enablement": { "$ref": "#/$defs/ContextKeyExpression" } + "enablement": { "$ref": "#/$defs/ContextKeyExpression" }, + "interactive": { "type": "boolean", "default": false, "description": "Require commands.interactive for this command's fixed bounded host interaction budget. Does not grant UI or clipboard permissions." } }, "additionalProperties": false }, diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index cf04406be..b01d0238c 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -80,6 +80,7 @@ export type CommandContribution = { description?: LocalizedText; icon?: IconReference; enablement?: ContextKeyExpression; + interactive?: boolean; }; export type CompanionExecutable = { @@ -388,6 +389,10 @@ export type ImporterSnippetDraft = { description?: string; }; +export type InteractiveCommandFeature = "commands.interactive"; + +export type InteractiveCommandLimits = {"timeoutMs":180000}; + export type JsonPrimitive = (string) | (number) | (boolean) | (null); export type JsonRpcStandardErrorCode = -32700 | -32600 | -32601 | -32602 | -32603; diff --git a/packages/plugin-contract/src/index.ts b/packages/plugin-contract/src/index.ts index 2ffb77e35..7e6facda9 100644 --- a/packages/plugin-contract/src/index.ts +++ b/packages/plugin-contract/src/index.ts @@ -54,3 +54,5 @@ export { inspectPluginBrandIcon, PLUGIN_BRAND_ICON_FEATURE, PLUGIN_BRAND_ICON_MA export const PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE = "network.credential-lease" as const satisfies import("./generated/plugin-contract.js").NetworkCredentialLeaseFeature; export const PLUGIN_HOST_INTERACTION_FEATURE = "host.interactions" as const satisfies import("./generated/plugin-contract.js").HostInteractionFeature; + +export const PLUGIN_INTERACTIVE_COMMAND_FEATURE = "commands.interactive" as const satisfies import("./generated/plugin-contract.js").InteractiveCommandFeature; diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 4967e7349..b2bc7f9f6 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -930,3 +930,4 @@ export function throwIfCancellationRequested(token: CancellationToken): void { export { PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from "@netcatty/plugin-contract"; export { PLUGIN_HOST_INTERACTION_FEATURE } from "@netcatty/plugin-contract"; +export { PLUGIN_INTERACTIVE_COMMAND_FEATURE } from "@netcatty/plugin-contract";