Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): preserve admitted delegation input delivery after source turn ends

lvnianef5b3db03441
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 1ba4966fb9..fa29c3a96e 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -4493,12 +4493,16 @@ describe('Bot Session task end-to-end runtime', () => {
agentKind: string;
}
- async function runOwnerAction<T>(tool: string, current: () => boolean, operation: () => Promise<T>): Promise<T> {
+ async function runOwnerAction<T>(tool: string, current: () => boolean, operation: () => Promise<T>, deliveryCurrent?: () => boolean): Promise<T> {
const check = () => { if (!current()) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED'); };
const decision = await admitTaskAction({
sessionId: 'session-1', server: 'cindy_helper', tool, args: {},
}, { key: 'input', ownerInput: true, delegated: false,
- assertCurrent: async () => check(), assertCurrentSync: check });
+ assertCurrent: async () => check(), assertCurrentSync: check,
+ ...(deliveryCurrent ? { assertDeliveryCurrent: async () => {
+ if (!deliveryCurrent()) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ } } : {}),
+ });
if (!decision.ok || !decision.run) throw new Error('Expected admission');
return decision.run(operation);
}
@@ -5916,7 +5920,9 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { read.mockRestore(); mkdir.mockRestore(); release(); runtime.dispose(); }
});
- it.each(['valid', 'revoked', 'ended', 'action-revoked'] as const)('cancels delegation input at the actual host accepted adapter: %s', async condition => {
+ // The adapter must retain real revocation and the legacy guard fallback,
+ // while normal source-turn completion alone must not cancel an admitted input.
+ it.each(['valid', 'revoked', 'ended', 'action-revoked', 'source-ended', 'delivery-revoked'] as const)('cancels delegation input at the actual host accepted adapter: %s', async condition => {
await seedPair(); seedGroupLane();
let draining = false;
const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',
@@ -5939,13 +5945,15 @@ describe('Bot Session task end-to-end runtime', () => {
const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Accepted boundary fixture.' });
if (!task.ok) throw new Error(task.message);
armed = true;
- const send = () => runtime.delegation.messageSessionTask(condition === 'action-revoked' ? 'session-1' : 'group-lane', task.delegationId, { kind: 'message', text: 'Follow-up input.' });
- await (condition === 'action-revoked' ? runOwnerAction('message_session_task', () => !draining, send) : send());
+ const ownerAction = ['action-revoked', 'source-ended', 'delivery-revoked'].includes(condition);
+ const send = () => runtime.delegation.messageSessionTask(ownerAction ? 'session-1' : 'group-lane', task.delegationId, { kind: 'message', text: 'Follow-up input.' });
+ await (ownerAction ? runOwnerAction('message_session_task', () => condition === 'delivery-revoked' || !draining, send,
+ condition === 'source-ended' ? () => true : condition === 'delivery-revoked' ? () => !draining : undefined) : send());
expect(input?.onAccepted).toBeTypeOf('function');
const vendor = vi.fn();
draining = true;
const drain = async () => { await runAcceptedCallback(input!.onAccepted, input!.targetSessionId, input!.clientId!, { warn: vi.fn() }); vendor(); };
- if (condition === 'valid') { await drain(); expect(vendor).toHaveBeenCalledOnce(); }
+ if (condition === 'valid' || condition === 'source-ended') { await drain(); expect(vendor).toHaveBeenCalledOnce(); }
else { await expect(drain()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled); expect(vendor).not.toHaveBeenCalled(); }
} finally { release(); runtime.dispose(); }
});
@@ -7590,6 +7598,44 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { runtime.dispose(); }
});
+ /**
+ * 测试价值:messageSessionTask → 真输入协调器 → onAccepted → SQLite 执行回执。
+ * Bug:已准入补充排队期间发起轮结束,旧 onAccepted 误用精确输入检查而拒绝续接。
+ * 缺口:既有队列用例没有绑定发起轮授权;仅 bindTaskActionInput 不能覆盖服务回调。
+ * 最小输入:忙碌子任务 + 一条已准入补充 + 发起 input 换新;unit,模型进程为替身。
+ */
+ it('delivers an admitted supplement after its source input changes without admitting a new mutation', async () => {
+ await seedPair();
+ let execution = { instanceId: 'native', generation: 1 };
+ let sourceCurrent = true;
+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(), readSessionExecution: () => execution });
+ const request = { sessionId: 'session-1', server: 'cindy_helper' as const, tool: 'message_session_task', args: {} };
+ const check = () => { if (!sourceCurrent) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED'); };
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });
+ if (!task.ok) throw new Error('missing task');
+ const scope = { key: 'original-input', ownerInput: true, delegated: false,
+ assertCurrent: async () => check(), assertCurrentSync: check, assertDeliveryCurrent: async () => {} };
+ const decision = await admitTaskAction(request, scope);
+ if (!decision.ok || !decision.run) throw new Error('missing admission');
+ await expect(decision.run(() => runtime.delegation.messageSessionTask('session-1', task.delegationId,
+ { kind: 'message', text: 'Already approved supplement.' }))).resolves.toMatchObject({ ok: true });
+ expect(runtime.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue).toHaveLength(1);
+ sourceCurrent = false;
+ // A new invocation cannot borrow the accepted input's delivery authority.
+ expect(await admitTaskAction(request, scope)).toMatchObject({ ok: false, errorCode: 'TASK_ACTION_AUTHORIZATION_EXPIRED' });
+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,
+ resultText: 'Original result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });
+ execution = { instanceId: 'native', generation: 2 };
+ await runtime.settleChild(task.childSessionId, 'Original turn ended.');
+ await vi.waitFor(() => expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(2));
+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,
+ resultText: 'Supplement result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });
+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))
+ .toEqual({ status: 'completed', result_summary: 'Supplement result.' });
+ } finally { runtime.dispose(); }
+ });
+
it('keeps a supplement queued after an empty terminal snapshot tracked until its result', async () => {
await seedPair();
let execution = { instanceId: 'native', generation: 1 };
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
index aaada52385..1a1c30c9d1 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
@@ -24,6 +24,7 @@ import {
ORCA_TASK_ACTION_TOOLS,
captureTaskActionSyncGuard,
captureTaskActionGuard,
+ captureTaskActionDeliveryGuard,
} from '../taskActionAuthorization.js';
function fixture(ownerInput = false, delegated = false) {
@@ -259,7 +260,8 @@ function desktopFixture(kind: 'private' | 'group' | 'automatic' = 'group') {
? rows.team
? [rows.team]
: []
- : [caller],
+ // SQL reads return value snapshots, not a shared mutable row.
+ : [{ ...caller }],
};
return query;
},
@@ -674,6 +676,28 @@ describe('Desktop owner input task actions', () => {
// Review regressions: caller identity must not erase scoped delegation or mint it.
// Existing owner-input cases did not exercise automatic continuations. Unit tier.
describe('Existing execution authority', () => {
+ // Regression: delegation onAccepted must use the Host delivery scope after
+ // source-input rollover. Prior queue-binding tests did not capture this guard.
+ // Minimum: one owner-admitted call + new input key; unit, no real account/IO.
+ it.each(['source-only', 'cleared', 'deleted', 'bot-paused', 'archived'] as const)
+ ('retains delivery scope across source-input rollover while rejecting %s revocation', async changed => {
+ const h = desktopFixture('private');
+ const decision = await h.authorize(call('message_session_task'));
+ if (!decision.ok || !decision.run) throw new Error('missing admission');
+ const guards = await decision.run(async () => ({
+ mutation: captureTaskActionGuard()!, delivery: captureTaskActionDeliveryGuard()!,
+ }));
+ h.activeInput.key = 'next-owner-input';
+ await expect(guards.mutation()).rejects.toThrow('AUTHORIZATION_EXPIRED');
+ if (changed === 'cleared') Object.assign(h.caller, { clearedAt: 1 });
+ if (changed === 'deleted') h.caller.status = 'deleted';
+ if (changed === 'bot-paused') h.caller.botStatus = 'paused';
+ if (changed === 'archived') Object.assign(h.caller, { archivedAt: 1 });
+ if (changed === 'source-only') await expect(guards.delivery()).resolves.toBeUndefined();
+ else await expect(guards.delivery()).rejects.toThrow('AUTHORIZATION_EXPIRED');
+ expect(h.confirm).not.toHaveBeenCalled();
+ });
+
it('keeps delegated work independent of follow-up enablement, but respects pause/revocation', async () => {
const h = desktopFixture('automatic');
const grant = {
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 734cd7794f..8ec0617676 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -2,7 +2,7 @@ import { signalBotAutonomyBotsChanged } from '../bot-autonomy/botsChangedSignal.
import { formatForwardedRequest, captureAgentRequest, type CapturedAgentRequest } from './forwardedRequest.js';
import { readForwardedRequestSource, type AgentRequestReceipt, type ForwardedRequestSource } from '../../shared/forwardedRequest.js';
import { openSession } from '../localDb/sessionOpening.js';
-import { approvedTaskDelegation, captureTaskActionGuard, captureTaskActionSyncGuard, runHostCompletionDelivery, TaskActionAuthorizationError } from './taskActionAuthorization.js';
+import { approvedTaskDelegation, captureTaskActionDeliveryGuard, captureTaskActionGuard, captureTaskActionSyncGuard, runHostCompletionDelivery, TaskActionAuthorizationError } from './taskActionAuthorization.js';
import { authorizeGroupTool, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
import { existsSync, statSync } from 'node:fs';
@@ -62,7 +62,10 @@ import type { SessionRuntimeProfile } from './sessionRuntimeControl.js';
import { readBotTaskModelOverride, type BotModelRoute } from '../../shared/botModelChain.js';
import { validateTaskModel, resolveTaskModelSelection, type TaskModelSelection } from './appDefaultModelControl.js';
-type TaskMutationAuthority = Pick<Awaited<ReturnType<typeof authorizeGroupTool>>, 'refresh' | 'assertCurrent'>;
+type TaskMutationAuthority = Pick<Awaited<ReturnType<typeof authorizeGroupTool>>, 'refresh' | 'assertCurrent'> & {
+ /** Already-admitted queued input may outlive its source turn, but not its owner scope. */
+ refreshDelivery?: () => Promise<void>;
+};
const isTaskAuthorityError = (error: unknown): error is GroupToolAuthorizationError | TaskActionAuthorizationError =>
error instanceof GroupToolAuthorizationError || error instanceof TaskActionAuthorizationError;
@@ -593,7 +596,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
await groupAuthority?.refresh();
const result = await deps.dispatch({ ...input, clientId, targetSessionId: row.childSessionId!,
onAccepted: async persisted => {
- await groupAuthority?.refresh();
+ // Admission checked the exact source input; delayed acceptance uses the
+ // existing delivery guard so a normally ended source turn is not revocation.
+ await (groupAuthority?.refreshDelivery?.() ?? groupAuthority?.refresh());
if (persisted) { replayed = true; return; }
await acceptExecution(row, clientId, input.clientId);
acceptedThisAttempt = true;
@@ -1609,9 +1614,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
? await authorizeGroupTool(callerSessionId, link.botId, 'owner-action') : null;
const action = ownerUi ? undefined : captureTaskActionGuard();
const actionSync = ownerUi ? undefined : captureTaskActionSyncGuard();
+ const delivery = ownerUi ? undefined : captureTaskActionDeliveryGuard();
// Share the existing mutation checkpoints and rollback paths for every caller,
// including private owner requests whose source can change while a call waits.
const groupAuthority: TaskMutationAuthority | null = action ? {
+ refreshDelivery: async () => {
+ await group?.refresh();
+ try { await (delivery ?? action)(); } catch { throw new TaskActionAuthorizationError(); }
+ },
refresh: async () => {
await group?.refresh();
try { await action(); } catch { throw new TaskActionAuthorizationError(); }
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index 01e90acb09..8830ae16be 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -60,7 +60,7 @@
| 项目 | 列出、登记、改名、移除;工作目录列表 | 有 | 无 |
| 伙伴 | 发现伙伴、伙伴间消息 | 有 | 有 |
| 伙伴 | 自身关联项目:列出、添加与移除(原有文件工具按需读资料) | 有 | 无(远程设置界面可管理) |
-| 伙伴 | 资料、能力、待办、后台任务 | 有 | 无 |
+| 伙伴 | 资料、能力、待办、后台任务 | 有(已准入的后台任务补充排队后可跨发起轮投递,仍复核撤权;见 [伙伴代表谁](teammate-authority.md)) | 无 |
| 伙伴 | 显式重新接受已保存模型,恢复旧版遗留的自动模型记录 | 有(`update_teammate_profile` 显式提交完整 `modelChain`,即使值未变) | 无(远程设置 IPC 可按版本接受,不等于跨电脑 Agent 工具) |
| 伙伴 | 发现与选择 Codex Apps 连接器(继承默认保留,显式 MCP 白名单可收窄) | 有(能力工具) | 无(SSH Codex 不提供) |
| 伙伴 | 按已证实归属搜索跨渠道聊天、按最近活动列出旧任务 | 有 | 有(历史查询,两端需支持筛选参数) |
diff --git a/docs/product-rules/teammate-authority.md b/docs/product-rules/teammate-authority.md
index 6a9dd7db3c..1151d77ab0 100644
--- a/docs/product-rules/teammate-authority.md
+++ b/docs/product-rules/teammate-authority.md
@@ -59,6 +59,10 @@ Auto 档由审核器结合例行任务指令判断,Full Access 不审,靠伙
它不等同于主人刚刚亲手输入,应用更新等专门要求本人输入的操作保持原有边界。
- 空闲、繁忙和新建任务共用持久输入协调器,插话、重试及历史恢复都保留原话;审核上下文不采用 Agent 补充
里的授权说法。原话不明或缺少背景时,先按来源任务查上下文,只有仍缺少必要决定才向主人提问。
+- 已准入的后台任务补充消息排队后,实际接受时复核投递范围,不再要求发起轮仍是同一条输入;
+ 发起轮正常结束或换新输入不撤销这条消息。账号、权限档、计划模式、群权限和委派执行代次等
+ 真实撤权仍生效,新写操作仍复核当前输入。实现见 `botDelegationService.ts` 的
+ `dispatchTrackedInput`;回归见 `botCanonicalSession.test.ts` 的排队补充与接受回调用例。
- IM 轮次不经过输入协调器:原话取自 IM 运行器写在逐轮租约上的本轮落库消息(`inputClientId`),
只在租约的发言人是主人时读取。
- 主人输入被自动续跑(包括生成的「继续」消息)仍算主人代办,但不算新的主人输入,