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(plugins): preserve delegated receipts and replay complete authority history

Dashdb022e5671fa
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index 667ed61356..8dd3daaf2e 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -298,6 +298,20 @@ describe('local-db:messages:list cursor', () => {
} finally { sqlite.close(); }
});
+ it('replays complete authorization history while retaining clear and rewind boundaries', async () => {
+ const sqlite = createDb();
+ try {
+ for(let i=0;i<130;i++) insertCostMessage(sqlite,{id:`human-${i}`,role:'user',createdAt:i+1,
+ agentMeta:{autoReviewUserText:`no-${i}`,delivery:'steer'}});
+ expect(await listMessagesForAgentHandoff('s1',null,undefined,'authorization')).toHaveLength(130);
+ sqlite.prepare('INSERT OR REPLACE INTO sessions (id, cleared_at) VALUES (?, ?)').run('s1',20);
+ sqlite.prepare('UPDATE messages SET rewind_at = 1000 WHERE id = ?').run('human-129');
+ const rows=await listMessagesForAgentHandoff('s1',null,undefined,'authorization');
+ expect(rows).toHaveLength(109);expect(rows[0]?.clientId).toBe('human-20');expect(rows.at(-1)?.clientId).toBe('human-128');
+ expect(await listMessagesForAgentHandoff('s1',100,undefined,'authorization')).toHaveLength(100);
+ } finally { sqlite.close(); }
+ });
+
it('selects a recently answered old card before limiting authorization history', async () => {
const sqlite = createDb();
try {
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index e33efac5f3..9fdbeb5b02 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -2487,7 +2487,7 @@ export async function findForkParentSessionId(sessionId: string): Promise<string
/**
* session-agent-switch:读取交接素材——本会话未被 rewind、晚于 /clear 边界的
- * 最近 limit 行(时间正序返回),只取交接需要的最小投影。
+ * 最近 limit 行(时间正序返回),只取交接需要的最小投影;null 读取边界内完整历史。
*
* `after`(Phase 2 增量交接):只取严格晚于该水位线(createdAt + rowid 决序,
* 与 findPendingAgentHandoff 同 tie-break 口径)的行——即目标引擎停泊
@@ -2495,7 +2495,7 @@ export async function findForkParentSessionId(sessionId: string): Promise<string
*/
export async function listMessagesForAgentHandoff(
sessionId: string,
- limit = 400,
+ limit: number | null = 400,
after?: { createdAt: number; rowid: number },
role?: 'user' | 'authorization',
): Promise<
@@ -2538,7 +2538,7 @@ export async function listMessagesForAgentHandoff(
AND json_valid(${messages.agentMeta}) THEN CASE
WHEN json_extract(${messages.agentMeta}, '$.autoReviewUserText.kind') IN ('scheduled-continuation', 'delegated-continuation')
THEN 0 ELSE 1 END ELSE 1 END`;
- const rows = await db
+ const query = db
.select({
rowid: messageRowid,
clientId: messages.clientId,
@@ -2554,8 +2554,10 @@ export async function listMessagesForAgentHandoff(
role === 'authorization' ? and(inArray(messages.role, ['user', 'ask_user', 'plan_review']), notScheduledExecution)
: role ? eq(messages.role, role) : undefined),
)
- .orderBy(desc(role === 'authorization' ? authorityTime : messages.createdAt), desc(messageRowid))
- .limit(limit);
+ .orderBy(desc(role === 'authorization' ? authorityTime : messages.createdAt), desc(messageRowid));
+ // Authority replay must start at the clear/rewind boundary: the shared intent
+ // budget is stateful, so an arbitrary row suffix has a different projection.
+ const rows = await (limit === null ? query : query.limit(limit));
rows.reverse();
return rows
.map((r) => {
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 c5d7adcfa9..8f0b3a7308 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
@@ -1,5 +1,6 @@
import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, appendAutoReviewUserIntent } from '@cindy/maker-core';
-import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '../autoReviewUserIntent.js';
+import { AUTO_REVIEW_DELEGATED_CONTINUATION, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from '../autoReviewUserIntent.js';
+import { createPluginTaskReviewResolver, type PluginReviewSnapshot } from '../pluginTaskReviewContext.js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentInputCoordinator } from '../agent-input-coordinator.js';
import {
@@ -37,6 +38,8 @@ import {
import type { RecoveryContextSnapshot } from '../recoveryCoordinator.js';
import {
stampTrustedDesktopQueuedOrigin,
+ createMakerSendTransaction,
+ type MakerSendTransactionSession,
TRUSTED_DESKTOP_PI_COMMAND_SNAPSHOT,
TRUSTED_DESKTOP_QUEUE_ORIGIN,
} from '../makerSendTransaction.js';
@@ -11251,7 +11254,7 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修
},
);
- it('preserves typed plugin authorship receipts through queue snapshots and dispatch', async () => {
+ it('preserves typed plugin receipts from queue snapshot through durable persistence and review', async () => {
const h = createHarness();
const sid = 'plugin-empty-authorship';
await h.coordinator.ensureQueueRestored(sid);
@@ -11264,10 +11267,50 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修
restarted.setLoadQueueSnapshot(async () => snapshot);
await restarted.coordinator.ensureQueueRestored(sid);
expect(restarted.coordinator.getQueueControlSnapshot(sid).pendingQueue[0]).toMatchObject({ autoReviewUserText: { kind: 'delegated-continuation' } });
+ const history: AutoReviewHistoryMessage[] = [{clientId:'human',role:'user',createdAt:1,content:{text:'Do not modify files'},agentMeta:{delivery:'turn',autoReviewUserText:'Do not modify files'}}];
+ const session: MakerSendTransactionSession = {
+ id:sid,instanceId:'runtime',agentKind:'codex',workDir:'/answer',remoteHostId:null,isTurnRunning:()=>false,
+ send:vi.fn(async (_message,opts)=>{await opts?.onAccepted?.();return {accepted:true as const};}),
+ };
+ const transaction=createMakerSendTransaction({
+ getSession:()=>session,closeSession:async()=>{},preflightBotRuntimeResources:async()=>{},
+ getSessionMeta:async()=>({}),ensureRemoteReadyForSessionStart:async()=>{},checkWorkDirExists:async()=>true,
+ isOrcaMcpHydrated:()=>true,buildCreateOptsWithStderr:x=>x,synthesizeOrcaVendorOptionsFromDb:async()=>false,
+ readSessionExtraDirsFromDb:async()=>[],readSessionWorkingDirFromDb:async()=>'/answer',
+ readWorkingDirectoryRecoveryCreateOpts:async()=>({agentKind:'codex',workingDir:'/answer',model:'m'}),
+ withRehydrateCloseSuppressed:async(_id,fn)=>fn(),bootstrapSession:async()=>({session,didInjectOrcaInstructions:false,didInjectProjectContext:false}),
+ markOrcaRoleIfNeeded:async()=>{},broadcastSessionCreated:()=>{},prepareSendUserMessage:async(_id,m)=>m as string,
+ createDbMessage:async(_id,row)=>{history.push(JSON.parse(JSON.stringify({...row,createdAt:history.length+1})));},
+ readAutoReviewHistory:async()=>history,isSessionRunningError:()=>false,log:{info:()=>{},warn:()=>{}},
+ });
+ restarted.sendToAgent.mockImplementation(async (...args)=>{
+ const result=await transaction.sendToAgentAccepted(...args);
+ expect(result.accepted).toBe(true);
+ return sendSuccess();
+ });
restarted.coordinator.enqueue(sid, makeItem('resume-input', 'Continue'), { resumeRestorePausedQueue: true });
await flush();
expect(restarted.sendToAgent.mock.calls[0]?.[3][AUTO_REVIEW_SOURCE_CONTENT]).toBe('');
expect(restarted.sendToAgent.mock.calls[0]?.[3][AUTO_REVIEW_DELEGATED_CONTINUATION]).toBe(true);
+ await restarted.sendToAgent.mock.results[0]!.value;
+ expect(history[1]?.agentMeta?.autoReviewUserText).toEqual({kind:'delegated-continuation'});
+ const route={agentKind:'codex' as const,providerId:'p',model:'m',effort:'high',fastMode:false};
+ const authority: PluginReviewSnapshot={pluginId:'test',authorized:true,revision:1,registeredRoute:route,
+ session:{workingDir:'/answer',permissionMode:'auto',status:'active',route},lead:{permissionMode:'auto',status:'active'},
+ plan:{task:'Inspect project',items:[],concurrency:null},history,sessionHistory:history,historyComplete:true};
+ const resolve=createPluginTaskReviewResolver(async()=>authority);
+ const live=vi.mocked(session.send).mock.calls[0]![1]![AUTO_REVIEW_USER_INTENT]!;
+ for(const userIntent of [live,restoreAutoReviewUserIntent(history)]){
+ const reviewed=await resolve({sessionId:sid,agentKind:'codex',model:'m',userIntent,workspaceRoots:['/answer'],platform:'linux',action:{kind:'exec',command:'ls',cwd:'/answer'}});
+ expect(reviewed.authorizationError).toBeUndefined();expect(reviewed.userIntent).toBe('Do not modify files');expect(reviewed.delegatedTask).toBeDefined();
+ }
+ // Genuine human resource input, without the Main-only symbol, still resets old consent.
+ await transaction.sendToAgentAccepted(sid,'New attachment',undefined,{
+ [AUTO_REVIEW_SOURCE_CONTENT]:'',
+ persistUserMessage:{clientId:'new-resource',content:JSON.stringify({text:'',files:[{name:'new.txt'}]}),delivery:'turn'},
+ });
+ expect(history.at(-1)?.agentMeta?.autoReviewUserText).toBe('');
+ expect(restoreAutoReviewUserIntent(history)).toBe('');
});
it('编辑保留主机接收时间,清空边界后的条目崩溃恢复时不会被误删', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
index 107b23406e..7319426939 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
@@ -2,7 +2,7 @@ import { mkdtemp, mkdir, realpath, rm, symlink } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it, expect } from 'vitest';
-import type { AutoReviewRequest } from '@cindy/maker-core';
+import { appendAutoReviewUserIntent, type AutoReviewRequest, type AutoReviewUserIntent } from '@cindy/maker-core';
import { restoreAutoReviewUserIntent } from '../autoReviewUserIntent.js';
import {
createPluginTaskReviewResolver,
@@ -59,6 +59,21 @@ function fixture(): PluginReviewSnapshot {
};
}
describe('plugin delegated Auto context', () => {
+ it.each([120, 1200])('matches %i persisted short inputs across budget cycles without accepting an unpersisted steer', async count => {
+ const s = fixture();
+ s.history = [];
+ let live: AutoReviewUserIntent = '';
+ for (let i = 0; i < count; i++) {
+ const text = `no-${i}`;
+ live = appendAutoReviewUserIntent(live, text);
+ s.history.push({clientId:String(i),role:'user',createdAt:i+1,content:{text},agentMeta:{delivery:'steer',autoReviewUserText:text}});
+ }
+ s.sessionHistory = s.history;
+ const resolve = createPluginTaskReviewResolver(async () => s);
+ expect((await resolve({...request,userIntent:live})).authorizationError).toBeUndefined();
+ expect((await resolve({...request,userIntent:appendAutoReviewUserIntent(live,'Stop now')})).authorizationError).toContain('not synchronized');
+ expect((await resolve({...request,userIntent:''})).authorizationError).toContain('not synchronized');
+ });
it.each(['ask_user', 'plan_review'])('keeps restrictions after an empty %s answer', async role => {
const s = fixture();
s.history = [
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 0cc7cca4d1..cc8ad2af69 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -1551,6 +1551,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
uuid: so.messageUuid,
...(so.origin?.kind === 'scheduler'
? { autoReviewUserText: { kind: 'scheduled-continuation' } }
+ : so[AUTO_REVIEW_DELEGATED_CONTINUATION]
+ ? { autoReviewUserText: { kind: 'delegated-continuation' } }
: trustedUserText !== undefined ? { autoReviewUserText: trustedUserText } : {}),
sdkSessionId: persistUserMessage.sdkSessionId,
...(persistUserMessage.delivery
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bb319b5605..67cb71bf4e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -13059,7 +13059,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const readAutoReviewHistory = async (sessionId: string) => {
await drainPersistQueue();
- return listMessagesForAgentHandoff(sessionId, 100, undefined, 'authorization');
+ return listMessagesForAgentHandoff(sessionId, null, undefined, 'authorization');
};
setAutoReviewContextResolver(createPluginTaskReviewResolver(async sessionId => {
const epoch = getCurrentDbClientSnapshot();
@@ -13112,7 +13112,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...(link ? { worker: { label: link.label ?? '', activeTeam: link.teamStatus === 'active' } } : {}),
history: histories.flat().filter(m => ['user','ask_user','plan_review'].includes(m.role)),
sessionHistory: histories[historySessionIds.indexOf(sessionId)]!,
- historyComplete: histories.every(h => h.length < 100),
+ historyComplete: true,
};
}));
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index ae1c619ad9..2fd5a229b6 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -119,7 +119,7 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedul
beforeDispatchUserTurn: deps.beforeDispatchUserTurn,
readAutoReviewHistory: async (sessionId) => {
await drainPersistQueue();
- return listMessagesForAgentHandoff(sessionId, 100, undefined, 'authorization');
+ return listMessagesForAgentHandoff(sessionId, null, undefined, 'authorization');
},
onUndispatchedUserTurn: deps.onUndispatchedUserTurn,
acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend,