Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): preserve permission and attachment state
Chrisb154dca0413c
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 1cd05ad432..39f5aa9e4c 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -962,6 +962,11 @@ function treeEntryUuid(agentMeta) {return parsed && typeof parsed.uuid === 'string' && parsed.uuid ? parsed.uuid : null;}+function linkedPiEntryId(agentMeta) {+ const parsed = parsedTreeObjectJson(agentMeta);+ return parsed && typeof parsed.piEntryId === 'string' && parsed.piEntryId ? parsed.piEntryId : null;+}+function normalizedTreeUserText(content) {const parsed = parsedTreeObjectJson(content);if (!parsed || typeof parsed.text !== 'string') return null;@@ -1021,13 +1026,16 @@ function sessionTreeRehydrate(readyDb, args) {const session = readyDb.prepare('SELECT id FROM sessions WHERE id = ? LIMIT 1').get(sessionId);if (!session) throw Object.assign(new Error('Session 不存在: ' + sessionId), { code: 'NOT_FOUND' });// Keep this fallback mirror in sync with worker/opHandlers/tx.ts: preserve only- // Cindy-managed attachments matched by stable id/uuid or a verified visible prefix.+ // Cindy-managed attachments matched by stable id/uuid/piEntryId or a verified visible prefix.const attachmentSources = selectUserAttachmentSources.all(sessionId);const byClientId = new Map(attachmentSources.map((row) => [row.client_id, row]));const byUuid = new Map();+ const byLinkedPiEntryId = new Map();for (const source of attachmentSources) {const uuid = treeEntryUuid(source.agent_meta);if (uuid) byUuid.set(uuid, source);+ const piEntryId = linkedPiEntryId(source.agent_meta);+ if (piEntryId) byLinkedPiEntryId.set(piEntryId, source);}const visibleUserSources = attachmentSources.filter((row) => row.rewind_at === null);let visiblePrefixIndex = 0;@@ -1039,7 +1047,10 @@ function sessionTreeRehydrate(readyDb, args) {let content = row.content;if (row.role === 'user') {const uuid = treeEntryUuid(row.agentMeta);- let source = byClientId.get(row.clientId) || (uuid ? byUuid.get(uuid) : null) || null;+ let source = byClientId.get(row.clientId)+ || (uuid ? byUuid.get(uuid) : null)+ || (uuid ? byLinkedPiEntryId.get(uuid) : null)+ || null;const candidate = visibleUserSources[visiblePrefixIndex] || null;if (source && visiblePrefixIntact && source !== candidate) {visiblePrefixIntact = false;diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex eff0aaca06..0c6323fcbb 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -679,7 +679,7 @@ describe('db worker tx handlers', () => {VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,['original-user', 'original-client', 's1', 'user', JSON.stringify(original),- JSON.stringify({ uuid: 'pi-user-entry' }), 'pi', 100, null,+ JSON.stringify({ uuid: 'host-message-uuid', piEntryId: 'pi-user-entry' }), 'pi', 123, null,],);@@ -690,6 +690,8 @@ describe('db worker tx handlers', () => {// Pi's transcript keeps only model-consumable blocks; the native image is a placeholder.content: JSON.stringify({ text: 'Review these assets\n\n[image]' }),toolUseId: null, agentMeta: JSON.stringify({ uuid: 'pi-user-entry' }),+ // DB createdAt=123 and Pi timestamp=100 are intentionally different: first navigation+ // must restore by the persisted piEntryId, not by timestamp coincidence.agentKind: 'pi', createdAt: 100,}],});diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex b4a64a48cc..12a203eee5 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -642,6 +642,11 @@ function treeEntryUuid(agentMeta: string | null): string | null {return typeof uuid === 'string' && uuid.length > 0 ? uuid : null;}+function linkedPiEntryId(agentMeta: string | null): string | null {+ const piEntryId = parsedObjectJson(agentMeta)?.piEntryId;+ return typeof piEntryId === 'string' && piEntryId.length > 0 ? piEntryId : null;+}+function normalizedTreeUserText(content: string): string | null {const parsed = parsedObjectJson(content);if (!parsed || typeof parsed.text !== 'string') return null;@@ -725,14 +730,18 @@ function sessionTreeRehydrate(const session = db.prepare('SELECT id FROM sessions WHERE id = ? LIMIT 1').get(sessionId);if (!session) throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });// 在隐藏前冻结附件来源。历史投影行(含已 rewind 的其它分支)按稳定 clientId / Pi- // entry uuid 精确复用;首次导航的旧 live 行没有稳定 id 时,只允许“可见公共前缀中+ // entry uuid 精确复用;首次导航按发送时持久化的 piEntryId 关联。旧 live 行没有关联时,+ // 只允许“可见公共前缀中// 文本和原始时间戳都一致”的保守回退,避免相同文字的另一分支附件串线。const attachmentSources = selectUserAttachmentSources.all(sessionId) as TreeAttachmentSourceRow[];const byClientId = new Map(attachmentSources.map((row) => [row.client_id, row]));const byUuid = new Map<string, TreeAttachmentSourceRow>();+ const byLinkedPiEntryId = new Map<string, TreeAttachmentSourceRow>();for (const source of attachmentSources) {const uuid = treeEntryUuid(source.agent_meta);if (uuid) byUuid.set(uuid, source);+ const piEntryId = linkedPiEntryId(source.agent_meta);+ if (piEntryId) byLinkedPiEntryId.set(piEntryId, source);}const visibleUserSources = attachmentSources.filter((row) => row.rewind_at === null);let visiblePrefixIndex = 0;@@ -747,7 +756,10 @@ function sessionTreeRehydrate(let content = row.content;if (row.role === 'user') {const uuid = treeEntryUuid(row.agentMeta);- let source = byClientId.get(row.clientId) ?? (uuid ? byUuid.get(uuid) : undefined) ?? null;+ let source = byClientId.get(row.clientId)+ ?? (uuid ? byUuid.get(uuid) : undefined)+ ?? (uuid ? byLinkedPiEntryId.get(uuid) : undefined)+ ?? null;const candidate = visibleUserSources[visiblePrefixIndex] ?? null;if (source && visiblePrefixIntact && source !== candidate) {// 已经精确命中另一个历史分支,说明公共可见前缀在这里结束;后续消息不能diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 2b543e28b5..2b15e2c2b0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -1,4 +1,4 @@-import type { AgentKind, SessionSendResult, UserMessage } from '@cindy/maker-core';+import type { AgentKind, SessionSendOptions, SessionSendResult, UserMessage } from '@cindy/maker-core';import { describe, expect, it, vi } from 'vitest';import {createMakerSendTransaction,@@ -17,9 +17,10 @@ function createSession(overrides: Partial<MakerSendTransactionSession> = {}): MaisTurnRunning: vi.fn(() => false),send: vi.fn(async (_message: UserMessage | string,- opts?: { onAccepted?: () => Promise<void>; onDispatching?: () => void },+ opts?: SessionSendOptions,) => {await opts?.onAccepted?.();+ await opts?.onTranscriptUserEntry?.('pi-user-entry');opts?.onDispatching?.();return { accepted: true } satisfies SessionSendResult;}),@@ -55,6 +56,7 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {broadcastSessionCreated: vi.fn(),prepareSendUserMessage: vi.fn(async (_sessionId, message) => message as UserMessage | string),createDbMessage: vi.fn(async () => {}),+ linkPiUserEntry: vi.fn(async () => true),previewUserPrompt: vi.fn(),dispatchUserPromptPreview: vi.fn(),commitUserPromptPreview: vi.fn(),@@ -153,6 +155,48 @@ describe('maker SEND transaction', () => {expect(deps.rollbackUserPromptPreview).not.toHaveBeenCalled();});+ it('links attachment messages to the accepted Pi transcript entry only for Pi attachments', async () => {+ const { deps, session } = createDeps();+ session.agentKind = 'pi';+ const transaction = createMakerSendTransaction(deps);++ await transaction.sendToAgentAccepted(+ 'session-1',+ { type: 'user', content: 'Review the image' },+ undefined,+ {+ messageUuid: 'host-message',+ persistUserMessage: {+ clientId: 'attachment-client',+ content: JSON.stringify({+ text: 'Review the image',+ images: [{ url: 'cindy-media://blobs/image.webp' }],+ }),+ },+ },+ );++ expect(deps.linkPiUserEntry).toHaveBeenCalledWith(+ 'session-1',+ 'attachment-client',+ 'pi-user-entry',+ );++ await transaction.sendToAgentAccepted(+ 'session-1',+ { type: 'user', content: 'Plain text' },+ undefined,+ {+ messageUuid: 'plain-message',+ persistUserMessage: {+ clientId: 'plain-client',+ content: JSON.stringify({ text: 'Plain text', images: [], files: [] }),+ },+ },+ );+ expect(deps.linkPiUserEntry).toHaveBeenCalledTimes(1);+ });+it('threads scheduler origin into session.send opts and persisted agentMeta', async () => {// scheduler 排队消息经 coordinator drain 透传 origin(见 AgentInputSendOpts.origin):// 既打到本轮 turnOrigin(session.send opts),也合进落库 agentMeta(自动化标签)。diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 679992efe6..0ab5827874 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -123,6 +123,12 @@ export interface MakerSendTransactionDeps {},opts?: { shouldBroadcast?: () => boolean },): Promise<unknown>;+ /** 把 Pi 原生 user entry id 补到已落库的 Cindy user 行,供会话树恢复附件。 */+ linkPiUserEntry?(+ sessionId: string,+ clientId: string,+ piEntryId: string,+ ): Promise<boolean | void>;beforeDispatchDirectUserTurn?: (sessionId: string) => void | Promise<void>;onUndispatchedDirectUserTurn?: (sessionId: string) => void;ackInterruptedTurnDispatched?: (sessionId: string, endedAt: number) => void | Promise<void>;@@ -206,6 +212,30 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {};}+function containsManagedAttachment(value: unknown): boolean {+ if (typeof value === 'string') {+ const trimmed = value.trim();+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return false;+ try {+ return containsManagedAttachment(JSON.parse(trimmed) as unknown);+ } catch {+ return false;+ }+ }+ if (Array.isArray(value)) {+ return value.some((item) => {+ if (typeof item !== 'object' || item === null) return false;+ const block = item as Record<string, unknown>;+ return block.type === 'image' || block.type === 'file' || containsManagedAttachment(block.content);+ });+ }+ if (typeof value !== 'object' || value === null) return false;+ const record = value as Record<string, unknown>;+ return (Array.isArray(record.images) && record.images.length > 0)+ || (Array.isArray(record.files) && record.files.length > 0)+ || containsManagedAttachment(record.content);+}+/*** 普通 maker:send 的产品事务。*@@ -478,6 +508,38 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make...(typeof (createOpts as { planMode?: unknown } | undefined)?.planMode === 'boolean'? { planMode: (createOpts as { planMode: boolean }).planMode }: {}),+ ...(sess.agentKind === 'pi'+ && persistUserMessage+ && containsManagedAttachment(persistUserMessage.content)+ && deps.linkPiUserEntry+ ? {+ onTranscriptUserEntry: async (piEntryId: string) => {+ try {+ const linked = await deps.linkPiUserEntry?.(+ sessionId,+ persistUserMessage.clientId,+ piEntryId,+ );+ if (linked === false) {+ deps.log.warn('send: Pi transcript entry target row missing', {+ sessionId,+ clientId: persistUserMessage.clientId,+ piEntryId,+ });+ }+ } catch (err) {+ // provider 已接受 prompt;关联补丁失败只能降级为 legacy 恢复,不能+ // 把发送结果翻成 rejected,避免 UI 重发同一条消息。+ deps.log.warn('send: Pi transcript entry link failed (non-fatal)', {+ sessionId,+ clientId: persistUserMessage.clientId,+ piEntryId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ },+ }+ : {}),onAccepted: persistUserMessage? async () => {persistUserMessage.onPersisting?.();diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex ad3dd4a981..eba64212f8 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -138,6 +138,7 @@ import {findParkedEngineSession,getMessageDeletionTarget,listMessagesForAgentHandoff,+ patchMessageAgentMeta,supersedeRetriedUserTurn,} from '../localDb/ipc/messages.js';import { messageToCamel } from '../localDb/mapper.js';@@ -7650,6 +7651,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});return result;},+ linkPiUserEntry: (sessionId, clientId, piEntryId) =>+ enqueueDurableWrite(`pi-entry-link:${sessionId}:${clientId}`, () =>+ patchMessageAgentMeta(sessionId, clientId, { piEntryId })),beforeDispatchDirectUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnStart(sessionId),onUndispatchedDirectUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnAbort(sessionId),ackInterruptedTurnDispatched: async (sessionId, endedAt) => {diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex ac2030b756..79736f01fa 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -888,6 +888,12 @@ export interface SendOptions {* Codex 端: 当前不消费 (Codex 无 file checkpointing 概念)。*/messageUuid?: string;+ /**+ * Adapter 回报这条 user prompt 在原生 transcript 中的稳定 entry id。+ * Host 可把它补到已落库的 Cindy user 行,供后续原生分支重投影精确恢复附件。+ * 回调失败不得改变已经接受的 provider dispatch 结果。+ */+ onTranscriptUserEntry?: (entryId: string) => void | Promise<void>;/*** 当前用户的展示名 (host / renderer 在调 send 时提供)。仅用于 turn-start 时* push status event 的文案 — agent 拼成 "<userName> Just Wait ..." 让 UI 个人化;diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex 79434883b6..d36fbf1eca 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts@@ -327,6 +327,69 @@ describe('Pi provider-aware model routing', () => {await handle.close();});+ it('does not replay a failed Full-access intent when Extra Dirs are updated later', async () => {+ const fsp = await import('node:fs');+ const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));+ const handle = await agent.startSession({+ sessionId: 'perm-failed-intent',+ workingDir: cwd,+ model: 'local-model',+ permissionMode: 'ask',+ });+ const permFile = path.join(agentHome, 'runtime', 'perm-perm-failed-intent.json');+ const spy = vi.spyOn(fsp.promises, 'writeFile').mockRejectedValueOnce(new Error('transient EIO'));+ await expect(handle.setPermissionMode!('bypassPermissions')).rejects.toThrow('transient EIO');+ spy.mockRestore();++ await handle.setExtraDirs!(['/reference-only']);+ expect(JSON.parse(readFileSync(permFile, 'utf8'))).toEqual({+ mode: 'ask',+ readOnlyRoots: ['/reference-only'],+ });+ await handle.close();+ });++ it('reports the stable Pi user entry id after prompt acceptance', async () => {+ let promptAccepted = false;+ captured.requestHandler = async (command) => {+ if (command.type === 'get_state') {+ return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };+ }+ if (command.type === 'prompt') {+ promptAccepted = true;+ return { success: true, data: {} };+ }+ if (command.type === 'get_entries') {+ return {+ success: true,+ data: {+ entries: [+ { id: 'old-user', type: 'message', message: { role: 'user', content: 'old' } },+ ...(promptAccepted+ ? [{ id: 'new-user', type: 'message', message: { role: 'user', content: 'new' } }]+ : []),+ ],+ },+ };+ }+ return { success: true, data: {} };+ };+ const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));+ const handle = await agent.startSession({+ sessionId: 'entry-link',+ workingDir: cwd,+ model: 'local-model',+ });+ const onTranscriptUserEntry = vi.fn();+ await handle.send(+ { type: 'user', content: 'new' },+ { onTranscriptUserEntry },+ );+ expect(onTranscriptUserEntry).toHaveBeenCalledOnce();+ expect(onTranscriptUserEntry).toHaveBeenCalledWith('new-user');+ await handle.close();+ });+it('closes the Pi process if tightening a persisted Full-access file fails', async () => {const fsp = await import('node:fs');const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 80906d4852..c7069140ad 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -609,7 +609,22 @@ export class PiAgent extends BaseAgent {const snapshot = { ...requestedPermissionSnapshot, readOnlyRoots: [...requestedPermissionSnapshot.readOnlyRoots] };const run = permissionWriteChain.then(async () => {if (gen !== permissionWriteGen) return;- await fs.writeFile(permissionFile, JSON.stringify(snapshot) + '\n');+ try {+ await fs.writeFile(permissionFile, JSON.stringify(snapshot) + '\n');+ } catch (error) {+ // 失败的最新意图不能留在 requested 里。否则一次 Full-access 写失败后,+ // 随后的 Extra Dirs 更新会从 requested 继承 bypassPermissions,再把失败的+ // 放宽意图重放到 bridge 文件。旧代际失败不能回滚较新的并发意图。+ if (gen === permissionWriteGen) {+ requestedPermissionSnapshot = {+ // 收紧在 I/O 前已 fail-closed 提交到 host;保留这个更安全的 mode。+ // 放宽失败时 permissionMode 仍是旧的已提交 mode,同样达到回滚效果。+ mode: permissionMode,+ readOnlyRoots: [...persistedPermissionSnapshot.readOnlyRoots],+ };+ }+ throw error;+ }// 只有落盘成功且仍是最新代际,host 才提交放宽/目录变更。失败时调用方// 收到 reject;已提前采取的收紧仍保留(fail-closed),下一次写可沿恢复后的链重试。if (gen === permissionWriteGen) {@@ -890,6 +905,63 @@ export class PiAgent extends BaseAgent {return false;};+ const readPiUserEntryIds = async (): Promise<Set<string> | null> => {+ try {+ const response = await proc.request({ type: 'get_entries' });+ if (!response.success) return null;+ const data = typeof response.data === 'object' && response.data !== null+ ? response.data as Record<string, unknown>+ : null;+ // malformed success 不能当“空历史”,否则下一次正常读取会把任意既有 user entry+ // 误判成刚发送的消息并串错附件。+ if (!Array.isArray(data?.entries)) return null;+ const entries = data.entries;+ const ids = new Set<string>();+ for (const raw of entries) {+ if (typeof raw !== 'object' || raw === null) continue;+ const entry = raw as Record<string, unknown>;+ if (entry.type !== 'message' || typeof entry.id !== 'string' || entry.id.length === 0) continue;+ const message = typeof entry.message === 'object' && entry.message !== null+ ? entry.message as Record<string, unknown>+ : null;+ if (message?.role === 'user') ids.add(entry.id);+ }+ return ids;+ } catch (error) {+ this.deps.logger.warn('pi user-entry snapshot failed (attachment link unavailable)', {+ message: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ };++ const reportAcceptedPiUserEntry = async (+ before: Set<string> | null,+ callback: SendOptions['onTranscriptUserEntry'],+ ): Promise<void> => {+ if (!before || !callback) return;+ // prompt RPC 在 Pi 的 preflight acceptance 点返回,entry 紧接着才 append。短轮询+ // get_entries,按“此前不存在的 user entry”取稳定 id;捕获失败只影响附件分支恢复,+ // 不能把已被 Pi 接受的发送伪报成失败。+ for (let attempt = 0; attempt < 25; attempt += 1) {+ const current = await readPiUserEntryIds();+ const entryId = current ? [...current].find((id) => !before.has(id)) : undefined;+ if (entryId) {+ try {+ await callback(entryId);+ } catch (error) {+ this.deps.logger.warn('pi user-entry link callback failed (non-fatal)', {+ entryId,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ return;+ }+ await new Promise<void>((resolve) => setTimeout(resolve, 8));+ }+ this.deps.logger.warn('pi user-entry id was not observable after prompt acceptance');+ };+const writePermissionSnapshotOrFailClosed = async (next: PermissionSnapshot): Promise<void> => {try {await writePermissionFile(next);@@ -1055,10 +1127,15 @@ export class PiAgent extends BaseAgent {if (images.length > 0) command.images = images;// send 语义 = 排队开新 turn;pi streaming 中裸 prompt 会被拒,补 followUp。if (ctx.isStreaming) command.streamingBehavior = 'followUp';+ const userEntriesBefore = sendOpts?.onTranscriptUserEntry+ ? await readPiUserEntryIds()+ : null;+ rejectIfCancelled(sendOpts, 'send');const resp = await proc.request(command);if (!resp.success) {throw new Error(`pi prompt rejected: ${resp.error ?? 'unknown'}`);}+ await reportAcceptedPiUserEntry(userEntriesBefore, sendOpts?.onTranscriptUserEntry);},async steer(message: UserMessage, sendOpts?: SendOptions): Promise<void> {