Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): preserve legacy task declarations and order receipt pages
Dashc32063dd0c55
diff --git a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts b/apps/desktop/src/main/__tests__/installedGhostManifest.test.tsindex 44f127ec8e..9a42895e30 100644--- a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts+++ b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts@@ -248,3 +248,8 @@ describe('installed ghost manifest compatibility', () => {).not.toHaveProperty('errand');});});++it.each(['future', { future: true }, null, false])('preserves installed unknown tasks %j alongside legacy manual metadata', (tasks) => {+ const result = parseInstalledGhostManifest({...manifest(),slots:['tool','agent'],agent:{tasks},manual:'old metadata'});+ expect(result).toMatchObject({ok:true,legacyManualIgnored:true,manifest:{agent:{tasks}}});+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex c27b73b1aa..378b5f27a9 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -308,6 +308,19 @@ describe('hashApprovedSkillContent · item.dir 路径段校验', () => {});describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {+ it.each(['future', { future: true }, ['future'], null, false])('keeps historical unknown tasks %j enabled without task approval', async (tasks) => {+ await writeLegacyInstall('hello', {...goodManifest(), slots:['tool','agent'], agent:{tasks}});+ await manager.migrateLegacyApprovalsOnce();+ const old = manager.list()[0];+ expect(old).toMatchObject({enabled:true, manifest:{agent:{tasks}}, approval:{state:'approved'}});+ expect(old.taskCapabilityApproved).toBeUndefined();+ if (old.approval.state !== 'approved') throw new Error('fixture not approved');+ expect(await manager.approveTaskCapability('hello', old.approval.revision, () => true)).toBe(false);+ await manager.setEnabled('hello', false);+ await manager.setEnabled('hello', true);+ expect(manager.list()[0]).toMatchObject({enabled:true,manifest:{agent:{tasks}},approval:old.approval});+ expect(manager.list()[0].taskCapabilityApproved).toBeUndefined();+ });it('keeps legacy tasks data inert, persists only explicit approval, and preserves it through enable and update', async () => {const manifest = {...goodManifest(), slots:['tool','agent'], agent:{tasks:true}};await writeLegacyInstall('hello', manifest);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex 1b7a64f220..6842e0cb7e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -172,6 +172,23 @@ describe('GhostInstallReceiptStore cleanup', () => {expect(fs.existsSync(path.join(stateRoot, 'hello.json'))).toBe(false);});+ it.each(['future', { future: true }, null, false])('reads and rewrites old unknown tasks %j without changing approval evidence', async (tasks) => {+ const original = createSetupReceipt();+ await store.write(original);+ const file = path.join(stateRoot, 'hello.json');+ const raw = JSON.parse(await fs.promises.readFile(file, 'utf8'));+ raw.manifest.slots.splice(1, 0, 'agent');raw.manifest.agent = { tasks };+ await fs.promises.writeFile(file, JSON.stringify(raw));+ const loaded = store.read('hello');+ expect(loaded.state).toBe('approved');+ if (loaded.state !== 'approved') throw new Error('fixture not approved');+ expect(loaded.receipt).toMatchObject({revision:original.revision,enabled:true,manifest:{agent:{tasks}},skillContentSha256:original.skillContentSha256});+ expect(loaded.receipt.taskCapabilityApproved).toBeUndefined();+ await store.write(loaded.receipt);+ const saved = JSON.parse(await fs.promises.readFile(file, 'utf8'));+ expect(saved).toEqual(raw);+ });+it('writes setup in the author format accepted by the v0.1.48 receipt reader', async () => {const receipt = createSetupReceipt();await store.write(receipt);diff --git a/apps/desktop/src/main/installedGhostManifest.ts b/apps/desktop/src/main/installedGhostManifest.tsindex c633f4028a..c9fb9bc156 100644--- a/apps/desktop/src/main/installedGhostManifest.ts+++ b/apps/desktop/src/main/installedGhostManifest.ts@@ -3,7 +3,7 @@ import path from 'node:path';import {ghostManifestToLegacyV2DigestFormat,- validateGhostManifest,+ validateInstalledGhostManifest,type GhostManifest,} from '../shared/ghost.js';import { readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';@@ -39,14 +39,14 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {* manifests; package/Forge validation remains strict via validateGhostManifest.*/export function parseInstalledGhostManifest(raw: unknown): InstalledGhostManifestParse {- const strict = validateGhostManifest(raw);+ const strict = validateInstalledGhostManifest(raw);if (strict.ok) return { ok: true, manifest: strict.manifest, legacyManualIgnored: false };if (!isPlainObject(raw) || !Object.prototype.hasOwnProperty.call(raw, 'manual')) {return { ok: false, reason: strict.reason };}const withoutLegacyManual = { ...raw };delete withoutLegacyManual.manual;- const compatible = validateGhostManifest(withoutLegacyManual);+ const compatible = validateInstalledGhostManifest(withoutLegacyManual);return compatible.ok? { ok: true, manifest: compatible.manifest, legacyManualIgnored: true }: { ok: false, reason: compatible.reason };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.tsnew file mode 100644index 0000000000..2f482cd981--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts@@ -0,0 +1,28 @@+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 { createPluginTaskStore } from '../pluginTaskStore.js';++it('pages by creation time and ID without losing later records with smaller UUIDs', 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 add = sqlite.prepare('INSERT INTO plugin_task_requests VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)');+ for (const operation of ['create', 'send']) {+ const prefix = operation + '-';+ const target = operation === 'send' ? 'task' : null;+ const insert = (id: string, time: number, plugin = 'p') => add.run(prefix + id, plugin, operation, 'task', id, 'h', '{}', time);+ insert('z', 1);insert('y', 1);+ expect((await store.list('p', operation, target, '', 1)).map(r => r.id)).toEqual([prefix + 'y']);+ expect((await store.list('p', operation, target, prefix + 'y', 1)).map(r => r.id)).toEqual([prefix + 'z']);+ insert('a', 2);insert('b', 3, 'other');+ expect((await store.list('p', operation, target, prefix + 'z', 10)).map(r => r.id)).toEqual([prefix + 'a']);+ await expect(store.list('other', operation, target, prefix + 'z', 10)).rejects.toMatchObject({ code: 'INVALID_REQUEST' });+ await expect(store.list('p', operation, 'different', prefix + 'z', 10)).rejects.toMatchObject({ code: 'INVALID_REQUEST' });+ }+ } finally { sqlite.close(); }+});diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts b/apps/desktop/src/main/maker-ipc/pluginTaskStore.tsindex 1510534968..d028640836 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts@@ -1,7 +1,8 @@-import { and, asc, eq, gt } from 'drizzle-orm';+import { and, asc, eq, gt, or } from 'drizzle-orm';import type { DbClient } from '../localDb/client/DbClient.js';import { pluginTaskRequests } from '../localDb/schema.js';import type { PluginTaskStore } from './pluginTaskService.js';+import { PluginTaskError } from './pluginTaskService.js';/** Captures the DB handle once, so a delayed operation never switches accounts. */export function createPluginTaskStore(db: DbClient): PluginTaskStore {@@ -23,20 +24,30 @@ export function createPluginTaskStore(db: DbClient): PluginTaskStore {).limit(1))[0],- list: (pluginId, operation, targetId, after, limit) =>- db.drizzle+ list: async (pluginId, operation, targetId, after, limit) => {+ const scope = and(+ eq(table.pluginId, pluginId),+ eq(table.operation, operation as 'create' | 'send'),+ targetId === null ? undefined : eq(table.targetId, targetId),+ );+ // Keep the existing opaque receipt-ID cursor, resolving its ordering key+ // within the same plugin and target without loading its payload.+ const [cursor] = after ? await db.drizzle.select({ createdAt: table.createdAt })+ .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().from(table).where(and(- eq(table.pluginId, pluginId),- eq(table.operation, operation as 'create' | 'send'),- targetId === null ? undefined : eq(table.targetId, targetId),- gt(table.id, after),+ scope,+ cursor ? or(gt(table.createdAt, cursor.createdAt),+ and(eq(table.createdAt, cursor.createdAt), gt(table.id, after))) : undefined,),)- .orderBy(asc(table.id))- .limit(limit),+ .orderBy(asc(table.createdAt), asc(table.id))+ .limit(limit);+ },forSession: (taskId) =>db.drizzle.select()diff --git a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts b/apps/desktop/src/shared/__tests__/ghost.tasks.test.tsindex 8aa9ca0700..2658674709 100644--- a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts@@ -3,6 +3,9 @@ import {ghostManifestToLegacyV2DigestFormat,ghostPermissionItems,validateGhostManifest,+ validateNormalizedGhostManifest,+ validateInstalledGhostManifest,+ ghostManifestToAuthorFormat,} from '../ghost.js';const base = {@@ -33,3 +36,15 @@ describe('plugin tasks permission compatibility', () => {expect(projected.agent).toEqual({ errand: true });});});++it.each(['future', { future: true }, ['future'], null, false])('retains historical tasks %j without granting it', (tasks) => {+ const raw = { ...base, agent: { tasks } };+ const result = validateInstalledGhostManifest(raw);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.manifest.agent).toEqual({ tasks });+ expect(ghostPermissionItems(result.manifest).some(item => item.key === 'agent:tasks')).toBe(false);+ const again = validateNormalizedGhostManifest(ghostManifestToAuthorFormat(result.manifest));+ expect(again.ok && again.manifest).toEqual(result.manifest);+ expect(validateGhostManifest(raw).ok).toBe(false);+});diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 814a80597b..ae91fc83e0 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -3758,6 +3758,15 @@ export function resolveGhostManifestLocale(* 顶层字段原样保留但不解释、不展示、不授权。任何已知字段不合格都给出 reason。*/export function validateGhostManifest(value: unknown): ManifestValidation {+ return validateGhostManifestInput(value, false);+}++/** Installed snapshots retain historical unknown tasks data without granting it. */+export function validateInstalledGhostManifest(value: unknown): ManifestValidation {+ return validateGhostManifestInput(value, true);+}++function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boolean): ManifestValidation {const preparation = prepareGhostManifestForValidation(value);if (!preparation.ok) return preparation;const prepared = preparation.prepared;@@ -4316,13 +4325,13 @@ export function validateGhostManifest(value: unknown): ManifestValidation {if (agentRaw.errand !== undefined && typeof agentRaw.errand !== 'boolean') {return { ok: false, reason: 'agent.errand 必须是布尔值' };}- if (agentRaw.tasks !== undefined && typeof agentRaw.tasks !== 'boolean') {+ if (!preserveHistoricalTasks && agentRaw.tasks !== undefined && typeof agentRaw.tasks !== 'boolean') {return { ok: false, reason: 'agent.tasks must be boolean' };}if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {return { ok: false, reason: 'agent.schedule 必须是布尔值' };}- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks'])).length === 0) {+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks'])).length === 0) {return {ok: false,reason:@@ -4330,7 +4339,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {};}agent = {- ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks']),+ ...unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks']),...(agentRaw.background === true ? { background: true } : {}),...(agentRaw.errand === true ? { errand: true } : {}),...(agentRaw.tasks === true ? { tasks: true } : {}),@@ -5997,7 +6006,7 @@ export function validateNormalizedGhostManifest(raw: unknown): ManifestValidatio// after a rollback. Still accept normalized snapshots produced by affected dev// builds and passed between current Host code paths.const authorInput = isPlainObject(raw) ? withLegacyAuthorSlots(raw) : raw;- const authorResult = validateGhostManifest(authorInput);+ const authorResult = validateInstalledGhostManifest(authorInput);if (authorResult.ok || !isPlainObject(raw) || raw.setup === undefined) return authorResult;if (!isPlainObject(raw.setup) || !Array.isArray(raw.setup.requires)) {return { ok: false, reason: '标准化清单 setup 必须是带 requires 数组的对象' };@@ -6029,7 +6038,7 @@ export function validateNormalizedGhostManifest(raw: unknown): ManifestValidatiorequires.push({ anyOf });}- return validateGhostManifest({ ...withLegacyAuthorSlots(raw), setup: { requires } });+ return validateInstalledGhostManifest({ ...withLegacyAuthorSlots(raw), setup: { requires } });}/** 把无 slots 的 v2 运行时投影还原成旧客户端能读取的作者清单。 */diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex c6d70800e9..c1370b8442 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -10,7 +10,7 @@- 发送走普通输入协调器,使用持久 requestKey 去重和稳定输入 ID;重复请求不会再次启动模型。- 指定 provider、model、effort、Fast 必须通过当前目录核验;派发前再次核验,不静默 fallback。- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。-- 读取限定于本插件创建的任务;返回消息 clientId,分页游标仍使用数据库稳定游标。+- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。