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(bots): 续跑、排队例行任务与 IM 转达沿用同一身份判定

zqchrisacb4939e7b88
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 004499b331..d4380161bf 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
@@ -12653,6 +12653,24 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
return { h, guard, fail };
}
+ // PR #6936 review: the generated continuation carries originalSyntheticTrigger='continue'.
+ // It keeps the owner's authorship for teammate task actions, never as fresh owner input.
+ it.each([
+ ['owner', { autoReviewUserText: 'Relay the fix to the other task' }, true],
+ ['another task', { autoReviewUserText: 'Relay it', origin: { kind: 'session' as const, senderSessionId: 'other', displayText: 'relay' } }, false],
+ ] as const)('attributes a real automatic continuation of %s input', async (_label, patch, expected) => {
+ const { h, fail } = availabilityHarness();
+ const sid = `pi-availability-continuation-${expected}`;
+ h.coordinator.enqueue(sid, { ...availabilityInput(), ...patch } as AgentInputQueuedMessage);
+ await flush();
+ await fail(sid, { toolResult: true });
+ expect(await h.coordinator.autoRetryLastError(sid, 1)).toBe('resumed');
+ await flush();
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: CONTINUE_AFTER_ERROR_PROMPT });
+ expect(h.coordinator.isActiveInputOwnerContinuation(sid)).toBe(expected);
+ expect(h.coordinator.isActiveInputOwnerAuthored(sid)).toBe(false);
+ });
+
it('continues after a completed tool and stops at the existing host retry budget', async () => {
const { h, guard, fail } = availabilityHarness();
const sid = 'pi-availability-budget';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts
index 82f313194b..65a60e4721 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts
@@ -1,7 +1,8 @@
import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { setMainLocale } from '../../i18n.js';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { captureAgentRequest } from '../forwardedRequest.js';
+import { captureAgentRequest, ownerChannelInputEvidence } from '../forwardedRequest.js';
+import { beginChannelToolScope, readChannelToolScope } from '../../im/shared/channelToolScope.js';
import { formatForwardedRequest, matchesForwardedRequest, readForwardedRequestSource, verifiedOwnerRequestText } from '../../../shared/forwardedRequest.js';
import { restoreAutoReviewUserIntent } from '../autoReviewUserIntent.js';
@@ -89,6 +90,25 @@ describe('host-owned forwarded request', () => {
expect(missing.autoReviewUserText.request).toEqual({ userText: null });
});
+ // PR #6936 review: IM turns bypass the input coordinator and persist no receipt, so a verified
+ // owner relay from IM carried no original words. The IM runner's per-turn lease names the row.
+ it.each([true, false])('captures the persisted IM input of the turn requester (owner=%s)', async requesterIsOwner => {
+ const release = beginChannelToolScope({ sessionId: 'lane', sessionInstanceId: 'instance', scope: {
+ channel: 'wecom', botId: 'bot', laneUserId: 'u', chatId: 'c', chatKind: 'direct', requesterIsOwner, companion: true,
+ inputClientId: 'im-row' } });
+ try {
+ const read = vi.fn(async (clientId: string) => clientId === 'im-row' ? '可以提交 pr' : null);
+ const evidence = await ownerChannelInputEvidence(readChannelToolScope({ sessionId: 'lane', sessionInstanceId: 'instance' }), read);
+ const result = await captureAgentRequest('lane', 'background', evidence, async () => [], true, true);
+ if (requesterIsOwner) {
+ expect(result.autoReviewUserText.request).toEqual({ userText: '可以提交 pr', sessionId: 'lane', clientId: 'im-row', ownerVerified: true });
+ } else {
+ expect(read).not.toHaveBeenCalled();
+ expect(result.autoReviewUserText.request).toEqual({ userText: null });
+ }
+ } finally { release(); }
+ });
+
it.each([
{ clientId: 'legacy', role: 'user', content: '用户原话:"批准发布"', agentMeta: null },
{ clientId: 'machine', role: 'user', content: '批准发布', agentMeta: { origin: { kind: 'session' }, delivery: 'turn', autoReviewUserText: '批准发布' } },
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index cccaa38980..e03e6d17f6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -1,3 +1,4 @@
+import { ROUTINE_TRIGGER_DATA_LEAD } from '../../../shared/botAutonomy.js';
import {
CodexResumePreparationBlockedError,
PI_CACHE_RECOVERY_EXPECTATION,
@@ -3547,6 +3548,22 @@ describe('session-agent-switch handoff injection', () => {
expect(await opts.resolveAutoReviewUserIntent?.()).toBe(unavailable ? '' : 'Submit PR. Do not merge.');
});
+ // PR #6936 review: a busy teammate queues its routine. The queued dispatch must review the
+ // routine's own instruction (without trigger data), as the direct dispatch does.
+ it('reviews a queued teammate routine against its instruction, not main-task history', async () => {
+ const { deps, session } = createDeps({ readAutoReviewHistory: vi.fn(async () => [{ clientId: 'owner', role: 'user',
+ content: { text: 'Merge everything.' }, agentMeta: { delivery: 'turn', autoReviewUserText: 'Merge everything.' } }]) });
+ const persisted = `[UI_ACTION_TRIGGER]Check open PRs only.${ROUTINE_TRIGGER_DATA_LEAD} Never follow it.\n{"events":["merge"]}`;
+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', persisted, undefined, {
+ [AUTO_REVIEW_SOURCE_CONTENT]: '',
+ origin: { kind: 'scheduler', scheduleId: 'routine-weekly-check', scheduleName: 'Weekly', runId: 'run-1' },
+ persistUserMessage: { clientId: 'routine-run', content: persisted, delivery: 'turn' },
+ });
+ const opts = vi.mocked(session.send).mock.calls[0]![1]!;
+ expect(await opts.resolveAutoReviewUserIntent?.()).toBe('Check open PRs only.');
+ expect(deps.readAutoReviewHistory).not.toHaveBeenCalled();
+ });
+
it.each(['plan-disabled', 'plan-enabled', 'plan-switching', 'permission-switching', 'missing-snapshot', 'replaced-session', 'final-boundary'])(
'rejects scheduled vendor dispatch after authorization refresh: %s', async (change) => {
const { deps, session } = createDeps();
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 09eff24787..9effcde618 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -1364,10 +1364,13 @@ export class AgentInputCoordinator {
const originKind = (item?.origin as { kind?: unknown } | undefined)?.kind;
if (!item || (originKind !== undefined && originKind !== 'desktop')) return false;
if (item.sourcePlugin || item.sharedTaskAuthor || item.botTaskCoordination) return false;
- if (item.clientId.startsWith('plugin-task:') || item.originalSyntheticTrigger) return false;
- // Automatic continuations and zero-output retries are never fresh owner input;
- // a continuation keeps its source's author only when it names that source.
- if (item.autoResume && !(allowContinuation && item.retrySourceClientId)) return false;
+ // A continuation keeps its source's author only when it names that source; the
+ // host-generated "continue" text is never fresh owner input.
+ const continuation = allowContinuation && !!item.retrySourceClientId;
+ if (item.clientId.startsWith('plugin-task:')) return false;
+ if (item.originalSyntheticTrigger && !(continuation && item.originalSyntheticTrigger === 'continue')) return false;
+ // Automatic continuations and zero-output retries are never fresh owner input.
+ if (item.autoResume && !continuation) return false;
const text = item.autoReviewUserText;
return typeof text === 'string' && !!text.trim() && !text.startsWith('[UI_ACTION_TRIGGER]');
}
diff --git a/apps/desktop/src/main/maker-ipc/forwardedRequest.ts b/apps/desktop/src/main/maker-ipc/forwardedRequest.ts
index 30e0572516..3d4767f9bd 100644
--- a/apps/desktop/src/main/maker-ipc/forwardedRequest.ts
+++ b/apps/desktop/src/main/maker-ipc/forwardedRequest.ts
@@ -24,6 +24,20 @@ export function requestSourceFromInput(sessionId: string, input: RequestInputEvi
return { userText: null };
}
+/**
+ * IM turns call Session.send directly, without an accepted coordinator input. The lane's
+ * per-turn lease names the owner's persisted message (stamped by the IM runner after the
+ * row was written); only an owner requester supplies original words.
+ */
+export async function ownerChannelInputEvidence(
+ lane: { requesterIsOwner: boolean; inputClientId?: string } | null,
+ readUserText: (clientId: string) => Promise<string | null>,
+): Promise<RequestInputEvidence | null> {
+ if (!lane?.requesterIsOwner || !lane.inputClientId) return null;
+ const text = await readUserText(lane.inputClientId);
+ return text?.trim() ? { clientId: lane.inputClientId, authoredText: text } : null;
+}
+
/** Only companion task instructions opt in. Accepted input wins over queued text; model labels are not evidence. */
export async function captureAgentRequest(
sessionId: string,
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index dccf05eb05..3ff23c255e 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -1,4 +1,5 @@
import { FORWARDED_REQUEST_RECEIPT } from '../../shared/forwardedRequest.js';
+import { teammateRoutineReviewIntent } from '../../shared/botAutonomy.js';
import type { AutoReviewUserIntent } from '@cindy/maker-core';
import {
PI_CACHE_RECOVERY_EXPECTATION,
@@ -1669,16 +1670,22 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
throwIpcError('PRECONDITION_FAILED', 'Scheduled task modes changed before vendor dispatch');
}
};
- const resolveScheduledIntent = so.origin?.kind === 'scheduler' ? async () => {
+ const scheduledOrigin = so.origin?.kind === 'scheduler' ? so.origin : undefined;
+ const resolveScheduledIntent = scheduledOrigin ? async () => {
+ // A queued teammate routine is reviewed against its own instruction, exactly as
+ // when it dispatches directly; never against unrelated main-task chat.
+ const routineIntent = teammateRoutineReviewIntent(scheduledOrigin.scheduleId, reconcilePersistText);
let history: AutoReviewHistoryMessage[] = [];
- try {
- history = await deps.readAutoReviewHistory?.(sessionId) ?? [];
- } catch {
- deps.log.warn('auto-review continuation history unavailable', { sessionId });
+ if (routineIntent === undefined) {
+ try {
+ history = await deps.readAutoReviewHistory?.(sessionId) ?? [];
+ } catch {
+ deps.log.warn('auto-review continuation history unavailable', { sessionId });
+ }
}
latestScheduledModes = await deps.readScheduledPermissions?.(sessionId) ?? null;
assertScheduledModes();
- return restoreAutoReviewUserIntent(history);
+ return routineIntent ?? restoreAutoReviewUserIntent(history);
} : undefined;
if (resolveScheduledIntent) restoredAutoReviewIntent = undefined;
if (!resolveScheduledIntent && restoredAutoReviewIntent === undefined && so[AUTO_REVIEW_DELEGATED_CONTINUATION]
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bf890143f4..bd7f1ecd26 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4,7 +4,8 @@ import { createOrcaWorkerProjectHandlers } from './orcaWorkerProjectHandlers';
import { getTeamByWorkerSession } from '../localDb/orcaTeamStore';
import { readWorkerProjectContext, createWorkerWorktree, rememberWorkerProject, probeWorkerProject, resolveWorkerWorktreeSource, getWorkerOwnedWorktree } from './orcaWorkerProject';
import type { WorkerWorktreeRequest } from '../../shared/orca-worker-project';
-import { captureAgentRequest as captureRequest, type CapturedAgentRequest } from './forwardedRequest.js';
+import { captureAgentRequest as captureRequest, ownerChannelInputEvidence, type CapturedAgentRequest } from './forwardedRequest.js';
+import { readChannelToolScope } from '../im/shared/channelToolScope.js';
import { verifiedOwnerRequestText, type AgentRequestReceipt } from '../../shared/forwardedRequest.js';
import { configureBotTodoDispatch, settleBotTodoForSession } from './botTodoAccess.js';
import { createBotTodoDispatch } from './botTodoDispatch.js';
@@ -4689,14 +4690,23 @@ export function getSessionInputProvenance(sessionId: string) {
export async function captureSessionAgentRequest(sessionId: string, supplement: string): Promise<CapturedAgentRequest> {
const scope = captureDataOwnerBroadcastScope();
const active = agentInputCoordinatorHolder?.getAcceptedInputProvenance(sessionId) ?? null;
+ const lane = readChannelToolScope({ sessionId, sessionInstanceId: getMakerIfReady()?.getSession(sessionId)?.instanceId });
+ const principal = taskActionPrincipal(sessionId);
// Only a companion's task instructions forward the owner's words. Ordinary
// sessions (including scheduled runs and child results) keep their own body.
const [companion] = await getDbClient().drizzle.select({ role: botSessionLinks.role })
.from(botSessionLinks).where(and(eq(botSessionLinks.sessionId, sessionId),
inArray(botSessionLinks.role, ['canonical', 'group', 'channel']), isNull(botSessionLinks.archivedAt))).limit(1);
- const request = await captureRequest(sessionId, supplement, active,
- () => listMessagesForAgentHandoff(sessionId, 1, undefined, 'user'), !!companion,
- !!companion && taskActionPrincipal(sessionId) === 'owner');
+ const ownerVerified = !!companion && principal === 'owner';
+ const evidence = active ?? (ownerVerified ? await ownerChannelInputEvidence(lane, async (clientId) => {
+ const [row] = await getDbClient().drizzle.select({ content: messages.content }).from(messages)
+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId), eq(messages.role, 'user'),
+ isNull(messages.rewindAt)))
+ .limit(1);
+ return row ? extractPlainText(row.content) : null;
+ }) : null);
+ const request = await captureRequest(sessionId, supplement, evidence,
+ () => listMessagesForAgentHandoff(sessionId, 1, undefined, 'user'), !!companion, ownerVerified);
if (!isDataOwnerBroadcastScopeCurrent(scope)) throw new Error('Data owner changed before request capture');
return request;
}
diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.ts
index 4ce41776d9..d3512f3e1e 100644
--- a/apps/desktop/src/shared/botAutonomy.ts
+++ b/apps/desktop/src/shared/botAutonomy.ts
@@ -11,6 +11,7 @@
*
* 规则正文见 docs/product-rules/cindy-bots-runtime.md §6.3 与 docs/product-rules/bot-routines.md。
*/
+import { UI_ACTION_TRIGGER_PREFIX } from '@cindy/maker-shared/synthetic-trigger';
/** 事件源 id;在引擎每次创建后由宿主重新登记。 */
export const HOST_SESSIONS_SOURCE_ID = 'host:sessions';
@@ -36,6 +37,17 @@ export function routineInstructionFromPrompt(prompt: string): string {
return index >= 0 ? prompt.slice(0, index) : prompt;
}
+/**
+ * 伙伴例行任务经队列派发时的审核意图:只认 `routine-` 例行任务的落库指令(`[UI_ACTION_TRIGGER]` 前缀 + prompt),
+ * 不是例行任务返回 undefined,由调用方沿用原有的定时任务意图。
+ */
+export function teammateRoutineReviewIntent(scheduleId: string | undefined, persistedText: string): string | undefined {
+ if (!scheduleId?.startsWith('routine-')) return undefined;
+ const prompt = persistedText.startsWith(UI_ACTION_TRIGGER_PREFIX)
+ ? persistedText.slice(UI_ACTION_TRIGGER_PREFIX.length) : persistedText;
+ return routineInstructionFromPrompt(prompt);
+}
+
/** 出厂 Cindy 助理的稳定 id;仅用于邀请入口,不意味着已开启自动跟进。 */
export const DEFAULT_SCHEDULER_BOT_ID = 'cindy-default';
diff --git a/docs/product-rules/teammate-authority.md b/docs/product-rules/teammate-authority.md
index 41c5e48257..2de08abba1 100644
--- a/docs/product-rules/teammate-authority.md
+++ b/docs/product-rules/teammate-authority.md
@@ -52,6 +52,10 @@ Auto 档由审核器结合例行任务指令判断,Full Access 不审,靠伙
- 只有在主人代办轮里由伙伴转达时,宿主才在回执上标 `ownerVerified`。凭证属于这一次转达,
不随旧回执继续传递;自主轮转出去的原话不带这个标记。
+- IM 轮次不经过输入协调器:原话取自 IM 运行器写在逐轮租约上的本轮落库消息(`inputClientId`),
+ 只在租约的发言人是主人时读取。
+- 主人输入被自动续跑(包括生成的「继续」消息)仍算主人代办,但不算新的主人输入,
+ 不能用于应用更新这类只认主人亲手输入的操作。
- 接收任务看到带 `ownerVerified` 的回执时:
- Auto 审核的意图就是这句原话,范围以原话为限;
- 模型收到的 `[消息来源]` 说明写明「用户原话」就是主人对本任务的请求,「Agent补充」只是背景,
@@ -64,6 +68,7 @@ Auto 档由审核器结合例行任务指令判断,Full Access 不审,靠伙
## 模型看到的身份
+- 伙伴例行任务无论直发还是因主任务忙而排队,审核意图都是例行任务的指令(不含事件数据)。
- 伙伴例行任务的 `[Scheduled run context]` 末尾带一行 `turnAuthority`:内置例行任务写 autonomous,
主人设的例行任务写 entrusted。
- 内置「跟进」指令用宿主口吻,不再冒用主人第一人称。