Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 修复计划模式通知导致回复错位 (#4753)
Chris Zhang8543e00dcb74
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex 3a5fa813dd..a4c604e213 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -82,6 +82,7 @@ import {onToolResultFullEvent,prepareSyntheticToolEventForBroadcast,onAssistantTextEvent,+ onStandaloneTextEvent,getSessionTextSnapshot,onInteractionMessage,onInteractionResolved,@@ -3687,3 +3688,68 @@ describe('resolved interactions publish authoritative history rows', () => {expect(broadcastMessageRow).not.toHaveBeenCalled();});});++describe('Pi extension notification and assistant reply isolation', () => {+ it('keeps plan toggles before the input from backdating the next answer', async () => {+ const clock = vi.spyOn(Date, 'now');+ try {+ clock.mockReturnValue(1000);+ const enabled = onStandaloneTextEvent(SESSION, 'Plan mode enabled.');+ clock.mockReturnValue(2000);+ const disabled = onStandaloneTextEvent(SESSION, 'Plan mode disabled.');+ expect(getSessionTextSnapshot(SESSION)).toBeNull();+ expect(consumeLastAssistantPersistId(SESSION)).toBeUndefined();+ clock.mockReturnValue(3000); // User input precedes model output.+ noteTurnStarted(SESSION);+ clock.mockReturnValue(4000);+ const reply = onAssistantTextEvent(SESSION, { text: 'Complete ', isFinal: false }, null);+ onAssistantTextEvent(SESSION, { text: 'answer', isFinal: false }, null);+ onAssistantTextEvent(SESSION, { text: 'Complete answer', isFinal: true, isFullText: true }, null);+ flushAssistantBlock(SESSION);+ await flushWrites();+ expect(new Set([enabled, disabled, reply]).size).toBe(3);+ const rows = vi.mocked(createMessage).mock.calls.map((call) => call[1]);+ expect(rows.map(({ content, createdAt }) => ({ content, createdAt }))).toEqual([+ { content: 'Plan mode enabled.', createdAt: 1000 },+ { content: 'Plan mode disabled.', createdAt: 2000 },+ { content: 'Complete answer', createdAt: 4000 },+ ]);+ expect(consumeLastAssistantPersistId(SESSION)).toBe(reply);+ expect(consumeLastTopLevelAssistantPersistId(SESSION)).toBe(reply);+ for (const call of vi.mocked(createMessage).mock.calls) {+ expect(call[2]).toMatchObject({ shouldBroadcast: expect.any(Function) });+ expect(call[2]?.shouldBroadcast?.()).toBe(true);+ }+ } finally {+ clock.mockRestore();+ }+ });++ it('preserves a streaming reply and its terminal ownership across interleaved notices', async () => {+ const reply = onAssistantTextEvent(SESSION, { text: 'First ', isFinal: false }, null);+ const before = getSessionTextSnapshot(SESSION);+ const notice = onStandaloneTextEvent(SESSION, 'Extension warning');+ expect(getSessionTextSnapshot(SESSION)).toEqual(before);+ expect(onAssistantTextEvent(SESSION, { text: 'second', isFinal: false }, null)).toBe(reply);+ expect(onAssistantTextEvent(SESSION, {+ text: 'First second', isFinal: true, isFullText: true,+ }, { model: 'test-model' })).toBe(reply);+ flushAssistantBlock(SESSION);+ const after = onStandaloneTextEvent(SESSION, 'Extension finished');+ expect(getSessionTextSnapshot(SESSION)).toBeNull();+ expect(consumeLastAssistantPersistId(SESSION)).toBe(reply);+ expect(consumeLastTopLevelAssistantPersistId(SESSION)).toBe(reply);+ await flushWrites();+ const rows = vi.mocked(createMessage).mock.calls.map((call) => call[1]);+ expect(rows.map(({ clientId, content }) => ({ clientId, content }))).toEqual([+ { clientId: notice, content: 'Extension warning' },+ { clientId: reply, content: 'First second' },+ { clientId: after, content: 'Extension finished' },+ ]);+ resetTurnPersistState(SESSION);+ const next = onAssistantTextEvent(SESSION, { text: 'First second', isFinal: true }, null);+ expect(next).not.toBe(reply);+ await flushWrites();+ expect(vi.mocked(createMessage).mock.calls.at(-1)?.[1].content).toBe('First second');+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex be904c3b49..d165c209e4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -110,6 +110,7 @@ vi.mock('../../messagePersistBroadcaster.js', () => ({enqueueDurableWrite: effects.fn('enqueueDurableWrite'),flushAssistantBlock: effects.fn('flushAssistantBlock'),onAssistantTextEvent: effects.fn('onAssistantTextEvent'),+ onStandaloneTextEvent: effects.fn('onStandaloneTextEvent'),onAgentTaskUpdateEvent: effects.fn('onAgentTaskUpdateEvent'),onThinkingEvent: effects.fn('onThinkingEvent'),onToolResultEvent: effects.fn('onToolResultEvent'),@@ -390,6 +391,62 @@ function ordered(...names: string[]) {}describe('production Session event pipeline', () => {+ it('delivers Pi notices as durable rows without entering model streaming or turn bookkeeping', async () => {+ const h = harness();+ h.deps.redactEventForRenderer.mockImplementation((value) => value);+ try {+ h.emit(event('text', { text: 'Plan mode enabled.', isFinal: true }, {+ source: 'pi', standaloneText: true, turnScope: 'background',+ }));+ await microtasks();+ expect(effects.fn('onStandaloneTextEvent')).toHaveBeenCalledWith('task', 'Plan mode enabled.', null);+ expect(effects.fn('onAssistantTextEvent')).not.toHaveBeenCalled();+ expect(effects.fn('flushAssistantBlock')).not.toHaveBeenCalled();+ expect(effects.fn('noteTurnStarted')).not.toHaveBeenCalled();+ expect(effects.fn('markAssistantTurnCompleted')).not.toHaveBeenCalled();+ expect(h.deps.broadcastToAllWindows).not.toHaveBeenCalled();+ expect(h.deps.orcaTeamServiceForEvents?.captureWorkerText).not.toHaveBeenCalled();+ h.emit(event('text', { text: 'Actual reply', isFinal: true, isFullText: true }, { source: 'pi' }));+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledOnce();+ expect(h.deps.broadcastToAllWindows).toHaveBeenCalled();+ } finally {+ await h.dispose();+ }+ });++ it('drops a pre-clear Pi notice on delayed delivery while accepting a new notice', async () => {+ const h = harness();+ h.deps.redactEventForRenderer.mockImplementation((value) => value);+ try {+ effects.fn('backgroundTurnPredatesSessionClear').mockReturnValueOnce(true);+ h.emit(event('text', { text: 'Old plan notice', isFinal: true }, {+ source: 'pi', standaloneText: true, turnScope: 'background', backgroundTurnStartedAt: 1000,+ }));+ expect(effects.fn('backgroundTurnPredatesSessionClear')).toHaveBeenCalledWith('task', 1000);+ expect(effects.fn('onStandaloneTextEvent')).not.toHaveBeenCalled();+ expect(h.deps.broadcastToAllWindows).not.toHaveBeenCalled();+ effects.fn('backgroundTurnPredatesSessionClear').mockReturnValueOnce(false);+ h.emit(event('text', { text: 'New plan notice', isFinal: true }, {+ source: 'pi', standaloneText: true, turnScope: 'background', backgroundTurnStartedAt: 3000,+ }));+ expect(effects.fn('onStandaloneTextEvent')).toHaveBeenCalledExactlyOnceWith('task', 'New plan notice', null);+ expect(effects.fn('onAssistantTextEvent')).not.toHaveBeenCalled();+ } finally {+ await h.dispose();+ }+ });++ it('retains accepted private-message visibility for independent Pi notices', async () => {+ const h = harness();+ h.deps.redactEventForRenderer.mockImplementation((value) => value);+ h.deps.agentInputCoordinatorHolder.getActiveInputClientId.mockReturnValue('bot-dm:private-input');+ h.emit(event('text', { text: 'Extension result', isFinal: true }, {+ source: 'pi', standaloneText: true, turnScope: 'background',+ }));+ expect(effects.fn('onStandaloneTextEvent')).toHaveBeenCalledWith('task', 'Extension result', { botPrivateReply: true });+ await h.dispose();+ });+it.each(['completed', 'failed', 'cancelled', 'interrupted'])('runs the upstream-merge follow-up only for a successful product boundary: %s', async (status) => {const h = harness();diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.tsindex 19833d35f0..da7d5848b2 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts@@ -23,6 +23,7 @@ import {backgroundTurnPredatesSessionClear,noteAgentMeta,noteTurnStarted,+ onStandaloneTextEvent,} from '../messagePersistBroadcaster.js';import { isCcMgrUpgradeInFlight } from '../remote-ssh/index.js';import { AgentInputCoordinator } from './agent-input-coordinator.js';@@ -157,6 +158,22 @@ export function prepareSessionEvent(},};}+ if (event.type === 'text' && event.standaloneText === true) {+ // Deliver through the existing persisted-row channel only. Sending a text+ // event as well would let older renderers adopt the notice as their active+ // assistant stream and overwrite/misdate the next model reply.+ const redacted = deps.redactEventForRenderer(event);+ const text = (redacted.data as { text?: unknown } | null)?.text;+ const inputId = deps.agentInputCoordinatorHolder?.getActiveInputClientId(session.id, event.sessionTurnGeneration);+ // Private-message visibility is still owned by the accepted input, even+ // though the notice is independent of the model's reply/usage state.+ const privateReply = inputId ? inputId.startsWith('bot-dm:') : event.agentMeta?.botPrivateReply;+ if (typeof text === 'string') {+ onStandaloneTextEvent(session.id, text,+ typeof privateReply === 'boolean' ? { botPrivateReply: privateReply } : null);+ }+ return;+ }// 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的// terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token// 盖到事件上,首个匹配 token 的事件即视为 provider accepted。diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex a86db18fd5..c1c5f29a83 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -2033,6 +2033,29 @@ export function resetTurnPersistState(sessionId: string): void {lastTopLevelAssistantPersistIdBySession.delete(sessionId);}+/**+ * Extension notices are already complete. Keep them out of assistantBlocks,+ * reply dedup/fork anchors and per-turn usage targets, including when a notice+ * arrives between model deltas. The normal durable-row broadcast works for+ * both local windows and older device-link clients without a new stream flag.+ */+export function onStandaloneTextEvent(+ sessionId: string,+ text: string,+ agentMeta: Pick<AgentMeta, 'botPrivateReply'> | null = null,+): string | undefined {+ if (!text.trim()) return undefined;+ const persistId = createId();+ enqueueVisibleDbMessage(`standalone_text:${sessionId}:${persistId}`, sessionId, {+ clientId: persistId,+ role: 'assistant',+ content: text,+ agentMeta,+ createdAt: Date.now(),+ });+ return persistId;+}+/*** 处理 assistant 'text' 事件,返回该消息的 persistId 供 onEvent 盖进广播 payload。*diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 0933beb027..56897fc279 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -625,6 +625,55 @@ describe('makerChatStore text delta batching', () => {assertReply();});+ it('keeps durable Pi notices separate before, during and after a streamed answer and history reload', async () => {+ const notice = (clientId: string, content: string, createdAt: string) => serverMessage({+ id: `${clientId}-row`, clientId, sessionId: SESSION_ID, role: 'assistant', content,+ agentMeta: null, createdAt,+ });+ const enabled = notice('plan-enabled', 'Plan mode enabled.', '2026-09-20T00:00:01Z');+ const user = serverMessage({+ id: 'user-row', clientId: 'user-input', sessionId: SESSION_ID, role: 'user',+ content: JSON.stringify({ text: 'Discuss the report' }), createdAt: '2026-09-20T00:00:02Z',+ });+ const during = notice('extension-warning', 'Extension warning', '2026-09-20T00:00:04Z');+ const after = notice('extension-finished', 'Extension finished', '2026-09-20T00:00:05Z');+ const reply = serverMessage({+ id: 'reply-row', clientId: 'reply', sessionId: SESSION_ID, role: 'assistant',+ content: 'Complete answer', createdAt: '2026-09-20T00:00:03Z',+ agentMeta: { model: 'test-model', stopReason: 'stop', turnCompleted: true },+ });+ for (const message of [enabled, user]) onDbMessageCreated?.({ sessionId: SESSION_ID, message });+ const sendText = (text: string, isFinal: boolean) => onEvent?.({+ sessionId: SESSION_ID, persistId: 'reply', event: {+ type: 'text', source: 'pi', data: { text, isFinal, ...(isFinal ? { isFullText: true } : {}) },+ },+ });+ sendText('Complete ', false);+ vi.advanceTimersByTime(32);+ onDbMessageCreated?.({ sessionId: SESSION_ID, message: during });+ sendText('answer', false);+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages.find((row) => row.clientId === 'reply')?.content)+ .toBe('Complete answer');+ sendText('Complete answer', true);+ onDbMessageCreated?.({ sessionId: SESSION_ID, message: reply });+ onDbMessageCreated?.({ sessionId: SESSION_ID, message: after });+ onEvent?.({ sessionId: SESSION_ID, event: {+ type: 'done', source: 'pi', data: { status: 'completed', result: 'Complete answer' },+ } });+ const assertRows = () => {+ const rows = makerChatStore.getSnapshot(SESSION_ID).messages;+ expect(rows.map((row) => row.clientId)).toEqual(['plan-enabled', 'user-input', 'reply', 'extension-warning', 'extension-finished']);+ expect(rows.find((row) => row.clientId === 'reply')).toMatchObject({ content: 'Complete answer', isStreaming: false });+ };+ assertRows();+ makerChatStore.purgeSession(SESSION_ID);+ vi.mocked(messageService.list).mockResolvedValueOnce([enabled, user, reply, during, after]);+ makerChatStore.ensureInitialMessages(SESSION_ID);+ await flushPromises();+ assertRows();+ });+it('coalesces consecutive text deltas into one store notification', () => {let notifyCount = 0;const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {diff --git a/docs/dev-rules/pi-extension-ui.md b/docs/dev-rules/pi-extension-ui.mdindex 49ae6a3bc8..97f168b638 100644--- a/docs/dev-rules/pi-extension-ui.md+++ b/docs/dev-rules/pi-extension-ui.md@@ -13,7 +13,7 @@ Pi 运行时分发共用它。更新 Pi 后按整张表核对,不为单一扩| 能力 | Cindy 行为 || --- | --- || `select` / `confirm` / `input` / `editor` | 保留现有选择卡适配和响应;带有限 `timeout` 的请求取消并回传,避免扩展等待,不输出兼容警告 |-| `notify` | 保留扩展实际通知、命令结果和错误输出 |+| `notify` | 保留扩展实际通知、命令结果和错误输出;作为独立完整消息落库并广播,不进入模型正文的流式缓冲,也不占用回复终态与费用归属 || `setStatus` / `setWidget` / `setTitle` | RPC 单向展示请求,Cindy 静默忽略,不回传、不写聊天正文 || `setEditorText` / `pasteToEditor` | 上游发出 `set_editor_text`,Cindy 静默忽略,不改写输入框 || `setWorkingMessage` / `setWorkingVisible` / `setWorkingIndicator` / `setHiddenThinkingLabel` | Pi RPC 已不执行;保留原生行为 |@@ -29,6 +29,10 @@ Cindy 不修改第三方扩展源码、不将 `ctx.hasUI` 改成 false、不替不因兼容分析停用整个扩展。未知 UI 请求同样不进入聊天正文;私有权限、包管理、子代理控制请求仍先经现有处理链,不能被 UI 过滤吞掉。工具执行、命令、事件及消息能力继续交给 Pi。+扩展通知使用 `standaloneText` 标记,经已有持久消息通道投递;不能仅将普通流式+`text` 改成 `isFinal`,否则通知仍可能接入或冲刷正在生成的回复。回归需覆盖通知在+用户输入前、回复生成中与结束后到达,并检查消息时间、正文、费用归属及历史重载。+设置页仍展示按源码发现的 API 限制。显式数字 `timeout` 的对话框列入交互限制;静态扫描不能保证发现动态生成的参数或调用,不将“没有发现”视为完整兼容证明。diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.tsindex b967fbbe2b..50b1dd581e 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts@@ -1456,6 +1456,51 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa},);+ it.each(['anthropic-messages', 'openai-completions'] as const)(+ 'keeps native plan notifications separate from replies using %s',+ { timeout: 60_000 },+ async (api) => {+ const deps = buildDeps();+ deps.resolvePiGatewayModelApi = () => api;+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-plan-reply-'));+ let handle: AgentSessionHandle | undefined;+ try {+ handle = await new PiAgent(deps).startSession({+ sessionId: `plan-reply-${api}`, workingDir, model: 'pi-test-model',+ });+ for (const enabled of [true, false, true]) {+ await handle.setPlanMode?.(enabled);+ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const event of handle!.events()) {+ events.push(event);+ if (event.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'Reply with a short greeting.' });+ await done;+ const notices = events.filter((event) => event.standaloneText);+ expect(notices).toHaveLength(1);+ expect(notices[0]).toMatchObject({+ type: 'text', source: 'pi', turnScope: 'background',+ data: { isFinal: true, text: expect.stringContaining(enabled ? 'enabled' : 'disabled') },+ });+ const reply = events.filter((event) => event.type === 'text' && !event.standaloneText);+ expect(reply.at(-1)?.data).toMatchObject({+ text: 'pong from fake gateway', isFinal: true, isFullText: true,+ });+ expect(events.find((event) => event.type === 'done')?.data).toMatchObject({+ status: 'completed', result: 'pong from fake gateway',+ });+ expect(events.filter((event) => event.type === 'error')).toEqual([]);+ }+ } finally {+ await handle?.close();+ rmSync(workingDir, { recursive: true, force: true });+ }+ },+ );+it('re-syncs plan mode from pi persisted state on resume (no mirror desync)',{ timeout: 60_000 },diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 41009ea34a..d9c03a30d7 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -1423,8 +1423,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {}});- it('presents Pi extension notifications in the Cindy transcript', async () => {+ it('stamps Pi notifications before delayed delivery so clear can reject old notices', async () => {const handle = await start();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1000);const events: Array<Record<string, unknown>> = [];void (async () => {for await (const event of handle.events()) {@@ -1439,17 +1440,22 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {message: '## context-mode stats (Pi)\n\n- Events captured: 0',notifyType: 'info',});+ clock.mockReturnValue(2000); // Simulate a clear/delivery boundary after emission.await flush();expect(events).toContainEqual({type: 'text',data: {text: '## context-mode stats (Pi)\n\n- Events captured: 0',- isFinal: false,+ isFinal: true,},source: 'pi',+ standaloneText: true,+ turnScope: 'background',+ backgroundTurnStartedAt: 1000,});expect(captured.sent.find((message) => message.id === 'context-mode-stats')).toBeUndefined();} finally {+ clock.mockRestore();await handle.close();}});@@ -1624,7 +1630,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(resolver).not.toHaveBeenCalled();expect(captured.sent).toHaveLength(sentBefore);expect(events.filter((event) => event.type === 'text')).toEqual([- { type: 'text', data: { text: 'Extension command result', isFinal: false }, source: 'pi' },+ { type: 'text', data: { text: 'Extension command result', isFinal: true }, source: 'pi', standaloneText: true, turnScope: 'background', backgroundTurnStartedAt: expect.any(Number) },]);} finally {await handle.close();diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 555dcae800..45303d4edc 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -5334,8 +5334,13 @@ export class PiAgent extends BaseAgent {}const notification: AgentEvent = {type: 'text',- data: { text, isFinal: false },+ data: { text, isFinal: true },source: 'pi',+ standaloneText: true,+ turnScope: 'background',+ // Freeze the notice's origin before the async queue: a later+ // /clear must discard it even when delivery happens afterward.+ backgroundTurnStartedAt: Date.now(),};queue.push(notification);return notification;diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex 01c756829b..ea3b8e38b1 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -192,6 +192,12 @@ export interface AgentEvent {* Session delivers it on `onRuntimeRecovery`, never on product `onEvent`.*/runtimeRecovery?: true;+ /**+ * A complete extension notice, independent of model text assembly and turn+ * settlement. Hosts deliver it as its own durable message, never as a delta+ * or a full-text replacement for the currently streaming assistant reply.+ */+ standaloneText?: true;/*** Provider-owned claim attached synchronously to a `done` boundary when that* boundary has an automatic continuation. Consumers pass it back to the