Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(history): scope page budgets and stop context reads at the boundary
Chrisbe88d70a5e0f
diff --git a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.tsindex 8f57d83df6..ff3e7dd988 100644--- a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts@@ -3,7 +3,7 @@ import Database from 'better-sqlite3';import { drizzle } from 'drizzle-orm/better-sqlite3';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getMessagesForHistory, listSessionsForHistory } from '../chatHistoryReader';-import { XdtHelperToolRegistry, registerGetChatHistoryTool, historyPayload } from '@cindy/mcps';+import { XdtHelperToolRegistry, registerGetChatHistoryTool, registerSearchChatHistoryTool, historyPayload } from '@cindy/mcps';import { searchChatHistoryHybrid } from '../chatHistorySearch';import { readRemoteBotSessionAccessBatch } from '../ipc/botRemoteSessionAccess';import { setChatEmbeddingEnabled } from '../../embedders/chat-history-embedder';@@ -211,7 +211,9 @@ describe.each(modes)('%s remote history visibility', (mode) => {expect(ids).toEqual(['ordinary', 'visible', 'zero']);});- it('continues search at the consumed candidate rather than the requested page limit', async () => {+ // r4411387401/r4411387386: real MCP entry must budget while reading, whereas+ // fixed-page internal consumers keep their original complete hit count (unit/SQLite).+ it.each([0, 2])('continues tool search at the consumed candidate without hydrating the remaining page (radius=%s)', async (radius) => {setChatEmbeddingEnabled(false);const text = 'budgetneedle ' + '文'.repeat(18000);const ids = ['budget-z', 'budget-a', 'budget-m'];@@ -221,16 +223,33 @@ describe.each(modes)('%s remote history visibility', (mode) => {db.prepare('INSERT INTO messages_fts VALUES (?, ?)').run(id, 'budgetneedle');}const found: string[] = [];- let offset = 0;+ const registry = new XdtHelperToolRegistry();+ registerSearchChatHistoryTool(registry, { history: {+ listWorkdirs: vi.fn(), listSessions: vi.fn(), getMessages: vi.fn(),+ searchChatHistory: async args => ({ ok: true, result: await searchChatHistoryHybrid(args) }),+ } });+ let cursor: string | undefined;for (let i = 0; i < 3; i++) {- const page = await searchChatHistoryHybrid({ ...searchArgs, query: 'budgetneedle', limit: 10, offset });+ const reads = vi.spyOn(state.client.drizzle, 'select');+ const page = historyPayload(await registry.call('search_chat_history', {+ query: 'budgetneedle', limit: 10, context_radius: radius, ...(cursor ? { cursor } : {}),+ })) as any;expect(page.hits).toHaveLength(1);- expect(page.hits[0].context[0].content).toBe(text);+ expect(page.hits[0].context.find((row: any) => row.isHit).content).toBe(text);found.push(page.hits[0].messageId);expect(page.hasMore).toBe(i < 2);- if (page.nextOffset !== null) { expect(page.nextOffset).toBe(offset + 1); offset = page.nextOffset; }+ if (radius === 2) {+ // This single full context exceeds the budget. Only its anchor + two+ // neighbour queries and one session metadata query should run.+ expect(reads).toHaveBeenCalledTimes(4);+ }+ reads.mockRestore();+ if (page.nextCursor !== null) { expect(page.nextCursor).not.toBe(cursor); cursor = page.nextCursor; }}expect(found.sort()).toEqual(ids.sort());+ const internal = await searchChatHistoryHybrid({ ...searchArgs, query: 'budgetneedle', limit: 10, contextRadius: radius });+ expect(internal.hits.map(hit => hit.messageId).sort()).toEqual(ids.sort());+ expect(internal.hasMore).toBe(false);});// Regression: old-created, recently active chats were lost by workdir/creationdiff --git a/apps/desktop/src/main/localDb/chatHistorySearch.ts b/apps/desktop/src/main/localDb/chatHistorySearch.tsindex 0ce7ebc7b6..43cd97446d 100644--- a/apps/desktop/src/main/localDb/chatHistorySearch.ts+++ b/apps/desktop/src/main/localDb/chatHistorySearch.ts@@ -39,7 +39,7 @@ import type {import { historyCompanionJson, parseHistoryCompanion } from './historyCompanion';import { getDbClient } from './client/current';-import { historyPageWithinBudget } from './historyPageBudget';+import { HistoryPageBudget } from './historyPageBudget';import { messages as messagesTable, sessions as sessionsTable } from './schema';import { messageToCamel } from './mapper';import { fuseRRF, buildMessagesFtsMatch, extractMessagesFtsTokens } from './chatHistorySearch.pure';@@ -89,6 +89,8 @@ interface HitMeta {type SearchSessionStatus = 'active' | 'archived' | 'deleted';interface SearchChatHistoryEngineArgs extends SearchChatHistoryArgs {+ /** Set only by search_chat_history's host invocation, never by UI/learn consumers. */+ historyToolPageBudget?: boolean;/** Host-owned remote visibility scope, applied to both retrieval arms before ranking. */remoteVisibleOnly?: boolean;/**@@ -196,17 +198,19 @@ export async function searchChatHistoryHybrid(const start = Math.max(0, Math.min(args.offset, pool.length));const pageEntries = pool.slice(start, start + args.limit);let nextOffset = start + args.limit < pool.length ? start + args.limit : null;+ const pageBudget = args.historyToolPageBudget === true ? new HistoryPageBudget() : null;// radius=0 is the conversation-search hot path. Hydrate the whole page in// one worker RPC; callers that need neighbours keep the original window query.const anchorContexts =- args.contextRadius <= 0+ args.contextRadius <= 0 && !pageBudget? await fetchAnchorContexts(pageEntries.map((entry) => entry.messageId)): null;// 5) 按命中顺序组装上下文窗口const hits: SearchChatHistoryHit[] = [];- for (const fe of pageEntries) {+ for (const [index, fe] of pageEntries.entries()) {+ if (pageBudget?.full) { nextOffset = start + index; break; }const meta = metaById.get(fe.messageId);if (!meta) continue; // 理论不会发生(fused 的 id 必来自两路 arm)const context =@@ -220,7 +224,7 @@ export async function searchChatHistoryHybrid(args.roles,args.contextRadius,));- hits.push({+ const hit: SearchChatHistoryHit = {messageId: fe.messageId,sessionId: meta.sessionId,role: meta.role,@@ -231,19 +235,19 @@ export async function searchChatHistoryHybrid(vectorRank: fe.vectorRank,vectorDistance: meta.distance,context,- });+ };+ if (pageBudget && !pageBudget.tryAdd(hit)) {+ nextOffset = start + index;+ break;+ }+ hits.push(hit);}// 6) session 元数据(顶层 map, 避免逐条命中重复)- const boundedHits = historyPageWithinBudget(hits);- if (boundedHits.length < hits.length) {- const last = boundedHits[boundedHits.length - 1];- nextOffset = start + pageEntries.findIndex(entry => entry.messageId === last.messageId) + 1;- }- const sessions = await fetchSessionsMeta(boundedHits.map((h) => h.sessionId));+ const sessions = await fetchSessionsMeta(hits.map((h) => h.sessionId));return {- hits: boundedHits,+ hits,sessions,vectorUsed: vec.skipReason === null,vectorSkipReason: vec.skipReason,diff --git a/apps/desktop/src/main/localDb/historyPageBudget.ts b/apps/desktop/src/main/localDb/historyPageBudget.tsindex 02c80ecbc2..92ebb985c6 100644--- a/apps/desktop/src/main/localDb/historyPageBudget.ts+++ b/apps/desktop/src/main/localDb/historyPageBudget.ts@@ -2,13 +2,26 @@* A single oversized record always makes progress and remains readable in full.* Never slice content: callers advance their native cursor at the last kept row.*/+export class HistoryPageBudget {+ private bytes = 2; // array brackets+ private count = 0;++ get full(): boolean { return this.bytes >= 64 * 1024; }++ tryAdd(item: unknown): boolean {+ const size = Buffer.byteLength(JSON.stringify(item), 'utf8') + (this.count ? 1 : 0);+ if (this.count > 0 && this.bytes + size > 64 * 1024) return false;+ this.bytes += size;+ this.count++;+ return true;+ }+}+export function historyPageWithinBudget<T>(items: T[]): T[] {- let bytes = 2; // array brackets+ const budget = new HistoryPageBudget();let count = 0;for (const item of items) {- const size = Buffer.byteLength(JSON.stringify(item), 'utf8') + (count ? 1 : 0);- if (count > 0 && bytes + size > 64 * 1024) break;- bytes += size;+ if (!budget.tryAdd(item)) break;count++;}return count === items.length ? items : items.slice(0, count);diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.mdindex a8e9d223e7..63e9101fb1 100644--- a/docs/product-rules/agent-user-parity.md+++ b/docs/product-rules/agent-user-parity.md@@ -171,6 +171,8 @@ Host 不因当前输入缺少主人标记再追加行动同意判定。只认运单条记录超过预算时仍完整返回,保证继续读取可以前进。调用方以 `hasMore` / `nextCursor`续读,不以返回条数少于 limit 判断结束。原始历史不改写、不另存摘要,所有 Harness 共用;跨电脑沿源设备同一查询与游标,旧设备保留其原有分页行为。+搜索预算仅由历史工具入口启用;界面搜索和学习证据等内部消费者保留按条数取页。+工具搜索逐条读取上下文并累计预算,到达边界后停止后续读取;游标保留未返回命中的位置。## 社区插件贡献diff --git a/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts b/packages/lizi-mcps/src/xdt-helper/search_chat_history.tsindex f207d2627e..26b0eb3a27 100644--- a/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts+++ b/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts@@ -166,7 +166,10 @@ export function registerSearchChatHistoryTool(const cursorWasBad = cursor !== undefined && cursor !== '' && offset === null;const effectiveRoles: HistoryRole[] = roles ?? [...DEFAULT_QA_ROLES];- const res = await deps.history.searchChatHistory({+ // Host-only hint travels with normalized args through the existing local+ // adapter (and the source device's tool registry). Public input has no knob.+ // Internal UI/learn callers omit it and keep count-based result pages.+ const searchArgs = {query: query.trim(),sessionIds: scope.sessionIds,...(args.teammate_id ? { teammateId: args.teammate_id } : {}),@@ -179,7 +182,9 @@ export function registerSearchChatHistoryTool(contextRadius: context_radius,limit,offset: offset ?? 0,- });+ historyToolPageBudget: true,+ };+ const res = await deps.history.searchChatHistory(searchArgs);if (!res.ok) {if (res.errorCode === 'HOST_NOT_READY') {return errorPayload(