diff --git a/docs/plugin-platform/ai-context-wip.md b/docs/plugin-platform/ai-context-wip.md index 3913d11f8..5c99ae584 100644 --- a/docs/plugin-platform/ai-context-wip.md +++ b/docs/plugin-platform/ai-context-wip.md @@ -2,16 +2,16 @@ Base: ThemePack #3978, `91b8927c56314e68c06e2c008e84559ddfb96d78`. Branch: `feat/plugin-ai-context`. -Status: isolated host internals and fixture-tested transport reuse. Public contract, -production adapters, installable example, independent review, and native acceptance -are pending. This source is not ready to merge or release. +Status: source-bound services, trusted main/renderer adapters, and an installable +minimal example are implemented. Shared trusted-preload wiring, complete independent +review, and native acceptance remain pending. This source is not ready to merge or release. -## Proposed public boundaries +## Public boundaries -The proposed optional features are `ai.model-invocation` and -`context.selected-read`. The parent has not confirmed these names. No canonical -schema, generated contract, SDK, runtime peer, hostService, or installer changes -are included in this checkpoint. +The parent approved `ai.model-invocation` and `context.selected-read`. The +transport task owns the canonical schema, SDK, runtime peer, and hostService +registration. Its `c4433d4961ecf4a81bea92b0a14f47b4ec12f679` head contains the +public AI/context routes. This branch does not overwrite those shared files. The model API uses a host-selected configured model. Plugins receive a chat handle, a display label, an expiry, turn handles, text chunks, and usage totals. @@ -32,7 +32,7 @@ or arbitrary entity-ID lookup. | --- | --- | | This task | `electron/plugins/ai/`, `electron/plugins/context/`, `infrastructure/ai/plugin/`, `examples/plugins/assistant/`, this document | | This task | Opt-in `requireBridge` and `maxStreamBytes` request context in `infrastructure/ai/sdk/providers.ts` | -| Parent coordination | Canonical schema, generated files, SDK, runtime forwarding, hostService registration, trusted renderer adapters | +| Transport task | Canonical schema, generated files, SDK, runtime forwarding, hostService registration, trusted preload methods, app host mount | | Market task | Source identity, private data-owner namespace, installer database, marketplace UI | | Transport task | Generic TCP and TLS streams | | Logging task | Optional local plugin logs | @@ -44,6 +44,12 @@ This branch does not claim that workflow is complete. ## Implemented authority +`PluginAISourceBinding` authenticates the current browser runtime before reading +`getActivePlugin().source`, `getRetainedPluginSource`, `privateOwner`, and +`publicPluginId`. Source binding is rechecked after asynchronous work. The source +database and sync implementation are unchanged. Source origin does not imply +that a package is officially maintained. + `ModelInvocationBroker` requires host-provided `resolveDataOwner` and `selectModel` adapters. It keeps chats and turns in memory. It stores no chat history and makes no database changes. Data owners are opaque host identities; @@ -67,7 +73,10 @@ trusted sharing UI must preview the selected text before sharing it. `createPluginModelAdapter` calls the existing `createModelFromConfig` and `streamText`, through the existing host provider transport. Credential injection stays in Netcatty. Direct-fetch fallback is disabled for this adapter. Incoming -SSE payloads have an aggregate 128 KiB cap before SDK buffering. SDK retries are +SSE payloads have an aggregate 128 KiB cap before SDK buffering. The main +transport also enforces a plugin-specific 128 KiB response cap and a 60-second +total deadline. Host-owned request tags allow sender/runtime cancellation +without cancelling the internal Agent's ordinary streams. SDK retries are disabled. Only text and allowlisted token totals reach the broker. Provider errors, raw chunks, reasoning, headers, and tool payloads do not cross it. @@ -87,7 +96,8 @@ restart within the broker's lifetime. Host shutdown clears this in-memory state. ## Required host adapters -Production integration is blocked on these parent-owned contracts: +The public service is registered in the transport integration. Its trusted +renderer wiring still needs these parent-owned connections: 1. `resolveDataOwner(context)` must return the current private source owner from host provenance. A plugin-supplied source value or plugin ID is insufficient. @@ -134,19 +144,40 @@ node --test --import tsx infrastructure/ai/plugin/modelInvocationAdapter.test.ts npx eslint infrastructure/ai/plugin/*.ts infrastructure/ai/sdk/providers.ts examples/plugins/assistant/panel.js ``` -The final focused domain run passes 16 tests. The transport suite passes three -tests, including the actual assistant panel's Send, streaming, usage, and Stop -handlers in JSDOM. The test bridge uses structured clones to model the existing -view command boundary. It does not replace installed-plugin or native coverage. -The wider plugin runtime run passes 556 tests with one skipped. The existing -provider regression suites pass 34 tests. +The installed assistant command test passes against the parent-coordinated local +integration of the AI branch and transport head `c4433d496`. It installs and +activates the six-file sample through the actual package manager and runtime peer, +then checks canonical SDK/RPC, independent model/content denial, text-review +cancellation, text/usage streaming, spoofed fields, revocation, and stale versions. +The in-process browser harness is a Node test transport, not native sandbox proof. -The full repository typecheck fails in existing code, including provider tool-call -inference and plugin CLI test manifest literals. No new adapter type errors were -reported. The focused lint passes. +The trusted main/renderer suites cover nonce replay, sender substitution, owner +replacement, navigation, hide, runtime release, lock, cancellation, focus recovery, +safe field projection, and late selected-content results. The main transport test +also verifies targeted plugin cancellation leaves an ordinary synthetic Agent +stream running and aborts an oversized plugin stream. -Native Electron launch aborts because the bundled `chrome-sandbox` is not owned -by root with mode 4755. No sandbox bypass was attempted. Native screenshots, -video, installed-plugin UI tests, packaged builds, and independent review are -pending on the parent's working desktop after shared integration. The panel -source alone is not evidence of native acceptance. +The first integrated runtime checkpoint reports 603 passed, 1 failed, and 2 skipped. +The failure is shared permission-copy coverage: the new AI/context and byte-stream +permissions need entries in `domain/pluginPermissionDescriptions.cjs`. The full +repository run has additional failures and is not a passing acceptance record. +Ten Cursor discovery failures also reproduce on the unchanged core baseline. +Other failures have not yet been attributed. Focused changed-source lint passes. +The repository typecheck retains existing errors; the new adapter files have no +diagnostics after the local type repair. + +The package build validates six files. The final artifact and native procedure +are recorded in [the native QA recipe](assistant-native-qa.md). The source staging +excludes build tooling and has no Node entry, network, filesystem, secret, storage, +or terminal permission. + +Independent review confirmed the malformed-reference revocation defect on +`afe831bfc`. The two regression tests failed before the repair and pass afterward. +The repair is retained in #3985 head `4882e0501`. Further independent review was +blocked by the review tool/model restriction. That review is incomplete and has +not been retried through another route. CI is not a substitute for that review. + +Native Electron launch on this executor aborts because `chrome-sandbox` is not +root-owned mode 4755. No sandbox bypass or native retry was attempted. Native +screenshots, video, and installed UI acceptance belong to the parent's working +cloud GUI machine after shared wiring. No native acceptance is claimed here. diff --git a/electron/plugins/ai/aiContextEntrypoint.test.cjs b/electron/plugins/ai/aiContextEntrypoint.test.cjs new file mode 100644 index 000000000..1257e2eb2 --- /dev/null +++ b/electron/plugins/ai/aiContextEntrypoint.test.cjs @@ -0,0 +1,73 @@ +"use strict"; +const assert = require("node:assert/strict"); +const test = require("node:test"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const os = require("node:os"); +const schema = require("../generated/plugin-contract.schema.json"); + +if (!schema.$defs.PluginAIChatResult) { + test("assistant installed runtime requires the shared canonical AI/context contract", { skip: "Run on the parent-coordinated integration head" }, () => {}); +} else { + test("installed assistant uses canonical SDK/RPC, independent content grants, reviewed version and revocation", { timeout: 15_000 }, async (t) => { + const { createPluginHostService } = require("../hostService.cjs"); + const { inProcessBrowserRuntime } = require("../fixtures/inProcessBrowserRuntime.cjs"); + const root = await fs.mkdtemp(path.join(os.tmpdir(), "netcatty-assistant-entry-")); + let service; let contentAllowed = false; let modelAllowed = true; let reviewed = true; let invoked = 0; let versionCurrent = true; + const decisions = []; + t.after(async () => { await service?.manager.shutdown(); await fs.rm(root, { recursive: true, force: true }); }); + service = createPluginHostService({ + app: { getAppPath: () => path.resolve(__dirname, "../../.."), getPath: () => root, getVersion: () => "0.0.0" }, electron: {}, env: {}, + pluginAIHostAdapter: { assertActive: (context) => context.assertActive(), + selectModel: async () => ({ label: "Synthetic fixture", isCurrent: () => true, invoke: async () => { + invoked++; return (async function* () { yield { kind: "text", text: "Synthetic summary" }; yield { kind: "usage", inputTokens: 12, outputTokens: 6, totalTokens: 18 }; })(); + } }), + listSelected: async () => [{ key: "synthetic-note", scope: "note", title: "Synthetic retry plan", version: "v1", + readText: () => "Synthetic retry plan: add a retry button", isCurrent: () => versionCurrent }], + reviewText: async () => reviewed, + }, + requestPermissionDecision: async (request) => { + decisions.push(request); + if ((request.permission === "context.selected.read" && !contentAllowed) || (request.permission === "ai.invoke" && !modelAllowed)) return { requestId: request.requestId, decision: "deny" }; + return { requestId: request.requestId, decision: "allow", scope: request.permission === "context.selected.read" ? "once" : "application" }; + }, + }); + service.runtimeSupervisor.runtimeFactories.browser = inProcessBrowserRuntime; + await service.manager.initialize(); + const sample = path.resolve(__dirname, "../../../examples/plugins/assistant"); + // Use an explicit six-file fixture snapshot, not source/build tooling. + const staging = path.join(root, "package"); await fs.mkdir(path.join(staging, "dist"), { recursive: true }); + for (const file of ["netcatty.plugin.json", "panel.html", "panel.css", "panel.js", "README.md"]) await fs.copyFile(path.join(sample, file), path.join(staging, file)); + await fs.copyFile(path.join(sample, "src/index.js"), path.join(staging, "dist/index.js")); + const { buildPluginPackage, validatePluginPackage } = await import("@netcatty/plugin-cli"); + const archive = path.join(root, "assistant.ncpkg"); const built = await buildPluginPackage(staging, archive); + assert.equal(built.fileCount, 6); assert.equal((await validatePluginPackage(archive)).manifest.id, "com.netcatty.assistant"); + await service.manager.install(archive, { enable: true }); + const id = "com.netcatty.assistant"; + const run = (name, args) => service.contributionService.executeCommand(`${id}.${name}`, args); + modelAllowed = false; await assert.rejects(run("open")); assert.equal(invoked, 0); + modelAllowed = true; + const chat = await run("open"); const references = await run("contexts"); assert.equal(references.length, 1); + assert.equal(references[0].scope, "note"); assert.equal(references[0].text, undefined); + const input = { chatHandle: chat.chatHandle, prompt: "Summarize", contexts: [{ handle: references[0].handle, version: references[0].version }] }; + await assert.rejects(run("send", input)); assert.equal(invoked, 0); + contentAllowed = true; reviewed = false; await assert.rejects(run("send", input)); assert.equal(invoked, 0); + reviewed = true; + const turn = await run("send", input); + assert.deepEqual(await run("read", { turnHandle: turn.turnHandle }), { kind: "text", sequence: 0, text: "Synthetic summary" }); + assert.deepEqual(await run("read", { turnHandle: turn.turnHandle }), { kind: "usage", sequence: 1, inputTokens: 12, outputTokens: 6, totalTokens: 18 }); + assert.deepEqual(await run("read", { turnHandle: turn.turnHandle }), { kind: "end", sequence: 2 }); + await assert.rejects(run("send", { ...input, privateOwner: "spoofed" })); + await assert.rejects(run("send", { ...input, contexts: [null] })); + await assert.rejects(run("read", { turnHandle: turn.turnHandle, source: "spoofed" })); + const pending = await run("send", input); + service.permissionEngine.revokeApplication(id, "ai.invoke", "*"); + assert.equal(service.aiContextService.broker.turns.size, 0); + await assert.rejects(run("read", { turnHandle: pending.turnHandle })); + assert.ok(decisions.some((decision) => decision.permission === "context.selected.read" && decision.resources[0].startsWith("selected:"))); + const fresh = await run("open"); const [reference] = await run("contexts"); + versionCurrent = false; + await assert.rejects(run("send", { chatHandle: fresh.chatHandle, prompt: "Hi", contexts: [{ handle: reference.handle, version: reference.version }] })); + await service.manager.setEnabled(id, false); assert.equal(service.aiContextService.broker.chats.size, 0); + }); +} diff --git a/electron/plugins/ai/modelInvocationBroker.cjs b/electron/plugins/ai/modelInvocationBroker.cjs index bbf549317..ae438bd6f 100644 --- a/electron/plugins/ai/modelInvocationBroker.cjs +++ b/electron/plugins/ai/modelInvocationBroker.cjs @@ -36,6 +36,7 @@ class ModelInvocationBroker { this.clock = clock; this.limits = boundedLimits(limits); this.chats = new Map(); + this.openings = new Set(); this.turns = new Map(); this.rates = new Map(); this.closed = false; @@ -81,22 +82,33 @@ class ModelInvocationBroker { async open(context) { const binding = await this.#binding(context); - // Host chooses from configured models. Plugin parameters cannot override it. - const model = await this.selectModel(context); - await context.assertActive(); - if (!model || typeof model.invoke !== "function" || typeof model.isCurrent !== "function" - || typeof model.label !== "string" || model.label.length > 160 || !await model.isCurrent()) { - throw fail("unavailable", "Choose a configured model in the host first"); - } - await context.assertActive(); this.#prune(); - if (this.closed || this.chats.size >= this.limits.chats - || [...this.chats.values()].filter((chat) => chat.runtimeId === context.runtimeId).length >= this.limits.perRuntime) { + if (this.closed || this.chats.size + this.openings.size >= this.limits.chats + || [...this.chats.values(), ...this.openings].filter((chat) => chat.runtimeId === context.runtimeId).length >= this.limits.perRuntime) { throw fail("resourceExhausted", "Plugin chat limit reached"); } - const chat = { ...binding, handle: randomUUID(), model, expiresAt: this.clock() + this.limits.chatMs, turn: null }; - this.chats.set(chat.handle, chat); - return { chatHandle: chat.handle, model: model.label, expiresAt: chat.expiresAt }; + // Reserve before awaiting the host picker. Revoke/close can invalidate this + // admission even if a host callback ignores cancellation and returns late. + const opening = { ...binding, active: true }; + this.openings.add(opening); + let model; + try { + model = await this.selectModel(context); + const current = await this.#binding(context); + if (!opening.active || this.closed || current.owner !== binding.owner) throw fail("cancelled", "Model selection was revoked"); + if (!model || typeof model.invoke !== "function" || typeof model.isCurrent !== "function" + || typeof model.label !== "string" || model.label.length > 160 || !await model.isCurrent()) { + throw fail("unavailable", "Choose a configured model in the host first"); + } + await context.assertActive(); + if (!opening.active || this.closed || (await this.#binding(context)).owner !== binding.owner) throw fail("cancelled", "Model selection was revoked"); + const chat = { ...binding, handle: randomUUID(), model, expiresAt: this.clock() + this.limits.chatMs, turn: null }; + this.chats.set(chat.handle, chat); + return { chatHandle: chat.handle, model: model.label, expiresAt: chat.expiresAt }; + } catch (error) { + try { Promise.resolve(model?.dispose?.()).catch(() => {}); } catch {} + throw this.#safe(error); + } finally { this.openings.delete(opening); } } async start({ chatHandle, prompt, contexts = [] }, context) { @@ -251,14 +263,16 @@ class ModelInvocationBroker { await this.#ownedChat(chat, context); this.#close(chat); return true; } releaseRuntime(runtimeId) { + for (const opening of [...this.openings]) if (opening.runtimeId === runtimeId) { opening.active = false; this.openings.delete(opening); } for (const chat of [...this.chats.values()]) if (chat.runtimeId === runtimeId) this.#close(chat); this.contexts?.releaseRuntime(runtimeId); } releaseOwner(owner) { + for (const opening of [...this.openings]) if (opening.owner === owner) { opening.active = false; this.openings.delete(opening); } for (const chat of [...this.chats.values()]) if (chat.owner === owner) this.#close(chat); this.contexts?.releaseOwner(owner); } - shutdown() { this.closed = true; for (const chat of [...this.chats.values()]) this.#close(chat); this.rates.clear(); this.contextSubscription?.dispose(); } + shutdown() { this.closed = true; for (const opening of this.openings) opening.active = false; this.openings.clear(); for (const chat of [...this.chats.values()]) this.#close(chat); this.rates.clear(); this.contextSubscription?.dispose(); } } module.exports = { ModelInvocationBroker, MODEL_INVOCATION_LIMITS: LIMITS }; diff --git a/electron/plugins/ai/modelInvocationBroker.test.cjs b/electron/plugins/ai/modelInvocationBroker.test.cjs index 86b1465c7..2a929b6cf 100644 --- a/electron/plugins/ai/modelInvocationBroker.test.cjs +++ b/electron/plugins/ai/modelInvocationBroker.test.cjs @@ -209,3 +209,14 @@ test("malformed context cannot publish a turn or interrupt two-handle runtime re assert.equal(f.calls.length, 0); f.broker.shutdown(); }); + +test("pending model selections reserve capacity and cannot publish after revocation", async () => { + const f = fixture({ limits: { perRuntime: 1 } }); const pending = deferred(); let disposed = 0; + f.broker.selectModel = () => pending.promise; + const opening = f.broker.open(f.context); const rejected = assert.rejects(opening); + await new Promise(setImmediate); + await assert.rejects(f.broker.open(f.context), (error) => error.code === RPC_ERRORS.resourceExhausted); + f.broker.releaseRuntime("r1"); + pending.resolve({ ...f.model, dispose: () => { disposed++; } }); + await rejected; assert.equal(f.broker.chats.size, 0); assert.equal(f.broker.openings.size, 0); assert.equal(disposed, 1); f.broker.shutdown(); +}); diff --git a/electron/plugins/ai/trustedHostAdapter.cjs b/electron/plugins/ai/trustedHostAdapter.cjs index 137205d0a..80e26bec0 100644 --- a/electron/plugins/ai/trustedHostAdapter.cjs +++ b/electron/plugins/ai/trustedHostAdapter.cjs @@ -24,11 +24,13 @@ class PluginAITrustedHostAdapter { } registerIpc(ipcMain) { + if (this.ipcRegistration) throw new Error("Trusted AI host IPC is already registered"); this.validateRequest ??= createDefinitionValidator("PluginAIHostRequest"); this.validateResponse ??= createDefinitionValidator("PluginAIHostResponse"); ipcMain.handle(CHANNELS.ready, (event, ready) => this.setReady(event.sender, ready)); ipcMain.handle(CHANNELS.response, (event, response) => this.respond(event.sender, response)); - return { dispose: () => { ipcMain.removeHandler(CHANNELS.ready); ipcMain.removeHandler(CHANNELS.response); } }; + this.ipcRegistration = { dispose: () => { ipcMain.removeHandler(CHANNELS.ready); ipcMain.removeHandler(CHANNELS.response); } }; + return this.ipcRegistration; } #owner() { @@ -170,7 +172,15 @@ class PluginAITrustedHostAdapter { async reviewText(selected, context) { await this.assertActive(context); const window = this.getWindow(); const generation = this.generation; - if (window.isFocused?.() !== true || typeof this.dialog?.showMessageBox !== "function") return false; + if (typeof this.dialog?.showMessageBox !== "function") return false; + // A native permission dialog can resolve just before its parent regains + // focus. Wait briefly for this exact owner, without focusing it ourselves. + const focusDeadline = Date.now() + 1_000; + while (window.isFocused?.() !== true) { + await this.assertActive(context); + if (generation !== this.generation || Date.now() >= focusDeadline) return false; + await new Promise((resolve) => setTimeout(resolve, 20)); + } const controller = new AbortController(); const signal = context.signal ? AbortSignal.any([context.signal, controller.signal]) : controller.signal; this.reviewControllers.set(controller, context.runtimeId); @@ -200,7 +210,7 @@ class PluginAITrustedHostAdapter { for (const listener of [...this.listeners]) { try { listener(); } catch {} } if (releaseOwner) { this.ownerCleanup?.(); this.ownerCleanup = null; this.owner = null; } } - shutdown() { this.closed = true; this.invalidate(true); this.unsubscribeLock?.(); this.listeners.clear(); } + shutdown() { this.ipcRegistration?.dispose(); this.ipcRegistration = null; this.closed = true; this.invalidate(true); this.unsubscribeLock?.(); this.listeners.clear(); } } module.exports = { PluginAITrustedHostAdapter, PLUGIN_AI_HOST_CHANNELS: CHANNELS }; diff --git a/electron/plugins/ai/trustedHostAdapter.test.cjs b/electron/plugins/ai/trustedHostAdapter.test.cjs index d9df4f613..18f7fcf52 100644 --- a/electron/plugins/ai/trustedHostAdapter.test.cjs +++ b/electron/plugins/ai/trustedHostAdapter.test.cjs @@ -65,3 +65,13 @@ test("selected text review is Cancel by default and cannot approve after cancell await tick(); assert.equal(options.defaultId, options.cancelId); assert.equal(options.cancelId, 1); controller.abort(); resolve({ response: 0 }); await assert.rejects(review); f.adapter.shutdown(); }); + +test("text review tolerates native permission focus restoration without focusing a window", async () => { + const f = fixture(); let focused = false; let focusCalls = 0; + f.window.isFocused = () => focused; f.window.focus = () => { focusCalls++; }; + const timer = setTimeout(() => { focused = true; }, 25); + try { + assert.equal(await f.adapter.reviewText({ title: "Synthetic", scope: "note", version: "1", text: "Synthetic", pluginId: "plugin" }, f.context), true); + assert.equal(focusCalls, 0); + } finally { clearTimeout(timer); f.adapter.shutdown(); } +}); diff --git a/electron/plugins/modelInvocation.test.cjs b/electron/plugins/modelInvocation.test.cjs index c9921072c..6b8a9265d 100644 --- a/electron/plugins/modelInvocation.test.cjs +++ b/electron/plugins/modelInvocation.test.cjs @@ -5,3 +5,4 @@ require("./context/selectedContextAuthority.test.cjs"); require("./ai/sourceBinding.test.cjs"); require("./ai/trustedHostAdapter.test.cjs"); require("./ai/aiContextService.test.cjs"); +require("./ai/aiContextEntrypoint.test.cjs"); diff --git a/examples/plugins/assistant/README.md b/examples/plugins/assistant/README.md index 002d41a59..a57e1ce9d 100644 --- a/examples/plugins/assistant/README.md +++ b/examples/plugins/assistant/README.md @@ -1,16 +1,21 @@ -# Assistant example source +# Selected Note Assistant -This panel contains the minimal example UI: a host-selected model, one explicitly -selected Note, Send, streamed text, Stop, and token usage. It uses the existing -`netcattyView.executeCommand` surface. It has no direct network access or Node API. +A minimal browser plugin that uses Netcatty's selected configured model and one +explicitly selected reference. It provides Send, streamed text, Stop, and usage. +It has no tools, terminal commands, direct network access, Node runtime, or storage. -The runtime entry and package manifest are pending the parent's shared contract -and SDK decision. This directory is not yet an installable plugin. -The command names in `panel.js` are example-local command IDs, not host RPC methods. -A menu or command ID grants no authority to read a resource. +The host must support `ai.model-invocation` and `context.selected-read`, with the +trusted renderer adapter connected. AI invocation, selected-summary enumeration, +and selected-content reading have separate optional permissions. The host shows +the exact selected text for review before the plugin or model receives it. +A menu or command ID grants no authority over a resource. -The QA harness binds these commands to `ModelInvocationBroker` and -`SelectedContextAuthority`. The production runtime must bind them through the -approved canonical SDK methods, with host permission checks and provenance. -The local deterministic provider proves the pipeline. It does not perform model -inference, use paid credentials, or read a real user's data. +Build the six-file staging directory with `node build.mjs`, then pack `.package` +with Netcatty's plugin CLI. Build scripts are not included in the installed package. +The plugin uses only the canonical `context.ai` and `context.selectedContext` SDK +methods through its own declared view commands. No chat history is persisted. + +For isolated QA, use the deterministic loopback provider and synthetic Note recipe +in `docs/plugin-platform/assistant-native-qa.md` in the Netcatty repository. Fixture +QA performs no model inference or paid API call. Native acceptance and the remaining +independent review are separate requirements.