Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
merge: sync approved plugin uninstall ownership and preserve Auto gates
Dash1163d34f17f1
diff --cc apps/desktop/src/main/cindy-brain/index.tsindex 10a149e217,4376381482..f9d506196d--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -1722,14 -1722,9 +1722,16 @@@ export function setGhostSessionRevealerlet pluginTaskHandler: PluginTaskHandler | null = null;export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }+ let pluginTaskUninstaller: ((pluginId: string, remove: () => Promise<void>) => Promise<void>) | null = null;+ export function setPluginTaskUninstaller(handler: typeof pluginTaskUninstaller): void { pluginTaskUninstaller = handler; }+/** Approval revision participates in Auto decision cache identity (including reinstall/update). */+export function pluginTaskAuthorizationRevision(id: string): string | null {+ const ghost = findAvailableGhost(id);+ return ghost?.enabled && ghost.manifest.agent?.tasks && ghost.approval.state === 'approved'+ ? ghost.approval.revision : null;+}+export function isPluginTaskAuthorized(id: string): boolean {const ghost = findAvailableGhost(id);return hasPluginTaskApproval(ghost);diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex cdde88dc00,df141e8aff..d64dbaec82--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@@ -12,20 -11,8 +12,44 @@@ importtype PluginTaskServiceDeps,} from '../pluginTaskService.js';import type { PluginTaskView } from '../../../shared/pluginTasks.js';+ import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from '../sessionExecutionOwnership.js';+import { PLUGIN_TEAM_PLAN_MAX_JSON_CHARS, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';++it('rejects oversized plans before saving and refuses oversized legacy receipts without truncation', async () => {+ const f=fixture(), task=await f.create();+ const before=structuredClone(f.rows.get(task.taskId)!);+ const plan={concurrency:2,items:Array.from({length:200},(_,i)=>({label:'w'+i,workingDir:'/answer',route:f.route,task:'x'.repeat(8000)}))};+ await expect(f.service.setTeamPlan('p',task.taskId,plan)).rejects.toMatchObject({code:'INVALID_REQUEST'});+ expect(f.rows.get(task.taskId)).toEqual(before);+ for (const payload of [' '.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS+1), JSON.stringify({teamPlan:{task:'x'.repeat(PLUGIN_TEAM_PLAN_MAX_JSON_CHARS)}})])+ expect(()=>readPluginTaskPlanReceipt(payload)).toThrow('size');+ f.rows.get(task.taskId)!.payload=JSON.stringify({teamPlan:plan});+ await expect(f.service.settleWorkerLabel('p',task.taskId,'w0')).rejects.toMatchObject({code:'INVALID_REQUEST'});+});+++it.each([false,true])('production Auto context checks uninstall after its projection await (worker=%s)', async worker => {++ for (const revoked of [false,true]) {++ const f=fixture(),task=await f.create();++ const session={...f.route,source:'plugin',workingDir:'/answer',permissionMode:'auto',status:'active'};++ const results=[[session],worker?[{leadId:task.taskId,label:'w',teamId:'team',teamStatus:'active'}]:[],[session]];++ const query={from:()=>query,where:()=>query,innerJoin:()=>query,limit:async()=>results.shift()};++ const epoch={client:{drizzle:{select:()=>query},tx:async()=>{if(revoked)await f.service.withUninstall('p',async()=>{});return {};}}};++ let load!:(id:string)=>Promise<unknown>;++ const deps={setAutoReviewContextResolver:(callback:typeof load)=>{load=callback;},createPluginTaskReviewResolver:(callback:typeof load)=>callback,++ getCurrentDbClientSnapshot:()=>epoch,sessions:{},orcaWorkers:{},orcaTeams:{},eq:()=>true,++ createPluginTaskStore:()=>f.deps.store,drainPersistQueue:async()=>{},++ pluginTaskServiceForCurrentOwner:()=>f.service,readGhostErrandConfig:()=>({permissionMode:'auto'}),++ readPluginTaskPlanReceipt,pluginTaskAuthorizationRevision:()=> 'new-install',isPluginTaskAuthorized:()=>true};++ const source=readFileSync(new URL('../register.ts',import.meta.url),'utf8');++ const start=source.indexOf(' setAutoReviewContextResolver(createPluginTaskReviewResolver(async sessionId => {');++ const block=source.slice(start,source.indexOf('\n }));',start)+7);++ const js=ts.transpileModule(block,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;++ new Function(...Object.keys(deps),js)(...Object.values(deps));++ if(revoked)await expect(load(worker?'worker':task.taskId)).rejects.toMatchObject({code:'TASK_NOT_FOUND'});++ else await expect(load(worker?'worker':task.taskId)).resolves.toMatchObject({authorized:true,pluginId:'p'});++ }++});+function fixture() {let seq = 0;let current = true;diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStoreBudget.test.tsindex 2f7e3cbe5f,0000000000..11b25fb638mode 100644,000000..100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStoreBudget.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStoreBudget.test.ts@@@ -1,49 -1,0 +1,47 @@@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { expect, it } from 'vitest';+import type { DbClient } from '../../localDb/client/DbClient.js';+import { PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';+import { createPluginTaskStore } from '../pluginTaskStore.js';++it('rejects persisted oversized receipts with SQLite selection, including UTF-16 expansion', async () => {+ const sqlite = new Database(':memory:');+ try {+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,+ revision INTEGER, created_at INTEGER)`);+ const store = createPluginTaskStore({ drizzle: drizzle(sqlite) } as unknown as DbClient);+ const insert = sqlite.prepare('INSERT INTO plugin_task_requests VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1)');+ insert.run('small', 'p', 'create', 'small', 'small', 'h', '{}');+ insert.run('large', 'p', 'create', 'large', 'large', 'h', 'x'.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS + 1));+ insert.run('unicode', 'p', 'create', 'unicode', 'unicode', 'h', '😀'.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS));+ expect((await store.get('small'))?.payload).toBe('{}');+ expect(await store.get('missing')).toBeUndefined();+ await expect(store.get('large')).rejects.toMatchObject({ code: 'INVALID_REQUEST' });+ await expect(store.get('unicode')).rejects.toMatchObject({ code: 'INVALID_REQUEST' });+ expect(sqlite.prepare('SELECT count(*) AS n FROM plugin_task_requests').get()).toEqual({ n: 3 });+ } finally { sqlite.close(); }+});++it('omits creation payloads in SQL while preserving pagination, ownership and run receipts', async () => {+ const sqlite = new Database(':memory:');- const queries: string[] = [];+ try {+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,+ revision INTEGER, created_at INTEGER)`);- const db = drizzle(sqlite, { logger: { logQuery(query) { queries.push(query); } } });++ const db = drizzle(sqlite);+ const store = createPluginTaskStore({ drizzle: db } as unknown as DbClient);+ const insert = sqlite.prepare('INSERT INTO plugin_task_requests VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1)');- const large = 'x'.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS);++ const large = JSON.stringify({plan:'x'.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS - 11)});+ for (const id of ['a', 'b', 'c']) insert.run(id, 'p', 'create', id, id, 'h', large);+ insert.run('other', 'other-plugin', 'create', 'other', 'other', 'h', large);+ insert.run('run', 'p', 'send', 'b', 'run', 'h', '{"status":"completed"}');+ const page = await store.list('p', 'create', null, '', 2);+ expect(page.map(row => [row.id, row.payload])).toEqual([['a', ''], ['b', '']]);- expect(queries.at(-1)?.split(' from ')[0]).not.toContain('"payload"');+ expect((await store.list('p', 'create', null, 'b', 2)).map(row => row.id)).toEqual(['c']);+ expect((await store.list('p', 'send', 'b', '', 2))[0]?.payload).toBe('{"status":"completed"}');+ expect(await store.list('p', 'send', 'a', '', 2)).toEqual([]);+ expect((await store.get('a'))?.payload).toBe(large);+ } finally { sqlite.close(); }+});diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.tsindex 2f482cd981,e18ebdf653..e8931c34f3--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts@@@ -3,6 -3,30 +3,39 @@@ import { drizzle } from 'drizzle-orm/beimport { expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';import { createPluginTaskStore } from '../pluginTaskStore.js';++import { createPluginTaskService } from '../pluginTaskService.js';++ it('durably revokes only create ownership while retaining plans, run results and request identities', async () => {+ const sqlite=new Database(':memory:');+ try {+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,+ revision INTEGER, created_at INTEGER)`);+ const db={drizzle:drizzle(sqlite)} as unknown as DbClient;+ const store=createPluginTaskStore(db);+ const add=sqlite.prepare('INSERT INTO plugin_task_requests VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1)');+ add.run('task','p','create','','original','hash',JSON.stringify({title:'keep',teamPlan:{items:[]}}));+ add.run('broken','p','create','','broken-key','hash','{bad');+ add.run('run','p','send','task','send-key','hash','{"status":"completed"}');+ add.run('other','q','create','','other-key','hash','{}');++ const route={agentKind:'codex' as const,providerId:'test',model:'test',effort:'high',fastMode:false};++ const unused=async():Promise<never>=>{throw Error('unexpected dispatch/control');};++ const service=createPluginTaskService({store,assertCurrent(){},assertAuthorized(){},++ readSession:async taskId=>({taskId,title:'kept',revision:1,status:'active',resolvedConfig:route,permissionMode:'plan'}),++ readPermissionMode:()=> 'plan',resolveRoute:unused,createSession:unused,dispatch:unused,inspect:unused,cancel:unused,++ });++ expect((await service.list('p')).items.map(row=>row.taskId)).toEqual(['task']);+ await store.revokePlugin('p');++ expect((await service.list('p')).items).toEqual([]);+ const restarted=createPluginTaskStore(db);+ const row=await restarted.find('p','create','','original');+ expect(row).toMatchObject({id:'task',requestKey:'original',revision:1});+ expect(JSON.parse(row!.payload)).toEqual({title:'keep',teamPlan:{items:[]},ownershipRevoked:true});+ expect(JSON.parse((await restarted.get('broken'))!.payload)).toEqual({ownershipRevoked:true});+ expect(await restarted.get('run')).toMatchObject({payload:'{"status":"completed"}',revision:0});+ expect(await restarted.get('other')).toMatchObject({payload:'{}',revision:0});+ } finally { sqlite.close(); }+ });it('pages by creation time and ID without losing later records with smaller UUIDs', async () => {const sqlite = new Database(':memory:');diff --cc apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex 818d5166d1,29b41bf0e5..ae6edf32ec--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@@ -277,6 -287,7 +300,8 @@@ export function createPluginTaskServiceconst rows = await deps.store.list(pluginId, 'create', null, after, limit);const items = [];for (const row of rows) {- if (!ownsTaskReceipt(row, pluginId)) continue;++ // The store projects valid create payloads as empty to avoid loading plans.++ if (row.payload !== '' && !ownsTaskReceipt(row, pluginId)) continue;const view = await deps.readSession(row.id);if (view && view.status !== 'deleted') items.push(view);}diff --cc apps/desktop/src/main/maker-ipc/pluginTaskStore.tsindex 31398238e6,f2320d8475..33c33c95f3--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts@@@ -45,13 -36,7 +45,12 @@@ export function createPluginTaskStore(d.from(table).where(and(scope, eq(table.id, after))).limit(1) : [];if (after && !cursor) throw new PluginTaskError('INVALID_REQUEST', 'Invalid task cursor');return db.drizzle- .select()+ .select({+ ...getTableColumns(table),- // Task listing only needs receipt IDs to read session views. Keep- // large creation plans inside SQLite; run listing still reconciles- // send payloads and therefore must retain them.- payload: operation === 'create' ? sql<string>`''` : table.payload,++ // Keep valid creation plans inside SQLite. Project only revocation++ // (including malformed receipts), never the potentially large plan.++ payload: operation === 'create' ? sql<string>`CASE WHEN json_valid(${table.payload}) THEN CASE WHEN json_type(${table.payload}) = 'object' AND coalesce(json_type(${table.payload}, '$.ownershipRevoked'), 'null') != 'true' THEN '' ELSE '{"ownershipRevoked":true}' END ELSE '{"ownershipRevoked":true}' END` : table.payload,+ }).from(table).where(and(diff --cc apps/desktop/src/main/maker-ipc/register.tsindex 71a41eaf45,f1d7f8f242..a4a53075c2--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -5,7 -4,7 +5,7 @@@ import { PluginWriteAccessGate } from 'import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';import { createPluginTaskStore } from './pluginTaskStore.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';- import { setPluginTaskHandler, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';-import { setPluginTaskHandler, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision } from '../cindy-brain/index.js';++import { setPluginTaskHandler, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';import { createHash as pluginTaskConfigHash } from 'node:crypto';import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';@@@ -13447,64 -13411,8 +13444,67 @@@ export function registerMakerIpc(makerconst 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();+ if (!epoch) throw new Error('Task storage unavailable');+ const db = epoch.client.drizzle;+ const [session] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);+ if (!session) throw new Error('Task unavailable');+ // Ordinary tasks do not depend on plugin receipt storage. Worker ownership+ // is checked through its lead before touching the plugin task store.+ if (session.source !== 'plugin' && session.orcaRole !== 'worker') {+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');+ return null;+ }+ const [link] = await db.select({ label: orcaWorkers.label, leadId: orcaTeams.leadSessionId,+ teamId: orcaTeams.id, teamStatus: orcaTeams.status }).from(orcaWorkers)+ .innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))+ .where(eq(orcaWorkers.sessionId, sessionId)).limit(1);+ const leadId = link?.leadId ?? sessionId;+ const [lead] = await db.select().from(sessions).where(eq(sessions.id, leadId)).limit(1);+ if (!lead) throw new Error('Lead unavailable');+ if (lead.source !== 'plugin') {+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');+ return null;+ }+ const store = createPluginTaskStore(epoch.client);+ const receipt = await store.get(leadId);+ if (!receipt || receipt.operation !== 'create') {+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');+ return null;+ }+ if (!session || !lead || !session.workingDir) throw new Error('Delegated task unavailable');+ const agentKind = session.agentKind === 'cc' ? 'cc' : session.agentKind === 'pi' ? 'pi' : session.agentKind === 'codex' ? 'codex' : null;+ if (!agentKind) throw new Error('Delegated task route unavailable');+ await drainPersistQueue();+ const projection = await epoch.client.tx('authorization.readProjection', { sessionId, leadId });++ // Reinstall must not revive the old Lead's delegated authority, including++ // requests that were already waiting for history/projection reads at uninstall.++ await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId, leadId);+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');+ const config = readGhostErrandConfig(receipt.pluginId);+ const data = readPluginTaskPlanReceipt(receipt.payload);+ const approvalRevision = pluginTaskAuthorizationRevision(receipt.pluginId);+ return {+ pluginId: receipt.pluginId,+ authorized: approvalRevision !== null && isPluginTaskAuthorized(receipt.pluginId) && config.permissionMode === 'auto',+ revision: [epoch.userId, epoch.clientEpoch, approvalRevision, config.permissionMode, link],+ plan: data.teamPlan, settledLabels: data.settledLabels,+ registeredRoute: data.route,+ session: { workingDir: session.workingDir, permissionMode: session.permissionMode, status: session.status,+ route: { agentKind, providerId: session.providerId ?? '', model: session.model,+ effort: session.effort, fastMode: !!session.fastMode } },+ lead: { permissionMode: lead.permissionMode, status: lead.status },+ ...(link ? { worker: { label: link.label ?? '', activeTeam: link.teamStatus === 'active' } } : {}),+ projection,+ history: [],+ sessionHistory: [],+ historyComplete: true,+ };+ }));+const { sendToAgentAccepted: sendToAgentAcceptedUnlocked } = createMakerSendTransaction({prepareProductTurn: (sessionId) => {const dispatch = prepareUpstreamMergeTurn(sessionId);