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。

feat(desktop): 每轮开始对账未收口的旧计划(顺手收拾,不烧独立轮次)

Kafeifei2306f292328c
diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
index fec025a0b6..7f1a6dd4fd 100644
--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
@@ -233,7 +233,8 @@ describe('注入接线(源码级守卫)', () => {
expect(source).toContain(
'deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true',
);
- expect(source).toContain('prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, mobileClientNote)');
+ // 注入链:normalized → withHandoff → withPlanReconcile → mobile note(最外层)。
+ expect(source).toContain('prependNoteToWireUserMessage(withPlanReconcile as HandoffWireMessage, mobileClientNote)');
expect(source).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');
// 落库内容必须仍取 persistUserMessage.content —— 若改成 outgoing,提示语会写进
// 用户消息、污染界面显示的原话。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index de22a33ee0..b6b6ed5075 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -1419,6 +1419,51 @@ describe('session-agent-switch handoff injection', () => {
expect(consumePendingHandoff).not.toHaveBeenCalled();
});
+ it('计划对账段命中时前置进 wire payload,落库内容保持用户原文', async () => {
+ const { deps, session } = createDeps({
+ peekPlanReconcileNote: vi.fn(async () => 'RECONCILE-NOTE'),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '新消息' }, undefined, {
+ persistUserMessage: { clientId: 'client-1', content: '新消息' },
+ });
+
+ expect(session.send).toHaveBeenCalledWith(
+ { type: 'user', content: 'RECONCILE-NOTE\n\n新消息' },
+ expect.anything(),
+ );
+ const persisted = vi.mocked(deps.createDbMessage).mock.calls[0]?.[1];
+ expect(persisted?.content).toBe('新消息');
+ });
+
+ it('计划对账在交接段外层(对账在前、交接在后)', async () => {
+ const { deps, session } = createDeps({
+ peekPendingHandoff: vi.fn(async () => 'HANDOFF-TEXT'),
+ consumePendingHandoff: vi.fn(),
+ peekPlanReconcileNote: vi.fn(async () => 'RECONCILE-NOTE'),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '新消息' }, undefined, {});
+ expect(session.send).toHaveBeenCalledWith(
+ { type: 'user', content: 'RECONCILE-NOTE\n\nHANDOFF-TEXT\n\n新消息' },
+ expect.anything(),
+ );
+ });
+
+ it('对账读取抛错时静默跳过,不挡发送', async () => {
+ const { deps, session } = createDeps({
+ peekPlanReconcileNote: vi.fn(async () => {
+ throw new Error('db unavailable');
+ }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '新消息' }, undefined, {});
+ expect(session.send).toHaveBeenCalledWith({ type: 'user', content: '新消息' }, expect.anything());
+ });
+
it('lazy-create 前调用 reconcileCreateOptsWithDb 以 DB 行校正 createOpts', async () => {
const reconcile = vi.fn(async (_sessionId: string, co: MakerSessionCreateOpts) => {
co.agentKind = 'codex';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/planReconcile.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/planReconcile.test.ts
new file mode 100644
index 0000000000..4f8c7f771c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/planReconcile.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildPlanReconcileNote,
+ summarizeOpenPlan,
+ type PlanReconcileCandidateRow,
+} from '../planReconcile';
+
+let seq = 0;
+function row(
+ role: string,
+ content: unknown,
+ clientId = `row-${(seq += 1)}`,
+): PlanReconcileCandidateRow {
+ return { clientId, role, content, createdAt: 1_700_000_000_000 + seq * 1000 };
+}
+
+function planRow(
+ plan: Array<{ step: string; status: string }>,
+ extra: Record<string, unknown> = {},
+ toolUseId = `plan:turn-${(seq += 1)}`,
+): PlanReconcileCandidateRow {
+ return row('tool_use', {
+ toolUseId,
+ toolName: 'update_plan',
+ input: { plan },
+ ...extra,
+ });
+}
+
+describe('summarizeOpenPlan', () => {
+ it('returns open steps for an unsealed plan left behind', () => {
+ const summary = summarizeOpenPlan([
+ row('user', { text: '做点什么' }),
+ planRow([
+ { step: 'Done work', status: 'completed' },
+ { step: 'Open work', status: 'in_progress' },
+ { step: 'Future work', status: 'pending' },
+ ]),
+ ]);
+
+ expect(summary).toEqual({
+ openSteps: ['Open work', 'Future work'],
+ totalSteps: 3,
+ });
+ });
+
+ it('returns null when there is no plan at all', () => {
+ expect(summarizeOpenPlan([row('user', { text: 'hi' })])).toBeNull();
+ });
+
+ it('returns null when the plan is fully completed', () => {
+ expect(
+ summarizeOpenPlan([
+ planRow([
+ { step: 'A', status: 'completed' },
+ { step: 'B', status: 'completed' },
+ ]),
+ ]),
+ ).toBeNull();
+ });
+
+ it('returns null when the plan was sealed by a successful turn', () => {
+ // 成功收尾盖了章的清单不对账:它的生命周期已经结束,哪怕留有未勾步骤
+ // 也是"如实记录",下一轮不需要 agent 交代。
+ expect(
+ summarizeOpenPlan([
+ planRow(
+ [
+ { step: 'Done', status: 'completed' },
+ { step: 'Left open', status: 'in_progress' },
+ ],
+ { terminalPlanSnapshot: true },
+ ),
+ ]),
+ ).toBeNull();
+ });
+
+ it('ignores subagent plans (ownership boundary)', () => {
+ expect(
+ summarizeOpenPlan([
+ row('tool_use', {
+ toolUseId: 'todo-sub',
+ toolName: 'TodoWrite',
+ parentToolUseId: 'agent-task-1',
+ input: { todos: [{ content: 'Subagent internal', status: 'in_progress' }] },
+ }),
+ ]),
+ ).toBeNull();
+ });
+
+ it('reconciles only the latest plan session after a user turn boundary', () => {
+ const summary = summarizeOpenPlan([
+ planRow([{ step: 'Old abandoned', status: 'in_progress' }]),
+ row('user', { text: '换个话题' }),
+ planRow([
+ { step: 'Current work', status: 'in_progress' },
+ { step: 'Current next', status: 'pending' },
+ ]),
+ ]);
+
+ // 只对账当前(最新 session)的清单,不把上一轮被 supersede 的旧步骤翻出来。
+ expect(summary?.openSteps).toEqual(['Current work', 'Current next']);
+ });
+});
+
+describe('buildPlanReconcileNote', () => {
+ it('lists open steps and grants all three outcomes including deletion', () => {
+ const note = buildPlanReconcileNote({
+ openSteps: ['Fix parser', 'Run tests'],
+ totalSteps: 4,
+ });
+
+ expect(note).toContain('- Fix parser');
+ expect(note).toContain('- Run tests');
+ // 三个出口都要在场:继续更新 / 修订 / 清掉。删除授权是关键——不给的话
+ // 模型会把不相干的旧清单硬拖进新话题。
+ expect(note).toContain('更新计划状态');
+ expect(note).toContain('修订条目');
+ expect(note).toContain('清掉');
+ // 顺手性质,不许抢占用户问题。
+ expect(note).toContain('不要让它先于用户的问题');
+ expect(note).toContain('以下是用户的新消息');
+ });
+
+ it('caps the listed steps and notes the remainder', () => {
+ const note = buildPlanReconcileNote({
+ openSteps: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
+ totalSteps: 8,
+ });
+
+ expect(note).toContain('- f');
+ expect(note).not.toContain('- g');
+ expect(note).toContain('另有 2 项未列出');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 2ec521ffce..242ffbca17 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -220,6 +220,13 @@ export interface MakerSendTransactionDeps {
*/
peekPendingHandoff?(sessionId: string): Promise<string | null>;
consumePendingHandoff?(sessionId: string): void;
+ /**
+ * 计划对账:会话里若有未收口的旧计划(未盖终态章且有未完成步骤),返回一段
+ * "顺手收拾"指示文本,与交接同通道前置进 wire payload(不进落库显示)。每次
+ * 发送现算,无 pending 状态、无 consume——旧清单被 agent 更新/清掉后,下一轮
+ * 自然算不出注入。undefined = 不启用(测试最小 harness)。
+ */
+ peekPlanReconcileNote?(sessionId: string): Promise<string | null>;
/**
* 本次调用是否来自手机控制端(缺省 = 否)。**纯体验分流,不是安全判据。**
*
@@ -737,6 +744,14 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
const withHandoff = pendingHandoff
? prependHandoffToUserMessage(normalized as HandoffWireMessage, pendingHandoff)
: normalized;
+ // 计划对账:旧的未收口计划让 agent 顺手交代(更新/修订/清掉)。位置在交接段
+ // 之前——两段各自带"以下是用户的新消息"式结束标记,对账在外层不破坏交接正文。
+ // 失败静默跳过:对账是锦上添花,不能挡发送。
+ const planReconcileNote =
+ (await deps.peekPlanReconcileNote?.(sessionId).catch(() => null)) ?? null;
+ const withPlanReconcile = planReconcileNote
+ ? prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, planReconcileNote)
+ : withHandoff;
const so = (outgoingSendOpts ?? {}) as MakerSendOptions;
// 手机客户端说明:同样只进 wire payload,落库/显示内容(persistUserMessage.content)
// 不含它。位置在交接段**之前** —— 交接正文自带「以下是用户的新消息」结束标记,
@@ -750,8 +765,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
? buildMobileClientPromptNote()
: null;
const outgoing = mobileClientNote
- ? prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, mobileClientNote)
- : withHandoff;
+ ? prependNoteToWireUserMessage(withPlanReconcile as HandoffWireMessage, mobileClientNote)
+ : withPlanReconcile;
const meta = await deps.getSessionMeta(sessionId).catch(() => null);
let persistUserMessage = readPersistUserMessageOption(so);
const topLevelClearBoundary = normalizeExpectedClearBoundary(so.expectedClearBoundaryMs);
diff --git a/apps/desktop/src/main/maker-ipc/planReconcile.ts b/apps/desktop/src/main/maker-ipc/planReconcile.ts
new file mode 100644
index 0000000000..e4dd2d72b7
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/planReconcile.ts
@@ -0,0 +1,101 @@
+/**
+ * 计划对账注入(plan reconcile)。
+ *
+ * 用户抱怨的另一半:泡泡退场(终态章)解决了"看得见的残留",但那份没做完的
+ * 清单本身还躺在会话里——下一轮 agent 被叫醒时没人要求它交代旧清单的下落,
+ * 清单内容就烂在那里(Codex 的 update_plan 是纯自述,引擎层没有回收机制)。
+ *
+ * 机制:每轮用户消息发送时(makerSendTransaction 的 wire 注入点,与
+ * agentHandoff / mobileClientNote 同一条搭车通道),若会话里最新的顶层计划
+ * 仍有未完成步骤,就在用户消息前注入一段"顺手收拾"指示:接着干就更新进度,
+ * 方向变了就改条目,不相干了就清掉。
+ *
+ * 三条纪律:
+ * - 只搭车,不烧独立轮次——"没在干了"的那一刻没人可问,叫醒它就又在干了,
+ * 所以对账只能发生在"本来就要叫醒它"的时机(用户的设计决策);
+ * - 措辞是顺手性质,不是任务——否则用户问"X 是什么",agent 先一本正经整理
+ * 清单,答案排到后面;
+ * - 归属判定复用 maker-shared 的所有权边界(跨轮不串号、子代理不算数),
+ * 这也是先修归属再开对账的原因:对着一份不存在或别人的清单唠叨,污染的
+ * 是用户下一轮的真正问题。
+ */
+
+import {
+ findLatestMessageTodoInsertion,
+ type MessageRenderSourceMessageLike,
+} from '@cindy/maker-shared/message-render';
+
+export interface PlanReconcileCandidateRow {
+ clientId: string;
+ role: string;
+ content: unknown;
+ createdAt: number;
+}
+
+/** 从 DB 行还原 maker-shared 扫描所需的最小形状(与 renderer 的 hydrate 同口径)。 */
+function toRenderSourceMessage(row: PlanReconcileCandidateRow): MessageRenderSourceMessageLike {
+ const content =
+ row.content && typeof row.content === 'object' && !Array.isArray(row.content)
+ ? (row.content as Record<string, unknown>)
+ : null;
+ const toolName = typeof content?.toolName === 'string' ? content.toolName : undefined;
+ const toolInput = content?.input;
+ const toolUseId = typeof content?.toolUseId === 'string' ? content.toolUseId : undefined;
+ const parentToolUseId =
+ typeof content?.parentToolUseId === 'string' ? content.parentToolUseId : undefined;
+ return {
+ clientId: row.clientId,
+ role: row.role,
+ content: row.content,
+ createdAt: new Date(row.createdAt).toISOString(),
+ ...(toolName ? { toolName } : {}),
+ ...(toolInput !== undefined ? { toolInput } : {}),
+ ...(toolUseId ? { toolUseId } : {}),
+ ...(parentToolUseId ? { parentToolUseId } : {}),
+ ...(content?.terminalPlanSnapshot === true ? { terminalPlanSnapshot: true } : {}),
+ };
+}
+
+export interface OpenPlanSummary {
+ /** 未完成步骤(pending / in_progress)的内容,注入文本引用它。 */
+ openSteps: string[];
+ totalSteps: number;
+}
+
+/**
+ * 找出会话里仍未收口的顶层计划。
+ *
+ * 返回 null 的情况就是不注入的情况:没有计划、计划全部完成、计划已被终态章
+ * 收口(成功收尾的清单不需要对账——它的生命周期已经结束,下一轮是新的开始)。
+ * 未盖章 + 有未完成步骤 = 中断/失败/被打断后遗留的清单,才值得让 agent 交代。
+ */
+export function summarizeOpenPlan(
+ rows: readonly PlanReconcileCandidateRow[],
+): OpenPlanSummary | null {
+ const insertion = findLatestMessageTodoInsertion(rows.map(toRenderSourceMessage));
+ if (!insertion) return null;
+ if (insertion.sealed === true) return null;
+ const openSteps = insertion.todos
+ .filter((todo) => todo.status !== 'completed')
+ .map((todo) => todo.content);
+ if (openSteps.length === 0) return null;
+ return { openSteps, totalSteps: insertion.todos.length };
+}
+
+/**
+ * 对账指示文本。三个出口穷尽所有情况(继续 / 修订 / 清掉),且明确授权删除——
+ * 不授权的话模型倾向于"计划不能丢",会把不相干的旧清单硬拖进新话题。
+ * 结尾用与 agentHandoff 同款的"以下是用户的新消息"边界,让正文归位。
+ */
+export function buildPlanReconcileNote(summary: OpenPlanSummary): string {
+ const steps = summary.openSteps.slice(0, 6).map((step) => `- ${step}`).join('\n');
+ const more =
+ summary.openSteps.length > 6 ? `\n(另有 ${summary.openSteps.length - 6} 项未列出)` : '';
+ return [
+ '[计划对账]上一轮留有未完成的计划步骤:',
+ `${steps}${more}`,
+ '处理用户消息时顺手收拾这份计划,不要让它先于用户的问题:若继续这些工作,',
+ '推进时更新计划状态;若方向已变,修订条目;若已与当前任务无关,用空计划清掉它。',
+ '== 对账说明结束,以下是用户的新消息 ==',
+ ].join('\n');
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 82c65fa53d..b5a3c62ac3 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -641,6 +641,7 @@ import {
} from './agentHandoff.js';
import { hydrateQueuedAgentReferences } from './agentInputReferences.js';
import { agentHandoffPending } from './agentHandoffPendingSingleton.js';
+import { buildPlanReconcileNote, summarizeOpenPlan } from './planReconcile.js';
import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';
import { persistAndHydrateSessionProvider } from './sessionProviderBootstrap.js';
import { registerMakerSessionSendHandler } from './sessionSendHandler.js';
@@ -9827,6 +9828,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
reconcileCreateOptsWithDb: reconcileCreateOptsAgainstDb,
peekPendingHandoff: (sessionId) => agentHandoffPending.peek(sessionId),
consumePendingHandoff: (sessionId) => agentHandoffPending.consume(sessionId),
+ // 计划对账:未收口的旧计划让 agent 在下一轮顺手交代。读近段历史现算,
+ // 无 pending 状态(清单被更新/清掉后下一轮自然不再注入)。
+ peekPlanReconcileNote: async (sessionId) => {
+ const rows = await listMessagesForAgentHandoff(sessionId, 400);
+ const summary = summarizeOpenPlan(rows);
+ return summary ? buildPlanReconcileNote(summary) : null;
+ },
// 手机客户端说明的开关:被控端盖章的来源判据(本机 renderer / 桌面控制端 / 平台
// 未知一律 false)。必须在这里现取,不能提前求值缓存——同一个装配好的事务会服务
// 后续所有 send,来源是逐次调用的属性。
diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.ts
index 8b1917ff61..e7dd40c3a2 100644
--- a/packages/maker-shared/src/messageRender.ts
+++ b/packages/maker-shared/src/messageRender.ts
@@ -20,6 +20,12 @@ export interface MessageRenderSourceMessageLike {
toolInput?: unknown;
/** SDK tool-use id — used to link a Task/collab tool-call to its live `agent_task_update`. */
toolUseId?: string | null;
+ /**
+ * Owning Agent/Task tool-use id when this message was produced inside a
+ * subagent. Plan scanning treats it as an ownership boundary: subagent plan
+ * calls never compete for the top-level pinned panel.
+ */
+ parentToolUseId?: string | null;
/** Host-persisted SDK turn boundary on the final assistant or owning Codex plan row. */
turnCompleted?: boolean;
/**