Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 发消息全程乐观可见,不再只读、不闪断、不换位 (#1068)
Dash8743594d6681
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex d4a4a3b5bb..e09fa8a345 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -124,6 +124,7 @@ import {import {MOBILE_MAX_ATTACHMENTS,attachmentDisplayLabel,+ mergeAttachmentsWithinLimit,} from '@/session/attachments';import {ContextSheet,@@ -139,6 +140,7 @@ import { ImageLightbox } from '@/session/ImageLightbox';import { pickWriteFields, retryPatchWhileLatest, writeGuardFields } from '@/session/swipeRowRegistry';import {dismissNewSessionCreation,+ getNewSessionCreationTask,retryNewSessionCreation,shouldBlockSessionSync,stashNewSessionDraftForEdit,@@ -208,7 +210,7 @@ import {useSessionQuotes,} from '@/session/chatQuoteStore';import { QuoteCapsule } from '@/session/QuoteCapsule';-import { formatQuotesForSend } from '@cindy/maker-shared/chat-quotes';+import { formatQuotesForSend, stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';import { confirmFullAccessChange } from '@/session/fullAccessConfirmation';@@ -226,12 +228,18 @@ import {} from '@/session/composerAttachmentInbox';import {buildQueuedTextMessage,+ buildQueueRowPresentation,createQueueEditTextState,queuedMessageHasEncodedQuotes,resolveQueueEditTextSubmission,stopOptionsForProjection,type QueueEditTextState,} from '@/session/inputProjection';+import {+ buildPendingSendItems,+ type MobilePendingSendActions,+} from '@/session/pendingSendItems';+import type { PendingSendBubbleActions } from '@/session/PendingSendBubble';import {acquireQueueEditLock,commitQueueEdit,@@ -280,6 +288,7 @@ import {recoverOutboxItemsToComposerDraft,replaceOutboxItem,type MobileOutboxItem,+ type MobileRecoverableDraftItem,} from '@/session/sessionOutbox';import {AT_RESOURCE_QUERY_DEBOUNCE_MS,@@ -448,12 +457,14 @@ import {shouldFallbackToLegacyCodexUsage,} from '@/session/sessionControls';import { buildSessionOperationLayout, composerDisabledReasonI18nKey } from '@/session/sessionOperationLayout';+import { computeVanishedQueueItems, mergeSettlingItems } from '@/session/queueSettling';import {summarizeSessionOverview,type SessionActionStripActionId,} from '@/session/sessionOverview';import {buildMobileSystemCardData,+ commandNeedsRemoteSession,mergeMobileLocalSlashCommands,parseMobileLocalSystemCommand,} from '@/session/systemCard';@@ -568,6 +579,46 @@ function isNotConnectedError(err: unknown): boolean {const ENQUEUE_RECONNECT_RETRIES = 3;const ENQUEUE_RECONNECT_BACKOFF_MS = 300;+/**+ * composer 活动条(「思考中 · 0s · N tokens」)的下降沿去抖窗口。+ *+ * 运行信号由 sending / 队列可停 / 远端 run status / turn streaming 四路拼成,交接时会+ * 漏出一两帧「都不为真」的空隙(实测新建会话日志 streaming 1→0→1),活动条会在那里+ * 闪一下、计时还被重置回 0s。真停了推迟这点时间熄灭无感,交接空隙则被吃掉。+ */+const COMPOSER_ACTIVITY_SETTLE_MS = 600;++/** 落定集合 / 基线的空值(模块级常量:引用稳定,不让 memo 每帧失效)。 */+const EMPTY_SETTLING_ITEMS: readonly QueuedRemoteMessage[] = [];+const EMPTY_SETTLING_BASELINE: {+ sessionId: string;+ queue: readonly QueuedRemoteMessage[];+ steeringSource: readonly string[];+ steeringClientIds: ReadonlySet<string>;+} = { sessionId: '', queue: [], steeringSource: [], steeringClientIds: new Set() };++/**+ * 「这个会话在被控端还不存在」——所有**需要远端会话**的入口共用的唯一判据。+ *+ * 新建乐观管线的合成会话行在 create 成功前带 `pendingLocalCreation`,此刻任何以+ * sessionId 打过去的 RPC 都会失败。三类入口都要看它(review 收敛检查点:这个语义+ * 原先只在会话设置那一处写了,slash 命令那条路漏了,于是创建窗口内发 `/context`+ * 会消费掉草稿再糊一张错误卡):+ * - 消息派发:由 outboxDispatchBlockedNow 复合(它还要求字段权威、管线已收口);+ * - 会话设置类 RPC(model / effort / fast / permission / plan);+ * - 需要远端的 slash 命令(/context 取用量、/learn 打蒸馏)。+ *+ * 行不存在也算「不存在」:那种状态下这些 RPC 同样无处可去。+ */+function isRemoteSessionMissing(row: RemoteSession | null | undefined): boolean {+ return !row || row.pendingLocalCreation === true;+}++/** 恢复进「只有一个输入框」的新建页时,气泡文本要剥掉产品私有 marker。 */+function outboxItemDraftText(item: MobileOutboxItem): string {+ return (item.quotesEncoded ? stripChatQuoteMarkerLines(item.text) : item.text).trim();+}+/** 编辑保存的降级判定:附件集合(按 id,顺序不敏感)未变时可退回 update-text。 */function attachmentIdSetsEqual(a: readonly { id: string }[] | undefined,@@ -589,8 +640,23 @@ function restoreOutboxItemsToDraft(items: readonly MobileOutboxItem[]): void {sessionItems.push(item);itemsBySession.set(item.sessionId, sessionItems);}-for (const [draftSessionId, sessionItems] of itemsBySession) {+ restoreRecoverableItemsToDraft(draftSessionId, sessionItems);+ }+}++/**+ * 把一组待发条目按给定顺序合并回某个会话的草稿。+ *+ * 显式收 sessionId(而不是从条目上读)是为了让**不属于 outbox 的消息**也能参与同一次+ * 合并:新建会话 enqueue 失败时,首条消息来自 creationTask.draft,必须排在创建期间攒下+ * 的后续消息前面,否则用户无法恢复原始顺序(重试后续会超到首条前面)。+ */+function restoreRecoverableItemsToDraft(+ draftSessionId: string,+ sessionItems: readonly MobileRecoverableDraftItem[],+): void {+ {const existingVisibleText = readComposerDraftSync(draftSessionId)?.trim() ?? '';const existingQuotes = [...getQuotes(draftSessionId)];const existingOrderedDraft = resolveOrderedQuoteDraft(@@ -733,6 +799,7 @@ export default function SessionScreen() {discardAllPendingUploads,waitForPendingUploads,claimActiveUploads,+ releaseClaimedUploads,waitForPastePlaceholdersSettled,hasPastePlaceholders,getPendingUploadCount,@@ -842,11 +909,96 @@ export default function SessionScreen() {// 后落库推送,device-link 下两者相隔可感知——此间继续渲染半透明气泡(转圈徽标),// 消息回流(clientId 进入 queueHiddenClientIds)或超时后移除,保证「原位变实」// 不闪断。用户主动删除的条目经 locallyRemoved 集合排除,不产生幽灵气泡。- const [settlingQueueItems, setSettlingQueueItems] = useState<readonly QueuedRemoteMessage[]>([]);+ // 状态本体带归属会话:同一个 SessionScreen 实例会原地从会话 A 切到 B,而清理是**被动**+ // effect(layout effect 先跑、它后跑),清理落地前 B 的首帧会照着 A 的残留画气泡 ——+ // 用户会在 B 里看到一瞬间 A 的消息内容(review P1)。带上 sessionId 后读侧一律先核身份,+ // 不匹配即视为空,时序不再影响正确性;被动清理只剩释放内存的作用。+ const [settlingState, setSettlingState] = useState<{+ sessionId: string;+ items: readonly QueuedRemoteMessage[];+ }>(() => ({ sessionId, items: [] }));+ const settlingQueueItems = settlingState.sessionId === sessionId ? settlingState.items : EMPTY_SETTLING_ITEMS;+ /** 更新本会话的落定集合;跨会话残留一律先丢掉再算(不把 A 的条目并进 B)。 */+ const setSettlingQueueItems = useCallback((+ updater: (current: readonly QueuedRemoteMessage[]) => readonly QueuedRemoteMessage[],+ ) => {+ setSettlingState((current) => {+ const base = current.sessionId === sessionId ? current.items : EMPTY_SETTLING_ITEMS;+ const next = updater(base);+ if (next === base && current.sessionId === sessionId) return current;+ return { sessionId, items: next };+ });+ }, [sessionId]);const settlingAddedAtRef = useRef<Map<string, number>>(new Map());- const prevPendingQueueRef = useRef<readonly QueuedRemoteMessage[]>([]);- const prevSteeringClientIdsRef = useRef<ReadonlySet<string>>(new Set());- const locallyRemovedQueueClientIdsRef = useRef<Set<string>>(new Set());+ /**+ * 「附件 ossRef → 发送时刻的本地预览 file://」。+ *+ * 排队气泡里的图不能等 sentAttachmentThumbStore 那条链(上传落定 → 拷进自有目录 →+ * AsyncStorage hydrate)——期间查询一律返回 null,气泡只能画空占位格。发送时手边就有+ * 预览,记下来直接用;store 仍是重开会话 / 预览失效后的后备。+ * 上限防无界:窗口本来就短(消息回流即不再需要),留 64 条覆盖极端连发。+ */+ const sentPreviewByOssRefRef = useRef<Map<string, string>>(new Map());+ const rememberSentAttachmentPreviews = useCallback((+ attachments: readonly RemoteSerializedAttachment[],+ previewOf: (attachment: RemoteSerializedAttachment) => string | null | undefined,+ ) => {+ const map = sentPreviewByOssRefRef.current;+ for (const attachment of attachments) {+ const ossRef = attachment.url ?? attachment.path;+ const preview = previewOf(attachment);+ if (!ossRef || !preview) continue;+ map.set(ossRef, preview);+ }+ while (map.size > 64) {+ const oldest = map.keys().next();+ if (oldest.done) break;+ map.delete(oldest.value);+ }+ }, []);+ // 「乐观气泡已上屏、enqueue RPC 尚未落定」的 clientId:这段窗口消息是否真的发出+ // 还没有答案(弱网可达数秒,且失败会回滚摘除气泡),徽标必须是转圈而不是「排入+ // 队尾」——后者是已确认入队的语义。成功 / 回滚 / 转失败任一落定即移除。+ const [sendingQueueClientIds, setSendingQueueClientIds] = useState<ReadonlySet<string>>(new Set());+ const markQueueItemSending = useCallback((clientId: string) => {+ setSendingQueueClientIds((current) => {+ if (current.has(clientId)) return current;+ const next = new Set(current);+ next.add(clientId);+ return next;+ });+ }, []);+ const clearQueueItemSending = useCallback((clientId: string) => {+ setSendingQueueClientIds((current) => {+ if (!current.has(clientId)) return current;+ const next = new Set(current);+ next.delete(clientId);+ return next;+ });+ }, []);+ /**+ * 落定判定的基线:上一帧的 pendingQueue 与插队标记。+ *+ * 必须是 state,不能是 ref(review P1)。render 阶段的现算(derivedSettlingItems)拿它+ * 当输入,而 useMemo 只在**列出的依赖**变化时重算——基线放 ref 时它推进不触发重算,+ * memo 就带着「上一次转移」的答案继续活着:队首被其它控制端删除 / 被 /clear 消化、+ * 消息永不回流时,10s 超时把条目从 settlingQueueItems 移除后,过期缓存又把它加回来,+ * 转圈永不停。放 state 后 memo 的依赖 = 它的全部输入,这类错误在结构上不可能再出现。+ * 存 projection 的原数组引用(不拷贝)是为了让「本帧是否已处理过」可用身份判定。+ */+ const [settlingBaselineState, setSettlingBaseline] = useState<{+ sessionId: string;+ queue: readonly QueuedRemoteMessage[];+ steeringSource: readonly string[];+ steeringClientIds: ReadonlySet<string>;+ }>(() => ({ sessionId, queue: [], steeringSource: [], steeringClientIds: new Set() }));+ // 基线同样按会话核身份:切到 B 的首帧若拿 A 的队列当基线,A 里有、B 里没有的条目会被+ // 判成「刚出队」,当场把 A 的消息画进 B(review P1)。不匹配 → 空基线 = 判不出消失。+ const settlingBaseline = settlingBaselineState.sessionId === sessionId+ ? settlingBaselineState+ : EMPTY_SETTLING_BASELINE;+ /** 用户本地主动删除的排队条目(同上:落定判定的输入,必须对 memo 可见)。 */+ const [locallyRemovedQueueClientIds, setLocallyRemovedQueueClientIds] = useState<ReadonlySet<string>>(new Set());const [pendingHistoryExpanded, setPendingHistoryExpanded] = useState(false);const [pendingInteractionActiveRequestId, setPendingInteractionActiveRequestId] = useState<string | null>(null);const [pendingPlanViewerState, setPendingPlanViewerState] = useState<MobilePlanViewerState>('half');@@ -1302,27 +1454,36 @@ export default function SessionScreen() {);// 缓存种入的会话行只是首屏骨架:字段经瘦身/截断(240 字符),不能作为发送参数// (buildQueuedTextMessage 会把 workingDir / model / permission 复制进队列请求)。- // fresh 元数据(getSession→upsertDeviceSession)到达前禁发,输入框仍可编辑存草稿- // (复用降级 composer 既有语义;codex review R15)。const cacheSeededReason = currentSession?.cacheSeeded? t('session.screen.composerSyncing'): null;- // 新建会话乐观管线在途:合成行(pendingLocalCreation)在被控端确认前禁发,- // 输入框仍可编辑存草稿(与 cacheSeeded 同一降级通道);权威 upsert 后自净解禁。+ // 新建会话乐观管线在途:合成行(pendingLocalCreation)期间会话可能还没在被控端建成,+ // 且首条 enqueue 落定前抢发的消息 sendAtMs 会早于首条、被排到它前面+ // (newSessionCreation.ts 的 sendAtMs 顺序注释)。const pendingCreationReason = currentSession?.pendingLocalCreation? t('session.screen.composerCreating'): null;+ // 会话设置类动作(model / effort / fast / permission / plan)在会话建成前不可用:+ // 它们是打到被控端会话的 RPC。cacheSeeded 不锁——那种会话在被控端是存在的,只是+ // 本地行还是瘦身缓存。硬门在 runControlAction 里,这里供按钮表达灰态。+ // 判据与命令式路径共用 isRemoteSessionMissing(见其注释):这里是渲染需要的+ // reactive 形态,send / runControlAction 用读 store 的 Now 形态。+ const sessionSettingsLocked = isRemoteSessionMissing(currentSession);+ // 这两条理由**不再**进 composer 的 readOnlyReason:共享模型会据此把整个输入框换成+ // 「只读模式」卡片,而它们表达的只是「会话参数还没就绪」——每次新建会话都必然经过,+ // 用户看到的是「刚发出消息就变只读」。改为:composer 全程正常,这期间发出的消息压进+ // 本地 outbox(转圈气泡上屏),就绪后由 pumpOutbox 按 FIFO 自动派发(sendAtMs 在+ // dispatch 时才生成,顺序天然正确)。判据见 outboxDispatchBlockedNow。const sessionOperationLayout = useMemo(() => buildSessionOperationLayout({hasCurrentSession,hasActivePendingInteraction,pendingInteractionBlocksComposer,remoteUnavailableReason,- // composer 用 composer-only reason:Lead → editable(可发消息),worker → read-only;- // 缓存种入行在 fresh 同步前同走此禁发通道。- readOnlyReason: cacheSeededReason ?? pendingCreationReason ?? composerReadOnlyReason,+ // composer 用 composer-only reason:Lead → editable(可发消息),worker → read-only。+ readOnlyReason: composerReadOnlyReason,}),- [cacheSeededReason, composerReadOnlyReason, hasActivePendingInteraction, hasCurrentSession, pendingCreationReason, pendingInteractionBlocksComposer, remoteUnavailableReason],+ [composerReadOnlyReason, hasActivePendingInteraction, hasCurrentSession, pendingInteractionBlocksComposer, remoteUnavailableReason],);useEffect(() => {if (!pendingInteractionActiveRequestId) return;@@ -1358,7 +1519,12 @@ export default function SessionScreen() {// inline 队列操作可用性:旧队列弹层由 showQueue 整体隐藏(离线/被撤销、pending// interaction 等),inline 化后气泡必须留在消息流里,故改为保留渲染、按同一规则// 禁用操作(取消/编辑/插话/重试/恢复),禁用理由沿用 composerDisabledReason。+ // 会话参数未就绪(缓存种入 / 新建在途)时队列行仍只读:取消 / 编辑 / 插队都是打到+ // 被控端队列的 RPC,会话在那边可能还不存在。composer 已按乐观语义放开,只有这些+ // 队列操作留在禁用档。const queueInlineReadOnlyReason = collaborationReadOnlyReason+ ?? cacheSeededReason+ ?? pendingCreationReason?? (sessionOperationLayout.showQueue ? null : composerDisabledReason);const showMessageHistory = sessionOperationLayout.messageHistoryMode === 'visible'|| (sessionOperationLayout.messageHistoryMode === 'collapsed' && pendingHistoryExpanded);@@ -1829,7 +1995,7 @@ export default function SessionScreen() {{renderComposerAttachmentButton()}{planModeOn ? (<PlanModeChip- disabled={!canUseComposer || controlBusy}+ disabled={!canUseComposer || controlBusy || sessionSettingsLocked}onExit={() => togglePlanMode(false)}testID="session.planModeChip"/>@@ -2059,18 +2225,28 @@ export default function SessionScreen() {extraDirBrowsePath,]);+ // 切会话时清掉上一个会话的排队交互态。+ //+ // 必须跳过首次挂载(实测 P1):React 的提交顺序是「先所有 layout effect,再所有 effect」,+ // 而 settling 的 vanish 检测是 layout effect —— 首帧它已经先记下「进入会话时队列长什么+ // 样」,这里紧接着把落定基线擦成空,首条消息被 drain 时就拿 [] 比 [],判不出+ // 「落定中」,排队气泡凭空消失只剩「正在同步」骨架(新建会话 100% 命中:进入会话页时首条+ // 消息就在队列里;打开已有会话时队列本就是空的,所以看不出来)。+ // 真正切会话才需要清:那时旧会话的队列快照对新会话没有意义。+ const resetForSessionIdRef = useRef(sessionId);useEffect(() => {+ if (resetForSessionIdRef.current === sessionId) return;+ resetForSessionIdRef.current = sessionId;setSettingsOpen(false);setQueueSelectedClientId(null);// ref 与 state 同步清:解锁已由下方 cleanup effect(旧 sessionId 闭包)在本// effect body 之前完成,这里再清 ref 是幂等的,保证两者时刻一致。queueEditingRef.current = null;setQueueEditing(null);- setSettlingQueueItems([]);+ setSettlingQueueItems(() => EMPTY_SETTLING_ITEMS);settlingAddedAtRef.current.clear();- prevPendingQueueRef.current = [];- prevSteeringClientIdsRef.current = new Set();- locallyRemovedQueueClientIdsRef.current.clear();+ setSettlingBaseline({ ...EMPTY_SETTLING_BASELINE, sessionId });+ setLocallyRemovedQueueClientIds(new Set());}, [sessionId]);// 切会话 / 卸载时收尾上一个会话的排队编辑态:cleanup 闭包持旧 sessionId,@@ -2747,6 +2923,52 @@ export default function SessionScreen() {}, [deviceId, deviceName, maker, openLink, sessionId, subscribe]);const load = useRemoteSyncTask(() => syncSession());+ /** 恢复路径里装不下的附件:中转对象回收,不留无人认领的已上传对象。 */+ const discardRecoveredAttachments = (attachments: readonly RemoteSerializedAttachment[]) => {+ for (const attachment of attachments) {+ discardMobileUploadedAttachment(attachment, { getToken: () => auth.getAccessToken() });+ }+ };++ /**+ * 把创建失败交还的附件并入 composer 托盘(enqueue-failed 的两条分支共用一条收尾)。+ *+ * 一条草稿只能带 MOBILE_MAX_ATTACHMENTS 个附件,而恢复的可能是 N 条消息的附件之和,+ * 溢出无法避免。取舍顺序:**托盘里已有的**(用户正拿着、屏幕上看得见)> 首条消息 >+ * 后续消息;溢出的回收中转对象 + 明确告知。两条铁律(review P1 收敛检查点):+ * - 不静默丢:装不下就说出来,绝不无声消失;+ * - 不删活的:discard 只会落在没进托盘的附件上,不碰用户正在编辑的东西。+ */+ const adoptRecoveredAttachments = (+ firstMessageAttachments: readonly RemoteSerializedAttachment[],+ followUps: readonly MobileOutboxItem[],+ ) => {+ const followUpAttachments = followUps.flatMap(outboxItemAttachments);+ if (firstMessageAttachments.length === 0 && followUpAttachments.length === 0) return;+ const withFirst = mergeAttachmentsWithinLimit(attachmentsRef.current, firstMessageAttachments);+ const withFollowUps = mergeAttachmentsWithinLimit(withFirst.merged, followUpAttachments);+ // 托盘缩略图:恢复的图片带上发送时刻记下的本地预览,否则回到托盘退化成无图 chip+ // (内容在、但用户看不出是哪张图)。+ const previewByAttachmentId: Record<string, string> = {};+ for (const item of followUps) {+ item.attachmentSlots.forEach((slot, index) => {+ const previewUri = item.slotMeta[index]?.previewUri;+ if (slot && previewUri) previewByAttachmentId[slot.id] = previewUri;+ });+ }+ if (Object.keys(previewByAttachmentId).length > 0) {+ // 已有映射优先:同 id 的现有预览是用户此刻正看着的那张。+ setAttachmentPreviews((current) => ({ ...previewByAttachmentId, ...current }));+ }+ attachmentsRef.current = withFollowUps.merged;+ setAttachments(withFollowUps.merged);+ const dropped = [...withFirst.dropped, ...withFollowUps.dropped];+ discardRecoveredAttachments(dropped);+ if (dropped.length > 0) {+ setAttachmentError(t('session.screen.attachmentsNotCarriedBack', { count: dropped.length }));+ }+ };+// 新建会话乐观管线的收口响应:// - running → task 移除(成功):守卫解除,补一轮完整同步(权威 meta / 交互 / projection);// - create-failed:Alert 重试面(重试 = 同 id 重跑管线,幂等安全;返回编辑 = 草稿@@ -2776,7 +2998,37 @@ export default function SessionScreen() {style: 'cancel',onPress: () => {if (!creationTask) return;- stashNewSessionDraftForEdit(creationTask);+ // 创建期间发出的后续消息必须一起带回新建页(review P1):它们此刻在 outbox 里,+ // 而下一行 dismiss 会连同合成会话行一起删掉——会话页 unmount 时 cleanup 会把它们+ // 写进那个已经不存在的会话的草稿,用户在新建页看不到、也再也找不回来。+ // 新建页只有一个首条消息输入框,所以按序拼成文本、附件按 id 去重合并后一起 stash。+ // 上传任务保不住:本页(连同 upload controller)马上就要销毁,只能取消+ // 并回收,再把「没能带回多少」告知用户(review P1:静默丢等于偷走内容)。+ const { items: followUps, cancelledUploadCount } = takeOutboxForSession(sessionId, 'cancel');+ if (followUps.length > 0) {+ const { merged, dropped } = mergeAttachmentsWithinLimit(+ creationTask.attachments,+ followUps.flatMap(outboxItemAttachments),+ );+ // 装不下的中转对象在这里回收:草稿带不走它们,留着就是没人认领的垃圾。+ discardRecoveredAttachments(dropped);+ const unrecoveredCount = dropped.length + cancelledUploadCount;+ stashNewSessionDraftForEdit(creationTask, {+ draft: {+ ...creationTask.draft,+ firstMessage: [+ creationTask.draft.firstMessage,+ ...followUps.map(outboxItemDraftText),+ ].filter(Boolean).join('\n\n'),+ },+ attachments: merged,+ notice: unrecoveredCount > 0+ ? t('session.screen.attachmentsNotCarriedBack', { count: unrecoveredCount })+ : null,+ });+ } else {+ stashNewSessionDraftForEdit(creationTask);+ }dismissNewSessionCreation(sessionId, { removeSyntheticRow: true });router.replace({ pathname: '/sessions/new', params: { deviceId, deviceName } });},@@ -2792,31 +3044,39 @@ export default function SessionScreen() {return;}if (status === 'enqueue-failed') {+ // 首条消息没发出,而创建期间用户可能已经发了后续消息(composer 全程可用)。+ //+ // 「首条回输入框 + 后续留在 outbox」是不可恢复的:重试失败的 outbox 条目会把后续+ // 消息发到首条前面,而重发首条又会追加到失败条目之后被挡住,原始顺序无论怎么操作+ // 都拼不回来(review P1)。所以两者必须一起交回 —— 全部按序合并进同一份草稿,+ // 首条在前,用户重发一次即恢复原顺序。+ // 留在本页:在途 / 失败的上传任务交还托盘,继续跑完就落进附件托盘(review P1)。+ const { items: followUps } = takeOutboxForSession(sessionId, 'release-to-tray');if (creationTask) {- // 等待窗口内 composer 可编辑(pendingLocalCreation 只禁发不禁输入),- // 用户可能已经打了下一段草稿 / 加了新附件——回填不能覆盖(codex review- // P2)。文本:空则回填,非空则把首条消息按时间序前置合并;附件:按 id- // 去重合并,回填的首条附件在前,超限截断(信息不静默丢,上限内保全)。+ // 等待窗口内用户可能已经打了下一段草稿 / 加了新附件——回填不能覆盖(codex review+ // P2)。文本:首条 + 后续消息按序前置到现有草稿之前(引用块与富文本结构由+ // recoverOutboxItemsToComposerDraft 保留);附件走 adoptRecoveredAttachments。const restoredText = creationTask.draft.firstMessage;- if (restoredText) {- setComposerDraft((current) => {- const existing = current.trim();- if (!existing) return restoredText;- if (existing === restoredText.trim()) return current;- return `${restoredText}\n\n${current}`;- });- }- if (creationTask.attachments.length > 0) {- setAttachments((current) => {- const merged = [...creationTask.attachments];- for (const attachment of current) {- if (merged.length >= MOBILE_MAX_ATTACHMENTS) break;- if (merged.some((item) => item.id === attachment.id)) continue;- merged.push(attachment);- }- return merged;- });- }+ const recoverables: MobileRecoverableDraftItem[] = [+ ...(restoredText+ ? [{+ text: restoredText,+ // draft.firstMessage 是发送文本,可能含产品引用 marker:剥离前后不同即说明有。+ quotesEncoded: stripChatQuoteMarkerLines(restoredText) !== restoredText,+ pastedTextRanges: [],+ slashCommandRanges: [],+ agentReferences: [],+ }]+ : []),+ ...followUps,+ ];+ if (recoverables.length > 0) restoreRecoverableItemsToDraft(sessionId, recoverables);+ adoptRecoveredAttachments(creationTask.attachments, followUps);+ } else if (followUps.length > 0) {+ // task 已被消费(极端竞态):后续消息仍然要回草稿,不能随 outbox 清空蒸发。+ // 附件走同一条收尾(这条分支原先只恢复文本,附件连带丢掉)。+ restoreRecoverableItemsToDraft(sessionId, followUps);+ adoptRecoveredAttachments([], followUps);}setError(creationTask?.error ?? t('session.screen.firstMessageNotSent'));dismissNewSessionCreation(sessionId);@@ -2824,6 +3084,19 @@ export default function SessionScreen() {}}, [creationTask, deviceId, deviceName, load, router, sessionId, setComposerDraft]);+ // 排队行里该显示「在途转圈」的 clientId:本页 enqueue 在途的条目,加上新建会话+ // 乐观管线仍在跑(create + 首条 enqueue 都还没确认)时的首条消息——它同样是+ // 「已上屏但没确认发出」,不能画排队 icon。+ const sendingQueueBadgeClientIds = useMemo(() => {+ const creationPendingClientId = creationTask?.status === 'running'+ ? creationTask.firstMessageClientId+ : null;+ if (!creationPendingClientId || sendingQueueClientIds.has(creationPendingClientId)) {+ return sendingQueueClientIds;+ }+ return new Set([...sendingQueueClientIds, creationPendingClientId]);+ }, [creationTask, sendingQueueClientIds]);+// 已读回执:liveActivity **签名变化且 attention=true**(会话开着时新 turn 完成翻// 未读,或 attention 一直为 true 但内容更新——新 turn 完成会经 completed→running→// completed,签名必变,仅凭 false→true 上升沿会漏)时作废同步门槛并触发一轮 load@@ -2856,15 +3129,17 @@ export default function SessionScreen() {let composerFocusFrame: number | null = null;const pending = drainComposerAttachments(sessionId);if (pending.length > 0) {- setAttachments((current) => {- const merged = [...current];- for (const attachment of pending) {- if (merged.length >= MOBILE_MAX_ATTACHMENTS) break;- if (merged.some((item) => item.id === attachment.id)) continue;- merged.push(attachment);- }- return merged;- });+ // 判据与创建失败恢复共用同一个 helper(去重 + 上限 + 溢出显式返回):同一语义+ // 分散实现过三处,其中两处会静默丢弃溢出附件(review 收敛检查点)。+ // 走 ref 而不是 setAttachments 更新器:更新器必须是纯函数,不能顺手把溢出条数+ // 写出来(ref 是本文件既有的同步真源,onUploaded 同样先写 ref 再镜像 state)。+ const { merged, dropped } = mergeAttachmentsWithinLimit(attachmentsRef.current, pending);+ attachmentsRef.current = merged;+ setAttachments(merged);+ // 中转对象的生命周期归投递方(文件浏览器把桌面端文件送进来),这里只负责不静默。+ if (dropped.length > 0) {+ setAttachmentError(t('session.common.maxAttachments', { max: MOBILE_MAX_ATTACHMENTS }));+ }}// 文件浏览器 lightbox 画笔投递的标注提交:交给标注管线烧录 + 上传进托盘// (与聊天 lightbox 直发同链路,annotated 标 / 再编辑真相一致)。@@ -3038,9 +3313,28 @@ export default function SessionScreen() {() => sending || canStopQueue || remoteSessionRunning || currentTurnStreaming,[canStopQueue, currentTurnStreaming, remoteSessionRunning, sending],);+ // 活动条信号去抖:isSessionStreaming 由四个来源(sending / canStopQueue /+ // remoteSessionRunning / currentTurnStreaming)拼成,它们交接时会漏出一两帧空隙+ // ——实测日志里 streaming 1→0→1,活动条跟着闪一下、计时还被重置回 0s。+ // 上升沿立即生效(「跑起来了」要第一时间说),下降沿延后熄灭:真停了这点延迟无感,+ // 交接空隙则被吃掉。换会话立即复位,不让上一会话的粘滞态泄漏过来。+ // 粘滞态绑定它属于哪个会话:切会话若正好落在去抖窗口内,清零要等提交后的 effect 才跑,+ // 新会话首帧会顶着上一个会话残留的「思考中」(review P2)。带上 sessionId 后,渲染阶段+ // 直接判定粘滞态是否属于当前会话,不依赖 effect 的执行时机。+ const [streamingSticky, setStreamingSticky] = useState<string | null>(null);useEffect(() => {- setComposerActivityStartedAt(isSessionStreaming ? Date.now() : null);+ if (isSessionStreaming) {+ setStreamingSticky(sessionId);+ return undefined;+ }+ const timer = setTimeout(() => setStreamingSticky(null), COMPOSER_ACTIVITY_SETTLE_MS);+ return () => clearTimeout(timer);}, [isSessionStreaming, sessionId]);+ const showComposerActivity = isSessionStreaming || streamingSticky === sessionId;+ useEffect(() => {+ // 计时起点跟着去抖后的信号走:否则空隙一过 startedAt 被重置,活动条从 0s 重新数。+ setComposerActivityStartedAt(showComposerActivity ? Date.now() : null);+ }, [showComposerActivity, sessionId]);const composerActivityStartedAtMs = remoteSessionRunStatus.startedAt ?? composerActivityStartedAt;const composerActivityTokenUsage = remoteSessionRunStatus.tokenUsage;const forkOrigin = useMemo(@@ -3069,22 +3363,38 @@ export default function SessionScreen() {// 消费,steer 按 steeringQueueClientIds 标记;两者都不沾的中段消失是远端删除// (桌面端/其它控制端取消),直接放行不渲染转圈幽灵(review P2)。队首的远端// 删除无法与派发区分,靠回流判定 + 30s 超时兜底。- useEffect(() => {- const previous = prevPendingQueueRef.current;- const previousSteering = prevSteeringClientIdsRef.current;+ //+ // useLayoutEffect 而非 useEffect(实测 P1):pendingQueue 减少与 settling 建立必须落在+ // 同一帧。用 useEffect 时两者跨帧,中间会漏出「queue=0 settling=0 msgs=0」——首条消息+ // 刚被 drain、消息还没回流,屏幕上气泡凭空消失、只剩「正在同步」骨架,新建会话每次+ // 都能看到。layout effect 在绘制前同步 flush 这次 setState,那一帧不会被用户看见。+ useLayoutEffect(() => {+ // 本帧的 projection 已经推进过基线 → 这次转移处理完了,直接返回(否则 setState 会+ // 让本 effect 依赖再次变化,自激成无限循环)。+ if (+ settlingBaseline.queue === inputProjection.pendingQueue+ && settlingBaseline.steeringSource === inputProjection.steeringQueueClientIds+ ) {+ return;+ }+ const previous = settlingBaseline.queue;+ const previousSteering = settlingBaseline.steeringClientIds;const currentIds = new Set(inputProjection.pendingQueue.map((item) => item.clientId));const currentSteering = new Set(inputProjection.steeringQueueClientIds);- prevPendingQueueRef.current = [...inputProjection.pendingQueue];- prevSteeringClientIdsRef.current = new Set(inputProjection.steeringQueueClientIds);- let vanishedPrefixEnd = 0;- while (vanishedPrefixEnd < previous.length- && !currentIds.has(previous[vanishedPrefixEnd].clientId)) {- vanishedPrefixEnd++;- }- const vanished = previous.filter((item, index) => !currentIds.has(item.clientId)- && (index < vanishedPrefixEnd || previousSteering.has(item.clientId) || currentSteering.has(item.clientId))- && !queueHiddenClientIds.has(item.clientId)- && !locallyRemovedQueueClientIdsRef.current.has(item.clientId));+ setSettlingBaseline({+ sessionId,+ queue: inputProjection.pendingQueue,+ steeringSource: inputProjection.steeringQueueClientIds,+ steeringClientIds: currentSteering,+ });+ const vanished = computeVanishedQueueItems({+ previous,+ current: inputProjection.pendingQueue,+ previousSteeringClientIds: previousSteering,+ currentSteeringClientIds: currentSteering,+ hiddenClientIds: queueHiddenClientIds,+ locallyRemovedClientIds: locallyRemovedQueueClientIds,+ });const now = Date.now();for (const item of vanished) settlingAddedAtRef.current.set(item.clientId, now);// 「条目回到队列」(派发失败被塞回队首等)的摘除必须无条件执行,不能只在有@@ -3098,18 +3408,71 @@ export default function SessionScreen() {if (added.length === 0 && kept.length === current.length) return current;return [...kept, ...added];});- }, [inputProjection.pendingQueue, inputProjection.steeringQueueClientIds, queueHiddenClientIds]);- // 2) 消息回流即移除(排队气泡消失的同帧正式气泡已在流里,原位变实);- useEffect(() => {+ }, [+ inputProjection.pendingQueue,+ inputProjection.steeringQueueClientIds,+ locallyRemovedQueueClientIds,+ queueHiddenClientIds,+ sessionId,+ setSettlingQueueItems,+ settlingBaseline,+ ]);+ // 「这一条不该再画落定气泡」的唯一判据:已回流(正式消息进流里)或用户本地删除。+ // render 过滤与 effect 摘除共用它,不再各写一份。+ const settlingRetired = useCallback(+ (clientId: string) => queueHiddenClientIds.has(clientId)+ || locallyRemovedQueueClientIds.has(clientId),+ [locallyRemovedQueueClientIds, queueHiddenClientIds],+ );+ // 2) 回流 / 本地删除即移除(排队气泡消失的同帧正式气泡已在流里,原位变实);+ // 同样用 layout effect:跨帧会让「落定转圈气泡 + 已回流正式消息」双显一帧+ // (实测日志里的 msgs=1 settling=1 那帧),视觉上是同一句话闪成两条。+ // 本地删除也在这里摘:删除标记与队列出队现在都是 state,谁先落地不确定,标记晚+ // 一帧到达时上面那个 effect 可能已经把条目记成落定中了——这里无条件复检,让顺序+ // 不再影响结果(ref 版靠同步写规避,state 版靠自愈)。+ useLayoutEffect(() => {setSettlingQueueItems((current) => {- const next = current.filter((item) => !queueHiddenClientIds.has(item.clientId));+ const next = current.filter((item) => !settlingRetired(item.clientId));if (next.length === current.length) return current;for (const item of current) {- if (queueHiddenClientIds.has(item.clientId)) settlingAddedAtRef.current.delete(item.clientId);+ if (settlingRetired(item.clientId)) settlingAddedAtRef.current.delete(item.clientId);}return next;});- }, [queueHiddenClientIds]);+ }, [setSettlingQueueItems, settlingRetired]);+ // render 阶段现算的落定项:上面那个 layout effect 的 setState 要多走一次 render 才落地+ // (RN 下不保证在绘制前 flush,实测 trace 里 queue=0 settling=0 会先亮一帧),队列减少的+ // 同一帧屏幕上就没有气泡了。这里用同一份纯判定在 render 时直接算出来补上,与 state 版+ // 按 clientId 去重。基线推进后(effect 已把这次转移落进 settlingQueueItems)它自然回到+ // 空集——依赖里列的就是它读的全部输入,不存在「缓存答的是上一次转移」的可能。+ const derivedSettlingItems = useMemo(+ () => computeVanishedQueueItems({+ previous: settlingBaseline.queue,+ current: inputProjection.pendingQueue,+ previousSteeringClientIds: settlingBaseline.steeringClientIds,+ currentSteeringClientIds: new Set(inputProjection.steeringQueueClientIds),+ hiddenClientIds: queueHiddenClientIds,+ locallyRemovedClientIds: locallyRemovedQueueClientIds,+ }),+ [+ inputProjection.pendingQueue,+ inputProjection.steeringQueueClientIds,+ locallyRemovedQueueClientIds,+ queueHiddenClientIds,+ settlingBaseline,+ ],+ );+ // state 版的落定项也在 render 阶段按「已回流」过滤:等 effect 移除会多亮一帧+ // 「落定气泡 + 正式消息」双显(实测 trace 的 msgs=1 settling=1 那帧),同一句话看着像+ // 出现了两条。渲染口径统一为「render 现算优先,effect 只负责持久化与超时兜底」。+ const settlingItemsForRender = useMemo(+ () => mergeSettlingItems(+ settlingQueueItems.filter((item) => !settlingRetired(item.clientId)),+ derivedSettlingItems,+ ),+ [derivedSettlingItems, settlingQueueItems, settlingRetired],+ );+// 3) 超时兜底:被 /clear、队首远端删除等消化而永不回流的条目清除,不留幽灵。// 正常派发的「出队→落库回流」在 device-link 上通常亚秒到数秒,10s 已是宽裕// 上界;线协议今天没有 accepted/draining 信号,队首远端删除的残余幽灵由此@@ -3127,7 +3490,7 @@ export default function SessionScreen() {}));}, SETTLE_TIMEOUT_MS + 500);return () => clearTimeout(timer);- }, [settlingQueueItems]);+ }, [setSettlingQueueItems, settlingQueueItems]);// session-tail-banner「忽略」过的错误行(本地乐观集合;持久化 dismiss 另发,老被控端// 降级本视图隐藏)。声明在 renderItems 之前——errorTailClientId 过滤要用;banner 相关// 的其余状态与 handler 在下方 queue handler 区。@@ -4108,6 +4471,17 @@ export default function SessionScreen() {pendingQueue: [...projectionBeforeSend.pendingQueue, queued],});updateOutbox((items) => items.filter((entry) => entry.clientId !== item.clientId));+ // outbox 条目的槽位预览接着给排队气泡用:交接后图不能因为换了数据源就消失。+ rememberSentAttachmentPreviews(+ outboxItemAttachments(item),+ (attachment) => {+ const slotIndex = item.attachmentSlots.findIndex((slot) => slot?.id === attachment.id);+ return slotIndex >= 0 ? item.slotMeta[slotIndex]?.previewUri : null;+ },+ );+ // outbox 气泡本来就在转圈:交接进 pendingQueue 后 enqueue 仍在途,徽标继续转圈,+ // 不要在这一帧闪成排队 icon 再回来(也不能谎报「已入队」)。+ markQueueItemSending(queued.clientId);try {// 弱网重试与写序边界同 send() 原路径(仅「保证未发出」的 NOT_CONNECTED 自动重发)。let projection: InputProjection | undefined;@@ -4146,9 +4520,35 @@ export default function SessionScreen() {failItem(formatRemoteError(err));}// applied:消息已在桌面队列,按成功继续(不回滚、不报错)。+ } finally {+ // 落定(入队确认 / 回 outbox 标失败)后收掉转圈:失败条目的气泡由 outbox 侧+ // 重新持有(它自己画错误徽标),排队行里不该留下悬空的在途标记。+ clearQueueItemSending(queued.clientId);}};+ /** 会话行的同步真源(store);命令式路径不能读可能落后一帧的 render 快照。 */+ const readSessionRowNow = () => remoteSessionStore.getSessions().find((item) => item.id === sessionId) ?? null;++ /**+ * 「会话参数还没就绪,现在不能 enqueue」——outbox 只排队不派发的判据。+ *+ * 这三种状态下消息仍然照常上屏(乐观语义,composer 不进只读档),只是派发要等:+ * - 会话行还没到:没有任何可用的发送参数;+ * - 缓存种入行:字段经瘦身 / 截断(240 字符),不能当发送参数;+ * - 新建在途 / 创建管线未收口:会话可能还没在被控端建成,且首条 enqueue 落定前+ * 抢发的消息 sendAtMs 会早于首条、被排到它前面(newSessionCreation.ts 注释)。+ *+ * 读 store 而非 render 快照:pump 是异步循环,每轮都要看当下的真相。+ */+ const outboxDispatchBlockedNow = () => {+ const row = readSessionRowNow();+ // 「会话在被控端还不存在」是子集;派发还额外要求字段权威、创建管线已收口。+ if (isRemoteSessionMissing(row)) return true;+ if (row?.cacheSeeded) return true;+ return getNewSessionCreationTask(sessionId) !== null;+ };+/** FIFO 派发循环:队首就绪(附件齐、无失败)才派发;失败条目留在队首阻塞后续保顺序。 */const pumpOutbox = async () => {if (outboxPumpBusyRef.current) return;@@ -4157,6 +4557,9 @@ export default function SessionScreen() {for (;;) {const head = outboxRef.current[0];if (!head || !outboxItemReady(head)) return;+ // 会话未就绪:条目原样留在 outbox(气泡继续转圈,不标失败),就绪时由+ // 下方的解禁 effect 重新 pump。+ if (outboxDispatchBlockedNow()) return;updateOutbox((items) => replaceOutboxItem(items, { ...head, phase: 'dispatching' }));await dispatchOutboxItem({ ...head, phase: 'dispatching' });}@@ -4207,6 +4610,108 @@ export default function SessionScreen() {const outboxDisplayItems = useMemo(() => outboxItems.map(outboxDisplayItem), [outboxItems]);+ /**+ * 取出并清空某会话的 outbox 条目(创建失败的两条收尾路径都要用)。+ *+ * 必须同步取走:调用方紧接着会 dismiss task / 删合成会话行,留在 ref 里的条目会被+ * unmount cleanup 写进一个即将消失的会话草稿里,等于丢消息。+ *+ * `uploads` 决定在途 / 失败上传任务的归宿——两条收尾路径的答案不同(review P1):+ * - `release-to-tray`:交还 composer 托盘(留在本页时的正解)。任务继续跑,落定后+ * routeUploadToOutbox 找不到归属条目、产物回落托盘;失败卡也回托盘可重试。取消+ * 重传是错的:用户已经等过一次上传,粘贴来源的本地文件此时可能已被回收,连重选+ * 都做不到。+ * - `cancel`:取消并回收中转对象,返回未能保住的条数。跨页导航(返回新建页)时+ * 上传 controller 随会话页销毁,保不住,只能取消 + 由调用方告知用户。+ */+ const takeOutboxForSession = (+ targetSessionId: string,+ uploads: 'release-to-tray' | 'cancel',+ ): { items: MobileOutboxItem[]; cancelledUploadCount: number } => {+ const taken = outboxRef.current.filter((item) => item.sessionId === targetSessionId);+ if (taken.length === 0) return { items: [], cancelledUploadCount: 0 };+ updateOutbox((items) => items.filter((item) => item.sessionId !== targetSessionId));+ const pendingLocalIds = taken.flatMap((item) => [...item.waitingIds, ...item.failedIds]);+ if (uploads === 'release-to-tray') {+ // 已就绪附件的中转对象由调用方决定是否随草稿保留,不在这里回收。+ releaseClaimedUploads(pendingLocalIds);+ return { items: taken, cancelledUploadCount: 0 };+ }+ for (const localId of pendingLocalIds) removePendingUpload(localId);+ return { items: taken, cancelledUploadCount: pendingLocalIds.length };+ };++ // 待发送气泡(排队 / 落定 / 本地 outbox)作为消息流末尾的渲染项。+ //+ // 它们过去挂在列表 footer,消息回流时要跨 footer↔data 搬家:位置从「footer 落点」跳到+ // 「列表末项」,空会话时还会被撑满高度的居中同步占位顶到屏幕中间——用户看到的就是+ // 「气泡在中间 → 消失 → 在底部重新出现」。进 data 后与正式消息同容器、同 key,回流即+ // 原地变实(见 pendingSendItems.ts)。只喂给消息列表,不进 renderItems——搜索 / 相册 /+ // diff 计数只认已落库的消息。+ const pendingSendItems = useMemo(+ () => {+ const presentationByClientId = new Map<+ string,+ { actions: MobilePendingSendActions; hint: string | null }+ >();+ inputProjection.pendingQueue.forEach((item, index) => {+ const presentation = buildQueueRowPresentation({+ busy: queueBusy,+ item,+ originalIndex: index,+ projection: inputProjection,+ queueLength: inputProjection.pendingQueue.length,+ readOnlyReason: queueInlineReadOnlyReason,+ });+ presentationByClientId.set(item.clientId, {+ actions: presentation.actions,+ hint: presentation.hint,+ });+ });+ return buildPendingSendItems({+ queue: inputProjection.pendingQueue,+ settling: settlingItemsForRender,+ outbox: outboxDisplayItems,+ hiddenClientIds: queueHiddenClientIds,+ sendingClientIds: sendingQueueBadgeClientIds,+ editingClientId: queueEditing?.clientId ?? null,+ steeringClientIds: new Set(inputProjection.steeringQueueClientIds),+ presentationByClientId,+ previewByOssRef: sentPreviewByOssRefRef.current,+ });+ },+ [+ inputProjection,+ outboxDisplayItems,+ queueBusy,+ queueEditing?.clientId,+ queueHiddenClientIds,+ queueInlineReadOnlyReason,+ sendingQueueBadgeClientIds,+ settlingItemsForRender,+ ],+ );+ const messageListItems = useMemo(+ () => (pendingSendItems.length === 0 ? renderItems : [...renderItems, ...pendingSendItems]),+ [pendingSendItems, renderItems],+ );+ // 解禁唤醒:会话参数就绪(fresh 元数据到达 / 新建管线收口)的那一帧重新 pump,把+ // 未就绪期间攒下的待发消息按 FIFO 发出去。渲染态判据与 outboxDispatchBlockedNow+ // 同构(那个读 store,供异步循环用;这个供 effect 依赖比较用)。+ // 声明位置在创建管线收口 effect 之后:enqueue-failed 那一帧要先把 outbox 条目标成+ // 失败挡住队首,再轮到这里 pump,否则后续消息会超车到首条消息前面。+ const outboxDispatchBlocked = !currentSession+ || currentSession.cacheSeeded === true+ || currentSession.pendingLocalCreation === true+ || creationTask !== null;+ useEffect(() => {+ if (outboxDispatchBlocked) return;+ void pumpOutbox();+ // pumpOutbox 是每 render 重建的普通闭包,不入依赖(入了会每帧重跑);它内部读+ // outboxRef / store 的最新真相,不依赖捕获值。+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [outboxDispatchBlocked]);+async function send(options: {draftOverride?: string;documentOverride?: ComposerDocument;@@ -4272,6 +4777,23 @@ export default function SessionScreen() {&& pendingSkillAtSend.name === parsedDesktopCommandAtSend.name? null: parsedDesktopCommandAtSend;+ // 需要远端会话的命令在会话建成前必须挡住(review P1)。+ //+ // 命令走的是下方「豁免 outbox」的原路径:/context 直接向被控端取用量、/learn 直接+ // 打蒸馏管线。合成行此刻在被控端还不存在,执行的唯一结果是把草稿消费掉、再糊一张+ // 错误卡。排队也不成立——outbox 的派发动作是「enqueue 一条消息」,命令原样入队+ // agent 只会当普通文本忽略。所以挡住 + 明说:草稿此刻还没被乐观清空(清空在下面+ // 几行),原文留在输入框,几秒后重试即可。纯本地卡不受影响(判据见+ // commandNeedsRemoteSession)。+ if (+ commandNeedsRemoteSession(earlyLocalCommand, earlyDesktopCommand)+ && isRemoteSessionMissing(readSessionRowNow())+ ) {+ setError(t('session.screen.commandWaitsForSession'));+ sendInFlightRef.current = false;+ setSending(false);+ return;+ }const sessionRefsAtSend = outboxEligible && !earlyLocalCommand && !earlyDesktopCommand? extractMobileSessionReferences(text, remoteSessionStore.getSessionDeviceId): [];@@ -4330,10 +4852,17 @@ export default function SessionScreen() {// outboxPumpBusyRef 也算「outbox 在途」:派发起点条目即移出 outbox,enqueue// 弱网重试窗内 outbox 可能为空——此时新消息若走原路径会并发 enqueue 超车// 在途消息,破坏 FIFO(review P1);计入 pump busy 让它同样进 outbox 排队。+ // 会话参数未就绪(缓存种入 / 新建在途)同样走本分支:此刻 enqueue 不可用,但消息+ // 照常上屏,由派发循环在就绪后按序发出——composer 不再为此进只读档。+ const dispatchBlockedAtSend = outboxDispatchBlockedNow();if (outboxEligible && !earlyLocalCommand && !earlyDesktopCommand- && (uploadsInFlight > 0 || outboxRef.current.length > 0 || outboxPumpBusyRef.current)) {+ && (uploadsInFlight > 0 || outboxRef.current.length > 0 || outboxPumpBusyRef.current+ || dispatchBlockedAtSend)) {try {- if (!currentSession.workingDir) {+ // workingDir 校验只对「此刻就能派发」的消息前置:dialogue 会话的工作目录由+ // 被控端在创建时分配,合成行此刻本就为空,而 dispatchOutboxItem 会在真正派发+ // 时重读 store 拿权威值并自行校验。+ if (!dispatchBlockedAtSend && !currentSession.workingDir) {setError(t('session.screen.missingWorkingDir'));restoreDraftAfterFailure();return;@@ -4669,6 +5198,14 @@ export default function SessionScreen() {sessionId: projectionBeforeSend.sessionId || sessionId,pendingQueue: [...projectionBeforeSend.pendingQueue, queued],});+ // 排队气泡的图立刻可见(先记预览,再让 projection 变化触发重算)。+ rememberSentAttachmentPreviews(+ sendAttachments,+ (attachment) => attachmentPreviews[attachment.id],+ );+ // 乐观气泡此刻还没有「已入队」这个事实:徽标先给转圈,enqueue 落定后才交给+ // 排队 icon(或随回滚一起消失)。+ markQueueItemSending(queued.clientId);setAttachments([]);attachmentsRef.current = [];// 标注再编辑真相(矢量笔迹 + 原图副本)不在乐观段清:enqueue 失败回滚恢复@@ -4737,6 +5274,10 @@ export default function SessionScreen() {}// applied:消息已在桌面队列(权威 / 推送 projection 已含该 clientId),// 按成功继续——不回滚、不报错,后续收尾(plan 恢复 / 映射清理)照常执行。+ } finally {+ // 成功、对账认定已入队、回滚 throw 三条路径都算「不再在途」:转圈必须收掉,+ // 否则回滚后集合残留、同 clientId 重发时首帧仍是转圈。+ clearQueueItemSending(queued.clientId);}if (sessionAtSend.permissionMode === 'plan') {// 一次性语义(对齐桌面 PR#494 / 产品决策):计划模式只对本条消息生效,发送后@@ -5015,7 +5556,12 @@ export default function SessionScreen() {const removed = index >= 0 ? before.pendingQueue[index] : undefined;// 用户主动删除:标记进 locallyRemoved,settling 跟踪不再把这次出队当成// "派发中"渲染幽灵气泡;回滚(删除失败)时撤销标记。- locallyRemovedQueueClientIdsRef.current.add(clientId);+ setLocallyRemovedQueueClientIds((current) => {+ if (current.has(clientId)) return current;+ const next = new Set(current);+ next.add(clientId);+ return next;+ });if (!removed) {void runQueueAction(() => maker.input.remove(sessionId, clientId));return;@@ -5026,7 +5572,12 @@ export default function SessionScreen() {pendingQueue: current.pendingQueue.filter((item) => item.clientId !== clientId),}),rollback: (current) => {- locallyRemovedQueueClientIdsRef.current.delete(clientId);+ setLocallyRemovedQueueClientIds((current) => {+ if (!current.has(clientId)) return current;+ const next = new Set(current);+ next.delete(clientId);+ return next;+ });const next = [...current.pendingQueue];next.splice(Math.min(index, next.length), 0, removed);return { ...current, pendingQueue: next };@@ -5139,6 +5690,36 @@ export default function SessionScreen() {};/** 放弃排队消息编辑:解锁 + 回收编辑期新增附件 + 恢复进入前的草稿与附件托盘。 */+ const pendingSendActions = useMemo<PendingSendBubbleActions>(+ () => ({+ busy: queueBusy,+ selectedClientId: queueSelectedClientId,+ onSelect: setQueueSelectedClientId,+ onRemove: (clientId: string) => {+ setQueueSelectedClientId(null);+ removeQueueItem(clientId);+ },+ onBeginEdit: (clientId: string) => {+ const target = remoteSessionStore.getInputProjection(sessionId).pendingQueue+ .find((entry) => entry.clientId === clientId);+ if (target) beginQueueEdit(target);+ },+ onSteer: (clientId: string) => {+ const target = remoteSessionStore.getInputProjection(sessionId).pendingQueue+ .find((entry) => entry.clientId === clientId);+ if (!target) return;+ setQueueSelectedClientId(null);+ steerQueueItem(target);+ },+ onRetryOutbox: retryOutboxItem,+ onRemoveOutbox: removeOutboxItem,+ }),+ [beginQueueEdit, queueBusy, queueSelectedClientId, removeQueueItem, removeOutboxItem, retryOutboxItem, sessionId, steerQueueItem],+ );++ // ⚠️ 临时取证(定位「气泡凭空消失」,定位完成后删):会话页实例身份 + 挂载/卸载。+ // settlingDiag 只在两次「首帧」打出 prev=0,之后再没跑过 —— 强烈指向组件被换了实例+ // (整棵树重建会清掉 settling / outbox / 落定基线等全部本地状态)。const cancelQueueEdit = useCallback(() => {const editing = queueEditingRef.current;if (!editing) return;@@ -5221,10 +5802,12 @@ export default function SessionScreen() {// 尚未落库回流的间隙):只看队列会在 settling 间隙让 banner 重现、允许对同一失败// 重复续跑(review P1)。该值**同时**是 hidden 释放信号与 resolveSessionTailBanner// 的抑制输入(continuationInFlight)——单点判定,两处各算一遍曾造成错位(第五轮)。+ // 用 render 合并后的落定集合(含本帧现算项):否则续跑项被 drain 的那一帧这里会短暂+ // 判成「不在途」,banner 闪回来一下。const tailContinuationInFlight = useMemo(() => inputProjection.pendingQueue.some(isContinuationQueueItem)- || settlingQueueItems.some(isContinuationQueueItem),- [inputProjection.pendingQueue, settlingQueueItems],+ || settlingItemsForRender.some(isContinuationQueueItem),+ [inputProjection.pendingQueue, settlingItemsForRender],);useEffect(() => {if (retryHiddenTailClientId === null) return;@@ -5336,6 +5919,13 @@ export default function SessionScreen() {opts?: { recover?: 'rollback' | 'refetch' },) => {if (controlBusy) return;+ // 新建会话在途:会话可能还没在被控端建成,setModel / setPlanMode 这类 RPC 必然+ // 失败并弹错,把「一切正常」的乐观观感打碎。静默忽略(不发 RPC、不写乐观 patch、+ // 不报错),对应入口的按钮同期也是灰的;窗口只有几秒。+ // composer 与发送不受此限:那条路径改走 outbox 排队(见 outboxDispatchBlockedNow)。+ // 判据与 send 里的命令门同源(sessionSettingsLocked = isRemoteSessionMissing);+ // 这里用 reactive 形态就够:按钮就是按这一帧的快照渲染的,点击不跨帧竞争。+ if (sessionSettingsLocked) return;setControlBusy(true);setError(null);let rollbackPatch: Partial<RemoteSession> | null = null;@@ -5384,12 +5974,17 @@ export default function SessionScreen() {} finally {setControlBusy(false);}- }, [controlBusy, currentSession, deviceId, maker, sessionId]);+ }, [controlBusy, currentSession, deviceId, maker, sessionId, sessionSettingsLocked]);const writeSessionAgentSwitchIntent = useCallback(async (nextIntent: NonNullable<RemoteSession['agentSwitchIntent']>,): Promise<boolean> => {if (!deviceId || controlBusy) return false;+ // 会话建成前不写切换意图:被控端的 switch handler 要求会话行已存在,合成行阶段+ // 一律 NOT_FOUND。这里是**全部** agent-switch 写入的唯一出口(换模型 / 换 effort /+ // 换 fast 三条路都经它),门放在这里而不是各调用点,新增入口不会漏(review P1:+ // 换模型那条路不走 runControlAction,只在那儿加锁就漏了它)。+ if (sessionSettingsLocked) return false;const seq = ++agentSwitchWriteSeqRef.current;const previousIntent = normalizeSessionAgentSwitchIntent(remoteSessionStore.getSessions().find((item) => item.id === sessionId)?.agentSwitchIntent,@@ -5448,7 +6043,7 @@ export default function SessionScreen() {} finally {if (agentSwitchWriteSeqRef.current === seq) setControlBusy(false);}- }, [controlBusy, deviceId, maker, sessionId]);+ }, [controlBusy, deviceId, maker, sessionId, sessionSettingsLocked]);// Context 面板「计划模式」开关,双路径(#494 迁移):// - 新协议(capabilities.planMode.supported):maker:set-plan-mode 开关一级 flag,@@ -5462,7 +6057,9 @@ export default function SessionScreen() {const legacyPlanModeOn = currentSession?.permissionMode === 'plan';const planModeOn = planModeCapability ? currentSession?.planModeEnabled === true : legacyPlanModeOn;const togglePlanMode = useCallback((next: boolean) => {- if (!canUseComposer || !currentSession) return;+ // sessionSettingsLocked:会话建成前不动权限档(老协议分支还会写+ // prePlanPermissionModeRef,提前 return 免得留下没生效的「进入前档位」记录)。+ if (!canUseComposer || sessionSettingsLocked || !currentSession) return;if (planModeCapability) {void runControlAction(() => maker.setPlanMode(sessionId, next), { planModeEnabled: next });return;@@ -5476,7 +6073,7 @@ export default function SessionScreen() {const remembered = prePlanPermissionModeRef.current;const restored = remembered && remembered !== 'plan' ? remembered : fallback;void runControlAction(() => maker.setPermissionMode(sessionId, restored), { permissionMode: restored });- }, [canUseComposer, currentSession, maker, planModeCapability, runControlAction, runtimeOptions, sessionId]);+ }, [canUseComposer, currentSession, maker, planModeCapability, runControlAction, runtimeOptions, sessionId, sessionSettingsLocked]);// 权限位置(设置面板下拉)不体现 plan(对齐桌面 PR#494 / Cursor):新协议下 permissionMode// 本就与 plan 正交,直接展示;仅老被控端 permissionMode='plan' 时替换为进入前的底层权限档// (无记录时回退首个非 plan 档),激活态由 composer 的 PlanModeChip 表达。@@ -6895,7 +7492,8 @@ export default function SessionScreen() {focusedRequestKey={focusedMessageRequestKey}followLatestRequestKey={messageListFollowLatestRequestKey}isSessionStreaming={isSessionStreaming}- items={renderItems}+ items={messageListItems}+ pendingSend={pendingSendActions}loadingEarlier={loadingEarlier}onCopyMessageLink={copyMessageLink}onAddMessageToComposer={canUseComposer ? addMessageToComposer : undefined}@@ -6932,30 +7530,15 @@ export default function SessionScreen() {state={tailBannerState}/>) : null}+ {/* 队列状态横幅(错误 / 凭证等待 / 停止确认 / 暂停)。待发送气泡+ 不在这里,它们是消息流里的 pending_send 项。 */}<InlineQueueSectionbusy={queueBusy}- editingClientId={queueEditing?.clientId ?? null}- hiddenClientIds={queueHiddenClientIds}- onBeginEdit={beginQueueEdit}onClearError={clearQueueError}- onRemove={(clientId) => {- setQueueSelectedClientId(null);- removeQueueItem(clientId);- }}- onRemoveOutboxItem={removeOutboxItem}onResume={resumeQueue}onRetryError={retryQueueError}- onRetryOutboxItem={retryOutboxItem}- onSelect={setQueueSelectedClientId}- onSteer={(item) => {- setQueueSelectedClientId(null);- steerQueueItem(item);- }}- outboxItems={outboxDisplayItems}projection={inputProjection}readOnlyReason={queueInlineReadOnlyReason}- selectedClientId={queueSelectedClientId}- settlingItems={settlingQueueItems}/></>)}@@ -7138,7 +7721,12 @@ export default function SessionScreen() {</View>) : (<>- {isSessionStreaming ? (+ {/* 消息区还在「正在同步」占位(新建会话第一帧 / 冷开首屏)时不谈运行状态:+ 「正在同步 + 思考中 + 0s · 0 tokens」三件事同时铺开,反倒像出错,而且+ 紧接着消息落屏时这条又要重排一次。等有内容了再显示活动条。+ 判据必须带 messageCount:syncingWhileEmpty 只要 loading 就为真,而收口后+ 还会再来几轮 load(实测日志),只看它会让已有消息的会话反复熄灭活动条。 */}+ {showComposerActivity && !(syncingWhileEmpty && messages.length === 0) ? (<Viewstyle={[styles.composerActivityFrame,@@ -7150,7 +7738,7 @@ export default function SessionScreen() {sideTaskRunning={remoteSessionRunStatus.sideTaskRunning}startedAt={composerActivityStartedAtMs}tokenUsage={composerActivityTokenUsage}- visible={isSessionStreaming}+ visible={showComposerActivity}/></View>) : null}diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex f77a41dc1b..cf59c2e4a0 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -377,28 +377,31 @@ export default function NewRemoteSessionScreen() {// create() 里 await 在途图片上传后闭包里的 attachments 已是旧值,经 ref 读最新列表。const attachmentsRef = useRef(attachments);attachmentsRef.current = attachments;+ // 相册资产 → 已上传附件 id 的映射(缩略图勾选态真相)。+ const [mediaAssetAttachments, setMediaAssetAttachments] = useState<Record<string, string>>({});+ // 待选相册资产(按选中顺序;Cursor 式两段提交,底部「加入对话」统一上传)。+ const [pendingMediaAssets, setPendingMediaAssets] = useState<ContextSheetMediaAsset[]>([]);+ // 本机图片附件的本地预览 uri(attachmentId → file://),composer 托盘缩略图 / 全图查看用。+ const [attachmentPreviews, setAttachmentPreviews] = useState<Record<string, string>>({});+ // composer 托盘里正被全屏查看的图片附件 id(null = 关闭)。+ const [composerPreviewAttachmentId, setComposerPreviewAttachmentId] = useState<string | null>(null);+ const [attachmentError, setAttachmentError] = useState<string | null>(null);// 乐观创建失败后「返回编辑」的草稿回填:会话页 stash → 跳回本页 → 挂载时 drain。- // 附件是已上传完成的引用,原样回列即可继续使用。+ // 附件是已上传完成的引用,原样回列即可继续使用;notice 是「有内容没能带回」的告知+ // (创建期间发出的消息可能超出单条上限,装不下的只能丢,但不能静默丢,review P1)。+ // 声明在 attachmentError 之后:notice 就落在附件错误行上。useEffect(() => {const stashed = drainStashedNewSessionDraft();if (!stashed) return;setDraft(stashed.draft);setAttachments([...stashed.attachments]);+ if (stashed.notice) setAttachmentError(stashed.notice);if (stashed.deviceId) {setSelectedDeviceId(stashed.deviceId);setSelectedDeviceName(stashed.deviceName || stashed.deviceId);}// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅挂载时领取一次信箱}, []);- // 相册资产 → 已上传附件 id 的映射(缩略图勾选态真相)。- const [mediaAssetAttachments, setMediaAssetAttachments] = useState<Record<string, string>>({});- // 待选相册资产(按选中顺序;Cursor 式两段提交,底部「加入对话」统一上传)。- const [pendingMediaAssets, setPendingMediaAssets] = useState<ContextSheetMediaAsset[]>([]);- // 本机图片附件的本地预览 uri(attachmentId → file://),composer 托盘缩略图 / 全图查看用。- const [attachmentPreviews, setAttachmentPreviews] = useState<Record<string, string>>({});- // composer 托盘里正被全屏查看的图片附件 id(null = 关闭)。- const [composerPreviewAttachmentId, setComposerPreviewAttachmentId] = useState<string | null>(null);- const [attachmentError, setAttachmentError] = useState<string | null>(null);// 圈点标注接线 api 的 ref 中转(同会话页):hook 实例声明在 removeAttachment// 之后,onUploaded 等回调延迟执行经 ref 读最新实例。const composerAnnotationsRef = useRef<UseComposerImageAnnotationsResult | null>(null);diff --git a/apps/mobile/src/__tests__/attachments.test.ts b/apps/mobile/src/__tests__/attachments.test.tsindex b1fc1f7a72..a80cdce313 100644--- a/apps/mobile/src/__tests__/attachments.test.ts+++ b/apps/mobile/src/__tests__/attachments.test.ts@@ -6,11 +6,14 @@ import {buildAttachmentPersistImageRefs,buildMobileRemoteFileAttachment,buildMobileUploadedAttachment,+ MOBILE_MAX_ATTACHMENTS,MOBILE_MAX_ATTACHMENT_BYTES,categorizeMobileAttachment,+ mergeAttachmentsWithinLimit,extractRemoteFileExt,} from '@/session/attachments';import { isAttachmentOssRef, parseAttachmentOssRef } from '@/session/attachmentOssRef';+import type { RemoteSerializedAttachment } from '@/session/types';const SHA256 = 'a'.repeat(64);@@ -198,3 +201,48 @@ describe('attachmentOssRef legacy 兼容', () => {expect(fresh!.path.startsWith('xdt-oss-attach://m/')).toBe(true);});});++describe('mergeAttachmentsWithinLimit', () => {+ const item = (id: string): RemoteSerializedAttachment => ({+ id,+ name: `${id}.png`,+ path: `cindy-oss-attach://key/${id}`,+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ });++ it('按 id 去重,前者优先,顺序稳定', () => {+ const result = mergeAttachmentsWithinLimit([item('a'), item('b')], [item('b'), item('c')]);+ expect(result.merged.map((a) => a.id)).toEqual(['a', 'b', 'c']);+ expect(result.dropped).toEqual([]);+ });++ it('溢出的附件进 dropped,不静默消失', () => {+ // 上限是「每条消息」的产品约束,而创建失败的恢复要把 N 条待发消息并进一条草稿:+ // 溢出不可避免,但必须交给调用方回收中转对象 + 告知用户,不能内部丢掉(review P1)。+ const preferred = Array.from({ length: MOBILE_MAX_ATTACHMENTS }, (_, i) => item(`p${i}`));+ const extra = [item('x'), item('y')];+ const result = mergeAttachmentsWithinLimit(preferred, extra);+ expect(result.merged).toHaveLength(MOBILE_MAX_ATTACHMENTS);+ expect(result.dropped.map((a) => a.id)).toEqual(['x', 'y']);+ // 一个都不许凭空消失:merged + dropped 覆盖全部输入(去重后)。+ expect(result.merged.length + result.dropped.length).toBe(preferred.length + extra.length);+ });++ it('重复 id 不占额度(先去重再判上限)', () => {+ const preferred = Array.from({ length: MOBILE_MAX_ATTACHMENTS }, (_, i) => item(`p${i}`));+ const result = mergeAttachmentsWithinLimit(preferred, [item('p0'), item('z')]);+ // p0 已在,既不重复也不算溢出;只有真正装不下的 z 进 dropped。+ expect(result.merged).toHaveLength(MOBILE_MAX_ATTACHMENTS);+ expect(result.dropped.map((a) => a.id)).toEqual(['z']);+ });++ it('preferred 自身超限时原样保留(不越权截断调用方自己的内容)', () => {+ const preferred = Array.from({ length: MOBILE_MAX_ATTACHMENTS + 3 }, (_, i) => item(`p${i}`));+ const result = mergeAttachmentsWithinLimit(preferred, []);+ expect(result.merged).toHaveLength(MOBILE_MAX_ATTACHMENTS + 3);+ expect(result.dropped).toEqual([]);+ });+});diff --git a/apps/mobile/src/__tests__/blurBackdropScrim.test.ts b/apps/mobile/src/__tests__/blurBackdropScrim.test.tsindex 080bd94750..76671a9ecd 100644--- a/apps/mobile/src/__tests__/blurBackdropScrim.test.ts+++ b/apps/mobile/src/__tests__/blurBackdropScrim.test.ts@@ -51,7 +51,9 @@ describe('BlurBackdrop scrim 双模式恒深 (用户定稿 2026-07-21)', () => {const files = ['ModelPickerSheet.tsx','SessionMenuSheet.tsx',- 'InlineQueueSection.tsx',+ // 待发送气泡的附件上传遮罩:气泡已从 InlineQueueSection(现在只剩队列状态横幅)+ // 搬进消息流渲染项 PendingSendBubble。+ 'PendingSendBubble.tsx','ContextSheetMediaViews.tsx','ComposerAttachmentTray.tsx',];diff --git a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.tsindex de2fa6a607..19751fc8a6 100644--- a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts+++ b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts@@ -47,7 +47,9 @@ describe('mobile cross-device quote wiring', () => {});it('strips private markers from queued and outbox raw-text bubbles', () => {- const source = readSource('src/session/InlineQueueSection.tsx');+ // 气泡文本的构造已从 InlineQueueSection(现在只剩队列状态横幅)搬进消息流渲染项的+ // 数据层 pendingSendItems.ts —— marker-bearing body 仍然绝不进气泡正文。+ const source = readSource('src/session/pendingSendItems.ts');expect(source).toContain('stripChatQuoteMarkerLines(item.text)');expect(source).toContain('item.chatMessage.quotesEncoded === true');expect(source).toContain('item.quotesEncoded ? stripChatQuoteMarkerLines(item.text)');diff --git a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.tsindex c6c130de6a..8da81bfe57 100644--- a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts+++ b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts@@ -642,6 +642,57 @@ describe('claim(划归乐观消息)', () => {expect(controller.claimableTasks()).toEqual([]);});+ it('unclaim 把在途任务交还托盘:继续跑、重回限额、产物回落 composer', async () => {+ // 创建失败把待发消息交还输入框时走这条路:取消重传是错的(用户已经等过一次上传,+ // 粘贴来源的本地文件此时可能已被回收,连重选都做不到,review P1)。+ const gate = gatedUpload();+ const { deps, pendingSnapshots, uploaded, discarded } = makeDeps({ upload: gate.upload });+ const controller = createMobileLocalAttachmentUploadController(deps);+ controller.enqueue([candidate('a.jpg')], { token: 't' });+ await flush();+ controller.claim(['local-attachment-upload-1']);+ expect(controller.pendingCount()).toBe(0);++ controller.unclaim(['local-attachment-upload-1']);+ // 回到托盘:重新出现在 pending 列表、重新占限额、waitForIdle 重新等它。+ expect(pendingSnapshots.at(-1)?.map((item) => item.localId)).toEqual(['local-attachment-upload-1']);+ expect(controller.pendingCount()).toBe(1);+ expect(controller.claimableTasks().map((task) => task.localId)).toEqual(['local-attachment-upload-1']);+ // 上传没有被取消:放行后照常产出,且中转对象没有被回收。+ gate.release('a.jpg');+ await flush();+ expect(uploaded).toHaveLength(1);+ expect(discarded).toEqual([]);+ });++ it('unclaim 把失败卡交还托盘(可重试),对未 claim / 未知任务是 no-op', async () => {+ const gate = gatedUpload();+ const { deps, pendingSnapshots } = makeDeps({ upload: gate.upload });+ const controller = createMobileLocalAttachmentUploadController(deps);+ controller.enqueue([candidate('a.jpg')], { token: 't' });+ await flush();+ controller.claim(['local-attachment-upload-1']);+ gate.fail('a.jpg');+ await flush();+ expect(controller.claimableTasks()).toEqual([]);++ controller.unclaim(['local-attachment-upload-1']);+ // 失败卡回到托盘,带 failed 标(渲染成可 retry / X 的卡)。+ expect(pendingSnapshots.at(-1)?.map((item) => ({ id: item.localId, failed: item.failed })))+ .toEqual([{ id: 'local-attachment-upload-1', failed: true }]);+ expect(controller.claimableTasks()).toEqual([{+ localId: 'local-attachment-upload-1',+ failed: true,+ kind: 'image',+ previewUri: 'file:///tmp/a.jpg',+ }]);++ const snapshotCount = pendingSnapshots.length;+ expect(() => controller.unclaim(['local-attachment-upload-1', 'nope'])).not.toThrow();+ // 已在托盘 / 不存在的任务不产生多余通知。+ expect(pendingSnapshots).toHaveLength(snapshotCount);+ });+it('removeAll 只丢 composer 域任务,claimed 任务照跑并回调(排队编辑退出不打断已发消息)', async () => {const gate = gatedUpload();const uploadedIds: string[] = [];diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsnew file mode 100644index 0000000000..68adef08fd--- /dev/null+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -0,0 +1,242 @@+/**+ * 会话参数未就绪(新建在途 / 缓存种入)时 composer 保持正常,发送走 outbox 排队。+ *+ * 这两种状态原先经 buildSessionOperationLayout 的 readOnlyReason 进来,共享模型据此把+ * 整个输入框换成「只读模式」卡片——每次新建会话都必然经过几秒,观感是「刚发出消息就+ * 变只读」。现在 composer 全程可用,派发由 outboxDispatchBlockedNow 挡住,就绪后自动+ * pump;顺序靠「sendAtMs 在 dispatch 时才生成」保证(见 newSessionCreation.ts 的+ * sendAtMs 注释)。+ *+ * mobile 没有组件渲染测试设施(惯例见 chatQuoteCrossDevice.test.ts),这里做源码级接线+ * 断言:门在该在的位置、失败路径不放行、设置类 RPC 仍被挡。+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++function readSource(relativePath: string): string {+ return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');+}++const SCREEN = 'app/sessions/[sessionId].tsx';++describe('mobile optimistic composer while session is not ready', () => {+ it('keeps the composer out of the read-only slot and only gates queue rows', () => {+ const source = readSource(SCREEN);++ // composer 只认真正的协作只读理由。+ expect(source).toContain(' readOnlyReason: composerReadOnlyReason,\n');+ expect(source).not.toContain('readOnlyReason: cacheSeededReason');+ // 队列行(取消 / 编辑 / 插队都是打到被控端队列的 RPC)仍然只读。+ expect(source).toContain('const queueInlineReadOnlyReason = collaborationReadOnlyReason\n ?? cacheSeededReason\n ?? pendingCreationReason');+ });++ it('blocks outbox dispatch until the session row can actually be sent with', () => {+ const source = readSource(SCREEN);++ expect(source).toContain('const outboxDispatchBlockedNow = () => {');+ // 「会话在被控端还不存在」走共用判据(见下方的入口收敛测试);派发还额外要求字段+ // 权威(cacheSeeded 行被瘦身截断过)与创建管线已收口。+ expect(source).toContain('if (isRemoteSessionMissing(row)) return true;');+ expect(source).toContain('if (row?.cacheSeeded) return true;');+ expect(source).toContain('return getNewSessionCreationTask(sessionId) !== null;');+ // pump 循环每轮都看当下真相,blocked 时留住条目(不标失败)。+ expect(source).toContain('if (outboxDispatchBlockedNow()) return;');+ // 解禁那一帧重新 pump。+ expect(source).toContain('const outboxDispatchBlocked = !currentSession');+ expect(source).toContain('if (outboxDispatchBlocked) return;\n void pumpOutbox();');+ });++ it('routes sends through the outbox while blocked and defers the workingDir check', () => {+ const source = readSource(SCREEN);++ expect(source).toContain('const dispatchBlockedAtSend = outboxDispatchBlockedNow();');+ expect(source).toContain('|| dispatchBlockedAtSend)) {');+ // dialogue 会话的 workingDir 由被控端在创建时分配,合成行此刻为空 —— 校验推迟到+ // dispatch(那时会重读 store 拿权威值),否则新建对话发消息会被误判成缺工作目录。+ expect(source).toContain('if (!dispatchBlockedAtSend && !currentSession.workingDir) {');+ });++ it('recovers the first message and the follow-ups together, in order', () => {+ // 「首条回输入框 + 后续留在 outbox」是不可恢复的:重试失败的 outbox 条目会把后续消息+ // 发到首条前面,重发首条又会追加到失败条目之后被挡住,原顺序拼不回来(review P1)。+ // 两者必须一起、按序进同一份草稿,首条在前。+ const source = readSource(SCREEN);+ const branchStart = source.indexOf("if (status === 'enqueue-failed') {");+ const branchEnd = source.indexOf('void load();', branchStart);+ const branch = source.slice(branchStart, branchEnd);++ expect(branch).toContain("takeOutboxForSession(sessionId, 'release-to-tray')");+ expect(branch).toContain('restoreRecoverableItemsToDraft(sessionId, recoverables)');+ // 首条排在后续消息之前。+ expect(branch.indexOf('text: restoredText,')).toBeLessThan(branch.indexOf('...followUps,'));+ // 取走 outbox 必须发生在 dismiss 之前:dismiss 会解禁派发门。+ expect(branch.indexOf('takeOutboxForSession'))+ .toBeLessThan(branch.indexOf('dismissNewSessionCreation(sessionId)'));+ // 附件走统一收尾;task 已被消费的竞态分支同样要恢复附件(原先只恢复了文本)。+ expect(branch).toContain('adoptRecoveredAttachments(creationTask.attachments, followUps)');+ expect(branch).toContain('adoptRecoveredAttachments([], followUps)');+ });++ it('hands in-flight uploads back to the tray instead of cancelling them', () => {+ // 留在本页时,在途 / 失败的上传任务必须交还 composer 托盘:取消重传是错的——用户已经+ // 等过一次上传,粘贴来源的本地文件此时可能已被回收,连重选都做不到(review P1)。+ const source = readSource(SCREEN);+ const fnStart = source.indexOf('const takeOutboxForSession = (');+ const fnEnd = source.indexOf('\n };', fnStart);+ const fn = source.slice(fnStart, fnEnd);+ expect(fn).toContain("uploads: 'release-to-tray' | 'cancel',");+ expect(fn).toContain('releaseClaimedUploads(pendingLocalIds);');+ // cancel 分支必须把「没能保住多少」报给调用方,不能悄悄取消。+ expect(fn).toContain('cancelledUploadCount: pendingLocalIds.length');+ });++ it('carries follow-ups back to the new-session screen when creation itself failed', () => {+ // create-failed 的「返回编辑」会连合成会话行一起删掉:不把 outbox 一并 stash,+ // unmount cleanup 会把那些消息写进一个即将消失的会话草稿,用户再也找不回(review P1)。+ const source = readSource(SCREEN);+ const backToEditStart = source.indexOf("text: t('session.screen.backToEdit')");+ const backToEditEnd = source.indexOf("text: t('session.screen.retry')", backToEditStart);+ const branch = source.slice(backToEditStart, backToEditEnd);+ // 跨页导航:upload controller 随会话页销毁,在途上传保不住,只能取消 + 告知。+ expect(branch).toContain("takeOutboxForSession(sessionId, 'cancel')");+ expect(branch.indexOf('takeOutboxForSession'))+ .toBeLessThan(branch.indexOf('dismissNewSessionCreation(sessionId, { removeSyntheticRow: true })'));+ expect(branch).toContain('outboxItemDraftText');+ // 装不下的中转对象回收 + 把「没能带回多少」随 stash 带到新建页。+ expect(branch).toContain('discardRecoveredAttachments(dropped);');+ expect(branch).toContain('const unrecoveredCount = dropped.length + cancelledUploadCount;');+ expect(branch).toContain("notice: unrecoveredCount > 0");+ });++ it('never silently drops recovered attachments, and never discards live tray ones', () => {+ // 一条草稿装不下 N 条消息的附件时,溢出不可避免;两条铁律:不静默丢(回收中转对象 ++ // 告知),不删活的(discard 只落在没进托盘的附件上,review P1 收敛检查点)。+ const source = readSource(SCREEN);+ const fnStart = source.indexOf('const adoptRecoveredAttachments = (');+ const fnEnd = source.indexOf('\n };', fnStart);+ const fn = source.slice(fnStart, fnEnd);+ // 取舍顺序:托盘已有 > 首条消息 > 后续消息。+ expect(fn).toContain('mergeAttachmentsWithinLimit(attachmentsRef.current, firstMessageAttachments)');+ expect(fn).toContain('mergeAttachmentsWithinLimit(withFirst.merged, followUpAttachments)');+ expect(fn).toContain('const dropped = [...withFirst.dropped, ...withFollowUps.dropped];');+ expect(fn).toContain('discardRecoveredAttachments(dropped);');+ expect(fn).toContain("setAttachmentError(t('session.screen.attachmentsNotCarriedBack'");+ // 判据只有一份:上限 / 去重逻辑在 attachments.ts,screen 里不再内联复制。+ expect(source).not.toContain('if (merged.length >= MOBILE_MAX_ATTACHMENTS) break;');+ });++ it('keeps every input of the settling derivation visible to its memo', () => {+ // render 阶段现算的落定项,输入必须全部出现在依赖里。基线放可变 ref 时它推进不触发+ // 重算,memo 会带着「上一次转移」的答案继续活着:队首被其它控制端删除 / 被 /clear+ // 消化时,10s 超时把条目移出 settlingQueueItems 后过期缓存又把它加回来,转圈永不停+ // (review P1)。所以基线与「本地已删」都必须是 state。+ const screen = readSource(SCREEN);+ expect(screen).toContain('const [settlingBaselineState, setSettlingBaseline] = useState<{');+ expect(screen).toContain('const [locallyRemovedQueueClientIds, setLocallyRemovedQueueClientIds]');+ expect(screen).not.toContain('prevPendingQueueRef');+ expect(screen).not.toContain('locallyRemovedQueueClientIdsRef');+ const memoStart = screen.indexOf('const derivedSettlingItems = useMemo(');+ const memoEnd = screen.indexOf('\n );', memoStart);+ const memo = screen.slice(memoStart, memoEnd);+ expect(memo).toContain('previous: settlingBaseline.queue,');+ expect(memo).toContain('locallyRemovedClientIds: locallyRemovedQueueClientIds,');+ // 依赖 ⊇ 输入。+ const deps = memo.slice(memo.indexOf('}),') + 3);+ for (const dep of ['settlingBaseline', 'locallyRemovedQueueClientIds', 'queueHiddenClientIds']) {+ expect(deps).toContain(dep);+ }+ // 自激防护:基线已是本帧 projection 时 layout effect 直接返回,否则 setState 会让+ // 自己的依赖再次变化。+ expect(screen).toContain('settlingBaseline.queue === inputProjection.pendingQueue');+ // 「不该再画」的判据只有一份,render 过滤与 effect 摘除共用;本地删除标记晚一帧到达+ // 时也能自愈(state 化后写入不再同步)。+ expect(screen).toContain('const settlingRetired = useCallback(');+ expect(screen).toContain('const next = current.filter((item) => !settlingRetired(item.clientId));');+ expect(screen).toContain('settlingQueueItems.filter((item) => !settlingRetired(item.clientId)),');+ });++ it('never renders the previous session\'s settling bubbles after an in-place switch', () => {+ // 同一个 SessionScreen 实例会原地从会话 A 切到 B,而清理是**被动** effect(layout+ // effect 先跑、它后跑):清理落地前 B 的首帧会照着 A 的基线与残留画气泡,用户会在 B 里+ // 看到一瞬间 A 的消息内容(review P1)。落定集合与基线都带归属会话,读侧先核身份,+ // 时序不再影响正确性。+ const screen = readSource(SCREEN);+ // 状态本体带 sessionId。+ expect(screen).toContain('const [settlingState, setSettlingState] = useState<{\n sessionId: string;');+ expect(screen).toContain('const [settlingBaselineState, setSettlingBaseline] = useState<{\n sessionId: string;');+ // 读侧核身份,不匹配即视为空。+ expect(screen).toContain('const settlingQueueItems = settlingState.sessionId === sessionId ? settlingState.items : EMPTY_SETTLING_ITEMS;');+ expect(screen).toContain('const settlingBaseline = settlingBaselineState.sessionId === sessionId\n ? settlingBaselineState\n : EMPTY_SETTLING_BASELINE;');+ // 写侧同样先核身份:不把 A 的条目并进 B。+ expect(screen).toContain('const base = current.sessionId === sessionId ? current.items : EMPTY_SETTLING_ITEMS;');+ // 空值是模块级常量:引用稳定,不让 memo 每帧失效。+ expect(screen).toContain('const EMPTY_SETTLING_ITEMS: readonly QueuedRemoteMessage[] = [];');+ // 写入器按 sessionId 记账,必须进各 effect 依赖,否则切会话那帧可能用旧写入器+ // 把新会话的集合覆盖掉。+ const writerDeps = screen.split('setSettlingQueueItems,').length - 1;+ expect(writerDeps).toBeGreaterThanOrEqual(3);+ });++ it('locks the agent-switch writer, not just the runControlAction callers', () => {+ // 换模型走的是 selectComposerModelRow → writeSessionAgentSwitchIntent,不经+ // runControlAction:只在后者加锁就漏了它,而被控端的 switch handler 要求会话行已存在,+ // 合成行阶段一律 NOT_FOUND(review P1)。门放在唯一出口,新增入口不会再漏。+ const screen = readSource(SCREEN);+ const fnStart = screen.indexOf('const writeSessionAgentSwitchIntent = useCallback(async (');+ expect(fnStart).toBeGreaterThan(-1);+ const fnEnd = screen.indexOf(' }, [controlBusy, deviceId, maker, sessionId', fnStart);+ expect(fnEnd).toBeGreaterThan(fnStart);+ const fn = screen.slice(fnStart, fnEnd);+ expect(fn).toContain('if (sessionSettingsLocked) return false;');+ // 锁进依赖,回调不会停留在「未锁」那一帧。+ expect(screen).toContain('}, [controlBusy, deviceId, maker, sessionId, sessionSettingsLocked]);');+ });++ it('binds sticky/locked derived state to the thing it belongs to', () => {+ // 同一族的两处泄漏:活动条粘滞态跨会话、缩略图锁定跨附件变更 —— 派生状态不带身份,+ // 切换目标时旧值会顶着新目标(review P1/P2)。+ const screen = readSource(SCREEN);+ expect(screen).toContain('const showComposerActivity = isSessionStreaming || streamingSticky === sessionId;');++ const bubble = readSource('src/session/PendingSendBubble.tsx');+ expect(bubble).toContain("const identity = `${thumb.uri ?? ''}|${thumb.ossRef ?? ''}`;");+ expect(bubble).toContain("const shown = shownRef.current?.identity === identity ? shownRef.current.uri : null;");+ expect(bubble).toContain('remoteState?.identity === identity ? remoteState.uri : null');+ });++ it('routes every remote-session-dependent entry through one judgement', () => {+ // 「会话在被控端还不存在」原先只在会话设置那一处写了,slash 命令那条路漏了:创建+ // 窗口内发 /context 会直接打 RPC,消费掉草稿再糊一张错误卡(review P1)。判据收敛+ // 成一个纯函数,三类入口共用——渲染用 reactive 形态,命令式路径读 store 同步真源。+ const source = readSource(SCREEN);++ expect(source).toContain('function isRemoteSessionMissing(row: RemoteSession | null | undefined): boolean {');+ expect(source).toContain('return !row || row.pendingLocalCreation === true;');+ // 1) 渲染:按钮灰态。+ expect(source).toContain('const sessionSettingsLocked = isRemoteSessionMissing(currentSession);');+ expect(source).toContain('disabled={!canUseComposer || controlBusy || sessionSettingsLocked}');+ // 2) 会话设置 RPC 的硬门(统一入口,覆盖全部 runControlAction 调用点)。+ expect(source).toContain('if (sessionSettingsLocked) return;\n setControlBusy(true);');+ // 3) 消息派发:复合判据,「不存在」是它的子集。+ expect(source).toContain('if (isRemoteSessionMissing(row)) return true;');+ expect(source).not.toContain('const sessionSettingsLocked = currentSession?.pendingLocalCreation === true;');+ });++ it('blocks remote-backed slash commands before the draft is consumed', () => {+ // 挡住而不是排队:outbox 的派发动作是「enqueue 一条消息」,命令原样入队 agent 只会+ // 当普通文本忽略。而且必须挡在乐观清空**之前**,否则草稿已经没了,提示再准确也+ // 救不回用户打的字(review P1)。+ const source = readSource(SCREEN);+ const gate = source.indexOf('commandNeedsRemoteSession(earlyLocalCommand, earlyDesktopCommand)');+ expect(gate).toBeGreaterThan(-1);+ const clear = source.indexOf('if (text) applyComposerDocument(documentAfterOptimisticClear);');+ expect(gate).toBeLessThan(clear);+ const branch = source.slice(gate, clear);+ expect(branch).toContain('isRemoteSessionMissing(readSessionRowNow())');+ expect(branch).toContain("setError(t('session.screen.commandWaitsForSession'));");+ // 早退必须自己解掉发送锁(这一段在 try/finally 之前)。+ expect(branch).toContain('sendInFlightRef.current = false;');+ expect(branch).toContain('setSending(false);');+ });+});diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.tsnew file mode 100644index 0000000000..56af9b5793--- /dev/null+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts@@ -0,0 +1,181 @@+/**+ * 待发送气泡 → 消息流渲染项的构造。+ *+ * 这些气泡原来挂在列表 footer,消息回流时跨 footer↔data 搬家,位置会跳(空会话时被撑满高度+ * 的居中同步占位顶到屏幕中间,实测差约 18% 屏高),用户看到「气泡在中间 → 消失 → 在底部+ * 重新出现」。改成消息流项后靠两点保证连续:key 与正式消息一致(`message-${clientId}`)、+ * 已回流的 clientId 立刻不再产出气泡(避免同一句话双显)。+ */+import { describe, expect, it } from 'vitest';+import {+ buildPendingSendItems,+ pendingSendItemKey,+ pendingSendSpins,+ type MobilePendingSendActions,+} from '@/session/pendingSendItems';+import type { MobileOutboxDisplayItem } from '@/session/sessionOutbox';+import type { QueuedRemoteMessage } from '@/session/types';++const NO_IDS: ReadonlySet<string> = new Set();+const NO_PRESENTATION: ReadonlyMap<string, { actions: MobilePendingSendActions; hint: string | null }> = new Map();++function queued(clientId: string, text = `text-${clientId}`): QueuedRemoteMessage {+ return {+ clientId,+ text,+ persistedContent: text,+ model: 'm',+ effort: '',+ permissionMode: 'ask',+ workingDir: '/tmp',+ chatMessage: {+ clientId,+ role: 'user',+ content: text,+ isStreaming: false,+ createdAt: '2026-07-30T00:00:00.000Z',+ },+ createOpts: { agentKind: 'codex', workingDir: '/tmp' },+ } as unknown as QueuedRemoteMessage;+}++function outboxItem(clientId: string, overrides: Partial<MobileOutboxDisplayItem> = {}): MobileOutboxDisplayItem {+ return {+ clientId,+ text: `outbox-${clientId}`,+ quotesEncoded: false,+ attachmentCount: 0,+ uploadedCount: 0,+ thumbnails: [],+ fileCount: 0,+ failed: false,+ errorText: null,+ ...overrides,+ };+}++function build(overrides: Partial<Parameters<typeof buildPendingSendItems>[0]> = {}) {+ return buildPendingSendItems({+ queue: [],+ settling: [],+ outbox: [],+ hiddenClientIds: NO_IDS,+ sendingClientIds: NO_IDS,+ editingClientId: null,+ steeringClientIds: NO_IDS,+ presentationByClientId: NO_PRESENTATION,+ ...overrides,+ });+}++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')] });+ expect(item.key).toBe(pendingSendItemKey('abc'));+ expect(item.key).toBe('message-abc');+ });++ it('orders settling first, queue next, local outbox last', () => {+ const items = build({+ settling: [queued('settled')],+ queue: [queued('q1'), queued('q2')],+ outbox: [outboxItem('local')],+ });+ expect(items.map((entry) => entry.clientId)).toEqual(['settled', 'q1', 'q2', 'local']);+ expect(items.map((entry) => entry.phase)).toEqual(['settling', 'queued', 'queued', 'sending']);+ });++ it('drops anything whose real message already came back (no double bubble)', () => {+ const items = build({+ settling: [queued('done')],+ queue: [queued('live')],+ hiddenClientIds: new Set(['done']),+ });+ expect(items.map((entry) => entry.clientId)).toEqual(['live']);+ });++ it('prefers the queue entry when an item is both settling and back in the queue', () => {+ const items = build({+ settling: [queued('same')],+ queue: [queued('same')],+ presentationByClientId: new Map([['same', {+ actions: {+ remove: { disabled: false, disabledReason: null },+ edit: { disabled: false, disabledReason: null },+ steer: { disabled: false, disabledReason: null },+ },+ hint: null,+ }]]),+ });+ expect(items).toHaveLength(1);+ expect(items[0].phase).toBe('queued');+ // 回到队列的条目重新可操作(取消 / 编辑 / 插队)。+ expect(items[0].actions).not.toBeNull();+ expect(items[0].queueIndex).toBe(1);+ });++ it('marks in-flight enqueue and steering as sending, editing as editing', () => {+ const items = build({+ queue: [queued('a'), queued('b'), queued('c')],+ sendingClientIds: new Set(['a']),+ steeringClientIds: new Set(['b']),+ editingClientId: 'c',+ });+ expect(items.map((entry) => entry.phase)).toEqual(['sending', 'sending', 'editing']);+ });++ it('derives outbox phases from upload progress and failure', () => {+ const items = build({+ outbox: [+ outboxItem('uploading', { attachmentCount: 2, uploadedCount: 1 }),+ outboxItem('ready', { attachmentCount: 2, uploadedCount: 2 }),+ outboxItem('broken', { failed: true, errorText: 'boom' }),+ ],+ });+ expect(items.map((entry) => entry.phase)).toEqual(['uploading', 'sending', 'failed']);+ expect(items[2].errorText).toBe('boom');+ // 失败条目不给队列操作(它还没入队),重试 / 删除走 outbox 侧动作。+ expect(items[2].actions).toBeNull();+ });++ it('never exposes queue actions for items that left the queue', () => {+ const [settling] = build({ settling: [queued('gone')] });+ expect(settling.actions).toBeNull();+ expect(settling.queueIndex).toBeNull();+ });+});++describe('pending_send 渲染接线', () => {+ it('keeps pendingSend on the renderer actions object', async () => {+ // 回归防线:MessageRenderer 的 actions 是显式组装的 useMemo。漏掉这一项时 props 和+ // 类型都还对(interface 上有、JSX 也传了),但 actions.pendingSend 是 undefined,渲染+ // 分支直接 null —— 气泡整个不画,乐观显示凭空消失(实测踩过)。+ const { readFileSync } = await import('node:fs');+ const { resolve: resolvePath } = await import('node:path');+ const source = readFileSync(+ resolvePath(process.cwd(), 'src/session/MessageRenderer.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const actionsStart = source.indexOf('const actions: MessageActions');+ const actionsEnd = source.indexOf('viewportLayout.contentWidth,\n ]);', actionsStart);+ const actionsBlock = source.slice(actionsStart, actionsEnd);+ expect(actionsBlock).toContain('pendingSend,');+ // 渲染分支存在,且 items 的联合类型里有这一支。+ expect(source).toContain("case 'pending_send':");+ expect(source).toContain('actions={actions.pendingSend}');+ // 粘贴时已上传到媒体总仓的图(cindy-media://blobs/…)本地没有文件,气泡要靠远端取件+ // 才有缩略图 —— 漏传 resolver 就只能画空占位格。+ expect(source).toContain('resolveRemoteMedia={actions.onResolveRemoteMedia}');+ });+});++describe('pendingSendSpins', () => {+ it('spins only while the message has not been confirmed as queued', () => {+ expect(pendingSendSpins('sending')).toBe(true);+ expect(pendingSendSpins('settling')).toBe(true);+ expect(pendingSendSpins('uploading')).toBe(true);+ expect(pendingSendSpins('queued')).toBe(false);+ expect(pendingSendSpins('editing')).toBe(false);+ expect(pendingSendSpins('failed')).toBe(false);+ });+});diff --git a/apps/mobile/src/__tests__/queueSettling.test.ts b/apps/mobile/src/__tests__/queueSettling.test.tsnew file mode 100644index 0000000000..b6e3b66364--- /dev/null+++ b/apps/mobile/src/__tests__/queueSettling.test.ts@@ -0,0 +1,90 @@+/**+ * 落定中判定的纯函数测试。+ *+ * 这份判定原来内联在会话页的 layout effect 里,只能事后 setState 补气泡——那要多走一次+ * render 才落地,队列减少的同一帧屏幕上就没有气泡了(实测 trace:queue=0 settling=0 先+ * 亮一帧,新建会话必然命中)。抽成纯函数后 render 阶段与 effect 共用同一份判据,这里锁住+ * 判据本身,防止两边漂移。+ */+import { describe, expect, it } from 'vitest';+import { computeVanishedQueueItems, mergeSettlingItems } from '@/session/queueSettling';++const NO_IDS: ReadonlySet<string> = new Set();++function item(clientId: string) {+ return { clientId };+}++function build(overrides: Partial<Parameters<typeof computeVanishedQueueItems>[0]> = {}) {+ return {+ previous: [],+ current: [],+ previousSteeringClientIds: NO_IDS,+ currentSteeringClientIds: NO_IDS,+ hiddenClientIds: NO_IDS,+ locallyRemovedClientIds: NO_IDS,+ ...overrides,+ };+}++describe('computeVanishedQueueItems', () => {+ it('treats the vanished head prefix as settling (drain 恒从队首连续消费)', () => {+ const vanished = computeVanishedQueueItems(build({+ previous: [item('a'), item('b'), item('c')],+ current: [item('c')],+ }));+ expect(vanished.map((entry) => entry.clientId)).toEqual(['a', 'b']);+ });++ it('ignores mid-queue removals (远端取消,不渲染转圈幽灵)', () => {+ const vanished = computeVanishedQueueItems(build({+ previous: [item('a'), item('b'), item('c')],+ current: [item('a'), item('c')],+ }));+ expect(vanished).toEqual([]);+ });++ it('keeps steered items even when they are not the head prefix', () => {+ const vanished = computeVanishedQueueItems(build({+ previous: [item('a'), item('b'), item('c')],+ current: [item('a'), item('c')],+ previousSteeringClientIds: new Set(['b']),+ }));+ expect(vanished.map((entry) => entry.clientId)).toEqual(['b']);+ });++ it('excludes items whose real message already landed, and locally removed ones', () => {+ expect(computeVanishedQueueItems(build({+ previous: [item('a')],+ current: [],+ hiddenClientIds: new Set(['a']),+ }))).toEqual([]);+ expect(computeVanishedQueueItems(build({+ previous: [item('a')],+ current: [],+ locallyRemovedClientIds: new Set(['a']),+ }))).toEqual([]);+ });++ it('covers the new-session case: the only queued message gets drained', () => {+ const vanished = computeVanishedQueueItems(build({+ previous: [item('first')],+ current: [],+ }));+ expect(vanished.map((entry) => entry.clientId)).toEqual(['first']);+ });+});++describe('mergeSettlingItems', () => {+ it('returns the settled list untouched when nothing was derived', () => {+ const settled = [item('a')];+ expect(mergeSettlingItems(settled, [])).toBe(settled);+ });++ it('appends only clientIds the settled list does not already carry', () => {+ const settled = [item('a')];+ expect(mergeSettlingItems(settled, [item('a')])).toBe(settled);+ expect(mergeSettlingItems(settled, [item('b')]).map((entry) => entry.clientId))+ .toEqual(['a', 'b']);+ });+});diff --git a/apps/mobile/src/__tests__/sendingQueueBadge.test.ts b/apps/mobile/src/__tests__/sendingQueueBadge.test.tsnew file mode 100644index 0000000000..a83a5cfeef--- /dev/null+++ b/apps/mobile/src/__tests__/sendingQueueBadge.test.ts@@ -0,0 +1,47 @@+/**+ * 未确认发出的消息:徽标必须是转圈,不是「排入队尾」。+ *+ * 「排入队尾 list-end」是一句事实断言(被控端已收下这条消息);enqueue RPC 在途、已出队等+ * 回流、附件上传中都还没有这个事实,弱网下这段窗口可达数秒且可能回滚。+ *+ * 气泡本身已经是消息流的渲染项(pending_send),判定集中在 pendingSendItems.ts 的纯函数里+ * ——那部分有 pendingSendItems.test.ts 覆盖行为;这里只锁「屏幕侧把在途集合喂进去」和+ * 「渲染层按 phase 转圈」这两处接线。+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++function readSource(relativePath: string): string {+ return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');+}++const SCREEN = 'app/sessions/[sessionId].tsx';++describe('mobile sending queue badge', () => {+ it('spins for every phase that has not been confirmed as queued', () => {+ const items = readSource('src/session/pendingSendItems.ts');+ expect(items).toContain("return phase === 'sending' || phase === 'settling' || phase === 'uploading';");++ const bubble = readSource('src/session/PendingSendBubble.tsx');+ // 失败优先画 ⚠,其余未确认态转圈,已确认入队才画排队 icon。+ expect(bubble).toContain('const spinning = pendingSendSpins(item.phase);');+ expect(bubble).toContain('<ActivityIndicator color={colors.textTertiary} size="small" />');+ expect(bubble).toContain('<ListEnd color={colors.textTertiary}');+ // 在途条目的无障碍播报不能说「排队中第 N 条」。+ expect(bubble).toContain("t('message.queue.sendingMessage', { text: bubbleLabel })");+ });++ it('feeds the in-flight enqueue set into the pending bubbles', () => {+ const source = readSource(SCREEN);++ expect(source).toContain('sendingClientIds: sendingQueueBadgeClientIds,');+ // 直发路径与 outbox 交接路径各 mark 一次,各自在 finally 收掉。+ expect(source.match(/markQueueItemSending\(queued\.clientId\);/g)).toHaveLength(2);+ expect(source.match(/clearQueueItemSending\(queued\.clientId\);/g)).toHaveLength(2);+ expect(source).toContain('} finally {\n // 成功、对账认定已入队、回滚 throw 三条路径都算「不再在途」');+ // 新建会话乐观管线在跑时,首条消息同样是「已上屏未确认」。+ expect(source).toContain("creationTask?.status === 'running'");+ expect(source).toContain('creationTask.firstMessageClientId');+ });+});diff --git a/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts b/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.tsindex 726574dfc2..c2eddece07 100644--- a/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts+++ b/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts@@ -100,7 +100,17 @@ describe('sentAttachmentThumbStore', () => {expect(parsed[0]?.file.includes('/')).toBe(false);});- it('非 oss 引用 / 空 sourceUri / 重复引用 / 超大文件不注册', async () => {+ it('桌面本地媒体引用(粘贴先进媒体总仓)同样留底,不必等远端取件', async () => {+ // 粘贴图片的字节会先进媒体总仓,附件 url 是 cindy-media://blobs/<指纹>,手机本地没有+ // 对应文件。原先只认 xdt-oss-attach://,这类图一律不留底 → 发出后气泡只能画空占位格。+ const mediaRef = 'cindy-media://blobs/8ae715a364e0f5ab.png';+ const { deps, copies } = makeFsDeps();+ await registerSentAttachmentThumb(mediaRef, 'file:///cache/pasted.png', deps);+ expect(copies).toHaveLength(1);+ expect(getSentAttachmentThumbUri(mediaRef)).toContain('sent-attachment-thumbs/');+ });++ it('非兜底引用 / 空 sourceUri / 重复引用 / 超大文件不注册', async () => {const { deps, copies } = makeFsDeps();await registerSentAttachmentThumb('https://example.com/a.jpg', 'file:///cache/a.jpg', deps);await registerSentAttachmentThumb(undefined, 'file:///cache/a.jpg', deps);diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.tsindex 1482a60938..4296e20fee 100644--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts@@ -80,10 +80,11 @@ describe('mobile session main layer desktop-first noise budget', () => {// composer 能力(buildSessionOperationLayout)与 header 徽标走 composer-only reason(Lead=可发消息)。expect(source).toContain('const composerReadOnlyReason = useMemo(');expect(source).toContain('sessionCollaborationComposerReadOnlyReason(currentSession)');- // 缓存种入行在 fresh 同步前经同一通道禁发(cacheSeededReason 前置,codex review R15),- // 新建会话乐观管线的合成行(pendingLocalCreation)同走该通道禁发;Lead 可发消息- // 的语义不变——fresh 元数据到达后两个 reason 均为 null。- expect(source).toContain('readOnlyReason: cacheSeededReason ?? pendingCreationReason ?? composerReadOnlyReason,');+ // 「会话参数未就绪」的两条理由(缓存种入 / 新建在途)**不再**进这个通道:它会把整个+ // 输入框换成只读卡片,而它们只表示还不能 enqueue。composer 保持可用,发送改走 outbox+ // 排队(见 optimisticSessionComposer.test.ts),这两条理由只留给队列行操作。+ expect(source).toContain(' readOnlyReason: composerReadOnlyReason,\n');+ expect(source).toContain('const queueInlineReadOnlyReason = collaborationReadOnlyReason\n ?? cacheSeededReason\n ?? pendingCreationReason');expect(source).toContain('readOnlyReason={composerReadOnlyReason}');// header notice:协作会话(可聊天的 Lead)显示协作标签而非"只读模式"。expect(source).toContain('const collaborationLabel = sessionCollaborationLabel(session);');diff --git a/apps/mobile/src/__tests__/subagentRender.test.ts b/apps/mobile/src/__tests__/subagentRender.test.tsindex ecfcd45689..1cf6b5e1c2 100644--- a/apps/mobile/src/__tests__/subagentRender.test.ts+++ b/apps/mobile/src/__tests__/subagentRender.test.ts@@ -85,6 +85,8 @@ describe('subagent nesting render wiring', () => {// 联合类型扩为 mobile-only(shared 类型不动)。expect(model).toContain("type: 'subagent_group';");expect(model).toContain('| MobileSubagentGroupItem');- expect(model).toContain('| MobileForkOriginItem;');+ expect(model).toContain('| MobileForkOriginItem');+ // 待发送气泡(pending_send)也是 mobile-only 的联合成员,同样不动 shared 类型。+ expect(model).toContain('| MobilePendingSendItem;');});});diff --git a/apps/mobile/src/__tests__/systemCard.test.ts b/apps/mobile/src/__tests__/systemCard.test.tsindex edcbfb81e8..1846f82165 100644--- a/apps/mobile/src/__tests__/systemCard.test.ts+++ b/apps/mobile/src/__tests__/systemCard.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest';import {+ MOBILE_LOCAL_SYSTEM_COMMANDS,buildMobileSystemCardData,+ commandNeedsRemoteSession,formatMobileSystemCard,mergeMobileLocalSlashCommands,parseMobileLocalSystemCommand,@@ -138,3 +140,29 @@ describe('formatMobileSystemCard — goal 续跑卡按原因分说法', () => {);});});++describe('commandNeedsRemoteSession', () => {+ // 新建会话的几秒窗口里 composer 全程可用(本 PR 的目的),于是用户可以在会话还没+ // 在被控端建成时发出 slash 命令。要远端的必须挡住(执行只会消费草稿再糊错误卡,+ // 而排队不成立——outbox 的派发动作是 enqueue 一条消息,命令原样入队 agent 会当+ // 普通文本忽略);纯本地卡不该挡,挡了反而破坏「一切正常」的观感。review P1。+ it('只有真正要打被控端的本地命令算(/context)', () => {+ expect(commandNeedsRemoteSession('context', null)).toBe(true);+ for (const name of ['help', 'cost', 'pwd', 'status'] as const) {+ expect(commandNeedsRemoteSession(name, null), name).toBe(false);+ }+ });++ it('desktop 命令一律算(手机端白名单只有 /learn,它就是打被控端的)', () => {+ expect(commandNeedsRemoteSession(null, { name: 'learn' })).toBe(true);+ // 同名 agent-skill 让行时 parse 会返回 null,那条路是普通消息,走 outbox。+ expect(commandNeedsRemoteSession(null, null)).toBe(false);+ });++ it('本地命令清单新增项必须显式归类(防止漏挡)', () => {+ // 这条是清单守卫:以后往 DEFAULT_LOCAL_SYSTEM_COMMANDS 里加命令时,如果它要打+ // 被控端却忘了进 MOBILE_REMOTE_BACKED_LOCAL_COMMANDS,至少这里会提醒有新成员。+ expect(MOBILE_LOCAL_SYSTEM_COMMANDS.map((command) => command.name).sort())+ .toEqual(['context', 'cost', 'help', 'pwd', 'status']);+ });+});diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex 429389c1f7..b938ccf8c9 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -38,6 +38,8 @@"backToEdit": "Back to Edit","retry": "Retry","firstMessageNotSent": "The first message wasn't sent; its content has been restored to the input box.",+ "attachmentsNotCarriedBack": "{{count}} attachment(s) couldn't be brought back — please add them again.",+ "commandWaitsForSession": "The conversation is still being created — this command needs the session to be ready. Please try again shortly.","locateMessageNotFound": "Couldn't find the message to jump to.","shareNoLocalImage": "Couldn't get the local image file","shareFailedTitle": "Share Failed",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 4cca49a5dc..1d5034c072 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -38,6 +38,8 @@"backToEdit": "編集に戻る","retry": "再試行","firstMessageNotSent": "最初のメッセージは送信されませんでした。内容は入力欄に復元されました。",+ "attachmentsNotCarriedBack": "{{count}} 件の添付は復元できませんでした。もう一度追加してください。",+ "commandWaitsForSession": "会話の作成中です。このコマンドはセッションの準備が必要なため、少し待ってから送信してください。","locateMessageNotFound": "移動先のメッセージが見つかりませんでした。","shareNoLocalImage": "ローカルの画像ファイルを取得できませんでした","shareFailedTitle": "共有に失敗しました",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 00e1f95d2e..b245d16b8a 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -38,6 +38,8 @@"backToEdit": "편집으로 돌아가기","retry": "다시 시도","firstMessageNotSent": "첫 메시지가 전송되지 않았습니다. 내용이 입력창에 복원되었습니다.",+ "attachmentsNotCarriedBack": "첨부 {{count}}개는 되돌리지 못했습니다. 다시 추가해 주세요.",+ "commandWaitsForSession": "대화를 만들고 있습니다. 이 명령은 세션이 준비된 뒤에 사용할 수 있습니다. 잠시 후 다시 보내 주세요.","locateMessageNotFound": "이동할 메시지를 찾을 수 없습니다.","shareNoLocalImage": "로컬 이미지 파일을 가져올 수 없습니다","shareFailedTitle": "공유 실패",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 96f4abe93a..1ec5b93bd4 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -38,6 +38,8 @@"backToEdit": "返回编辑","retry": "重试","firstMessageNotSent": "首条消息没有发出,内容已还原到输入框。",+ "attachmentsNotCarriedBack": "有 {{count}} 个附件没能一起带回,需要重新添加。",+ "commandWaitsForSession": "对话还在创建中,这个命令要等对话就绪后才能用,请稍后再发。","locateMessageNotFound": "未找到要定位的消息。","shareNoLocalImage": "无法获取本地图片文件","shareFailedTitle": "分享失败",diff --git a/apps/mobile/src/session/InlineQueueSection.tsx b/apps/mobile/src/session/InlineQueueSection.tsxindex e57d055f0d..e8d637ea5c 100644--- a/apps/mobile/src/session/InlineQueueSection.tsx+++ b/apps/mobile/src/session/InlineQueueSection.tsx@@ -1,22 +1,15 @@/**- * 排队消息 inline 区(消息流末尾,作为消息列表 footer 随内容滚动)。+ * 队列状态横幅(消息流末尾,作为消息列表 footer 随内容滚动)。*- * 取代旧的 SessionQueueSheet 底部弹层:排队消息以"待发送的用户气泡"形态直接出现在- * 会话流里——右对齐、与已发送气泡同款但整体半透明(不透明=已发送,半透明=排队中,- * 落定时原位变实),气泡左侧「排入队尾 list-end」徽标表示排队态(对齐 Codex 的排队- * 图标语义);顺序由排列先后表达,不标数字(不用时钟,时钟语义留给定时任务)。+ * 待发送的**气泡**不在这里 —— 它们是消息流的一等渲染项(`pending_send`,见+ * `pendingSendItems.ts` / `PendingSendBubble.tsx`)。原先气泡挂在 footer,消息回流时要跨+ * footer↔data 搬家,位置会从「footer 落点」跳到「列表末项」,空会话时还被撑满高度的居中+ * 同步占位顶到屏幕中间,用户看到的是「气泡在中间 → 消失 → 在底部重新出现」。*- * 交互契约(状态由父屏持有,本组件纯展示 + 回调):- * - 轻点气泡 → 展开/收起该条的操作行(取消 / 编辑 / 插队发送),同时只展开一条;- * - 编辑不在气泡原位改,由父屏把整条消息载入底部 composer(见 [sessionId].tsx 编辑模式),- * 编辑中的条目在这里变暗 + ✎ 徽标;- * - 队列暂停(Stop 保留队列)时组顶出现「队列已暂停 + 继续」提示条,徽标变 ⏸;- * - 队列错误 / 停止确认中沿用原 QueuePanel 的文案语义,以横幅形式出现在组顶。- *- * 去重:父屏传入已回流消息的 clientId 集合(hiddenClientIds),已落定的条目不再渲染,- * 避免「排队气泡 + 正式消息」双显(排队气泡消失的同帧正式气泡已在流里,无跳变)。+ * 留在 footer 的只有**整组队列的状态横幅**:队列错误(可重试 / 清除)、凭证切换等待、+ * 停止确认中、队列已暂停(可继续)。它们描述的是队列整体而非某一条消息,没有身份连续性+ * 问题,留在 footer 最自然。*/-import { useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import {ActivityIndicator,@@ -26,141 +19,26 @@ import {type StyleProp,type ViewStyle,} from 'react-native';-import { Image } from 'expo-image';+import type { ReactNode } from 'react';import { Text } from '@/components/AppText';-import {- AlertCircle,- ArrowUp,- ListEnd,- Paperclip,- Pause,- Pencil,- Play,- RotateCcw,- Trash2,- type LucideIcon,-} from 'lucide-react-native';+import { Pause, Play } from 'lucide-react-native';import { describeAgentAuthError } from '@/device-link/remoteStatus';-import { buildQueueRowPresentation } from '@/session/inputProjection';+import type { InputProjection } from '@/session/types';import {- getSentAttachmentThumbUri,- useSentAttachmentThumbsVersion,-} from '@/session/sentAttachmentThumbStore';-import { syntheticTriggerKind } from '@cindy/maker-shared/synthetic-trigger';-import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';-import type { MobileOutboxDisplayItem, MobileOutboxThumb } from '@/session/sessionOutbox';-import type { InputProjection, QueuedRemoteMessage } from '@/session/types';-import { iconSize, iconStroke, fontWeight, lineHeight, useTheme, useThemedStyles, type ThemeColors } from '@/theme';+ fontWeight,+ iconSize,+ iconStroke,+ lineHeight,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from '@/theme';import { radius, spacing, typeScale } from '@/theme/tokens';-import { i18n } from '@/i18n';--/** 折叠时挂载的排队行数(与旧 QueuePanel 同档),其余收进「展开剩余 N 条」。 */-const COLLAPSED_VISIBLE_ROWS = 3;--/**- * 排队气泡显示文本:合成 UI 指令行(桌面「失败后继续」等隐藏 prompt)用遮蔽标签- * 替代原文——裸英文指令不能给用户看(对齐桌面 PendingQueuePanel 的 i18n 遮蔽标签)。- */-function queueBubbleText(item: Pick<QueuedRemoteMessage, 'text' | 'chatMessage'>): string {- const visibleText = item.chatMessage.quotesEncoded === true- ? stripChatQuoteMarkerLines(item.text)- : item.text;- const kind = syntheticTriggerKind(visibleText);- if (kind === 'continue') return i18n.t('message.queue.continueSystemInstruction');- if (kind === 'generic') return i18n.t('message.queue.systemInstruction');- return visibleText;-}--/** 本地 outbox 同样不能把产品私有 marker 当正文画出来。 */-function outboxBubbleText(item: MobileOutboxDisplayItem): string {- return item.quotesEncoded ? stripChatQuoteMarkerLines(item.text) : item.text;-}--/**- * 排队 / 落定中气泡的图片缩略数据:消息 files 里的图片附件此刻仍是- * `cindy-oss-attach://` 中转引用,本地渲染靠 sentAttachmentThumbStore 的兜底映射- * (上传成功时已把实际 PUT 的文件拷进自有目录)。非图片附件走计数行。- */-function queuedAttachmentThumbs(- item: Pick<QueuedRemoteMessage, 'clientId' | 'files'>,-): { thumbs: MobileOutboxThumb[]; fileCount: number } {- const thumbs: MobileOutboxThumb[] = [];- let fileCount = 0;- (item.files ?? []).forEach((file, index) => {- if (file.category !== 'image') {- fileCount += 1;- return;- }- thumbs.push({- key: `${item.clientId}-file-${index}`,- uri: null,- ossRef: file.url ?? file.path,- uploading: false,- });- });- return { thumbs, fileCount };-}--/**- * 气泡内图片缩略条:乐观语义下图片从第一帧就以图的形态出现,不做「📎 附件行 →- * 正式消息图片」的形态跳变(规则 7 视觉连续性)。uri 缺失时按 ossRef 查- * sentAttachmentThumbStore(订阅版本号,hydrate / 注册完成后自动补图);- * 两者都拿不到时渲染 chip 底色占位格。上传中的格子压转圈遮罩。- */-function AttachmentThumbStrip({ thumbs }: { thumbs: readonly MobileOutboxThumb[] }) {- const styles = useThemedStyles(makeStyles);- const { colors } = useTheme();- useSentAttachmentThumbsVersion();- if (thumbs.length === 0) return null;- return (- <View style={styles.thumbStrip} testID="queue.inline.thumbStrip">- {thumbs.map((thumb) => {- const uri = thumb.uri ?? (thumb.ossRef ? getSentAttachmentThumbUri(thumb.ossRef) : null);- return (- <View key={thumb.key} style={styles.thumbCell}>- {uri ? (- <Image contentFit="cover" source={{ uri }} style={styles.thumbCellImage} transition={0} />- ) : null}- {thumb.uploading ? (- <View style={styles.thumbUploadingOverlay}>- <ActivityIndicator color={colors.ctaText} size="small" />- </View>- ) : null}- </View>- );- })}- </View>- );-}export interface InlineQueueSectionProps {projection: InputProjection;busy?: boolean;readOnlyReason?: string | null;- /** 展开操作行的条目;null = 全收起。 */- selectedClientId: string | null;- /** 正在底部 composer 编辑的条目(变暗 + ✎ 徽标,不可再展开操作)。 */- editingClientId: string | null;- /** 已回流进消息流的 clientId(去重不渲染)。 */- hiddenClientIds?: ReadonlySet<string>;- /**- * 落定中条目(已被桌面端 drain 出队、消息尚未回流):渲染为不可交互的半透明- * 气泡 + 转圈徽标,填补 device-link 下「出队→落库回流」的窗口,保证原位变实- * 不闪断。生命周期由屏幕侧跟踪(回流/超时移除)。- */- settlingItems?: readonly QueuedRemoteMessage[];- /**- * 本地待发条目(outbox:附件仍在上传 / enqueue 在途或失败,消息尚未真正入队):- * 渲染在排队行之后(它们是最晚发出的),转圈徽标 + 「上传中 k/N」;失败时- * 展示错误并提供重试 / 删除。生命周期由屏幕侧 outbox 状态机管理。- */- outboxItems?: readonly MobileOutboxDisplayItem[];- onSelect(clientId: string | null): void;- onSteer(item: QueuedRemoteMessage): void;- onBeginEdit(item: QueuedRemoteMessage): void;- onRemove(clientId: string): void;- onRetryOutboxItem?(clientId: string): void;- onRemoveOutboxItem?(clientId: string): void;onResume(): void;onRetryError(): void;onClearError(): void;@@ -170,17 +48,6 @@ export function InlineQueueSection({projection,busy,readOnlyReason,- selectedClientId,- editingClientId,- hiddenClientIds,- settlingItems,- outboxItems,- onSelect,- onSteer,- onBeginEdit,- onRemove,- onRetryOutboxItem,- onRemoveOutboxItem,onResume,onRetryError,onClearError,@@ -188,24 +55,14 @@ export function InlineQueueSection({const styles = useThemedStyles(makeStyles);const { colors } = useTheme();const { t } = useTranslation();- // 本区在 FlatList 的 ListFooterComponent 里,行不参与虚拟化:默认只挂前- // COLLAPSED_VISIBLE_ROWS 条(最先发送的在前),其余折叠为「展开剩余 N 条」,- // 防止排队几十条时打开会话即整段挂载导致卡顿(review P2)。展开是用户显式- // 动作,local state 即可,不复用远端 queueExpanded(面板时代的跨端状态)。- const [expanded, setExpanded] = useState(false);- const queue = projection.pendingQueue;- const visibleQueue = hiddenClientIds- ? queue.filter((item) => !hiddenClientIds.has(item.clientId))- : queue;- const settling = settlingItems ?? [];- const outbox = outboxItems ?? [];- if (visibleQueue.length === 0 && settling.length === 0 && outbox.length === 0- && !projection.queueAbortPending && !projection.error) return null;+ const hasBanner = !!projection.error+ || !!projection.credentialSwitchWait+ || projection.queueAbortPending+ || projection.queuePaused;+ if (!hasBanner) return null;const controlsDisabled = busy || !!readOnlyReason;- const visibleRows = expanded ? visibleQueue : visibleQueue.slice(0, COLLAPSED_VISIBLE_ROWS);- const hiddenRowCount = visibleQueue.length - visibleRows.length;return (<View style={styles.container} testID="queue.inline.section">@@ -262,248 +119,26 @@ export function InlineQueueSection({</QueueTouchButton></View>) : null}-- {settling.map((item) => {- const settlingThumbs = queuedAttachmentThumbs(item);- return (- <View key={`settling-${item.clientId}`} style={styles.rowWrap} testID={`queue.inline.settling.${item.clientId}`}>- <View style={styles.bubbleRow}>- <View style={styles.badge}>- <ActivityIndicator color={colors.textTertiary} size="small" />- </View>- <View style={[styles.bubble, styles.bubbleSettling]}>- {item.text ? (- <Text numberOfLines={6} style={styles.bubbleText}>{queueBubbleText(item)}</Text>- ) : null}- <AttachmentThumbStrip thumbs={settlingThumbs.thumbs} />- {settlingThumbs.fileCount > 0 ? (- <View style={styles.attachmentLine}>- <Paperclip color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />- <Text style={styles.attachmentLineText}>{t('message.queue.attachmentCount', { n: settlingThumbs.fileCount })}</Text>- </View>- ) : null}- </View>- </View>- </View>- );- })}- {visibleRows.map((item) => {- const originalIndex = queue.findIndex((candidate) => candidate.clientId === item.clientId);- const presentation = buildQueueRowPresentation({- busy,- item,- originalIndex,- projection,- queueLength: queue.length,- readOnlyReason,- });- const editing = editingClientId === item.clientId;- const selected = !editing && selectedClientId === item.clientId;- const queuedThumbs = queuedAttachmentThumbs(item);- return (- <View key={item.clientId} style={styles.rowWrap} testID={`queue.inline.row.${originalIndex + 1}`}>- <View style={styles.bubbleRow}>- <View style={styles.badge} testID={`queue.inline.badge.${originalIndex + 1}`}>- {presentation.steering ? (- <ActivityIndicator color={colors.textTertiary} size="small" />- ) : editing ? (- <Pencil color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />- ) : (- // 暂停态不换 ⏸:组顶横幅已表达暂停,逐条再换会重复;行内恒用排队 icon。- <ListEnd color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />- )}- </View>- <Pressable- accessibilityHint={presentation.hint ?? undefined}- accessibilityLabel={presentation.steering- ? t('message.queue.steeringLabel', { text: queueBubbleText(item) || t('message.queue.attachmentMessage') })- : t('message.queue.queuedMessageLabel', { index: originalIndex + 1, text: queueBubbleText(item) || t('message.queue.attachmentMessage') })}- accessibilityRole="button"- accessibilityState={{ expanded: selected, disabled: editing }}- disabled={editing}- onPress={() => onSelect(selected ? null : item.clientId)}- style={({ pressed }) => [- styles.bubble,- selected && styles.bubbleSelected,- editing && styles.bubbleEditing,- pressed && styles.pressed,- ]}- testID={`queue.inline.bubble.${originalIndex + 1}`}- >- {item.text ? (- <Text numberOfLines={selected ? undefined : 6} style={styles.bubbleText}>- {queueBubbleText(item)}- </Text>- ) : null}- <AttachmentThumbStrip thumbs={queuedThumbs.thumbs} />- {queuedThumbs.fileCount > 0 ? (- <View style={styles.attachmentLine}>- <Paperclip color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />- <Text style={styles.attachmentLineText}>{t('message.queue.attachmentCount', { n: queuedThumbs.fileCount })}</Text>- </View>- ) : null}- {editing ? (- <Text style={styles.editingHint} testID={`queue.inline.editingHint.${originalIndex + 1}`}>- {t('message.queue.editingInComposer')}- </Text>- ) : null}- </Pressable>- </View>- {selected && presentation.hint ? (- <Text style={styles.rowHint} testID={`queue.inline.rowHint.${originalIndex + 1}`}>- {presentation.hint}- </Text>- ) : null}- {selected ? (- <View style={styles.actionRow} testID={`queue.inline.actions.${originalIndex + 1}`}>- <ActionPill- busy={busy}- disabled={presentation.actions.remove.disabled}- disabledReason={presentation.actions.remove.disabledReason}- icon={Trash2}- label={t('message.queue.cancel')}- onPress={() => onRemove(item.clientId)}- testID={`queue.inline.remove.${originalIndex + 1}`}- />- <ActionPill- busy={busy}- disabled={presentation.actions.edit.disabled}- disabledReason={presentation.actions.edit.disabledReason}- icon={Pencil}- label={t('message.queue.edit')}- onPress={() => onBeginEdit(item)}- testID={`queue.inline.edit.${originalIndex + 1}`}- />- <ActionPill- busy={busy}- cta- disabled={presentation.actions.steer.disabled}- disabledReason={presentation.actions.steer.disabledReason}- icon={ArrowUp}- label={t('message.queue.steer')}- onPress={() => onSteer(item)}- testID={`queue.inline.steer.${originalIndex + 1}`}- />- </View>- ) : null}- </View>- );- })}- {hiddenRowCount > 0 || (expanded && visibleQueue.length > COLLAPSED_VISIBLE_ROWS) ? (- <View style={styles.toggleRow}>- <QueueTouchButton- accessibilityLabel={expanded ? t('message.queue.collapseQueued') : t('message.queue.expandRemainingQueued', { n: hiddenRowCount })}- onPress={() => setExpanded(!expanded)}- style={styles.togglePill}- testID="queue.inline.toggle"- >- <Text style={styles.togglePillText}>- {expanded ? t('message.queue.collapse') : t('message.queue.expandRemaining', { n: hiddenRowCount })}- </Text>- </QueueTouchButton>- </View>- ) : null}- {/* 本地待发条目(outbox):恒排在排队行之后——它们是最晚发出的消息。- 附件仍在上传时消息就已在对话里,这是「点发送即上屏」的乐观语义主体。 */}- {outbox.map((item, outboxIndex) => {- const selected = selectedClientId === item.clientId;- const uploadsPending = item.attachmentCount > 0 && item.uploadedCount < item.attachmentCount;- const visibleText = outboxBubbleText(item);- return (- <View key={item.clientId} style={styles.rowWrap} testID={`queue.inline.outbox.${outboxIndex + 1}`}>- <View style={styles.bubbleRow}>- <View style={styles.badge} testID={`queue.inline.outboxBadge.${outboxIndex + 1}`}>- {item.failed ? (- <AlertCircle color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />- ) : (- <ActivityIndicator color={colors.textTertiary} size="small" />- )}- </View>- <Pressable- accessibilityLabel={item.failed- ? t('message.queue.sendFailedMessage', { text: visibleText || t('message.queue.attachmentMessage') })- : t('message.queue.sendingMessage', { text: visibleText || t('message.queue.attachmentMessage') })}- accessibilityRole="button"- accessibilityState={{ expanded: selected }}- onPress={() => onSelect(selected ? null : item.clientId)}- style={({ pressed }) => [- styles.bubble,- selected && styles.bubbleSelected,- pressed && styles.pressed,- ]}- testID={`queue.inline.outboxBubble.${outboxIndex + 1}`}- >- {visibleText ? (- <Text numberOfLines={selected ? undefined : 6} style={styles.bubbleText}>{visibleText}</Text>- ) : null}- <AttachmentThumbStrip thumbs={item.thumbnails} />- {item.fileCount > 0 || uploadsPending ? (- <View style={styles.attachmentLine}>- <Paperclip color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />- <Text style={styles.attachmentLineText}>- {uploadsPending- ? t('message.queue.uploadingAttachments', { uploaded: item.uploadedCount, total: item.attachmentCount })- : t('message.queue.attachmentCount', { n: item.fileCount })}- </Text>- </View>- ) : null}- {item.errorText ? (- <Text style={styles.outboxErrorText} testID={`queue.inline.outboxError.${outboxIndex + 1}`}>- {item.errorText}- </Text>- ) : null}- </Pressable>- </View>- {selected ? (- <View style={styles.actionRow} testID={`queue.inline.outboxActions.${outboxIndex + 1}`}>- <ActionPill- busy={busy}- icon={Trash2}- label={t('message.queue.delete')}- onPress={() => onRemoveOutboxItem?.(item.clientId)}- testID={`queue.inline.outboxRemove.${outboxIndex + 1}`}- />- {item.failed ? (- <ActionPill- busy={busy}- cta- icon={RotateCcw}- label={t('message.queue.retry')}- onPress={() => onRetryOutboxItem?.(item.clientId)}- testID={`queue.inline.outboxRetry.${outboxIndex + 1}`}- />- ) : null}- </View>- ) : null}- </View>- );- })}</View>);}function ActionPill({busy,- cta,disabled,disabledReason,- icon: Icon,label,onPress,testID,}: {busy?: boolean;- cta?: boolean;disabled?: boolean;disabledReason?: string | null;- icon?: LucideIcon;label: string;onPress(): void;testID?: string;}) {const styles = useThemedStyles(makeStyles);- const { colors } = useTheme();- const iconColor = cta ? colors.ctaText : colors.textSecondary;return (<QueueTouchButtonaccessibilityLabel={label}@@ -511,11 +146,10 @@ function ActionPill({disabled={disabled}disabledReason={disabledReason}onPress={onPress}- style={[styles.actionPill, cta && styles.actionPillCta]}+ style={styles.actionPill}testID={testID}>- {Icon ? <Icon color={iconColor} size={iconSize.sm} strokeWidth={iconStroke.regular} /> : null}- <Text style={[styles.actionPillText, cta && styles.actionPillTextCta]}>{label}</Text>+ <Text style={styles.actionPillText}>{label}</Text></QueueTouchButton>);}@@ -587,8 +221,8 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({borderRadius: radius.pill,flexDirection: 'row',gap: 4,- minHeight: 30,justifyContent: 'center',+ minHeight: 30,paddingHorizontal: spacing.md,},resumePillText: { color: colors.ctaText, fontSize: typeScale.caption, fontWeight: fontWeight.medium },@@ -602,74 +236,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({},errorText: { color: colors.errorText, fontSize: typeScale.caption, lineHeight: lineHeight.caption },errorActions: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },- rowWrap: { alignItems: 'flex-end', gap: spacing.sm, width: '100%' },- bubbleRow: {- alignItems: 'center',- flexDirection: 'row',- gap: spacing.sm,- justifyContent: 'flex-end',- width: '100%',- },- badge: { alignItems: 'center', flexDirection: 'row' },- // 排队气泡:与已发送用户气泡同款(surfaceElevated + borderStrong)但整体半透明——- // "这就是你的消息,只是还没生效";落定时原位变为完全不透明,过渡自然无跳变。- // 顺序由排列先后表达,不标数字。- bubble: {- backgroundColor: colors.surfaceElevated,- borderColor: colors.borderStrong,- borderRadius: radius.container,- borderWidth: StyleSheet.hairlineWidth,- gap: spacing.xs,- maxWidth: '86%',- opacity: 0.62,- padding: spacing.md,- },- bubbleSelected: {- borderColor: colors.textSecondary,- opacity: 1,- },- bubbleEditing: { opacity: 0.38 },- // 落定中:即将变实,透明度介于排队(0.62)与已发送(1)之间。- bubbleSettling: { opacity: 0.85 },- bubbleText: {- color: colors.textPrimary,- fontSize: typeScale.bodyLarge,- lineHeight: lineHeight.bodyLarge,- },- attachmentLine: { alignItems: 'center', flexDirection: 'row', gap: 4 },- attachmentLineText: { color: colors.textTertiary, fontSize: typeScale.footnote },- // 气泡内图片缩略条(与 ComposerAttachmentTray 缩略卡同一视觉词汇:chip 底 +- // hairline 边 + container 圆角;上传中压 overlay 遮罩转圈)。- thumbStrip: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs, justifyContent: 'flex-end' },- thumbCell: {- backgroundColor: colors.surfaceChip,- borderColor: colors.border,- borderRadius: radius.container,- borderWidth: StyleSheet.hairlineWidth,- height: 72,- overflow: 'hidden',- width: 72,- },- thumbCellImage: { height: '100%', width: '100%' },- thumbUploadingOverlay: {- alignItems: 'center',- backgroundColor: colors.overlay,- bottom: 0,- justifyContent: 'center',- left: 0,- position: 'absolute',- right: 0,- top: 0,- },- outboxErrorText: { color: colors.errorText, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },- editingHint: { color: colors.textTertiary, fontSize: typeScale.footnote },- rowHint: {- color: colors.textTertiary,- fontSize: typeScale.footnote,- lineHeight: lineHeight.caption,- textAlign: 'right',- },- actionRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm, justifyContent: 'flex-end' },actionPill: {alignItems: 'center',backgroundColor: colors.surfaceElevated,@@ -678,24 +244,11 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({borderWidth: StyleSheet.hairlineWidth,flexDirection: 'row',gap: 6,- minHeight: 36,justifyContent: 'center',+ minHeight: 36,paddingHorizontal: spacing.md,},- actionPillCta: { backgroundColor: colors.cta, borderColor: colors.cta },actionPillText: { color: colors.textPrimary, fontSize: typeScale.caption, fontWeight: fontWeight.medium },- actionPillTextCta: { color: colors.ctaText },- toggleRow: { flexDirection: 'row', justifyContent: 'flex-end' },- togglePill: {- alignItems: 'center',- borderColor: colors.border,- borderRadius: radius.pill,- borderWidth: StyleSheet.hairlineWidth,- minHeight: 32,- justifyContent: 'center',- paddingHorizontal: spacing.md,- },- togglePillText: { color: colors.textSecondary, fontSize: typeScale.caption, fontWeight: fontWeight.medium },pressed: { opacity: 0.72 },disabled: { opacity: 0.42 },});diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex fdd6254c4f..581a9a5488 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -224,6 +224,10 @@ import {type MobileWorkChildItem,type MobileWorkGroupItem,} from '@/session/messageRenderModel';+import {+ PendingSendBubble,+ type PendingSendBubbleActions,+} from '@/session/PendingSendBubble';import { dedupeToolMediaByUrl } from '@cindy/maker-shared/message-render';import { tokenizeThinkingText } from '@cindy/maker-shared/thinking-text';import {@@ -433,6 +437,8 @@ interface MessageActions {/** 正文里会话深链 chip(xdt-maker://session/…)点击回调,app 内跳转。 */onOpenSessionLink?: (url: string) => void;onPreviewRewind?: (clientId: string, draft: MobileMessageDraft) => void;+ /** 待发送气泡(pending_send 项)的展开态与队列操作回调。 */+ pendingSend?: PendingSendBubbleActions;onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;onResolveRemoteMedia?: ResolveRemoteMediaFn;@@ -458,6 +464,7 @@ export function MessageRenderer({onOpenSessionLink,onPreviewRewind,onQuoteSelection,+ pendingSend,onReadTextFilePreview,onReleaseRemoteMedia,onResolveRemoteMedia,@@ -697,6 +704,9 @@ export function MessageRenderer({onPreviewRewind,onOpenPayload: setPayload,onResolveRemoteMedia,+ // 待发送气泡(pending_send 项)的展开态与队列操作:漏了这一项 actions.pendingSend 就是+ // undefined,渲染分支直接 null —— 气泡整个不画,乐观显示消失。+ pendingSend,busyClientId,firstUserMessageClientId,isSessionStreaming,@@ -713,6 +723,7 @@ export function MessageRenderer({onOpenSessionLink,onPreviewRewind,onResolveRemoteMedia,+ pendingSend,viewportLayout.contentWidth,]);// chat-text-quote:选区采集 context。仅「会话页传了采集回调 + iOS」时启用@@ -1299,6 +1310,20 @@ const RenderItemView = memo(function RenderItemView({case 'fork_origin':node = <ForkOriginMarker onOpenForkOrigin={actions.onOpenForkOrigin} />;break;+ case 'pending_send':+ // 待发送气泡。actions.pendingSend 由会话页恒传;真缺失时**跳过这一项**(不渲染),+ // 而不是渲染一个点不动的气泡 —— 没有回调的气泡无法取消 / 编辑 / 重试,画出来只会+ // 让用户对着死气泡操作。渲染路径无 ErrorBoundary,这里也不抛,免得整列崩掉。+ node = actions.pendingSend+ ? (+ <PendingSendBubble+ actions={actions.pendingSend}+ item={item}+ resolveRemoteMedia={actions.onResolveRemoteMedia}+ />+ )+ : null;+ break;default:// 穷尽性保证:给 render-item union 加新变体却漏处理 → typecheck 报错(入参 never)。运行时降级为// log+skip(node 保持空)而非 throw —— render 路径无 ErrorBoundary,不能让单个未知 item 崩整列。diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsxnew file mode 100644index 0000000000..392e490e89--- /dev/null+++ b/apps/mobile/src/session/PendingSendBubble.tsx@@ -0,0 +1,446 @@+/**+ * 待发送消息气泡(渲染在消息流里,不再是列表 footer)。+ *+ * 形态与已发送用户气泡同款(右对齐、surfaceElevated + borderStrong)但整体半透明——+ * 「这就是你的消息,只是还没生效」;落定时提高不透明度,回流后同一个列表位置换成正式+ * 消息,原地变实。徽标语义:+ * - 转圈 = 还没有「已被收下」这个事实(enqueue 在途 / 已出队待回流 / 附件上传中);+ * - 「排入队尾 list-end」= 已确认入队,顺序由排列先后表达,不标数字;+ * - ✎ = 正在底部 composer 编辑这一条;+ * - ⚠ = 失败,可重试 / 删除。+ * 「排入队尾」是个事实断言,未确认时画它就是谎报,所以未确认一律转圈。+ */+import { useEffect, useLayoutEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';+import { Image } from 'expo-image';+import { Text } from '@/components/AppText';+import {+ AlertCircle,+ ArrowUp,+ ListEnd,+ Paperclip,+ Pencil,+ RotateCcw,+ Trash2,+ type LucideIcon,+} from 'lucide-react-native';+import {+ getSentAttachmentThumbUri,+ useSentAttachmentThumbsVersion,+} from '@/session/sentAttachmentThumbStore';+import { pendingSendSpins, type MobilePendingSendItem } from '@/session/pendingSendItems';+import {+ isDesktopLocalMediaUrl,+ type ResolveRemoteMediaFn,+} from '@/session/remoteMedia';+import type { MobileOutboxThumb } from '@/session/sessionOutbox';+import {+ fontWeight,+ iconSize,+ iconStroke,+ lineHeight,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from '@/theme';+import { radius, spacing, typeScale } from '@/theme/tokens';++export interface PendingSendBubbleActions {+ /** 展开 / 收起操作行的条目;null = 全收起。 */+ selectedClientId: string | null;+ onSelect(clientId: string | null): void;+ onRemove(clientId: string): void;+ onBeginEdit(clientId: string): void;+ onSteer(clientId: string): void;+ onRetryOutbox(clientId: string): void;+ onRemoveOutbox(clientId: string): void;+ busy?: boolean;+}++/**+ * 气泡内图片缩略条:乐观语义下图片从第一帧就以图的形态出现,不做「📎 附件行 → 正式消息+ * 图片」的形态跳变。uri 缺失时按 ossRef 查 sentAttachmentThumbStore(订阅版本号,+ * hydrate / 注册完成后自动补图);两者都拿不到时渲染 chip 底色占位格。+ */+/**+ * 单格缩略图的 uri 解析,三条来源按可靠性排序:+ * 1. sentAttachmentThumbStore 的持久拷贝 —— 手机上传的图,活得比粘贴源文件久;+ * 2. 发送时刻记下的本地预览 file://;+ * 3. 远端媒体解析 —— 粘贴时图片已经先传到媒体总仓的场景,附件 url 是+ * `cindy-media://blobs/<指纹>`,本地根本没有这个文件,只能经 device-link 取缩略图+ * (正式消息就是走这条路;不走的话排队气泡只能画空占位格)。+ */+function useThumbCellUri(+ thumb: MobileOutboxThumb,+ resolveRemoteMedia?: ResolveRemoteMediaFn,+): string | null {+ // 「这一格现在指的是哪张图」。排队消息被编辑、同一附件下标换成另一张图时,ThumbCell 的+ // key(clientId-file-index)不变、hook 实例被复用 —— 所有缓存都必须绑定这个身份,否则旧图+ // 会一直压住新图直到整行卸载,编辑后的气泡显示的是已被移除的附件(review P1)。+ const identity = `${thumb.uri ?? ''}|${thumb.ossRef ?? ''}`;+ const durableUri = thumb.ossRef ? getSentAttachmentThumbUri(thumb.ossRef) : null;+ const localUri = durableUri ?? thumb.uri ?? null;+ const [remoteState, setRemoteState] = useState<{ uri: string; identity: string } | null>(null);+ const remoteUri = remoteState?.identity === identity ? remoteState.uri : null;+ const remoteCandidate = localUri ? null : thumb.ossRef;+ useEffect(() => {+ if (!remoteCandidate || !resolveRemoteMedia || !isDesktopLocalMediaUrl(remoteCandidate)) {+ return undefined;+ }+ let cancelled = false;+ const controller = new AbortController();+ void (async () => {+ try {+ const resolved = await resolveRemoteMedia(+ { kind: 'image', url: remoteCandidate, previewable: false, thumbnail: true },+ { signal: controller.signal },+ );+ if (!cancelled && resolved.url) setRemoteState({ uri: resolved.url, identity });+ } catch {+ // 取不到就回落占位格:待发气泡的图是增强,不能因为取件失败妨碍发送流程。+ }+ })();+ return () => {+ cancelled = true;+ controller.abort();+ };+ }, [identity, remoteCandidate, resolveRemoteMedia]);+ const candidate = localUri ?? remoteUri;+ // 已显示出来的 uri 锁住,不为「更可靠的来源出现」而换:三条来源可用时机不同(本地底片要+ // 等 store hydrate、远端取件更晚),换 uri 会让 Image 重新加载、中间露出底色(闪白)。+ // 锁同样绑身份:身份变了就解锁,重新按新图取。+ const shownRef = useRef<{ uri: string; identity: string } | null>(null);+ const shown = shownRef.current?.identity === identity ? shownRef.current.uri : null;+ // 写 ref 放 layout effect(render 阶段不碰 ref:Concurrent 下被丢弃的 render 会污染它)。+ useLayoutEffect(() => {+ if (candidate && shownRef.current?.identity !== identity) {+ shownRef.current = { uri: candidate, identity };+ }+ }, [candidate, identity]);+ return shown ?? candidate;+}++function ThumbCell({+ thumb,+ resolveRemoteMedia,+}: {+ thumb: MobileOutboxThumb;+ resolveRemoteMedia?: ResolveRemoteMediaFn;+}) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ const uri = useThumbCellUri(thumb, resolveRemoteMedia);+ return (+ <View style={styles.thumbCell}>+ {uri ? (+ <Image+ // 缓存命中优先:同一张图在气泡与回流后的正式消息之间复用解码结果,交接时不重绘。+ cachePolicy="memory-disk"+ contentFit="cover"+ // recyclingKey 绑到这一格:列表复用视图时不会短暂顶着上一条消息的图。+ recyclingKey={thumb.key}+ source={{ uri }}+ style={styles.thumbCellImage}+ transition={0}+ />+ ) : null}+ {thumb.uploading ? (+ <View style={styles.thumbUploadingOverlay}>+ <ActivityIndicator color={colors.ctaText} size="small" />+ </View>+ ) : null}+ </View>+ );+}++function AttachmentThumbStrip({+ thumbs,+ resolveRemoteMedia,+}: {+ thumbs: readonly MobileOutboxThumb[];+ resolveRemoteMedia?: ResolveRemoteMediaFn;+}) {+ const styles = useThemedStyles(makeStyles);+ useSentAttachmentThumbsVersion();+ if (thumbs.length === 0) return null;+ return (+ <View style={styles.thumbStrip} testID="pendingSend.thumbStrip">+ {thumbs.map((thumb) => (+ <ThumbCell key={thumb.key} resolveRemoteMedia={resolveRemoteMedia} thumb={thumb} />+ ))}+ </View>+ );+}++export function PendingSendBubble({+ item,+ actions,+ resolveRemoteMedia,+}: {+ item: MobilePendingSendItem;+ actions: PendingSendBubbleActions;+ /** 远端媒体取件(粘贴时已上传到媒体总仓的图靠它取缩略图)。 */+ resolveRemoteMedia?: ResolveRemoteMediaFn;+}) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ const { t } = useTranslation();+ const spinning = pendingSendSpins(item.phase);+ const editing = item.phase === 'editing';+ const failed = item.phase === 'failed';+ const interactive = item.actions !== null || failed;+ const selected = interactive && actions.selectedClientId === item.clientId;+ const bubbleLabel = item.text || t('message.queue.attachmentMessage');+ const uploadsPending = item.phase === 'uploading';++ return (+ <View style={styles.rowWrap} testID={`pendingSend.row.${item.clientId}`}>+ <View style={styles.bubbleRow}>+ <View style={styles.badge} testID={`pendingSend.badge.${item.phase}`}>+ {failed ? (+ <AlertCircle color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />+ ) : spinning ? (+ <ActivityIndicator color={colors.textTertiary} size="small" />+ ) : editing ? (+ <Pencil color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />+ ) : (+ // 暂停态不换 ⏸:组顶横幅已表达暂停,逐条再换会重复;行内恒用排队 icon。+ <ListEnd color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />+ )}+ </View>+ <Pressable+ accessibilityHint={item.hint ?? undefined}+ accessibilityLabel={failed+ ? t('message.queue.sendFailedMessage', { text: bubbleLabel })+ : spinning+ ? t('message.queue.sendingMessage', { text: bubbleLabel })+ : item.queueIndex !== null+ ? t('message.queue.queuedMessageLabel', { index: item.queueIndex, text: bubbleLabel })+ : t('message.queue.sendingMessage', { text: bubbleLabel })}+ accessibilityRole="button"+ accessibilityState={{ expanded: selected, disabled: !interactive }}+ disabled={!interactive}+ onPress={() => actions.onSelect(selected ? null : item.clientId)}+ style={({ pressed }) => [+ styles.bubble,+ item.phase === 'settling' && styles.bubbleSettling,+ selected && styles.bubbleSelected,+ editing && styles.bubbleEditing,+ pressed && styles.pressed,+ ]}+ testID={`pendingSend.bubble.${item.clientId}`}+ >+ {item.text ? (+ <Text numberOfLines={selected ? undefined : 6} style={styles.bubbleText}>+ {item.text}+ </Text>+ ) : null}+ <AttachmentThumbStrip resolveRemoteMedia={resolveRemoteMedia} thumbs={item.thumbs} />+ {item.fileCount > 0 || uploadsPending ? (+ <View style={styles.attachmentLine}>+ <Paperclip color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />+ <Text style={styles.attachmentLineText}>+ {uploadsPending+ ? t('message.queue.uploadingAttachments', {+ uploaded: item.uploadedCount,+ total: item.attachmentCount,+ })+ : t('message.queue.attachmentCount', { n: item.fileCount })}+ </Text>+ </View>+ ) : null}+ {editing ? (+ <Text style={styles.editingHint} testID={`pendingSend.editingHint.${item.clientId}`}>+ {t('message.queue.editingInComposer')}+ </Text>+ ) : null}+ {item.errorText ? (+ <Text style={styles.errorText} testID={`pendingSend.error.${item.clientId}`}>+ {item.errorText}+ </Text>+ ) : null}+ </Pressable>+ </View>+ {selected && item.hint ? (+ <Text style={styles.rowHint} testID={`pendingSend.hint.${item.clientId}`}>{item.hint}</Text>+ ) : null}+ {selected && item.actions ? (+ <View style={styles.actionRow} testID={`pendingSend.actions.${item.clientId}`}>+ <ActionPill+ busy={actions.busy}+ disabled={item.actions.remove.disabled}+ disabledReason={item.actions.remove.disabledReason}+ icon={Trash2}+ label={t('message.queue.cancel')}+ onPress={() => actions.onRemove(item.clientId)}+ testID={`pendingSend.remove.${item.clientId}`}+ />+ <ActionPill+ busy={actions.busy}+ disabled={item.actions.edit.disabled}+ disabledReason={item.actions.edit.disabledReason}+ icon={Pencil}+ label={t('message.queue.edit')}+ onPress={() => actions.onBeginEdit(item.clientId)}+ testID={`pendingSend.edit.${item.clientId}`}+ />+ <ActionPill+ busy={actions.busy}+ cta+ disabled={item.actions.steer.disabled}+ disabledReason={item.actions.steer.disabledReason}+ icon={ArrowUp}+ label={t('message.queue.steer')}+ onPress={() => actions.onSteer(item.clientId)}+ testID={`pendingSend.steer.${item.clientId}`}+ />+ </View>+ ) : null}+ {selected && failed ? (+ <View style={styles.actionRow} testID={`pendingSend.outboxActions.${item.clientId}`}>+ <ActionPill+ busy={actions.busy}+ icon={Trash2}+ label={t('message.queue.delete')}+ onPress={() => actions.onRemoveOutbox(item.clientId)}+ testID={`pendingSend.outboxRemove.${item.clientId}`}+ />+ <ActionPill+ busy={actions.busy}+ cta+ icon={RotateCcw}+ label={t('message.queue.retry')}+ onPress={() => actions.onRetryOutbox(item.clientId)}+ testID={`pendingSend.outboxRetry.${item.clientId}`}+ />+ </View>+ ) : null}+ </View>+ );+}++function ActionPill({+ busy,+ cta,+ disabled,+ disabledReason,+ icon: Icon,+ label,+ onPress,+ testID,+}: {+ busy?: boolean;+ cta?: boolean;+ disabled?: boolean;+ disabledReason?: string | null;+ icon?: LucideIcon;+ label: string;+ onPress(): void;+ testID?: string;+}) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ const iconColor = cta ? colors.ctaText : colors.textSecondary;+ return (+ <Pressable+ accessibilityHint={disabledReason ?? undefined}+ accessibilityLabel={label}+ accessibilityRole="button"+ accessibilityState={{ busy: busy || undefined, disabled }}+ disabled={disabled}+ onPress={disabled ? undefined : onPress}+ style={({ pressed }) => [+ styles.actionPill,+ cta && styles.actionPillCta,+ pressed && styles.pressed,+ disabled && styles.disabled,+ ]}+ testID={testID}+ >+ {Icon ? <Icon color={iconColor} size={iconSize.sm} strokeWidth={iconStroke.regular} /> : null}+ <Text style={[styles.actionPillText, cta && styles.actionPillTextCta]}>{label}</Text>+ </Pressable>+ );+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ rowWrap: { alignItems: 'flex-end', gap: spacing.sm, width: '100%' },+ bubbleRow: {+ alignItems: 'center',+ flexDirection: 'row',+ gap: spacing.sm,+ justifyContent: 'flex-end',+ width: '100%',+ },+ badge: { alignItems: 'center', flexDirection: 'row' },+ // 与已发送用户气泡同款,但整体半透明:「这就是你的消息,只是还没生效」。+ bubble: {+ backgroundColor: colors.surfaceElevated,+ borderColor: colors.borderStrong,+ borderRadius: radius.container,+ borderWidth: StyleSheet.hairlineWidth,+ gap: spacing.xs,+ maxWidth: '86%',+ opacity: 0.62,+ padding: spacing.md,+ },+ bubbleSelected: { borderColor: colors.textSecondary, opacity: 1 },+ bubbleEditing: { opacity: 0.38 },+ // 落定中:即将变实,透明度介于排队(0.62)与已发送(1)之间。+ bubbleSettling: { opacity: 0.85 },+ bubbleText: {+ color: colors.textPrimary,+ fontSize: typeScale.bodyLarge,+ lineHeight: lineHeight.bodyLarge,+ },+ attachmentLine: { alignItems: 'center', flexDirection: 'row', gap: 4 },+ attachmentLineText: { color: colors.textTertiary, fontSize: typeScale.footnote },+ thumbStrip: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs, justifyContent: 'flex-end' },+ thumbCell: {+ backgroundColor: colors.surfaceChip,+ borderColor: colors.border,+ borderRadius: radius.container,+ borderWidth: StyleSheet.hairlineWidth,+ height: 72,+ overflow: 'hidden',+ width: 72,+ },+ thumbCellImage: { height: '100%', width: '100%' },+ thumbUploadingOverlay: {+ alignItems: 'center',+ backgroundColor: colors.overlay,+ bottom: 0,+ justifyContent: 'center',+ left: 0,+ position: 'absolute',+ right: 0,+ top: 0,+ },+ editingHint: { color: colors.textTertiary, fontSize: typeScale.footnote },+ errorText: { color: colors.errorText, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ rowHint: {+ color: colors.textTertiary,+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ textAlign: 'right',+ },+ actionRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm, justifyContent: 'flex-end' },+ actionPill: {+ alignItems: 'center',+ backgroundColor: colors.surfaceElevated,+ borderColor: colors.border,+ borderRadius: radius.pill,+ borderWidth: StyleSheet.hairlineWidth,+ flexDirection: 'row',+ gap: 6,+ justifyContent: 'center',+ minHeight: 36,+ paddingHorizontal: spacing.md,+ },+ actionPillCta: { backgroundColor: colors.cta, borderColor: colors.cta },+ actionPillText: { color: colors.textPrimary, fontSize: typeScale.caption, fontWeight: fontWeight.medium },+ actionPillTextCta: { color: colors.ctaText },+ pressed: { opacity: 0.72 },+ disabled: { opacity: 0.42 },+});diff --git a/apps/mobile/src/session/attachments.ts b/apps/mobile/src/session/attachments.tsindex 9f0ef32789..f1ee0418fd 100644--- a/apps/mobile/src/session/attachments.ts+++ b/apps/mobile/src/session/attachments.ts@@ -55,6 +55,33 @@ const KNOWN_TEXT_FILENAMES = new Set(['cmakelists',]);+/**+ * 附件按 id 去重合并,前者优先,受托盘上限截断。+ *+ * **溢出必须由调用方处理**:回收中转对象 + 告知用户。上限是「每条消息」的产品约束,而+ * 创建失败的恢复路径要把 N 条待发消息的附件并进**一条**草稿——只要有两条带附件的消息+ * 就可能超,静默截断等于把用户已上传的附件连同它在 OSS 的中转对象一起吞掉(review P1)。+ * 返回 dropped 而不是内部丢弃,是为了让「丢了什么」在类型上无法被忽略。+ *+ * preferred 自身超限时原样保留:那是调用方自己的内容,该由它决定,这里不越权截断。+ */+export function mergeAttachmentsWithinLimit(+ preferred: readonly RemoteSerializedAttachment[],+ extra: readonly RemoteSerializedAttachment[],+): { merged: RemoteSerializedAttachment[]; dropped: RemoteSerializedAttachment[] } {+ const merged = [...preferred];+ const dropped: RemoteSerializedAttachment[] = [];+ for (const attachment of extra) {+ if (merged.some((item) => item.id === attachment.id)) continue;+ if (merged.length >= MOBILE_MAX_ATTACHMENTS) {+ dropped.push(attachment);+ continue;+ }+ merged.push(attachment);+ }+ return { merged, dropped };+}+/** 本机文件附件的体积校验(乐观上传后台任务里执行,超限 throw 由失败回调呈现)。 */export function assertMobileDocumentSize(size: number): void {if (!Number.isFinite(size) || size <= 0) {diff --git a/apps/mobile/src/session/messageGallery.ts b/apps/mobile/src/session/messageGallery.tsindex c48363e374..3e5a1e1028 100644--- a/apps/mobile/src/session/messageGallery.ts+++ b/apps/mobile/src/session/messageGallery.ts@@ -136,6 +136,10 @@ export function collectMobileMessageGalleryImages(case 'fork_origin':// fork 来源标记只含导航 UI,no-op。break;+ case 'pending_send':+ // 待发送气泡:附件还是 `cindy-oss-attach://` 中转引用 / 本地预览,不是可供+ // lightbox 分页的正式媒体;等消息回流后由 message 路径入图集。+ break;default:// 穷尽性保证:新增 render-item 变体会被 typecheck 拦下(入参 never)。运行时降级为 log+skip// (不 throw),与 RenderItemView 一致——相册收集在 useMemo 路径,不能让单个未知 item 崩。diff --git a/apps/mobile/src/session/messagePresentation.ts b/apps/mobile/src/session/messagePresentation.tsindex 88a4d2b735..4ee885ca9f 100644--- a/apps/mobile/src/session/messagePresentation.ts+++ b/apps/mobile/src/session/messagePresentation.ts@@ -67,6 +67,8 @@ export function countMobileRenderItemDiffs(items: readonly MobileMessageRenderItnested += countMobileRenderItemDiffs(item.childItems);} else if (item.type === 'fork_origin') {// 导航标记不含 diff payload。+ } else if (item.type === 'pending_send') {+ // 待发送气泡还没有正文以外的 payload(diff 由回流后的正式消息承载)。} else {sharedItems.push(item);}diff --git a/apps/mobile/src/session/messageRenderModel.ts b/apps/mobile/src/session/messageRenderModel.tsindex 8b947f4543..2f150c3eee 100644--- a/apps/mobile/src/session/messageRenderModel.ts+++ b/apps/mobile/src/session/messageRenderModel.ts@@ -15,6 +15,7 @@ import {type MessageRenderWorkGroupItem,} from '@cindy/maker-shared/message-render';import type { AgentTaskUpdate } from '@cindy/maker-shared/agent-task';+import type { MobilePendingSendItem } from '@/session/pendingSendItems';import { normalizeRemoteMessages, type NormalizedRemoteMessage } from '@/session/messageNormalize';import type { RemoteMessage } from '@/session/types';import {@@ -68,7 +69,10 @@ export interface MobileForkOrigin {export type MobileMessageRenderItem =| MessageRenderItem<NormalizedRemoteMessage>| MobileSubagentGroupItem- | MobileForkOriginItem;+ | MobileForkOriginItem+ // 待发送气泡(排队 / 落定 / 本地 outbox)也是消息流的一等项:与正式消息同容器同 key,+ // 回流时原地变实,不再跨 footer↔data 搬家(见 pendingSendItems.ts 的说明)。+ | MobilePendingSendItem;export function buildMobileMessageRenderItems(messages: readonly RemoteMessage[],diff --git a/apps/mobile/src/session/messageSearch.ts b/apps/mobile/src/session/messageSearch.tsindex a8dc34e815..2fd983345b 100644--- a/apps/mobile/src/session/messageSearch.ts+++ b/apps/mobile/src/session/messageSearch.ts@@ -26,6 +26,10 @@ export function findMobileMessageSearchHits(if (item.type === 'fork_origin') {continue;}+ // 待发送气泡不进搜索:它还不是会话记录,命中它无法定位/跳转(回流后正式消息会被索引)。+ if (item.type === 'pending_send') {+ continue;+ }if (item.type === 'subagent_group') {const hit = searchSubagentGroup(item, query);if (hit) hits.push(hit);diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.tsindex 514a2019e3..064f88733b 100644--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts@@ -164,6 +164,14 @@ export interface MobileLocalAttachmentUploadController {* remove / retry 对 claimed 任务照常可用(outbox 条目的删除与重试复用它们)。*/claim(localIds: readonly string[]): void;+ /**+ * claim 的逆操作:任务交还 composer 域(重回托盘、重新计入限额)。+ *+ * 乐观消息被收回成草稿时用(创建失败把待发消息交还输入框):任务本身继续跑,+ * 落定后宿主的 outbox 路由找不到归属条目,产物自然回落到托盘。取消再重传是错的+ * ——用户已经等过一次上传,且粘贴来源的本地文件可能已被回收(review P1)。+ */+ unclaim(localIds: readonly string[]): void;/*** 未 claim 且未丢弃任务的同步快照(顺序 = 入队序):发送时刻用它决定「这条消息* 要带走哪些在途上传」。failed = 已失败结算的卡(claim 后随消息进失败态);@@ -501,6 +509,18 @@ export function createMobileLocalAttachmentUploadController(if (changed) notifyPending();},+ unclaim(localIds) {+ let changed = false;+ for (const localId of localIds) {+ const task = tasks.get(localId);+ if (!task || task.discarded || !task.claimed) continue;+ task.claimed = false;+ changed = true;+ }+ // 任务回到托盘域,同步刷一次 pending 列表(失败卡也会重新出现,可 retry / X)。+ if (changed) notifyPending();+ },+claimableTasks() {const out: Array<{localId: string;diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.tsindex 0be946837a..d1ce7ecc01 100644--- a/apps/mobile/src/session/newSessionCreation.ts+++ b/apps/mobile/src/session/newSessionCreation.ts@@ -308,16 +308,36 @@ export interface StashedNewSessionDraft {deviceName: string;draft: NewSessionDraft;attachments: readonly RemoteSerializedAttachment[];+ /**+ * 「有内容没能带回来」的可见告知(新建页展示为附件错误行)。+ *+ * 新建页只有一条首条消息 + 一个受上限约束的托盘,而创建期间可能已经发出多条带附件+ * 的消息:装不下的部分只能丢,但**绝不能静默丢**——中转对象由会话页回收,用户得知道+ * 少了什么、需要重新选(review P1)。+ */+ notice?: string | null;}let stashedDraft: StashedNewSessionDraft | null = null;-export function stashNewSessionDraftForEdit(task: NewSessionCreationTask): void {+/**+ * override 用于把「创建期间攒下的后续消息」并进带回新建页的草稿:那些消息此刻在会话页的+ * outbox 里,而合成会话行紧接着就被删掉,不并进来就再也找不回(review P1)。+ */+export function stashNewSessionDraftForEdit(+ task: NewSessionCreationTask,+ override?: {+ draft?: NewSessionDraft;+ attachments?: readonly RemoteSerializedAttachment[];+ notice?: string | null;+ },+): void {stashedDraft = {deviceId: task.deviceId,deviceName: task.deviceName,- draft: task.draft,- attachments: task.attachments,+ draft: override?.draft ?? task.draft,+ attachments: override?.attachments ?? task.attachments,+ notice: override?.notice ?? null,};}diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.tsnew file mode 100644index 0000000000..9e16fd8219--- /dev/null+++ b/apps/mobile/src/session/pendingSendItems.ts@@ -0,0 +1,216 @@+/**+ * 待发送消息 → 消息流渲染项。+ * ---------------------------------------------------------------------------+ * 为什么这些气泡必须进消息流(而不是继续挂在列表 footer):+ *+ * 排队 / 落定 / outbox 气泡原来渲染在 LegendList 的 ListFooterComponent 里,正式消息在+ * data 里。消息回流时气泡必须跨容器搬家 —— footer 里卸载、data 里挂载,位置也从「footer+ * 的落点」跳到「列表末项」。空会话时更明显:listData 为空会渲染撑满高度的居中「正在同步」+ * 占位,把 footer 顶到屏幕中间,于是用户看到「气泡在屏幕中间 → 消失 → 在底部重新出现」+ * (实测两张截图位置差约 18% 屏高)。key 统一、同帧提交都救不了跨容器搬家。+ *+ * 进了 data 之后:与正式消息同容器、同 key(`message-${clientId}`)、同一处位置,回流就是+ * 同一个列表位置上的内容替换 —— 原地变实,零跳动;listData 也不再为空,居中占位自然不出现。+ *+ * 顺序契约(与原 footer 一致):落定中(已出队、等回流)在前,排队中居中,本地 outbox 在后+ * —— outbox 是最晚发出的。+ */+import { syntheticTriggerKind } from '@cindy/maker-shared/synthetic-trigger';+import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';+import { i18n } from '@/i18n';+import type { MobileOutboxDisplayItem, MobileOutboxThumb } from '@/session/sessionOutbox';+import type { QueuedRemoteMessage } from '@/session/types';++export type MobilePendingSendPhase =+ /** 已确认入队,等被控端派发。 */+ | 'queued'+ /** enqueue RPC 在途,还没有「已入队」这个事实。 */+ | 'sending'+ /** 已被派发出队,消息还没回流。 */+ | 'settling'+ /** 本地 outbox:附件还在上传 / 等轮到队首。 */+ | 'uploading'+ /** 上传或 enqueue 失败,气泡保留待用户重试 / 删除。 */+ | 'failed'+ /** 正在底部 composer 里编辑这一条。 */+ | 'editing';++/** 气泡上的三个队列操作在当前条目上可不可用(由 buildQueueRowPresentation 预先算好)。 */+export interface MobilePendingSendActions {+ remove: { disabled: boolean; disabledReason: string | null };+ edit: { disabled: boolean; disabledReason: string | null };+ steer: { disabled: boolean; disabledReason: string | null };+}++export interface MobilePendingSendItem {+ type: 'pending_send';+ /** 与回流后的正式消息项同 key —— 同一个列表位置,内容原地替换。 */+ key: string;+ clientId: string;+ text: string;+ phase: MobilePendingSendPhase;+ /** 队列序号(从 1 起,用于无障碍播报);不在队列里的条目为 null。 */+ queueIndex: number | null;+ thumbs: MobileOutboxThumb[];+ /** 非图片附件数(pdf / office 等,渲染「N 个文件」计数行)。 */+ fileCount: number;+ /** 附件总数与已上传数(uploading 阶段渲染「上传中 k/N」)。 */+ attachmentCount: number;+ uploadedCount: number;+ errorText: string | null;+ /** 可否轻点展开操作行:只有还在队列里的条目能取消 / 编辑 / 插队。 */+ actions: MobilePendingSendActions | null;+ /** 展开后显示的提示(插队限制等)。 */+ hint: string | null;+}++export function pendingSendItemKey(clientId: string): string {+ return `message-${clientId}`;+}++/**+ * 气泡显示文本:合成 UI 指令行(桌面「失败后继续」等隐藏 prompt)用遮蔽标签替代原文+ * —— 裸英文指令不能给用户看(对齐桌面 PendingQueuePanel 的 i18n 遮蔽标签)。+ */+export function pendingSendBubbleText(+ item: Pick<QueuedRemoteMessage, 'text' | 'chatMessage'>,+): string {+ const visibleText = item.chatMessage.quotesEncoded === true+ ? stripChatQuoteMarkerLines(item.text)+ : item.text;+ const kind = syntheticTriggerKind(visibleText);+ if (kind === 'continue') return i18n.t('message.queue.continueSystemInstruction');+ if (kind === 'generic') return i18n.t('message.queue.systemInstruction');+ return visibleText;+}++/**+ * 排队 / 落定气泡的图片缩略数据:消息 files 里的图片附件此刻仍是 `cindy-oss-attach://`+ * 中转引用,本地渲染靠 sentAttachmentThumbStore 的兜底映射。非图片附件走计数行。+ */+function queuedAttachmentThumbs(+ item: Pick<QueuedRemoteMessage, 'clientId' | 'files'>,+ previewByOssRef?: ReadonlyMap<string, string>,+): { thumbs: MobileOutboxThumb[]; fileCount: number } {+ const thumbs: MobileOutboxThumb[] = [];+ let fileCount = 0;+ (item.files ?? []).forEach((file, index) => {+ if (file.category !== 'image') {+ fileCount += 1;+ return;+ }+ const ossRef = file.url ?? file.path;+ thumbs.push({+ key: `${item.clientId}-file-${index}`,+ // 发送时刻抓下的本地预览优先:sentAttachmentThumbStore 那条兜底链要等「上传落定 →+ // 拷进自有目录 → AsyncStorage hydrate」全部完成才查得到,期间 getSentAttachmentThumbUri+ // 一律返回 null,排队气泡只能画空占位格(实测:兜底文件已生成,气泡仍是空方块)。+ // 乐观语义下图必须从第一帧就在,所以直接用手边的 file:// 预览,store 只作为+ // 「重开会话 / 预览已失效」时的后备。+ uri: (ossRef && previewByOssRef?.get(ossRef)) || null,+ ossRef,+ uploading: false,+ });+ });+ return { thumbs, fileCount };+}++export interface BuildPendingSendItemsInput {+ /** 权威队列(projection.pendingQueue)。 */+ queue: readonly QueuedRemoteMessage[];+ /** 已出队、等回流的落定条目。 */+ settling: readonly QueuedRemoteMessage[];+ /** 本地待发条目(附件上传中 / enqueue 在途或失败)。 */+ outbox: readonly MobileOutboxDisplayItem[];+ /** 已回流进消息流的 clientId:正式消息已在流里,气泡不再渲染(避免双显)。 */+ hiddenClientIds: ReadonlySet<string>;+ /** enqueue RPC 在途的 clientId(徽标转圈,不谎报「已入队」)。 */+ sendingClientIds: ReadonlySet<string>;+ /** 正在 composer 里编辑的条目。 */+ editingClientId: string | null;+ /** 插队发送中的 clientId(projection.steeringQueueClientIds)。 */+ steeringClientIds: ReadonlySet<string>;+ /** 每个在队条目的操作可用性 + hint,由调用方用 buildQueueRowPresentation 算好。 */+ presentationByClientId: ReadonlyMap<string, { actions: MobilePendingSendActions; hint: string | null }>;+ /**+ * 发送时刻记下的「附件 ossRef → 本地预览 file://」。+ * 排队气泡的图靠它即时显示,不等 sentAttachmentThumbStore 的拷贝 + hydrate 链。+ */+ previewByOssRef?: ReadonlyMap<string, string>;+}++/**+ * 组装消息流末尾的待发送气泡项。+ *+ * 落定中的条目也可能同时还在 queue 里(派发失败被塞回队首):按 clientId 去重,queue 优先+ * —— 它带着可用的队列操作。+ */+export function buildPendingSendItems(input: BuildPendingSendItemsInput): MobilePendingSendItem[] {+ const items: MobilePendingSendItem[] = [];+ const seen = new Set<string>();++ const pushQueued = (item: QueuedRemoteMessage, phase: MobilePendingSendPhase, queueIndex: number | null) => {+ if (seen.has(item.clientId) || input.hiddenClientIds.has(item.clientId)) return;+ seen.add(item.clientId);+ const attachments = queuedAttachmentThumbs(item, input.previewByOssRef);+ const presentation = queueIndex === null+ ? null+ : input.presentationByClientId.get(item.clientId) ?? null;+ items.push({+ type: 'pending_send',+ key: pendingSendItemKey(item.clientId),+ clientId: item.clientId,+ text: pendingSendBubbleText(item),+ phase,+ queueIndex,+ thumbs: attachments.thumbs,+ fileCount: attachments.fileCount,+ attachmentCount: attachments.thumbs.length + attachments.fileCount,+ uploadedCount: attachments.thumbs.length + attachments.fileCount,+ errorText: null,+ actions: presentation?.actions ?? null,+ hint: presentation?.hint ?? null,+ });+ };++ // 落定中在前:它们已经离开队列、最先被派发。+ for (const item of input.settling) {+ if (input.queue.some((queued) => queued.clientId === item.clientId)) continue;+ pushQueued(item, 'settling', null);+ }+ input.queue.forEach((item, index) => {+ const phase: MobilePendingSendPhase = input.editingClientId === item.clientId+ ? 'editing'+ : input.steeringClientIds.has(item.clientId) || input.sendingClientIds.has(item.clientId)+ ? 'sending'+ : 'queued';+ pushQueued(item, phase, index + 1);+ });+ // 本地 outbox 恒在最后:它们是最晚发出的消息。+ for (const item of input.outbox) {+ if (seen.has(item.clientId) || input.hiddenClientIds.has(item.clientId)) continue;+ seen.add(item.clientId);+ const uploadsPending = item.attachmentCount > 0 && item.uploadedCount < item.attachmentCount;+ items.push({+ type: 'pending_send',+ key: pendingSendItemKey(item.clientId),+ clientId: item.clientId,+ text: item.quotesEncoded ? stripChatQuoteMarkerLines(item.text) : item.text,+ phase: item.failed ? 'failed' : uploadsPending ? 'uploading' : 'sending',+ queueIndex: null,+ thumbs: item.thumbnails,+ fileCount: item.fileCount,+ attachmentCount: item.attachmentCount,+ uploadedCount: item.uploadedCount,+ errorText: item.errorText,+ actions: null,+ hint: null,+ });+ }+ return items;+}++/** 气泡徽标该不该转圈(未确认发出 / 已出队待回流 / 上传中)。 */+export function pendingSendSpins(phase: MobilePendingSendPhase): boolean {+ return phase === 'sending' || phase === 'settling' || phase === 'uploading';+}diff --git a/apps/mobile/src/session/queueSettling.ts b/apps/mobile/src/session/queueSettling.tsnew file mode 100644index 0000000000..7899d78896--- /dev/null+++ b/apps/mobile/src/session/queueSettling.ts@@ -0,0 +1,68 @@+/**+ * 排队条目「落定中」判定的纯函数。+ * ---------------------------------------------------------------------------+ * 被控端 drain 会先把条目从 pendingQueue 摘除、之后消息才落库回流,device-link 下两者+ * 相隔可感知。这段窗口要继续渲染半透明气泡(转圈徽标),否则气泡凭空消失、只剩「正在+ * 同步」骨架 —— 新建会话必然命中(进入会话页时首条消息就在队列里)。+ *+ * 判据(与原会话页内联实现一致):只把「像被派发」的消失算落定中——+ * - drain 恒从队首连续消费 → 消失的队首连续前缀算;+ * - steer(插队发送)按 steeringQueueClientIds 标记 → 沾上的算;+ * - 两者都不沾的中段消失是远端删除(桌面端 / 其它控制端取消),放行不渲染幽灵;+ * - 已回流(hiddenClientIds)与本地主动删除(locallyRemovedClientIds)一律排除。+ *+ * 抽成纯函数是为了让 render 阶段与 layout effect 共用同一份判定:effect 里的 setState+ * 要多走一次 render 才落地(RN 下不保证绘制前 flush),render 阶段现算才能让气泡在队列+ * 减少的**同一帧**就补上,不漏空窗。+ */++export interface QueueSettlingInput<T extends { clientId: string }> {+ /** 上一帧的 pendingQueue 快照。 */+ previous: readonly T[];+ /** 当前 pendingQueue。 */+ current: readonly T[];+ /** 上一帧的插队发送标记集合。 */+ previousSteeringClientIds: ReadonlySet<string>;+ /** 当前插队发送标记集合。 */+ currentSteeringClientIds: ReadonlySet<string>;+ /** 已回流进消息流的 clientId(正式消息已在,不再需要落定气泡)。 */+ hiddenClientIds: ReadonlySet<string>;+ /** 用户本地主动删除的 clientId(不产生幽灵气泡)。 */+ locallyRemovedClientIds: ReadonlySet<string>;+}++/** 本帧从队列消失、且应当渲染成「落定中」的条目(保持原队列顺序)。 */+export function computeVanishedQueueItems<T extends { clientId: string }>(+ input: QueueSettlingInput<T>,+): T[] {+ const currentIds = new Set(input.current.map((item) => item.clientId));+ let vanishedPrefixEnd = 0;+ while (+ vanishedPrefixEnd < input.previous.length+ && !currentIds.has(input.previous[vanishedPrefixEnd].clientId)+ ) {+ vanishedPrefixEnd++;+ }+ return input.previous.filter((item, index) => !currentIds.has(item.clientId)+ && (+ index < vanishedPrefixEnd+ || input.previousSteeringClientIds.has(item.clientId)+ || input.currentSteeringClientIds.has(item.clientId)+ )+ && !input.hiddenClientIds.has(item.clientId)+ && !input.locallyRemovedClientIds.has(item.clientId));+}++/**+ * 合并 render 阶段现算的落定项与已落库的 settling state,按 clientId 去重+ * (state 优先——它带着 settling 起始时间,用于超时兜底)。+ */+export function mergeSettlingItems<T extends { clientId: string }>(+ settled: readonly T[],+ derived: readonly T[],+): readonly T[] {+ if (derived.length === 0) return settled;+ const known = new Set(settled.map((item) => item.clientId));+ const extra = derived.filter((item) => !known.has(item.clientId));+ return extra.length === 0 ? settled : [...settled, ...extra];+}diff --git a/apps/mobile/src/session/sentAttachmentThumbStore.ts b/apps/mobile/src/session/sentAttachmentThumbStore.tsindex b7cc2a4f6c..22d2f337d8 100644--- a/apps/mobile/src/session/sentAttachmentThumbStore.ts+++ b/apps/mobile/src/session/sentAttachmentThumbStore.ts@@ -22,6 +22,7 @@import AsyncStorage from '@react-native-async-storage/async-storage';import { useSyncExternalStore } from 'react';import { isAttachmentOssRef } from '@/session/attachmentOssRef';+import { isPayloadDesktopLocalMediaUrl } from '@cindy/maker-shared/payload-summary';const STORAGE_KEY = 'xdt.sentAttachmentThumbs.v1';/** documentDirectory 下的自有子目录(不放 cache:系统清缓存会把兜底图清裂)。 */@@ -146,6 +147,19 @@ async function hydrateInternal(deps: SentAttachmentThumbFsDeps): Promise<void> {bump();}+/**+ * 哪些引用值得留本地底片。+ *+ * 除了手机自己上传产生的 `xdt-oss-attach://`,还包括桌面本地媒体引用+ * (`cindy-media://blobs/<指纹>` 等):粘贴图片时字节会先进媒体总仓,附件 url 就是这种+ * 引用,手机本地没有对应文件。原先这里只认 OSS 引用,这类图一律不留底,于是发出后+ * 气泡只能画空占位格、必须等远端取件才有图。粘贴那一刻前端手里同时握着本地文件与远端+ * 引用,应当当场记下对应关系 —— 留底之后气泡第一帧就有图,远端取件退化为后备。+ */+function isThumbBackedRef(value: unknown): value is string {+ return isAttachmentOssRef(value) || isPayloadDesktopLocalMediaUrl(value);+}+/*** 注册一条兜底映射:把 sourceUri(实际上传的文件,降采样产物或原图)拷贝进* 自有目录并持久化 ossRef → 文件名。全程静默失败——兜底是增强,不挡主流程。@@ -155,7 +169,7 @@ export async function registerSentAttachmentThumb(sourceUri: string,deps: SentAttachmentThumbFsDeps = defaultFsDeps,): Promise<void> {- if (!isAttachmentOssRef(ossRef) || !sourceUri) return;+ if (!isThumbBackedRef(ossRef) || !sourceUri) return;try {await ensureSentAttachmentThumbsHydrated(deps);if (entries.has(ossRef)) return;diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.tsindex 5c359d6b85..b06c8454a1 100644--- a/apps/mobile/src/session/sessionOutbox.ts+++ b/apps/mobile/src/session/sessionOutbox.ts@@ -196,9 +196,22 @@ export function buildOutboxItem(input: {};}-/** 将一组同会话 outbox 条目按 FIFO 顺序合并回一个可持久化 composer 草稿。 */+/**+ * 恢复回草稿所需的最小信息。+ *+ * 放宽到 Pick 而不是整个 MobileOutboxItem:新建会话失败时,首条消息(它来自+ * creationTask.draft,从来不是 outbox 条目)必须和创建期间攒下的后续消息**一起、按序**+ * 恢复,否则用户拿不回原始顺序。有了这个最小形状,首条消息可以直接参与同一次合并,+ * 引用块与富文本结构都不丢。+ */+export type MobileRecoverableDraftItem = Pick<+ MobileOutboxItem,+ 'text' | 'quotesEncoded' | 'pastedTextRanges' | 'slashCommandRanges' | 'agentReferences'+>;++/** 将一组同会话待发条目按 FIFO 顺序合并回一个可持久化 composer 草稿。 */export function recoverOutboxItemsToComposerDraft(- items: readonly MobileOutboxItem[],+ items: readonly MobileRecoverableDraftItem[],existingDraft?: MobileOutboxExistingDraft | null,): MobileOutboxDraftRecovery {const visibleParts: string[] = [];diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.tsindex 6dcf6a277f..430108c310 100644--- a/apps/mobile/src/session/systemCard.ts+++ b/apps/mobile/src/session/systemCard.ts@@ -56,6 +56,31 @@ export function parseMobileLocalSystemCommand(text: string): MobileSystemCardTypreturn parseLocalSystemCommand(text, MOBILE_LOCAL_SYSTEM_COMMANDS);}+/**+ * 出卡前需要「会话在被控端已存在」的本地命令。+ *+ * /context 要向被控端取上下文用量(maker.getContextUsage);/help /cost /pwd /status+ * 都只是本地 projection 与会话行的视图,合成行上照样出得来,不该挡——挡了反而破坏+ * 新建会话「一切正常」的观感。+ */+export const MOBILE_REMOTE_BACKED_LOCAL_COMMANDS: ReadonlySet<MobileSystemCardType> = new Set(['context']);++/**+ * 这次发送要执行的命令是否需要远端会话已经存在。+ *+ * desktop 命令一律算:手机端白名单(MOBILE_SUPPORTED_DESKTOP_COMMANDS)只有 /learn,+ * 而它就是打被控端蒸馏管线的。会话还没建成时这类命令必须挡住而不是执行 —— 也不能+ * 排队,outbox 的派发动作是「enqueue 一条消息」,命令原样入队 agent 只会当普通文本+ * 忽略(review P1)。+ */+export function commandNeedsRemoteSession(+ localCommand: MobileSystemCardType | null,+ desktopCommand: { name: string } | null,+): boolean {+ if (desktopCommand) return true;+ return localCommand !== null && MOBILE_REMOTE_BACKED_LOCAL_COMMANDS.has(localCommand);+}+export function mergeMobileLocalSlashCommands(remoteCommands: readonly MobileSlashCommand[],): MobileSlashCommand[] {diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.tsindex 879b63ec00..e26e5123a9 100644--- a/apps/mobile/src/session/useMobileLocalAttachments.ts+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts@@ -121,6 +121,14 @@ export interface UseMobileLocalAttachmentsResult {* onUploaded / onError 的 localId 路由。快照与 claim 同一同步段完成,无竞态窗。*/claimActiveUploads: () => ReturnType<MobileLocalAttachmentUploadController['claimableTasks']>;+ /**+ * claimActiveUploads 的逆操作:把一批已划归乐观消息的上传任务交还托盘。+ *+ * 乐观消息被收回成草稿时用(创建失败交还待发消息):任务继续跑,落定后宿主的+ * outbox 路由找不到归属条目、产物回落托盘。取消重传是错的——用户已经等过一次+ * 上传,粘贴来源的本地文件此时可能已被回收,重选都做不到(review P1)。+ */+ releaseClaimedUploads: (localIds: readonly string[]) => void;/** 只等粘贴占位落定(兑现任务已入队 / 失败 / 超时),不等上传完成;详见实现处注释。 */waitForPastePlaceholdersSettled: () => Promise<void>;/** 是否有粘贴占位在途(同步真源):占位兑现前任务尚未入队、无法 claim。 */@@ -480,6 +488,7 @@ export function useMobileLocalAttachments(controller.claim(snapshot.map((task) => task.localId));return snapshot;},+ releaseClaimedUploads: controller.unclaim,// 只等粘贴占位落定(兑现的同步段任务已入 controller 队列),不等上传本身:// 乐观发送(outbox)在占位窗口内需要它把「尚未入队、无法划归」的粘贴图等成// 可划归任务,再做同步 claim——不能用 waitForPendingUploads(那会退化回