Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): bind results only to replies after their completion input
zqchris5d2e08741dc2
diff --git a/apps/desktop/src/main/__tests__/botTaskReplyResults.test.ts b/apps/desktop/src/main/__tests__/botTaskReplyResults.test.tsindex 9c7c25f586..9ee6e86fd9 100644--- a/apps/desktop/src/main/__tests__/botTaskReplyResults.test.ts+++ b/apps/desktop/src/main/__tests__/botTaskReplyResults.test.ts@@ -5,6 +5,7 @@ import { readTaskResultsForReply } from '../botTaskReplyResults';import type { DbClient } from '../localDb/client/DbClient';import { BOT_DELEGATION_CLIENT_ID as ids, type BotCollaborationMeta } from '../../shared/botCollaboration';let sqlite: Database.Database;+let createdAt: number;let db: Pick<DbClient, 'queryOne' | 'query'>;const card = (id = 'job', runSequence = 1): BotCollaborationMeta => ({ v: 1, role: 'delegation-result',delegationId: id, fromBotId: 'bot', fromBotName: 'Cindy', toBotId: null, toBotName: '',@@ -12,11 +13,15 @@ const card = (id = 'job', runSequence = 1): BotCollaborationMeta => ({ v: 1, rolresult: { title: 'Report', runSequence, status: 'completed', text: 'Frozen result', artifacts: [] } });function row(id: string, role: string, content: string, meta: object = {}, session = 'chat') {sqlite.prepare('INSERT INTO messages (session_id,client_id,role,content,agent_meta,created_at) VALUES (?,?,?,?,?,?)')- .run(session, id, role, JSON.stringify(content), JSON.stringify(meta), 1000);+ .run(session, id, role, JSON.stringify(content), JSON.stringify(meta), ++createdAt);+}+function receipt(id = 'job', run = 1) {+ row(ids.resultRun(id, run), 'assistant', 'Frozen result', { botCollaboration: card(id, run) });+ row(ids.completionRun(id, run), 'user', 'Completion input');}-function receipt(id = 'job', run = 1) { row(ids.resultRun(id, run), 'assistant', 'Frozen result', { botCollaboration: card(id, run) }); }const bind = (inputs = [ids.completionRun('job', 1)]) => readTaskResultsForReply('chat', 'final', inputs, db);beforeEach(() => {+ createdAt = 1000;sqlite = new Database(':memory:');sqlite.exec(`CREATE TABLE sessions(id TEXT,source TEXT); CREATE TABLE bot_session_links(session_id TEXT,bot_id TEXT,role TEXT);CREATE TABLE messages(session_id TEXT,client_id TEXT,role TEXT,content TEXT,agent_meta TEXT,created_at INTEGER,rewind_at INTEGER);@@ -32,7 +37,7 @@ it('binds multiple exact executions to one reply, independent of receipt order arow('final', 'assistant', 'Both reports are ready', { assistantPhase: 'final' });expect(await bind([ids.completionRun('a', 2), ids.completionRun('b', 1), ids.completionRun('a', 2)])).toEqual([card('a', 2), card('b')]);- expect(sqlite.prepare('SELECT count(*) n FROM messages').get()).toEqual({ n: 6 });+ expect(sqlite.prepare('SELECT count(*) n FROM messages').get()).toEqual({ n: 9 });});it('does not adopt receipts from queued/unrelated inputs, a different run or another conversation', async () => {receipt(); row('final', 'assistant', 'Unrelated answer');@@ -57,9 +62,12 @@ it.each(['task', 'scheduler'])('does not touch ordinary %s sessions', async sourit('preserves durable ownership after restart/repeated delivery and permits a separate continuation run', async () => {receipt(); row('old-final', 'assistant', 'First answer', { turnCompleted: true, botTaskResults: [card()] });row('final', 'assistant', 'Repeated wake'); expect(await bind()).toEqual([]);- receipt('job', 2); expect(await bind([ids.completionRun('job', 2)])).toEqual([card('job', 2)]);- sqlite.prepare('UPDATE messages SET agent_meta=? WHERE client_id=?').run(JSON.stringify({ turnCompleted: true, botTaskResults: [card('job', 2)] }), 'final');- expect(await bind([ids.completionRun('job', 2)])).toEqual([card('job', 2)]);+ receipt('job', 2);+ row('continuation-final', 'assistant', 'Second run ready');+ const bindContinuation = () => readTaskResultsForReply('chat', 'continuation-final', [ids.completionRun('job', 2)], db);+ expect(await bindContinuation()).toEqual([card('job', 2)]);+ sqlite.prepare('UPDATE messages SET agent_meta=? WHERE client_id=?').run(JSON.stringify({ turnCompleted: true, botTaskResults: [card('job', 2)] }), 'continuation-final');+ expect(await bindContinuation()).toEqual([card('job', 2)]);});it('requires matching teammate ownership and retains malformed/rewound rows as unbound', async () => {receipt(); row('final', 'assistant', 'Answer');@@ -85,3 +93,30 @@ it('ignores corrupt historic metadata without losing new results or valid duplicexpect(sqlite.prepare('SELECT agent_meta FROM messages WHERE client_id=?').get('corrupt')).toEqual({ agent_meta: '{truncated' });});++it('keeps a late completion standalone when done reuses text from before that input', async () => {+ receipt('early');+ row('final', 'assistant', 'Answer to the earlier result');+ receipt('late');+ expect(await bind([ids.completionRun('early', 1), ids.completionRun('late', 1)]))+ .toEqual([card('early')]);+ row('post-input-final', 'assistant', 'Both results are now ready');+ expect(await readTaskResultsForReply('chat', 'post-input-final', [ids.completionRun('late', 1)], db))+ .toEqual([card('late')]);+});++it.each([-1, 0])('does not mistake a delayed flush for post-input text (time offset %s)', async offset => {+ receipt();+ const inputTime = createdAt;+ row('final', 'assistant', 'Buffered pre-steer answer');+ sqlite.prepare('UPDATE messages SET created_at=? WHERE client_id=?').run(inputTime + offset, 'final');+ expect(await bind()).toEqual([]);+});++it('requires the exact visible input boundary and leaves missing or rewound input unbound', async () => {+ receipt(); row('final', 'assistant', 'Ready');+ sqlite.prepare('UPDATE messages SET rewind_at=1 WHERE client_id=?').run(ids.completionRun('job', 1));+ expect(await bind()).toEqual([]);+ sqlite.prepare('DELETE FROM messages WHERE client_id=?').run(ids.completionRun('job', 1));+ expect(await bind()).toEqual([]);+});diff --git a/apps/desktop/src/main/botTaskReplyResults.ts b/apps/desktop/src/main/botTaskReplyResults.tsindex 5b6d417cb1..ef9700c3fe 100644--- a/apps/desktop/src/main/botTaskReplyResults.ts+++ b/apps/desktop/src/main/botTaskReplyResults.ts@@ -7,14 +7,16 @@ export async function readTaskResultsForReply(sessionId: string, replyClientId: string, inputClientIds: readonly string[],db: Pick<DbClient, 'queryOne' | 'query'> = getDbClient(),): Promise<BotCollaborationMeta[]> {- const receiptIds = [...new Set(inputClientIds.flatMap(id => {- const receipt = taskResultClientIdForInput(id);- return receipt ? [receipt] : [];- }))];- if (!receiptIds.length) return [];+ const inputs = [...new Set(inputClientIds)].flatMap(inputClientId => {+ const receiptId = taskResultClientIdForInput(inputClientId);+ return receiptId ? [{ inputClientId, receiptId }] : [];+ });+ if (!inputs.length) return [];// Only canonical teammate conversations participate; ordinary tasks/group lanes do not.- const reply = await db.queryOne<{ botId: string; content: string; agentMeta: string | null }>(`- SELECT b.bot_id AS botId, m.content, m.agent_meta AS agentMeta+ const reply = await db.queryOne<{+ botId: string; content: string; agentMeta: string | null; createdAt: number; rowid: number;+ }>(`+ SELECT b.bot_id AS botId, m.content, m.agent_meta AS agentMeta, m.created_at AS createdAt, m.rowidFROM messages m JOIN sessions s ON s.id = m.session_idJOIN bot_session_links b ON b.session_id = s.idWHERE m.session_id = ? AND m.client_id = ? AND m.role = 'assistant'@@ -32,11 +34,18 @@ export async function readTaskResultsForReply(// A replayed seal may carry only part of the consumed inputs. Preserve its existing attachments.const results = meta.turnCompleted === true ? readBotTaskResults(meta.botTaskResults) : [];const attached = new Set(results.map(botTaskResultKey));- for (const receiptId of receiptIds) {+ for (const { inputClientId, receiptId } of inputs) {+ // The accepted input's durable row is a conservative lower boundary. Assistant timestamps+ // retain the first text event, even when a pre-steer block is flushed after the user row.+ // Require both orders strictly; missing/equal-time/rewound inputs keep their standalone receipt.const row = await db.queryOne<{ agentMeta: string }>(`- SELECT agent_meta AS agentMeta FROM messages- WHERE session_id = ? AND client_id = ? AND role = 'assistant' AND rewind_at IS NULL- `, [sessionId, receiptId]);+ SELECT receipt.agent_meta AS agentMeta FROM messages receipt+ JOIN messages input ON input.session_id = receipt.session_id AND input.client_id = ?+ AND input.role = 'user' AND input.rewind_at IS NULL+ AND input.created_at < ? AND input.rowid < ?+ WHERE receipt.session_id = ? AND receipt.client_id = ?+ AND receipt.role = 'assistant' AND receipt.rewind_at IS NULL+ `, [inputClientId, reply.createdAt, reply.rowid, sessionId, receiptId]);if (!row) continue;let card: BotCollaborationMeta | null;try { card = readBotCollaborationMeta(JSON.parse(row.agentMeta).botCollaboration); } catch { continue; }diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex c2465585da..0030d0cfd9 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -288,7 +288,7 @@ Session 任务遵守同一套机制与呈现契约:- **任务卡**:发起方消息流原位出现一张持久任务卡,实时反映排队 / 执行 / 等待 / 终态。卡片不得使用“加入对话”等通讯语言,也不得再叠加顶部运行条或另造一套协同面板。状态由任务行推送驱动,不靠消息文本。-- **执行结果入口**:完成结果属于伙伴收尾回复末尾的紧凑附件,正文先读,卡片与该条回复同列、同一容器归属。宿主以本轮实际消费的完成信号绑定冻结结果,成功收尾后随回复持久保存;同轮多结果分别附上,不按相邻消息、时间或正文猜配,不把所有卡移到时间线末尾。忙时尚未消费的队列不参与当前回复,重复信号不重复绑定,续跑按执行代次保留独立结果。+- **执行结果入口**:完成结果属于伙伴收尾回复末尾的紧凑附件,正文先读,卡片与该条回复同列、同一容器归属。宿主以本轮实际消费的完成信号绑定冻结结果,成功收尾后随回复持久保存;同轮多结果分别附上,不按相邻消息、时间或正文猜配,不把所有卡移到时间线末尾。忙时尚未消费的队列不参与当前回复;每个结果还必须有该完成输入持久化之后生成的新正文,旧正文延迟落库、同毫秒无法确认顺序或输入记录缺失时保留独立入口。重复信号不重复绑定,续跑按执行代次保留独立结果。原任务卡和消息顺序不变。结果先按既有机制独立持久化;没有最终正文、失败或中断、关联读取失败、旧记录没有关联、或仅加载到原回执时,保留独立结果入口,不伪造总结、不改用户历史库。关联回复加载后,其对应独立回执只在伙伴展示投影中收起。旧客户端忽略新增的可选 `botTaskResults`,继续显示独立回执。新回执保存当次子任务标题;旧回执只读回退到已有任务标题,再回退到目标首行。附件冻结的状态、正文、文件与错误不从当前任务覆盖。普通任务、执行调度与自动化静默不改变。实现见 `botTaskReplyResults.ts`、`botConversationPresentation.ts` 与 Mobile `companionConversationPresentation.ts`。- **补充消息留痕**:`message_session_task` 的完整指令继续投递并保存在后台任务,主聊天的发送留痕只显示简短状态。