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(teammates): read the in-memory clear fence and keep messages on failed checks

Dashec5425a914f7
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index e1422598e2..e27b82ce65 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -103,7 +103,7 @@ describe('task action dispatch authorization', () => {
await h.coordinator.ensureQueueRestored(sid);
h.setRunning(true);
const queued = makeItem('automatic', 'Continue');
- bindTaskActionInput(sid, queued, async () => { if (!current) throw new Error('revoked'); });
+ bindTaskActionInput(sid, queued, async () => { if (!current) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED'); });
h.coordinator.enqueue(sid, mode === 'restored' ? JSON.parse(JSON.stringify(queued)) : queued);
h.coordinator.enqueue(sid, makeItem('owner', 'Owner message'));
await flush();
@@ -119,6 +119,33 @@ describe('task action dispatch authorization', () => {
expect(h.onUndispatchedUserTurn).not.toHaveBeenCalled();
expect(h.coordinator.getProjection(sid)).toMatchObject({ error: null, pendingQueue: [] });
});
+
+ // Review on #7969: a failed check (group transport, database not ready) is not a
+ // revocation. The message must stay as a retryable queue head, not be destroyed.
+ it('keeps the message as a retryable queue head when the delivery check itself fails', async () => {
+ const h = createHarness(), sid = 'task-action-check-failed';
+ h.sendToAgent.mockImplementation(async (_id, _message, _opts, sendOpts) => {
+ await sendOpts[MCP_APP_MESSAGE_GUARD]?.();
+ return sendSuccess();
+ });
+ await h.coordinator.ensureQueueRestored(sid);
+ h.setRunning(true);
+ const queued = makeItem('automatic', 'Continue');
+ bindTaskActionInput(sid, queued, async () => {
+ throw Object.assign(new Error('verification unavailable'), { code: 'GROUP_AUTHORIZATION_UNAVAILABLE' });
+ });
+ h.coordinator.enqueue(sid, queued);
+ await flush();
+ h.setRunning(false);
+ h.coordinator.wakeSession(sid, 'idle');
+ await flush();
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.coordinator.getProjection(sid)).toMatchObject({
+ recovery: { kind: 'queue-head', clientId: 'automatic' },
+ pendingQueue: [expect.objectContaining({ clientId: 'automatic' })],
+ });
+ });
});
// #6399 queue-edit regression: run the actual trusted IPC finalizer plus the
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 7d32aa16d1..2198e8ed9e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
@@ -28,6 +28,7 @@ import {
captureTaskActionSyncGuard,
captureTaskActionGuard,
captureTaskActionDeliveryGuard,
+ isTaskActionRevoked,
} from '../taskActionAuthorization.js';
function fixture(ownerInput = false, delegated = false) {
@@ -284,6 +285,7 @@ function desktopFixture(kind: 'private' | 'group' | 'automatic' = 'group') {
ownerContinuation: false,
automatic: kind !== 'private',
boundary: 'runtime-1',
+ clearBoundaryMs: null as number | null,
};
const confirm = vi.fn(async () => true);
const runtime = {
@@ -458,6 +460,35 @@ describe('Owner-delegated scheduled task actions', () => {
else await delivery.resolves.toBeUndefined();
});
+ // Review on #7969: /clear moves the coordinator's boundary before cleared_at is persisted,
+ // and persisting may fail, so delivery reads that boundary too. A persisted boundary the
+ // coordinator merely loads late (restart) is older than the admission, not a new clear.
+ it.each([
+ { name: 'cleared in memory after admission', dbClearedAt: null, memoryAfter: 2_000, expired: true },
+ { name: 'older persisted boundary loaded late', dbClearedAt: 1_000, memoryAfter: 1_000, expired: false },
+ ])('queued delivery when $name (expired=$expired)', async ({ dbClearedAt, memoryAfter, expired }) => {
+ const h = scheduledFixture();
+ Object.assign(h.caller, { clearedAt: dbClearedAt });
+ const queued = input();
+ await withToolCallAuthority(h.authorize, scheduledSend(), async () => bindTaskActionInput('target', queued));
+ h.activeInput.clearBoundaryMs = memoryAfter;
+ const delivery = expect(taskActionInputGuard('target', queued)!());
+ if (expired) await delivery.rejects.toThrow('AUTHORIZATION_EXPIRED');
+ else await delivery.resolves.toBeUndefined();
+ });
+
+ // Only a proven revocation may destroy a queued message; a failed check keeps it for retry.
+ it.each([
+ [new Error('TASK_ACTION_AUTHORIZATION_EXPIRED'), true],
+ [new Error('TASK_ACTION_AUTHORIZATION_REQUIRED'), true],
+ [new Error('OWNER_SCOPE_CHANGED'), true],
+ [Object.assign(new Error('revoked'), { code: 'GROUP_AUTHORIZATION_REQUIRED' }), true],
+ [Object.assign(new Error('transport'), { code: 'GROUP_AUTHORIZATION_UNAVAILABLE' }), false],
+ [new Error('DbClient not ready'), false],
+ ])('classifies %s as revoked=%s', (error, revoked) => {
+ expect(isTaskActionRevoked(error)).toBe(revoked);
+ });
+
it.each(['permission', 'account', 'turn'] as const)('does not act or prompt if %s changes during review', async changed => {
const h = scheduledFixture();
h.runtime.reviewHostPermissionAction.mockImplementation(async () => {
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index e4e7de4e3d..f641ab1b83 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -2,7 +2,7 @@ import { FORWARDED_REQUEST_RECEIPT, verifiedOwnerRequestText, type ForwardedRequ
import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT } from '@cindy/maker-core';
import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
import { assertSharedTaskQueueMutation } from './sharedTaskInput.js';
-import { assertTaskActionCurrent, combineInputGuards, hasTaskActionAuthorization, taskActionInputGuard, TASK_ACTION_INPUT_GUARD } from './taskActionAuthorization.js';
+import { assertTaskActionCurrent, combineInputGuards, hasTaskActionAuthorization, isTaskActionRevoked, taskActionInputGuard, TASK_ACTION_INPUT_GUARD } from './taskActionAuthorization.js';
import { isBotGroupClientId } from '../../shared/botGroupChat.js';
import { SchedulerQueuedPreparationError } from './schedulerQueuedPreparation.js';
import { ProviderGroupUsageLimitError } from '../provider-group/failurePolicy.js';
@@ -5071,13 +5071,16 @@ export class AgentInputCoordinator {
try {
if (taskActionGuard) {
// A revoked task action settles before screening, persistence or a vendor
- // turn, so the receiving task never shows a failed reply for it. The send
+ // turn, so the receiving task never shows a failed reply for it. A check that
+ // merely failed is not a revocation: it takes the ordinary pre-accept failure
+ // path below, which keeps the message as a retryable queue head. The send
// transaction still rechecks the same guard at dispatch.
- const revoked = await taskActionGuard().then(() => null, (error: unknown) => ({ error }));
+ const rejection = await taskActionGuard().then(() => null, (error: unknown) => ({ error }));
if (!this.isActiveTurnCurrent(sessionId, active)) return;
- if (revoked) {
+ if (rejection) {
+ if (!isTaskActionRevoked(rejection.error)) throw rejection.error;
log.info('discarding revoked task action input before dispatch', {
- sessionId, clientId: head.clientId, reason: errorMessage(revoked.error),
+ sessionId, clientId: head.clientId, reason: errorMessage(rejection.error),
});
this.discardRevokedAppInput(sessionId, active, head);
return;
@@ -5149,15 +5152,22 @@ export class AgentInputCoordinator {
// may synchronously emit the new turn's started marker before it returns;
// post-dispatch acknowledgements must remain older than that marker.
const preVendorDispatchAt = Math.max(0, Date.now() - 1);
- const appMessageGuard = combineInputGuards(queuedAppMessageGuard(head), taskActionGuard);
+ const appMessageGuard = queuedAppMessageGuard(head);
const result = await this.deps.sendToAgent(sessionId, makerUserMessage, head.createOpts, {
- ...(appMessageGuard ? { [MCP_APP_MESSAGE_GUARD]: async () => {
+ ...(appMessageGuard || taskActionGuard ? { [MCP_APP_MESSAGE_GUARD]: async () => {
try {
- await appMessageGuard();
+ await appMessageGuard?.();
} catch (error) {
appMessageGuardRejected = true;
throw error;
}
+ try {
+ await taskActionGuard?.();
+ } catch (error) {
+ // Only a proven revocation discards; a failed check keeps the message retryable.
+ if (isTaskActionRevoked(error)) appMessageGuardRejected = true;
+ throw error;
+ }
} } : {}),
...(head.supersedesUserClientId ? { retryUserClientId: head.supersedesUserClientId } : {}),
[AUTO_REVIEW_SOURCE_CONTENT]: queuedAutoReviewText(head),
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index fdfd2ddcc2..8a7d9f0a2a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4934,6 +4934,7 @@ export function getTaskActionInputState(sessionId: string) {
automatic: !!input.input && !isActiveInputOwnerAuthored(sessionId),
orcaSenderSessionId: input.input?.orcaSenderSessionId,
boundary: `${session?.instanceId ?? ''}:${agentInputCoordinatorHolder?.getGeneration(sessionId) ?? -1}`,
+ clearBoundaryMs: agentInputCoordinatorHolder?.getClearBoundaryMs(sessionId) ?? null,
};
}
diff --git a/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts b/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
index 20fa1c80c6..831a861322 100644
--- a/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
+++ b/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
@@ -351,6 +351,25 @@ export class TaskActionAuthorizationError extends Error {
}
}
+const REVOKED_MESSAGES: ReadonlySet<string> = new Set([
+ 'TASK_ACTION_AUTHORIZATION_EXPIRED',
+ 'TASK_ACTION_AUTHORIZATION_REQUIRED',
+ 'OWNER_SCOPE_CHANGED',
+]);
+
+/**
+ * Whether a delivery-guard rejection proves the grant is gone. A check that merely failed
+ * (group transport outage, database not ready, anything unknown) is not a revocation: its
+ * message stays queued for retry instead of being destroyed. Group errors are matched by
+ * code (`GROUP_AUTHORIZATION_UNAVAILABLE` is the temporary one) to avoid importing the group module.
+ */
+export function isTaskActionRevoked(error: unknown): boolean {
+ if (error instanceof TaskActionAuthorizationError) return true;
+ if (typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'GROUP_AUTHORIZATION_REQUIRED')
+ return true;
+ return error instanceof Error && REVOKED_MESSAGES.has(error.message);
+}
+
/** Capture once; late callbacks must not pick up another invocation's authority. */
export function captureTaskActionSyncGuard(): (() => void) | undefined {
const current = actionContext.getStore();
diff --git a/apps/desktop/src/main/maker-ipc/taskActionHost.ts b/apps/desktop/src/main/maker-ipc/taskActionHost.ts
index 5de0de28e7..8e28ed7202 100644
--- a/apps/desktop/src/main/maker-ipc/taskActionHost.ts
+++ b/apps/desktop/src/main/maker-ipc/taskActionHost.ts
@@ -110,6 +110,8 @@ export function createDesktopTaskActionAuthorizer(deps: {
isCurrent?: () => boolean;
} | null;
boundary: string;
+ /** The coordinator's in-memory /clear fence; it can be ahead of `sessions.cleared_at`. */
+ clearBoundaryMs?: number | null;
};
getSession(sessionId: string): TaskActionSession | undefined;
confirm(sessionId: string, tool: string, args: unknown, context?: TaskActionConfirmation): Promise<boolean>;
@@ -333,6 +335,12 @@ export function createDesktopTaskActionAuthorizer(deps: {
(caller.botId && (fresh.botStatus !== 'active' || fresh.archivedAt !== null))
)
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ // /clear moves the coordinator's fence before persisting cleared_at, and persisting may
+ // fail, so the sender's clear is also read from memory. A persisted boundary loaded late
+ // (restart) is no newer than what admission already saw in the database.
+ const clearedInMemory = deps.input(sessionId).clearBoundaryMs;
+ if (clearedInMemory != null && clearedInMemory > Math.max(input.clearBoundaryMs ?? 0, caller.clearedAt ?? 0))
+ throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
if (delegation) {
const current = await readDelegation(true);
if (!current || current.runSequence !== delegation.runSequence)
diff --git a/docs/product-rules/teammate-authority.md b/docs/product-rules/teammate-authority.md
index 9768907f6b..f63a9538a5 100644
--- a/docs/product-rules/teammate-authority.md
+++ b/docs/product-rules/teammate-authority.md
@@ -50,7 +50,10 @@
发起轮结束、发起方 Session 重建、换新输入,或发起方的权限档、计划模式变化,都不撤销这条消息;
它由接收任务按自己的权限执行,主人可以在接收任务的队列里编辑或撤回。只有切换账号、发起任务被
清空或删除、伙伴被暂停或归档、委派执行代次或 Orca 团队变化、群授权失效时才不再投递;这类消息在
- 落库前移出队列,不在接收任务里留下失败回复。实现见 `taskActionHost.ts` 的 `assertDeliveryCurrent`
+ 落库前移出队列,不在接收任务里留下失败回复。清空以协调器的内存边界和数据库 `cleared_at` 中较新者
+ 为准(`/clear` 先改内存、后写库,写库可能失败);重启后晚加载的旧边界不算新的清空。校验本身失败
+ (群授权传输中断、数据库未就绪等)不算撤权:消息保留为可重试的队首,不被销毁。实现见
+ `taskActionHost.ts` 的 `assertDeliveryCurrent`、`taskActionAuthorization.ts` 的 `isTaskActionRevoked`
与 `agent-input-coordinator.ts` 的派发前复核;回归见 `taskActionAuthorization.test.ts` 与
`agent-input-coordinator.test.ts`。
- 来源判定与操作决定分别保留。获准自主操作不会给后续转达生成主人原话凭证。