From 63f0572e0b1ade05ebf06cdc0fe1ffbaf7c9074e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A5=87?= <16399091+binaricat@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:45:57 +0000 Subject: [PATCH] fix(plugin-agent): guard delegated cancellation and empty context paths --- docs/plugin-platform/global-agent-wip.md | 26 ++++++++++++++ .../aiBridge/sdk/sdkStreamHandlers.cjs | 10 +++++- .../aiBridge/sdk/sdkStreamHandlers.test.cjs | 36 +++++++++++++++++++ electron/bridges/mcpServerBridge.cjs | 26 +++++++++----- .../mcpServerBridge.pluginDelegation.test.cjs | 15 ++++++++ 5 files changed, 104 insertions(+), 9 deletions(-) diff --git a/docs/plugin-platform/global-agent-wip.md b/docs/plugin-platform/global-agent-wip.md index ce640dd83..6d08f98b7 100644 --- a/docs/plugin-platform/global-agent-wip.md +++ b/docs/plugin-platform/global-agent-wip.md @@ -117,6 +117,32 @@ checked. These records are not substituted for exact-head green CI. ## Planned public contract and adapters +### Independent transport correction + +The exact `ea619555` internal-handler reproductions fail all four targeted cases: +both no-session and empty-selection environment reads serialize global tool hints; +stale chat-wide cleanup cancels replacement B; and caller-supplied builtin chat +text can downgrade cancellation of a main-owned delegated request. The outer +sender gate still accepts only the current trusted main window. These are trusted +application lifecycle defects, not arbitrary plugin IPC exposure or installed +runtime exploit evidence. + +Cancellation now resolves ownership from the main request map, rejects a +conflicting caller chat, checks the recorded sender and current turn lease, and +cancels only that native request. The legacy chat-wide cleanup IPC is unavailable +for reserved delegated conversations; main-owned exact-turn release remains the +cleanup authority. All delegated environment return paths omit global tool hints. + +An additional Node 22 regression is independently reproduced: inline arrow +properties at the beginning of `module.exports` prevent namespace detection of +existing exports such as `init`, breaking the real Catty attachment harness. +Identifier exports preserve that existing interface. Correction tests pass 94 on +Node 22.23.3, including the actual Catty attachment consumer; focused lint passes. +Failed-before logs are `/tmp/netcatty-global-agent-transport-review-four-failed-before.log` +and `/tmp/netcatty-global-agent-ea619-namespace-before.log`. The transport PR's +review checkpoint remains `ea619555` until the parent integrates/rechecks this +separate correction. No native/backend/full-CI acceptance is implied. + ### Stage 2A: trusted native dispatch boundary The independent bounded recheck of foundation `ba4d3fc` passed all 20 reviewer diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs index c4629038c..5af6c28e9 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs @@ -1415,11 +1415,16 @@ function registerSdkStreamHandlers(ctx) { ipcMain.handle("netcatty:ai:sdk-agent:cancel", async (event, { requestId, chatSessionId }) => { if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" }; - const effectiveChatSessionId = chatSessionId || sdkRequestSessions.get(requestId); + const ownedChatSessionId = sdkRequestSessions.get(requestId); + // Caller text cannot select the legacy route for a delegated request. + if (ownedChatSessionId && chatSessionId && ownedChatSessionId !== chatSessionId) return { ok: false, error: "Agent request ownership mismatch" }; + const effectiveChatSessionId = ownedChatSessionId || chatSessionId; if (mcpServerBridge.isPluginAgentConversation?.(effectiveChatSessionId)) { const native = sdkRequestRuntimes.get(requestId); if (!native?.delegationTag || native.senderId !== event.sender.id || sdkRequestSessions.get(requestId) !== effectiveChatSessionId) return { ok: false, error: "Agent turn unavailable" }; + try { mcpServerBridge.assertPluginAgentCaller(effectiveChatSessionId, event.sender.id, native.delegationTag); } + catch { return { ok: false, error: "Agent turn unavailable" }; } sdkActiveStreams.get(requestId)?.abort(); return { ok: true }; } @@ -1439,6 +1444,9 @@ function registerSdkStreamHandlers(ctx) { ipcMain.handle("netcatty:ai:sdk-agent:cleanup", async (event, { chatSessionId }) => { if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" }; + // This legacy route has no per-request identity. Delegated lifecycle is + // owned by main's exact-turn lease, never a delayed chat-wide UI cleanup. + if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) return { ok: false, error: "Delegated Agent cleanup is main-owned" }; mcpServerBridge.setChatSessionCancelled?.(chatSessionId, true); mcpServerBridge.cancelPtyExecsForSession(chatSessionId); mcpServerBridge.cancelWorkerBackgroundJobsForSession?.(chatSessionId); diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs index 81b31d423..a1c32774a 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs @@ -2222,6 +2222,7 @@ test("delegated native cancellation is exact-request and cannot mark replacement const broad = []; const { handlers, ctx } = registerWithStubbedCtx({ mcpServerBridge: { isPluginAgentConversation: () => true, + assertPluginAgentCaller: () => {}, setChatSessionCancelled: () => broad.push('chat'), cancelPtyExecsForSession: () => broad.push('pty'), clearPendingApprovals: () => broad.push('approval'), cancelWorkerBackgroundJobsForSession: () => broad.push('worker'), } }); @@ -2238,3 +2239,38 @@ test("delegated native cancellation is exact-request and cannot mark replacement assert.equal((await cancel({ sender: { id: 99 } }, { requestId: 'native-b', chatSessionId: chat })).ok, false); assert.equal(second.signal.aborted, false); assert.deepEqual(broad, []); }); + +test("legacy chat-wide cleanup cannot abort replacement delegated turn B or remove its metadata", async () => { + const effects = []; + const { handlers, ctx } = registerWithStubbedCtx({ mcpServerBridge: { + isPluginAgentConversation: (id) => id?.startsWith('plugin-agent:'), + setChatSessionCancelled: () => effects.push('cancelled'), cancelPtyExecsForSession: () => effects.push('pty'), + cancelWorkerBackgroundJobsForSession: () => effects.push('worker'), cleanupScopedMetadata: async () => effects.push('metadata'), + } }); + const chat = 'plugin-agent:11111111-1111-4111-8111-111111111111'; + const replacement = new AbortController(); + ctx.sdkActiveStreams.set('native-b', replacement); ctx.sdkRequestSessions.set('native-b', chat); + ctx.sdkRequestRuntimes.set('native-b', { backendKey: 'claude', delegationTag: 'turn-b', senderId: 7 }); + const result = await handlers.get('netcatty:ai:sdk-agent:cleanup')({ sender: { id: 7 } }, { chatSessionId: chat, delegationTag: 'turn-a' }); + assert.equal(replacement.signal.aborted, false); assert.equal(ctx.sdkActiveStreams.has('native-b'), true); + assert.equal(ctx.sdkRequestSessions.get('native-b'), chat); assert.equal(ctx.sdkRequestRuntimes.get('native-b').delegationTag, 'turn-b'); + assert.deepEqual(effects, []); assert.equal(result.ok, false); +}); + +test("caller-supplied builtin chat cannot downgrade cancellation of a main-owned delegated request", async () => { + const effects = []; const chat = 'plugin-agent:11111111-1111-4111-8111-111111111111'; + const { handlers, ctx } = registerWithStubbedCtx({ mcpServerBridge: { + isPluginAgentConversation: (id) => id?.startsWith('plugin-agent:'), + assertPluginAgentCaller: (id, sender, tag) => { if (id !== chat || sender !== 7 || tag !== 'turn-b') throw Error('Unavailable'); }, + setChatSessionCancelled: () => effects.push('cancelled'), cancelPtyExecsForSession: () => effects.push('pty'), + clearPendingApprovals: () => effects.push('approval'), cancelWorkerBackgroundJobsForSession: () => effects.push('worker'), + } }); + const replacement = new AbortController(); + ctx.sdkActiveStreams.set('native-b', replacement); ctx.sdkRequestSessions.set('native-b', chat); + ctx.sdkRequestRuntimes.set('native-b', { backendKey: 'claude', delegationTag: 'turn-b', senderId: 7 }); + const cancel = handlers.get('netcatty:ai:sdk-agent:cancel'); + const result = await cancel({ sender: { id: 99 } }, { requestId: 'native-b', chatSessionId: 'builtin-chat' }); + assert.equal(replacement.signal.aborted, false); assert.equal(result.ok, false); assert.deepEqual(effects, []); + assert.equal((await cancel({ sender: { id: 7 } }, { requestId: 'native-b', chatSessionId: chat })).ok, true); + assert.equal(replacement.signal.aborted, true); +}); diff --git a/electron/bridges/mcpServerBridge.cjs b/electron/bridges/mcpServerBridge.cjs index 26d27c079..12a363dff 100644 --- a/electron/bridges/mcpServerBridge.cjs +++ b/electron/bridges/mcpServerBridge.cjs @@ -2307,9 +2307,11 @@ async function dispatchCore(method, params, approvalContext = {}) { // ── Handler: getContext ── async function handleGetContext(params, approvalContext) { - debugLog("handleGetContext:start", { params, sessionCount: sessions?.size || 0 }); - const toolHints = buildMcpToolHints(); + const delegated = pluginAgentDelegations.isApproved(approvalContext); + debugLog("handleGetContext:start", delegated ? { delegated: true } : { params, sessionCount: sessions?.size || 0 }); + const toolHints = delegated ? null : buildMcpToolHints(); if (!sessions) { + if (delegated) return { environment: "netcatty-terminal", description: "No host-selected terminal sessions are available.", hosts: [], hostCount: 0 }; return { hosts: [], instructions: "No sessions available.", @@ -2355,7 +2357,7 @@ async function handleGetContext(params, approvalContext) { description: "No hosts are available in the current scope.", hosts: [], hostCount: 0, - tools: toolHints, + ...(delegated ? {} : { tools: toolHints }), }; } for (const [sessionId, session] of sessions.entries()) { @@ -2566,12 +2568,20 @@ function cleanup() { shutdownHost(); } +// Keep identifier exports so Node 22's CJS namespace analysis also preserves the +// existing named exports consumed by renderer-side harness tests. +const registerPluginAgentDelegation = (...args) => pluginAgentDelegations.register(...args); +const getPluginAgentMcpConfiguration = (id, tag) => pluginAgentDelegations.configuration(id, tag); +const isPluginAgentConversation = (id) => pluginAgentDelegations.isReserved(id); +const assertPluginAgentCaller = (id, senderId, tag) => pluginAgentDelegations.assertCaller(id, senderId, tag); +const onPluginAgentRelease = (id, tag, cancel) => pluginAgentDelegations.onRelease(id, tag, cancel); + module.exports = { - registerPluginAgentDelegation: (...args) => pluginAgentDelegations.register(...args), - getPluginAgentMcpConfiguration: (id, tag) => pluginAgentDelegations.configuration(id, tag), - isPluginAgentConversation: (id) => pluginAgentDelegations.isReserved(id), - assertPluginAgentCaller: (id, senderId, tag) => pluginAgentDelegations.assertCaller(id, senderId, tag), - onPluginAgentRelease: (id, tag, cancel) => pluginAgentDelegations.onRelease(id, tag, cancel), + registerPluginAgentDelegation, + getPluginAgentMcpConfiguration, + isPluginAgentConversation, + assertPluginAgentCaller, + onPluginAgentRelease, init, setCommandBlocklist, getCommandBlocklist, diff --git a/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs b/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs index 20ae67889..3a18f6504 100644 --- a/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs +++ b/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs @@ -93,3 +93,18 @@ test("actual main TCP gate binds delegated credentials, scope and policy at work await assert.rejects(app.call("netcatty/getContext", { chatSessionId: coreId })); assert.throws(() => bridge.getPluginAgentMcpConfiguration(coreId)); }); + +for (const sessions of [null, new Map()]) test(`delegated empty environment omits global tool inventory (${sessions === null ? "uninitialized" : "empty scope"})`, async (t) => { + bridge.init({ sessions }); + const id = `plugin-agent:${randomUUID()}`; const tag = randomUUID(); + const registration = bridge.registerPluginAgentDelegation(id, { senderId: 7, turnTag: tag, tools: ["get_environment"], + assertCurrent: () => {}, dispatch: (_method, _params, execute) => execute() }); + t.after(() => { registration.dispose(); bridge.cleanup(); }); + const value = await bridge.dispatchBuiltinRpc("netcatty/getContext", { chatSessionId: id }, { trustedAgentSenderId: 7, trustedAgentTurnTag: tag }); + assert.equal(Object.hasOwn(value, "tools"), false); assert.deepEqual(value.hosts, []); +}); + +test("MCP bridge retains existing CJS namespace exports for actual Catty harness consumers", async () => { + const namespace = await import("./mcpServerBridge.cjs"); + for (const name of ["init", "cleanup", "dispatchBuiltinRpc", "registerPluginAgentDelegation"]) assert.equal(typeof namespace[name], "function", name); +});