Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-agent): preserve credential confirmations and propagate cancellation
DavidShen0e40c5ada974
diff --git a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.tsindex eeef1ba100..06edeb5c8a 100644--- a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts+++ b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts@@ -1,7 +1,7 @@import { readFileSync } from 'node:fs';import ts from 'typescript';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';+import type { InteractionDecision, InteractionRequest, InteractionResolver } from '@cindy/maker-core';import { createSharedPermission, type SharedPermission } from '../maker-ipc/sharedPermission';import { beginInteractionRoute, installDesktopInteractionHandler, type InteractionHandler, type InteractionSession } from '../maker-ipc/interactionRouter';import { assertSharedTaskInteractionResolveCurrent, assertSharedTaskInvoke, setSharedTaskInteractionReader, type SharedTaskPeerCapture } from '../device-link/sharedTaskDispatch.js';@@ -12,7 +12,7 @@ const ast = ts.createSourceFile('register.ts', source, ts.ScriptTarget.ES2022, tconst names = new Set(['installDesktopInteractionListener', 'clearPendingInteraction','schedulePendingPermissionTimeout', 'setPendingInteractionTimeoutsPaused',- 'resolvePendingInteraction', 'defaultDecisionForPending',+ 'resolvePendingInteraction', 'cancelPendingInteraction', 'defaultDecisionForPending','cleanupPendingAgentInteractionsForSession', 'takePendingInteractionsForSession','bindSharedPermission',]);@@ -55,7 +55,7 @@ function harness() {setExecutionPaused: (id: string, value: boolean) => { if (value) held.add(id); else held.delete(id); },onInteractionResolved: vi.fn(),};- const listeners = new Map<string, (request: InteractionRequest) => Promise<InteractionDecision>>();+ const listeners = new Map<string, InteractionResolver>();const entries = new Map();const dismiss = vi.fn();const deps = {@@ -86,7 +86,7 @@ function harness() {take: (id: string) => Array<{ resolve: (decision: InteractionDecision) => void; sharedPermission?: SharedPermission }>;resolveFromIpc: (event: unknown, id: string, decision: InteractionDecision) => Promise<{ accepted: boolean }>;};- const request = (id = 'permission', sessionId = 'task', kind: InteractionRequest['kind'] = 'permission', channel?: InteractionHandler) => {+ const request = (id = 'permission', sessionId = 'task', kind: InteractionRequest['kind'] = 'permission', channel?: InteractionHandler, signal?: AbortSignal) => {const session: InteractionSession = { id: sessionId, setInteractionListener: handler => { if (handler) listeners.set(sessionId, handler); } };runtime.install(session);const lease = channel ? beginInteractionRoute(session, {@@ -96,7 +96,7 @@ function harness() {onCancel: () => true,}) : undefined;const settled = vi.fn();- const promise = listeners.get(sessionId)!({ kind, requestId: id, toolName: 'Shell', input: {} } as InteractionRequest);+ const promise = listeners.get(sessionId)!({ kind, requestId: id, toolName: 'Shell', input: {} } as InteractionRequest, signal);void promise.then(settled);return { promise, settled, lease };};@@ -190,6 +190,35 @@ it('rejects a guest replacement tool input without consuming the pending request});describe('permission timeout follows the task pause lifecycle', () => {+ // IM permission contract: production listener cancellation must dismiss paused cards too.+ // Existing cases stop the whole task; a single aborted provider request must also settle+ // Desktop and an IM takeover, reject late approval, and leave other tasks alone (unit).+ it.each(['desktop', 'im-takeover'])('dismisses an aborted request while paused on %s', async (surface) => {+ const h = harness();+ const abort = new AbortController();+ const p = h.request('permission', 'task', 'permission', undefined, abort.signal);+ const other = h.request('other', 'other-task');+ const taken = surface === 'im-takeover' ? h.take('task')[0] : undefined;+ h.hold('task', true);+ const allow = { kind: 'permission', behavior: 'allow' } as const;+ if (taken) taken.resolve(allow);+ else expect(h.answer('permission', allow)).toBe(false);+ expect(p.settled).not.toHaveBeenCalled();+ abort.abort();+ const denied = { kind: 'permission', behavior: 'deny', reason: 'session_aborted' };+ await expect(p.promise).resolves.toEqual(denied);+ expect(h.entries.has('permission')).toBe(false);+ expect(h.dismiss).toHaveBeenCalledTimes(1);+ if (taken) await expect(taken.sharedPermission!.result).resolves.toEqual(denied);+ h.hold('task', false);+ expect(h.answer('permission', allow)).toBe(false);+ expect(taken?.sharedPermission?.decide(allow)).not.toBe(true);+ expect(h.entries.has('other')).toBe(true);+ expect(other.settled).not.toHaveBeenCalled();+ expect(h.answer('other', allow)).toBe(true);+ await expect(other.promise).resolves.toEqual(allow);+ });+it('holds a shared route timeout until resume without closing either surface early', async () => {const h = harness();h.hold('task', true);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.tsindex e80fadeb0a..9ad27f777f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';+import type { InteractionDecision, InteractionRequest, InteractionResolver } from '@cindy/maker-core';import {beginInteractionRoute,@@ -29,8 +29,8 @@ function ask(requestId: string): InteractionRequest {}function makeSession() {- let listener: InteractionHandler | null = null;- const setInteractionListener = vi.fn((next: InteractionHandler | null) => {+ let listener: InteractionResolver | null = null;+ const setInteractionListener = vi.fn((next: InteractionResolver | null) => {listener = next;});return {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.tsindex 5ed42557df..a5cc66b085 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';+import type { InteractionDecision, InteractionRequest, InteractionResolver } from '@cindy/maker-core';import {beginInteractionRoute,installDesktopInteractionHandler,@@ -8,10 +8,10 @@ import {import type { SharedPermission } from '../sharedPermission';function setup() {- let dispatch!: InteractionHandler;+ let dispatch!: InteractionResolver;const session = {id: 'session',- setInteractionListener(handler: InteractionHandler | null) {+ setInteractionListener(handler: InteractionResolver | null) {if (handler) dispatch = handler;},};@@ -43,7 +43,7 @@ function setup() {input: {},} as InteractionRequest;return {- dispatch: () => dispatch(request),+ dispatch: (signal?: AbortSignal) => dispatch(request, signal),desktopHandler,imHandler,lease,@@ -85,11 +85,24 @@ describe('shared permission route', () => {await expect(test.im.result).resolves.toMatchObject({ behavior: 'deny' });});+ // 远程凭证请求的取消经 Session listener 进入;旧覆盖只有整轮结束,缺单请求取消(unit)。+ it('settles Desktop and IM with the same denial when a provider request is cancelled', async () => {+ const test = setup();+ const abort = new AbortController();+ const result = test.dispatch(abort.signal);+ try {+ abort.abort();+ await expect(result).resolves.toMatchObject({ behavior: 'deny', reason: 'session_aborted' });+ await expect(test.desktop.result).resolves.toEqual(await test.im.result);+ expect(test.im.decide({ kind: 'permission', behavior: 'allow' })).toBe(false);+ } finally { test.lease.release(); }+ });+it('applies a channel restriction before either confirmation is exposed', async () => {- let dispatch!: InteractionHandler;+ let dispatch!: InteractionResolver;const session = {id: 'restricted',- setInteractionListener(handler: InteractionHandler | null) {+ setInteractionListener(handler: InteractionResolver | null) {if (handler) dispatch = handler;},};diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.tsindex b476aa3a1c..9d735c70bf 100644--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts@@ -10,6 +10,7 @@import type {InteractionDecision,InteractionRequest,+ InteractionResolver,TurnPermissionOrigin,} from '@cindy/maker-core';import { createSharedPermission, type SharedPermission } from './sharedPermission';@@ -47,7 +48,7 @@ export interface InteractionLifecycleObserver {export interface InteractionSession {readonly id: string;- setInteractionListener(listener: InteractionHandler | null): void;+ setInteractionListener(listener: InteractionResolver | null): void;}type RouteRegistration =@@ -120,7 +121,7 @@ class SessionInteractionRouter {private readonly pending = new Map<string, PendingRequest>();constructor(private readonly session: InteractionSession) {- session.setInteractionListener((request) => this.dispatch(request));+ session.setInteractionListener((request, signal) => this.dispatch(request, signal));}setDesktopHandler(handler: InteractionHandler, cancel?: (requestId: string, decision: InteractionDecision) => void): void {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 99fc9469db..d292270022 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -3453,6 +3453,18 @@ function bindSharedPermission(requestId: string, entry: PendingInteractionEntry,});}+/** Host cancellation is final even while user answers are held by execution-pause. */+function cancelPendingInteraction(requestId: string, decision: InteractionDecision): boolean {+ const entry = pendingInteractionResolvers.get(requestId);+ if (!entry) return false;+ if (entry.sharedPermission) {+ entry.sharedPermission.settle(decision);+ decision = entry.sharedPermission.decision ?? decision;+ }+ // Use the same final-decision path as SharedPermission, never the paused answer gate.+ return resolvePendingInteraction(requestId, decision, true);+}+function resolvePendingInteraction(requestId: string, decision: InteractionDecision, fromShared = false): boolean {const resolver = pendingInteractionResolvers.get(requestId);if (!resolver || (!fromShared && agentInputCoordinatorHolder?.isExecutionPaused(resolver.sessionId))) return false;@@ -5141,7 +5153,7 @@ export function installDesktopInteractionListener(session: {);});}, (requestId, decision) => {- resolvePendingInteraction(requestId, decision);+ cancelPendingInteraction(requestId, decision);});}diff --git a/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.tsindex 332325bc6d..850275ba72 100644--- a/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts@@ -11,7 +11,7 @@ import os from 'node:os';import path from 'node:path';import { createAnthropicCompatProxy, type ProxyHandle } from '@cindy/anthropic-compat-proxy';-import { ClaudeCodeAgent, type AgentDeps, type AgentEvent, type InteractionRequest, type Logger } from '@cindy/maker-core';+import { ClaudeCodeAgent, type AgentDeps, type AgentEvent, type InteractionDecision, type InteractionRequest, type Logger } from '@cindy/maker-core';import { buildUserProvider } from '@cindy/model-providers';import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';@@ -23,12 +23,13 @@ import { getActiveCatalog, setCustomProviders } from '../../maker-host/active-caimport { createModelRoutingTransform, setClaudeProxyGatewayKeyReader, setClaudeProxySessionIdResolver } from '../../maker-host/anthropic-compat-proxy-host';import { setCustomProviderKeyReader } from '../../maker-host/provider-route';import { bindHostedSessionProvider, clearAllSessionProviders } from '../../maker-host/session-provider-store';+import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';const REPO = path.resolve(__dirname, '../../../../../..');const ARCH = `${process.platform}-${process.arch}`;const CLAUDE = path.join(REPO, 'apps', 'claude-code-bin', ARCH, process.platform === 'win32' ? 'claude.exe' : 'claude');const RG = path.join(REPO, 'apps', 'ripgrep-bin', ARCH, process.platform === 'win32' ? 'rg.exe' : 'rg');-const available = fs.existsSync(CLAUDE) && fs.existsSync(RG) && process.platform !== 'win32';+const available = fs.existsSync(CLAUDE) && fs.existsSync(RG);const MODEL = 'claude-sonnet-4-5';const noopLogger: Logger = {@@ -83,13 +84,13 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {let root = '';let steps: Array<{ name: string; input: unknown }> = [];const requests: MainRequest[] = [];- const previousHome = process.env.HOME;beforeAll(async () => {root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-cc-hosted-')));// Claude Code 读写 ~/.claude:指向临时目录,不碰开发机的真实配置。- process.env.HOME = path.join(root, 'home');- fs.mkdirSync(process.env.HOME, { recursive: true });+ const isolatedHome = path.join(root, 'home');+ fs.mkdirSync(isolatedHome, { recursive: true });+ for (const key of ['HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA']) vi.stubEnv(key, isolatedHome);server = createServer((req, res) => {let body = '';req.on('data', (chunk) => { body += chunk; });@@ -138,10 +139,10 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {});afterAll(async () => {- process.env.HOME = previousHome;+ vi.unstubAllEnvs();await new Promise<void>((resolve) => server.close(() => resolve()));- // Claude Code 退出时可能还在写 ~/.claude,重试几次再删。- fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ // 异步等待 CLI 退出并释放 Windows 文件句柄,避免同步重试挡住子进程收尾。+ await fs.promises.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });});function claudeDeps(proxyEndpoint = endpoint): AgentDeps {@@ -163,12 +164,17 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {resolve?: (request: InteractionRequest) => boolean,route?: { endpoint: string; model: string; providerId: string; resolveHostedId?: boolean },initialPermissionMode = permissionMode,+ credentialConsent?: (request: InteractionRequest) => Promise<InteractionDecision>,) {const project = path.join(root, `project-${permissionMode}`);const hostRoot = path.join(root, `host-${permissionMode}`);fs.mkdirSync(project, { recursive: true });fs.writeFileSync(path.join(project, 'hello.txt'), 'hello from the controller\n');fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Project memory\nAlways answer briefly.\n');+ if (credentialConsent) {+ fs.writeFileSync(path.join(project, '.env'), 'INVALID_FIXTURE=first');+ fs.writeFileSync(path.join(project, '.env.production'), 'INVALID_FIXTURE=second');+ }const agent = new ClaudeCodeAgent(claudeDeps(route?.endpoint));const host = createRemoteAgentHost({isAgentAvailable: (kind) => kind === 'claude-code',@@ -197,6 +203,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),rgPath: RG,prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ ...(credentialConsent ? { credentialConsent: { description: 'Fixture credential confirmation' } } : {}),capture: () => ({beforeWrite: async (file) => {captured.push(file);@@ -211,6 +218,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {const asked: InteractionRequest[] = [];handle.setInteractionResolver(async (request) => {asked.push(request);+ if (credentialConsent) return credentialConsent(request);const allow = resolve ? resolve(request) : true;return request.kind === 'permission'? { kind: 'permission', behavior: allow ? 'allow' : 'deny', ...(allow ? {} : { reason: 'denied by test' }) }@@ -237,7 +245,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {return { project, hostRoot, events, asked, captured };}- it('replaces the built-in file and shell tools and runs every step on the controller', { timeout: 120_000 }, async () => {+ it.skipIf(process.platform === 'win32')('replaces the built-in file and shell tools and runs every step on the controller', { timeout: 120_000 }, async () => {const projectPath = path.join(root, 'project-bypassPermissions');steps = [{ name: 'mcp__cindy_exec__Bash', input: { command: 'pwd; ls', description: 'Show location' } },@@ -276,7 +284,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {expect(toolNames).toEqual(['Bash', 'Write', 'Read', 'Edit']);});- it('honors switching an existing hosted session to Full access without a confirmation', { timeout: 120_000 }, async () => {+ it.skipIf(process.platform === 'win32')('honors switching an existing hosted session to Full access without a confirmation', { timeout: 120_000 }, async () => {steps = [{ name: 'mcp__cindy_exec__Bash', input: { command: 'printf switched > switched.txt' } }];requests.length = 0;const { project, asked } = await run('bypassPermissions', undefined, undefined, 'default');@@ -284,7 +292,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {expect(fs.readFileSync(path.join(project, 'switched.txt'), 'utf8')).toBe('switched');});- it('asks on this computer for commands that change things, but not for reads and read-only commands', { timeout: 120_000 }, async () => {+ it.skipIf(process.platform === 'win32')('asks on this computer for commands that change things, but not for reads and read-only commands', { timeout: 120_000 }, async () => {const projectPath = path.join(root, 'project-default');steps = [{ name: 'mcp__cindy_exec__Read', input: { file_path: path.join(projectPath, 'hello.txt') } },@@ -308,6 +316,34 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {expect(last.results[3].isError).toBe(true);});+ // Bug: MCP 首次 HTTP 响应默认 60s,原 JSON 隧道把人工确认也算进去。+ // 生产入口:真实 ClaudeCodeAgent → runHost 隧道 → startRemoteAgentSession → 执行器。+ // 原 E2E 都立即回答;此处第 70s 授权,后续另一凭证读取应直接成功。tier: e2e(真实 CLI/计时)。+ it('keeps a credential confirmation alive past the MCP first-response timeout', { timeout: 120_000 }, async () => {+ const projectPath = path.join(root, 'project-bypassPermissions');+ steps = [+ { name: 'mcp__cindy_exec__Read', input: { file_path: path.join(projectPath, '.env') } },+ { name: 'mcp__cindy_exec__Read', input: { file_path: path.join(projectPath, '.env.production') } },+ ];+ requests.length = 0;+ let waited = false;+ const { asked } = await run('bypassPermissions', undefined, undefined, 'bypassPermissions', async () => {+ if (!waited) {+ waited = true;+ // real-wait: CLI 子进程的 60s HTTP 定时器不能由 Vitest fake timers 推进。+ await new Promise((resolve) => setTimeout(resolve, 70_000));+ }+ return { kind: 'permission', behavior: 'allow', permissionUpdates: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL] };+ });+ expect(asked).toHaveLength(1);+ const results = requests.at(-1)!.results;+ expect(results.map((result) => result.isError)).toEqual([false, false]);+ expect(results[0].text).toContain('INVALID_FIXTURE=first');+ expect(results[1].text).toContain('INVALID_FIXTURE=second');+ expect(requests.every((request) => request.system === requests[0].system)).toBe(true);+ expect(requests.every((request) => JSON.stringify(request.toolNames) === JSON.stringify(requests[0].toolNames))).toBe(true);+ });+async function withProviderProxy(model: string,use: (proxyEndpoint: string, fallbackRequests: string[]) => Promise<void>,@@ -359,7 +395,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {}}- it('cleans up the fallback server and provider settings when proxy startup fails', async () => {+ it.skipIf(process.platform === 'win32')('cleans up the fallback server and provider settings when proxy startup fails', async () => {let fallbackEndpoint = '';const use = vi.fn(async () => {});const createProxy = vi.fn<typeof createAnthropicCompatProxy>(async (options) => {@@ -374,7 +410,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {await expect(fetch(fallbackEndpoint)).rejects.toThrow();});- it.each(['claude-sonnet-4-5-20250929', 'hosted-shared-model'])('routes the first real Claude SDK model request for %s to its selected provider', { timeout: 120_000 }, async (model) => {+ it.skipIf(process.platform === 'win32').each(['claude-sonnet-4-5-20250929', 'hosted-shared-model'])('routes the first real Claude SDK model request for %s to its selected provider', { timeout: 120_000 }, async (model) => {await withProviderProxy(model, async (proxyEndpoint, fallbackRequests) => {requests.length = 0;steps = [];diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.tsindex 786f09aa88..4772467408 100644--- a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts@@ -4,7 +4,9 @@ import path from 'node:path';import { pathToFileURL } from 'node:url';import { MAIN_OWNED_SEND_CONTEXT, type InteractionDecision } from '@cindy/maker-core';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import WebSocket from 'ws';import { mapClaudeHostedEvent } from '../controller/eventMap';@@ -15,6 +17,8 @@ import type { RemoteAgentRunClient } from '../controller/runClient';import { credentialConfirmation, takeGroupSwitchState } from '../controller/startRemote';import { EventLog, LineSplitter } from '../eventLog';import { ExecutorGate } from '../executor/gate';+import { RemoteExecutor, type ExecutorConfirmation } from '../executor/executor';+import { handleExecMcpRequest } from '../executor/ccMcp';import { ExecutorWorkspace } from '../executor/workspace';import { createRunTunnel } from '../host/tunnel';import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';@@ -63,6 +67,229 @@ describe('event log', () => {});describe('tunnel', () => {+ // Regression: SDK cancellation uses a notification without closing its transport.+ // Real MCP Client -> tunnel -> executor, with a pending credential read (unit/loopback).+ // Socket-abort coverage did not catch stale execution/grants after a tool timeout.+ it.each(['timeout', 'abort'])('cancels an MCP tool through the SDK %s notification without accepting late approval', async (end) => {+ fs.writeFileSync(path.join(root, '.env'), 'INVALID_FIXTURE=secret');+ fs.writeFileSync(path.join(root, 'hello.txt'), 'ordinary read');+ const signals: AbortSignal[] = [];+ const answers: Array<(answer: ExecutorConfirmation) => void> = [];+ const workspace = new ExecutorWorkspace({ workingDir: root });+ const gate = new ExecutorGate(workspace, 'full', Date.now, { confirmCredentials: true });+ const executor = new RemoteExecutor({+ workspace, gate, rgPath: '',+ confirm: (_action, signal) => {+ signals.push(signal);+ return new Promise((resolve) => { answers.push(resolve); });+ },+ });+ let streamStarted = false;+ const tunnel = await createRunTunnel({+ http: (request, signal) => handleExecMcpRequest(executor, request.method, request.body, signal),+ wsOpen() {}, wsMessage() {}, wsClose() {},+ });+ const client = new Client({ name: 'cancellation-test', version: '1' });+ const abort = new AbortController();+ try {+ await client.connect(new StreamableHTTPClientTransport(new URL(`${tunnel.url}/mcp/cindy_exec`), {+ requestInit: { headers: { authorization: `Bearer ${tunnel.token}` } },+ fetch: async (input, init) => {+ const response = await fetch(input, init);+ if (response.headers.get('content-type')?.includes('text/event-stream')) streamStarted = true;+ return response;+ },+ }));+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });+ const read = { name: 'Read', arguments: { file_path: path.join(root, '.env') } };+ const pending = client.callTool(read, undefined, { timeout: 60_000, signal: abort.signal }).catch((error: unknown) => error);+ await vi.waitFor(() => { expect(signals).toHaveLength(1); expect(streamStarted).toBe(true); });+ const ordinary = client.callTool({ name: 'Read', arguments: { file_path: path.join(root, 'hello.txt') } }, undefined, { timeout: 120_000 });+ if (end === 'timeout') await vi.advanceTimersByTimeAsync(60_000);+ else abort.abort();+ expect(await pending).toBeInstanceOf(Error);+ await vi.waitFor(() => expect(signals[0].aborted).toBe(true));+ answers[0]('session');+ expect(await ordinary).toMatchObject({ content: [expect.objectContaining({ text: expect.stringContaining('ordinary read') })] });+ await vi.waitFor(() => expect(tunnel.linkActivity().httpInFlight).toBe(0));+ const retry = client.callTool(read);+ await vi.waitFor(() => expect(signals).toHaveLength(2));+ expect(gate.needsCredentialConsent({ kind: 'read', path: path.join(root, '.env') })).toBe(true);+ answers[1](false);+ expect(await retry).toMatchObject({ isError: true });+ } finally {+ abort.abort();+ await executor.close();+ for (const answer of answers) answer(false);+ await client.close();+ await tunnel.close();+ vi.useRealTimers();+ }+ });++ // Cancellation belongs to one run/session/typed request id. A reused id must survive+ // a late result from its cancelled predecessor, and a duplicate must not replace it (unit).+ it('isolates cancellation identities and keeps a reused id registered after a late result', async () => {+ const calls: Array<{ name: string; signal: AbortSignal; finish: () => void }> = [];+ const handlers: Parameters<typeof createRunTunnel>[0] = {+ http: (request, signal) => {+ const message = JSON.parse(request.body!.toString());+ if (message.method !== 'tools/call') return Promise.resolve({ status: 202, headers: [] });+ return new Promise((resolve) => calls.push({ name: message.params.name, signal,+ finish: () => resolve({ status: 200, headers: [['content-type', 'application/json']],+ body: Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { content: [] } })) }),+ }));+ },+ wsOpen() {}, wsMessage() {}, wsClose() {},+ };+ const first = await createRunTunnel(handlers);+ const second = await createRunTunnel(handlers);+ const post = (tunnel: typeof first, session: string, body: unknown, token = tunnel.token) => fetch(`${tunnel.url}/mcp/cindy_exec`, {+ method: 'POST', headers: { authorization: `Bearer ${token}`, 'mcp-session-id': session, accept: 'application/json, text/event-stream' },+ body: JSON.stringify(body),+ });+ const call = (tunnel: typeof first, session: string, id: string | number, name: string) =>+ post(tunnel, session, { jsonrpc: '2.0', id, method: 'tools/call', params: { name } });+ const cancel = (tunnel: typeof first, session: string, requestId: string | number, token?: string) =>+ post(tunnel, session, { jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId } }, token);+ try {+ const responses = await Promise.all([+ call(first, 'a', 0, 'original'), call(first, 'a', '0', 'string-id'),+ call(first, 'b', 0, 'other-session'), call(second, 'a', 0, 'other-run'),+ ]);+ expect((await call(first, 'a', 0, 'duplicate')).status).toBe(400);+ expect(calls).toHaveLength(4);+ expect((await cancel(first, 'a', 0, 'wrong-token')).status).toBe(401);+ expect((await cancel(first, 'a', 'unknown')).status).toBe(202);+ expect(calls.every((entry) => !entry.signal.aborted)).toBe(true);+ expect((await cancel(first, 'a', 0)).status).toBe(202);+ expect(calls.filter((entry) => entry.signal.aborted).map((entry) => entry.name)).toEqual(['original']);+ expect(await responses[0].text()).toContain('Request cancelled.');+ const reused = await call(first, 'a', 0, 'reused');+ calls.find((entry) => entry.name === 'original')!.finish();+ await vi.waitFor(() => expect(first.linkActivity().httpInFlight).toBe(3));+ await cancel(first, 'a', 0);+ expect(calls.find((entry) => entry.name === 'reused')!.signal.aborted).toBe(true);+ expect(await reused.text()).toContain('Request cancelled.');+ for (const entry of calls) entry.finish();+ for (const response of responses.slice(1)) expect(await response.text()).toContain('"result"');+ await vi.waitFor(() => {+ expect(first.linkActivity().httpInFlight).toBe(0);+ expect(second.linkActivity().httpInFlight).toBe(0);+ });+ } finally {+ for (const entry of calls) entry.finish();+ await first.close();+ await second.close();+ }+ });++ // 60s 首次响应超时:真实 tunnel 必须先返回 MCP SSE,等待业务结果时保持连接;旧用例都是立即返回(unit)。+ it('starts an MCP tool response before confirmation and finishes it with the original result', async () => {+ let answer!: (value: { status: number; headers: Array<[string, string]>; body: Buffer }) => void;+ const tunnel = await createRunTunnel({+ http: () => new Promise((resolve) => { answer = resolve; }),+ wsOpen() {}, wsMessage() {}, wsClose() {},+ });+ const abort = new AbortController();+ let received = false;+ const response = fetch(`${tunnel.url}/mcp/cindy_exec`, {+ method: 'POST', signal: abort.signal,+ headers: { authorization: `Bearer ${tunnel.token}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 0, method: 'tools/call', params: { name: 'Read', arguments: { file_path: '.env' } } }),+ }).then((value) => { received = true; return value; });+ void response.catch(() => {});+ try {+ await vi.waitFor(() => expect(received).toBe(true), { timeout: 1000 });+ const stream = await response;+ expect(stream.headers.get('content-type')).toContain('text/event-stream');+ const result = { jsonrpc: '2.0', id: 0, result: { content: [{ type: 'text', text: 'fixture' }] } };+ answer({ status: 200, headers: [['content-type', 'application/json']], body: Buffer.from(JSON.stringify(result)) });+ const data = (await stream.text()).split('\n').filter((line) => line.startsWith('data:')).map((line) => JSON.parse(line.slice(5)));+ expect(data).toEqual([result]);+ } finally {+ abort.abort();+ answer?.({ status: 200, headers: [], body: Buffer.from('{}') });+ await tunnel.close();+ }+ });++ // 同一生产 HTTP 入口:SSE 不能改变 JSON 客户端、初始化与其他 MCP 服务的状态码/响应(unit)。+ it.each([+ ['/mcp/cindy_exec', 'application/json', 'tools/call'],+ ['/mcp/cindy_exec', 'text/event-stream', 'initialize'],+ ['/mcp/other', 'text/event-stream', 'tools/call'],+ ])('preserves the ordinary response for %s accepting %s on %s', async (endpoint, accept, method) => {+ const tunnel = await createRunTunnel({+ http: async () => ({ status: 409, headers: [['content-type', 'application/json']], body: Buffer.from('{"error":"fixture"}') }),+ wsOpen() {}, wsMessage() {}, wsClose() {},+ });+ try {+ const response = await fetch(`${tunnel.url}${endpoint}`, {+ method: 'POST', headers: { authorization: `Bearer ${tunnel.token}`, accept },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method }),+ });+ expect(response.status).toBe(409);+ expect(response.headers.get('content-type')).toBe('application/json');+ expect(await response.json()).toEqual({ error: 'fixture' });+ } finally { await tunnel.close(); }+ });++ // 流已建立后无法改 HTTP 状态;失败必须收口成对应请求的协议错误,不能泄露内部异常(unit)。+ it.each(['status', 'invalid-json', 'empty', 'throw'])('ends an MCP stream with a protocol error on %s', async (failure) => {+ const tunnel = await createRunTunnel({+ http: async () => {+ if (failure === 'throw') throw new Error('PRIVATE_FIXTURE_PATH');+ return { status: failure === 'status' ? 502 : 200, headers: [],+ ...(failure === 'empty' ? {} : { body: Buffer.from('PRIVATE_FIXTURE_PATH') }) };+ },+ wsOpen() {}, wsMessage() {}, wsClose() {},+ });+ try {+ const response = await fetch(`${tunnel.url}/mcp/cindy_exec`, {+ method: 'POST', headers: { authorization: `Bearer ${tunnel.token}`, accept: 'text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 'call-1', method: 'tools/call' }),+ });+ const body = await response.text();+ expect(body).not.toContain('PRIVATE_FIXTURE_PATH');+ expect(JSON.parse(body.split('\n').find((line) => line.startsWith('data:'))!.slice(5)))+ .toMatchObject({ jsonrpc: '2.0', id: 'call-1', error: { code: -32603 } });+ } finally { await tunnel.close(); }+ });++ // 旧用例没有挂起 SSE:等待期间有心跳,客户端取消必须中止反向请求并清除心跳(unit)。+ it('keeps a pending MCP stream alive and cancels its reverse request and heartbeat on disconnect', async () => {+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });+ let cancelled!: () => void;+ const cancellation = new Promise<void>((resolve) => { cancelled = resolve; });+ const tunnel = await createRunTunnel({+ http: (_request, signal) => new Promise((_resolve, reject) => {+ signal.addEventListener('abort', () => { cancelled(); reject(new Error('aborted')); }, { once: true });+ }),+ wsOpen() {}, wsMessage() {}, wsClose() {},+ });+ const abort = new AbortController();+ try {+ const response = await fetch(`${tunnel.url}/mcp/cindy_exec`, {+ method: 'POST', signal: abort.signal,+ headers: { authorization: `Bearer ${tunnel.token}`, accept: 'text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call' }),+ });+ const reader = response.body!.getReader();+ expect(new TextDecoder().decode((await reader.read()).value)).toContain(': waiting');+ vi.advanceTimersByTime(60_000);+ expect(new TextDecoder().decode((await reader.read()).value)).toContain(': waiting');+ abort.abort();+ await cancellation;+ await vi.waitFor(() => expect(tunnel.linkActivity().httpInFlight).toBe(0));+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ abort.abort();+ await tunnel.close();+ vi.useRealTimers();+ }+ });+it('requires the run token in the header or the path prefix and strips the prefix', async () => {const seen: string[] = [];const tunnel = await createRunTunnel({diff --git a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.tsindex 9074c235fb..50970f47bd 100644--- a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts@@ -17,8 +17,8 @@ import type {SendOptions,UserMessage,} from '@cindy/maker-core';-import { MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { MAIN_OWNED_SEND_CONTEXT, Session } from '@cindy/maker-core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { RemoteAgentPoller } from '../controller/poller';import { credentialGrantFor, forgetCredentialGrants } from '../executor/credentialGrants';@@ -26,6 +26,7 @@ import { startRemoteAgentSession, type StartRemoteAgentDeps } from '../controlleimport { createRemoteAgentHost, type HostedStartInput } from '../host/runHost';import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';import { DEFAULT_REMOTE_AGENT_LIMITS, type RemoteAgentLimits } from '../../../shared/remoteAgentLimits';+import { installDesktopInteractionHandler } from '../../maker-ipc/interactionRouter';const RG = path.resolve(__dirname, '../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');const CONTROLLER = 'controller-device-1';@@ -200,6 +201,52 @@ function createHost(readLimits: () => RemoteAgentLimits = () => DEFAULT_REMOTE_A}describe('remote agent round trip', () => {+ // provider-sharing §9:走 HTTP → 执行器 → Session → 真实交互路由,检查取消卡片及迟到授权。+ // 现有往返用例没有挂起确认后取消;最小输入是一次 .env 读取,tier: unit(仅 loopback)。+ it.each(['request', 'stop', 'permission', 'close'])('dismisses a shared-provider credential card on %s cancellation', async (end) => {+ fs.writeFileSync(path.join(project, '.env'), 'INVALID_FIXTURE=one');+ const host = createHost();+ const grant = credentialGrantFor(`cancel-${end}`, 'share:fixture');+ const handle = await startRemoteAgentSession('claude-code', {+ sessionId: `cancel-${end}`, workingDir: project, model: 'm', permissionMode: 'bypassPermissions',+ }, { ...makeDeps(host), credentialConsent: { description: 'fixture', grant } });+ const noop = () => {};+ const logger = { trace: noop, debug: noop, info: noop, warn: noop, error: noop, fatal: noop, child: () => logger };+ const session = new Session({ id: `cancel-${end}`, agentKind: 'claude-code', workDir: project, handle, capabilities: {} as never, logger, turnStallMs: 0 });+ let answer!: (value: InteractionDecision) => void;+ let requestId = '';+ const cancel = vi.fn();+ installDesktopInteractionHandler(session, (request) => {+ requestId = request.requestId;+ return new Promise((resolve) => { answer = resolve; });+ }, cancel);+ const abort = new AbortController();+ const tunnel = hostInputs[0].tunnel;+ const response = fetch(`${tunnel.url}/exec/fs.read`, {+ method: 'POST', signal: abort.signal,+ headers: { authorization: `Bearer ${tunnel.token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ path: '.env' }),+ });+ void response.catch(() => {});+ try {+ await vi.waitFor(() => expect(requestId).not.toBe(''));+ if (end === 'request') abort.abort();+ else if (end === 'stop') await handle.abort();+ else if (end === 'permission') await handle.setPermissionMode!('ask');+ else await handle.close({ reason: 'navigation' });+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledWith(requestId, expect.objectContaining({ behavior: 'deny' })), { timeout: 1000 });+ answer({ kind: 'permission', behavior: 'allow', permissionUpdates: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL] });+ await response.then((value) => value.arrayBuffer(), () => undefined);+ expect(grant.restore(JSON.stringify(['bypassPermissions', false]))).toBe(false);+ } finally {+ abort.abort();+ answer?.({ kind: 'permission', behavior: 'deny' });+ await session.close();+ host.dispose();+ forgetCredentialGrants(`cancel-${end}`);+ }+ });+it('enforces limits through the controller and releases capacity after close', async () => {let limits = { perDevice: 1, total: 2 };const host = createHost(() => limits);diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.tsindex 4d424ef9f9..1c0acd7e9e 100644--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts@@ -178,6 +178,8 @@ export interface RemoteHandleDeps {started: RemoteStartedInfo;workspace: ExecutorWorkspace;recordApproval(action: ExecutorAction): void;+ /** 用户停止或关闭时立即收起本机确认,不等远端 RPC 返回。 */+ cancelPendingConfirmations?(): void;onInvalidResumeSession?: (expectedSdkSessionId: string) => Promise<boolean>;/** 读本机图片(随消息带给对方)。 */readImage?: (path: string) => Promise<Buffer>;@@ -211,7 +213,7 @@ export interface RemoteAgentHandleController {* 本机自己发起的确认(不是 Agent 发来的):走与 Agent 确认同一个确认卡通道,桌面、手机远控与 IM 都能* 处理。只有本机提供了凭证授权建议的确认卡能返回会话级允许;交互还没接上或任务已结束时按拒绝处理。*/- confirm(request: LocalConfirmation): Promise<ExecutorConfirmation>;+ confirm(request: LocalConfirmation, signal?: AbortSignal): Promise<ExecutorConfirmation>;}export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandleController {@@ -298,9 +300,11 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandsend: (message, opts) => sendLike('send', message, opts),steer: (message, opts) => sendLike('steer', message, opts),abort: async () => {+ deps.cancelPendingConfirmations?.();await call('abort');},close: async (opts?: AgentSessionTeardownOptions) => {+ deps.cancelPendingConfirmations?.();try {await client.close('close', opts?.reason ?? 'navigation');} finally {@@ -308,6 +312,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand}},detach: async (opts?: AgentSessionTeardownOptions) => {+ deps.cancelPendingConfirmations?.();try {await client.close('detach', opts?.reason ?? 'navigation');} finally {@@ -452,10 +457,10 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand}return null;},- async confirm(request) {- if (!resolver || disposed) return false;- const decision = await resolver({ ...request, kind: 'permission', requestId: deps.newId() });- if (disposed || decision.kind !== 'permission' || decision.behavior !== 'allow') return false;+ async confirm(request, signal) {+ if (!resolver || disposed || signal?.aborted) return false;+ const decision = await resolver({ ...request, kind: 'permission', requestId: deps.newId() }, signal);+ if (disposed || signal?.aborted || decision.kind !== 'permission' || decision.behavior !== 'allow') return false;// 只能从本机生成的凭证确认卡建立授权;对方的 interaction 回包不经过这里。if (request.metadata?.hostOwnedConfirmation === 'shared_provider_credential'&& isProviderShareCredentialSessionApproval(request.suggestions)diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex 7f95d51aaa..219205606f 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -251,8 +251,8 @@ export async function startRemoteAgentSession(...(kind === 'claude-code' && deps.webFetch ? { webFetch: deps.webFetch } : {}),...(credentialConsent? {- confirm: async (action: ExecutorAction) =>- controller?.confirm(credentialConfirmation(action, credentialConsent.description)) ?? false,+ confirm: async (action: ExecutorAction, signal: AbortSignal) =>+ controller?.confirm(credentialConfirmation(action, credentialConsent.description), signal) ?? false,gitCredentials: sharedGitCredentials,...(grant? {@@ -412,6 +412,7 @@ export async function startRemoteAgentSession(started,workspace,recordApproval: (action) => executor.recordApproval(action),+ cancelPendingConfirmations: () => executor.cancelPendingConfirmations(),onInvalidResumeSession: opts.onInvalidResumeSession,mapEvent: deps.mapEvent?.(kind),newId: deps.newId,diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.tsindex 5233a5223c..b50c27c5a5 100644--- a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts@@ -617,7 +617,7 @@ describe('shared provider credentials', () => {function sharedExecutor(mode: ReturnType<typeof executorGateModeFor>,- confirm?: (action: ExecutorAction) => Promise<ExecutorConfirmation>,+ confirm?: RemoteExecutorOptions['confirm'],gitCredentials?: GitCredentialHistory,credentialGrant?: RemoteExecutorOptions['credentialGrant'],) {@@ -769,7 +769,7 @@ describe('shared provider credentials', () => {try {expect(gate.authorize(action).ok).toBe(false);expect(await executor.confirm(action)).toBe(false);- expect(asked).toHaveBeenCalledExactlyOnceWith(action);+ expect(asked).toHaveBeenCalledExactlyOnceWith(action, expect.any(AbortSignal));expect(gate.authorize(action).ok).toBe(false);} finally {await executor.close();@@ -794,7 +794,7 @@ describe('shared provider credentials', () => {const denied = await executor.callTool('Bash', { command: action.command });expect(denied.isError).toBe(true);expect(text(denied)).not.toContain('PRIVATE_FIXTURE=changed-target');- expect(asked).toHaveBeenCalledExactlyOnceWith(action);+ expect(asked).toHaveBeenCalledExactlyOnceWith(action, expect.any(AbortSignal));} finally {await executor.close();}@@ -820,7 +820,7 @@ describe('shared provider credentials', () => {gate.recordCredentialExemption(compound);try {expect(await executor.confirm(compound)).toBe(false);- expect(asked).toHaveBeenCalledExactlyOnceWith(compound);+ expect(asked).toHaveBeenCalledExactlyOnceWith(compound, expect.any(AbortSignal));expect(gate.authorize(compound).ok).toBe(false);expect(gate.authorize(ordinary).ok).toBe(false);} finally {@@ -980,7 +980,7 @@ describe('shared provider credentials', () => {else resolve(answer);expect(await Promise.all(pending)).toEqual([answer === true, false]);expect(confirm).toHaveBeenCalledTimes(2);- expect(confirm).toHaveBeenNthCalledWith(2, second);+ expect(confirm).toHaveBeenNthCalledWith(2, second, expect.any(AbortSignal));expect(executor.check(first).ok).toBe(answer === true);expect(executor.check(first).ok).toBe(false);expect(executor.check(second).ok).toBe(false);@@ -1036,7 +1036,7 @@ describe('shared provider credentials', () => {answers[0](true);expect(await pending[0]).toBe(true);await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(2));- expect(confirm).toHaveBeenNthCalledWith(2, third);+ expect(confirm).toHaveBeenNthCalledWith(2, third, expect.any(AbortSignal));answers[1](true);expect(await pending[2]).toBe(true);} finally {@@ -1058,7 +1058,7 @@ describe('shared provider credentials', () => {expect(confirm).toHaveBeenCalledTimes(1);abort.abort();await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(2));- expect(confirm).toHaveBeenNthCalledWith(2, second);+ expect(confirm).toHaveBeenNthCalledWith(2, second, expect.any(AbortSignal));// 已取消请求的卡片之后再回答,不建立任务授权。answers[0]('session');expect(await pending[0]).toBe(false);@@ -1146,24 +1146,34 @@ describe('shared provider credentials', () => {}});- it('does not grant credentials from a cancelled, closed or outdated confirmation', async () => {- for (const end of ['cancel', 'close', 'permission-change']) {- let answer!: (result: ExecutorConfirmation) => void;- const { executor, gate } = sharedExecutor('full', () => new Promise((resolve) => { answer = resolve; }));- const abort = new AbortController();- const action: ExecutorAction = { kind: 'read', path: path.join(project, '.env') };- const pending = executor.confirm(action, abort.signal);+ // provider-sharing §9:旧用例只在迟到回答后检查授权;补上取消必须立即关闭卡片并结束等待的时序(unit)。+ it.each(['cancel', 'close', 'permission-change'])('cancels the open confirmation before a late answer after %s', async (end) => {+ let answer!: (result: ExecutorConfirmation) => void;+ let confirmationSignal: AbortSignal | undefined;+ const { executor, gate } = sharedExecutor('full', (_action, signal) => {+ confirmationSignal = signal;+ return new Promise((resolve) => { answer = resolve; });+ });+ const abort = new AbortController();+ const action: ExecutorAction = { kind: 'read', path: path.join(project, '.env') };+ const pending = executor.confirm(action, abort.signal);+ try {if (end === 'cancel') abort.abort();else if (end === 'close') await executor.close();else {executor.setGateMode('normal');executor.setGateMode('full');}- answer('session');+ expect(confirmationSignal?.aborted).toBe(true);expect(await pending).toBe(false);+ answer('session');+ await Promise.resolve();expect(gate.needsCredentialConsent(action)).toBe(true);expect(gate.authorize(action).ok).toBe(false);+ } finally {+ answer(false);await executor.close();+ await pending;}});@@ -1257,7 +1267,7 @@ describe('shared provider credentials', () => {// 旧卡还没回答:切换权限档后的新请求不必等它。fresh = executor.confirm(production);await vi.waitFor(() => expect(asked).toHaveBeenCalledTimes(2));- expect(asked).toHaveBeenNthCalledWith(2, production);+ expect(asked).toHaveBeenNthCalledWith(2, production, expect.any(AbortSignal));// 旧卡之后再回答,不建立授权。answers[0]('session');expect(await stale).toBe(false);@@ -1312,7 +1322,7 @@ describe('shared provider credentials', () => {try {expect(await executor.confirm(git)).toBe(true);expect(asked).toHaveBeenCalledTimes(1);- expect(asked).toHaveBeenCalledWith(env);+ expect(asked).toHaveBeenCalledWith(env, expect.any(AbortSignal));answer(true);expect(await pending).toBe(true);} finally {diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsindex 6df014a3f7..c87358736d 100644--- a/apps/desktop/src/main/remote-agent/executor/executor.ts+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -66,7 +66,7 @@ export interface RemoteExecutorOptions {* 在本机弹确认卡问本机用户(供应商分享的受邀者任务):凭证类操作没有本机批准时用它补问,允许后* 默认只放行这一个操作;用户明确选择会话级允许后免除后续的分享凭证确认。缺省时直接拒绝。*/- confirm?(action: ExecutorAction): Promise<ExecutorConfirmation>;+ confirm?(action: ExecutorAction, signal: AbortSignal): Promise<ExecutorConfirmation>;/** 与 confirm 一起提供:git 查看内容、打出 git 配置的命令先在本机核实,读不到凭证时不弹卡。 */gitCredentials?: GitCredentialHistory;/**@@ -126,9 +126,8 @@ export class RemoteExecutor {private readonly writeHooks: FileWriteHooks;private closed = false;private permissionGeneration = 0;+ private credentialConfirmationAbort = new AbortController();private credentialConfirmationTail?: Promise<void>;- /** 当前占着确认排队位置的请求的放行函数。 */- private readonly credentialSlotReleases = new Set<() => void>();private readonly unwatchCredentialGrant?: () => void;constructor(private readonly opts: RemoteExecutorOptions) {@@ -151,25 +150,25 @@ export class RemoteExecutor {/** 本机任务的权限档变化时更新上限档位。 */setGateMode(mode: ExecutorGateMode): void {- this.permissionGeneration += 1;this.gate.setMode(mode);- this.releaseCredentialQueue();+ this.cancelPendingConfirmations();this.opts.credentialGrant?.forget();}/** 撤销分享凭证的任务授权:与权限档变化一样清掉授权,并作废等待中的确认。 */private revokeCredentialGrant(): void {- this.permissionGeneration += 1;this.gate.setMode(this.gate.getMode());- this.releaseCredentialQueue();+ this.cancelPendingConfirmations();}/**- * 等待中的确认已作废(权限档变化或授权撤销):放开它们占着的排队位置,之后的请求不必等旧卡;- * 旧卡之后的回答仍按 generation 丢弃。+ * 停止、权限变化或撤权时取消已显示和排队中的确认。停止本身不撤销先前有效的任务授权。*/- private releaseCredentialQueue(): void {- for (const release of [...this.credentialSlotReleases]) release();+ cancelPendingConfirmations(): void {+ this.permissionGeneration += 1;+ const previous = this.credentialConfirmationAbort;+ this.credentialConfirmationAbort = new AbortController();+ previous.abort();}/** 本机用户在确认卡上允许了一个操作。 */@@ -190,6 +189,9 @@ export class RemoteExecutor {*/async confirm(action: ExecutorAction, signal?: AbortSignal): Promise<boolean> {if (this.closed || signal?.aborted || !this.opts.confirm || !this.gate.needsCredentialConsent(action)) return false;+ signal = signal+ ? AbortSignal.any([signal, this.credentialConfirmationAbort.signal])+ : this.credentialConfirmationAbort.signal;const permissionGeneration = this.permissionGeneration;// 只有要核实的 git 命令才在弹卡前等核实结果;核实通过不弹卡,也不必排在其他确认卡后面。const gitCheck = this.gitReadsCheck(action, signal);@@ -209,7 +211,6 @@ export class RemoteExecutor {const settled = new Promise<void>((resolve) => { settle = resolve; });const slot = previous ? previous.then(() => settled) : settled;this.credentialConfirmationTail = slot;- this.credentialSlotReleases.add(settle);// 自己的请求取消后立即让出:还在排队就不再等(后面的请求仍等前一张卡);// 卡已弹出就不再挡住后面的请求,这张卡之后的回答会被丢弃。let onAbort: (() => void) | undefined;@@ -222,7 +223,10 @@ export class RemoteExecutor {if (this.closed || signal?.aborted || permissionGeneration !== this.permissionGeneration) return false;// 调用方仍会重新检查普通权限上限;这里只免除已授权的分享凭证确认。if (!this.gate.needsCredentialConsent(action)) return true;- const allowed = await this.opts.confirm(action).catch(() => false);+ const allowed = await Promise.race([+ this.opts.confirm(action, signal).catch(() => false),+ aborted.then(() => false as const),+ ]);// 等确认期间任务结束、请求被取消或权限已切换:不接受旧确认。if ((allowed !== true && allowed !== 'session') || this.closed || signal?.aborted|| permissionGeneration !== this.permissionGeneration) return false;@@ -235,7 +239,6 @@ export class RemoteExecutor {return true;} finally {if (onAbort) signal?.removeEventListener('abort', onAbort);- this.credentialSlotReleases.delete(settle);settle();void slot.then(() => {if (this.credentialConfirmationTail === slot) this.credentialConfirmationTail = undefined;@@ -263,6 +266,7 @@ export class RemoteExecutor {async close(): Promise<void> {if (this.closed) return;this.closed = true;+ this.cancelPendingConfirmations();this.unwatchCredentialGrant?.();await this.shell.close();}diff --git a/apps/desktop/src/main/remote-agent/host/tunnel.ts b/apps/desktop/src/main/remote-agent/host/tunnel.tsindex 422f7df953..18d614d8e8 100644--- a/apps/desktop/src/main/remote-agent/host/tunnel.ts+++ b/apps/desktop/src/main/remote-agent/host/tunnel.ts@@ -19,6 +19,23 @@ export const TUNNEL_MAX_BODY_BYTES = 48 * 1024 * 1024;const MAX_WS_CONNECTIONS = 16;/** 单条 WebSocket 消息上限(Codex exec-server 读写大文件时整段 base64 在一条消息里)。 */const MAX_WS_FRAME_BYTES = 48 * 1024 * 1024;+const MCP_KEEPALIVE_MS = 15_000;++/** 只识别本机执行器的单次工具调用及标准取消通知,不接管其他 MCP 服务。 */+function execMcpMessage(req: IncomingMessage, requestPath: string, body: Buffer): { kind: 'call' | 'cancel'; id: string | number } | undefined {+ if (req.method !== 'POST' || requestPath.split('?')[0] !== '/mcp/cindy_exec') return undefined;+ try {+ const message = JSON.parse(body.toString('utf8'));+ if (message?.jsonrpc !== '2.0') return undefined;+ if (message.method === 'tools/call' && (typeof message.id === 'string' || typeof message.id === 'number')) {+ return { kind: 'call', id: message.id };+ }+ const cancelledId = message.params?.requestId;+ if (message.id === undefined && message.method === 'notifications/cancelled'+ && (typeof cancelledId === 'string' || typeof cancelledId === 'number')) return { kind: 'cancel', id: cancelledId };+ } catch { /* 非法请求交回原路由处理。 */ }+ return undefined;+}export interface TunnelHttpRequest {method: string;@@ -111,6 +128,8 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnconst token = randomBytes(32).toString('base64url');const sockets = new Set<Socket>();const connections = new Map<string, WebSocket>();+ // 每个 run 独立;保留 MCP session 和 JSON-RPC id 的类型,不能取消其它并行调用。+ const pendingExecCalls = new Map<string, () => void>();let nextConn = 0;let closed = false;const activity = new TunnelLinkActivity();@@ -139,6 +158,54 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnif (!FORWARDED_HEADERS.has(name) || value === undefined) continue;headers.push([name, Array.isArray(value) ? value.join(', ') : value]);}+ const execMessage = execMcpMessage(req, requestPath, body);+ const callKey = execMessage ? JSON.stringify([req.headers['mcp-session-id'] ?? null, execMessage.id]) : undefined;+ if (execMessage?.kind === 'cancel') {+ // SDK 总超时/单次取消只发通知,不关闭 transport。复用原反向请求的取消信号,+ // 不新增跨端字段,也不关闭共享连接或重放工具操作。+ pendingExecCalls.get(callKey!)?.();+ res.writeHead(202).end();+ return;+ }+ if (callKey !== undefined && pendingExecCalls.has(callKey)) {+ res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({+ jsonrpc: '2.0', id: execMessage!.id, error: { code: -32600, message: 'Request ID is already in use.' },+ }));+ return;+ }+ const streamId = execMessage?.kind === 'call'+ && req.headers.accept?.split(',').some((part) => part.trim().split(';')[0] === 'text/event-stream')+ ? execMessage.id : undefined;+ let keepalive: ReturnType<typeof setInterval> | undefined;+ const streamMessage = (value: unknown) => res.end(`event: message\ndata: ${JSON.stringify(value)}\n\n`);+ const streamError = () => streamMessage({+ jsonrpc: '2.0', id: streamId,+ error: { code: -32603, message: 'The tool request could not be completed.' },+ });+ if (streamId !== undefined) {+ // Claude Code 的 MCP fetch 在首份 HTTP 响应前默认只等 60s。及时建立标准 SSE 响应,+ // 让等待用户确认与命令执行留在工具调用生命周期内,不改变工具执行超时,也不重放请求。+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });+ res.write(': waiting\n\n');+ keepalive = setInterval(() => {+ if (!res.destroyed && !res.writableNeedDrain) res.write(': waiting\n\n');+ }, MCP_KEEPALIVE_MS);+ keepalive.unref();+ }+ const release = () => {+ clearInterval(keepalive);+ if (callKey !== undefined && pendingExecCalls.get(callKey) === cancel) pendingExecCalls.delete(callKey);+ };+ const cancel = () => {+ abort.abort();+ release();+ if (res.destroyed || res.writableEnded) return;+ const cancelled = { jsonrpc: '2.0', id: execMessage!.id, error: { code: -32800, message: 'Request cancelled.' } };+ if (streamId !== undefined) streamMessage(cancelled);+ else res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(cancelled));+ };+ if (callKey !== undefined) pendingExecCalls.set(callKey, cancel);+ res.once('close', release);activity.httpStarted();try {const response = await handlers.http({@@ -147,11 +214,23 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnheaders,...(body.length ? { body } : {}),}, abort.signal);- if (res.destroyed) return;+ if (res.destroyed || res.writableEnded) return;+ if (streamId !== undefined) {+ if (response.status !== 200 || !response.body) streamError();+ else {+ try { streamMessage(JSON.parse(response.body.toString('utf8'))); }+ catch { streamError(); }+ }+ return;+ }res.writeHead(response.status, Object.fromEntries(response.headers));res.end(response.body);} catch (error) {- if (res.destroyed) return;+ if (res.destroyed || res.writableEnded) return;+ if (streamId !== undefined) {+ streamError();+ return;+ }// 错误消息/栈可能携带本机路径等信息,不原样回给隧道对端;按错误类别给固定文案。const raw = error instanceof Error ? error.message : String(error);const message = /aborted/i.test(raw)@@ -160,6 +239,7 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnres.writeHead(502, { 'content-type': 'application/json' });res.end(JSON.stringify({ error: { code: 'REMOTE_AGENT_TUNNEL', message } }));} finally {+ release();activity.httpFinished();}})();diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 5b7f605139..405ed81b9a 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -86,7 +86,7 @@ export interface PermissionModeState {export type SessionEventListener = (event: AgentEvent) => void;export type SessionStatusListener = (status: SessionStatus) => void;-export type InteractionRequestListener = (req: InteractionRequest) => Promise<InteractionDecision>;+export type InteractionRequestListener = (req: InteractionRequest, signal?: AbortSignal) => Promise<InteractionDecision>;/*** turn 零事件看门狗阈值(ms)。turn 在跑、却连续这么久**没有产品进展**,视为整条@@ -635,7 +635,7 @@ export class Session {// 注入 InteractionResolver 到底层 handle, 转发到 host 维护的 listener。// 没接 listener 时按 kind 给出安全默认: 都视作 deny(host 必须接 listener 才能交互)。- this.handle.setInteractionResolver((req) => this.runHostInteraction(req, async () => {+ this.handle.setInteractionResolver((req, signal) => this.runHostInteraction(req, async () => {if (!this.interactionListener) {this.logger.warn('interaction request received but no listener attached, denying', { kind: req.kind, requestId: req.requestId });if (req.kind === 'ask_user_question') {@@ -646,7 +646,7 @@ export class Session {}return { kind: req.kind, behavior: 'deny', reason: 'no_listener_attached' } as InteractionDecision;}- return await this.interactionListener(req);+ return await (signal ? this.interactionListener(req, signal) : this.interactionListener(req));}));}diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex 5724a6471e..6678f04afb 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -380,7 +380,8 @@ export type InteractionDecision =dismissed?: boolean;};-export type InteractionResolver = (req: InteractionRequest) => Promise<InteractionDecision>;+/** signal 仅在本进程传递,不进入请求载荷或跨端协议。 */+export type InteractionResolver = (req: InteractionRequest, signal?: AbortSignal) => Promise<InteractionDecision>;/*** pending interaction 被自动 resolve 时, agent emit 此事件让 UI 关闭对话框。