Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 回忆清单上限提到 50 并如实标记截断;受派 history 用 route_key 持久辨识

zqchris6463bf217bc9
diff --git a/apps/desktop/src/main/localDb/__tests__/botHistoryScope.test.ts b/apps/desktop/src/main/localDb/__tests__/botHistoryScope.test.ts
index 0faf49d4cb..908461bcd1 100644
--- a/apps/desktop/src/main/localDb/__tests__/botHistoryScope.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/botHistoryScope.test.ts
@@ -16,7 +16,7 @@ beforeEach(() => {
h.sqlite = new Database(':memory:');
h.sqlite.exec(`
CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT);
- CREATE TABLE bot_session_links (session_id TEXT, bot_id TEXT, created_at INTEGER, role TEXT NOT NULL DEFAULT 'canonical');
+ CREATE TABLE bot_session_links (session_id TEXT, bot_id TEXT, created_at INTEGER, role TEXT NOT NULL DEFAULT 'canonical', route_key TEXT);
CREATE TABLE bot_delegations (requesting_bot_id TEXT, child_session_id TEXT, created_at INTEGER, target_bot_id TEXT);
INSERT INTO sessions VALUES ('bot-main', 'bot'), ('owner-task', 'desktop'), ('child-1', 'desktop');
INSERT INTO bot_session_links (session_id, bot_id, created_at) VALUES ('bot-main', 'bot-1', 1), ('other-bot-main', 'bot-2', 2);
@@ -39,26 +39,32 @@ describe('resolveBotHistorySessionIds', () => {
describe('listBotRecallSessionIds', () => {
it('keeps every chat session ahead of background tasks within the bound, newest first', async () => {
// 恢复前的旧对话(更早)+ 当前对话,再加一堆比它们都新的后台任务;群专线、受派任务
- // (含完成后转成 history 的)都不是私聊,哪怕更新也不进清单。
+ // (含完成后转成 history 的,无论 bot_delegations 行还在不在)都不是私聊,哪怕更新也不进清单。
h.sqlite!.exec(`
- INSERT INTO bot_session_links (session_id, bot_id, created_at, role) VALUES
- ('bot-main-old', 'bot-1', 0, 'history'),
- ('bot-group-lane', 'bot-1', 20, 'group'),
- ('bot-received-live', 'bot-1', 21, 'delegation'),
- ('bot-received-done', 'bot-1', 22, 'history');
+ INSERT INTO bot_session_links (session_id, bot_id, created_at, role, route_key) VALUES
+ ('bot-main-old', 'bot-1', 0, 'history', NULL),
+ ('bot-group-lane', 'bot-1', 20, 'group', 'group:g1'),
+ ('bot-received-live', 'bot-1', 21, 'delegation', 'delegation:d1'),
+ ('bot-received-done', 'bot-1', 22, 'history', NULL),
+ ('bot-received-orphan', 'bot-1', 23, 'history', 'delegation:d3');
INSERT INTO bot_delegations (requesting_bot_id, child_session_id, created_at, target_bot_id) VALUES
('bot-2', 'bot-received-live', 21, 'bot-1'),
('bot-2', 'bot-received-done', 22, 'bot-1');
${Array.from({ length: 6 }, (_, i) => `INSERT INTO bot_delegations (requesting_bot_id, child_session_id, created_at) VALUES ('bot-1', 'task-${i}', ${10 + i});`).join('\n')}
`);
- const ids = await listBotRecallSessionIds('bot-main', 4);
- expect(ids).toEqual(['bot-main', 'bot-main-old', 'task-5', 'task-4']);
+ expect(await listBotRecallSessionIds('bot-main', 4)).toEqual({
+ sessionIds: ['bot-main', 'bot-main-old', 'task-5', 'task-4'],
+ chatsTruncated: false,
+ });
// 名额够时全部带上;非伙伴 / 未知调用方 / 零名额都为空。
- expect(await listBotRecallSessionIds('bot-main', 50)).toEqual([
- 'bot-main', 'bot-main-old', 'task-5', 'task-4', 'task-3', 'task-2', 'task-1', 'task-0', 'child-1',
- ]);
- expect(await listBotRecallSessionIds('owner-task', 4)).toEqual([]);
- expect(await listBotRecallSessionIds('missing', 4)).toEqual([]);
- expect(await listBotRecallSessionIds('bot-main', 0)).toEqual([]);
+ expect(await listBotRecallSessionIds('bot-main', 50)).toEqual({
+ sessionIds: ['bot-main', 'bot-main-old', 'task-5', 'task-4', 'task-3', 'task-2', 'task-1', 'task-0', 'child-1'],
+ chatsTruncated: false,
+ });
+ expect(await listBotRecallSessionIds('owner-task', 4)).toEqual({ sessionIds: [], chatsTruncated: false });
+ expect(await listBotRecallSessionIds('missing', 4)).toEqual({ sessionIds: [], chatsTruncated: false });
+ expect(await listBotRecallSessionIds('bot-main', 0)).toEqual({ sessionIds: [], chatsTruncated: false });
+ // 私聊比名额多:只放最新的,并如实标记没放全(后台任务一个都不占名额)。
+ expect(await listBotRecallSessionIds('bot-main', 1)).toEqual({ sessionIds: ['bot-main'], chatsTruncated: true });
});
});
diff --git a/apps/desktop/src/main/localDb/botHistoryScope.ts b/apps/desktop/src/main/localDb/botHistoryScope.ts
index e2f15c765d..052fbd812e 100644
--- a/apps/desktop/src/main/localDb/botHistoryScope.ts
+++ b/apps/desktop/src/main/localDb/botHistoryScope.ts
@@ -69,26 +69,37 @@ export async function resolveBotHistorySessionIds(
* 给最新的、由它发起的后台任务——后台任务再多,结果也早已按回执进过主对话;而旧对话一旦被
* 挤出清单,用户追问恢复前的事就只能得到"没有记录"。
*
- * 只算私聊:`group`(群专线,不进主时间线)和 `delegation`(受派任务)链接都不是这段私聊,
- * 受派任务完成后会转成 `history`(tx.ts 的委派收尾),所以还要按 bot_delegations 的
- * target_bot_id 把"别人派给我的"排除掉,否则群消息 / 受派内容会被当成私聊里的承诺。
- * 非伙伴会话或归属损坏返回 []。
+ * 只算私聊:`group`(群专线,不进主时间线)和 `delegation`(受派任务)链接都不是这段私聊。
+ * 受派任务完成后会转成 `history`(tx.ts 的委派收尾),识别它靠两重标记:链接上保留的
+ * `route_key = 'delegation:<id>'`(收尾不再清空,发起方被删除后仍在),以及 bot_delegations 的
+ * `target_bot_id`(兜底收尾前写入的旧行)。否则群消息 / 受派内容会被当成私聊里的承诺。
+ *
+ * 私聊超过 `limit` 条时只列最新的,但用 `chatsTruncated` 如实告诉调用方,指引据此给模型
+ * 一条可用的退路,而不是静默截断。非伙伴会话或归属损坏返回空清单。
*/
-export async function listBotRecallSessionIds(callerSessionId: string, limit: number): Promise<string[]> {
+export interface BotRecallSessionIds {
+ sessionIds: string[];
+ /** 私聊会话比 limit 多,清单里没放全(后台任务被挤掉不算)。 */
+ chatsTruncated: boolean;
+}
+
+export async function listBotRecallSessionIds(callerSessionId: string, limit: number): Promise<BotRecallSessionIds> {
const scope = await resolveBotHistoryScope(callerSessionId, undefined);
- if (scope.kind !== 'bot' || limit <= 0) return [];
+ if (scope.kind !== 'bot' || limit <= 0) return { sessionIds: [], chatsTruncated: false };
const db = getDbClient();
const chats = await db.query<{ sessionId: string }>(
`SELECT l.session_id AS sessionId FROM bot_session_links l
WHERE l.bot_id = ? AND l.role IN ('canonical', 'history')
+ AND (l.route_key IS NULL OR l.route_key NOT LIKE 'delegation:%')
AND NOT EXISTS (
SELECT 1 FROM bot_delegations d
WHERE d.child_session_id = l.session_id AND d.target_bot_id = ?
)
ORDER BY l.created_at DESC LIMIT ?`,
- [scope.botId, scope.botId, limit],
+ [scope.botId, scope.botId, limit + 1],
);
- const ids = new Set(chats.map((row) => row.sessionId));
+ const chatsTruncated = chats.length > limit;
+ const ids = new Set(chats.slice(0, limit).map((row) => row.sessionId));
const remaining = limit - ids.size;
if (remaining > 0) {
const tasks = await db.query<{ sessionId: string }>(
@@ -99,7 +110,7 @@ export async function listBotRecallSessionIds(callerSessionId: string, limit: nu
);
for (const row of tasks) ids.add(row.sessionId);
}
- return [...ids];
+ return { sessionIds: [...ids], chatsTruncated };
}
/**
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 72c165f280..88ae036a91 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -855,8 +855,11 @@ function botsFinishDelegation(
db.prepare(`UPDATE sessions SET status = 'archived', updated_at = ?
WHERE id = ? AND status = 'active'`)
.run(completedAt, row.childSessionId);
+ // 保留 route_key('delegation:<id>')作为来源标记:bot_delegations 行会随发起伙伴
+ // 的删除级联消失,之后只有它能证明这段 history 是"别人派给我的",不是自己的私聊
+ // (botHistoryScope.listBotRecallSessionIds)。route_key 的其它读者都只认 group 键。
db.prepare(`UPDATE bot_session_links SET role = 'history',
- route_key = NULL, archived_at = ? WHERE session_id = ?`)
+ archived_at = ? WHERE session_id = ?`)
.run(completedAt, row.childSessionId);
}
return row;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
index 4292ddbdaa..b9fa1e14c8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
@@ -134,15 +134,23 @@ describe('buildHandoffText', () => {
expect(companion).toContain('"to":"<createdAt of the hit>","order":"desc"');
expect(companion).toContain('"context_radius":6');
expect(companion).not.toContain('the host scopes it to your own history');
- // 宿主没给清单:只认当前对话。超过上限只列最新的 20 个。
+ // 清单没放全时给退路;放全了不提。
+ expect(companion).not.toContain('could list only your newest');
+ const truncated = buildHandoffText(messages, {
+ ...opts, sessionId: 's-bot', reason: 'native-session-recovery', companion: true,
+ companionSessionIds: ['s-bot', 's-old'], companionSessionIdsTruncated: true,
+ });
+ expect(truncated).toContain('The host could list only your newest 50 chats');
+ expect(truncated).toContain('search once more without session_ids and treat any hit as possibly yours but unverified');
+ // 宿主没给清单:只认当前对话。防御性上限 = 工具单次 session_ids 上限 50。
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}`),
+ companionSessionIds: Array.from({ length: 60 }, (_, i) => `s-${i}`),
});
- expect(many).toContain('"s-18"]}');
- expect(many).not.toContain('"s-19"');
+ expect(many).toContain('"s-48"]}');
+ expect(many).not.toContain('"s-49"');
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.ts
index d031b04812..a7ffb3c0af 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@ -372,7 +372,7 @@ 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 withOwn = { ...deps, listCompanionSessionIds: vi.fn(async () => ['s1', 's-old', 's-bg']) };
+ const withOwn = { ...deps, listCompanionSessionIds: vi.fn(async () => ({ sessionIds: ['s1', 's-old', 's-bg'], chatsTruncated: false })) };
const rollover = createContextOverflowRollover(withOwn);
await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);
const handoff = deps.setPendingHandoff.mock.calls[0]![1] as string;
@@ -383,6 +383,7 @@ describe('createContextOverflowRollover', () => {
expect(withOwn.listCompanionSessionIds).toHaveBeenCalledWith('s1');
expect(handoff).toContain('== Recalling earlier history (use when needed) ==');
expect(handoff).toContain('{"query":"<keywords>","limit":10,"session_ids":["s1","s-old","s-bg"]}');
+ expect(handoff).not.toContain('could list only your newest');
expect(handoff.length).toBeLessThanOrEqual(16_000);
expect(deps.replayUserMessage).not.toHaveBeenCalled();
// Persisted reset prevents another checkpoint after a cold restart.
@@ -402,7 +403,7 @@ describe('createContextOverflowRollover', () => {
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'); }),
+ listCompanionSessionIds: vi.fn(async (): Promise<{ sessionIds: string[]; chatsTruncated: boolean }> => { 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);
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index ce2f99f6cf..3d16b76eba 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -94,6 +94,11 @@ export interface BuildHandoffOptions {
* 历史。缺省只认当前对话。
*/
companionSessionIds?: readonly string[];
+ /**
+ * 私聊会话比上限多、清单没放全(宿主 chatsTruncated)。指引据此给模型一条退路:限定搜索
+ * 找不到时可以不带 session_ids 再搜一次,但命中只能当未经核实的历史、先向用户确认。
+ */
+ companionSessionIdsTruncated?: boolean;
/**
* 伙伴工作记忆账本的渲染段(botWorkingMemory.renderWorkingMemory):承诺、纠正、
* 等待、线索。它是代码摘录之外唯一的语义交接载体,排在工作状态区之后、提要之前;
@@ -652,10 +657,11 @@ const RETRIEVAL_SECTION_HEADING = '== Retrieving earlier verbatim history';
/** 伙伴主对话的检索指引标题(按需回忆口径),同样属于必须整段保住的尾部。 */
const RECALL_SECTION_HEADING = '== Recalling earlier history';
/**
- * 回忆指引里列出的伙伴自有会话 id 上限。宿主(listBotRecallSessionIds)按同一上限分层取数:
- * 对话会话整体优先、后台任务补足,旧对话不会被后台任务挤掉;这里的截断只是防御性兜底。
+ * 回忆指引里列出的伙伴自有会话 id 上限 = history 工具 `session_ids` 的单次上限(50)。宿主
+ * (listBotRecallSessionIds)按同一上限分层取数:私聊整体优先、后台任务补足,并告知私聊是否
+ * 没放全;这里的截断只是防御性兜底。
*/
-export const COMPANION_SESSION_IDS_LIMIT = 20;
+export const COMPANION_SESSION_IDS_LIMIT = 50;
function splitMandatoryHandoffTail(text: string, opts: BuildHandoffOptions): {
body: string;
@@ -850,7 +856,11 @@ function assembleHandoffText(
`== 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,"session_ids":${JSON.stringify(ownSessionIds)}}. Those session_ids are your own history as recorded by the host (this chat and your earlier chats before a restart first, then the background tasks you started) — 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` +
+ `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 and your earlier chats before a restart first, then the background tasks you started) — 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.${
+ opts.companionSessionIdsTruncated
+ ? ` The host could list only your newest ${COMPANION_SESSION_IDS_LIMIT} chats; older chats of yours exist beyond that list. If the user refers to something older and the scoped search finds nothing, search once more without session_ids and treat any hit as possibly yours but unverified: confirm with the user before relying on it.`
+ : ''
+ }\n` +
`2. Only if that is not enough, read around the hit, anchored on the hit's sessionId and createdAt (get_chat_history returns the newest rows first by default, so without the anchor you would read the end of that session instead of the hit): get_chat_history, args {"session_ids":["<sessionId of the hit>"],"from":"<createdAt of the hit>","order":"asc","roles":["user","assistant"],"limit":20} for what followed, or {"session_ids":["<sessionId of the hit>"],"to":"<createdAt of the hit>","order":"desc","roles":["user","assistant"],"limit":20} for what came before. A wider excerpt is also available by repeating step 1 with "context_radius":6.\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.ts
index 3c1c715d1f..d601d3ea78 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -409,10 +409,11 @@ export interface ContextOverflowRolloverDeps {
*/
readWorkingMemoryNote?(sessionId: string): Promise<string | null>;
/**
- * 伙伴自己的会话 id(botHistoryScope.resolveBotHistorySessionIds,最新在前),写进回忆指引
- * 让 history 工具按 session_ids 限定到自己的历史。非伙伴返回 [];失败也按 [],不挡换窗。
+ * 伙伴自己的会话清单(botHistoryScope.listBotRecallSessionIds:私聊优先、后台任务补足,
+ * 并告知私聊是否没放全),写进回忆指引让 history 工具按 session_ids 限定到自己的历史。
+ * 非伙伴返回空清单;失败也按空清单,不挡换窗。
*/
- listCompanionSessionIds?(sessionId: string): Promise<string[]>;
+ listCompanionSessionIds?(sessionId: string): Promise<{ sessionIds: string[]; chatsTruncated: boolean }>;
/** 不受 handoff 窗口限制的最近 user,避免工具密集 turn 把身份扫丢。 */
findLatestUser?(sessionId: string): Promise<OverflowSourceMessage | null>;
findLatestRebuildMeta(
@@ -553,12 +554,17 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
}
};
// 伙伴自有会话清单同样是增强:非伙伴不查,读不到按只认当前对话。
- const listCompanionSessionIds = async (sessionId: string, companion: boolean): Promise<string[]> => {
- if (!companion) return [];
+ const companionRecall = async (
+ sessionId: string,
+ companion: boolean,
+ ): Promise<{ companionSessionIds: string[]; companionSessionIdsTruncated: boolean }> => {
+ const none = { companionSessionIds: [], companionSessionIdsTruncated: false };
+ if (!companion) return none;
try {
- return (await deps.listCompanionSessionIds?.(sessionId)) ?? [];
+ const own = await deps.listCompanionSessionIds?.(sessionId);
+ return own ? { companionSessionIds: own.sessionIds, companionSessionIdsTruncated: own.chatsTruncated } : none;
} catch {
- return [];
+ return none;
}
};
const runRecover = async (
@@ -635,7 +641,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)),
+ ...(await companionRecall(sessionId, isCanonicalBotContext(sessionRow))),
workingMemory: await readWorkingMemoryNote(sessionId),
});
await deps.commitRebuild(sessionId, handoff, {
@@ -828,7 +834,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
sessionId,
reason: 'model-window-switch',
companion: isCanonicalBotContext(sessionRow),
- companionSessionIds: await listCompanionSessionIds(sessionId, isCanonicalBotContext(sessionRow)),
+ ...(await companionRecall(sessionId, isCanonicalBotContext(sessionRow))),
workingMemory: await readWorkingMemoryNote(sessionId),
});
await deps.commitRebuild(sessionId, handoff, {
@@ -948,7 +954,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
reason: companion || isOversizedHistoryErrorData(lastError) ? 'native-session-recovery' : rebuildReason,
includeToolResults: companion || isOversizedHistoryErrorData(lastError),
companion,
- companionSessionIds: await listCompanionSessionIds(sessionId, companion),
+ ...(await companionRecall(sessionId, companion)),
workingMemory: await readWorkingMemoryNote(sessionId),
});
await deps.commitRebuild(sessionId, handoff, {
@@ -1008,7 +1014,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
reason: 'native-session-recovery',
includeToolResults: !target || isCanonicalBotContext(row),
companion: isCanonicalBotContext(row),
- companionSessionIds: await listCompanionSessionIds(sessionId, isCanonicalBotContext(row)),
+ ...(await companionRecall(sessionId, isCanonicalBotContext(row))),
workingMemory: await readWorkingMemoryNote(sessionId),
});
// Durable handoff, SDK reset and complete target route succeed or fail together.