Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 发消息后「思考中」不再出现、熄灭、再出现 (#5366)
Dash990a243f003d
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 3a45cd4100..fd09808579 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -381,6 +381,7 @@ import {import {appendOptimisticUserMessage,confirmedHistoryUserClientIds,+ repliedHistoryUserClientIds,projectOptimisticUserMessages,reconcileOptimisticUserMessages,type OptimisticUserMessage,@@ -434,6 +435,7 @@ import {import {buildOutboxItem,createOutboxClientId,+ hasActiveOutboxHandoff,outboxDisplayItem,outboxItemAttachments,recoverOutboxItemsToComposerDraft,@@ -4217,7 +4219,28 @@ export default function SessionScreen() {// Sending/queueing drives the composer immediately, but cannot reopen the loaded previous// turn before the new user message arrives. Only remote activity drives message grouping.const isMessageListStreaming = remoteSessionRunning || currentTurnStreaming;- // 活动条信号去抖:isSessionStreaming 由四个来源(sending / canStopQueue /+ // 消息正在交给被控端(已进 outbox、被控端尚未确认)也算活动:sending 在本地写入 outbox+ // 后就落下,而被控端回报运行要一次远程往返,远超下面的去抖窗口,不补这段活动条会+ // 「出现 → 熄灭 → 再出现」。只作用于活动条,不改 isSessionStreaming 的停止 / 横幅语义。+ // 只读本会话的 durable 记录(enqueue 在途即 state=sending):页面级的+ // sendingQueueClientIds 不带会话身份、也不看连接,不能拿来驱动活动条。+ const confirmedUserClientIds = useMemo(() => confirmedHistoryUserClientIds(historyView.snapshot, rawMessages),+ [historyView.snapshot, rawMessages]);+ // 已进被控端队列的消息归队列管,不再算交接。已回流进历史、且后面已有回复(turn 已跑过)+ // 的消息也不算,否则快速 turn 结束后活动条要等后台对账才熄灭。只「已确认」不排除:+ // 被控端先落库用户消息、再跑派发前钩子,这段还没有运行信号。+ const handoffSettledClientIds = useMemo(() => new Set([+ ...inputProjection.pendingQueue.map((item) => item.clientId),+ ...repliedHistoryUserClientIds(historyView.snapshot, rawMessages),+ ]), [inputProjection.pendingQueue, historyView.snapshot, rawMessages]);+ const messageHandoffActive = hasActiveOutboxHandoff(+ durableOutboxRecords,+ { deviceId, sessionId },+ outboxConnectionState,+ handoffSettledClientIds,+ );+ const composerActivitySignal = isSessionStreaming || messageHandoffActive;+ // 活动条信号去抖:composerActivitySignal 由多个来源(sending / 消息交接 / canStopQueue /// remoteSessionRunning / currentTurnStreaming)拼成,它们交接时会漏出一两帧空隙// ——实测日志里 streaming 1→0→1,活动条跟着闪一下、计时还被重置回 0s。// 上升沿立即生效(「跑起来了」要第一时间说),下降沿延后熄灭:真停了这点延迟无感,@@ -4227,14 +4250,14 @@ export default function SessionScreen() {// 直接判定粘滞态是否属于当前会话,不依赖 effect 的执行时机。const [streamingSticky, setStreamingSticky] = useState<string | null>(null);useEffect(() => {- if (isSessionStreaming) {+ if (composerActivitySignal) {setStreamingSticky(sessionId);return undefined;}const timer = setTimeout(() => setStreamingSticky(null), COMPOSER_ACTIVITY_SETTLE_MS);return () => clearTimeout(timer);- }, [isSessionStreaming, sessionId]);- const showComposerActivity = isSessionStreaming || streamingSticky === sessionId;+ }, [composerActivitySignal, sessionId]);+ const showComposerActivity = composerActivitySignal || streamingSticky === sessionId;useEffect(() => {// 计时起点跟着去抖后的信号走:否则空隙一过 startedAt 被重置,活动条从 0s 重新数。setComposerActivityStartedAt(showComposerActivity ? Date.now() : null);@@ -4253,8 +4276,6 @@ export default function SessionScreen() {),[currentSession?.createdAt, currentSession?.forkedAtMessageId, currentSession?.parentSessionId],);- const confirmedUserClientIds = useMemo(() => confirmedHistoryUserClientIds(historyView.snapshot, rawMessages),- [historyView.snapshot, rawMessages]);// inline 排队区去重集:已回流进消息流的 clientId 不再渲染排队气泡(排队气泡消失的// 同帧正式气泡已在流里,视觉上原位变实心,无跳变)。const queueHiddenClientIds = useMemo(() => {diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex 50501710d0..6801cdb83a 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -415,7 +415,7 @@ describe('mobile optimistic composer while session is not ready', () => {// 同一族的两处泄漏:活动条粘滞态跨会话、缩略图锁定跨附件变更 —— 派生状态不带身份,// 切换目标时旧值会顶着新目标(review P1/P2)。const screen = readSource(SCREEN);- expect(screen).toContain('const showComposerActivity = isSessionStreaming || streamingSticky === sessionId;');+ expect(screen).toContain('const showComposerActivity = composerActivitySignal || streamingSticky === sessionId;');const bubble = readSource('src/session/PendingSendBubble.tsx');// 上传补齐 ossRef 不改变本地图片身份;附件替换仍重置预览。diff --git a/apps/mobile/src/__tests__/sentMessageHandoff.test.ts b/apps/mobile/src/__tests__/sentMessageHandoff.test.tsindex 2e50a766ee..32e599d515 100644--- a/apps/mobile/src/__tests__/sentMessageHandoff.test.ts+++ b/apps/mobile/src/__tests__/sentMessageHandoff.test.ts@@ -1,6 +1,6 @@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 { appendOptimisticUserMessage, confirmedHistoryUserClientIds, projectOptimisticUserMessages, reconcileOptimisticUserMessages, repliedHistoryUserClientIds } from '../session/optimisticUserMessages';import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';import { buildMobileMessageRenderItems } from '../session/messageRenderModel';import { buildPendingSendItems, mergePendingSendItems } from '../session/pendingSendItems';@@ -205,4 +205,23 @@ describe('sent message handoff', () => {it.each(['hiddenClientIds', 'locallyRemovedClientIds'] as const)('does not settle an already retired item (%s)', (field) => {expect(settleEnqueueResult([], queued, true, queueInput([], { [field]: new Set(['sent']) }))).toEqual([]);});++ it('只有后面已出现消息的已确认用户行才算 turn 跑过', async () => {+ const previousReply: RemoteMessage = { ...echo, id: 'previous-reply', clientId: 'previous-reply', role: 'assistant', createdAt: '2026-09-16T23:59:10Z' };+ const reply: RemoteMessage = { ...previousReply, id: 'reply', clientId: 'reply', createdAt: '2026-09-17T00:00:10Z' };+ let history: RemoteMessage[] = [previousReply, echo];+ 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,+ });+ await view.refresh();+ // 权威历史已落库用户行、实时推送还停在上一条回复:派发前钩子期间,不算跑过。+ expect(repliedHistoryUserClientIds(view.getSnapshot(), [previousReply])).toEqual(new Set());+ // 实时推送先到回复(快速 turn),权威历史还没刷新:算跑过。+ expect(repliedHistoryUserClientIds(view.getSnapshot(), [echo, reply])).toEqual(new Set(['sent']));+ history = [previousReply, echo, reply];+ await view.refresh();+ expect(repliedHistoryUserClientIds(view.getSnapshot(), [previousReply])).toEqual(new Set(['sent']));+ });});diff --git a/apps/mobile/src/__tests__/sessionOutbox.test.ts b/apps/mobile/src/__tests__/sessionOutbox.test.tsindex 538da16960..ce03f26499 100644--- a/apps/mobile/src/__tests__/sessionOutbox.test.ts+++ b/apps/mobile/src/__tests__/sessionOutbox.test.ts@@ -4,6 +4,7 @@ import { i18n } from '@/i18n';import {buildOutboxItem,createOutboxClientId,+ hasActiveOutboxHandoff,isSafelyUnsentOutboxEnqueueError,outboxDisplayItem,outboxItemAttachments,@@ -60,6 +61,85 @@ describe('createOutboxClientId', () => {});});+describe('hasActiveOutboxHandoff', () => {+ const online = {+ relayOnline: true,+ targetAvailable: true,+ deviceUnresponsive: false,+ autoRecoveringError: false,+ syncInProgress: false,+ };+ const target = { deviceId: 'device-1', sessionId: 'session-1' };+ const none = new Set<string>();+ const record = (overrides: Partial<Parameters<typeof hasActiveOutboxHandoff>[0][number]> = {}) => ({+ deviceId: 'device-1',+ item: { sessionId: 'session-1', clientId: 'client-1' } as Parameters<typeof hasActiveOutboxHandoff>[0][number]['item'],+ state: 'queued' as const,+ ...overrides,+ });++ it('待发、enqueue 在途、被控端已收下未确认都算消息正在交接', () => {+ expect(hasActiveOutboxHandoff([record()], target, online, none)).toBe(true);+ expect(hasActiveOutboxHandoff([record({ state: 'sending' })], target, online, none)).toBe(true);+ expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true })], target, online, none)).toBe(true);+ expect(hasActiveOutboxHandoff([], target, online, none)).toBe(false);+ });++ it('只看当前设备的当前会话', () => {+ expect(hasActiveOutboxHandoff([record({ deviceId: 'device-2' })], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([+ record({ item: { sessionId: 'session-2', clientId: 'client-1' } as ReturnType<typeof record>['item'] }),+ ], target, online, none)).toBe(false);+ });++ it('断线或被控端无响应时消息只是在等重连,不算交接', () => {+ expect(hasActiveOutboxHandoff([record()], target, { ...online, relayOnline: false }, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record()], target, { ...online, targetAvailable: false }, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record()], target, { ...online, deviceUnresponsive: true }, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record()], target, { ...online, autoRecoveringError: true }, none)).toBe(false);+ });++ it('发送后的同步不打断交接', () => {+ expect(hasActiveOutboxHandoff([record()], target, { ...online, syncInProgress: true }, none)).toBe(true);+ expect(hasActiveOutboxHandoff([record()], target, { ...online, targetAvailable: null }, none)).toBe(true);+ });++ it('出错、失败、撤销中、挂起和待确认的条目不算交接', () => {+ expect(hasActiveOutboxHandoff([record({ error: '网络错误' })], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ state: 'failed' })], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ state: 'confirming' })], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ cancelRequested: true })], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ suspended: true })], target, online, none)).toBe(false);+ });++ it('未移交的记录只看会话 FIFO 队首:队首卡住时后面的消息不算交接', () => {+ const later = record({ item: { sessionId: 'session-1', clientId: 'client-2' } as ReturnType<typeof record>['item'] });+ expect(hasActiveOutboxHandoff([record({ state: 'failed' }), later], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ suspended: true }), later], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ cancelRequested: true }), later], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ state: 'confirming', error: '待确认' }), later], target, online, none)).toBe(false);+ // 已移交被控端的记录不挡队首,下一条正常推进照样算。+ expect(hasActiveOutboxHandoff([+ record({ state: 'host-owned', retrySafe: true, cancelRequested: true }),+ later,+ ], target, online, none)).toBe(true);+ });++ it('已落定、撤销中的已移交记录不算交接', () => {+ expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true, cleanupOutcome: 'accepted' })], target, online, none)).toBe(false);+ expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true, cancelRequested: true })], target, online, none)).toBe(false);+ });++ it('已进被控端队列或已回流进历史的条目不算交接', () => {+ expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true })], target, online, new Set(['client-1']))).toBe(false);+ // 历史已确认的 clientId 同样走这个集合:快速 turn 结束后不必等 outbox 对账。+ expect(hasActiveOutboxHandoff([+ record({ state: 'host-owned', retrySafe: true }),+ record({ state: 'host-owned', retrySafe: true, item: { sessionId: 'session-1', clientId: 'client-2' } as ReturnType<typeof record>['item'] }),+ ], target, online, new Set(['client-1', 'client-2']))).toBe(false);+ });+});+describe('shouldHoldOutboxDispatchForConnection', () => {const online = {relayOnline: true,diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.tsindex 0fd49165fc..6876c7c5a2 100644--- a/apps/mobile/src/session/durableOutbox.ts+++ b/apps/mobile/src/session/durableOutbox.ts@@ -59,6 +59,14 @@ export function isDurableOutboxSettled(record: DurableOutboxRecord): boolean {return record.cleanupOutcome !== undefined;}+/**+ * 已移交被控端的记录:持久投递已收下(或已落定)。会话 FIFO 只派发第一条未移交的记录,+ * 移交后的记录只做对账,不再挡后面的消息。+ */+export function isDurableOutboxHandedOff(record: Pick<DurableOutboxRecord, 'state' | 'retrySafe' | 'cleanupOutcome'>): boolean {+ return (record.state === "host-owned" && record.retrySafe === true) || record.cleanupOutcome !== undefined;+}+/** Preparation is local; only a persisted pre-enqueue proof permits offline disposal.* Legacy records without that proof must also lack all previous-send evidence.*/diff --git a/apps/mobile/src/session/durableOutboxDelivery.ts b/apps/mobile/src/session/durableOutboxDelivery.tsindex 3d451f4e82..e835600ca9 100644--- a/apps/mobile/src/session/durableOutboxDelivery.ts+++ b/apps/mobile/src/session/durableOutboxDelivery.ts@@ -2,6 +2,7 @@ import type { InputDeliveryProjection } from "@cindy/device-link";import { isExplicitRemoteNotFoundError } from "./newSessionWorktree";import {createDurableOutbox,+ isDurableOutboxHandedOff,isDurableOutboxSettled,isDurableOutboxUnsent,type DurableOutboxRecord,@@ -315,11 +316,10 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {// Session FIFO, while one unavailable computer never blocks a different task.const candidates = [...groups.values()].flatMap((group) => {- const handedOff = (r: DurableOutboxRecord) => hasDurableOwnership(r) || isDurableOutboxSettled(r);- const head = group.find((r) => !handedOff(r));+ const head = group.find((r) => !isDurableOutboxHandedOff(r));return [...(head ? [head] : []),- ...group.filter(handedOff),+ ...group.filter(isDurableOutboxHandedOff),];}).filter((r) => deps.canRun(r) && (due.get(id(r)) ?? 0) <= Date.now());diff --git a/apps/mobile/src/session/optimisticUserMessages.ts b/apps/mobile/src/session/optimisticUserMessages.tsindex bbdb960605..5f37c51eac 100644--- a/apps/mobile/src/session/optimisticUserMessages.ts+++ b/apps/mobile/src/session/optimisticUserMessages.ts@@ -2,14 +2,41 @@ import type { QueuedRemoteMessage, RemoteMessage } from './types';import { historyViewLeaves, isHistoryViewUnavailable, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';import { pendingSendBubbleText } from './pendingSendItems';+function authoritativeHistoryMessages(+ snapshot: HistoryViewSnapshot<RemoteMessage>, rawMessages: readonly RemoteMessage[],+): readonly RemoteMessage[] {+ return isHistoryViewUnavailable(snapshot.error) ? rawMessages+ : snapshot.ready ? historyViewLeaves(snapshot.items)+ .flatMap((item) => item.type === 'messages' ? item.messages : []) : [];+}+/** A raw push is not a handoff: the first history page may still predate it. */export function confirmedHistoryUserClientIds(snapshot: HistoryViewSnapshot<RemoteMessage>, rawMessages: readonly RemoteMessage[],): ReadonlySet<string> {- const authoritative = isHistoryViewUnavailable(snapshot.error) ? rawMessages- : snapshot.ready ? historyViewLeaves(snapshot.items)- .flatMap((item) => item.type === 'messages' ? item.messages : []) : [];- return new Set(authoritative.filter((message) => message.role === 'user').map((message) => message.clientId));+ return new Set(authoritativeHistoryMessages(snapshot, rawMessages)+ .filter((message) => message.role === 'user').map((message) => message.clientId));+}++/**+ * 已确认、且其后已出现任何消息(turn 已跑过)的用户消息 clientId。+ *+ * 被控端先落库用户行、再跑派发前钩子,之后才有运行信号;只「已确认」不代表已开跑。+ * 权威历史与实时推送(rawMessages)可能分叉,任一来源里这条后面已有消息就算跑过。+ */+export function repliedHistoryUserClientIds(+ snapshot: HistoryViewSnapshot<RemoteMessage>, rawMessages: readonly RemoteMessage[],+): ReadonlySet<string> {+ const confirmed = confirmedHistoryUserClientIds(snapshot, rawMessages);+ const replied = new Set<string>();+ for (const source of [authoritativeHistoryMessages(snapshot, rawMessages), rawMessages]) {+ source.forEach((message, index) => {+ if (message.role === 'user' && confirmed.has(message.clientId) && index < source.length - 1) {+ replied.add(message.clientId);+ }+ });+ }+ return replied;}/** Page-local transcript slots, never persisted or sent over device-link. */diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.tsindex fe9c57b176..4afd7cf2fb 100644--- a/apps/mobile/src/session/sessionOutbox.ts+++ b/apps/mobile/src/session/sessionOutbox.ts@@ -4,6 +4,7 @@* Recovery helpers remain for legacy direct sends and composer editing.*/import { i18n } from '@/i18n';+import { isDurableOutboxHandedOff, type DurableOutboxRecord } from '@/session/durableOutbox';import type { MobileSessionReference } from '@/session/sessionReferences';import type { RemoteSerializedAttachment } from '@/session/types';import { isInFlightDeviceLinkError } from '@cindy/device-link';@@ -52,6 +53,52 @@ export function shouldHoldOutboxDispatchForConnection(|| state.syncInProgress;}+/**+ * 本会话是否有消息正在交给被控端:已进待发、尚未被被控端历史确认的条目。+ *+ * 活动条(「思考中」)用它把「点发送 → 被控端回报运行」整段连起来:本地写入 outbox+ * 后 sending 就落下,而 enqueue 往返 + 被控端回报运行状态要一次远程往返,远超活动条+ * 的下降沿去抖,中间会熄灭一次再亮。+ *+ * 按投递的真实推进口径判断(records 须保持 store 的 FIFO 顺序):+ * - 已移交被控端、还没被历史确认的记录算交接中。settledClientIds 里的不再计入:已出现在+ * 被控端队列里的归队列管(队列暂停时不该显示「思考中」);已回流进历史的已经落定,+ * 只是 outbox 还没对账清掉。+ * - 未移交的记录只看会话 FIFO 队首——投递只派发它。队首在正常推进(待发 / enqueue+ * 在途)才算;队首出错重试 / 待确认 / 失败 / 撤销中 / 挂起时,后面的消息也走不动,+ * 不能说成「思考中」。+ * 断线 / 被控端无响应时消息只是在等重连,一律不算。syncInProgress 不算断线——发送后的+ * 同步很常见,把它算进来会在交接中途再制造一次熄灭。+ */+export function hasActiveOutboxHandoff(+ records: readonly Pick<+ DurableOutboxRecord,+ 'deviceId' | 'item' | 'state' | 'error' | 'cancelRequested' | 'suspended' | 'retrySafe' | 'cleanupOutcome'+ >[],+ target: { deviceId: string; sessionId: string },+ connection: MobileOutboxConnectionState,+ settledClientIds: ReadonlySet<string>,+): boolean {+ if (+ !connection.relayOnline+ || connection.targetAvailable === false+ || connection.deviceUnresponsive+ || connection.autoRecoveringError+ ) return false;+ const group = records.filter((record) => record.deviceId === target.deviceId+ && record.item.sessionId === target.sessionId+ && record.cleanupOutcome === undefined);+ if (group.some((record) => isDurableOutboxHandedOff(record)+ && !record.cancelRequested+ && !settledClientIds.has(record.item.clientId))) return true;+ const head = group.find((record) => !isDurableOutboxHandedOff(record));+ return !!head+ && (head.state === 'queued' || head.state === 'sending')+ && !head.error+ && !head.cancelRequested+ && !head.suspended;+}+/*** enqueue 只有在能证明请求尚未交给被控端时才可自动回 outbox。* in-flight 断线与 INVOKE_TIMEOUT 都可能是「已执行、回执丢失」,必须排除。