Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 打开任务不再为没看到的计划翻十页 (#3179)
Dashcba38978dbf8
diff --git a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.tsindex dbf4f707c5..9f91603728 100644--- a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts+++ b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts@@ -296,6 +296,9 @@ describe('turn-done list preview refresh', () => {expect(latestSource).toContain('.orderBy(desc(messages.createdAt), desc(joinedMessageRowid))',);+ expect(latestSource).toContain(+ "CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.autoResume') END IS NOT 1",+ );});});diff --git a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.tsindex 5585c42302..75a6e371d5 100644--- a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { extractMessagePreview, messageToCamel } from '../mapper.js';+import { boundSerializedMessageContent, extractMessagePreview, messageToCamel } from '../mapper.js';const marker = '\uE200cite\uE202turn17search1\uE202turn17search2\uE201';@@ -50,4 +50,34 @@ describe('message mapper internal citation compatibility', () => {);expect(extractMessagePreview(JSON.stringify('用户说 <|eos|>'), 'user')).toBe('用户说 <|eos|>');});++ it('bounds oversized serialized content without cutting JSON in the middle', () => {+ const text = `hello ${'x'.repeat(5000)}`;+ const raw = JSON.stringify({ text, images: [], files: [] });+ const bounded = boundSerializedMessageContent(raw);+ expect(bounded).toBeDefined();+ const parsed = JSON.parse(bounded as string) as { text: string };+ expect(parsed.text.startsWith('hello ')).toBe(true);+ expect(parsed.text.length).toBe(4096);+ expect(extractMessagePreview(bounded, 'user')).toBe(parsed.text.slice(0, 140));+ });++ it('keeps short text valid when structured attachments make the payload oversized', () => {+ const raw = JSON.stringify({+ text: 'see this file',+ images: [],+ files: [{ path: '/tmp/notes.md', data: 'x'.repeat(5000) }],+ });+ const bounded = boundSerializedMessageContent(raw);+ const parsed = JSON.parse(bounded as string) as { text: string; files: unknown[] };+ expect(parsed.text).toBe('see this file');+ expect(extractMessagePreview(bounded, 'user')).toBe('see this file');+ });++ it('does not slice valid JSON that has no string text field', () => {+ const raw = JSON.stringify({ images: [{ data: 'x'.repeat(5000) }] });+ const bounded = boundSerializedMessageContent(raw);+ expect(bounded).toBe(raw);+ expect(extractMessagePreview(bounded, 'user')).toBeNull();+ });});diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.tsindex 608888a34d..9574e9a317 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts@@ -206,12 +206,10 @@ describe('sessions:list messageCount source', () => {it('keeps the production query pinned to the covering-index column', () => {const source = readFileSync(path.join(__dirname, '..', 'ipc', 'sessions.ts'), 'utf-8');- // 单行 get/update 路径:LEFT JOIN 形状,count 必须走覆盖索引列常量。- expect(source).toMatch(/const MESSAGE_COUNT_COL = messages\.sessionId;/);- expect(source).toMatch(/messageCount: count\(MESSAGE_COUNT_COL\),/);-- // list 路径:两段式,count 走标量子查询常量。+ // list / get / update 都走同一条标量子查询,不再 LEFT JOIN 该会话全部消息。expect(source).toMatch(/messageCount: SESSION_MESSAGE_COUNT_SQL,/);+ expect(source).not.toMatch(/leftJoin\(messages/);+ expect(source).not.toMatch(/MESSAGE_COUNT_COL/);// 标量子查询里必须是 count(*)(无 LEFT JOIN 补行,空会话得 0),且限定 session_id。expect(source).toMatch(/SESSION_MESSAGE_COUNT_SQL = sql<number>`\(\s*SELECT count\(\*\) FROM messages m WHERE m\.session_id = \$\{sessions\.id\}/,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.tsindex 786ec0b47b..04ba7001d2 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts@@ -444,9 +444,233 @@ describe('local-db:messages:list cursor', () => {expect(JSON.parse(stored.agent_meta)).toEqual({turnCostUsd: 0.777042,});- // list/session + one visibility scan (plus the direct storage assertion);- // never one SQLite query set per SDK segment.- expect(prepareSpy).toHaveBeenCalledTimes(5);+ // list/session + prior-user lookup + bounded visibility scan+ // (plus the direct storage assertion); never one SQLite query set per SDK segment.+ expect(prepareSpy).toHaveBeenCalledTimes(6);+ });++ it('does not scan older user rounds when projecting legacy turn cost', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ insertCostMessage(sqlite, { id: 'old-user', role: 'user', createdAt: 100 });+ insertCostMessage(sqlite, {+ id: 'old-assistant',+ role: 'assistant',+ createdAt: 200,+ agentMeta: { turnCostUsd: 9.99 },+ });+ insertCostMessage(sqlite, { id: 'user', role: 'user', createdAt: 1_000 });+ insertCostMessage(sqlite, {+ id: 'final',+ role: 'assistant',+ createdAt: 1_400,+ agentMeta: { turnCostUsd: 0.5 },+ });++ registerMessageIpc();+ const listHandler = h.handlers.get('local-db:messages:list');+ const rows = (await listHandler?.({}, 's1', { limit: 2 })) as Array<{+ id: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ const final = rows.find((row) => row.id === 'final');+ expect(final?.agentMeta).toMatchObject({+ turnCostUsd: 0.5,+ userTurnCostUsd: 0.5,+ });+ });++ it('returns oversized local history rows intact', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ const huge = 'x'.repeat(40_000);+ insertMessage(sqlite, { id: 'huge', createdAt: 1_000, content: huge });++ registerMessageIpc();+ const listHandler = h.handlers.get('local-db:messages:list');+ const rows = (await listHandler?.({}, 's1', { limit: 1 })) as Array<{+ id: string;+ content: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ expect(rows).toHaveLength(1);+ expect(rows[0]?.content).toBe(huge);+ expect(rows[0]?.agentMeta).toBeNull();+ });++ it('returns oversized around windows intact', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ const huge = 'y'.repeat(40_000);+ insertMessage(sqlite, { id: 'huge', createdAt: 1_000, content: huge });++ registerMessageIpc();+ const aroundHandler = h.handlers.get('local-db:messages:around');+ const rows = (await aroundHandler?.({}, 's1', 'huge', { radius: 0 })) as Array<{+ id: string;+ content: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ expect(rows).toHaveLength(1);+ expect(rows[0]?.content).toBe(huge);+ expect(rows[0]?.agentMeta).toBeNull();+ });++ it('keeps structured local user content instead of slicing it', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ sqlite+ .prepare(+ `+ INSERT INTO messages (+ id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at+ ) VALUES (+ 'user-row', 'user-row', 's1', 'user', @content, NULL, NULL, 1000, NULL+ )+ `,+ )+ .run({+ content: JSON.stringify({+ text: 'see this file',+ images: [],+ files: [{ path: '/tmp/notes.md' }],+ }),+ });++ registerMessageIpc();+ const listHandler = h.handlers.get('local-db:messages:list');+ const rows = (await listHandler?.({}, 's1', { limit: 1 })) as Array<{+ id: string;+ content: unknown;+ agentMeta: Record<string, unknown> | null;+ }>;+ expect(rows[0]?.content).toEqual({+ text: 'see this file',+ images: [],+ files: [{ path: '/tmp/notes.md' }],+ });+ expect(rows[0]?.agentMeta).toBeNull();+ });++ it('does not scan newer rounds after the current history page', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ insertCostMessage(sqlite, { id: 'user', role: 'user', createdAt: 1_000 });+ insertCostMessage(sqlite, {+ id: 'old-final',+ role: 'assistant',+ createdAt: 1_400,+ agentMeta: { turnCostUsd: 0.5 },+ });+ insertCostMessage(sqlite, { id: 'later-user', role: 'user', createdAt: 2_000 });+ for (let i = 0; i < 20; i += 1) {+ insertCostMessage(sqlite, {+ id: `later-${i}`,+ role: 'assistant',+ createdAt: 2_100 + i,+ agentMeta: { turnCostUsd: 1 },+ });+ }++ registerMessageIpc();+ const prepareSpy = vi.spyOn(sqlite, 'prepare');+ const listHandler = h.handlers.get('local-db:messages:list');+ const rows = (await listHandler?.({}, 's1', {+ limit: 2,+ beforeTs: 1_500,+ })) as Array<{+ id: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ const oldFinal = rows.find((row) => row.id === 'old-final');+ expect(oldFinal?.agentMeta).toMatchObject({+ turnCostUsd: 0.5,+ userTurnCostUsd: 0.5,+ });+ expect(prepareSpy.mock.calls.some((call) => String(call[0]).includes('later-19'))).toBe(false);+ });++ it('projects legacy turn cost when an older user row has malformed agent_meta', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ sqlite+ .prepare(+ `+ INSERT INTO messages (+ id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at+ ) VALUES (+ 'broken-user', 'broken-user', 's1', 'user', '""', NULL, '{not-json', 900, NULL+ )+ `,+ )+ .run();+ insertCostMessage(sqlite, { id: 'user', role: 'user', createdAt: 1_000 });+ insertCostMessage(sqlite, {+ id: 'final',+ role: 'assistant',+ createdAt: 1_400,+ agentMeta: { turnCostUsd: 0.5 },+ });++ registerMessageIpc();+ const listHandler = h.handlers.get('local-db:messages:list');+ const rows = (await listHandler?.({}, 's1', { limit: 2 })) as Array<{+ id: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ const final = rows.find((row) => row.id === 'final');+ expect(final?.agentMeta).toMatchObject({+ turnCostUsd: 0.5,+ userTurnCostUsd: 0.5,+ });+ });++ it('isolates malformed nearest prior user with CASE so list and around still hydrate', async () => {+ const sqlite = createDb();+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ sqlite+ .prepare(+ `+ INSERT INTO messages (+ id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at+ ) VALUES (+ 'broken-user', 'broken-user', 's1', 'user', '""', NULL, '{not-json', 900, NULL+ )+ `,+ )+ .run();+ insertCostMessage(sqlite, {+ id: 'final',+ role: 'assistant',+ createdAt: 1_400,+ agentMeta: { turnCostUsd: 0.5 },+ });++ registerMessageIpc();+ const prepareSpy = vi.spyOn(sqlite, 'prepare');+ const listHandler = h.handlers.get('local-db:messages:list');+ const aroundHandler = h.handlers.get('local-db:messages:around');+ const listRows = (await listHandler?.({}, 's1', { limit: 1 })) as Array<{+ id: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ const aroundRows = (await aroundHandler?.({}, 's1', 'final', { radius: 1 })) as Array<{+ id: string;+ agentMeta: Record<string, unknown> | null;+ }>;+ expect(listRows.find((row) => row.id === 'final')?.agentMeta).toMatchObject({+ turnCostUsd: 0.5,+ userTurnCostUsd: 0.5,+ });+ expect(aroundRows.find((row) => row.id === 'final')?.agentMeta).toMatchObject({+ turnCostUsd: 0.5,+ userTurnCostUsd: 0.5,+ });+ const hydrateSql = prepareSpy.mock.calls+ .map((call) => String(call[0]))+ .find((sql) => sql.includes('autoResume'));+ expect(hydrateSql).toEqual(expect.stringContaining('CASE WHEN json_valid'));+ expect(hydrateSql).not.toMatch(/json_valid\([^)]*\) = 0 OR json_extract/);});});diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 35944a1a62..d05463ff06 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -7,7 +7,7 @@*/import { ipcMain, BrowserWindow } from 'electron';-import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';+import { and, asc, eq, inArray, lt, lte, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';import { createId } from '@paralleldrive/cuid2';import { getDbClient } from '../client/current';@@ -55,6 +55,15 @@ const DEFAULT_LIMIT = 50;const MAX_LIMIT = 100;const MESSAGE_DELETION_USER_BOUNDARY_PAGE_SIZE = 32;const messageRowid = sql<number>`rowid`;+/**+ * Skip silent-stop autoResume user rows without letting one bad historical+ * agent_meta blob fail the whole page query. SQLite may evaluate+ * json_extract even when a sibling OR json_valid(...) = 0 is already true.+ */+function notAutoResumeAgentMetaSql() {+ return sql`(${messages.agentMeta} IS NULL OR CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.autoResume') END IS NOT 1)`;+}+type MessageRow = typeof messages.$inferSelect;type MessageRowWithRowid = MessageRow & { rowid: number };type DataOwnerBroadcastScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope>;@@ -947,7 +956,7 @@ export async function commitMessageDeletion(// agentMeta.autoResume / cleared_at。//// 刻意**不**广播 `_count.messages`:列表里 `_count.messages` 的权威口径是该会话的全部- // messages 行数(sessions.ts 的 SESSION_MESSAGE_COUNT_SQL / MESSAGE_COUNT_COL,不过滤+ // messages 行数(sessions.ts 的 SESSION_MESSAGE_COUNT_SQL,不过滤// role / rewind_at / cleared_at),而下面这个可见投影只数 user/assistant 行——一个正常// 会话里 tool_use / tool_result / thinking / error 行往往是它的几十倍,拿它去 patch 会把// 侧栏与手机端卡片的「N 条消息」改成明显偏小的值,且 shallow merge 消费端不会自己纠正,@@ -1897,6 +1906,10 @@ export async function readPriorUserRoundCost(* correct user-round total without rewriting legacy data or changing the raw* segment values used by every billing aggregate. New messages already carry* the persisted field and skip this path.+ *+ * Scan only from the oldest row on this page back to the previous real user+ * boundary. A full-session walk here used to re-read tens of thousands of+ * agent_meta blobs on every history page.*/async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]> {const legacyClientIds = new Set(@@ -1918,6 +1931,9 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]const sessionId = history[0]?.sessionId;if (!sessionId) return history;+ const oldestOnPage = oldestHistoryMessage(history);+ const oldestCreatedAtMs = Date.parse(oldestOnPage.createdAt);+ if (!Number.isFinite(oldestCreatedAtMs)) return history;const db = getDbClient().drizzle;const [session] = await db.select({ clearedAt: sessions.clearedAt })@@ -1926,6 +1942,47 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[].limit(1);const visibleAfterClear =session?.clearedAt == null ? [] : [gt(messages.createdAt, session.clearedAt)];+ const olderThanOldestOnPage =+ oldestOnPage.rowid != null+ ? or(+ lt(messages.createdAt, oldestCreatedAtMs),+ and(eq(messages.createdAt, oldestCreatedAtMs), lt(messageRowid, oldestOnPage.rowid)),+ )+ : lt(messages.createdAt, oldestCreatedAtMs);+ const priorUser = await db+ .select({+ createdAt: messages.createdAt,+ rowid: messageRowid,+ })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'user'),+ isNull(messages.rewindAt),+ ...visibleAfterClear,+ olderThanOldestOnPage,+ notAutoResumeAgentMetaSql(),+ ),+ )+ .orderBy(desc(messages.createdAt), desc(messageRowid))+ .limit(1);+ const newestOnPage = newestHistoryMessage(history);+ const newestCreatedAtMs = Date.parse(newestOnPage.createdAt);+ const fromPriorUser = priorUser[0]+ ? or(+ gt(messages.createdAt, priorUser[0].createdAt),+ and(eq(messages.createdAt, priorUser[0].createdAt), gte(messageRowid, priorUser[0].rowid)),+ )+ : undefined;+ const throughNewestOnPage = Number.isFinite(newestCreatedAtMs)+ ? newestOnPage.rowid != null+ ? or(+ lt(messages.createdAt, newestCreatedAtMs),+ and(eq(messages.createdAt, newestCreatedAtMs), lte(messageRowid, newestOnPage.rowid)),+ )+ : lte(messages.createdAt, newestCreatedAtMs)+ : undefined;const rows = await db.select({clientId: messages.clientId,@@ -1933,7 +1990,15 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]agentMeta: messages.agentMeta,}).from(messages)- .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt), ...visibleAfterClear))+ .where(+ and(+ eq(messages.sessionId, sessionId),+ isNull(messages.rewindAt),+ ...visibleAfterClear,+ ...(fromPriorUser ? [fromPriorUser] : []),+ ...(throughNewestOnPage ? [throughNewestOnPage] : []),+ ),+ ).orderBy(asc(messages.createdAt), asc(messageRowid));const totalsByClientId = new Map<string, PriorUserRoundCost>();@@ -2005,6 +2070,29 @@ function isAutoResumeUserMessage(agentMeta: string | null): boolean {return parseAgentMetaRecord(agentMeta)?.autoResume === true;}+function oldestHistoryMessage(history: Message[]): Message {+ return history.reduce((oldest, message) =>+ compareHistoryTimeline(message, oldest) < 0 ? message : oldest,+ );+}++function newestHistoryMessage(history: Message[]): Message {+ return history.reduce((newest, message) =>+ compareHistoryTimeline(message, newest) > 0 ? message : newest,+ );+}++function compareHistoryTimeline(a: Message, b: Message): number {+ const timeDiff = Date.parse(a.createdAt) - Date.parse(b.createdAt);+ if (Number.isFinite(timeDiff) && timeDiff !== 0) return timeDiff;+ const aRowid = typeof a.rowid === 'number' ? a.rowid : Number.NaN;+ const bRowid = typeof b.rowid === 'number' ? b.rowid : Number.NaN;+ if (Number.isFinite(aRowid) && Number.isFinite(bRowid) && aRowid !== bRowid) {+ return aRowid - bRowid;+ }+ return 0;+}+/** DB content 可为 JSON string、含 text 的对象,或迁移前遗留的裸文本。 */function readMessageText(content: string): string {try {diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 1a152a8561..66f6c6bdb2 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -9,7 +9,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import { ipcMain, app, BrowserWindow } from 'electron';-import { eq, ne, and, desc, count, inArray, isNotNull, isNull, sql, type SQL } from 'drizzle-orm';+import { eq, ne, and, desc, inArray, isNotNull, isNull, sql, type SQL } from 'drizzle-orm';import {clearPiSubagentDeletedTombstone,@@ -508,34 +508,18 @@ export async function persistSessionFields(const MAX_LIMIT = 1000;/**- * LEFT JOIN 形状下 `count()` 的目标列——必须是 `messages.session_id`,不能是 `messages.id`。- * 当前只有单行 get/update 路径({@link selectSessionWithCount})用这个形状。+ * list / get / update 共用的 messageCount:标量子查询。口径是该会话的全部 messages 行数,+ * 不过滤 role / rewind_at / cleared_at(口径要动就得连手机端卡片上的「N 条消息」一起想,+ * 见 maker-shared/sessionList 的 messageCountLabel)。*- * 三种写法只有一种可用:- * - `count(messages.id)` 语义对但**回表**:id 不在任何覆盖索引里,SQLite 为取它- * 必须逐行读 messages 主表。消息多的会话就是读几万行。- * - `count(*)` **语义错**:LEFT JOIN 对零消息会话也补一行,数出 1 而非 0,- * 会打歪 sidebar 的「单空 New Maker 草稿」判定。- * - `count(messages.session_id)` 语义对且免回表:session_id 是- * idx_messages_session_created 的首列。+ * 标量子查询没有 LEFT JOIN 补的那一行空行,无匹配时聚合返回 0,所以这里用 `count(*)` 是+ * 安全的。仍然只扫 idx_messages_session_created(session_id 是首列),不回表。*- * 代价差一个数量级。这个形状原先也用在 list 路径上(`LIMIT` 在 GROUP BY 之后才生效、削不掉- * 扫描量,于是成本正比于 messages 表**总体积**):4.7GB / 111 万条消息的真实库上同库同数据- * 实测冷缓存 10.2s → 1.25s、热缓存 920ms → 73ms。list 现已另走两段式(见- * {@link selectSessionListRows}),但 get/update 每次改标题、切模型都会跑这一条。+ * 旧的一段式 LEFT JOIN + GROUP BY 不能图快改用 `count(*)`:LEFT JOIN 会给空会话补一行,+ * 数出 1 而非 0,打歪 sidebar 的「单空 New Maker 草稿」判定。list 已改成两段式;get/update+ * 也走同一条标量子查询,避免切任务时把几万行 join 进单行快照。*- * 由 sessionListMessageCount 回归测试守护:它在真库上对照两种写法的 query plan(覆盖索引- * vs 回表)与空会话语义,并静态断言生产源码用的就是这一列。- */-const MESSAGE_COUNT_COL = messages.sessionId;--/**- * 两段式 list 里的 messageCount:标量子查询版。口径与 `count(MESSAGE_COUNT_COL)` 完全- * 一致——该会话的全部 messages 行数,不过滤 role / rewind_at / cleared_at(口径要动就得- * 连手机端卡片上的「N 条消息」一起想,见 maker-shared/sessionList 的 messageCountLabel)。- *- * 这里用 `count(*)` 反而是安全的:标量子查询没有 LEFT JOIN 补的那一行空行,无匹配时聚合- * 返回 0。仍然只扫 idx_messages_session_created(session_id 是首列),不回表。+ * 由 sessionListMessageCount 回归测试守护。*/const SESSION_MESSAGE_COUNT_SQL = sql<number>`(SELECT count(*) FROM messages m WHERE m.session_id = ${sessions.id}@@ -554,14 +538,14 @@ const SESSION_MESSAGE_COUNT_SQL = sql<number>`(// 见 register.ts handleSilentStopTurnEnd)不是用户消息,渲染层显示为「已自动继续」// 分隔卡,预览同样不能把它当最近消息展示(session.preview 经 device-link 直达手机// 首页,漏了会显示一条用户没发过的消息)。按落库标记过滤,不按文本——用户真发-// 「继续」是合法消息。json_extract 对 JSON true 返回 1;非 JSON / 缺字段返回 NULL,-// IS NOT 1 对两者都放行。+// 「继续」是合法消息。json_extract 对 JSON true 返回 1;缺字段返回 NULL,IS NOT 1 放行。+// 非法 JSON 必须用 CASE 挡住 json_extract,OR json_valid 不保证短路,会整句 malformed JSON。const LATEST_MSG_CONTENT_SQL = sql<string | null>`(SELECT m.content FROM messages mWHERE m.session_id = ${sessions.id}AND m.role IN ('user', 'assistant')AND m.rewind_at IS NULL- AND (m.agent_meta IS NULL OR json_extract(m.agent_meta, '$.autoResume') IS NOT 1)+ AND (m.agent_meta IS NULL OR CASE WHEN json_valid(m.agent_meta) THEN json_extract(m.agent_meta, '$.autoResume') END IS NOT 1)AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1)`.as('latest_message_content');@@ -570,7 +554,7 @@ const LATEST_MSG_ROLE_SQL = sql<string | null>`(WHERE m.session_id = ${sessions.id}AND m.role IN ('user', 'assistant')AND m.rewind_at IS NULL- AND (m.agent_meta IS NULL OR json_extract(m.agent_meta, '$.autoResume') IS NOT 1)+ AND (m.agent_meta IS NULL OR CASE WHEN json_valid(m.agent_meta) THEN json_extract(m.agent_meta, '$.autoResume') END IS NOT 1)AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1)`.as('latest_message_role');@@ -2066,9 +2050,8 @@ interface SessionListRow {* CTE 是单条语句、单一致性快照。* 2. 参数——`IN (...)` 要绑 cap 个参数(当前 MAX_LIMIT=1000),CTE 只绑一个 limit。*- * messageCount 在这里是**标量子查询**里的 `count(*)`,与一段式的 `count(MESSAGE_COUNT_COL)`- * 语义一致:无匹配行时聚合返回 0,不存在 LEFT JOIN 那个"空会话数出 1"的坑(那也是为什么- * 一段式不能图快改用 `count(*)`)。它同样只扫 idx_messages_session_created,不回表。+ * messageCount 在这里是**标量子查询**里的 `count(*)`:无匹配行时聚合返回 0,不存在 LEFT JOIN+ * 那个"空会话数出 1"的坑。它同样只扫 idx_messages_session_created,不回表。** @param where 行过滤条件,同时作用于 CTE 与主查询(CTE 决定取哪些、主查询决定算哪些)。* @param cap 取前 N 行;`null` = 不限(置顶补齐分支用,pinned 行数天然很少)。@@ -2100,11 +2083,9 @@ function selectSessionListRows(.orderBy(desc(sessions.updatedAt));}-/** 单行 SELECT + messages count:LEFT JOIN + GROUP BY 保证 0 条消息时 count 为 0。+/** 单行 SELECT + 标量 count / preview:与 list 同口径,不 JOIN 该会话全部消息。* preview 子查询同步带出——get/update 路径返回的 Session 会整体替换 store 里的行,- * 缺字段会把列表查询带回的 preview 冲掉。- * count 目标列同 list 路径走 {@link MESSAGE_COUNT_COL}:这里虽只数一个会话,但消息多的- * 会话回表一样要读几万行主表,而 get/update 在每次改标题、切模型后都会跑。 */+ * 缺字段会把列表查询带回的 preview 冲掉。 */async function selectSessionWithCount(db: DbClient['drizzle'],id: string,@@ -2112,14 +2093,12 @@ async function selectSessionWithCount(const [r] = await db.select({session: sessions,- messageCount: count(MESSAGE_COUNT_COL),+ messageCount: SESSION_MESSAGE_COUNT_SQL,latestMessageContent: LATEST_MSG_CONTENT_SQL,latestMessageRole: LATEST_MSG_ROLE_SQL,}).from(sessions)- .leftJoin(messages, eq(messages.sessionId, sessions.id)).where(eq(sessions.id, id))- .groupBy(sessions.id).limit(1);if (!r) return undefined;return {diff --git a/apps/desktop/src/main/localDb/latestMessageText.ts b/apps/desktop/src/main/localDb/latestMessageText.tsindex 58acbdd5d3..11961acbd2 100644--- a/apps/desktop/src/main/localDb/latestMessageText.ts+++ b/apps/desktop/src/main/localDb/latestMessageText.ts@@ -86,7 +86,9 @@ export async function latestVisiblePreviewRow(eq(messages.sessionId, sessionId),sql`${messages.role} IN ('user', 'assistant')`,isNull(messages.rewindAt),- sql`(${messages.agentMeta} IS NULL OR json_extract(${messages.agentMeta}, '$.autoResume') IS NOT 1)`,+ // SQLite may still evaluate json_extract when OR json_valid is false.+ // CASE keeps malformed historical agent_meta from failing the whole query.+ sql`(${messages.agentMeta} IS NULL OR CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.autoResume') END IS NOT 1)`,or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),),)diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex e63661d389..023b1f445b 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -84,6 +84,8 @@ export type SessionRowWithCount = SessionRow & {/** preview 最大长度(字符)。渲染端 3 行 line-clamp 之外的兜底硬上限。 */const PREVIEW_MAX_CHARS = 140;+/** Bound serialized content before JSON.parse so oversized rows stay valid JSON. */+const PREVIEW_CONTENT_BOUND_CHARS = 4096;/*** 从消息 content(DB 存的 JSON string)提炼 sidebar 卡片预览纯文本。@@ -121,6 +123,36 @@ export function extractMessagePreview(return collapsed.length > PREVIEW_MAX_CHARS ? collapsed.slice(0, PREVIEW_MAX_CHARS) : collapsed;}+/**+ * Bound oversized serialized message bodies before they enter the mapper.+ * Truncate the extracted text, then re-encode, so JSON objects stay valid and+ * `extractMessagePreview` still sees `.text` instead of a cut-off document.+ */+export function boundSerializedMessageContent(+ raw: string | null | undefined,+ maxChars = PREVIEW_CONTENT_BOUND_CHARS,+): string | null | undefined {+ if (raw == null || raw.length <= maxChars) return raw;+ try {+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed === 'string') {+ return JSON.stringify(parsed.slice(0, maxChars));+ }+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {+ const record = parsed as { text?: unknown };+ if (typeof record.text === 'string') {+ return JSON.stringify({+ ...record,+ text: record.text.length > maxChars ? record.text.slice(0, maxChars) : record.text,+ });+ }+ }+ return raw;+ } catch {+ return raw.slice(0, maxChars);+ }+}+/*** Session 行 → 与原 HTTP 响应同形的 camel + ISO 对象。*@@ -189,7 +221,10 @@ export function sessionToCamel(row: SessionRowWithCount): Session {createdAt: new Date(row.createdAt).toISOString(),updatedAt: new Date(row.updatedAt).toISOString(),_count: { messages: row.messageCount },- preview: extractMessagePreview(row.latestMessageContent, row.latestMessageRole),+ preview: extractMessagePreview(+ boundSerializedMessageContent(row.latestMessageContent),+ row.latestMessageRole,+ ),summary: row.summary ?? null,};}diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.tsindex 8fdc3afeee..0e8a198d33 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts@@ -242,7 +242,7 @@ describe('makerChatStore active view tracking', () => {it('initial history load backfills to the latest plan boundary', async () => {const sessionId = sid('initial-plan-backfill');- const latestPage = Array.from({ length: 50 }, (_, i) =>+ const latestPage = Array.from({ length: 49 }, (_, i) =>dbMessage(sessionId,`latest-${String(i).padStart(2, '0')}`,@@ -250,16 +250,23 @@ describe('makerChatStore active view tracking', () => {new Date(BASE_TIME.getTime() + (60 + i) * 1000).toISOString(),),);- const planRow = dbToolUseMessage(+ const latestPlan = dbToolUseMessage(+ sessionId,+ 'latest-plan',+ 'TaskUpdate',+ { taskId: 'abc', status: 'completed' },+ new Date(BASE_TIME.getTime() + 120_000).toISOString(),+ );+ const olderPlan = dbToolUseMessage(sessionId,'older-plan','update_plan',- { plan: [{ step: 'Restore pinned plan', status: 'in_progress' }] },+ { plan: [{ step: 'Older unresolved source', status: 'completed' }] },new Date(BASE_TIME.getTime() + 30_000).toISOString(),);vi.mocked(messageService.list)- .mockResolvedValueOnce(latestPage)- .mockResolvedValueOnce([planRow]);+ .mockResolvedValueOnce([...latestPage, latestPlan])+ .mockResolvedValueOnce([olderPlan]);makerChatStore.ensureInitialMessages(sessionId);await flushPromises();@@ -276,7 +283,7 @@ describe('makerChatStore active view tracking', () => {it('shows the latest page before background plan discovery completes', async () => {const sessionId = sid('initial-page-first');- const latestPage = Array.from({ length: 50 }, (_, i) =>+ const latestPage = Array.from({ length: 49 }, (_, i) =>dbMessage(sessionId,`latest-${String(i).padStart(2, '0')}`,@@ -284,9 +291,16 @@ describe('makerChatStore active view tracking', () => {new Date(BASE_TIME.getTime() + (60 + i) * 1000).toISOString(),),);+ const latestPlan = dbToolUseMessage(+ sessionId,+ 'latest-plan',+ 'TaskUpdate',+ { taskId: 'abc', status: 'completed' },+ new Date(BASE_TIME.getTime() + 120_000).toISOString(),+ );let resolveOlderPage!: (rows: Message[]) => void;vi.mocked(messageService.list)- .mockResolvedValueOnce(latestPage)+ .mockResolvedValueOnce([...latestPage, latestPlan]).mockReturnValueOnce(new Promise<Message[]>((resolve) => {resolveOlderPage = resolve;@@ -367,7 +381,7 @@ describe('makerChatStore active view tracking', () => {expect(snapshot.isLoadingMore).toBe(false);});- it('continues initial history backfill until the latest plan boundary is found', async () => {+ it('does not page through filler history on open just to find a later plan', async () => {const sessionId = sid('initial-plan-backfill-deep');vi.mocked(messageService.list).mockClear();const page = (prefix: string, startOffsetSeconds: number) =>@@ -397,15 +411,12 @@ describe('makerChatStore active view tracking', () => {makerChatStore.ensureInitialMessages(sessionId);await flushPromises();- expect(messageService.list).toHaveBeenCalledTimes(5);- expect(messageService.list).toHaveBeenNthCalledWith(5, sessionId, {- limit: 50,- before: 'older-3-00',- });- expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-plan');+ expect(messageService.list).toHaveBeenCalledTimes(1);+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('latest-00');+ expect(makerChatStore.getSnapshot(sessionId).historyLoaded).toBe(true);});- it('caps initial plan discovery backfill for sessions that never used plans', async () => {+ it('does not probe older pages on open for sessions that never used plans', async () => {const sessionId = sid('initial-plan-backfill-no-plan');vi.mocked(messageService.list).mockClear();const page = (prefix: string, startOffsetSeconds: number) =>@@ -426,8 +437,151 @@ describe('makerChatStore active view tracking', () => {makerChatStore.ensureInitialMessages(sessionId);await flushPromises(20);- expect(messageService.list).toHaveBeenCalledTimes(11);- expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-9-00');+ expect(messageService.list).toHaveBeenCalledTimes(1);+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('latest-00');+ expect(makerChatStore.getSnapshot(sessionId).historyLoaded).toBe(true);+ });++ it('loads one older page after idle when the newest page has no plan', async () => {+ const sessionId = sid('idle-plan-discovery');+ enter(sessionId);+ vi.mocked(messageService.list).mockClear();+ const latest = Array.from({ length: 50 }, (_, i) =>+ dbMessage(+ sessionId,+ `latest-${String(i).padStart(2, '0')}`,+ `latest message ${i}`,+ new Date(BASE_TIME.getTime() + (1000 + i) * 1000).toISOString(),+ ),+ );+ const olderPlan = [+ dbToolUseMessage(+ sessionId,+ 'idle-plan',+ 'update_plan',+ { plan: [{ step: 'Idle discovered plan', status: 'in_progress' }] },+ new Date(BASE_TIME.getTime() - 1_000).toISOString(),+ ),+ ];+ vi.mocked(messageService.list)+ .mockResolvedValueOnce(latest)+ .mockResolvedValueOnce(olderPlan);++ makerChatStore.ensureInitialMessages(sessionId);+ await flushPromises(20);+ expect(messageService.list).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(200);+ await flushPromises(20);++ expect(messageService.list).toHaveBeenCalledTimes(2);+ expect(messageService.list).toHaveBeenNthCalledWith(2, sessionId, {+ limit: 50,+ before: 'latest-00',+ });+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('idle-plan');+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(0);+ });++ it('continues idle discovery into plan resolution when the extra page is unresolved', async () => {+ const sessionId = sid('idle-plan-resolution');+ enter(sessionId);+ vi.mocked(messageService.list).mockClear();+ const latest = Array.from({ length: 50 }, (_, i) =>+ dbMessage(+ sessionId,+ `latest-${String(i).padStart(2, '0')}`,+ `latest message ${i}`,+ new Date(BASE_TIME.getTime() + (2000 + i) * 1000).toISOString(),+ ),+ );+ const unresolvedPage = [+ ...Array.from({ length: 49 }, (_, i) =>+ dbMessage(+ sessionId,+ `mid-${String(i).padStart(2, '0')}`,+ `mid message ${i}`,+ new Date(BASE_TIME.getTime() + (1000 + i) * 1000).toISOString(),+ ),+ ),+ dbToolUseMessage(+ sessionId,+ 'latest-task-update',+ 'TaskUpdate',+ { taskId: 'abc', status: 'completed' },+ new Date(BASE_TIME.getTime() + 1_500_000).toISOString(),+ ),+ ];+ const resolvedPage = [+ dbToolUseMessage(+ sessionId,+ 'task-create',+ 'TaskCreate',+ { subject: 'Collect logs' },+ new Date(BASE_TIME.getTime() - 2_000).toISOString(),+ ),+ dbToolResultMessage(+ sessionId,+ 'task-create-result',+ 'tool-task-create',+ 'Task #abc created successfully: Collect logs',+ new Date(BASE_TIME.getTime() - 1_000).toISOString(),+ ),+ ];+ vi.mocked(messageService.list)+ .mockResolvedValueOnce(latest)+ .mockResolvedValueOnce(unresolvedPage)+ .mockResolvedValueOnce(resolvedPage);++ makerChatStore.ensureInitialMessages(sessionId);+ await flushPromises(20);+ expect(messageService.list).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(200);+ await flushPromises(20);++ expect(messageService.list).toHaveBeenCalledTimes(3);+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('task-create');+ });++ it('schedules idle plan discovery when a prefetched session later mounts', async () => {+ const sessionId = sid('prefetch-then-enter');+ vi.mocked(messageService.list).mockClear();+ const latest = Array.from({ length: 50 }, (_, i) =>+ dbMessage(+ sessionId,+ `latest-${String(i).padStart(2, '0')}`,+ `latest message ${i}`,+ new Date(BASE_TIME.getTime() + (1000 + i) * 1000).toISOString(),+ ),+ );+ const olderPlan = [+ dbToolUseMessage(+ sessionId,+ 'prefetch-plan',+ 'update_plan',+ { plan: [{ step: 'Prefetch discovered plan', status: 'in_progress' }] },+ new Date(BASE_TIME.getTime() - 1_000).toISOString(),+ ),+ ];+ vi.mocked(messageService.list)+ .mockResolvedValueOnce(latest)+ .mockResolvedValueOnce(olderPlan);++ makerChatStore.ensureInitialMessages(sessionId);+ await flushPromises(20);+ expect(messageService.list).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(200);+ await flushPromises(20);+ expect(messageService.list).toHaveBeenCalledTimes(1);++ enter(sessionId);+ await vi.advanceTimersByTimeAsync(200);+ await flushPromises(20);++ expect(messageService.list).toHaveBeenCalledTimes(2);+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('prefetch-plan');});it('continues initial plan backfill past older sources until a latest TaskUpdate can be resolved', async () => {diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.tsindex b345b06c01..27fd6e9c94 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts@@ -1350,7 +1350,7 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {expect(restoreSessionAutomaticHistoryLoadAttempts(SID, 5)).toBe(5);});- it('Y2. 超长裁剪丢掉当前计划边界时,允许重入重新首拉补回计划', async () => {+ it('Y2. 超长裁剪丢掉当前计划边界时,仍保留 historyLoaded,不把打开路径打回全量首拉', async () => {const oldPlan = planToolMessage({id: 'trimmed-plan',clientId: 'trimmed-plan',@@ -1380,7 +1380,100 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {const snapshot = makerChatStore.getSnapshot(SID);expect(snapshot.messages).toHaveLength(200);expect(snapshot.messages.some((message) => message.clientId === 'trimmed-plan')).toBe(false);- expect(snapshot.historyLoaded).toBe(false);+ expect(snapshot.historyLoaded).toBe(true);+ });++ it('Y3. 裁剪后窗口仍含孤岛时,空闲补页从最新连续尾段下沿填缺口,不从孤岛往更老处翻', async () => {+ // 最新连续尾段只有 50 行,around 孤岛 260 行 → 裁剪保留 200 行后仍夹着孤岛。+ // 未解析计划落在孤岛与尾段之间的缺口:若 trim 把 oldestMessageId 清成 null,+ // loadOlderMessages 会拿 messages[0](孤岛)走 beforeTs,向更老处分页,永远填不上缺口。+ const island = Array.from({ length: 260 }, (_, i) =>+ serverMessage({+ id: `island-${String(i).padStart(3, '0')}`,+ clientId: `island-${String(i).padStart(3, '0')}`,+ createdAt: new Date(Date.UTC(2026, 6, 1, 0, 0, 0) + i * 1000).toISOString(),+ }),+ );+ const newestTail = Array.from({ length: 50 }, (_, i) =>+ serverMessage({+ id: `tail-${String(i).padStart(2, '0')}`,+ clientId: `tail-${String(i).padStart(2, '0')}`,+ createdAt: new Date(Date.UTC(2026, 6, 25, 12, 0, 0) - i * 60_000).toISOString(),+ }),+ );+ vi.mocked(aroundMessagesByClientIdFor).mockResolvedValueOnce(island);+ vi.mocked(listMessagesFor).mockResolvedValueOnce(newestTail);++ await makerChatStore.loadAroundMessageClientId(SID, 'island-000', { radius: 60 });+ expect(makerChatStore.getSnapshot(SID).messages.length).toBeGreaterThan(300);+ expect(makerChatStore.getSnapshot(SID).historyWindowHasIsland).toBe(true);+ const contiguousCursor = makerChatStore.getSnapshot(SID).oldestMessageId;+ expect(contiguousCursor).toBe('tail-49');+ markSessionAutomaticHistoryLoadCompleted(SID);++ const leave = makerChatStore.enterView(SID);+ leave();++ const trimmed = makerChatStore.getSnapshot(SID);+ expect(trimmed.messages).toHaveLength(200);+ expect(trimmed.historyWindowHasIsland).toBe(true);+ expect(trimmed.historyLoaded).toBe(true);+ expect(trimmed.messages[0]?.clientId.startsWith('island-')).toBe(true);+ expect(trimmed.messages.some((message) => message.clientId === 'tail-49')).toBe(true);+ // 关键:游标留在最新连续尾段下沿,而不是清成 null / 孤岛 id。+ expect(trimmed.oldestMessageId).toBe(contiguousCursor);++ vi.mocked(listMessagesFor).mockClear();+ vi.mocked(listMessagesFor).mockResolvedValueOnce([+ planToolMessage({+ id: 'gap-plan',+ clientId: 'gap-plan',+ createdAt: '2026-07-10T12:00:00.000Z',+ }),+ ]);+ await makerChatStore.loadOlderMessages(SID, false, 1);++ expect(listMessagesFor).toHaveBeenCalledWith(SID, { limit: 50, before: 'tail-49' });+ expect(listMessagesFor).not.toHaveBeenCalledWith(+ SID,+ expect.objectContaining({ beforeTs: expect.any(Number) }),+ );+ expect(makerChatStore.getSnapshot(SID).messages.some((message) => message.clientId === 'gap-plan')).toBe(+ true,+ );+ });++ it('Y4. 孤岛与尾段间隔不足 HISTORY_GAP_SPLIT_MS 时,裁剪仍保留结构化游标', async () => {+ const island = Array.from({ length: 260 }, (_, i) =>+ serverMessage({+ id: `near-island-${String(i).padStart(3, '0')}`,+ clientId: `near-island-${String(i).padStart(3, '0')}`,+ createdAt: new Date(Date.UTC(2026, 6, 25, 11, 40, 0) + i * 1000).toISOString(),+ }),+ );+ const newestTail = Array.from({ length: 50 }, (_, i) =>+ serverMessage({+ id: `near-tail-${String(i).padStart(2, '0')}`,+ clientId: `near-tail-${String(i).padStart(2, '0')}`,+ createdAt: new Date(Date.UTC(2026, 6, 25, 12, 0, 0) - i * 5_000).toISOString(),+ }),+ );+ vi.mocked(aroundMessagesByClientIdFor).mockResolvedValueOnce(island);+ vi.mocked(listMessagesFor).mockResolvedValueOnce(newestTail);++ await makerChatStore.loadAroundMessageClientId(SID, 'near-island-000', { radius: 60 });+ expect(makerChatStore.getSnapshot(SID).historyWindowHasIsland).toBe(true);+ const contiguousCursor = makerChatStore.getSnapshot(SID).oldestMessageId;+ expect(contiguousCursor).toBe('near-tail-49');+ markSessionAutomaticHistoryLoadCompleted(SID);++ const leave = makerChatStore.enterView(SID);+ leave();++ const trimmed = makerChatStore.getSnapshot(SID);+ expect(trimmed.messages).toHaveLength(200);+ expect(trimmed.oldestMessageId).toBe(contiguousCursor);+ expect(trimmed.messages[0]?.clientId.startsWith('near-island-')).toBe(true);});it('X. /clear 清空窗口时一并清掉孤岛标记,不把会话永久钉在"不连续"', async () => {diff --git a/apps/desktop/src/renderer/lib/historyGap.ts b/apps/desktop/src/renderer/lib/historyGap.tsindex b8ef743deb..c88f1e3d82 100644--- a/apps/desktop/src/renderer/lib/historyGap.ts+++ b/apps/desktop/src/renderer/lib/historyGap.ts@@ -2,8 +2,9 @@* 历史窗口空洞的判定阈值 —— 桌面侧入口,正本在 `@cindy/maker-shared/history-gap`。** 桌面消费方:`components/chat/MessageStream` —— tool_segment 按它切段、工作组按它切组。- * makerChatStore 一度按它模拟切段来估算跳转补齐预算,现已改为按行数取保守上界- * (见 JUMP_BACKFILL_MAX_ITEMS),不再依赖本常量。+ * makerChatStore 用同一把尺子识别裁剪后窗口里「孤岛 + 最新连续尾段」的缺口,好把+ * 向上翻页的游标留在尾段下沿(见 oldestMessageOfNewestContiguousRun);跳转补齐预算+ * 本身仍按行数取保守上界(JUMP_BACKFILL_MAX_ITEMS),不按本常量估算。** 为什么保留这层 re-export 而不让 MessageStream 直接引 shared:阈值原本是桌面常量,* 手机端接入后成为两端共用的产品级阈值(见正本文件头的完整理由)。留住这个路径让桌面侧diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 32c9ae27ad..189510e2bb 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -127,6 +127,7 @@ import {markSessionAutomaticHistoryLoadCompleted,resetSessionAutomaticHistoryLoadCompletion,} from '@/lib/sessionScrollStore';+import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';import { extractIpcError } from '@/utils/ipcError';import { tryBeginAgentSendDispatch } from '@/lib/agentSwitchCoordinator';import { getUserPrompt } from '@/lib/userPromptStore';@@ -348,6 +349,8 @@ export interface AskUserQuestionItem {export interface ChatMessage {clientId: string;+ /** Server message id when this row came from history; used as a pagination cursor. */+ id?: string;/** chat-text-quote:开头 blockquote 为引用功能产出(渲染判据),见 imageRef.ts。 */quotesEncoded?: boolean;/** Hidden semantic projection metadata for rich user-message references. */@@ -3308,6 +3311,7 @@ function _purgeSession(sessionId: string): void {bumpRendererClearGeneration(sessionId);cancelRemoteOptimisticSendsForSessionPurge(sessionId);clearWakeBridgeReconcileTimer(sessionId);+ cancelIdlePlanDiscovery(sessionId);sessions.delete(sessionId);localSentUserMessageIds.delete(sessionId);pendingLocalRetryIntents.delete(sessionId);@@ -3399,17 +3403,53 @@ function _isSessionBusy(sessionId: string, s: SessionChatState): boolean {);}+/**+ * 已加载窗口里最新连续段的最老一行。+ *+ * `messages` 是 oldest-first。窗口可能是「更老的孤岛 + 缺口 + 最新连续尾段」,+ * 此时 `messages[0]` 是孤岛边缘,不是向上翻页该用的游标。切段尺子与渲染层相同+ * (`HISTORY_GAP_SPLIT_MS`);没有超过该阈值的空洞时,整窗都算最新连续段。+ */+function oldestMessageOfNewestContiguousRun(messages: ChatMessage[]): ChatMessage | null {+ if (messages.length === 0) return null;+ let runStart = 0;+ for (let i = 1; i < messages.length; i++) {+ const prev = messageTime(messages[i - 1].createdAt);+ const next = messageTime(messages[i].createdAt);+ if (!Number.isFinite(prev) || !Number.isFinite(next)) continue;+ if (next - prev > HISTORY_GAP_SPLIT_MS) runStart = i;+ }+ return messages[runStart] ?? null;+}++function messageMatchesHistoryCursor(+ message: ChatMessage,+ cursorId: string,+): boolean {+ return message.clientId === cursorId || message.id === cursorId;+}++function retainedWindowKeepsGapCursor(+ retained: ChatMessage[],+ oldestMessageId: string | null,+): boolean {+ if (typeof oldestMessageId !== 'string' || oldestMessageId.length === 0) return false;+ const cursorIndex = retained.findIndex((message) =>+ messageMatchesHistoryCursor(message, oldestMessageId),+ );+ return cursorIndex > 0;+}+function _trimMessagesIfNeeded(sessionId: string): void {const state = sessions.get(sessionId);if (!state || state.messages.length <= TRIM_THRESHOLD) return;if (_isSessionBusy(sessionId, state)) return;if (_activeViewSessions.has(sessionId)) return;- // 裁剪等于一次代际重置:它砍掉窗口中段、把 oldestMessageId 清空,in-flight 的翻页 /- // 跳转补齐若仍按 pre-trim 游标提交,就会把更老的一页直接接到保留的尾部上 —— 中间被裁掉- // 的区间成了新的空洞,而补齐还可能据此判 covered 并清掉孤岛标记(#676 review)。- // 所以照 reloadMessages / clear / edit-last 同一规矩:bump epoch 作废 in-flight,并由- // 本次重置自己释放分页锁。+ // 裁剪等于一次代际重置:它砍掉窗口中段。in-flight 的翻页 / 跳转补齐若仍按 pre-trim+ // 游标提交,就会把更老的一页直接接到保留的尾部上 —— 中间被裁掉的区间成了新的空洞,+ // 而补齐还可能据此判 covered 并清掉孤岛标记(#676 review)。所以照 reloadMessages /+ // clear / edit-last 同一规矩:bump epoch 作废 in-flight,并由本次重置自己释放分页锁。bumpMessagesEpoch(sessionId);setState(sessionId, (s) => {// 兜底早返(当前不可达:上面三道守卫都在 bump 之前,而 setState 是同步的、拿到的就是@@ -3418,21 +3458,21 @@ function _trimMessagesIfNeeded(sessionId: string): void {if (s.messages.length <= TRIM_THRESHOLD) {return s.isLoadingMore ? { ...s, isLoadingMore: false } : s;}- const preTrimPlanState = getLatestMessageTodoState(s.messages);- const trimmedMessages = s.messages.slice(-TRIM_TARGET);- const trimmedPlanState = getLatestMessageTodoState(trimmedMessages);- const needsPlanReloadAfterTrim =- s.historyLoaded &&- preTrimPlanState.insertion !== null &&- (!trimmedPlanState.hasPlanEvent || !trimmedPlanState.isResolved);-+ const retained = s.messages.slice(-TRIM_TARGET);+ // 连续尾段被裁短、孤岛已不在保留窗口里:游标清成 null,loadOlderMessages 走+ // beforeTs(messages[0]),从新的窗口下沿接着往更早翻。+ // 保留窗口里还夹着孤岛(最新连续尾段不足 200 行):必须留下「最新连续段最老一行」+ // 的精确游标。清成 null 后空闲恢复会拿 messages[0](孤岛)当 beforeTs,向更老处+ // 翻页,填不了孤岛与尾段之间的缺口,未解析计划会一直缺席到整窗重载。+ const keepGapCursor =+ s.historyWindowHasIsland === true &&+ retainedWindowKeepsGapCursor(retained, s.oldestMessageId);return {...s,- messages: trimmedMessages,+ messages: retained,hasMoreMessages: true,- oldestMessageId: null,+ oldestMessageId: keepGapCursor ? s.oldestMessageId : null,isLoadingMore: false,- ...(needsPlanReloadAfterTrim ? { historyLoaded: false } : {}),// 孤岛标记**保持原值**:`slice(-TRIM_TARGET)` 只保证"取最新的 200 行",不保证这 200 行// 连续 —— 若先前几次深跳留下多个孤岛、而真正连续的尾段不足 200 行,裁剪结果里就还夹着// 孤岛。清掉标记会让 canFocusWithoutJumpLoad 把命中孤岛当成已覆盖直接 focus,而从孤岛@@ -3440,8 +3480,6 @@ function _trimMessagesIfNeeded(sessionId: string): void {//// 代价是出现过孤岛的会话在裁剪后仍会多做补齐尝试;方向上是安全的那一侧。// 真正清零只发生在"整窗从最新重建"的路径(reloadMessages / clear / demote / purge)。- // 注意游标被清成 null:此时补齐会从最新页重新起翻(见 backfillHistoryUntil 的首页分支),- // 恰好能穿过缺失区间自愈。};});}@@ -3478,6 +3516,7 @@ function enterView(sessionId: string): () => void {_activeViewSessions.set(sessionId, (_activeViewSessions.get(sessionId) ?? 0) + 1);_lastViewedAt.delete(sessionId);_ensureDemoteTimer();+ scheduleIdlePlanDiscoveryIfNeeded(sessionId);return () => leaveView(sessionId);}@@ -3490,6 +3529,7 @@ function leaveView(sessionId: string): void {return;}_activeViewSessions.delete(sessionId);+ cancelIdlePlanDiscovery(sessionId);_lastViewedAt.set(sessionId, Date.now());if (_pendingErrorClearOnLeave.has(sessionId)) {_pendingErrorClearOnLeave.delete(sessionId);@@ -3520,6 +3560,7 @@ function _demoteIdleSessions(): void {// 等于代际重置,必须 bump epoch 作废 in-flight 的翻页 / 跳转补齐,并由本次重置释放// 分页锁。漏 bump 的后果是 in-flight 那一页按 demote 前的游标提交,把一段脱离上下文// 的旧历史 merge 进空切片(或重开后的新切片),最近的消息反而缺席(#676 review)。+ cancelIdlePlanDiscovery(sessionId);invalidateMessageHistoryWindow(sessionId);setState(sessionId, (s) => ({...s,@@ -9902,13 +9943,11 @@ function ensureInitialMessages(sessionId: string): void {// - 计划工具行:计划只在输入框上方的胶囊呈现,不在消息流中留锚点;// - 合成指令行:渲染 null,混在这些行里同样撑不出可见锚点。//- // PinnedPlanPanel 的唯一数据源同样是当前消息窗口。计划工具行不再在消息流中渲染,- // 所以冷开超过一页的会话时,如果最近一次 plan 在更早页,胶囊会直接消失。这里也继续- // 往前翻到最近 plan 边界,保证初始窗口能派生当前计划快照。- //- // 无锚点按 10 页(500 行)兜底。计划胶囊分两段:- // - 当前窗口没有任何计划事件时,最多探测 10 页,避免从未使用计划的长会话全量拉历史;- // - 已看到计划事件但最新 TaskUpdate 还缺创建/列表边界时,最多再补 10 页。+ // 计划 UI(胶囊或流内卡)都从当前消息窗口派生。打开路径不再为「第一页没看到+ // plan」去翻 10 页:绝大多数任务根本没有 plan,那次固定税会把单线程 DB worker+ // 堵住。无锚点仍按 10 页兜底;已经看到计划事件但最新 TaskUpdate 还缺创建/列表+ // 边界时继续补页。没看到 plan 的任务改到空闲后再最多翻 1 页+ // (见 scheduleIdlePlanDiscoveryIfNeeded)。窗口不完整时由渲染层决定不画半截卡。let merged: Message[] = existing;let oldestRow = oldestMessageRow(merged, 'newest-first');if (!oldestRow) {@@ -9939,7 +9978,6 @@ function ensureInitialMessages(sessionId: string): void {}let hasMore = serverMessagePageHasMore(existing);const MAX_NO_ANCHOR_BACKFILL_PAGES = 10;- const MAX_PLAN_DISCOVERY_BACKFILL_PAGES = 10;const MAX_PLAN_RESOLUTION_BACKFILL_PAGES = 10;// Make the newest page visible as soon as it arrives. `historyLoaded`@@ -9952,8 +9990,7 @@ function ensureInitialMessages(sessionId: string): void {const initialNeedsBackfill =hasMore &&(existing.every(isNonAnchorHistoryRow) ||- !initialPlanState.hasPlanEvent ||- !initialPlanState.isResolved);+ (initialPlanState.hasPlanEvent && !initialPlanState.isResolved));if (initialHasVisibleAnchor) {const initialMapped = mapServerMessages(existing);const initialOldestId = oldestRow.id;@@ -10002,10 +10039,7 @@ function ensureInitialMessages(sessionId: string): void {planState.hasPlanEvent &&!planState.isResolved &&planResolutionPagesFetched < MAX_PLAN_RESOLUTION_BACKFILL_PAGES;- const needsPlanBackfill = planState.hasPlanEvent- ? needsPlanResolution- : pagesFetched < MAX_PLAN_DISCOVERY_BACKFILL_PAGES;- if (!needsAnchorBackfill && !needsPlanBackfill) break;+ if (!needsAnchorBackfill && !needsPlanResolution) break;pagesFetched += 1;if (needsPlanResolution) planResolutionPagesFetched += 1;@@ -10118,6 +10152,7 @@ function ensureInitialMessages(sessionId: string): void {// 历史加载完 → 重建当前挂起交互:历史里被转 expired 的 ask/plan 在此翻回 pending// (按 requestId 去重,不重复),permission 重新置 pendingPermission。void reconcilePendingInteractions(sessionId, isCurrentHistoryLoad).catch(() => undefined);+ scheduleIdlePlanDiscoveryIfNeeded(sessionId);}).catch(() => {if (@@ -10147,6 +10182,72 @@ function ensureInitialMessages(sessionId: string): void {});}+const IDLE_PLAN_DISCOVERY_DELAY_MS = 200;+const _idlePlanDiscoveryHandles = new Map<string, ReturnType<typeof setTimeout>>();++function cancelIdlePlanDiscovery(sessionId: string): void {+ const handle = _idlePlanDiscoveryHandles.get(sessionId);+ if (handle === undefined) return;+ _idlePlanDiscoveryHandles.delete(sessionId);+ clearTimeout(handle);+}++function scheduleIdlePlanDiscoveryIfNeeded(sessionId: string): void {+ if (!_activeViewSessions.has(sessionId)) return;+ const state = sessions.get(sessionId);+ if (!state?.historyLoaded || state.isLoadingMore || !state.hasMoreMessages) return;+ const planState = getLatestMessageTodoState(state.messages, {+ taskHistoryMayBeIncomplete: state.hasMoreMessages || state.historyWindowHasIsland,+ });+ if (planState.hasPlanEvent && planState.isResolved) return;+ if (_idlePlanDiscoveryHandles.has(sessionId)) return;++ const run = () => {+ _idlePlanDiscoveryHandles.delete(sessionId);+ void loadOneOlderPageForPlanDiscovery(sessionId);+ };++ _idlePlanDiscoveryHandles.set(sessionId, setTimeout(run, IDLE_PLAN_DISCOVERY_DELAY_MS));+}++function loadOneOlderPageForPlanDiscovery(sessionId: string): Promise<boolean> {+ if (!_activeViewSessions.has(sessionId)) return Promise.resolve(false);+ const state = sessions.get(sessionId);+ if (!state?.historyLoaded || state.isLoadingMore || !state.hasMoreMessages) {+ return Promise.resolve(false);+ }+ const planState = getLatestMessageTodoState(state.messages, {+ taskHistoryMayBeIncomplete: state.hasMoreMessages || state.historyWindowHasIsland,+ });+ if (planState.hasPlanEvent && planState.isResolved) return Promise.resolve(false);+ if (planState.hasPlanEvent && !planState.isResolved) {+ return continuePlanResolutionAfterIdleDiscovery(sessionId).then(() => true);+ }+ // 先只翻 1 页。若这一页首次露出未解析完的 plan,再转入与首拉相同的有界 resolution+ // 回填;没有 plan 的长任务仍只付这一页。automatic=false:不消耗视口自动补载预算。+ return loadOlderMessages(sessionId, false, 1).then(async (advanced) => {+ if (!advanced) return false;+ await continuePlanResolutionAfterIdleDiscovery(sessionId);+ return advanced;+ });+}++const MAX_IDLE_PLAN_RESOLUTION_PAGES = 10;++async function continuePlanResolutionAfterIdleDiscovery(sessionId: string): Promise<void> {+ for (let page = 0; page < MAX_IDLE_PLAN_RESOLUTION_PAGES; page += 1) {+ if (!_activeViewSessions.has(sessionId)) return;+ const state = sessions.get(sessionId);+ if (!state?.historyLoaded || state.isLoadingMore || !state.hasMoreMessages) return;+ const planState = getLatestMessageTodoState(state.messages, {+ taskHistoryMayBeIncomplete: state.hasMoreMessages || state.historyWindowHasIsland,+ });+ if (!planState.hasPlanEvent || planState.isResolved) return;+ const advanced = await loadOlderMessages(sessionId, false, 1);+ if (!advanced) return;+ }+}+/*** rewind-session: force-reload the message slice from server after a rewind* commit. Server already soft-deleted (rewind_at) the truncated rows and the@@ -10706,7 +10807,11 @@ const MAX_LOAD_OLDER_PAGES = 10;* 行首守卫、空页、全程失败、代际作废和提交异常都返回 false。* automatic=true 时只在推进成功后耗尽该缓存窗口的跨 mount 自动补载预算。*/-function loadOlderMessages(sessionId: string, automatic = false): Promise<boolean> {+function loadOlderMessages(+ sessionId: string,+ automatic = false,+ maxPages = MAX_LOAD_OLDER_PAGES,+): Promise<boolean> {const state = getOrCreateState(sessionId);if (state.isLoadingMore || !state.hasMoreMessages) return Promise.resolve(false);@@ -10714,7 +10819,12 @@ function loadOlderMessages(sessionId: string, automatic = false): Promise<booleaif (state.oldestMessageId) {firstPageOpts = { limit: 50, before: state.oldestMessageId };} else if (state.messages.length > 0) {- const oldest = state.messages[0];+ // 无 ID 时默认用 messages[0]。有孤岛时那是孤岛最老行,beforeTs 会翻到缺口+ // 更早的一侧;改用最新连续段下沿,才能填孤岛与尾段之间的洞。+ const oldest =+ state.historyWindowHasIsland === true+ ? (oldestMessageOfNewestContiguousRun(state.messages) ?? state.messages[0])+ : state.messages[0];if (!oldest.createdAt) return Promise.resolve(false);const ts = new Date(oldest.createdAt).getTime();if (!Number.isFinite(ts)) return Promise.resolve(false);@@ -10743,7 +10853,7 @@ function loadOlderMessages(sessionId: string, automatic = false): Promise<boolealet hasMore = true;let oldestId: string | null = state.oldestMessageId;try {- for (let page = 0; page < MAX_LOAD_OLDER_PAGES; page++) {+ for (let page = 0; page < maxPages; page++) {const rows = await listMessagesFor(sessionId, pageOpts);if (rows.length === 0) {hasMore = false;@@ -15355,6 +15465,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {// mapped ChatMessage uniformly (each branch below builds a different// shape, easier to attach the timestamp once at the end).const createdAtById = new Map(serverMsgs.map((m) => [m.clientId, m.createdAt]));+ const serverIdByClientId = new Map(serverMsgs.map((m) => [m.clientId, m.id]));const rowidById = new Map(serverMsgs.map((m) => [m.clientId, m.rowid]));const remoteContentTruncatedById = new Map(serverMsgs.map((m) => [m.clientId, m.agentMeta?.remoteContentTruncated === true]),@@ -15834,6 +15945,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {return mapped.map((cm): ChatMessage => {const ts = createdAtById.get(cm.clientId);const iso = mapServerCreatedAt(cm, ts);+ const serverId = serverIdByClientId.get(cm.clientId);const rowid = rowidById.get(cm.clientId);const remoteContentTruncated = remoteContentTruncatedById.get(cm.clientId) === true;const remoteRowsTrimmed = remoteRowsTrimmedById.get(cm.clientId) === true;@@ -15843,7 +15955,8 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {rowid === undefined &&!remoteContentTruncated &&!remoteRowsTrimmed &&- !legacyUserTurnCost+ !legacyUserTurnCost &&+ !serverId) {return cm;}@@ -15851,6 +15964,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {...cm,...(legacyUserTurnCost ?? {}),...(iso ? { createdAt: iso } : {}),+ ...(typeof serverId === 'string' && serverId.length > 0 ? { id: serverId } : {}),...(rowid !== undefined ? { rowid } : {}),...(remoteContentTruncated ? { remoteContentTruncated: true } : {}),...(remoteRowsTrimmed ? { remoteRowsTrimmed: true } : {}),