Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot): drop working-memory items whose source turn was rewound
zqchrisb5b6165e538d
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.tsindex 140d586903..ee9ae3a706 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts@@ -3,7 +3,26 @@ import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: {} }) }));+/**+ * 最小 drizzle 假链:每次 select() 按顺序弹出一组行;链上任何方法都返回自身并可 await。+ * 读取路径依次 select:伙伴归属 → 来源消息存活 → 进行中的后台任务。+ */+const db = vi.hoisted(() => ({ queue: [] as unknown[][] }));+vi.mock('../../localDb/client/current.js', () => ({+ getDbClient: () => ({+ drizzle: {+ select: () => {+ const rows = db.queue.shift() ?? [];+ const chain: Record<string, unknown> = {+ then: (resolve: (value: unknown) => unknown, reject?: (reason: unknown) => unknown) =>+ Promise.resolve(rows).then(resolve, reject),+ };+ for (const name of ['from', 'innerJoin', 'where', 'limit']) chain[name] = () => chain;+ return chain;+ },+ },+ }),+}));import {applyWorkingMemoryProposal,@@ -12,8 +31,10 @@ import {emptyWorkingMemory,isWorkingMemoryFresh,parseWorkingMemory,+ pruneWithdrawnWorkingMemoryForSession,pruneWorkingMemoryForMessages,readBotWorkingMemory,+ readWorkingMemoryNoteForSession,renderWorkingMemory,WORKING_MEMORY_HEADING,WORKING_MEMORY_LIMITS,@@ -255,6 +276,48 @@ describe('store', () => {expect((await fs.readdir(path.join(root, 'bots', 'bot-1'))).filter((f) => f.includes('.tmp-'))).toEqual([]);});+ it('drops items whose source message was rewound or tombstoned at render time, and prunes them after a rewind', async () => {+ await writeBotWorkingMemory(+ root,+ 'bot-1',+ {+ ...emptyWorkingMemory(),+ updatedAt: 1,+ commitments: [+ { id: 'c-live', text: '仍在时间线上的承诺', messageId: 'live', updatedAt: 3 },+ { id: 'c-rewound', text: '被编辑上一条消息撤回的承诺', messageId: 'rewound', updatedAt: 2 },+ { id: 'c-gone', text: '来源已成墓碑的承诺', messageId: 'tomb', updatedAt: 1 },+ ],+ corrections: [{ id: 'x', text: '被撤回轮次里的纠正', messageId: 'rewound', updatedAt: 2 }],+ },+ 0,+ );+ const dbRows = [+ { clientId: 'live', rewindAt: null, role: 'assistant' },+ { clientId: 'rewound', rewindAt: 1_700_000_000_000, role: 'user' },+ { clientId: 'tomb', rewindAt: null, role: 'message_tombstone' },+ ];+ // 渲染:伙伴归属 → 来源存活 → 后台任务。+ db.queue.push([{ botId: 'bot-1' }], dbRows, []);+ const note = (await readWorkingMemoryNoteForSession('s-bot', root))!;+ expect(note).toContain('仍在时间线上的承诺');+ expect(note).not.toContain('撤回');+ expect(note).not.toContain('墓碑');+ // 磁盘上还没清;rewind 提交后对账持久清掉。+ expect((await readBotWorkingMemory(root, 'bot-1'))!.commitments).toHaveLength(3);+ db.queue.push([{ botId: 'bot-1' }], dbRows);+ expect(await pruneWithdrawnWorkingMemoryForSession('s-bot', root)).toBe(3);+ const after = (await readBotWorkingMemory(root, 'bot-1'))!;+ expect(after.commitments.map((c) => c.id)).toEqual(['c-live']);+ expect(after.corrections).toEqual([]);+ expect(after.revision).toBe(2);+ // 非伙伴主对话:不渲染也不清。+ db.queue.push([]);+ expect(await readWorkingMemoryNoteForSession('s-task', root)).toBeNull();+ db.queue.push([]);+ expect(await pruneWithdrawnWorkingMemoryForSession('s-task', root)).toBe(0);+ });+it('treats a corrupt or foreign file as no ledger', async () => {await fs.mkdir(path.join(root, 'bots', 'bot-2'), { recursive: true });await fs.writeFile(workingMemoryPath(root, 'bot-2'), '{not json', 'utf8');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.tsindex b739b42593..315b72d3cd 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts@@ -13,6 +13,15 @@ const mocks = vi.hoisted(() => ({finishSubagentRewindFence: vi.fn(),primeSubagentRewindFence: vi.fn(),listVisibleSubagentObservationIdentities: vi.fn(),+ pruneWithdrawnWorkingMemoryForSession: vi.fn(async () => 0),+}));++vi.mock('../../appSessionState.js', () => ({+ ownerScopedUserDataPath: () => '/owner-root',+}));++vi.mock('../botWorkingMemory.js', () => ({+ pruneWithdrawnWorkingMemoryForSession: mocks.pruneWithdrawnWorkingMemoryForSession,}));vi.mock('electron', () => ({@@ -99,6 +108,17 @@ describe('maker rewind IPC stop-then-rewind', () => {}await rewinding;expect(mocks.commitRewindAtMessage).toHaveBeenCalledOnce();+ // 被撤回轮次的伙伴工作记忆条目在提交成功后清理,顺序在 commit 之后。+ expect(mocks.pruneWithdrawnWorkingMemoryForSession).toHaveBeenCalledWith('session-1', '/owner-root');+ expect(mocks.pruneWithdrawnWorkingMemoryForSession.mock.invocationCallOrder[0]!)+ .toBeGreaterThan(mocks.commitRewindAtMessage.mock.invocationCallOrder[0]!);+ });++ it('does not prune working memory when the rewind commit fails', async () => {+ mocks.commitRewindAtMessage.mockRejectedValueOnce(new Error('NO_LIVE_QUERY'));+ const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT)!;+ await expect(handler({}, 'session-1', 'message-1', {})).rejects.toThrow();+ expect(mocks.pruneWithdrawnWorkingMemoryForSession).not.toHaveBeenCalled();});it('runs normal rewind inside the stopped input boundary when requested', async () => {diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.tsindex 84a32e788f..f5bbfddd45 100644--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts@@ -20,7 +20,7 @@ import path from 'node:path';import { and, eq, inArray, isNull } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current.js';-import { botDelegations, botProfiles, botSessionLinks, sessions } from '../localDb/schema.js';+import { botDelegations, botProfiles, botSessionLinks, messages, sessions } from '../localDb/schema.js';import { botSkillRootDir } from './botSkillStore.js';export const WORKING_MEMORY_FILE = 'working-memory.json';@@ -526,11 +526,40 @@ async function listOpenTasks(botId: string): Promise<WorkingMemoryOpenTask[]> {return rows.map((row) => ({ id: row.id, objective: row.objective, status: String(row.status) }));}+function sourceMessageIds(memory: BotWorkingMemory): string[] {+ const ids = new Set<string>();+ for (const list of [memory.threads, memory.commitments, memory.waiting, memory.corrections, memory.recentlyDone]) {+ for (const item of list) if (item.messageId) ids.add(item.messageId);+ }+ return [...ids];+}++/**+ * 账本条目的来源消息里,已经不在会话可见时间线上的那些:被 rewind(含「编辑上一条消息」)+ * 软删(`rewind_at` 非空)、被删除成墓碑、或根本找不到。这些条目和被删消息产生的条目一样,+ * 不能再借交接回到新上下文。+ */+export async function listWithdrawnSourceMessageIds(+ sessionId: string,+ memory: BotWorkingMemory,+): Promise<Set<string>> {+ const ids = sourceMessageIds(memory);+ if (ids.length === 0) return new Set();+ const rows = await getDbClient()+ .drizzle.select({ clientId: messages.clientId, rewindAt: messages.rewindAt, role: messages.role })+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, ids)));+ const live = new Set(+ rows.filter((row) => row.rewindAt === null && row.role !== 'message_tombstone').map((row) => row.clientId),+ );+ return new Set(ids.filter((id) => !live.has(id)));+}+/*** 换窗交接 / 压缩后刷新用的渲染段;非伙伴主对话或没有账本时返回 null。* 任何读取失败都按"没有账本"处理——账本是增强,不能挡住换窗。- * `excludeMessageIds`:正在删除的消息,渲染时先把它们产生的条目排除(持久清理在删除- * 提交后另做,见 pruneWorkingMemoryForSession)。+ * 渲染前统一排除来源已撤回(rewind / 删除)的条目;`excludeMessageIds` 是正在删除、+ * 还没落库的那批(持久清理在删除提交后另做,见 pruneWorkingMemoryForSession)。*/export async function readWorkingMemoryNoteForSession(sessionId: string,@@ -542,9 +571,9 @@ export async function readWorkingMemoryNoteForSession(if (!botId) return null;const stored = await readBotWorkingMemory(userDataDir, botId);if (!stored) return null;- const memory = opts.excludeMessageIds- ? pruneWorkingMemoryForMessages(stored, opts.excludeMessageIds).memory- : stored;+ const withdrawn = await listWithdrawnSourceMessageIds(sessionId, stored).catch(() => new Set<string>());+ for (const id of opts.excludeMessageIds ?? []) withdrawn.add(id);+ const memory = withdrawn.size > 0 ? pruneWorkingMemoryForMessages(stored, withdrawn).memory : stored;const openTasks = await listOpenTasks(botId).catch(() => []);return renderWorkingMemory(memory, { openTasks });} catch {@@ -566,6 +595,27 @@ export async function pruneWorkingMemoryForSession(}}+/**+ * rewind 提交成功后调用:按数据库现状持久清掉来源已撤回的条目。rewind 不返回被软删的+ * 消息清单,所以直接对账而不是接收 id 列表;失败不抛,渲染时的统一过滤仍兜底。+ */+export async function pruneWithdrawnWorkingMemoryForSession(+ sessionId: string,+ userDataDir: string,+): Promise<number> {+ try {+ const botId = await resolveCanonicalBotIdForSession(sessionId);+ if (!botId) return 0;+ const stored = await readBotWorkingMemory(userDataDir, botId);+ if (!stored) return 0;+ const withdrawn = await listWithdrawnSourceMessageIds(sessionId, stored);+ if (withdrawn.size === 0) return 0;+ return await pruneBotWorkingMemoryForMessages(userDataDir, botId, withdrawn);+ } catch {+ return 0;+ }+}+// ── 原生压缩后的一次性刷新 ─────────────────────────────────────────────────────/**diff --git a/apps/desktop/src/main/maker-ipc/rewind.ts b/apps/desktop/src/main/maker-ipc/rewind.tsindex 710fb5b42d..a006131dac 100644--- a/apps/desktop/src/main/maker-ipc/rewind.ts+++ b/apps/desktop/src/main/maker-ipc/rewind.ts@@ -33,6 +33,8 @@ import { requireString, throwIpcError } from '../utils/ipcValidate.js';import { MAKER_INVOKE } from './channels.js';import { withSessionInputStoppedForRewind } from './register.js';import { agentHandoffPending } from './agentHandoffPendingSingleton.js';+import { ownerScopedUserDataPath } from '../appSessionState.js';+import { pruneWithdrawnWorkingMemoryForSession } from './botWorkingMemory.js';const log = createLogger('maker-ipc/rewind');const STOPPED_REWIND_RETRY_MS = 100;@@ -70,6 +72,9 @@ async function commitAfterPersistBarrier(return withSendToSessionLock(sessionId, async () => {const result = await commitRewindAtMessage(sessionId, clientId, opts);advanceSessionRewindGeneration(sessionId);+ // 被撤回轮次产生的伙伴工作记忆条目一并清掉(与删除路径同一失效模式);提交成功+ // 后按数据库现状对账,失败不影响 rewind,渲染时的统一过滤仍兜底。+ await pruneWithdrawnWorkingMemoryForSession(sessionId, ownerScopedUserDataPath()).catch(() => 0);return result;});}