Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修复发送消息与历史列表交接时短暂消失
Dash276bc5182c1a
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex d6f8afc95c..d4cc434eed 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, historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';+import { HistoryViewHandoff, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';import { buildMobileHistoryRenderItems } from '@/session/mobileHistoryRender';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';@@ -342,6 +342,7 @@ import {} from '@/session/pendingSendItems';import {appendOptimisticUserMessage,+ confirmedHistoryUserClientIds,projectOptimisticUserMessages,reconcileOptimisticUserMessages,type OptimisticUserMessage,@@ -616,7 +617,7 @@ import {shouldFallbackToLegacyCodexUsage,} from '@/session/sessionControls';import { buildSessionOperationLayout, composerDisabledReasonI18nKey } from '@/session/sessionOperationLayout';-import { computeVanishedQueueItems, mergeSettlingItems } from '@/session/queueSettling';+import { computeVanishedQueueItems, mergeSettlingItems, settleEnqueueResult } from '@/session/queueSettling';import {summarizeSessionOverview,type SessionActionStripActionId,@@ -1520,6 +1521,12 @@ export default function SessionScreen() {}const markQueueItemSending = useCallback((queued: QueuedRemoteMessage) => {const clientId = queued.clientId;+ setLocallyRemovedQueueClientIds((current) => {+ if (!current.has(clientId)) return current;+ const next = new Set(current);+ next.delete(clientId);+ return next;+ });const projection = remoteSessionStore.getInputProjection(sessionId);const source = remoteSessionStore.getMessages(sessionId);// Match Desktop's idle-send placement. Busy follow-ups retain the existing@@ -1538,14 +1545,27 @@ export default function SessionScreen() {return next;});}, [sessionId]);- const clearQueueItemSending = useCallback((clientId: string) => {+ const clearQueueItemSending = useCallback((queued: QueuedRemoteMessage, accepted: boolean) => {+ const clientId = queued.clientId;setSendingQueueClientIds((current) => {if (!current.has(clientId)) return current;const next = new Set(current);next.delete(clientId);return next;});- }, []);+ if (outboxSessionAliveRef.current !== sessionId) return;+ const pendingQueue = remoteSessionStore.getInputProjection(sessionId).pendingQueue;+ // The enqueue RPC can finish after drain but before any queued frame commits.+ // Transfer ownership in the same completion callback, including reconciled ACK loss.+ if (accepted && !pendingQueue.some((item) => item.clientId === clientId)) {+ if (!settlingAddedAtRef.current.has(clientId)) settlingAddedAtRef.current.set(clientId, Date.now());+ }+ if (!accepted) {+ settlingAddedAtRef.current.delete(clientId);+ setLocallyRemovedQueueClientIds((current) => new Set([...current, clientId]));+ }+ setSettlingQueueItems((current) => settleEnqueueResult(current, queued, accepted, pendingQueue));+ }, [sessionId, setSettlingQueueItems]);/*** 落定判定的基线:上一帧的 pendingQueue 与插队标记。*@@ -4048,15 +4068,17 @@ export default function SessionScreen() {),[currentSession?.createdAt, currentSession?.forkedAtMessageId, currentSession?.parentSessionId],);+ const confirmedUserClientIds = useMemo(() => confirmedHistoryUserClientIds(historyView.snapshot),+ [historyView.snapshot]);// inline 排队区去重集:已回流进消息流的 clientId 不再渲染排队气泡(排队气泡消失的// 同帧正式气泡已在流里,视觉上原位变实心,无跳变)。const queueHiddenClientIds = useMemo(() => {const ids = new Set<string>();- for (const message of latestMessagesRef.current) {+ for (const message of messages) {if (message.clientId) ids.add(message.clientId);}return ids;- }, [messageStructureToken]);+ }, [messages]);// 落定中条目跟踪(见 settlingQueueItems 声明处注释):// 1) pendingQueue diff——只把「像被派发」的消失当作落定中:drain 恒从队首连续// 消费,steer 按 steeringQueueClientIds 标记;两者都不沾的中段消失是远端删除@@ -4091,7 +4113,7 @@ export default function SessionScreen() {current: inputProjection.pendingQueue,previousSteeringClientIds: previousSteering,currentSteeringClientIds: currentSteering,- hiddenClientIds: queueHiddenClientIds,+ hiddenClientIds: confirmedUserClientIds,locallyRemovedClientIds: locallyRemovedQueueClientIds,});const now = Date.now();@@ -4111,19 +4133,19 @@ export default function SessionScreen() {inputProjection.pendingQueue,inputProjection.steeringQueueClientIds,locallyRemovedQueueClientIds,- queueHiddenClientIds,+ confirmedUserClientIds,sessionId,setSettlingQueueItems,settlingBaseline,]);- // 「这一条不该再画落定气泡」的唯一判据:已回流(正式消息进流里)或用户本地删除。- // render 过滤与 effect 摘除共用它,不再各写一份。+ // 永久释放等待状态必须等历史接管;实时回流只通过 queueHiddenClientIds 隐藏本帧+ // 气泡,否则首个旧历史页接管时,实时消息和已清理的气泡会同时缺席。const settlingRetired = useCallback(- (clientId: string) => queueHiddenClientIds.has(clientId)+ (clientId: string) => confirmedUserClientIds.has(clientId)|| locallyRemovedQueueClientIds.has(clientId),- [locallyRemovedQueueClientIds, queueHiddenClientIds],+ [locallyRemovedQueueClientIds, confirmedUserClientIds],);- // 2) 回流 / 本地删除即移除(排队气泡消失的同帧正式气泡已在流里,原位变实);+ // 2) 历史接管 / 本地删除即移除;// 同样用 layout effect:跨帧会让「落定转圈气泡 + 已回流正式消息」双显一帧// (实测日志里的 msgs=1 settling=1 那帧),视觉上是同一句话闪成两条。// 本地删除也在这里摘:删除标记与队列出队现在都是 state,谁先落地不确定,标记晚@@ -4150,14 +4172,14 @@ export default function SessionScreen() {current: inputProjection.pendingQueue,previousSteeringClientIds: settlingBaseline.steeringClientIds,currentSteeringClientIds: new Set(inputProjection.steeringQueueClientIds),- hiddenClientIds: queueHiddenClientIds,+ hiddenClientIds: confirmedUserClientIds,locallyRemovedClientIds: locallyRemovedQueueClientIds,}),[inputProjection.pendingQueue,inputProjection.steeringQueueClientIds,locallyRemovedQueueClientIds,- queueHiddenClientIds,+ confirmedUserClientIds,settlingBaseline,],);@@ -4228,14 +4250,9 @@ export default function SessionScreen() {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),+ ...sendingQueueClientIds,...settlingItemsForRender.map((item) => item.clientId),]);// Only the enqueue path can reserve a transcript position. A vanished@@ -4243,9 +4260,9 @@ export default function SessionScreen() {// can arrive in either order, across any number of committed renders.return reconcileOptimisticUserMessages(optimisticUserState.sessionId === sessionId ? optimisticUserState.items : [],- messages, activeIds, confirmedUserClientIds,+ rawMessages, activeIds, confirmedUserClientIds,);- }, [optimisticUserState, sessionId, messages, inputProjection.pendingQueue,+ }, [optimisticUserState, sessionId, rawMessages,sendingQueueClientIds, settlingItemsForRender, confirmedUserClientIds]);if (optimisticUserState.sessionId === sessionId && optimisticUsers !== optimisticUserState.items) {setOptimisticUserState({ sessionId, items: optimisticUsers });@@ -5549,6 +5566,7 @@ export default function SessionScreen() {remoteSessionStore.captureInputProjectionRemoteEpoch(item.sessionId);const projectionEpochAtRequestStart =remoteSessionStore.captureInputProjectionAuthorityEpoch(item.sessionId);+ let enqueueAccepted = false;try {// 弱网重试与写序边界同 send() 原路径(仅明确可安全重发的瞬时传输错误)。let projection: InputProjection | undefined;@@ -5572,12 +5590,14 @@ export default function SessionScreen() {projectionRemoteEpochAtRequestStart,queued.clientId,);+ enqueueAccepted = true;} catch (err) {// 与原路径同口径:先对账分辨「确实没应用」vs「已应用但响应丢了」。const safeToRetry = isSafelyUnsentOutboxEnqueueError(err);const accepted = await readAuthoritativeEnqueueAcceptance(item.sessionId, queued.clientId, projectionRemoteEpochAtRequestStart,);+ enqueueAccepted = accepted;if (!accepted) {const current = remoteSessionStore.getInputProjection(item.sessionId);remoteSessionStore.setInputProjectionOptimistically(item.sessionId, {@@ -5593,7 +5613,7 @@ export default function SessionScreen() {} finally {// 入队确认、回 outbox / 失败,或转交 optimistic projection 等待权威同步后,// 都不再是当前 RPC 在途;收掉 sending 标记,避免后续同 id 气泡悬空转圈。- clearQueueItemSending(queued.clientId);+ clearQueueItemSending(queued, enqueueAccepted);}// enqueue / 对账期间离场时,成功路径无需恢复草稿,但旧 pump 也绝不能接着// 消费新任务的 outbox;失败路径已由 failItem / waitForConnection 按 A 收口。@@ -6546,6 +6566,7 @@ export default function SessionScreen() {requestMessageListFollowLatest();const projectionEpochAtRequestStart =remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);+ let enqueueAccepted = false;try {// 弱网重试:切基站 / 短暂断连时自动补发,不让用户为一次抖动手动重发。// 写序边界(codex review P1 + auto-review P1):只有「保证未发出」的@@ -6572,6 +6593,7 @@ export default function SessionScreen() {projectionRemoteEpochAtRequestStart,queued.clientId,);+ enqueueAccepted = true;} catch (err) {// 回滚前先分辨「确实没应用」vs「已应用但响应丢了」:优先 refetch 权威// projection 判断。只有权威证据能保留乐观气泡;证据不可用时回到现有@@ -6579,6 +6601,7 @@ export default function SessionScreen() {const accepted = await readAuthoritativeEnqueueAcceptance(sessionId, queued.clientId, projectionRemoteEpochAtRequestStart,);+ enqueueAccepted = accepted;if (!accepted) {// 回滚:按 clientId 精确摘除乐观气泡(期间 projection 可能已被其他事件更新,// 不能整体还原快照),并恢复草稿与附件托盘。@@ -6603,7 +6626,7 @@ export default function SessionScreen() {} finally {// 成功、对账认定已入队、回滚 throw 三条路径都算「不再在途」:转圈必须收掉,// 否则回滚后集合残留、同 clientId 重发时首帧仍是转圈。- clearQueueItemSending(queued.clientId);+ clearQueueItemSending(queued, enqueueAccepted);}// 消息已由 A 路径落定;若等待期间切到 B,只停止旧 continuation,不能再用// A 的附件 id / plan 状态去清理 B 的 composer UI。diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.tsindex 1dd1f826c4..af02c451b9 100644--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts@@ -258,7 +258,10 @@ describe('reply before user echo', () => {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);+ const echo = row('sent', 'user', 2);+ const echoedSlots = reconcileOptimisticUserMessages(slots, [echo], NO_IDS, NO_IDS);+ expect(echoedSlots).toEqual([{ ...slots[0], message: echo }]);+ expect(reconcileOptimisticUserMessages(echoedSlots, [echo], NO_IDS, NO_IDS)).toBe(echoedSlots);expect(reconcileOptimisticUserMessages(slots, [row('sent', 'user', 2)], NO_IDS, new Set(['sent']))).toEqual([]);});diff --git a/apps/mobile/src/__tests__/sentMessageHandoff.test.ts b/apps/mobile/src/__tests__/sentMessageHandoff.test.tsnew file mode 100644index 0000000000..cd716702d0--- /dev/null+++ b/apps/mobile/src/__tests__/sentMessageHandoff.test.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from 'vitest';+import { HistoryViewController, HistoryViewHandoff, projectHistoryView } from '@cindy/maker-shared/message-window';+import { appendOptimisticUserMessage, confirmedHistoryUserClientIds, projectOptimisticUserMessages, reconcileOptimisticUserMessages } from '../session/optimisticUserMessages';+import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';+import { buildMobileMessageRenderItems } from '../session/messageRenderModel';+import { buildPendingSendItems, mergePendingSendItems } from '../session/pendingSendItems';+import { settleEnqueueResult } from '../session/queueSettling';+import type { QueuedRemoteMessage, RemoteMessage } from '../session/types';++const none: ReadonlySet<string> = new Set();+const queued = {+ clientId: 'sent', text: 'hello',+ chatMessage: { clientId: 'sent', role: 'user', content: 'hello', createdAt: '2030-01-01T00:00:00Z' },+} as QueuedRemoteMessage;+const echo: RemoteMessage = {+ id: 'db-sent', clientId: 'sent', sessionId: 's', role: 'user', content: 'authoritative hello',+ createdAt: '2026-09-17T00:00:00Z', toolUseId: null, agentMeta: null,+};++describe('sent message handoff', () => {+ it.each([false, true])('keeps exactly one user row across a stale history page (initially ready=%s)', async (ready) => {+ let history: RemoteMessage[] = [];+ 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,+ });+ if (ready) await view.refresh();+ const handoff = new HistoryViewHandoff<RemoteMessage>((row) => row.agentMeta?.isStreaming === true);+ let slots = appendOptimisticUserMessage([], [], queued, 's');+ const render = (raw: RemoteMessage[], active = none) => {+ const snapshot = view.getSnapshot();+ const state = handoff.reconcile(snapshot, raw);+ slots = reconcileOptimisticUserMessages(slots, raw, active, confirmedHistoryUserClientIds(snapshot));+ const messages = projectOptimisticUserMessages(state.messages, slots);+ return snapshot.ready+ ? buildMobileHistoryRenderItems({ view, snapshot, messages, pendingHandoff: state.pending,+ localUserClientIds: new Set(slots.map((entry) => entry.message.clientId)), streaming: false, sessionId: 's' })+ : buildMobileMessageRenderItems(messages, { preserveSourceOrder: true });+ };+ expect(render([], new Set(['sent'])).map((item) => item.key)).toEqual(['message-sent']);+ expect(render([echo]).map((item) => item.key)).toEqual(['message-sent']);+ await view.refresh(); // A page requested before enqueue finishes after the push.+ const stale = render([echo]);+ expect(stale.map((item) => item.key)).toEqual(['message-sent']);+ expect(JSON.stringify(stale)).toContain('authoritative hello');+ expect(slots).toHaveLength(1);+ history = [echo];+ await view.refresh();+ expect(render([echo]).map((item) => item.key)).toEqual(['message-sent']);+ expect(slots).toHaveLength(0);+ // After ownership transfers, clear/rewind must not resurrect a local copy.+ history = [];+ await view.refresh();+ expect(render([])).toEqual([]);+ view.setActive(false);+ });++ it.each([false, true])('covers drain before the queued frame commits (reserved=%s)', (reserved) => {+ let slots = reserved ? appendOptimisticUserMessage([], [], queued, 's') : [];+ // React never observed pendingQueue=[queued]. Completion still owns the bubble.+ const settling = settleEnqueueResult([], queued, true, []);+ slots = [...reconcileOptimisticUserMessages(slots, [], new Set(settling.map((item) => item.clientId)), none)];+ const pending = buildPendingSendItems({ queue: [], settling, outbox: [], hiddenClientIds: none,+ sendingClientIds: none, editingClientId: null, steeringClientIds: none, presentationByClientId: new Map() });+ const render = (raw: RemoteMessage[]) => mergePendingSendItems(+ buildMobileMessageRenderItems(projectOptimisticUserMessages(raw, slots), { preserveSourceOrder: true }),+ pending, new Set(slots.filter((entry) => !raw.some((row) => row.clientId === entry.message.clientId))+ .map((entry) => entry.message.clientId)),+ );+ expect(render([]).map((item) => item.key)).toEqual(['message-sent']);+ expect(render([echo]).map((item) => item.key)).toEqual(['message-sent']);+ expect(settleEnqueueResult(settling, queued, true, [])).toBe(settling);+ expect(settleEnqueueResult(settling, queued, false, [])).toEqual([]);+ });++ it('does not claim a settling item while it remains queued', () => {+ const settling: QueuedRemoteMessage[] = [];+ expect(settleEnqueueResult(settling, queued, true, [queued])).toBe(settling);+ });++ it('retains a busy send through raw-to-history switching without duplicating the echo', async () => {+ let history: RemoteMessage[] = [];+ 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 = new HistoryViewHandoff<RemoteMessage>(() => false);+ let settling = settleEnqueueResult([], queued, true, []);+ const render = () => {+ const snapshot = view.getSnapshot();+ const state = handoff.reconcile(snapshot, [echo]);+ const confirmed = confirmedHistoryUserClientIds(snapshot);+ settling = settling.filter((item) => !confirmed.has(item.clientId));+ const pending = buildPendingSendItems({ queue: [], settling, outbox: [],+ hiddenClientIds: new Set(state.messages.map((row) => row.clientId)), sendingClientIds: none,+ editingClientId: null, steeringClientIds: none, presentationByClientId: new Map() });+ const rendered = snapshot.ready+ ? buildMobileHistoryRenderItems({ view, snapshot, messages: state.messages, streaming: false, sessionId: 's' })+ : buildMobileMessageRenderItems(state.messages);+ return mergePendingSendItems(rendered, pending, none);+ };+ expect(render().map((item) => item.key)).toEqual(['message-sent']);+ expect(settling).toHaveLength(1);+ await view.refresh();+ expect(render().map((item) => item.key)).toEqual(['message-sent']);+ history = [echo];+ await view.refresh();+ expect(render().map((item) => item.key)).toEqual(['message-sent']);+ expect(settling).toEqual([]);+ view.setActive(false);+ });++ it('drops a reservation when the raw echo is deleted before history takes over', () => {+ let slots = appendOptimisticUserMessage([], [], queued, 's');+ slots = reconcileOptimisticUserMessages(slots, [echo], none, none);+ expect(slots[0].message).toBe(echo);+ expect(reconcileOptimisticUserMessages(slots, [], none, none)).toEqual([]);+ });+});diff --git a/apps/mobile/src/session/optimisticUserMessages.ts b/apps/mobile/src/session/optimisticUserMessages.tsindex 59d83c3563..93f7db796f 100644--- a/apps/mobile/src/session/optimisticUserMessages.ts+++ b/apps/mobile/src/session/optimisticUserMessages.ts@@ -1,6 +1,14 @@import type { QueuedRemoteMessage, RemoteMessage } from './types';+import { historyViewLeaves, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';import { pendingSendBubbleText } from './pendingSendItems';+/** A raw push is not a handoff: the first history page may still predate it. */+export function confirmedHistoryUserClientIds(snapshot: HistoryViewSnapshot<RemoteMessage>): ReadonlySet<string> {+ return new Set(snapshot.ready ? historyViewLeaves(snapshot.items)+ .flatMap((item) => item.type === 'messages' ? item.messages : [])+ .filter((message) => message.role === 'user').map((message) => message.clientId) : []);+}+/** Page-local transcript slots, never persisted or sent over device-link. */export interface OptimisticUserMessage {message: RemoteMessage;@@ -59,8 +67,12 @@ export function reconcileOptimisticUserMessages(confirmedClientIds: ReadonlySet<string>,): readonly OptimisticUserMessage[] {if (current.length === 0) return current;- const echoed = new Set(messages.map((message) => message.clientId));+ const echoed = new Map(messages.map((message) => [message.clientId, message]));const remaining = current.filter(({ message }) => !confirmedClientIds.has(message.clientId)- && (activeClientIds.has(message.clientId) || echoed.has(message.clientId)));- return remaining.length === current.length ? current : remaining;+ && (activeClientIds.has(message.clientId) || echoed.has(message.clientId))).map((entry) => {+ const echo = echoed.get(entry.message.clientId);+ return echo && echo !== entry.message ? { ...entry, message: echo } : entry;+ });+ return remaining.length === current.length && remaining.every((entry, index) => entry === current[index])+ ? current : remaining;}diff --git a/apps/mobile/src/session/queueSettling.ts b/apps/mobile/src/session/queueSettling.tsindex 7899d78896..43e17e521f 100644--- a/apps/mobile/src/session/queueSettling.ts+++ b/apps/mobile/src/session/queueSettling.ts@@ -66,3 +66,12 @@ export function mergeSettlingItems<T extends { clientId: string }>(const extra = derived.filter((item) => !known.has(item.clientId));return extra.length === 0 ? settled : [...settled, ...extra];}++/** Enqueue and drain can both finish before React observes the queued frame. */+export function settleEnqueueResult<T extends { clientId: string }>(+ current: readonly T[], queued: T, accepted: boolean, pendingQueue: readonly T[],+): readonly T[] {+ if (!accepted) return current.filter((item) => item.clientId !== queued.clientId);+ if (pendingQueue.some((item) => item.clientId === queued.clientId)) return current;+ return mergeSettlingItems(current, [queued]);+}