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(pi): broadcast every hidden clientId from tree rehydrate to avoid stale renderer rows

Chris7abb511aac60
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index 6ec282554c..7cffc53c2a 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -968,22 +968,28 @@ function sessionTreeRehydrate(readyDb, args) {
createdAt: expectNumber(row.createdAt, 'messages.' + index + '.createdAt'),
};
});
+ const selectVisibleClientIds = readyDb.prepare(
+ 'SELECT client_id FROM messages WHERE session_id = ? AND rewind_at IS NULL',
+ );
const hideVisible = readyDb.prepare(
'UPDATE messages SET rewind_at = ? WHERE session_id = ? AND rewind_at IS NULL',
);
const upsert = readyDb.prepare(
'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at, rewind_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL) ON CONFLICT(session_id, client_id) DO UPDATE SET role = excluded.role, content = excluded.content, tool_use_id = excluded.tool_use_id, agent_meta = excluded.agent_meta, agent_kind = excluded.agent_kind, created_at = excluded.created_at, rewind_at = NULL',
);
- readyDb.transaction(() => {
+ const hiddenClientIds = readyDb.transaction(() => {
const session = readyDb.prepare('SELECT id FROM sessions WHERE id = ? LIMIT 1').get(sessionId);
if (!session) throw Object.assign(new Error('Session 不存在: ' + sessionId), { code: 'NOT_FOUND' });
+ // 与 worker/opHandlers/tx.ts 保持同步:原子快照可见集再隐藏,导航期间并发落库的消息也纳入。
+ const captured = selectVisibleClientIds.all(sessionId).map((row) => row.client_id);
hideVisible.run(now, sessionId);
for (const row of rows) {
upsert.run(row.id, row.clientId, sessionId, row.role, row.content, row.toolUseId, row.agentMeta, row.agentKind, row.createdAt);
}
readyDb.prepare('UPDATE sessions SET cleared_at = NULL, context_tokens = ?, context_window = ?, updated_at = ? WHERE id = ?').run(contextTokens, contextWindow, now, sessionId);
+ return captured;
})();
- return { messageCount: rows.length };
+ return { messageCount: rows.length, hiddenClientIds };
}
function selectRewindMessageIds(rows, opts) {
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index 1a2d84f315..8ee97f54d3 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -589,7 +589,12 @@ describe('db worker tx handlers', () => {
createdAt: 201,
},
],
- })).resolves.toEqual({ messageCount: 2 });
+ })).resolves.toEqual({
+ messageCount: 2,
+ // 隐藏动作那一刻的完整可见集(只有 shared-client 可见;hidden-client 早已 rewind),
+ // 供调用方作删除广播的权威集 —— 含导航期间并发落库的消息。
+ hiddenClientIds: ['shared-client'],
+ });
await expect(client.query(
'SELECT id, client_id, content, created_at, rewind_at FROM messages WHERE session_id = ? ORDER BY id',
@@ -617,6 +622,49 @@ describe('db worker tx handlers', () => {
});
});
+ it('session.treeRehydrate returns every hidden clientId so a concurrently-persisted message is broadcast for removal', async () => {
+ // codex review 回归:导航前的陈旧快照会漏掉导航期间并发落库的消息,使它被 rewind
+ // 后仍留在 Renderer。事务内原子快照可见集,返回集须含这条并发消息的 clientId。
+ await withClient(async (client) => {
+ await seedSession(client, 's1', { contextTokens: 10 });
+ await client.exec(
+ `INSERT INTO messages
+ (id, client_id, session_id, role, content, agent_meta, agent_kind, created_at, rewind_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ [
+ 'pre-visible', 'client-pre', 's1', 'user', JSON.stringify('before navigation'),
+ null, 'pi', 100, null,
+ // 模拟导航进行中另一个窗口并发落库、导航前快照未见的消息。
+ 'concurrent', 'client-concurrent', 's1', 'assistant', JSON.stringify('sent mid-navigation'),
+ null, 'pi', 150, null,
+ ],
+ );
+
+ const result = await client.tx('session.treeRehydrate', {
+ sessionId: 's1',
+ now: 2000,
+ contextTokens: 5,
+ contextWindow: 200000,
+ messages: [
+ {
+ id: 'active', clientId: 'client-active', role: 'assistant',
+ content: JSON.stringify('new active path'), toolUseId: null,
+ agentMeta: null, agentKind: 'pi', createdAt: 300,
+ },
+ ],
+ });
+
+ // 两条导航前可见的消息(含并发落库的 client-concurrent)都要进删除广播集。
+ expect(result.messageCount).toBe(1);
+ expect([...result.hiddenClientIds].sort()).toEqual(['client-concurrent', 'client-pre']);
+ // 并发消息确实被 rewind(不再可见),否则 Renderer 会继续显示 DB 里已隐藏的它。
+ await expect(client.query(
+ 'SELECT client_id FROM messages WHERE session_id = ? AND rewind_at IS NULL ORDER BY client_id',
+ ['s1'],
+ )).resolves.toEqual([{ client_id: 'client-active' }]);
+ });
+ });
+
it('sessions.renameTitles applies title changes atomically with preconditions', async () => {
await withClient(async (client) => {
await seedSession(client, 's1', {
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 457bbd6bad..451f9dad40 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -720,7 +720,7 @@ export type DbTxResultByName = {
'codex.importMessages': { changed: number };
'claude.importMessages': { changed: number };
'rewind.commit': undefined;
- 'session.treeRehydrate': { messageCount: number };
+ 'session.treeRehydrate': { messageCount: number; hiddenClientIds: string[] };
'fork.session': { messageCount: number };
'embedding.markDone': undefined;
'embedding.commit': undefined;
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 1448c8f1e1..35316e03b0 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -621,7 +621,7 @@ function rewindCommit(db: Database.Database, args: unknown): void {
function sessionTreeRehydrate(
db: Database.Database,
args: unknown,
-): { messageCount: number } {
+): { messageCount: number; hiddenClientIds: string[] } {
const payload = asRecord(args, 'session.treeRehydrate args');
const sessionId = expectString(payload.sessionId, 'sessionId');
const now = expectNumber(payload.now, 'now');
@@ -642,6 +642,9 @@ function sessionTreeRehydrate(
createdAt: expectNumber(row.createdAt, `messages.${index}.createdAt`),
};
});
+ const selectVisibleClientIds = db.prepare(
+ 'SELECT client_id FROM messages WHERE session_id = ? AND rewind_at IS NULL',
+ );
const hideVisible = db.prepare(
'UPDATE messages SET rewind_at = ? WHERE session_id = ? AND rewind_at IS NULL',
);
@@ -658,9 +661,13 @@ function sessionTreeRehydrate(
created_at = excluded.created_at,
rewind_at = NULL`,
);
- const transaction = db.transaction(() => {
+ const transaction = db.transaction((): string[] => {
const session = db.prepare('SELECT id FROM sessions WHERE id = ? LIMIT 1').get(sessionId);
if (!session) throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });
+ // 原子快照当前可见集,再隐藏:导航期间(带摘要可等数分钟)并发落库的消息也在其中,
+ // 交给调用方作删除广播的权威集 —— 避免用导航前的陈旧快照漏掉这条(codex review)。
+ const hiddenClientIds = (selectVisibleClientIds.all(sessionId) as { client_id: string }[])
+ .map((row) => row.client_id);
hideVisible.run(now, sessionId);
for (const row of rows) {
upsert.run(
@@ -680,9 +687,10 @@ function sessionTreeRehydrate(
SET cleared_at = NULL, context_tokens = ?, context_window = ?, updated_at = ?
WHERE id = ?`,
).run(contextTokens, contextWindow, now, sessionId);
+ return hiddenClientIds;
});
- transaction();
- return { messageCount: rows.length };
+ const hiddenClientIds = transaction();
+ return { messageCount: rows.length, hiddenClientIds };
}
interface RewindMessageRow {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 3d059917d5..59d88a71ff 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -9073,10 +9073,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
const sess = await getOrResumeSessionTreeSession(sessionId);
if (!sess || !sess.capabilities.sessionTree?.supported) return null;
- const oldRows = await getDbClient().drizzle
- .select({ clientId: messages.clientId })
- .from(messages)
- .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt)));
const result = await sess.navigateSessionTree(entryId, {
summarize: parsed.summarize === true,
...(typeof parsed.customInstructions === 'string'
@@ -9084,7 +9080,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: {}),
});
const now = Date.now();
- await getDbClient().tx('session.treeRehydrate', {
+ // hiddenClientIds 由重投影事务原子返回:它是隐藏动作发生那一刻的完整可见集,
+ // 含导航期间(带摘要可等数分钟)并发落库的消息 —— 用导航前的陈旧快照会漏掉这条,
+ // 导致它被 rewind 后仍留在已打开的 Renderer 里直到重载(codex review)。
+ const { hiddenClientIds } = await getDbClient().tx('session.treeRehydrate', {
sessionId,
now,
contextTokens: result.contextTokens,
@@ -9103,12 +9102,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
resetTurnPersistState(sessionId);
// 多窗口与 device-link 控制端先清旧投影,再按 DB 真相补当前活动路径。
- const oldClientIds = oldRows.map((row) => row.clientId);
- if (oldClientIds.length > 0) {
+ if (hiddenClientIds.length > 0) {
broadcastMessageDeleted({
sessionId,
- clientId: oldClientIds[0],
- clientIds: oldClientIds,
+ clientId: hiddenClientIds[0],
+ clientIds: hiddenClientIds,
});
}
const visibleRows = await getDbClient().drizzle