Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 回复行时间戳不早于本轮起点,修回复排在 user 消息之前(#3805) (#4432)
biao435434f97088
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex e307be3500..60fc4c4a91 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -2147,6 +2147,232 @@ describe('event timestamp persistence', () => {);});+ it('stamps a pre-turn assistant block with the turn start when the turn writes into it', async () => {+ const attachAt = Date.parse('2026-06-20T11:00:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:00:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ // 运行时就绪 / 重连时到达的非 final text(扩展 notify、宿主机提示)不属于本轮,+ // 却会先建一个 block;它的 createdAt 早于本轮 user 行。+ nowSpy.mockReturnValue(attachAt);+ onAssistantTextEvent(SESSION, { text: 'runtime notice', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ let persistId: string | undefined;+ try {+ noteTurnStarted(SESSION);+ persistId = onAssistantTextEvent(SESSION, { text: 'reply', isFinal: false }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ clientId: persistId,+ role: 'assistant',+ createdAt: turnStartAt,+ }),+ broadcastGuard(),+ );+ });++ it('keeps the block own start when the turn created it', async () => {+ const turnStartAt = Date.parse('2026-06-20T11:01:30.000Z');+ const firstDeltaAt = Date.parse('2026-06-20T11:01:31.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ nowSpy.mockReturnValue(firstDeltaAt);+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: false }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'assistant', createdAt: firstDeltaAt }),+ broadcastGuard(),+ );+ });++ it('keeps a pre-turn block the turn never wrote to before the turn start', async () => {+ const noticeAt = Date.parse('2026-06-20T11:01:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:01:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(noticeAt);+ onAssistantTextEvent(SESSION, { text: 'runtime notice', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'assistant', createdAt: noticeAt }),+ broadcastGuard(),+ );+ });++ it('stamps a pre-turn block when the turn writes its authoritative full text', async () => {+ const attachAt = Date.parse('2026-06-20T11:02:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:02:04.000Z');+ const fullTextAt = Date.parse('2026-06-20T11:02:09.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(attachAt);+ onAssistantTextEvent(SESSION, { text: 'runtime notice', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ nowSpy.mockReturnValue(fullTextAt);+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: true, isFullText: true }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'assistant', createdAt: turnStartAt }),+ broadcastGuard(),+ );+ });++ it('does not stamp a pre-turn block from an unrelated non-full-text final', async () => {+ const attachAt = Date.parse('2026-06-20T11:06:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:06:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(attachAt);+ onAssistantTextEvent(SESSION, { text: 'runtime notice', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ // 内容不同、且不是更长前缀的 final 可能属于相邻 text block,不能归到当前提示上。+ onAssistantTextEvent(SESSION, { text: 'different reply', isFinal: true }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ role: 'assistant',+ content: 'runtime notice',+ createdAt: attachAt,+ }),+ broadcastGuard(),+ );+ });++ it('stamps a pre-turn block when an accepted longer-prefix final completes it', async () => {+ const attachAt = Date.parse('2026-06-20T11:07:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:07:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(attachAt);+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ onAssistantTextEvent(SESSION, { text: 'reply continued', isFinal: true }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ role: 'assistant',+ content: 'reply continued',+ createdAt: turnStartAt,+ }),+ broadcastGuard(),+ );+ });++ it('stamps a pre-turn block on an equal-length final without isFullText', async () => {+ const attachAt = Date.parse('2026-06-20T11:04:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:04:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(attachAt);+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ // Claude Code 重连 / delta 丢失后可能补发等长的 final 全文,不重写 block。+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: true }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'assistant', createdAt: turnStartAt }),+ broadcastGuard(),+ );+ });++ it('does not stamp a pre-turn block from a background turn text', async () => {+ const attachAt = Date.parse('2026-06-20T11:05:00.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:05:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(attachAt);+ onAssistantTextEvent(SESSION, { text: 'runtime notice', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteTurnStarted(SESSION);+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: false }, null, 'background');+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'assistant', createdAt: attachAt }),+ broadcastGuard(),+ );+ });++ it('does not lift a pre-/clear block above the clear boundary', async () => {+ const preClearAt = Date.parse('2026-06-20T11:03:00.000Z');+ const clearedAt = Date.parse('2026-06-20T11:03:02.000Z');+ const turnStartAt = Date.parse('2026-06-20T11:03:04.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(preClearAt);+ onAssistantTextEvent(SESSION, { text: 'runtime notice', isFinal: false }, null);+ nowSpy.mockReturnValue(turnStartAt);+ try {+ noteSessionClearBoundary(SESSION, clearedAt);+ noteTurnStarted(SESSION);+ onAssistantTextEvent(SESSION, { text: 'reply', isFinal: false }, null);+ flushAssistantBlock(SESSION, null);+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'assistant', createdAt: preClearAt }),+ broadcastGuard(),+ );+ });+it('captures non-thinking create timestamps before queued writes drain', async () => {const eventAt = Date.parse('2026-06-20T10:01:00.000Z');const delayedWriteTime = Date.parse('2026-06-20T10:01:07.000Z');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex 0154565ec7..8fe72fa07f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -512,7 +512,7 @@ describe('production Session event pipeline', () => {effects.fn('onAssistantTextEvent').mockClear();effects.fn('broadcast').mockClear();h.emit(receipt);- expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledWith('task', { ...data, text }, null);+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledWith('task', { ...data, text }, null, undefined);expect(effects.fn('broadcast')).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({sessionId: 'task', event: { ...receipt, data: { ...data, text } },}));@@ -542,7 +542,7 @@ describe('production Session event pipeline', () => {const h = harness();const data = { isFinal: true, text: 'partial: restart-cindy-to-refresh-packages' };h.emit(event('text', data, { source: 'pi' }));- expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledWith('task', data, null);+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledWith('task', data, null, undefined);await h.dispose();});diff --git a/apps/desktop/src/main/maker-ipc/sessionEventStream.ts b/apps/desktop/src/main/maker-ipc/sessionEventStream.tsindex e6af9c5117..824536c4ac 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventStream.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventStream.ts@@ -52,6 +52,7 @@ export function persistSessionStreamEvent(agentMessageId?: unknown;},eventAgentMeta,+ event.turnScope,);// Pi message_end carries the authoritative whole assistant message. Commit// its calibrated block now: agent_settled may arrive much later (or never),diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 330d89a811..cc5427df65 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -206,6 +206,28 @@ interface AssistantBlock {}const assistantBlocks = new Map<string, AssistantBlock>();++/**+ * 本轮 prompt 之前到达的非 final text(运行时就绪 / 重连期间的提示文本)会先建一个 block,+ * 它的 createdAt 早于本轮的 user 行。这样的 block 一旦被本轮写入(delta 或本轮全文快照),+ * 就把起点夹到本轮起点之后;否则落库的回复会排在触发它的 user 消息之前+ * (renderer 按 (createdAt, rowid) 排序)。本轮自己建的 block 起点就在本轮起点之后,不进这里。+ * 后台 turn 的文本不属于当前前台 turn,不抬(turnScope === 'background')。+ */+function stampBlockAfterTurnStart(+ sessionId: string,+ block: AssistantBlock,+ turnScope: 'turn' | 'background' | undefined,+): void {+ if (turnScope === 'background') return;+ const turnStartedAt = _turnStartedAtBySession.get(sessionId);+ if (turnStartedAt === undefined || turnStartedAt <= block.createdAt) return;+ // /clear 之前的 block 不抬升:抬上去会让 pre-clear 文本跟着漏进清空后的历史+ // (messages 按 createdAt > clearedAt 过滤、广播也用同一个边界)。+ const clearBoundary = clearBoundaryBySession.get(sessionId);+ if (clearBoundary !== undefined && block.createdAt <= clearBoundary) return;+ block.createdAt = turnStartedAt;+}// In-flight thinking is not in SQLite until final. Keep one recoverable snapshot// so expanding midway does not depend on deltas a collapsed controller never received.const historyThinkingBlocks = new Map<string, Map<string, Message>>();@@ -2081,6 +2103,7 @@ export function onAssistantTextEvent(sessionId: string,data: { text?: unknown; isFinal?: unknown; isFullText?: unknown; agentMessageId?: unknown; phase?: string; runtimeRecovery?: boolean },agentMeta: AgentMeta | null,+ turnScope?: 'turn' | 'background',): string | undefined {if (typeof data.phase === 'string' || data.runtimeRecovery === true) {agentMeta = { ...agentMeta, assistantPhase: data.runtimeRecovery === true ? 'commentary' : data.phase as string };@@ -2145,12 +2168,18 @@ export function onAssistantTextEvent(// Claude Code 的 local text block 没有该标记,但在 text_delta 丢失时仍可能携带// 已完整的、更长前缀文本。只接受以当前增量为前缀的更长文本,避免同一 assistant// 消息中相邻 text block 互相覆盖。- if (- isFullText ||- (rawText.length > block.text.length && rawText.startsWith(block.text))- ) {+ const acceptedLongerPrefix =+ rawText.length > block.text.length && rawText.startsWith(block.text);+ // 校时必须能确认这条 final 属于当前 block:权威全文、等长同文,或上面已接受的+ // 更长前缀。内容不同的非 isFullText final 可能属于相邻 text block(写入条件会+ // 拒绝覆盖),不能因此把 turn 前提示的 createdAt 抬到本轮起点。+ const finalBelongsToBlock = isFullText || rawText === block.text || acceptedLongerPrefix;+ if (isFullText || acceptedLongerPrefix) {block.text = rawText;}+ if (finalBelongsToBlock) {+ stampBlockAfterTurnStart(sessionId, block, turnScope);+ }if (agentMeta) block.agentMeta = agentMeta;return block.persistId;}@@ -2266,6 +2295,7 @@ export function onAssistantTextEvent(assistantBlocks.set(sessionId, block);} else {block.text += rawText;+ stampBlockAfterTurnStart(sessionId, block, turnScope);if (agentMeta) block.agentMeta = agentMeta;}return block.persistId;