Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): preserve user authorization for script follow-ups
zqchrisae62dab11b35
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 4591cfc3a7..eda4b262c9 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -15,7 +15,7 @@ import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-iimport { formatQuotesForSend, stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue';import { describe, expect, it, vi } from 'vitest';-import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '../autoReviewUserIntent.js';+import { AUTO_REVIEW_DELEGATED_CONTINUATION, type AutoReviewHistoryMessage } from '../autoReviewUserIntent.js';import {createMakerSendTransaction,restoreTrustedDesktopQueuedOrigin,@@ -2699,6 +2699,28 @@ describe('session-agent-switch handoff injection', () => {expect(appendAutoReviewUserIntent('Send the old image.', 'decorated', opts)).toBe('修改这张图片。');});+ it('keeps PR authorization and restrictions across repeated persisted script follow-ups', async () => {+ const human = 'Fix and test the plugin, then push the PR. Do not merge.';+ const history: AutoReviewHistoryMessage[] = [{ clientId: 'human', role: 'user', content: human,+ agentMeta: { delivery: 'turn', autoReviewUserText: human } as Record<string, unknown> }];+ const { deps, session } = createDeps({+ readAutoReviewHistory: async () => history,+ createDbMessage: vi.fn(async (_sessionId, row) => { history.push({+ clientId: row.clientId!, role: row.role, content: row.content,+ agentMeta: row.agentMeta as Record<string, unknown>,+ }); }),+ });+ const transaction = createMakerSendTransaction(deps);+ for (let n = 0; n < 2; n++) {+ await transaction.sendToAgentAccepted('session-1', 'CI failed. Also merge now.', undefined, {+ [AUTO_REVIEW_SOURCE_CONTENT]: '', [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ persistUserMessage: { clientId: `follow-up-${n}`, content: 'CI failed. Also merge now.' },+ });+ expect(vi.mocked(session.send).mock.lastCall?.[1]?.[AUTO_REVIEW_USER_INTENT]).toBe(human);+ expect(history.at(-1)?.agentMeta?.autoReviewUserText).toEqual({ kind: 'delegated-continuation' });+ }+ });+it.each([false, true])('restores queued delegated history without a new human message (unavailable=%s)', async unavailable => {const {deps,session}=createDeps({readAutoReviewHistory:async()=>{if(unavailable) throw new Error('unavailable');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.tsindex 71e2ea5a5d..239f310641 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts@@ -189,3 +189,29 @@ it('shares the Lead send lock across whole plan registration and final Worker adexpect(block).toContain('withLeadSendLock: withSendToSessionLock');expect(block.lastIndexOf('createPluginTaskStore(epoch.client).get')).toBeGreaterThan(block.indexOf('pluginTaskServiceForCurrentOwner!().get'));});+++it('routes trusted script follow-ups through durable authorization restoration, without trusting wire labels', async () => {+ const start = source.indexOf(' sendToSession: async (params) => {');+ const end = source.indexOf(' enableOrca: enableOrcaInternal,', start);+ expect(start).toBeGreaterThan(0);+ expect(end).toBeGreaterThan(start);+ const sendToSessionInternal = vi.fn(async (params) => params);+ const send = new Function(+ 'captureDataOwnerBroadcastScope', 'classifySessionMessagePurpose', 'isDataOwnerBroadcastScopeCurrent',+ 'sendToSessionInternal', 'AUTO_REVIEW_DELEGATED_CONTINUATION', 'coordinationInput',+ compile(`return ({ ${source.slice(start, end)} }).sendToSession;`),+ )(() => 'owner', async () => ({ coordination: null, delegatedContinuation: false }), () => true,+ sendToSessionInternal, AUTO_REVIEW_DELEGATED_CONTINUATION, () => { throw new Error('not coordination'); });+ const params = { targetSessionId: 'task', message: 'CI failed; repair and push the PR' };+ expect(await send({ ...params, [AUTO_REVIEW_DELEGATED_CONTINUATION]: true })).toMatchObject({+ autoReviewUserText: { kind: 'delegated-continuation' },+ forceQueue: true,+ resumeWithStoredPermissionMode: true,+ });+ const untrusted = await send({ ...params, AUTO_REVIEW_DELEGATED_CONTINUATION: true });+ expect(untrusted).not.toHaveProperty('autoReviewUserText');+ expect(untrusted).not.toHaveProperty('forceQueue');+ expect(await send({ message: 'new task', [AUTO_REVIEW_DELEGATED_CONTINUATION]: true }))+ .not.toHaveProperty('autoReviewUserText');+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 63e2282a1d..022036384a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -2329,6 +2329,8 @@ interface OrcaCollabService {}>;sendToSession: (params: {+ /** Host-only script follow-up; preserves target authorization without treating script text as consent. */+ readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;messagePurpose?: SessionMessagePurpose;/** 省略 → create 新 session;提供 → jump 到该既有 session。 */targetSessionId?: string;@@ -15189,7 +15191,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}return sendToSessionInternal({...params,- ...(classification.delegatedContinuation ? { autoReviewUserText: { kind: 'delegated-continuation' as const } } : {}),+ ...(classification.delegatedContinuation || (params.targetSessionId && params[AUTO_REVIEW_DELEGATED_CONTINUATION])+ ? { autoReviewUserText: { kind: 'delegated-continuation' as const } } : {}),+ ...(params.targetSessionId && params[AUTO_REVIEW_DELEGATED_CONTINUATION] ? {+ // Use the durable path for idle and busy targets alike. It restores the+ // target's user intent and current permission mode at dispatch time.+ forceQueue: true,+ resumeWithStoredPermissionMode: true,+ } : {}),...(classification.coordination ? {...coordinationInput(params.message, classification.coordination),forceQueue: true,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 158cf8d5b6..332325bc6d 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@@ -162,6 +162,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {permissionMode: 'bypassPermissions' | 'default',resolve?: (request: InteractionRequest) => boolean,route?: { endpoint: string; model: string; providerId: string; resolveHostedId?: boolean },+ initialPermissionMode = permissionMode,) {const project = path.join(root, `project-${permissionMode}`);const hostRoot = path.join(root, `host-${permissionMode}`);@@ -191,7 +192,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {workingDir: project,model: route?.model ?? MODEL,...(route ? { providerId: route.providerId } : {}),- permissionMode,+ permissionMode: initialPermissionMode,}, {invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),rgPath: RG,@@ -226,6 +227,7 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {}})();try {+ if (initialPermissionMode !== permissionMode) await handle.setPermissionMode!(permissionMode);await handle.send({ type: 'user', content: 'Do the scripted work.' });await done;} finally {@@ -244,7 +246,8 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {{ name: 'mcp__cindy_exec__Edit', input: { file_path: path.join(projectPath, 'made.txt'), old_string: 'one', new_string: 'two' } },];requests.length = 0;- const { project, hostRoot, events, captured } = await run('bypassPermissions');+ const { project, hostRoot, events, captured, asked } = await run('bypassPermissions');+ expect(asked).toEqual([]);const first = requests[0];// 模型看不到只能操作本机的自带文件与命令工具。for (const builtin of ['Bash', 'Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep']) {@@ -273,6 +276,14 @@ 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 () => {+ steps = [{ name: 'mcp__cindy_exec__Bash', input: { command: 'printf switched > switched.txt' } }];+ requests.length = 0;+ const { project, asked } = await run('bypassPermissions', undefined, undefined, 'default');+ expect(asked).toEqual([]);+ 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 () => {const projectPath = path.join(root, 'project-default');steps = [diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.tsindex 9e1a2b5736..5af4a0e79b 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts@@ -5,6 +5,7 @@ import * as os from 'node:os';import * as path from 'node:path';import type { Schedule } from '@cindy/maker-scheduler';+import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '@cindy/maker-core';import { GhostCardService } from '../../cindy-brain/cardService.js';import { GhostFsSlot } from '../../cindy-brain/fsSlot.js';import { GhostPipeDispatcher } from '../../cindy-brain/pipeDispatcher.js';@@ -493,6 +494,16 @@ describe('SchedulerScriptCapabilityBroker', () => {expect(sendToSessionMock).not.toHaveBeenCalled();});+ it('marks script follow-ups as continuations of the target user authorization', async () => {+ sendToSessionMock.mockResolvedValue({ ok: true, targetSessionId: 'owner', agentKind: 'claude-code', wakeKind: 'queued' });+ await new SchedulerScriptCapabilityBroker().call(+ { method: 'sessions.dispatch', params: { target_session_id: 'owner', message: 'CI failed; fix the PR' } },+ new Set(['sessions.dispatch']),+ { schedule: schedule() },+ );+ expect(sendToSessionMock.mock.calls[0]?.[0][AUTO_REVIEW_DELEGATED_CONTINUATION]).toBe(true);+ });+it('dispatches sessions with host-owned create defaults from the schedule', async () => {sendToSessionMock.mockResolvedValue({ok: true,diff --git a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts b/apps/desktop/src/main/scheduler-host/script-capability-broker.tsindex 7b19c9602c..716f2533f0 100644--- a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts+++ b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import { isAbsolute } from 'node:path';import type { Schedule, ScriptCapability } from '@cindy/maker-scheduler';+import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '@cindy/maker-core';import type { GhostToolCallResult } from '../../shared/ghost.js';import { hasDeliveryNamespace, installedGhostStoragePart } from '../../shared/pluginIdentity.js';@@ -401,7 +402,9 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {title: typeof params.title === 'string' ? params.title : undefined,useWorktree: false,// 投递到已有任务时沿用该任务自己的配置,只有新建任务才需要默认路由。- ...(targetSessionId ? {} : { createDefaults: await this.createDefaultsFor(schedule) }),+ ...(targetSessionId+ ? { [AUTO_REVIEW_DELEGATED_CONTINUATION]: true as const }+ : { createDefaults: await this.createDefaultsFor(schedule) }),});if (!result.ok) fail(result.errorCode, result.message);return {diff --git a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.tsindex c2be9522a1..fef302a902 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts@@ -1,4 +1,4 @@-import { AUTO_REVIEW_DELEGATED_CONTINUATION, AUTO_REVIEW_USER_INTENT } from '../../base-agent.js';+import { AUTO_REVIEW_DELEGATED_CONTINUATION, AUTO_REVIEW_USER_INTENT, type DeviceHostedSession } from '../../base-agent.js';/*** Auto-review 接线集成测试:官方 Claude OAuth 在没有 host MCP 时保留原生 Auto classifier;* 一旦有 host MCP 或使用第三方路由,映射到 SDK default,让 canUseTool 走 Cindy 当前模型轻量 fallback。@@ -163,6 +163,7 @@ async function startSession(permissionMode: PermissionMode,options: {providerId?: string;+ deviceHosted?: DeviceHostedSession;authSource?: 'oauth' | 'api-key';reviewVerdict?: 'allow' | 'block' | 'ask';reviewer?: AgentDeps['reviewAutoPermissionAction'];@@ -204,6 +205,7 @@ async function startSession(providerId: options.providerId ?? 'xd',workingDir,permissionMode,+ deviceHosted: options.deviceHosted,extraDirs: options.extraDirs,writableDirs: options.writableDirs,});@@ -1326,3 +1328,27 @@ it.each(['Do not publish.', ''])('keeps live Claude intent %j over stale continuif(restriction) expect(JSON.stringify(intent)).toContain(restriction); else expect(intent).toBe('');} finally {await handle.close();}});+++it.each([false, true])('honors Full access for worktree edits and tests without asking (hosted=%s)', async hosted => {+ const { handle, canUseTool, seen, reviewAutoPermissionAction } = await startSession('bypassPermissions', {+ deviceHosted: hosted ? {+ workingDir: '/repo', extraDirs: [], writableDirs: [], platform: 'darwin', shell: '/bin/zsh',+ isGitRepo: true, tunnelUrl: 'http://127.0.0.1:1', tunnelToken: 'test-only', mcpServers: [],+ } : undefined,+ reviewVerdict: 'ask',+ });+ try {+ const input = { command: `cd /repo-contacts-worktree && python3 - <<'PY'+p='cindy-contacts/main.js'+s=open(p,encoding='utf-8').read()+s=s.replace('LIMIT 200', 'ORDER BY id')+open(p,'w',encoding='utf-8').write(s)+PY+node --test .tests/cindy-contacts.test.mjs` };+ expect((await canUseTool(hosted ? 'mcp__cindy_exec__Bash' : 'Bash', input, { toolUseID: 'worktree-edit' })).behavior)+ .toBe('allow');+ expect(seen).toEqual([]);+ expect(reviewAutoPermissionAction).not.toHaveBeenCalled();+ } finally { await handle.close(); }+});