Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): roll back enqueues without remote evidence (#2260)
tiammomo2c66b2d3c618
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 0307ae5948..ec467b772f 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -4054,10 +4054,12 @@ export default function SessionScreen() {const creationPendingClientId = creationTask?.status === 'running'? creationTask.firstMessageClientId: null;- if (!creationPendingClientId || sendingQueueClientIds.has(creationPendingClientId)) {- return sendingQueueClientIds;+ const sending = new Set(sendingQueueClientIds);+ if (!creationPendingClientId || sending.has(creationPendingClientId)) {+ return sending;}- return new Set([...sendingQueueClientIds, creationPendingClientId]);+ sending.add(creationPendingClientId);+ return sending;}, [creationTask, sendingQueueClientIds]);// 已读回执:liveActivity **签名变化且 attention=true**(会话开着时新 turn 完成翻@@ -5614,6 +5616,27 @@ export default function SessionScreen() {}};+ const readAuthoritativeEnqueueAcceptance = async (targetSessionId: string, clientId: string,+ expectedRemoteEpoch: number) => {+ try {+ const expectedAuthorityEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch(targetSessionId);+ const queryRemoteEpoch = remoteSessionStore.captureInputProjectionRemoteEpoch(targetSessionId);+ const fresh = await maker.input.getProjection(targetSessionId);+ const accepted = fresh.pendingQueue.some((item) => item.clientId === clientId)+ || remoteSessionStore.hasAuthoritativeQueuedItemSince(+ targetSessionId,+ clientId,+ expectedRemoteEpoch,+ );+ remoteSessionStore.setInputProjectionIfCurrent(+ targetSessionId, fresh, expectedAuthorityEpoch, queryRemoteEpoch, accepted ? clientId : undefined,+ );+ return accepted;+ } catch {+ return remoteSessionStore.hasAuthoritativeQueuedItemSince(targetSessionId, clientId, expectedRemoteEpoch);+ }+ };+/*** 派发一条就绪的 outbox 条目:构建 queued(权限档用发送时刻快照,model / effort* 等跟随会话最新值)→ 乐观进本地 pendingQueue(待发气泡原位变为排队气泡,同帧@@ -5700,7 +5723,7 @@ export default function SessionScreen() {// 乐观交接:进本地 pendingQueue 的同一同步段把条目移出 outbox,气泡原位从// 「发送中」变「排队中」不闪断;enqueue 成功后用权威 projection 覆盖 reconcile。const projectionBeforeSend = remoteSessionStore.getInputProjection(item.sessionId);- remoteSessionStore.setInputProjection(item.sessionId, {+ remoteSessionStore.setInputProjectionOptimistically(item.sessionId, {...projectionBeforeSend,sessionId: projectionBeforeSend.sessionId || item.sessionId,pendingQueue: [...projectionBeforeSend.pendingQueue, queued],@@ -5717,10 +5740,12 @@ export default function SessionScreen() {// outbox 气泡本来就在转圈:交接进 pendingQueue 后 enqueue 仍在途,徽标继续转圈,// 不要在这一帧闪成排队 icon 再回来(也不能谎报「已入队」)。markQueueItemSending(queued.clientId);+ const projectionRemoteEpochAtRequestStart =+ remoteSessionStore.captureInputProjectionRemoteEpoch(item.sessionId);+ const projectionEpochAtRequestStart =+ remoteSessionStore.captureInputProjectionAuthorityEpoch(item.sessionId);try {// 弱网重试与写序边界同 send() 原路径(仅明确可安全重发的瞬时传输错误)。- const projectionEpochAtRequestStart =- remoteSessionStore.captureInputProjectionAuthorityEpoch(item.sessionId);let projection: InputProjection | undefined;for (let attempt = 0; ; attempt++) {try {@@ -5739,55 +5764,18 @@ export default function SessionScreen() {item.sessionId,projection,projectionEpochAtRequestStart,+ projectionRemoteEpochAtRequestStart,+ queued.clientId,);} catch (err) {// 与原路径同口径:先对账分辨「确实没应用」vs「已应用但响应丢了」。const safeToRetry = isSafelyUnsentOutboxEnqueueError(err);- const acceptanceUnknown = !safeToRetry && isAutoRecoveringRemoteError(err);- if (acceptanceUnknown) {- // 写请求已出、回执不确定时,fresh projection 不含 clientId 也不能证明没应用:- // 空闲 agent 可能已把消息从 pendingQueue 取进 active turn。只在 fresh 明确- // 含原 id 时吸收它;否则保留现有 optimistic projection,交给后续权威同步- // 收敛。这里绝不回 outbox / 草稿,避免离场后用新 id 重发造成重复执行。- try {- const projectionEpochAtRequestStart =- remoteSessionStore.captureInputProjectionAuthorityEpoch(item.sessionId);- const fresh = await maker.input.getProjection(item.sessionId);- if (fresh.pendingQueue.some((entry) => entry.clientId === queued.clientId)) {- remoteSessionStore.setInputProjectionIfCurrent(- item.sessionId,- fresh,- projectionEpochAtRequestStart,- );- }- } catch {- // 自动恢复同步会继续收敛;当前 optimistic clientId 仍是唯一 Mobile owner。- }- if (outboxSessionAliveRef.current === item.sessionId) {- setError(formatRemoteError(err));- }- return;- }- const applied = await (async () => {- try {- const projectionEpochAtRequestStart =- remoteSessionStore.captureInputProjectionAuthorityEpoch(item.sessionId);- const fresh = await maker.input.getProjection(item.sessionId);- remoteSessionStore.setInputProjectionIfCurrent(- item.sessionId,- fresh,- projectionEpochAtRequestStart,- );- // safeToRetry 时 fresh 是同 clientId 先前重试是否已经生效的唯一证据;本地- // optimistic pendingQueue 不能自证。确定性远端失败也沿用同一权威口径。- return fresh.pendingQueue.some((entry) => entry.clientId === queued.clientId);- } catch {- return false;- }- })();- if (!applied) {+ const accepted = await readAuthoritativeEnqueueAcceptance(+ item.sessionId, queued.clientId, projectionRemoteEpochAtRequestStart,+ );+ if (!accepted) {const current = remoteSessionStore.getInputProjection(item.sessionId);- remoteSessionStore.setInputProjection(item.sessionId, {+ remoteSessionStore.setInputProjectionOptimistically(item.sessionId, {...current,pendingQueue: current.pendingQueue.filter((entry) => entry.clientId !== queued.clientId),});@@ -5797,7 +5785,6 @@ export default function SessionScreen() {}failItem(formatRemoteError(err));}- // applied:消息已在桌面队列,按成功继续(不回滚、不报错)。} finally {// 入队确认、回 outbox / 失败,或转交 optimistic projection 等待权威同步后,// 都不再是当前 RPC 在途;收掉 sending 标记,避免后续同 id 气泡悬空转圈。@@ -6733,7 +6720,7 @@ export default function SessionScreen() {// previews / mediaAssetAttachments 映射保留到成功后再清:它们不入消息体,失败// 恢复 attachments 时缩略图能原样回来。const projectionBeforeSend = remoteSessionStore.getInputProjection(sessionId);- remoteSessionStore.setInputProjection(sessionId, {+ remoteSessionStore.setInputProjectionOptimistically(sessionId, {...projectionBeforeSend,sessionId: projectionBeforeSend.sessionId || sessionId,pendingQueue: [...projectionBeforeSend.pendingQueue, queued],@@ -6746,23 +6733,21 @@ export default function SessionScreen() {// 乐观气泡此刻还没有「已入队」这个事实:徽标先给转圈,enqueue 落定后才交给// 排队 icon(或随回滚一起消失)。markQueueItemSending(queued.clientId);+ const projectionRemoteEpochAtRequestStart =+ remoteSessionStore.captureInputProjectionRemoteEpoch(sessionId);setAttachments([]);attachmentsRef.current = [];// 标注再编辑真相(矢量笔迹 + 原图副本)不在乐观段清:enqueue 失败回滚恢复// 托盘后,标注附件必须还能继续编辑/撤销(review P2);成功收尾按本批精确清。setAttachmentError(null);requestMessageListFollowLatest();+ const projectionEpochAtRequestStart =+ remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);try {// 弱网重试:切基站 / 短暂断连时自动补发,不让用户为一次抖动手动重发。// 写序边界(codex review P1 + auto-review P1):只有「保证未发出」的// NOT_CONNECTED 仅在 inFlight 未置位时允许自动重发——// in-flight 被断连批量 reject 的 NOT_CONNECTED 可能已送达(ack 丢失),- // 且 projection 无法证明未入队(空闲 agent 下消息瞬间进 activeTurn、- // 不在 pendingQueue 里),盲重会双入队;这类歧义失败直接交给下方 catch- // 的回滚/报错路径。BACKPRESSURE 在本地发送前或被控端 admission 拒绝- // 执行时产生,可安全重发。被控端 enqueue 侧另有 clientId 幂等去重兜底。- const projectionEpochAtRequestStart =- remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);let projection: InputProjection | undefined;for (let attempt = 0; ; attempt++) {try {@@ -6781,36 +6766,21 @@ export default function SessionScreen() {sessionId,projection,projectionEpochAtRequestStart,+ projectionRemoteEpochAtRequestStart,+ queued.clientId,);} catch (err) {- // 回滚前先分辨「确实没应用」vs「已应用但响应丢了」:弱网下 enqueue 的 invoke- // 响应可能超时丢失而桌面端已入队——此时摘除气泡会让手机隐藏一条桌面将处理的- // 消息,用户重发即重复(codex review R19)。优先 refetch 权威 projection 判断,- // refetch 也失败再退回本地 store(订阅推送在此窗口内可能已带回该 clientId)。- const applied = await (async () => {- try {- const projectionEpochAtRequestStart =- remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);- const fresh = await maker.input.getProjection(sessionId);- const accepted = remoteSessionStore.setInputProjectionIfCurrent(- sessionId,- fresh,- projectionEpochAtRequestStart,- );- // If a newer push/terminal boundary won the fence, the fetched value is- // stale for both the mirror and the applied decision; consult current state.- const current = accepted ? fresh : remoteSessionStore.getInputProjection(sessionId);- return current.pendingQueue.some((item) => item.clientId === queued.clientId);- } catch {- return remoteSessionStore.getInputProjection(sessionId).pendingQueue- .some((item) => item.clientId === queued.clientId);- }- })();- if (!applied) {+ // 回滚前先分辨「确实没应用」vs「已应用但响应丢了」:优先 refetch 权威+ // projection 判断。只有权威证据能保留乐观气泡;证据不可用时回到现有+ // 可重试失败路径,避免留下没有持久 owner 的永久转圈条目。+ const accepted = await readAuthoritativeEnqueueAcceptance(+ sessionId, queued.clientId, projectionRemoteEpochAtRequestStart,+ );+ if (!accepted) {// 回滚:按 clientId 精确摘除乐观气泡(期间 projection 可能已被其他事件更新,// 不能整体还原快照),并恢复草稿与附件托盘。const current = remoteSessionStore.getInputProjection(sessionId);- remoteSessionStore.setInputProjection(sessionId, {+ remoteSessionStore.setInputProjectionOptimistically(sessionId, {...current,pendingQueue: current.pendingQueue.filter((item) => item.clientId !== queued.clientId),});@@ -6827,8 +6797,6 @@ export default function SessionScreen() {restoreDirectSendDraftAfterFailure();throw err;}- // applied:消息已在桌面队列(权威 / 推送 projection 已含该 clientId),- // 按成功继续——不回滚、不报错,后续收尾(plan 恢复 / 映射清理)照常执行。} finally {// 成功、对账认定已入队、回滚 throw 三条路径都算「不再在途」:转圈必须收掉,// 否则回滚后集合残留、同 clientId 重发时首帧仍是转圈。@@ -6917,7 +6885,7 @@ export default function SessionScreen() {if (queueBusy) return;setQueueBusy(true);if (!outboxConnectionDispatchBlocked) setError(null);- remoteSessionStore.setInputProjection(+ remoteSessionStore.setInputProjectionOptimistically(sessionId,opts.optimistic(remoteSessionStore.getInputProjection(sessionId)),);@@ -6929,7 +6897,7 @@ export default function SessionScreen() {applyProjectionIfCurrent(result, projectionEpochAtRequestStart);}} catch (err) {- remoteSessionStore.setInputProjection(+ remoteSessionStore.setInputProjectionOptimistically(sessionId,opts.rollback(remoteSessionStore.getInputProjection(sessionId)),);diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex 03f2c513b7..dfd13e2840 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -228,35 +228,28 @@ describe('mobile optimistic composer while session is not ready', () => {const source = readSource(SCREEN);const outboxStart = source.indexOf('const dispatchOutboxItem = async (item: MobileOutboxItem) => {');const directStart = source.indexOf('const queuedDraft = buildQueuedTextMessage(');- const directEnd = source.indexOf('// applied:消息已在桌面队列', directStart);+ const directEnd = source.indexOf('// 消息已由 A 路径落定', directStart);const outboxDispatch = source.slice(outboxStart, directStart);const directRecovery = source.slice(directStart, directEnd);- const unknownStart = outboxDispatch.indexOf('if (acceptanceUnknown) {');- const unknownEnd = outboxDispatch.indexOf('const applied = await', unknownStart);- const acceptanceUnknownRecovery = outboxDispatch.slice(unknownStart, unknownEnd);expect(source).toContain('const waitForConnection = (');expect(source).toContain('const waiting = outboxItemWaitingForConnection(item);');expect(source).toContain("if (result === 'deferred' || result === 'stopped') return;");expect(source).toContain("return 'stopped' as const;");expect(source).toContain('const safeToRetry = isSafelyUnsentOutboxEnqueueError(err);');- expect(source).toContain(- 'const acceptanceUnknown = !safeToRetry && isAutoRecoveringRemoteError(err);',- );expect(source).toContain('if (safeToRetry) {\n waitForConnection(err);');- // 回执不确定时只保留原 optimistic projection,不能把已开始写的消息重新交给- // page-local outbox / 草稿;后者离场时没有跨页 clientId owner。- expect(acceptanceUnknownRecovery).toContain('fresh.pendingQueue.some(');- expect(acceptanceUnknownRecovery).toContain('setError(formatRemoteError(err));');- expect(acceptanceUnknownRecovery).not.toContain('failItem(');- expect(acceptanceUnknownRecovery).not.toContain('waitForConnection(');- expect(acceptanceUnknownRecovery).not.toContain('salvageOutboxItem(');- expect(outboxDispatch).toContain('return fresh.pendingQueue.some(');+ // 只有权威 projection / 已持久 user 行能证明已接收。没有权威证据时,outbox+ // 回到既有失败/重试 owner,直发恢复草稿,不能留下无持久 owner 的转圈行。+ expect(source).toContain('const accepted = fresh.pendingQueue.some(');+ expect(outboxDispatch).toContain('failItem(formatRemoteError(err));');+ expect(outboxDispatch).not.toContain('acceptanceUnknown');expect(source).not.toContain('shouldWaitForOutboxEnqueueRecovery');expect(source).toContain('isAutoRecoveringSessionReferencePreparationError(err)');expect(directRecovery).not.toContain('buildOutboxItem({');expect(directRecovery).not.toContain('salvageOutboxItem(');expect(directRecovery).not.toContain('updateOutbox(');+ expect(directRecovery).not.toContain('acceptanceUnknown');+ expect(directRecovery).toContain('restoreDirectSendDraftAfterFailure();');expect(directRecovery).toContain('在线直发一旦开始 enqueue 就不再转入本 PR 的页面 outbox');});diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 82d80745ea..cdf5b3e254 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -3031,6 +3031,53 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.getInputProjection('s1').pendingQueue[0]?.clientId).toBe('q-1');});+ it('keeps optimistic projection writes out of remote acceptance evidence', () => {+ const local = projection('s1', 'q-local');+ const authorityEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');+ const remoteEpoch = remoteSessionStore.captureInputProjectionRemoteEpoch('s1');+ remoteSessionStore.setInputProjectionOptimistically('s1', { ...local, queuePaused: true });+ expect(remoteSessionStore.captureInputProjectionAuthorityEpoch('s1')).not.toBe(authorityEpoch);+ expect(remoteSessionStore.captureInputProjectionRemoteEpoch('s1')).toBe(remoteEpoch);+ expect(remoteSessionStore.hasAuthoritativeQueuedItemSince('s1', 'q-local', remoteEpoch)).toBe(false);+ expect(remoteSessionStore.setInputProjectionIfCurrent('s1', local, authorityEpoch, remoteEpoch)).toBe(false);+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue[0]?.clientId).toBe('q-local');++ remoteSessionStore.setInputProjection('s1', local);+ expect(remoteSessionStore.hasAuthoritativeQueuedItemSince('s1', 'q-local', remoteEpoch)).toBe(true);+ });++ it('records accepted evidence from a stale response without overwriting a newer projection', () => {+ const expectedEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');+ const expectedRemoteEpoch = remoteSessionStore.captureInputProjectionRemoteEpoch('s1');+ remoteSessionStore.setInputProjection('s1', projection('s1', 'q-new'));++ expect(remoteSessionStore.setInputProjectionIfCurrent(+ 's1',+ projection('s1', 'q-old'),+ expectedEpoch,+ expectedRemoteEpoch,+ 'q-accepted',+ )).toBe(false);+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue[0]?.clientId).toBe('q-new');+ expect(remoteSessionStore.hasAuthoritativeQueuedItemSince(+ 's1',+ 'q-accepted',+ expectedRemoteEpoch,+ )).toBe(true);+ });++ it('settles a local optimistic row when its persisted user message arrives', () => {+ const local = projection('s1', 'q-local');+ const remoteEpoch = remoteSessionStore.captureInputProjectionRemoteEpoch('s1');+ remoteSessionStore.setInputProjectionOptimistically('s1', local);+ remoteSessionStore.appendMessage('s1', message('q-local', 's1'));+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toHaveLength(1);++ remoteSessionStore.appendMessage('s1', { ...message('q-local', 's1'), role: 'user' });+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);+ expect(remoteSessionStore.hasAuthoritativeQueuedItemSince('s1', 'q-local', remoteEpoch)).toBe(true);+ });+it('clears a continuation owner at a terminal boundary without a projection clear push', () => {const ownerProjection = {...projection('s1'),@@ -3039,6 +3086,7 @@ describe('remoteSessionStore', () => {remoteSessionStore.setInputProjection('s1', ownerProjection);remoteSessionStore.setSessionRunning('s1', true);const operationEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');+ const operationRemoteEpoch = remoteSessionStore.captureInputProjectionRemoteEpoch('s1');remoteSessionStore.applyRemotePush('dev-1', 'maker:status-changed', {sessionId: 's1',@@ -3047,7 +3095,9 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.getInputProjection('s1').continuationTurnClientId).toBeNull();expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(false);- expect(remoteSessionStore.setInputProjectionIfCurrent('s1', ownerProjection, operationEpoch)).toBe(false);+ expect(remoteSessionStore.setInputProjectionIfCurrent('s1', { ...ownerProjection, pendingQueue: [] }, operationEpoch, operationRemoteEpoch, 'q-1')).toBe(false);+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue[0]?.clientId).toBe('q-1');+ expect(remoteSessionStore.hasAuthoritativeQueuedItemSince('s1', 'q-1', operationRemoteEpoch)).toBe(true);});it('soft-invalidates an offline device without deleting sessions or messages', () => {diff --git a/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts b/apps/mobile/src/__tests__/sendEnqueueRetry.test.tsindex 47c546ca68..07e91f6692 100644--- a/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts+++ b/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts@@ -9,8 +9,6 @@ import { describe, expect, it } from 'vitest';* - BACKPRESSURE 要么在本地发送前拒绝,要么由被控端 admission 明确拒绝执行;* - projection 也无法证明未入队——空闲 agent 下 enqueue-immediate 会把消息瞬间* slice 进 activeTurn,pendingQueue 里查不到;- * 因此自动重发只允许发生在「保证未发出」的失败上(inFlight 未置位),in-flight- * 歧义失败一律交回滚路径;被控端 enqueue 另有 clientId 幂等去重兜底。*/describe('send enqueue weak-network retry ordering', () => {const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');@@ -24,7 +22,7 @@ describe('send enqueue weak-network retry ordering', () => {const extractRetryLoops = (): string[] => {const loops: string[] = [];for (let from = source.indexOf(LOOP_MARKER); from > -1; from = source.indexOf(LOOP_MARKER, from + 1)) {- const endMatch = /remoteSessionStore\.setInputProjection(?:IfCurrent)?\(\s*[^,]+,\s*projection(?:,\s*projectionEpochAtRequestStart)?\s*,?\s*\);/.exec(source.slice(from));+ const endMatch = /remoteSessionStore\.setInputProjectionIfCurrent\(\s*[^,]+,\s*projection,\s*projectionEpochAtRequestStart,\s*projectionRemoteEpochAtRequestStart,\s*queued\.clientId,\s*\);/.exec(source.slice(from));expect(endMatch).not.toBeNull();loops.push(source.slice(from, from + (endMatch?.index ?? 0)));}diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.tsindex b223ff11a7..ad883a6379 100644--- a/apps/mobile/src/session/newSessionCreation.ts+++ b/apps/mobile/src/session/newSessionCreation.ts@@ -279,7 +279,7 @@ export function startNewSessionCreation(params: NewSessionCreationParams): voidfirstMessageClientId,{ attachments: [...params.attachments] },), firstMessageSessionRefs);- remoteSessionStore.setInputProjection(params.sessionId, buildOptimisticProjection(params.sessionId, queued));+ remoteSessionStore.setInputProjectionOptimistically(params.sessionId, buildOptimisticProjection(params.sessionId, queued));const task: InternalTask = {sessionId: params.sessionId,deviceId: params.deviceId,@@ -326,7 +326,7 @@ export function retryNewSessionCreation(sessionId: string): void {task.firstMessageClientId,{ attachments: [...task.attachments] },), task.firstMessageSessionRefs);- remoteSessionStore.setInputProjection(sessionId, buildOptimisticProjection(sessionId, queued));+ remoteSessionStore.setInputProjectionOptimistically(sessionId, buildOptimisticProjection(sessionId, queued));emit();void runPipeline(task);}@@ -342,7 +342,7 @@ export function dismissNewSessionCreation(sessionId: string, opts: { removeSynthtasks.delete(sessionId);if (opts.removeSyntheticRow) {remoteSessionStore.applySessionPatch(task.deviceId, sessionId, { status: 'deleted' });- remoteSessionStore.setInputProjection(sessionId, null);+ remoteSessionStore.setInputProjectionOptimistically(sessionId, null);remoteSessionStore.clearPendingTitlePreview(sessionId);}emit();@@ -568,7 +568,7 @@ function failTask(task: InternalTask, status: 'create-failed' | 'enqueue-failed'// 回填 composer,用户走正常发送);同时清掉合成行的 pendingLocalCreation// 禁发标——弱网下 fresh getSession / 会话页 load 可能都还没成功,不清的话// 用户拿着回填草稿仍被禁发,只能干等 load(codex review P2)。- remoteSessionStore.setInputProjection(task.sessionId, null);+ remoteSessionStore.setInputProjectionOptimistically(task.sessionId, null);remoteSessionStore.clearPendingTitlePreview(task.sessionId);remoteSessionStore.applySessionPatch(task.deviceId, task.sessionId, {pendingLocalCreation: false,@@ -869,7 +869,7 @@ function cancelStaleOwnerTask(task: InternalTask): void {);if (session && remoteSessionStore.getSessionDeviceId(task.sessionId) === task.deviceId) {remoteSessionStore.applySessionPatch(task.deviceId, task.sessionId, { status: 'deleted' });- remoteSessionStore.setInputProjection(task.sessionId, null);+ remoteSessionStore.setInputProjectionOptimistically(task.sessionId, null);remoteSessionStore.clearPendingTitlePreview(task.sessionId);}emit();diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.tsindex f74d39099e..cd04467a2a 100644--- a/apps/mobile/src/session/pendingSendItems.ts+++ b/apps/mobile/src/session/pendingSendItems.ts@@ -247,7 +247,8 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobileinput.queue.forEach((item, index) => {const phase: MobilePendingSendPhase = input.editingClientId === item.clientId? 'editing'- : input.steeringClientIds.has(item.clientId) || input.sendingClientIds.has(item.clientId)+ : input.steeringClientIds.has(item.clientId)+ || input.sendingClientIds.has(item.clientId)? 'sending': 'queued';pushQueued(item, phase, index + 1);diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex ace7b8179e..a8a00e3143 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -306,6 +306,11 @@ const pendingTitlePreview = new Map<string, string>();const inputProjectionAuthorityEpochs = new Map<string, number>();let nextInputProjectionAuthorityEpoch = 0;let inputProjectionAuthorityEpochFloor = 0;+const inputProjectionRemoteEpochs = new Map<string, number>();+let nextInputProjectionRemoteEpoch = 0;+let inputProjectionRemoteEpochFloor = 0;+const inputProjectionRemoteQueuedEvidence = new Map<string, Map<string, number>>();+const INPUT_PROJECTION_REMOTE_EVIDENCE_LIMIT = 256;const sessionLiveActivity = new Map<string, RemoteSessionLiveActivity>();const sessionRunning = new Map<string, boolean>();const sessionRunStatus = new Map<string, RemoteSessionRunStatus>();@@ -615,7 +620,6 @@ const subs = new Set<() => void>();const emptyMessages: RemoteMessage[] = [];const emptyPendingInteractions: PendingInteraction[] = [];const EMPTY_TASK_UPDATES: ReadonlyMap<string, AgentTaskUpdate> = new Map();-const REGULAR_SESSION_GLOBAL_MESSAGE_BUDGET = 800;const REGULAR_SESSION_GLOBAL_MESSAGE_BYTES_BUDGET = 64 * 1024 * 1024;const MESSAGE_STRUCTURAL_BYTES_ESTIMATE = 512;@@ -762,6 +766,8 @@ function removeSessionRuntimeState(sessionId: string): void {pendingInteractions.delete(sessionId);pendingInteractionsAuthoritative.delete(sessionId);inputProjections.delete(sessionId);+ inputProjectionRemoteEpochs.delete(sessionId);+ inputProjectionRemoteQueuedEvidence.delete(sessionId);bumpInputProjectionAuthorityEpoch(sessionId);sessionLiveActivity.delete(sessionId);sessionRunning.delete(sessionId);@@ -1049,6 +1055,52 @@ function bumpInputProjectionAuthorityEpoch(sessionId: string): number {return epoch;}+function recordInputProjectionRemoteEvidence(sessionId: string, clientIds: Iterable<string>, settled = false): void {+ const epoch = ++nextInputProjectionRemoteEpoch;+ inputProjectionRemoteEpochs.set(sessionId, epoch);+ let evidence = inputProjectionRemoteQueuedEvidence.get(sessionId);+ for (const clientId of clientIds) {+ inputProjectionRemoteQueuedEvidence.set(sessionId, evidence ??= new Map<string, number>());+ evidence.delete(clientId);+ evidence.set(clientId, settled ? -epoch : epoch);+ }+ while (evidence && evidence.size > INPUT_PROJECTION_REMOTE_EVIDENCE_LIMIT) evidence.delete(evidence.keys().next().value!);+}++function settleInputProjectionClientIds(+ sessionId: string,+ settledClientIds: ReadonlySet<string>,+): boolean {+ if (settledClientIds.size === 0) return false;+ recordInputProjectionRemoteEvidence(sessionId, settledClientIds, true);+ const current = inputProjections.get(sessionId);+ const pendingQueue = current?.pendingQueue.filter(+ (item) => !settledClientIds.has(item.clientId),+ );+ const projectionChanged = Boolean(current && pendingQueue?.length !== current.pendingQueue.length);+ if (!projectionChanged || !current || !pendingQueue) return false;+ inputProjections.set(sessionId, { ...current, pendingQueue });+ bumpInputProjectionAuthorityEpoch(sessionId);+ return true;+}++function settleInputProjectionFromMessages(+ sessionId: string, list: readonly RemoteMessage[],+): boolean {+ const tracked = new Set(inputProjections.get(sessionId)?.pendingQueue.map((item) => item.clientId) ?? []);+ for (const [clientId, epoch] of inputProjectionRemoteQueuedEvidence.get(sessionId) ?? []) if (epoch > 0) tracked.add(clientId);+ if (tracked.size === 0) return false;+ const settled = new Set(list+ .filter((message) => message.role === 'user' && tracked.has(message.clientId))+ .map((message) => message.clientId));+ return settleInputProjectionClientIds(sessionId, settled);+}++function invalidateInputProjectionForOffline(sessionId: string): boolean {+ recordInputProjectionRemoteEvidence(sessionId, []);+ return inputProjections.delete(sessionId);+}+function commitInputProjection(sessionId: string, next: InputProjection): boolean {if (deepValueEqual(inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION, next)) {if (next.pendingQueue.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);@@ -2755,13 +2807,14 @@ export const remoteSessionStore = {if (!messageWriteAllowed(sessionId, options.authority)) return;const textFlushed = flushPendingTextDelta(sessionId);const next = normalizeWindowForRetention(sessionId, normalizeMessages(list));+ const projectionSettled = settleInputProjectionFromMessages(sessionId, next);// 记账在相等早退**之前**:这一页是服务端一次给出的连续段,它带来的连续性结论与"窗口内容有没有// 变"无关。冷开缓存恰好与服务端最新页逐行相同时(常态)若被早退跳过,这次权威响应就白来了 ——// 之后会话涨过一页、再遇一次满页重连刷新,本可保留的历史会被当成来源不明全丢(#1210 review)。coverReplacedWindow(sessionId, next);if (next.length === 0) clearSessionMessageCache(sessionId);if (remoteMessageListsEqual(messages.get(sessionId) ?? emptyMessages, next)) {- if (textFlushed) emit();+ if (textFlushed || projectionSettled) emit();return;}messages.set(sessionId, next);@@ -2804,6 +2857,7 @@ export const remoteSessionStore = {if (!messageWriteAllowed(sessionId, options.authority)) return;const textFlushed = flushPendingTextDelta(sessionId);const latestWindow = normalizeWindowForRetention(sessionId, normalizeMessages(list));+ const projectionSettled = settleInputProjectionFromMessages(sessionId, latestWindow);if (latestWindow.length === 0) {// 空窗口仍需保留本地系统卡(mobile-system-*):新会话首条消息发出后服务端// 消息列表可能仍为空,下一次 setLatestMessageWindow 传空数组不能把刚追加的@@ -2812,7 +2866,7 @@ export const remoteSessionStore = {// A live assistant row is not yet represented in the DB window. Do not erase it// while the persistence push is still in flight.if (hasLiveAssistantMessage(sessionId)) {- if (textFlushed) emit();+ if (textFlushed || projectionSettled) emit();return;}const preserved = existing.filter((item) => messageKey(item).startsWith('mobile-system-'));@@ -2825,7 +2879,7 @@ export const remoteSessionStore = {if (next.length === 0) clearSessionMessageCache(sessionId);bumpMessageVersion();emit();- } else if (textFlushed) {+ } else if (textFlushed || projectionSettled) {emit();}return;@@ -3031,6 +3085,7 @@ export const remoteSessionStore = {): void {if (!messageWriteAllowed(sessionId, options.authority)) return;const textFlushed = flushPendingTextDelta(sessionId);+ const projectionSettled = settleInputProjectionFromMessages(sessionId, list);const byKey = new Map<string, RemoteMessage>();for (const item of messages.get(sessionId) ?? []) {byKey.set(messageKey(item), item);@@ -3054,7 +3109,7 @@ export const remoteSessionStore = {}const next = normalizeWindowForRetention(sessionId, normalizeMessages([...byKey.values()]));if (remoteMessageListsEqual(messages.get(sessionId) ?? emptyMessages, next)) {- if (textFlushed) emit();+ if (textFlushed || projectionSettled) emit();return;}messages.set(sessionId, next);@@ -3093,6 +3148,7 @@ export const remoteSessionStore = {): void {if (!messageWriteAllowed(sessionId, options.authority)) return;let changed = flushPendingTextDelta(sessionId);+ changed = settleInputProjectionFromMessages(sessionId, [message]) || changed;const reanchorAfterMessage = options.hostTimeAuthoritative !== false && message.role === 'user';const userCanReanchorPendingLiveReply = reanchorAfterMessage&& userMessageCanConsumePendingLiveReply(sessionId, message);@@ -3161,6 +3217,10 @@ export const remoteSessionStore = {removeMessages(sessionId: string, clientIds: readonly string[], deviceId?: string): void {const deletedClientIds = new Set(clientIds.filter(Boolean));if (!sessionId || deletedClientIds.size === 0) return;+ const tracked = new Set(inputProjections.get(sessionId)?.pendingQueue.map((item) => item.clientId) ?? []);+ for (const [clientId, epoch] of inputProjectionRemoteQueuedEvidence.get(sessionId) ?? []) if (epoch > 0) tracked.add(clientId);+ const settled = new Set([...deletedClientIds].filter((clientId) => tracked.has(clientId)));+ const projectionSettled = settleInputProjectionClientIds(sessionId, settled);const existing = messages.get(sessionId) ?? emptyMessages;const removed = existing.filter((message) => (deletedClientIds.has(message.clientId) || deletedClientIds.has(message.id)@@ -3219,7 +3279,7 @@ export const remoteSessionStore = {if (messagesChanged) {applyMessageWriteRetention(sessionId);}- if (!messagesChanged && !tasksChanged) return;+ if (!messagesChanged && !tasksChanged && !projectionSettled) return;bumpMessageVersion();emit();},@@ -3316,6 +3376,14 @@ export const remoteSessionStore = {},setInputProjection(sessionId: string, projection: unknown): void {+ const next = normalizeInputProjection(projection, sessionId);+ bumpInputProjectionAuthorityEpoch(sessionId);+ recordInputProjectionRemoteEvidence(sessionId, next.pendingQueue.map((item) => item.clientId));+ commitInputProjection(sessionId, next);+ },++ /** Apply local UI state without claiming that the controlled device accepted it. */+ setInputProjectionOptimistically(sessionId: string, projection: unknown): void {const next = normalizeInputProjection(projection, sessionId);bumpInputProjectionAuthorityEpoch(sessionId);commitInputProjection(sessionId, next);@@ -3325,16 +3393,36 @@ export const remoteSessionStore = {return inputProjectionAuthorityEpochs.get(sessionId) ?? inputProjectionAuthorityEpochFloor;},+ captureInputProjectionRemoteEpoch(sessionId: string): number {+ return inputProjectionRemoteEpochs.get(sessionId) ?? inputProjectionRemoteEpochFloor;+ },++ hasAuthoritativeQueuedItemSince(sessionId: string, clientId: string, expectedRemoteEpoch: number): boolean {+ return Math.abs(inputProjectionRemoteQueuedEvidence.get(sessionId)?.get(clientId) ?? 0)+ > expectedRemoteEpoch;+ },+setInputProjectionIfCurrent(sessionId: string,projection: unknown,expectedEpoch: number,+ expectedRemoteEpoch?: number,+ acceptedClientId?: string,): boolean {+ const remoteEpoch = inputProjectionRemoteEpochs.get(sessionId) ?? inputProjectionRemoteEpochFloor;const currentEpoch = inputProjectionAuthorityEpochs.get(sessionId) ?? inputProjectionAuthorityEpochFloor;- if (currentEpoch !== expectedEpoch) {+ const authorityStale = currentEpoch !== expectedEpoch;+ const remoteStale = expectedRemoteEpoch !== undefined && remoteEpoch !== expectedRemoteEpoch;+ if (authorityStale || remoteStale) {+ if (acceptedClientId) {+ recordInputProjectionRemoteEvidence(sessionId, [acceptedClientId]);+ }return false;}const next = normalizeInputProjection(projection, sessionId);+ const queuedClientIds = new Set(next.pendingQueue.map((item) => item.clientId));+ if (acceptedClientId) queuedClientIds.add(acceptedClientId);+ recordInputProjectionRemoteEvidence(sessionId, queuedClientIds);bumpInputProjectionAuthorityEpoch(sessionId);commitInputProjection(sessionId, next);return true;@@ -3350,6 +3438,7 @@ export const remoteSessionStore = {boundaryAgentMeta?: Record<string, unknown> | null,): void {if (!sessionId) return;+ recordInputProjectionRemoteEvidence(sessionId, []);// A maker turn boundary supersedes any projection query that started// before it. This is the terminal fence for late owner snapshots.bumpInputProjectionAuthorityEpoch(sessionId);@@ -4194,7 +4283,7 @@ export const remoteSessionStore = {changed = pendingInteractions.delete(sessionId) || changed;// 投影没了,这份(空)列表就不再权威:重连拿到全量快照前不许据此做清理。changed = pendingInteractionsAuthoritative.delete(sessionId) || changed;- changed = inputProjections.delete(sessionId) || changed;+ changed = invalidateInputProjectionForOffline(sessionId) || changed;bumpInputProjectionAuthorityEpoch(sessionId);changed = sessionLiveActivity.delete(sessionId) || changed;changed = sessionGoalStatus.delete(sessionId) || changed;@@ -4309,6 +4398,9 @@ export const remoteSessionStore = {inputProjections.clear();inputProjectionAuthorityEpochFloor = ++nextInputProjectionAuthorityEpoch;inputProjectionAuthorityEpochs.clear();+ inputProjectionRemoteEpochFloor = ++nextInputProjectionRemoteEpoch;+ inputProjectionRemoteEpochs.clear();+ inputProjectionRemoteQueuedEvidence.clear();// Keep authority tombstones monotonic across a global store reset so an// old in-flight query cannot be accepted after the session is recreated.sessionLiveActivity.clear();