Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 稳定本地空闲发送的乐观气泡位置 (#4328)
Dash67b8d4fd7166
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex cb305efcc1..5cf01072b3 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -116,7 +116,7 @@ import { shouldClearOperationErrorAfterSync, type SessionOperationError } from 'import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';import { findRemoteHistoryView, useRemoteHistoryView } from '@/session/remoteHistoryView';-import { HistoryViewHandoff, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';+import { HistoryViewHandoff, historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';import { buildMobileHistoryRenderItems } from '@/session/mobileHistoryRender';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';@@ -336,10 +336,16 @@ import {type QueueEditTextState,} from '@/session/inputProjection';import {- appendPendingSendItems,+ mergePendingSendItems,buildPendingSendItems,type MobilePendingSendActions,} from '@/session/pendingSendItems';+import {+ appendOptimisticUserMessage,+ projectOptimisticUserMessages,+ reconcileOptimisticUserMessages,+ type OptimisticUserMessage,+} from '@/session/optimisticUserMessages';import type { PendingSendBubbleActions } from '@/session/PendingSendBubble';import {acquireQueueEditLock,@@ -1505,14 +1511,33 @@ export default function SessionScreen() {// 还没有答案(弱网可达数秒,且失败会回滚摘除气泡),徽标必须是转圈而不是「排入// 队尾」——后者是已确认入队的语义。成功 / 回滚 / 转失败任一落定即移除。const [sendingQueueClientIds, setSendingQueueClientIds] = useState<ReadonlySet<string>>(new Set());- const markQueueItemSending = useCallback((clientId: string) => {+ const [optimisticUserState, setOptimisticUserState] = useState<{+ sessionId: string;+ items: readonly OptimisticUserMessage[];+ }>(() => ({ sessionId, items: [] }));+ if (optimisticUserState.sessionId !== sessionId) {+ setOptimisticUserState({ sessionId, items: [] });+ }+ const markQueueItemSending = useCallback((queued: QueuedRemoteMessage) => {+ const clientId = queued.clientId;+ const projection = remoteSessionStore.getInputProjection(sessionId);+ const source = remoteSessionStore.getMessages(sessionId);+ // Match Desktop's idle-send placement. Busy follow-ups retain the existing+ // pending tail until authoritative history supplies their transcript row.+ const busy = projection.pendingQueue.length > 0 || projection.steeringQueueClientIds.length > 0+ || projection.queueAbortPending || remoteSessionStore.isSessionRunning(sessionId)+ || remoteSessionStore.getPendingInteractions(sessionId).length > 0+ || currentTurnHasStreamingAssistant(source);+ if (!busy) setOptimisticUserState((current) => current.sessionId !== sessionId ? current : {+ sessionId, items: appendOptimisticUserMessage(current.items, source, queued, sessionId),+ });setSendingQueueClientIds((current) => {if (current.has(clientId)) return current;const next = new Set(current);next.add(clientId);return next;});- }, []);+ }, [sessionId]);const clearQueueItemSending = useCallback((clientId: string) => {setSendingQueueClientIds((current) => {if (!current.has(clientId)) return current;@@ -4198,17 +4223,46 @@ export default function SessionScreen() {projectedMessageWindowRef.current = { projection, sessionId };return projection;}, [messageStructureChangedIndexes, messageStructureToken, messages, sessionId]);- const projectedMessages = projectedMessageWindow.projected;- const projectedMessageStructureChangedIndexes = projectedMessageWindow.changedIndexes;- const oldestLoadedMessageCursor = useMemo(- () => historyView.snapshot.ready ? historyView.snapshot.nextCursor : oldestMessageCursor(latestMessagesRef.current),- [messageStructureToken, historyView.snapshot],- );const previousRenderItemsRef = useRef<{sessionId: string;items: readonly MobileMessageRenderItem[];prefix: MobileStreamingRenderPrefixCache | null;} | null>(null);+ const confirmedUserClientIds = useMemo(() => new Set(+ (historyView.snapshot.ready+ ? historyViewLeaves(historyView.snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : [])+ : messages).filter((message) => message.role === 'user').map((message) => message.clientId),+ ), [historyView.snapshot, messages]);+ const optimisticUsers = useMemo(() => {+ const activeIds = new Set([+ ...inputProjection.pendingQueue.filter((item) => sendingQueueClientIds.has(item.clientId)).map((item) => item.clientId),+ ...settlingItemsForRender.map((item) => item.clientId),+ ]);+ // Only the enqueue path can reserve a transcript position. A vanished+ // busy queue has no reliable local turn boundary: history and projection+ // can arrive in either order, across any number of committed renders.+ return reconcileOptimisticUserMessages(+ optimisticUserState.sessionId === sessionId ? optimisticUserState.items : [],+ messages, activeIds, confirmedUserClientIds,+ );+ }, [optimisticUserState, sessionId, messages, inputProjection.pendingQueue,+ sendingQueueClientIds, settlingItemsForRender, confirmedUserClientIds]);+ if (optimisticUserState.sessionId === sessionId && optimisticUsers !== optimisticUserState.items) {+ setOptimisticUserState({ sessionId, items: optimisticUsers });+ }+ const localUserClientIds = useMemo(() => new Set(optimisticUsers.map((entry) => entry.message.clientId)), [optimisticUsers]);+ const optimisticClientIds = useMemo(() => new Set([...localUserClientIds].filter((id) => !queueHiddenClientIds.has(id))),+ [localUserClientIds, queueHiddenClientIds]);+ const projectedMessages = useMemo(() => projectOptimisticUserMessages(projectedMessageWindow.projected, optimisticUsers),+ [projectedMessageWindow.projected, optimisticUsers]);+ // Adding/removing a user boundary invalidates prefix grouping, even if no host+ // message changed. Do not reuse source indexes after inserting local rows.+ const renderMessageStructureToken = useMemo(() => ({}), [messageStructureToken, optimisticUsers]);+ const projectedMessageStructureChangedIndexes = optimisticUsers.length > 0 ? undefined : projectedMessageWindow.changedIndexes;+ const oldestLoadedMessageCursor = useMemo(+ () => historyView.snapshot.ready ? historyView.snapshot.nextCursor : oldestMessageCursor(latestMessagesRef.current),+ [messageStructureToken, historyView.snapshot],+ );const streamingRenderPrefixRef = useRef<MobileStreamingRenderPrefixCache | null>(null);const renderWindow = useMemo(() => {@@ -4216,9 +4270,10 @@ export default function SessionScreen() {cacheKey: i18nInstance.language,messages: projectedMessages,messageStructureChangedIndexes: projectedMessageStructureChangedIndexes,- messageStructureToken,+ messageStructureToken: renderMessageStructureToken,options: {autoResumePending: inputProjection.autoResumePending,+ preserveSourceOrder: optimisticUsers.length > 0,isSessionStreaming: isMessageListStreaming,renderOrphanTaskUpdates: makerTurnRunning,sessionId,@@ -4229,7 +4284,7 @@ export default function SessionScreen() {const historyItems = historyView.snapshot.ready ? buildMobileHistoryRenderItems({view: historyView.view, snapshot: historyView.snapshot, messages: projectedMessages,streaming: isMessageListStreaming, sessionId, taskUpdates,- pendingHandoff: handoff.pending,+ pendingHandoff: handoff.pending, localUserClientIds,}) : builtWindow.items;let items = insertMobileForkOriginItem(// 孤儿 agent_task 兜底用 maker status 驱动的权威 turn 边界 gate,与 store 的@@ -4271,12 +4326,16 @@ export default function SessionScreen() {stablePrefixItemCount,};},- [historyView.snapshot, historyView.view, handoff.pending, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, projectedMessages, projectedMessageStructureChangedIndexes, sessionId, taskUpdates],+ [optimisticUsers, localUserClientIds, renderMessageStructureToken, historyView.snapshot, historyView.view, handoff.pending, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, projectedMessages, projectedMessageStructureChangedIndexes, sessionId, taskUpdates],);- const renderItems = renderWindow.items;+ // Search, media and sharing only see durable user rows. Local user boundaries+ // still participate in grouping and in the message list below.+ const renderItems = useMemo(() => optimisticClientIds.size === 0 ? renderWindow.items : renderWindow.items.filter((item) =>+ !(item.type === 'message' && optimisticClientIds.has(item.message.source.clientId))),+ [renderWindow.items, optimisticClientIds]);const renderItemsStructureKey = useMemo(() => ({}),- [historyView.snapshot, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, sessionId, taskUpdates],+ [optimisticUsers, historyView.snapshot, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, sessionId, taskUpdates],);// Reconciliation must only use committed rows. Unlike the prefix cache above, a speculative// render-item baseline could leak rows from an abandoned render and destabilize tail memoization.@@ -4286,14 +4345,14 @@ export default function SessionScreen() {&& previousRenderItemsRef.current?.prefix !== renderWindow.prefix&& streamingRenderPrefixRef.current === renderWindow.prefix) {- commitMobileStreamingPrefixItems(renderWindow.prefix, renderItems);+ commitMobileStreamingPrefixItems(renderWindow.prefix, renderWindow.items);}previousRenderItemsRef.current = {sessionId,- items: renderItems,+ items: renderWindow.items,prefix: renderWindow.prefix,};- }, [renderItems, renderWindow.prefix, sessionId]);+ }, [renderWindow.items, renderWindow.prefix, sessionId]);// Known stale entry content bypasses the quiet delay; routine sync stays subtle.const showSyncingIndicator = !showConnectionBanner && !showCachedHistoryNotice&& (loading || historyView.snapshot.loading || status === 'connecting' || contentRecoveryState === 'syncing');@@ -5468,6 +5527,7 @@ export default function SessionScreen() {// 乐观交接:进本地 pendingQueue 的同一同步段把条目移出 outbox,气泡原位从// 「发送中」变「排队中」不闪断;enqueue 成功后用权威 projection 覆盖 reconcile。const projectionBeforeSend = remoteSessionStore.getInputProjection(item.sessionId);+ markQueueItemSending(queued);remoteSessionStore.setInputProjectionOptimistically(item.sessionId, {...projectionBeforeSend,sessionId: projectionBeforeSend.sessionId || item.sessionId,@@ -5485,7 +5545,6 @@ export default function SessionScreen() {);// outbox 气泡本来就在转圈:交接进 pendingQueue 后 enqueue 仍在途,徽标继续转圈,// 不要在这一帧闪成排队 icon 再回来(也不能谎报「已入队」)。- markQueueItemSending(queued.clientId);const projectionRemoteEpochAtRequestStart =remoteSessionStore.captureInputProjectionRemoteEpoch(item.sessionId);const projectionEpochAtRequestStart =@@ -5719,12 +5778,12 @@ export default function SessionScreen() {],);const messageListItems = useMemo(- () => appendPendingSendItems(renderItems, pendingSendItems),- [pendingSendItems, renderItems],+ () => mergePendingSendItems(renderWindow.items, pendingSendItems, optimisticClientIds),+ [pendingSendItems, renderWindow.items, optimisticClientIds],);const messageListStructureKey = useMemo(() => ({}),- [pendingSendItems, renderItemsStructureKey],+ [pendingSendItems, renderItemsStructureKey, optimisticClientIds],);const shareExpandableBlockIds = useMemo(() => (shareSelectionActive ? collectConversationShareBlockIds(messageListItems) : []),@@ -6463,6 +6522,7 @@ export default function SessionScreen() {// previews / mediaAssetAttachments 映射保留到成功后再清:它们不入消息体,失败// 恢复 attachments 时缩略图能原样回来。const projectionBeforeSend = remoteSessionStore.getInputProjection(sessionId);+ markQueueItemSending(queued);remoteSessionStore.setInputProjectionOptimistically(sessionId, {...projectionBeforeSend,sessionId: projectionBeforeSend.sessionId || sessionId,@@ -6476,7 +6536,6 @@ export default function SessionScreen() {);// 乐观气泡此刻还没有「已入队」这个事实:徽标先给转圈,enqueue 落定后才交给// 排队 icon(或随回滚一起消失)。- markQueueItemSending(queued.clientId);const projectionRemoteEpochAtRequestStart =remoteSessionStore.captureInputProjectionRemoteEpoch(sessionId);setAttachments([]);diff --git a/apps/mobile/src/__tests__/mobileHistoryRender.test.ts b/apps/mobile/src/__tests__/mobileHistoryRender.test.tsindex 75ba718aa7..c639b32b8a 100644--- a/apps/mobile/src/__tests__/mobileHistoryRender.test.ts+++ b/apps/mobile/src/__tests__/mobileHistoryRender.test.ts@@ -31,6 +31,28 @@ function harness(rows: RemoteMessage[], streaming = false) {}describe('remote history preserves original folding', () => {+ it.each([0, 2_000_000_000_000])('keeps a local send before an early reply with phone time %s', async (phoneTime) => {+ const rows = [row(0, 'user', 'Earlier'), row(1, 'assistant', 'Done')];+ const { view } = harness(rows);+ await view.refresh();+ const sent = { ...row(2, 'user', 'Continue'), createdAt: new Date(phoneTime).toISOString() };+ const reply = { ...row(3, 'assistant', 'Reply'), agentMeta: { isStreaming: true } };+ const render = (user: RemoteMessage) => buildMobileHistoryRenderItems({+ view, snapshot: view.getSnapshot(), messages: [...rows.slice(0, 2), user, reply],+ streaming: true, sessionId: 'session', localUserClientIds: new Set([sent.clientId]),+ });+ const expected = ['message-client-0', 'message-client-1', 'message-client-2', 'message-client-3'];+ expect(render(sent).map((item) => item.key)).toEqual(expected);+ // Durable push before the history refresh must replace the local body, not+ // drop the row or append it after its response.+ const echo = row(2, 'user', 'Confirmed');+ expect(render(echo).map((item) => item.key)).toEqual(expected);+ rows.push(echo, row(3, 'assistant', 'Reply'));+ await view.refresh();+ expect(render(echo).map((item) => item.key)).toEqual(expected);+ view.setActive(false);+ });+it('clips retained detail bodies when a visible media tool splits the old range', async () => {const rows = [row(0, 'user', 'Work'), call(1), row(2, 'tool_result', 'ok', 'tool-1'), thought(3),call(4), row(5, 'tool_result', 'pending', 'tool-4'), thought(6), call(7), row(8, 'tool_result', 'ok', 'tool-7'), row(9, 'assistant', 'Done')];diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.tsindex 41de33dd6b..b5e66c57ee 100644--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts@@ -6,19 +6,25 @@* 重新出现」。改成消息流项后靠两点保证连续:key 与正式消息一致(`message-${clientId}`)、* 已回流的 clientId 立刻不再产出气泡(避免同一句话双显)。*/-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { formatQuoteForSend } from '@cindy/maker-shared/chat-quotes';import {appendPendingSendItems,buildMobileMessageListExtraData,buildPendingSendItems,isPendingSendItemSelected,+ mergePendingSendItems,pendingSendItemKey,pendingSendSpins,type MobilePendingSendActions,} from '@/session/pendingSendItems';import type { MobileOutboxDisplayItem } from '@/session/sessionOutbox';-import type { QueuedRemoteMessage } from '@/session/types';+import type { QueuedRemoteMessage, RemoteMessage } from '@/session/types';+import { remoteSessionStore } from '@/session/remoteSessionStore';+import { buildMobileMessageRenderItems } from '@/session/messageRenderModel';+import { buildMobileStreamingRenderWindow } from '@/session/messageRenderStreamingCache';+import { computeVanishedQueueItems } from '@/session/queueSettling';+import { appendOptimisticUserMessage, projectOptimisticUserMessages, reconcileOptimisticUserMessages, type OptimisticUserMessage } from '@/session/optimisticUserMessages';const NO_IDS: ReadonlySet<string> = new Set();const NO_PRESENTATION: ReadonlyMap<string, { actions: MobilePendingSendActions; hint: string | null }> = new Map();@@ -95,6 +101,177 @@ describe('appendPendingSendItems', () => {});});+describe('reply before user echo', () => {+ const sessionId = 'reply-order';+ function row(clientId: string, role: RemoteMessage['role'], seconds: number): RemoteMessage {+ return { id: clientId, clientId, sessionId, role,+ createdAt: new Date(Date.UTC(2026, 6, 30, 0, 0, seconds)).toISOString(),+ content: role === 'user' ? { text: 'Continue' } : 'Reply', toolUseId: null, agentMeta: null };+ }+ function push(message: RemoteMessage) {+ remoteSessionStore.applyRemotePush('dev', 'local-db:messages:created', { sessionId, message });+ }+ function reserve(current: readonly OptimisticUserMessage[] = [], clientId = 'sent') {+ return appendOptimisticUserMessage(current, remoteSessionStore.getMessages(sessionId), queued(clientId), sessionId);+ }+ function render(pending: ReturnType<typeof build>, slots: readonly OptimisticUserMessage[]) {+ const messages = remoteSessionStore.getMessages(sessionId);+ const echoed = new Set(messages.map((message) => message.clientId));+ return mergePendingSendItems(buildMobileMessageRenderItems(+ projectOptimisticUserMessages(messages, slots), { isSessionStreaming: true, preserveSourceOrder: true },+ ), pending, new Set(slots.map((entry) => entry.message.clientId).filter((id) => !echoed.has(id))));+ }+ afterEach(() => { remoteSessionStore.clear(); vi.useRealTimers(); });++ it.each([false, true])('leaves unreserved busy sends to authoritative history (separate renders: %s)', (separateRenders) => {+ push(row('current', 'user', 0));+ push(row('current-reply', 'assistant', 1));+ const previousQueue = [queued('sent')];+ // Busy sends keep the existing pending tail, without claiming a turn slot.+ expect(render(build({ queue: previousQueue }), []).at(-1)?.key).toBe('message-sent');+ push(row('next-reply', 'assistant', 3));+ if (separateRenders) {+ expect(render(build({ queue: previousQueue }), []).map((item) => item.key)).toEqual([+ 'message-current', 'message-current-reply', 'message-next-reply', 'message-sent',+ ]);+ }+ const settling = computeVanishedQueueItems({+ previous: previousQueue, current: [], previousSteeringClientIds: NO_IDS,+ currentSteeringClientIds: NO_IDS, hiddenClientIds: NO_IDS, locallyRemovedClientIds: NO_IDS,+ });+ expect(render(build({ settling }), []).map((item) => item.key)).toEqual([+ 'message-current', 'message-current-reply', 'message-next-reply', 'message-sent',+ ]);+ push(row('sent', 'user', 2));+ expect(render(build({ settling }), []).map((item) => item.key)).toEqual([+ 'message-current', 'message-current-reply', 'message-sent', 'message-next-reply',+ ]);+ });++ it('invalidates the streaming prefix when a local user introduces a new turn boundary', () => {+ const old = [row('old-user', 'user', 0), { ...row('old-thinking', 'thinking', 1), content: { text: 'Old thought' } }];+ const previous = buildMobileStreamingRenderWindow({+ cacheKey: 'en', messages: old, messageStructureToken: {},+ options: { isSessionStreaming: true, sessionId },+ });+ const slots = appendOptimisticUserMessage([], old, queued('sent'), sessionId);+ const current = [...old, { ...row('new-thinking', 'thinking', 3), content: { text: 'New thought' } }];+ const next = buildMobileStreamingRenderWindow({+ cacheKey: 'en', messages: projectOptimisticUserMessages(current, slots),+ messageStructureToken: {}, previousPrefix: previous.prefix,+ options: { isSessionStreaming: true, preserveSourceOrder: true, sessionId },+ });+ expect(next.items.map((item) => item.key)).toEqual([+ 'message-old-user', 'work-old-thinking', 'message-sent', 'work-new-thinking',+ ]);+ });++ it.each(['settling', 'sending'])('keeps the %s bubble before an early reply and replaces it in place', (phase) => {+ push(row('old-user', 'user', 0));+ push(row('old-reply', 'assistant', 1));+ const slots = reserve(); // The production send path reserves BEFORE enqueue.+ const pending = build({+ settling: phase === 'settling' ? [queued('sent')] : [],+ queue: phase === 'sending' ? [queued('sent'), queued('next')] : [queued('next')],+ sendingClientIds: new Set(phase === 'sending' ? ['sent'] : []),+ outbox: [outboxItem('upload', { attachmentCount: 1, uploadedCount: 0 })],+ });+ push(row('reply', 'assistant', 3));+ const before = render(pending, slots);+ expect(before.map((item) => item.key)).toEqual([+ 'message-old-user', 'message-old-reply', 'message-sent', 'message-reply', 'message-next', 'message-upload',+ ]);+ expect(before[2]).toBe(pending[0]);+ push(row('sent', 'user', 2));+ expect(render(pending, slots).map((item) => item.key)).toEqual(before.map((item) => item.key));+ expect(render(pending, slots)[2].type).toBe('message');+ });++ it.each(['2020-01-01', '2030-01-01'])('ignores a phone clock set to %s', (clock) => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(clock));+ const source = queued('sent');+ source.chatMessage.createdAt = new Date().toISOString();+ const slots = appendOptimisticUserMessage([], [], source, sessionId);+ const pending = build({ settling: [source] });+ remoteSessionStore.applyRemotePush('dev', 'maker:event', {+ sessionId, persistId: 'reply', event: { type: 'text', data: { text: 'Reply', isFinal: false } },+ });+ vi.advanceTimersByTime(100);+ expect(render(pending, slots).map((item) => item.key)).toEqual(['message-sent', 'message-reply']);+ push(row('sent', 'user', 2));+ expect(render(pending, slots).map((item) => item.key)).toEqual(['message-sent', 'message-reply']);+ });++ it('separates new folded work from the previous turn before grouping', () => {+ push(row('old-user', 'user', 0));+ push({ ...row('old-thinking', 'thinking', 1), content: { text: 'Old thought' } });+ const slots = reserve();+ push({ ...row('thinking', 'thinking', 3), content: { text: 'New thought' } });+ const items = render(build({ settling: [queued('sent')] }), slots);+ expect(items.map((item) => item.key)).toEqual([+ 'message-old-user', 'work-old-thinking', 'message-sent', 'work-thinking',+ ]);+ });++ it.each(['image', 'synthetic'])('retains the reserved %s bubble before reply grouping', (kind) => {+ const source = queued('sent', kind === 'synthetic' ? '[UI_ACTION_TRIGGER] hidden action' : '');+ if (kind === 'image') source.chatMessage.images = [{ url: 'https://example.com/image.png', name: 'image.png' }];+ const slots = appendOptimisticUserMessage([], [], source, sessionId);+ push(row('reply', 'assistant', 3));+ const pending = build({ settling: [source] });+ const items = render(pending, slots);+ expect(items.map((item) => item.key)).toEqual(['message-sent', 'message-reply']);+ expect(items[0]).toBe(pending[0]);+ expect(JSON.stringify(items[0])).not.toContain('hidden action');+ });++ it.each(['sent', 'second'])('keeps two reserved positions when %s echoes first', (firstEcho) => {+ let slots = reserve();+ push(row('reply', 'assistant', 3));+ slots = reserve(slots, 'second');+ push(row('second-reply', 'assistant', 5));+ let pending = build({ settling: [queued('sent'), queued('second')] });+ const expected = ['message-sent', 'message-reply', 'message-second', 'message-second-reply'];+ expect(render(pending, slots).map((item) => item.key)).toEqual(expected);+ push(row(firstEcho, 'user', firstEcho === 'sent' ? 2 : 4));+ expect(render(pending, slots).map((item) => item.key)).toEqual(expected);+ pending = pending.filter((item) => item.clientId !== firstEcho);+ slots = reconcileOptimisticUserMessages(slots, remoteSessionStore.getMessages(sessionId),+ new Set(pending.map((item) => item.clientId)), new Set([firstEcho]));+ expect(render(pending, slots).map((item) => item.key)).toEqual(expected);+ });++ it('keeps a busy follow-up and unsent outbox at the tail until dispatch', () => {+ push(row('current', 'user', 0));+ const pending = build({ queue: [queued('next')], sendingClientIds: new Set(['next']), outbox: [outboxItem('upload')] });+ push(row('reply', 'assistant', 3));+ expect(render(pending, []).map((item) => item.key))+ .toEqual(['message-current', 'message-reply', 'message-next', 'message-upload']);+ const slots = reserve([], 'next');+ push(row('next-reply', 'assistant', 5));+ expect(render(build({ settling: [queued('next')] }), slots).map((item) => item.key))+ .toEqual(['message-current', 'message-reply', 'message-next', 'message-next-reply']);+ });++ it('drops failed, cancelled, and rolled-back queue reservations', () => {+ const slots = reserve();+ expect(reconcileOptimisticUserMessages(slots, [], NO_IDS, NO_IDS)).toEqual([]);+ expect(reconcileOptimisticUserMessages(slots, [], new Set(['sent']), NO_IDS)).toBe(slots);+ expect(reconcileOptimisticUserMessages(slots, [row('sent', 'user', 2)], NO_IDS, NO_IDS)).toBe(slots);+ expect(reconcileOptimisticUserMessages(slots, [row('sent', 'user', 2)], NO_IDS, new Set(['sent']))).toEqual([]);+ });++ it('preserves prepended history and does not use timestamps to reanchor the send', () => {+ push(row('old-reply', 'assistant', 1));+ const slots = reserve();+ push(row('older-user', 'user', 0));+ push(row('reply', 'assistant', 3));+ expect(render(build({ settling: [queued('sent')] }), slots).map((item) => item.key))+ .toEqual(['message-older-user', 'message-old-reply', 'message-sent', 'message-reply']);+ });+});+describe('buildPendingSendItems', () => {it('shares the message item key so the bubble and the real message land in one place', () => {const [item] = build({ queue: [queued('abc')] });diff --git a/apps/mobile/src/__tests__/sendingQueueBadge.test.ts b/apps/mobile/src/__tests__/sendingQueueBadge.test.tsindex a83a5cfeef..5e419c7725 100644--- a/apps/mobile/src/__tests__/sendingQueueBadge.test.ts+++ b/apps/mobile/src/__tests__/sendingQueueBadge.test.ts@@ -37,7 +37,13 @@ describe('mobile sending queue badge', () => {expect(source).toContain('sendingClientIds: sendingQueueBadgeClientIds,');// 直发路径与 outbox 交接路径各 mark 一次,各自在 finally 收掉。- expect(source.match(/markQueueItemSending\(queued\.clientId\);/g)).toHaveLength(2);+ expect(source.match(/markQueueItemSending\(queued\);/g)).toHaveLength(2);+ // Both send entries reserve the user slot before publishing the optimistic+ // queue (and before enqueue can deliver an assistant event).+ expect(source.match(/markQueueItemSending\(queued\);\s+remoteSessionStore\.setInputProjectionOptimistically/g)).toHaveLength(2);+ // Only enqueue reserves a slot; queue recovery must not infer a boundary+ // from either current messages or a previous committed render.+ expect(source.match(/appendOptimisticUserMessage\(/g)).toHaveLength(1);expect(source.match(/clearQueueItemSending\(queued\.clientId\);/g)).toHaveLength(2);expect(source).toContain('} finally {\n // 成功、对账认定已入队、回滚 throw 三条路径都算「不再在途」');// 新建会话乐观管线在跑时,首条消息同样是「已上屏未确认」。diff --git a/apps/mobile/src/session/messageRenderStreamingCache.ts b/apps/mobile/src/session/messageRenderStreamingCache.tsindex 868dd39edf..4fbc3e1f1b 100644--- a/apps/mobile/src/session/messageRenderStreamingCache.ts+++ b/apps/mobile/src/session/messageRenderStreamingCache.ts@@ -50,6 +50,7 @@ interface BuildMobileStreamingRenderWindowInput {messageStructureToken?: object;options: MessageRenderOptions & {autoResumePending?: Record<string, unknown> | null;+ preserveSourceOrder?: boolean;sessionId?: string;};prefixCache?: MobileStreamingRenderPrefixCacheRef;diff --git a/apps/mobile/src/session/mobileHistoryRender.ts b/apps/mobile/src/session/mobileHistoryRender.tsindex 01b68f5bb9..92cc39b998 100644--- a/apps/mobile/src/session/mobileHistoryRender.ts+++ b/apps/mobile/src/session/mobileHistoryRender.ts@@ -10,12 +10,14 @@ export function buildMobileHistoryRenderItems(options: {streaming: boolean;sessionId: string;pendingHandoff?: ReadonlySet<string>;+ localUserClientIds?: ReadonlySet<string>;taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;}): MobileMessageRenderItem[] {return renderHistoryView<RemoteMessage, MobileMessageRenderItem>({view: options.view, snapshot: options.snapshot, liveMessages: options.messages,isLive: (row) => row.agentMeta?.isStreaming === true,pendingHandoff: options.pendingHandoff,+ isLocalUser: (row) => options.localUserClientIds?.has(row.clientId) === true,streaming: options.streaming,build: (rows, streaming) => buildMobileMessageRenderItems(rows, {isSessionStreaming: streaming, sessionId: options.sessionId, preserveSourceOrder: true,diff --git a/apps/mobile/src/session/optimisticUserMessages.ts b/apps/mobile/src/session/optimisticUserMessages.tsnew file mode 100644index 0000000000..59d83c3563--- /dev/null+++ b/apps/mobile/src/session/optimisticUserMessages.ts@@ -0,0 +1,66 @@+import type { QueuedRemoteMessage, RemoteMessage } from './types';+import { pendingSendBubbleText } from './pendingSendItems';++/** Page-local transcript slots, never persisted or sent over device-link. */+export interface OptimisticUserMessage {+ message: RemoteMessage;+ precedingClientIds: ReadonlySet<string>;+}++/** Reserve a user row synchronously before enqueue, as Desktop does. */+export function appendOptimisticUserMessage(+ current: readonly OptimisticUserMessage[],+ messages: readonly RemoteMessage[],+ queued: QueuedRemoteMessage,+ sessionId: string,+): readonly OptimisticUserMessage[] {+ if (current.some((entry) => entry.message.clientId === queued.clientId)+ || messages.some((message) => message.clientId === queued.clientId)) return current;+ const source = queued.chatMessage;+ return [...current, {+ message: {+ id: queued.clientId, clientId: queued.clientId, sessionId, role: 'user',+ createdAt: source.createdAt, toolUseId: null, agentMeta: null,+ // This is the pending bubble's visible label, including synthetic-action+ // masking. Its authoritative body replaces it on echo.+ content: { ...source, text: pendingSendBubbleText(queued) },+ },+ precedingClientIds: new Set([+ ...messages.map((message) => message.clientId),+ ...current.map((entry) => entry.message.clientId),+ ]),+ }];+}++/** Preserve observation order; device clocks are not ordering evidence. */+export function projectOptimisticUserMessages(+ messages: readonly RemoteMessage[],+ optimistic: readonly OptimisticUserMessage[],+): readonly RemoteMessage[] {+ if (optimistic.length === 0) return messages;+ const result = [...messages];+ for (const entry of optimistic) {+ const echo = result.findIndex((message) => message.clientId === entry.message.clientId);+ const message = echo < 0 ? entry.message : result.splice(echo, 1)[0];+ let after = -1;+ for (let index = 0; index < result.length; index++) {+ if (entry.precedingClientIds.has(result[index].clientId)) after = index;+ }+ result.splice(after + 1, 0, message);+ }+ return result;+}++/** Queue rollback/failure removes the slot; a durable echo hands it to history. */+export function reconcileOptimisticUserMessages(+ current: readonly OptimisticUserMessage[],+ messages: readonly RemoteMessage[],+ activeClientIds: ReadonlySet<string>,+ confirmedClientIds: ReadonlySet<string>,+): readonly OptimisticUserMessage[] {+ if (current.length === 0) return current;+ const echoed = new Set(messages.map((message) => message.clientId));+ const remaining = current.filter(({ message }) => !confirmedClientIds.has(message.clientId)+ && (activeClientIds.has(message.clientId) || echoed.has(message.clientId)));+ return remaining.length === current.length ? current : remaining;+}diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.tsindex dba595d97b..1fa32db457 100644--- a/apps/mobile/src/session/pendingSendItems.ts+++ b/apps/mobile/src/session/pendingSendItems.ts@@ -12,8 +12,8 @@* 进了 data 之后:与正式消息同容器、同 key(`message-${clientId}`)、同一处位置,回流就是* 同一个列表位置上的内容替换 —— 原地变实,零跳动;listData 也不再为空,居中占位自然不出现。*- * 顺序契约(与原 footer 一致):落定中(已出队、等回流)在前,排队中居中,本地 outbox 在后- * —— outbox 是最晚发出的。+ * 未派发条目保持队列 / outbox 顺序。已派发气泡在分组前占据本地用户消息的位置,+ * 正式回流以同一个 clientId 原位替换,不比较控制端与主机的时钟。*/import { syntheticTriggerKind } from '@cindy/maker-shared/synthetic-trigger';import {@@ -28,6 +28,7 @@ import {} from '@/session/sentMessageAtoms';import type { QueuedRemoteMessage } from '@/session/types';import type { GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';+import type { MobileMessageRenderItem } from '@/session/messageRenderModel';export type MobilePendingSendPhase =/** 已确认入队,等被控端派发。 */@@ -119,6 +120,19 @@ export function appendPendingSendItems<T extends { key: string }>(return remaining.length === 0 ? rendered : [...rendered, ...remaining];}+/** Replace only local placeholders; durable echoes win even with stale queue state. */+export function mergePendingSendItems(+ rendered: readonly MobileMessageRenderItem[],+ pending: readonly MobilePendingSendItem[],+ optimisticClientIds: ReadonlySet<string>,+): readonly MobileMessageRenderItem[] {+ const byId = new Map(pending.map((item) => [item.clientId, item]));+ const replaced = optimisticClientIds.size === 0 ? rendered : rendered.map((item) =>+ item.type === 'message' && optimisticClientIds.has(item.message.source.clientId)+ ? byId.get(item.message.source.clientId) ?? item : item);+ return appendPendingSendItems(replaced, pending);+}+/*** 气泡显示文本:合成 UI 指令行(桌面「失败后继续」等隐藏 prompt)用遮蔽标签替代原文* —— 裸英文指令不能给用户看(对齐桌面 PendingQueuePanel 的 i18n 遮蔽标签)。