Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 保持历史恢复期间的流式正文顺序 (#4216)
Dashb27f99d51bd8
diff --git a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.tsindex 14beb5883e..f399a04559 100644--- a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts+++ b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts@@ -13,6 +13,71 @@ const row = (id: string, streaming = false): RemoteMessage => ({const createHandoff = () => new HistoryViewHandoff<RemoteMessage>((row) => row.agentMeta?.isStreaming === true);describe('mobile history handoff', () => {+ it('keeps the live tail below completed text when recovery history has not caught up to that tail', async () => {+ const first = { ...row('A'), content: 'first paragraph' };+ let live = { ...row('B', true), content: 'second paragraph', createdAt: first.createdAt };+ let history = [row('user'), first];+ const view = new HistoryViewController<RemoteMessage>({+ page: async () => ({ version: 1, items: projectHistoryView(history, false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ const handoff = createHandoff();+ const render = () => {+ const state = handoff.reconcile(view.getSnapshot(), [first, live]);+ return buildMobileHistoryRenderItems({ view, snapshot: view.getSnapshot(),+ messages: state.messages, pendingHandoff: state.pending, streaming: true, sessionId: 's',+ }).filter(item => item.type === 'message').map(item => item.message);+ };+ await view.refresh();+ expect(render().map(item => item.source.clientId)).toEqual(['user', 'A', 'B']);+ // A recovery page knows A's host timestamp, but B only exists in the live store.+ // B still has the older provisional timestamp it received before the disconnect.+ history = [row('user'), { ...first, createdAt: '2026-09-08T00:00:02Z', rowid: 42 }];+ view.setActive(false);+ view.setActive(true);+ await view.refresh();+ const recovered = render();+ expect(recovered.map(item => item.source.clientId)).toEqual(['user', 'A', 'B']);+ expect(recovered[2]).toMatchObject({ body: 'second paragraph', isStreaming: true });+ expect(recovered[2].source.createdAt).toBe(first.createdAt);+ live = { ...live, content: 'second paragraph continues' };+ expect(render().map(item => item.body)).toEqual(['question', 'first paragraph', 'second paragraph continues']);+ live = { ...live, agentMeta: null };+ expect(render()[2].isStreaming).not.toBe(true);+ history = [...history, { ...live, createdAt: '2026-09-08T00:00:03Z', rowid: 43 }];+ await view.refresh();+ expect(render().map(item => item.source.clientId)).toEqual(['user', 'A', 'B']);+ expect(handoff.reconcile(view.getSnapshot(), [first, live]).pending.size).toBe(0);+ view.setActive(false);+ });++ it('keeps multiple displayed pending paragraphs in order while persistence overtakes history', async () => {+ const first = row('A');+ const second = { ...row('B', true), createdAt: first.createdAt };+ const third = { ...row('C', true), createdAt: first.createdAt };+ const view = new HistoryViewController<RemoteMessage>({+ page: async () => ({ version: 1, items: projectHistoryView([row('user'), first], false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ const handoff = createHandoff();+ const render = (raw: RemoteMessage[]) => {+ const state = handoff.reconcile(view.getSnapshot(), raw);+ return buildMobileHistoryRenderItems({ view, snapshot: view.getSnapshot(),+ messages: state.messages, pendingHandoff: state.pending, streaming: true, sessionId: 's',+ }).filter(item => item.type === 'message').map(item => item.message.source.clientId);+ };+ await view.refresh();+ expect(render([first, second])).toEqual(['user', 'A', 'B']);+ const finalized = { ...second, agentMeta: null };+ expect(render([first, finalized, third])).toEqual(['user', 'A', 'B', 'C']);+ // The raw store has received B's durable timestamp and re-sorted its rows.+ // History has neither B nor C yet; both still belong to the displayed live tail.+ const persisted = { ...finalized, createdAt: '2026-09-08T00:00:02Z', rowid: 42 };+ expect(render([first, third, persisted])).toEqual(['user', 'A', 'B', 'C']);+ view.setActive(false);+ });it.each([true, false])('keeps text order when history timestamps arrive before live persistence (handoff=%s)', async (useHandoff) => {const message = (id: string, second: number, streaming = false): RemoteMessage => ({...row(id, streaming), content: id,diff --git a/apps/mobile/src/__tests__/subagentGrouping.test.ts b/apps/mobile/src/__tests__/subagentGrouping.test.tsindex f607f86bff..31022dea66 100644--- a/apps/mobile/src/__tests__/subagentGrouping.test.ts+++ b/apps/mobile/src/__tests__/subagentGrouping.test.ts@@ -70,6 +70,26 @@ function collectSourceIds(items: readonly MobileMessageRenderItem[]): string[] {}describe('subagent grouping (buildMobileMessageRenderItems)', () => {+ it.each([1, 2, 7])('preserves history paragraph order through %s nesting levels and fallback', (depth) => {+ const parents = Array.from({ length: depth }, (_, index) => agentToolUse(`order-A${index}`, {+ parentUuid: index === 0 ? undefined : `order-A${index - 1}`,+ createdAt: `2026-01-01T00:00:0${index}.000Z`,+ }));+ const paragraphs = ['first', 'second', 'third'].map((id, index) => msg({+ id, role: 'assistant', content: id,+ agentMeta: { parentUuid: `order-A${depth === 7 && index === 1 ? 5 : depth - 1}`, isStreaming: index > 0 },+ createdAt: `2026-01-01T00:00:${30 - index}.000Z`,+ }));+ const messages = [...parents, ...paragraphs];+ const original = structuredClone(messages);+ const paragraphIds = (preserveSourceOrder: boolean) => collectSourceIds(buildMobileMessageRenderItems(+ messages, { preserveSourceOrder, isSessionStreaming: true },+ )).filter(id => paragraphs.some(message => message.id === id));+ expect(paragraphIds(true)).toEqual(['first', 'second', 'third']);+ expect(paragraphIds(false)).toEqual(['third', 'second', 'first']);+ expect(messages).toEqual(original);+ });+it('replaces a top-level Agent tool_use with a subagent_group nesting its children', () => {const items = buildMobileMessageRenderItems([msg({ id: 'u', role: 'user', content: { text: 'go' }, createdAt: '2026-01-01T00:00:01.000Z' }),diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex 722f7100bc..dea4911009 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -191,8 +191,13 @@ interface ToolUsePayload extends MessageNormalizeToolUse {const toolResultPreviewByContent = new WeakMap<object, { language: string; preview: string }>();const toolUsePayloadByMessage = new WeakMap<RemoteMessage, ToolUsePayload>();-export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): NormalizedRemoteMessage[] {- const sorted = sortMessagesByCreatedAt(messages);+export function normalizeRemoteMessages(+ messages: readonly RemoteMessage[],+ options: { preserveSourceOrder?: boolean } = {},+): NormalizedRemoteMessage[] {+ // History views already place live tails after their persisted prefix. A live+ // row's provisional timestamp must not undo that order during normalization.+ const sorted = options.preserveSourceOrder ? messages : sortMessagesByCreatedAt(messages);const toolResultPairing = buildMessageToolResultPairing(sorted, {contentToPreview: toolResultContentToPreview,});diff --git a/apps/mobile/src/session/messageRenderModel.ts b/apps/mobile/src/session/messageRenderModel.tsindex 0802f51e3b..5d3ba1d4dc 100644--- a/apps/mobile/src/session/messageRenderModel.ts+++ b/apps/mobile/src/session/messageRenderModel.ts@@ -76,10 +76,14 @@ export type MobileMessageRenderItem =export function buildMobileMessageRenderItems(messages: readonly RemoteMessage[],- options: MessageRenderOptions & { autoResumePending?: Record<string, unknown> | null; sessionId?: string } = {},+ options: MessageRenderOptions & {+ autoResumePending?: Record<string, unknown> | null;+ sessionId?: string;+ preserveSourceOrder?: boolean;+ } = {},taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>,): MobileMessageRenderItem[] {- const normalized = normalizeRemoteMessages(messages);+ const normalized = normalizeRemoteMessages(messages, options);scopeUnsettledToolsToActiveTail(normalized);markTurnFinalAssistants(normalized, options.isSessionStreaming === true);if (options.autoResumePending) {diff --git a/apps/mobile/src/session/mobileHistoryRender.ts b/apps/mobile/src/session/mobileHistoryRender.tsindex 374104a795..01b68f5bb9 100644--- a/apps/mobile/src/session/mobileHistoryRender.ts+++ b/apps/mobile/src/session/mobileHistoryRender.ts@@ -17,7 +17,9 @@ export function buildMobileHistoryRenderItems(options: {isLive: (row) => row.agentMeta?.isStreaming === true,pendingHandoff: options.pendingHandoff,streaming: options.streaming,- build: (rows, streaming) => buildMobileMessageRenderItems(rows, { isSessionStreaming: streaming, sessionId: options.sessionId }, options.taskUpdates),+ build: (rows, streaming) => buildMobileMessageRenderItems(rows, {+ isSessionStreaming: streaming, sessionId: options.sessionId, preserveSourceOrder: true,+ }, options.taskUpdates),structure: {placeholder: (summary) => ({ id: summary.firstMessageId,clientId: summary.anchorClientId ?? summary.key.slice('work-'.length), sessionId: options.sessionId,diff --git a/apps/mobile/src/session/subagentGrouping.ts b/apps/mobile/src/session/subagentGrouping.tsindex 8e5e7c26ea..e8caa01846 100644--- a/apps/mobile/src/session/subagentGrouping.ts+++ b/apps/mobile/src/session/subagentGrouping.ts@@ -6,7 +6,7 @@* 消息的 `agentMeta.parentUuid`;Agent 的最终 tool_result(子 agent 终稿)经 tool_use_id 配对;codex* 无 parentUuid → 自然不触发;嵌套真实存在(深度通常 1,极少 2)。*- * 纯函数,可单测。归一化 / 分桶不靠模型判断(规则 9):全程按 parentUuid 精确归属 + createdAt 定序。+ * 纯函数,可单测。按 parentUuid 精确归属;历史视图保留来源顺序,旧路径按 createdAt 定序。*/import {buildMessageRenderItems,@@ -50,7 +50,7 @@ export function hasSubagentMessages(normalized: readonly NormalizedRemoteMessageexport function buildSubagentAwareRenderItems(normalized: readonly NormalizedRemoteMessage[],resultMeta: ReadonlyMap<string, SubagentResultMeta>,- options: MessageRenderOptions,+ options: MessageRenderOptions & { preserveSourceOrder?: boolean },): MobileMessageRenderItem[] {// 不变量:每条 normalized 消息在输出里恰好出现一次。// 生产是 80 条最近窗口(分页),Agent tool_use 的 createdAt 早于其 children → 窗口边界可能把某子 agent@@ -77,20 +77,23 @@ export function buildSubagentAwareRenderItems(topLevel.push(message);}}- // 各桶按 createdAt 稳定定序,保证确定性(归一化已大致有序,这里兜底)。- for (const bucket of byParent.values()) bucket.sort(compareByCreatedAt);+ // 历史视图已给出权威顺序,不能再按流式消息的临时时间排序。+ if (!options.preserveSourceOrder) {+ for (const bucket of byParent.values()) bucket.sort(compareByCreatedAt);+ }const consumed = new Set<string>();const out = buildLevel(topLevel, byParent, resultMeta, options, 0, consumed);// F2 兜底:深度上限(MAX_SUBAGENT_NEST_DEPTH)导致未被任何 subagent_group 消费的桶。真实嵌套 ≤2 够不到// cap=5,纯防御异常数据;但绝不 silent drop —— 把这些 children 追加 flat 渲染,保住"恰好出现一次"不变量。- const leftover: NormalizedRemoteMessage[] = [];- for (const [parentId, bucket] of byParent) {- if (!consumed.has(parentId)) leftover.push(...bucket);- }+ // 从原序列取回未消费行,避免拼接多个 parent 桶打乱交错段落。+ const leftover = normalized.filter((message) => {+ const parent = parentUuidOf(message);+ return parent !== null && byParent.has(parent) && !consumed.has(parent);+ });if (leftover.length > 0) {- leftover.sort(compareByCreatedAt);+ if (!options.preserveSourceOrder) leftover.sort(compareByCreatedAt);out.push(...buildMessageRenderItems(leftover, options));}return out;diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.tsindex d1975ec65b..81f2ad6647 100644--- a/packages/maker-shared/src/__tests__/historyView.test.ts+++ b/packages/maker-shared/src/__tests__/historyView.test.ts@@ -397,6 +397,48 @@ describe('shared history view lifecycle', () => {expect(rendered).toEqual(['c1']);});+ it('preserves pending observation order without moving known history or other live rows', async () => {+ const known = row(1, 'assistant', 'history');+ const first = row(4, 'assistant', 'first pending');+ const second = row(2, 'assistant', 'second pending');+ const other = row(3, 'user', 'other live');+ const view = new HistoryViewController<HistoryMessageSource>({+ page: async () => ({ version: 1, items: projectHistoryView([known], false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ await view.refresh();+ const liveMessages = [known, second, other, first];+ const pendingHandoff = new Set(['removed', known.clientId, first.clientId, second.clientId]);+ const output = renderHistoryView({ view, snapshot: view.getSnapshot(), liveMessages, pendingHandoff,+ streaming: true, isLive: () => true, build: rows => [...rows], structure: ungroupedStructure });+ expect(output).toEqual([known, first, other, second]);+ expect(liveMessages).toEqual([known, second, other, first]);+ expect([...pendingHandoff]).toEqual(['removed', known.clientId, first.clientId, second.clientId]);+ view.setActive(false);+ });++ it.each(['pending', 'blocked'])('anchors %s local users to the reordered handoff slots', async (status) => {+ const known = row(10, 'assistant', 'history');+ const first = row(4, 'assistant', 'first');+ const second = row(2, 'assistant', 'second');+ const users = [20, 21, 22, 23].map(id => ({ ...row(id, 'user', status), createdAt: row(0, 'user', '').createdAt }));+ const view = new HistoryViewController<HistoryMessageSource>({+ page: async () => ({ version: 1, items: projectHistoryView([known], false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ await view.refresh();+ const liveMessages = [known, users[0], second, users[1], users[2], first, users[3]];+ const output = renderHistoryView({ view, snapshot: view.getSnapshot(), liveMessages,+ pendingHandoff: new Set([first.clientId, second.clientId]), streaming: true,+ isLocalUser: message => message.role === 'user' && message.content === status,+ build: rows => [...rows], structure: ungroupedStructure });+ expect(output).toEqual([known, users[0], first, users[1], users[2], second, users[3]]);+ expect(liveMessages).toEqual([known, users[0], second, users[1], users[2], first, users[3]]);+ view.setActive(false);+ });+it('preserves current local user bubbles, source authority and store order despite clock skew', async () => {type Message = HistoryMessageSource & { isPendingPersist?: boolean; blockedByGhost?: boolean };const source = [row(1, 'user', 'kept'), row(10, 'assistant', 'answer'), row(11, 'user', 'persisted rewrite')];diff --git a/packages/maker-shared/src/historyViewRender.ts b/packages/maker-shared/src/historyViewRender.tsindex 2f55bfc526..d7768096b8 100644--- a/packages/maker-shared/src/historyViewRender.ts+++ b/packages/maker-shared/src/historyViewRender.ts@@ -10,7 +10,7 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(optionsbuild(messages: readonly T[], streaming: boolean): TItem[];streaming: boolean;isLive?(message: T): boolean;- /** Already displayed assistant identities awaiting history, not arbitrary cached rows. */+ /** Already displayed assistant identities in observation order, awaiting history. */pendingHandoff?: ReadonlySet<string>;isLocalUser?(message: T): boolean;structure: {@@ -69,17 +69,29 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options}endMs = Math.max(endMs, summary.endedAtMs);}- for (const row of options.liveMessages) {+ // Durable pushes can change a pending row's provisional timestamp before the+ // history page includes it. Preserve the handoff's observation order for those+ // rows, without moving other live rows or changing authoritative history order.+ const pendingTail = [...(options.pendingHandoff ?? [])].flatMap((id) => {+ const row = live.get(id);+ return row?.role === 'assistant' && !seen.has(id) ? [row] : [];+ });+ let pendingIndex = 0;+ const orderedLiveMessages = options.liveMessages.map((source) =>+ isPendingHandoff(source) && !seen.has(source.clientId)+ ? pendingTail[pendingIndex++] : source);+ for (const row of orderedLiveMessages) {if (isLive(row) && !seen.has(row.clientId) && (row.role === 'assistant' || row.role === 'user')&& (Date.parse(row.createdAt) >= endMs|| isPendingHandoff(row))) rows.push(row);}// Local pending/blocked user bubbles belong to the current UI store, not- // persisted history. Keep their store order without trusting device clocks.+ // persisted history. Anchor them to the same reordered slots used above,+ // without trusting device clocks or changing their order relative to each other.const renderedIds = new Set(rows.map((row) => row.clientId));let beforeClientId: string | undefined;- for (let index = options.liveMessages.length - 1; index >= 0; index--) {- const row = options.liveMessages[index];+ for (let index = orderedLiveMessages.length - 1; index >= 0; index--) {+ const row = orderedLiveMessages[index];if (renderedIds.has(row.clientId)) {beforeClientId = row.clientId;} else if (row.role === 'user' && options.isLocalUser?.(row)) {