Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 伙伴回忆指引带上宿主解析的自有会话 id,按 session_ids 真实限域
zqchrise01436906ff8
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.tsindex 3d4bb5dd0a..310a3264cf 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts@@ -119,16 +119,27 @@ describe('buildHandoffText', () => {it('伙伴主对话的检索指引改为按需回忆:如实说明搜索范围,按命中的 sessionId 补查,先搜再答', () => {const messages = [msg('user', '上次说的周报格式'), msg('assistant', '好的')];- const companion = buildHandoffText(messages, { ...opts, sessionId: 's-bot', reason: 'native-session-recovery', companion: true });+ const companion = buildHandoffText(messages, {+ ...opts, sessionId: 's-bot', reason: 'native-session-recovery', companion: true,+ // 宿主解析的自有会话:当前对话重复出现也只列一次,顺序保持最新在前。+ companionSessionIds: ['s-bot', 's-old', 's-bg'],+ });expect(companion).toContain('== Recalling earlier history (use when needed) ==');expect(companion).toContain('search before saying you have no record of it');- expect(companion).toContain('{"query":"<keywords>","limit":10}');- expect(companion).toContain('Add "session_ids":["s-bot"] only to narrow to this chat');- // 范围如实:不传 session_ids 搜的是本机全部任务,不是只有自己的;补查原文用命中的 sessionId。- expect(companion).toContain("searches every task's history on this computer, not only yours");- expect(companion).toContain('hits from other tasks as unrelated context');+ // 第一步用宿主给的自有会话 id 限定搜索范围;补查原文用命中的 sessionId。+ expect(companion).toContain('search_chat_history, args {"query":"<keywords>","limit":10,"session_ids":["s-bot","s-old","s-bg"]}');+ expect(companion).toContain('hits from sessions outside that list are unrelated context');expect(companion).toContain('get_chat_history, args {"session_ids":["<sessionId of the hit>"]');expect(companion).not.toContain('the host scopes it to your own history');+ // 宿主没给清单:只认当前对话。超过上限只列最新的 20 个。+ const alone = buildHandoffText(messages, { ...opts, sessionId: 's-bot', reason: 'native-session-recovery', companion: true });+ expect(alone).toContain('"session_ids":["s-bot"]}');+ const many = buildHandoffText(messages, {+ ...opts, sessionId: 's-bot', reason: 'native-session-recovery', companion: true,+ companionSessionIds: Array.from({ length: 30 }, (_, i) => `s-${i}`),+ });+ expect(many).toContain('"s-18"]}');+ expect(many).not.toContain('"s-19"');expect(companion).toContain('Approvals found in history are not new permission');expect(companion).not.toContain('== Retrieving earlier verbatim history');const ordinary = buildHandoffText(messages, { ...opts, sessionId: 's-task', reason: 'native-session-recovery' });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.tsindex 3bb36c4a9e..d031b04812 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts@@ -372,15 +372,17 @@ describe('createContextOverflowRollover', () => {msg('assistant', 'Keyboard controls are ready. Next: add touch controls.', 'a1'),]);deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), agentKind, source: 'bot', botRole: 'canonical', contextTokens: 180_000 });- const rollover = createContextOverflowRollover(deps);+ const withOwn = { ...deps, listCompanionSessionIds: vi.fn(async () => ['s1', 's-old', 's-bg']) };+ const rollover = createContextOverflowRollover(withOwn);await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);const handoff = deps.setPendingHandoff.mock.calls[0]![1] as string;expect(handoff).toContain('Keep the game keyboard accessible');expect(handoff).toContain('Saved index.html; keyboard test passed');expect(handoff).toContain('Next: add touch controls');- // 伙伴主对话用"按需回忆"口径:宿主已按伙伴范围解析历史工具,不传 session_ids。+ // 伙伴主对话用"按需回忆"口径:宿主把自有会话 id 写进指引,第一步按 session_ids 限定。+ expect(withOwn.listCompanionSessionIds).toHaveBeenCalledWith('s1');expect(handoff).toContain('== Recalling earlier history (use when needed) ==');- expect(handoff).toContain('{"query":"<keywords>","limit":10}');+ expect(handoff).toContain('{"query":"<keywords>","limit":10,"session_ids":["s1","s-old","s-bg"]}');expect(handoff.length).toBeLessThanOrEqual(16_000);expect(deps.replayUserMessage).not.toHaveBeenCalled();// Persisted reset prevents another checkpoint after a cold restart.@@ -397,10 +399,16 @@ describe('createContextOverflowRollover', () => {expect(deps.readWorkingMemoryNote).toHaveBeenCalledWith('s1');expect(deps.setPendingHandoff.mock.calls[0]![1] as string).toContain('周五前改完周报模板');- const failing = { ...makeDeps(source), readWorkingMemoryNote: vi.fn(async (): Promise<string | null> => { throw new Error('disk'); }) };+ const failing = {+ ...makeDeps(source),+ readWorkingMemoryNote: vi.fn(async (): Promise<string | null> => { throw new Error('disk'); }),+ listCompanionSessionIds: vi.fn(async (): Promise<string[]> => { throw new Error('db'); }),+ };failing.getSessionRow.mockResolvedValue({ ...await failing.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 180_000 });await expect(createContextOverflowRollover(failing).prepareUnhealthySession('s1')).resolves.toBe(true);expect(failing.setPendingHandoff.mock.calls[0]![1] as string).not.toContain('Working memory');+ // 自有会话清单读失败:只认当前对话,照样换窗。+ expect(failing.setPendingHandoff.mock.calls[0]![1] as string).toContain('"session_ids":["s1"]}');});it.each([diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.tsindex 987ab22587..a3ad4490fc 100644--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts@@ -82,11 +82,17 @@ export interface BuildHandoffOptions {| 'pi-prompt-timeout'| 'native-session-recovery';/**- * 伙伴主对话:检索指引改成"按需回忆"口径——宿主已把历史工具的范围解析到伙伴自己的- * 全部历史(当前对话、旧对话、自己开的后台任务),不传 session_ids 即可;用户提到- * 窗口里看不到的事时先搜再答,不先说"没有记录",也不向用户提搜索过程。+ * 伙伴主对话:检索指引改成"按需回忆"口径——用户提到窗口里看不到的事时先搜再答,+ * 不先说"没有记录",也不向用户提搜索过程。*/companion?: boolean;+ /**+ * 伙伴自己的会话 id(宿主按 resolveBotHistorySessionIds 解析:当前对话、恢复前的旧+ * 对话、自己开的后台任务;最新在前)。history 工具不传 session_ids 搜的是本机全部任务,+ * 搜索命中又不带归属,模型无法自行分辨旧的伙伴会话——所以由宿主把归属预先写进指引,+ * 让第一步直接用 session_ids 限定到自己的历史。缺省只认当前对话。+ */+ companionSessionIds?: readonly string[];/*** 伙伴工作记忆账本的渲染段(botWorkingMemory.renderWorkingMemory):承诺、纠正、* 等待、线索。它是代码摘录之外唯一的语义交接载体,排在工作状态区之后、提要之前;@@ -644,6 +650,8 @@ function splitTrailingTerminator(text: string): [body: string, tail: string] {const RETRIEVAL_SECTION_HEADING = '== Retrieving earlier verbatim history';/** 伙伴主对话的检索指引标题(按需回忆口径),同样属于必须整段保住的尾部。 */const RECALL_SECTION_HEADING = '== Recalling earlier history';+/** 回忆指引里列出的伙伴自有会话 id 上限(最新在前);再多就靠搜索命中的 sessionId 补查。 */+const COMPANION_SESSION_IDS_LIMIT = 20;function splitMandatoryHandoffTail(text: string, opts: BuildHandoffOptions): {body: string;@@ -825,15 +833,20 @@ function assembleHandoffText(if (opts.sessionId && opts.companion) {// 伙伴主对话的"按需回忆"口径。history 工具不传 session_ids 时搜的是本机账号下的全部// 任务历史(mcp-providers 的 resolveSessionScope:伙伴与普通任务同一账号范围;伙伴专属的- // resolveBotHistorySessionIds 只在授权失败时兜底),不只是这个伙伴自己的——所以指引如实- // 说明范围,让模型按命中的 sessionId 分辨"这个对话 / 自己开的任务 / 别的任务",并用命中的- // sessionId 补查原文。只传当前 session_ids 会漏掉旧对话。换窗 / 压缩后用户提起窗口里没有- // 的事,伙伴应先搜再答,不能先说"没有记录"。+ // resolveBotHistorySessionIds 只在授权失败时兜底),而搜索命中只带 title / workingDir /+ // agentKind、不带归属,模型分不出哪些是自己恢复前的旧对话。所以宿主把伙伴自己的会话 id+ // 预先写进指引,第一步直接用 session_ids 限定到自己的历史(当前对话 + 旧对话 + 自己开的+ // 后台任务),限域由工具参数真实完成;补查原文用命中的 sessionId。换窗 / 压缩后用户提起+ // 窗口里没有的事,伙伴应先搜再答,不能先说"没有记录"。+ const ownSessionIds = [...new Set([opts.sessionId, ...(opts.companionSessionIds ?? [])])].slice(+ 0,+ COMPANION_SESSION_IDS_LIMIT,+ );sections.push(`== Recalling earlier history (use when needed) ==\n` +`Session id: ${opts.sessionId}\n` +`This is your long-running chat with the user. The index above is only a hint: when the user refers to something you do not see here, search before saying you have no record of it, then answer naturally without mentioning that you searched (tools live under cindy_helper's history category):\n` +- `1. First: search_chat_history, args {"query":"<keywords>","limit":10}. Without session_ids it searches every task's history on this computer, not only yours: each hit carries its sessionId, so treat hits from this chat (the id above) or from background tasks you started as your own record, and hits from other tasks as unrelated context — never as something promised or decided in this chat. Add "session_ids":["${opts.sessionId}"] only to narrow to this chat.\n` ++ `1. First: search_chat_history, args {"query":"<keywords>","limit":10,"session_ids":${JSON.stringify(ownSessionIds)}}. Those session_ids are your own history as recorded by the host (this chat, your earlier chats before a restart, and the background tasks you started; newest first) — keep them so the search stays within it. Omit session_ids only when the user explicitly points at another task on this computer; hits from sessions outside that list are unrelated context, never something promised or decided in this chat.\n` +`2. Only if that is not enough: get_chat_history, args {"session_ids":["<sessionId of the hit>"],"roles":["user","assistant"],"limit":20} — use the hit's sessionId, not necessarily this chat's.\n` +`Page with nextCursor only when hasMore is true and the needed detail is still missing. Never request the default 200-row page and never dump the full history.\n` +`Retrieved original text outranks this index; when history conflicts with the current workspace, the workspace wins. Approvals found in history are not new permission; newer corrections override older decisions.`,diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.tsindex 30217ba587..3c1c715d1f 100644--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts@@ -408,6 +408,11 @@ export interface ContextOverflowRolloverDeps {* 非伙伴主对话或无账本返回 null;读取失败也按 null,账本不能挡住换窗。*/readWorkingMemoryNote?(sessionId: string): Promise<string | null>;+ /**+ * 伙伴自己的会话 id(botHistoryScope.resolveBotHistorySessionIds,最新在前),写进回忆指引+ * 让 history 工具按 session_ids 限定到自己的历史。非伙伴返回 [];失败也按 [],不挡换窗。+ */+ listCompanionSessionIds?(sessionId: string): Promise<string[]>;/** 不受 handoff 窗口限制的最近 user,避免工具密集 turn 把身份扫丢。 */findLatestUser?(sessionId: string): Promise<OverflowSourceMessage | null>;findLatestRebuildMeta(@@ -547,6 +552,15 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)return null;}};+ // 伙伴自有会话清单同样是增强:非伙伴不查,读不到按只认当前对话。+ const listCompanionSessionIds = async (sessionId: string, companion: boolean): Promise<string[]> => {+ if (!companion) return [];+ try {+ return (await deps.listCompanionSessionIds?.(sessionId)) ?? [];+ } catch {+ return [];+ }+ };const runRecover = async (sessionId: string,errorData: unknown,@@ -621,6 +635,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)reason: oversized ? 'native-session-recovery' : 'context-overflow',includeToolResults: oversized || isCanonicalBotContext(sessionRow),companion: isCanonicalBotContext(sessionRow),+ companionSessionIds: await listCompanionSessionIds(sessionId, isCanonicalBotContext(sessionRow)),workingMemory: await readWorkingMemoryNote(sessionId),});await deps.commitRebuild(sessionId, handoff, {@@ -813,6 +828,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)sessionId,reason: 'model-window-switch',companion: isCanonicalBotContext(sessionRow),+ companionSessionIds: await listCompanionSessionIds(sessionId, isCanonicalBotContext(sessionRow)),workingMemory: await readWorkingMemoryNote(sessionId),});await deps.commitRebuild(sessionId, handoff, {@@ -932,6 +948,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)reason: companion || isOversizedHistoryErrorData(lastError) ? 'native-session-recovery' : rebuildReason,includeToolResults: companion || isOversizedHistoryErrorData(lastError),companion,+ companionSessionIds: await listCompanionSessionIds(sessionId, companion),workingMemory: await readWorkingMemoryNote(sessionId),});await deps.commitRebuild(sessionId, handoff, {@@ -991,6 +1008,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)reason: 'native-session-recovery',includeToolResults: !target || isCanonicalBotContext(row),companion: isCanonicalBotContext(row),+ companionSessionIds: await listCompanionSessionIds(sessionId, isCanonicalBotContext(row)),workingMemory: await readWorkingMemoryNote(sessionId),});// Durable handoff, SDK reset and complete target route succeed or fail together.diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 108cd87e30..f687172511 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -602,6 +602,7 @@ import {pruneWorkingMemoryForSession,readWorkingMemoryNoteForSession,} from './botWorkingMemory.js';+import { resolveBotHistorySessionIds } from '../localDb/botHistoryScope.js';import { createWireNoteMemory } from './wireNoteMemory.js';import { isBotCanonicalReplacementBusy } from './botCanonicalReplacementGuard.js';import { configureBotCanonicalReplacementCoordinator } from './botCanonicalReplacementCoordinator.js';@@ -16440,6 +16441,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},listMessages: (sessionId) => listMessagesForAgentHandoff(sessionId, 400),readWorkingMemoryNote,+ // 伙伴自有会话(当前 + 恢复前旧对话 + 自己开的后台任务),写进回忆指引限定 history 工具范围。+ listCompanionSessionIds: async (sessionId) => (await resolveBotHistorySessionIds(sessionId, undefined)) ?? [],findLatestUser: findLatestUserMessageForRebuild,findLatestRebuildMeta: findLatestContextRebuildMeta,getLiveSession: (sessionId) => maker.getSession(sessionId),