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): 删除消息不再广播偏小的 _count.messages (#1287)

zhanghengxd8b4abfc66499
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 0bc484008f..574f7f34f1 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, count, eq, inArray, lt, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';
+import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { getDbClient } from '../client/current';
@@ -712,7 +712,6 @@ export async function commitMessageDeletion(
deletedClientIds: string[];
updatedAt: number;
preview: string | null;
- messageCount: number;
}> {
const now = Date.now();
const result = await getDbClient().tx('message.delete', {
@@ -747,11 +746,27 @@ export async function commitMessageDeletion(
}
void recomputePrRefsForSession(sessionId).catch(() => undefined);
- // sessions:patched 的消费者只做 shallow merge,不会主动重拉。删除后同步带出
- // canonical session-list projection,避免其它窗口 / device-link 控制端继续显示
- // 已删除的末条消息预览或旧 _count。count 口径与 sessions:list / preview 的可见消息保持一致。
+ // sessions:patched 的消费者只做 shallow merge,不会主动重拉。删除后同步带出 canonical
+ // preview,避免其它窗口 / device-link 控制端继续显示已删除的末条消息。preview 口径与
+ // sessions:list 的 LATEST_MSG_CONTENT_SQL 一致:可见 user/assistant,过滤 rewind_at /
+ // agentMeta.autoResume / cleared_at。
+ //
+ // 刻意**不**广播 `_count.messages`:列表里 `_count.messages` 的权威口径是该会话的全部
+ // messages 行数(sessions.ts 的 SESSION_MESSAGE_COUNT_SQL / MESSAGE_COUNT_COL,不过滤
+ // role / rewind_at / cleared_at),而下面这个可见投影只数 user/assistant 行——一个正常
+ // 会话里 tool_use / tool_result / thinking / error 行往往是它的几十倍,拿它去 patch 会把
+ // 侧栏与手机端卡片的「N 条消息」改成明显偏小的值,且 shallow merge 消费端不会自己纠正,
+ // 错值一直留到下次完整 reseed。
+ //
+ // 那为什么不顺手广播权威口径?因为删除对它的影响只有 0 或 +1,不值得每次删除多跑一次
+ // 全表 count:message.delete 事务(worker/opHandlers/tx.ts)先物理删掉该会话所有旧
+ // context_rebuild 行,再把目标行原地改成 message_tombstone(保留,不删行),最后插入
+ // 一个新的 context_rebuild 行——首次删除(无旧标记)净 +1,之后每次删旧插新、净 0。
+ // 差的这一行是用户看不见的隐藏派生行(普通列表 / 搜索 / 导出都按 rewind_at 过滤掉它),
+ // 下次完整 reseed 即收敛;而事务外单独查的标量本身也带竞态(并发落消息时它已不等于
+ // 「删除后那一刻」的值)。要真的同步就得广播不过滤的 count(*),见 issue #1282 的讨论。
+ // 口径要动得连 maker-shared/sessionList 的 messageCountLabel 一起改。
let preview: string | null = null;
- let messageCount = 0;
try {
const db = getDbClient().drizzle;
const [sessionRow] = await db
@@ -768,20 +783,13 @@ export async function commitMessageDeletion(
sql`(${messages.agentMeta} IS NULL OR json_extract(${messages.agentMeta}, '$.autoResume') IS NOT 1)`,
visibleAfterClear,
);
- const [[countRow], [latestRow]] = await Promise.all([
- db
- .select({ messageCount: count(messages.id) })
- .from(messages)
- .where(visibleMessageProjection),
- db
- .select({ content: messages.content, role: messages.role })
- .from(messages)
- .where(visibleMessageProjection)
- .orderBy(desc(messages.createdAt), desc(messageRowid))
- .limit(1),
- ]);
+ const [latestRow] = await db
+ .select({ content: messages.content, role: messages.role })
+ .from(messages)
+ .where(visibleMessageProjection)
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
preview = extractMessagePreview(latestRow?.content, latestRow?.role);
- messageCount = countRow?.messageCount ?? 0;
} catch (error) {
// 删除已经原子提交;投影查询失败不能把成功操作伪装成失败。广播保守空值,
// 后续 sessions:list / reseed 会按 DB 真相收敛。
@@ -796,7 +804,6 @@ export async function commitMessageDeletion(
deletedClientIds: result.messages.map((message) => message.clientId),
updatedAt: now,
preview,
- messageCount,
};
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts
index ea3bdc4c7d..9fc15c8848 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts
@@ -30,7 +30,6 @@ function makeDeps(
deletedClientIds,
updatedAt: 500,
preview: 'keep after',
- messageCount: 4,
})),
setPendingHandoff: vi.fn(),
onCommitted: vi.fn(),
@@ -41,7 +40,7 @@ function makeDeps(
}
describe('performMessageDeletion', () => {
- it('keeps deleted-session patch count on the visible message projection', () => {
+ it('keeps the deleted-session preview on the visible message projection', () => {
const source = readFileSync(resolve(process.cwd(), 'src/main/localDb/ipc/messages.ts'), 'utf8');
const deletionBlock = source.slice(
source.indexOf('export async function commitMessageDeletion'),
@@ -49,10 +48,56 @@ describe('performMessageDeletion', () => {
);
expect(deletionBlock).toContain('const visibleMessageProjection = and(');
- expect(deletionBlock).toContain(".where(visibleMessageProjection)");
+ expect(deletionBlock).toContain('.where(visibleMessageProjection)');
expect(deletionBlock).not.toContain('.where(eq(messages.sessionId, sessionId))');
});
+ /**
+ * issue #1282:删除路径一度用「可见 user/assistant 行数」去 patch `_count.messages`,而列表的
+ * 权威口径是全部 messages 行数(sessions.ts 的 SESSION_MESSAGE_COUNT_SQL),差几十倍。shallow
+ * merge 消费端不会自纠,错值留到下次 reseed。权威口径受删除影响只有 0 或 +1(见
+ * commitMessageDeletion 的注释),不值得每次删除多跑一次全表 count,故整个字段不再广播。
+ * 这几条静态断言守住「删除不按可见投影数行、不广播 _count」。
+ */
+ it('never patches _count.messages from the delete path', () => {
+ const messagesSource = readFileSync(
+ resolve(process.cwd(), 'src/main/localDb/ipc/messages.ts'),
+ 'utf8',
+ );
+ const deletionStart = messagesSource.indexOf('export async function commitMessageDeletion');
+ const deletionBlock = messagesSource.slice(
+ deletionStart,
+ messagesSource.indexOf('export function broadcastMessageDeleted'),
+ );
+ // 返回契约里不得再出现 messageCount——它就是 _count 广播的唯一来源。只看函数签名段,
+ // 因为下方注释本身要提这个名字解释原因。(切点找不到时先失败在这里,否则 slice(-1) 会把
+ // 整个文件当签名段,报出一个和真实原因无关的断言。)
+ const bodyStart = messagesSource.indexOf('const now = Date.now()', deletionStart);
+ expect(bodyStart).toBeGreaterThan(deletionStart);
+ const signatureBlock = messagesSource.slice(deletionStart, bodyStart);
+ expect(signatureBlock).not.toContain('messageCount');
+ // 也不得再对可见投影数行。只匹配真实查询写法——注释里提 count 口径是允许的。
+ expect(deletionBlock).not.toContain('.select({ messageCount');
+ expect(deletionBlock).not.toMatch(/count\(messages\./);
+
+ // 只切 broadcastSessionPatched 的对象字面量本身:整个 onCommitted 块里的注释也提 `_count`
+ // (说明为什么不发),连注释一起断言会把自己打挂。
+ const registerSource = readFileSync(
+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),
+ 'utf8',
+ );
+ const onCommittedStart = registerSource.indexOf('onCommitted: ({ sessionId, deletedClientIds');
+ expect(onCommittedStart).toBeGreaterThan(-1);
+ const patchStart = registerSource.indexOf(
+ 'broadcastSessionPatched(sessionId, {',
+ onCommittedStart,
+ );
+ expect(patchStart).toBeGreaterThan(-1);
+ const patchBlock = registerSource.slice(patchStart, registerSource.indexOf('});', patchStart));
+ expect(patchBlock).toContain('preview,');
+ expect(patchBlock).not.toContain('_count');
+ });
+
it('closes the old native session and rebuilds handoff from history without the target', async () => {
const deps = makeDeps();
@@ -84,7 +129,6 @@ describe('performMessageDeletion', () => {
deletedClientIds: ['target'],
updatedAt: 500,
preview: 'keep after',
- messageCount: 4,
},
'target',
);
diff --git a/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts b/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts
index f56115c98d..737387e754 100644
--- a/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts
@@ -22,12 +22,16 @@ interface MessageDeleteSessionRow {
agentKind: string;
}
+/**
+ * 不含 messageCount:删除对 `_count.messages` 权威口径(全部 messages 行数)的影响只有
+ * 0 或 +1(见 commitMessageDeletion 的注释),不值得为此每次删除多跑一次全表 count,故
+ * 删除路径不 patch 该字段,由 sessions:list / reseed 提供权威值。见 issue #1282。
+ */
interface MessageDeleteCommittedPayload {
sessionId: string;
deletedClientIds: string[];
updatedAt: number;
preview: string | null;
- messageCount: number;
}
export interface MessageDeleteHandlerDeps {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c96cdc6d58..25702a014c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -5269,20 +5269,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
setPendingHandoff: (sessionId, handoff, expectedGeneration) =>
agentHandoffPending.set(sessionId, handoff, expectedGeneration),
readPendingHandoffGeneration: (sessionId) => agentHandoffPending.readGeneration(sessionId),
- onCommitted: (
- { sessionId, deletedClientIds, updatedAt, preview, messageCount },
- requestedClientId,
- ) => {
+ onCommitted: ({ sessionId, deletedClientIds, updatedAt, preview }, requestedClientId) => {
broadcastMessageDeleted({
sessionId,
clientId: requestedClientId,
clientIds: deletedClientIds,
});
+ // 不带 _count:可见消息数不是列表的权威口径,拿它 patch 的错值会被 shallow merge 一直
+ // 留住;权威口径受删除影响只有 0 或 +1,交给 sessions:list / reseed 收敛就够。
+ // 见 commitMessageDeletion 的注释与 issue #1282。
broadcastSessionPatched(sessionId, {
sdkSessionId: null,
updatedAt: new Date(updatedAt).toISOString(),
preview,
- _count: { messages: messageCount },
});
},
withCloseSuppressed: withRehydrateCloseSuppressed,