Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 排队子代理并发审批,避免先到的请求被覆盖 (#4694)
Yunjin Zhangec483055efe3
diff --git a/docs/pi-subagent-parity-plan.md b/docs/pi-subagent-parity-plan.mdindex 86c7e57425..614ed70367 100644--- a/docs/pi-subagent-parity-plan.md+++ b/docs/pi-subagent-parity-plan.md@@ -78,6 +78,10 @@ exit writes the same atomic stop controls synchronously before process exit.10. Device-link and SSH controls must execute on the data-owning device. A localrenderer must not present a stop action that targets an unreachable remotesession.+11. Concurrent child approval requests are queued per child, oldest first, and+ answered by request id. A newer request never displaces an earlier+ unanswered one; the published status exposes only the oldest pending+ request while the runner holds the rest of the queue.## Final acceptance checklistdiff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.tsindex a9a8ae46e4..2f47017337 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts@@ -90,7 +90,7 @@ function sharedRunnerFile(): Promise<string> {*/async function readCommandsIfPresent(file: string,-): Promise<Array<{ type?: string; message?: string }> | null> {+): Promise<Array<{ type?: string; message?: string; id?: string }> | null> {let text: string;try {text = await readFile(file, 'utf8');@@ -100,7 +100,7 @@ async function readCommandsIfPresent(}const trimmed = text.trim();if (!trimmed) return null;- return trimmed.split('\n').map((line) => JSON.parse(line) as { type?: string; message?: string });+ return trimmed.split('\n').map((line) => JSON.parse(line) as { type?: string; message?: string; id?: string });}/**@@ -218,6 +218,13 @@ async function makeFixture(options: {outputText?: string;chain?: boolean;approval?: boolean;+ /**+ * Emit several approval requests from one prompt, the way a turn whose+ * parallel tool calls each ask before running does. The fake child only+ * settles once every id has been answered, so a runner that drops one leaves+ * the fixture running instead of turning the assertion into a timeout.+ */+ approvalIds?: string[];approvalMethod?: 'confirm' | 'input';modelError?: boolean;retryThenSucceed?: boolean;@@ -315,6 +322,7 @@ setTimeout(() => process.exit(0), 60000).unref();await writeFile(permissionFile, '{"mode":"ask"}\n');const fixtureOutput = JSON.stringify(options.outputText ?? 'fixture result');const approvalMethod = options.approvalMethod ?? 'confirm';+ const approvalIds = options.approvalIds ?? (options.approval ? ['approval-1'] : []);const fixtureLifecycle = options.outputThenHang? `process.stdout.write(JSON.stringify({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: ${fixtureOutput} }], usage: { input: 3, output: 2, cost: { total: 0.01 } } } }) + '\\n');`: options.hang@@ -389,6 +397,9 @@ function waitForPidCount(count) {}}let buffer = '';+const expectedApprovals = ${JSON.stringify(approvalIds)};+const answeredApprovals = new Set();+let allowedApprovals = 0;process.stdin.setEncoding('utf8');process.stdin.on('data', (chunk) => {buffer += chunk;@@ -403,21 +414,27 @@ process.stdin.on('data', (chunk) => {if (command.type === 'prompt') {fs.appendFileSync(process.env.CINDY_TEST_PI_PROMPTS, JSON.stringify(command.message) + '\\n');process.stdout.write(JSON.stringify({ type: 'response', command: 'prompt', success: true }) + '\\n');- ${options.approval- ? `process.stdout.write(JSON.stringify({ type: 'extension_ui_request', id: 'approval-1', method: ${JSON.stringify(approvalMethod)}, title: 'cindy:permission', ${approvalMethod === 'input' ? 'placeholder' : 'message'}: JSON.stringify({ toolName: 'write', input: { path: 'a.txt' } }) }) + '\\n');`+ ${approvalIds.length > 0+ ? `for (const id of expectedApprovals) {+ process.stdout.write(JSON.stringify({ type: 'extension_ui_request', id, method: ${JSON.stringify(approvalMethod)}, title: 'cindy:permission', ${approvalMethod === 'input' ? 'placeholder' : 'message'}: JSON.stringify({ toolName: 'write', input: { path: 'a.txt' } }) }) + '\\n');+ }`: `${options.hangOnMessage ? `if (command.message !== ${JSON.stringify(options.hangOnMessage)}) {` : ''}${options.gateFinishOnPidCount ? `waitForPidCount(${options.gateFinishOnPidCount});` : ''}process.stdout.write(JSON.stringify({ type: 'tool_execution_start', toolName: 'read' }) + '\\n');${fixtureLifecycle}${options.hangOnMessage ? '}' : ''}`}}- if (command.type === 'extension_ui_response' && command.id === 'approval-1') {- if (command.confirmed || command.value === 'allow') {- process.stdout.write(JSON.stringify({ type: 'tool_execution_start', toolName: 'write' }) + '\\n');- process.stdout.write(JSON.stringify({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: ${fixtureOutput} }], usage: { input: 3, output: 2, cost: { total: 0.01 } } } }) + '\\n');+ if (command.type === 'extension_ui_response' && expectedApprovals.includes(command.id)) {+ answeredApprovals.add(command.id);+ if (command.confirmed || command.value === 'allow') allowedApprovals += 1;+ if (answeredApprovals.size === expectedApprovals.length) {+ if (allowedApprovals === expectedApprovals.length) {+ process.stdout.write(JSON.stringify({ type: 'tool_execution_start', toolName: 'write' }) + '\\n');+ process.stdout.write(JSON.stringify({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: ${fixtureOutput} }], usage: { input: 3, output: 2, cost: { total: 0.01 } } } }) + '\\n');+ }+ process.stdout.write(JSON.stringify({ type: 'agent_end' }) + '\\n');+ process.stdout.write(JSON.stringify({ type: 'agent_settled' }) + '\\n');}- process.stdout.write(JSON.stringify({ type: 'agent_end' }) + '\\n');- process.stdout.write(JSON.stringify({ type: 'agent_settled' }) + '\\n');}}});@@ -1309,6 +1326,95 @@ describe('Cindy durable PI Subagent runner', () => {await waitForClose(fixture.child, fixture.stderr);});+ it('queues concurrent child approvals instead of overwriting the earlier request', async () => {+ // Parallel tool calls raise their approvals in the same turn. With a single+ // replacement slot the second request displaced the first, the Host only+ // ever saw the second, and the child waited forever on the first: a live+ // run sat with zero CPU and a frozen transcript for fifty minutes. Every+ // request must stay answerable, oldest first.+ const fixture = await makeFixture({ approvalIds: ['approval-1', 'approval-2'] });+ const pending = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.tasks[0]?.pendingApproval ? run : null;+ });+ expect(pending.tasks[0]?.pendingApproval?.id).toBe('approval-1');++ await expect(controlPiSubagentRuns(fixture.root, 'tool-fixture', 'approval', {+ childId: pending.tasks[0]?.childId,+ approvalId: 'approval-1',+ confirmed: true,+ })).resolves.toBe(1);++ const second = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.tasks[0]?.pendingApproval?.id === 'approval-2' ? run : null;+ });+ await expect(controlPiSubagentRuns(fixture.root, 'tool-fixture', 'approval', {+ childId: second.tasks[0]?.childId,+ approvalId: 'approval-2',+ confirmed: true,+ })).resolves.toBe(1);++ const completed = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.state === 'completed' ? run : null;+ });+ expect(completed.tasks[0]?.output).toBe('fixture result');+ const commands = (await readCommandsIfPresent(fixture.commandsFile)) ?? [];+ expect(commands+ .filter((command) => command.type === 'extension_ui_response')+ .map((command) => command.id))+ .toEqual(['approval-1', 'approval-2']);+ await waitForClose(fixture.child, fixture.stderr);+ });++ it('accepts an answer for a queued request that is no longer the published head', async () => {+ // Two surfaces can read the same status (a second Desktop instance sharing+ // userData, or a status read that raced the previous answer) and answer+ // different ids. Refusing the non-head answer because the published head+ // moved on would strand a request the other surface already recorded as+ // handed over. Matching by id anywhere in the queue keeps it deliverable;+ // a control for an id that is not pending stays refused, so replays cannot+ // answer the same request twice.+ const fixture = await makeFixture({ approvalIds: ['approval-1', 'approval-2'] });+ const pending = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.tasks[0]?.pendingApproval?.id === 'approval-1' ? run : null;+ });+ // Straight into the mailbox: `controlPiSubagentRuns` filters by the+ // published head, which is the very restriction this case exists to test+ // beyond.+ await publishControlsAtomically(fixture.runDir, [+ {+ requestedAt: 1,+ action: 'approval',+ childId: pending.tasks[0]?.childId,+ approvalId: 'approval-2',+ confirmed: true,+ },+ ]);++ // approval-1 is still the published head, and approval-2 is gone from the+ // queue rather than waiting to be asked again.+ await expect(controlPiSubagentRuns(fixture.root, 'tool-fixture', 'approval', {+ childId: pending.tasks[0]?.childId,+ approvalId: 'approval-1',+ confirmed: true,+ })).resolves.toBe(1);+ const completed = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.state === 'completed' ? run : null;+ });+ expect(completed.tasks[0]?.output).toBe('fixture result');+ const commands = (await readCommandsIfPresent(fixture.commandsFile)) ?? [];+ expect(commands+ .filter((command) => command.type === 'extension_ui_response')+ .map((command) => command.id)+ .sort())+ .toEqual(['approval-1', 'approval-2']);+ await waitForClose(fixture.child, fixture.stderr);+ });+it('fails closed at the run timeout when no host approval resolver ever responds', async () => {const fixture = await makeFixture({ approval: true, timeoutMs: 200 });const failed = await waitFor(async () => {diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.tsindex 02fefbb41e..6c54c5262d 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts@@ -278,7 +278,13 @@ function main() {output: '',outputTruncated: false,error: undefined,- pendingApproval: undefined,+ // Approval requests this child is still waiting on, oldest first. The+ // status projection publishes only the head (the Host protocol stays one+ // request at a time), but every entry here must be answered: a newer+ // request must never displace an earlier unanswered one. That overwrite+ // is exactly how a child used to wait forever on its first parallel tool+ // call while the Host only ever saw the second.+ pendingApprovals: [],pendingControls: [],stopRequested: false,startedAt: undefined,@@ -370,7 +376,10 @@ function main() {),outputTruncated: task.outputTruncated || undefined,error: task.error,- pendingApproval: task.pendingApproval,+ // Only the oldest unanswered request is published so the status+ // schema and every consumer stay unchanged; the runner holds the rest+ // of the queue and promotes the next entry as answers arrive.+ pendingApproval: task.pendingApprovals.length > 0 ? task.pendingApprovals[0] : undefined,startedAt: task.startedAt,endedAt: task.endedAt,};@@ -552,7 +561,15 @@ function main() {let accepted = false;for (const task of selected) {if (state.stopRequested || task.stopRequested) continue;- if (!task.pendingApproval || task.pendingApproval.id !== control.approvalId) continue;+ // Match by id anywhere in the queue, not only at the head: a second+ // writer (another Desktop instance sharing userData, or a status read+ // that raced the previous answer) may answer a request that is still+ // pending but no longer first. An id that is not pending at all stays+ // refused, so a replayed control cannot deliver twice.+ const pendingIndex = task.pendingApprovals.findIndex(function (pending) {+ return pending.id === control.approvalId;+ });+ if (pendingIndex < 0) continue;const delivered = send(task, {type: 'extension_ui_response',id: control.approvalId,@@ -562,7 +579,7 @@ function main() {});if (delivered) {accepted = true;- task.pendingApproval = undefined;+ task.pendingApprovals.splice(pendingIndex, 1);}}scheduleStatus();@@ -833,7 +850,7 @@ function main() {task.child = undefined;task.stdin = undefined;task.inputClosed = true;- task.pendingApproval = undefined;+ task.pendingApprovals = [];task.endedAt = Date.now();if (state.stopRequested || task.stopRequested) {task.status = 'stopped';@@ -869,13 +886,23 @@ function main() {}safeAppendTranscript(state, { type: 'cindy.subagent.child_event', at: Date.now(), childId: task.childId, event: event });if (event.type === 'extension_ui_request') {- task.pendingApproval = {+ const pending = {id: typeof event.id === 'string' ? event.id : 'approval-' + randomUUID(),method: typeof event.method === 'string' ? event.method : 'confirm',title: typeof event.title === 'string' ? event.title.slice(0, 500) : undefined,message: typeof event.message === 'string' ? event.message.slice(0, 32000) : undefined,placeholder: typeof event.placeholder === 'string' ? event.placeholder.slice(0, 32000) : undefined,};+ // Parallel tool calls raise their approvals in the same turn, so a+ // single replacement slot silently orphaned every request but the+ // last. Queue them instead; the child is blocked on all of them.+ // A repeated id is a restatement of one request, so refresh its+ // payload rather than queueing a second response for it.+ const existing = task.pendingApprovals.findIndex(function (entry) {+ return entry.id === pending.id;+ });+ if (existing >= 0) task.pendingApprovals[existing] = pending;+ else task.pendingApprovals.push(pending);scheduleStatus();return;}@@ -1126,7 +1153,7 @@ function main() {task.child = undefined;task.stdin = undefined;task.inputClosed = true;- task.pendingApproval = undefined;+ task.pendingApprovals = [];if (task.status === 'running' || task.status === 'queued') {task.status = state.stopRequested || task.stopRequested ? 'stopped' : 'failed';task.error = task.error || reason;