Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(mobile): 治理任务消息内存驻留

david948769193910
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 42027d3e49..acdaf9c133 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -888,6 +888,55 @@ export default function SessionScreen() {
const visualSearchQuery = MOBILE_VISUAL_MOCK_ENABLED ? readRouteParam(params.visualSearchQuery) : null;
const navigation = useNavigation<SessionRouteParamsNavigation & { isFocused(): boolean }>();
const router = useRouter();
+ // 完整消息读取权限按「会话 + 单调代际」登记。focus 与 AppState 正交:后台时
+ // 导航仍可能保持 focused,必须立即撤权;重新聚焦/回前台会生成新代际,使旧
+ // listMessages 响应永久失效。
+ const messageAuthorityRef = useRef<ReturnType<
+ typeof remoteSessionStore.enterSessionMessageDetail
+ > | null>(null);
+ const messageScreenFocusedRef = useRef(false);
+ const messageAppActiveRef = useRef(AppState.currentState === 'active');
+ const lastEnteredMessageSessionRef = useRef<string | null>(null);
+ const handledMessageReloadRevisionRef = useRef(0);
+ const [messageReloadRevision, setMessageReloadRevision] = useState(0);
+ useFocusEffect(
+ useCallback(() => {
+ messageScreenFocusedRef.current = true;
+ if (messageAppActiveRef.current) {
+ const shouldReload = lastEnteredMessageSessionRef.current === sessionId;
+ messageAuthorityRef.current = remoteSessionStore.enterSessionMessageDetail(sessionId);
+ lastEnteredMessageSessionRef.current = sessionId;
+ if (shouldReload) setMessageReloadRevision((value) => value + 1);
+ }
+ return () => {
+ messageScreenFocusedRef.current = false;
+ const authority = messageAuthorityRef.current;
+ messageAuthorityRef.current = null;
+ if (authority) {
+ remoteSessionStore.leaveSessionMessageDetail(sessionId, 'detail-blur', authority);
+ }
+ };
+ }, [sessionId]),
+ );
+ useEffect(() => {
+ const subscription = AppState.addEventListener('change', (nextState) => {
+ const active = nextState === 'active';
+ messageAppActiveRef.current = active;
+ if (!active) {
+ const authority = messageAuthorityRef.current;
+ messageAuthorityRef.current = null;
+ if (authority) {
+ remoteSessionStore.leaveSessionMessageDetail(sessionId, 'app-background', authority);
+ }
+ return;
+ }
+ if (!messageScreenFocusedRef.current || messageAuthorityRef.current) return;
+ messageAuthorityRef.current = remoteSessionStore.enterSessionMessageDetail(sessionId);
+ lastEnteredMessageSessionRef.current = sessionId;
+ setMessageReloadRevision((value) => value + 1);
+ });
+ return () => subscription.remove();
+ }, [sessionId]);
const auth = useAuth();
const windowDimensions = useWindowDimensions();
const insets = useSafeAreaInsets();
@@ -907,6 +956,11 @@ export default function SessionScreen() {
const maker = useMobileMakerTransport(deviceId);
const sessions = useRemoteSessions();
const messages = useSessionMessages(sessionId, deviceId);
+ const sessionRetention = useSyncExternalStore(
+ remoteSessionStore.subscribe,
+ () => remoteSessionStore.getSessionRetention(sessionId),
+ );
+ const isScheduleDetail = sessionRetention === 'schedule';
const pending = useSessionPendingInteractions(sessionId);
// pending 列表是否已被被控端的全量快照确认过(空列表能不能当「都处理完了」用)。
const pendingInteractionsAuthoritative = useSessionPendingInteractionsAuthoritative(sessionId);
@@ -1443,6 +1497,29 @@ export default function SessionScreen() {
// 同步真源(上传回调 / 派发循环 / send 同步段都要读最新值),state 只驱动渲染。
const [outboxItems, setOutboxItems] = useState<readonly MobileOutboxItem[]>([]);
const outboxRef = useRef<readonly MobileOutboxItem[]>([]);
+ const pageMessageWorkLeaseRef = useRef<ReturnType<
+ typeof remoteSessionStore.acquireSessionMessageWork
+ > | null>(null);
+ const pageHasMessageWork = outboxItems.length > 0
+ || pendingUploads.length > 0
+ || pastePlaceholderCount > 0
+ || getPendingUploadCount() > 0
+ || sendInFlightRef.current
+ || sending
+ || sendingQueueClientIds.size > 0
+ || settlingQueueItems.length > 0
+ || attachments.length > 0;
+ useLayoutEffect(() => {
+ const lease = remoteSessionStore.acquireSessionMessageWork(sessionId, pageHasMessageWork);
+ pageMessageWorkLeaseRef.current = lease;
+ return () => {
+ if (pageMessageWorkLeaseRef.current === lease) pageMessageWorkLeaseRef.current = null;
+ lease.release();
+ };
+ }, [sessionId]);
+ useLayoutEffect(() => {
+ pageMessageWorkLeaseRef.current?.update(pageHasMessageWork);
+ }, [pageHasMessageWork]);
// 派发循环重入锁 + 路由函数的 ref 中转(onUploaded 闭包声明在组件前部,实际
// 路由/派发逻辑声明在 send() 附近,经 ref 断开声明顺序依赖,同 composerAnnotationsRef)。
const outboxPumpBusyRef = useRef(false);
@@ -3558,12 +3635,20 @@ export default function SessionScreen() {
});
return () => {
cancelled = true;
+ if (
+ loadedRouteFocusKeyRef.current === routeFocusKey
+ && appliedRouteFocusKeyRef.current !== routeFocusKey
+ ) loadedRouteFocusKeyRef.current = null;
};
}, [connectionEpoch, deviceId, lastSyncedAt, maker, openLink, sessionAgentSwitchSupported, sessionId]);
const syncSession = useCallback(async (syncRun: Pick<RemoteSyncRun, 'isStale' | 'replaceMessages'>) => {
const options = { replaceMessages: syncRun.replaceMessages };
if (!deviceId || !sessionId || syncRun.isStale()) return;
+ const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
+ const messageAuthorityCurrent = () =>
+ remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority);
+ if (!messageAuthorityCurrent()) return;
// 新建会话乐观管线在途(running / create-failed):被控端可能还没有这个会话,
// getSession 会 NOT_FOUND 报错横幅。统一在这里挡掉全部 load 触发点;管线完成
// (task 移除)后由下方 effect 触发一轮真正的同步。
@@ -3622,7 +3707,7 @@ export default function SessionScreen() {
fetchActiveSessionSnapshot(),
]);
});
- if (syncRun.isStale()) return;
+ if (syncRun.isStale() || !messageAuthorityCurrent()) return;
remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
remoteSessionStore.setActiveSessionSnapshots(
deviceId,
@@ -3637,9 +3722,12 @@ export default function SessionScreen() {
// 「加载更早」入口同源,两者本就该一致。
const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);
if (options.replaceMessages) {
- remoteSessionStore.setMessages(sessionId, historyPage);
+ remoteSessionStore.setMessages(sessionId, historyPage, { authority: messageAuthority });
} else {
- remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, { moreBeyondWindow });
+ remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, {
+ authority: messageAuthority,
+ moreBeyondWindow,
+ });
}
remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);
setHasOlderMessages(moreBeyondWindow);
@@ -3670,7 +3758,7 @@ export default function SessionScreen() {
messageWindowSynced: remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),
storedSession: storedSessionAtStart,
});
- if (syncRun.isStale()) return;
+ if (syncRun.isStale() || !messageAuthorityCurrent()) return;
remoteSessionStore.setActiveSessionSnapshots(
deviceId,
Array.isArray(activeSessionSnapshot.activeSessions)
@@ -3685,11 +3773,14 @@ export default function SessionScreen() {
REOPEN_MESSAGE_WINDOW_LIMITS,
),
);
- if (syncRun.isStale()) return;
+ if (syncRun.isStale() || !messageAuthorityCurrent()) return;
const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];
// 同首开路径:上沿之外还有历史时不保留更早的缓存段(#1222)。
const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);
- remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, { moreBeyondWindow });
+ remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, {
+ authority: messageAuthority,
+ moreBeyondWindow,
+ });
remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);
setHasOlderMessages(moreBeyondWindow);
} else {
@@ -3709,7 +3800,7 @@ export default function SessionScreen() {
// 不变量:上面 setHasOlderMessages 的校正(:806/:841/:846)与这里的 setLastSyncedAt 之间必须保持
// 同步尾、无 await —— 否则乐观点亮 effect(依赖 lastSyncedAt===null)会在 await 间隙把刚校正成 false
// 的「加载更早」入口重新点亮。将来切勿在两者之间插入 await。
- if (syncRun.isStale()) return;
+ if (syncRun.isStale() || !messageAuthorityCurrent()) return;
// 当前设备的权威 session + projection 同步已完整落定,才解除独立 transport hold。
// 不在 connectionEpoch 刚推进时提前清,避免同一 commit 的 outbox effect 抢在 resync 前派发。
setOutboxTransportHold((current) => current?.deviceId === deviceId ? null : current);
@@ -3721,7 +3812,7 @@ export default function SessionScreen() {
setReadAckSyncedKey(`${sessionId}:${readAckEpochAtStart}`);
}
} catch (err) {
- if (!syncRun.isStale()) {
+ if (!syncRun.isStale() && messageAuthorityCurrent()) {
const formatted = formatRemoteError(err);
setError(formatted);
// 两类失败都写入 hold 且不能清门:瞬态错误继续自动重试,确定性错误保留
@@ -3729,7 +3820,7 @@ export default function SessionScreen() {
latchOutboxTransportHold(formatted);
}
} finally {
- if (!syncRun.isStale()) setLoading(false);
+ if (!syncRun.isStale() && messageAuthorityCurrent()) setLoading(false);
}
}, [deviceId, deviceName, latchOutboxTransportHold, maker, openLink, sessionId, subscribe]);
// 任一连接恢复身份变化都会让旧读取失去提交资格。否则断线前启动的同步可能在
@@ -3750,6 +3841,13 @@ export default function SessionScreen() {
() => requestSync({ reason: 'passive-refresh' }),
[requestSync],
);
+ useEffect(() => {
+ if (messageReloadRevision === 0) return;
+ if (handledMessageReloadRevisionRef.current === messageReloadRevision) return;
+ if (!messageScreenFocusedRef.current || !messageAppActiveRef.current) return;
+ handledMessageReloadRevisionRef.current = messageReloadRevision;
+ void load();
+ }, [load, messageReloadRevision]);
/** 恢复路径里装不下的附件:中转对象回收,不留无人认领的已上传对象。 */
const discardRecoveredAttachments = (attachments: readonly RemoteSerializedAttachment[]) => {
@@ -4066,11 +4164,12 @@ export default function SessionScreen() {
// (lastSyncedAt 为空)、入口当前不可见、且 _count 已知且 > 已加载时乐观置 true;A1 / reopen 回来后仍按
// shouldKeepOlderMessagesAffordance / hasOlderMessagesAfterReopen 校正(:806/:846)。_count 未知不凭空点亮。
useEffect(() => {
+ if (isScheduleDetail) return;
if (lastSyncedAt !== null || hasOlderMessages || messages.length === 0) return;
if (hasOlderMessagesByServerCount(currentSession?._count?.messages, messages)) {
setHasOlderMessages(true);
}
- }, [currentSession?._count?.messages, hasOlderMessages, lastSyncedAt, messages]);
+ }, [currentSession?._count?.messages, hasOlderMessages, isScheduleDetail, lastSyncedAt, messages]);
// 在线时按 connectionEpoch 去重:每个连接 epoch 只 resync 一次。首开同步由上面的 mount effect 负责
// (此处 epoch == 初值 → skip);仅在 epoch 变化(真正重连 / 回前台 connectNow→online)时再 resync,
@@ -4468,12 +4567,20 @@ export default function SessionScreen() {
loadedRouteFocusKeyRef.current = routeFocusKey;
let cancelled = false;
+ const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
void withTransientRemoteRetry(() =>
maker.aroundMessagesByClientId(sessionId, routeFocusClientId, { radius: 60 }),
)
.then((list) => {
- if (cancelled) return;
- remoteSessionStore.mergeMessages(sessionId, Array.isArray(list) ? list : []);
+ if (
+ cancelled
+ || !remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)
+ ) return;
+ remoteSessionStore.mergeMessages(
+ sessionId,
+ Array.isArray(list) ? list : [],
+ { authority: messageAuthority },
+ );
if (!Array.isArray(list) || list.length === 0) {
setError(t('session.screen.locateMessageNotFound'));
return;
@@ -4482,7 +4589,10 @@ export default function SessionScreen() {
setRouteFocusedClientId(routeFocusClientId);
})
.catch((err) => {
- if (!cancelled) setError(formatRemoteError(err));
+ if (
+ !cancelled
+ && remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)
+ ) setError(formatRemoteError(err));
});
return () => {
@@ -4633,7 +4743,10 @@ export default function SessionScreen() {
}, [abandonInFlightBackfill, sessionId, connectionEpoch]);
const loadEarlierMessages = useCallback(async () => {
+ if (isScheduleDetail) return;
if (!deviceId || !sessionId || loadingEarlier || !hasOlderMessages) return;
+ const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
+ if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;
const before = oldestMessageCursor(messages);
if (!before) {
setHasOlderMessages(false);
@@ -4649,18 +4762,21 @@ export default function SessionScreen() {
const page = await withTransientRemoteRetry(() =>
listMessagesWithPayloadRetry((limit) => maker.listMessages(sessionId, { limit, before })),
);
+ if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;
const pageList = Array.isArray(page.messages) ? page.messages : [];
// 用 mergeEarlierMessages 而不是 mergeMessages:这一页是沿 before 从窗口最旧端**连续**取的,
// 登记进「已验证连续」区间后,后续满页的最新窗口同步才不会把用户一路翻出来的历史当成来源
// 不明的缓存丢掉(#1210 review)。
- remoteSessionStore.mergeEarlierMessages(sessionId, pageList);
+ remoteSessionStore.mergeEarlierMessages(sessionId, pageList, { authority: messageAuthority });
setHasOlderMessages(shouldKeepOlderMessagesAffordance(page));
} catch (err) {
- setError(formatRemoteError(err));
+ if (remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) {
+ setError(formatRemoteError(err));
+ }
} finally {
setLoadingEarlier(false);
}
- }, [abandonInFlightBackfill, deviceId, hasOlderMessages, loadingEarlier, maker, messages, sessionId]);
+ }, [abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, messages, sessionId]);
/**
* 历史窗口空洞的自动补齐(见 `historyWindowGap.ts` 的文件头)。
@@ -4710,6 +4826,7 @@ export default function SessionScreen() {
*/
const [backfillInFlightRun, setBackfillInFlightRun] = useState<{ sid: string; seq: number } | null>(null);
useEffect(() => {
+ if (isScheduleDetail) return;
if (!deviceId || !sessionId) return;
// 同步门槛必须按 **session + 连接代** 判定,不能用 lastSyncedAt:屏实例复用、原地从会话 A
// 切到有缓存消息的 B 时,lastSyncedAt 仍是 A 留下的非空值,补齐会在 B 的 listMessages 对账
@@ -4756,6 +4873,8 @@ export default function SessionScreen() {
const gapKey = historyWindowGapKey(gap);
const sessionIdAtStart = sessionId;
const epochAtStart = connectionEpoch;
+ const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionIdAtStart);
+ if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;
// 本轮的身份:单调序号。启动即成为"最新一轮",此前还在飞的那一轮由此自我作废。
const runSeq = backfillRunSeqRef.current + 1;
backfillRunSeqRef.current = runSeq;
@@ -4772,7 +4891,9 @@ export default function SessionScreen() {
return Array.isArray(page.messages) ? page.messages : [];
},
merge: (rows) => {
- if (rows.length > 0) remoteSessionStore.mergeMessages(sessionIdAtStart, rows);
+ if (rows.length > 0) {
+ remoteSessionStore.mergeMessages(sessionIdAtStart, rows, { authority: messageAuthority });
+ }
},
// 两个收手条件:
// - **我不再是最新那一轮** —— 屏幕已经为别的会话(或切回来后的同一会话)起了新的一轮。
@@ -4781,13 +4902,17 @@ export default function SessionScreen() {
// - 空洞较新一侧那行已不在窗口里 —— /clear、rewind 或整窗替换把它拿掉了,继续 merge 会
// 把刚被移除的历史(甚至 clearedAt 之前的消息)塞回窗口。锚点没了就等于这处空洞不存在了。
isCancelled: () => backfillLatestRunSeqRef.current !== runSeq
+ || !remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)
|| !remoteSessionStore.getMessages(sessionIdAtStart).some((row) => row.id === gap.newerId),
}).then((outcome) => {
// 按结局归类(容器的三类语义见 backfillGapStateRef 的注释)。归类发生在**收尾**而不是发起
// 前:发起期间的重入由飞行标记挡住,不需要预先占位。切会话 / 换连接代之后落地的旧结局
// 一律丢弃 —— 它属于上一个容器,写进新容器会污染当前会话的判断。
// 已被新一轮取代的旧轮不写结论:它看到的窗口已经不是当前的了。
- if (backfillLatestRunSeqRef.current !== runSeq) return;
+ if (
+ backfillLatestRunSeqRef.current !== runSeq
+ || !remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)
+ ) return;
const state = backfillGapStateRef.current;
if (!state || state.sid !== sessionIdAtStart || state.epoch !== epochAtStart) return;
// cancelled 刻意**不记**:它的两个触发条件本身就不会招来立刻重试 —— 会话切走时当前会话
@@ -4805,6 +4930,7 @@ export default function SessionScreen() {
backfillInFlightRun,
connectionEpoch,
deviceId,
+ isScheduleDetail,
loading,
loadingEarlier,
maker,
@@ -5473,6 +5599,8 @@ export default function SessionScreen() {
*/
const dispatchOutboxItem = async (item: MobileOutboxItem) => {
if (outboxSessionAliveRef.current !== item.sessionId) return 'stopped' as const;
+ const messageWorkLease = remoteSessionStore.acquireSessionMessageWork(item.sessionId, true);
+ try {
const failItem = (message: string) => {
// 归属校验:条目所属会话已离场(切会话 cleanup 已跑 / 屏已卸载)时不回插
// 共享 ref——那会把 A 会话的失败气泡画进 B,或写进没人消费的 ref 让文字
@@ -5653,6 +5781,9 @@ export default function SessionScreen() {
// enqueue / 对账期间离场时,成功路径无需恢复草稿,但旧 pump 也绝不能接着
// 消费新任务的 outbox;失败路径已由 failItem / waitForConnection 按 A 收口。
if (outboxSessionAliveRef.current !== item.sessionId) return 'stopped' as const;
+ } finally {
+ messageWorkLease.release();
+ }
};
/** 会话行的同步真源(store);命令式路径不能读可能落后一帧的 render 快照。 */
@@ -6042,6 +6173,8 @@ export default function SessionScreen() {
const connectionDispatchBlockedAtSend = outboxConnectionBlockedNow();
sendInFlightRef.current = true;
setSending(true);
+ const messageWorkLease = remoteSessionStore.acquireSessionMessageWork(sessionId, true);
+ try {
// 自动恢复中的 error 也是 outbox 的派发门;先清掉会让刚入队的消息在下一帧
// 立刻撞回断链。真正恢复后的 load / connection epoch 会负责清理并唤醒 pump。
if (!connectionDispatchBlockedAtSend) setError(null);
@@ -6686,6 +6819,9 @@ export default function SessionScreen() {
sendInFlightRef.current = false;
setSending(false);
}
+ } finally {
+ messageWorkLease.release();
+ }
}
// Keep the latest send available to imperative callers (voice release-to-send, long-press)
@@ -8514,7 +8650,6 @@ export default function SessionScreen() {
target.messageClientId,
{ radius: 1 },
);
- remoteSessionStore.mergeMessages(target.sessionId, around);
targetMessage = around.find((message) => (
message.clientId === target.messageClientId || message.id === target.messageClientId
));
@@ -8607,21 +8742,9 @@ export default function SessionScreen() {
// 也必须执行,否则该 session 的回撤结果丢失——不受下面 guard 影响。
remoteSessionStore.applySessionPatch(deviceId, sessionId, updated);
if (rewindRequestSeqRef.current !== seq) {
- // 代际已变(切走 / 切走又切回 / 另发起新请求):不碰当前在屏 session 的 UI,但仍要把目标
- // session 的消息 store 整窗刷新到 rewind 后。commit 已返回 = 服务端已截断历史,这里直接
- // session-scoped 写 store(不经 syncSession,不写 loading/error 等当前 UI state),避免
- // 「confirm 后立刻切走又切回」竞态下 reopen 抢在 commit 前用旧 meta 判定「已同步」而残留
- // rewind 前的旧消息。失败不阻断:下次进入该会话的 reopen 会据过期的 sync 标记兜底重拉。
- const refreshSeq = rewindRequestSeqRef.current;
- const history = await listMessagesWithPayloadRetry((limit) => maker.listMessages(sessionId, { limit })).catch(() => null);
- // fetch 往返期间代际又变(用户再次切换,或在该会话又完成了一次更新的 rewind)→ 这页已 stale。
- // 丢弃:否则旧页会覆盖更新的消息 store,并用旧 meta 误标记已同步,导致已删消息重现,直到下次
- // resync。交给下次进入该会话的 reopen 兜底重拉。
- if (rewindRequestSeqRef.current !== refreshSeq) return;
- if (history) {
- remoteSessionStore.setMessages(sessionId, Array.isArray(history.messages) ? history.messages : []);
- remoteSessionStore.markSessionMessagesSynced(sessionId, updated);
- }
+ // 远端 rewind 已成功,但这个页面代际不再拥有目标会话的消息写权限。
+ // 失效内存/磁盘窗口并登记刷新;当前若已切回会自动 load,否则下次打开重拉。
+ remoteSessionStore.invalidateSessionMessageWindow(sessionId, deviceId);
return;
}
applyComposerDocument(state.draftDocument ?? migrateLegacyComposerDraft(
@@ -8780,7 +8903,7 @@ export default function SessionScreen() {
<SessionSearchSheet
activeHit={activeSearchHit}
activeIndex={activeSearchIndex}
- hasOlderMessages={hasOlderMessages}
+ hasOlderMessages={hasOlderMessages && !isScheduleDetail}
hitCount={searchHits.length}
loadingEarlier={loadingEarlier}
onChangeQuery={setSearchQuery}
@@ -9047,7 +9170,7 @@ export default function SessionScreen() {
topOverlayHeight={topOverlayHeight}
busyAction={messageActionBusy?.kind ?? null}
busyClientId={messageActionBusy?.clientId ?? null}
- canLoadEarlier={hasOlderMessages && messages.length > 0}
+ canLoadEarlier={hasOlderMessages && messages.length > 0 && !isScheduleDetail}
emptyTestID="session.messageList.empty"
focusedItemKey={focusedMessageItemKey ?? null}
focusedRequestKey={focusedMessageRequestKey}
diff --git a/apps/mobile/docs/task-message-memory-governance-architecture.md b/apps/mobile/docs/task-message-memory-governance-architecture.md
new file mode 100644
index 0000000000..4ac69c1294
--- /dev/null
+++ b/apps/mobile/docs/task-message-memory-governance-architecture.md
@@ -0,0 +1,161 @@
+# Mobile 任务消息内存治理架构
+
+状态:实现说明(2026-08-15)
+
+## 1. 模块职责
+
+### `sessionRetention.ts`
+
+唯一分类入口:`source === 'scheduler'` 返回 `schedule`,其余返回 `regular`。
+
+### `sessionMessageLifecycle.ts`
+
+纯状态 controller,负责:
+
+- per-session generation 与 visible;
+- authority 捕获和提交校验;
+- 本地工作租约;
+- 跨页面卸载存活的 pending reclaim;
+- microtask 重试与重新聚焦取消。
+
+它不导入 Store,不执行具体清理。`remoteSessionStore` 注册唯一 reclaimer,避免循环依赖
+和页面各自实现回收状态机。
+
+### `remoteSessionStore.ts`
+
+负责:
+
+- authority-aware 的消息写入口;
+- schedule 写围栏和单窗裁剪;
+- regular 压窗、保护判定与全局 LRU;
+- 轻量运行时投影的 schedule 回收;
+- 显式缓存删除语义;
+- source 晚到后的策略迁移。
+
+### `mobileSessionMessageCache.ts`
+
+负责缓存 key、内容净化、保护行归一化,以及同 key 写删串行。
+
+### `app/sessions/[sessionId].tsx`
+
+只报告:
+
+- 导航 focus/blur;
+- AppState active/background;
+- 页面聚合本地工作是否存在;
+- `send()` 与 outbox dispatch 各自独立、跨卸载存活的工作租约。
+
+页面发起的异步消息读取捕获 authority,并把它传给 Store 提交入口。device-link 重连补读
+另保留从未打开 regular 的全局镜像路径,但提交时必须再次确认任务仍从未进入详情、且仍
+归属请求发起设备;一旦进入过详情,就只能走 authority 路径。
+
+## 2. 时序
+
+### 2.1 正常打开
+
+```text
+focus + App active
+ -> enter(sessionId)
+ -> generation += 1, visible = true
+ -> cache hydrate(regular only,提交前校验 authority)
+ -> listMessages(捕获同一 authority)
+ -> Store 写入并应用窗口/预算
+```
+
+### 2.2 失焦后快速返回
+
+```text
+A1 listMessages in flight
+ -> blur: leave(A1), generation += 1, visible = false
+ -> focus: enter(A2), generation += 1, visible = true
+ -> A1 response arrives: generation mismatch, reject
+ -> A2 response arrives: commit
+```
+
+旧 cleanup 同样携带 A1,晚到时无法撤销 A2。
+
+### 2.3 有本地工作的离场
+
+```text
+leave -> revoke authority immediately
+ -> local work active: record pending reclaim
+page unmount / async finally -> last lease release
+ -> microtask retry
+ -> generation still inactive: Store reclaims
+```
+
+microtask 让同一轮 React cleanup 中的 outbox 恢复草稿、上传取消等步骤先完成。
+
+### 2.4 source 晚到
+
+```text
+unknown source => regular (conservative)
+fresh session metadata arrives with source=scheduler
+ -> cache clear queued after older writes
+ -> visible: clamp to one window
+ -> hidden: request reclaim
+ -> pending hydrate/timer commit rechecks retention and rejects
+```
+
+## 3. 关键不变量
+
+1. authority 只能单调失效,不能通过 sessionId “摆回来”恢复有效。
+2. leave 先撤权,后判断能否做破坏性回收。
+3. deferred reclaim 的所有者是常驻 controller,不是页面 effect。
+4. `messages.length === 0` 不是磁盘删除指令。
+5. schedule 不读取或持久化长期完整消息缓存。
+6. regular LRU 只淘汰内存,不碰磁盘窗口。
+7. 本地系统卡没有服务端副本,所有压窗与缓存归一化必须保护。
+8. 当前详情保护对 regular 与 schedule 一致;回前台必须重新 enter。
+9. status、通知摘要与 live activity 不依赖完整消息驻留。
+10. source 缺失时只能保守按 regular,不能用标题或索引猜测。
+11. 页面聚合租约结束不代表异步发送结束;send/outbox 独立租约只能由自己的 `finally` 释放。
+12. regular 离场与 LRU 都必须释放详情投影并抬升 projection epoch。
+13. 含不可重取消息行的 regular 窗口不能参与整窗 LRU 淘汰。
+14. 从未打开 regular 的重连补读只有在生命周期与设备归属都未变化时才能更新全局镜像。
+15. 登出全清开始后到 `multiRemove` 完成前不能创建新的缓存写 authority。
+
+## 4. 故障半径三问
+
+### 断在哪里?
+
+- 导航失焦;
+- App 进入后台;
+- device-link session topic 取消或断线;
+- 页面原地切换 sessionId。
+
+### 谁负责恢复?
+
+- focus/AppState active 重新生成 authority;
+- 页面触发一次 `load()`;
+- device-link 对已进入详情的任务携带请求开始时 authority;从未打开的 regular 仅在响应
+ 返回时仍未进入且设备归属未变时更新全局镜像;
+- regular 可先从磁盘窗口乐观恢复,schedule 直接从工作设备读取。
+
+### 恢复前允许展示什么?
+
+- regular 可展示仍在内存或合法 hydrate 的最新缓存窗口;
+- schedule 回收后展示加载态/空窗,直到新代际读取完成;
+- 不允许旧代际响应、旧订阅 push 或旧流式批次填回正文。
+
+## 5. 交付检查清单
+
+- [x] 分类只看 source。
+- [x] per-session generation authority。
+- [x] focus、AppState 与 session switch 接线。
+- [x] 常驻工作租约与卸载后补回收。
+- [x] async send 与 outbox dispatch 独立租约。
+- [x] schedule 单窗、隐藏后归零、禁用加载更早。
+- [x] regular 80 条压窗与 800 条 / 64 MiB LRU。
+- [x] 草稿、运行、交互、pending queue、本地工作保护。
+- [x] regular 离场/LRU 释放详情投影并抬升 projection epoch。
+- [x] LRU 跳过含不可重取消息行的任务。
+- [x] 缓存语义与内存淘汰解耦。
+- [x] 本地系统卡保护。
+- [x] authority、Store、缓存自动化测试。
+- [x] Mobile 全量单测、scope guard、smoke、related unit 与 typecheck。
+- [ ] iOS 模拟器:regular/schedule 前后台与快速切换目检。
+- [ ] Android 模拟器:regular/schedule 前后台与快速切换目检。
+- [ ] 长会话连续滚动、加载更早与内存曲线实机观察。
+
+未完成的模拟器项目不应伪装成已验证;PR 描述需明确列出。
diff --git a/apps/mobile/docs/task-message-memory-governance-plan.md b/apps/mobile/docs/task-message-memory-governance-plan.md
new file mode 100644
index 0000000000..2e14653140
--- /dev/null
+++ b/apps/mobile/docs/task-message-memory-governance-plan.md
@@ -0,0 +1,178 @@
+# Mobile 任务消息内存治理方案
+
+状态:已实现(2026-08-15)
+
+## 1. 背景与目标
+
+Mobile 的任务详情此前把完整消息长期保存在进程级 `remoteSessionStore`,并通过
+AsyncStorage 缓存最新一页。浏览大量任务、持续接收流式消息或遇到超大工具输出时,
+消息正文会在 JS 堆中持续累积;定时任务又会自动产生大量很少再次打开的会话,放大
+驻留问题。
+
+本方案只治理 Mobile 的完整消息正文与紧邻的运行时投影,不改变 Desktop、共享协议、
+数据库 schema、原生配置或依赖。
+
+交付目标:
+
+- schedule 任务只在当前可见详情驻留完整消息,隐藏后最终回收到 0;
+- regular 任务离开详情后压回最近一页,全局约 800 条或 64 MiB;
+- 当前详情、运行中、待处理交互、排队输入、草稿和本地在途工作不被误回收;
+- 失焦、切任务、切后台后,旧异步读取和旧订阅不得在重新聚焦后复活正文;
+- 内存淘汰与磁盘缓存删除使用不同语义,不因 `messages=[]` 误删 regular 缓存;
+- 本地系统卡、乐观用户行和未落库的 assistant 行优先保留。
+
+## 2. 边界
+
+本次改动限定在 `apps/mobile/**`:
+
+- 不修改 device-link wire protocol;
+- 不修改 Desktop 或服务端;
+- 不修改 Mobile 原生配置、原生依赖与 runtime fingerprint;
+- 不引入轮询、TTL 或后台常驻定时回收器;
+- 不把消息正文迁移进新的数据库。
+
+## 3. 分类
+
+分类是创建来源决定的二分类:
+
+| 分类 | 判据 | 隐藏后的目标 |
+| --- | --- | --- |
+| `schedule` | `session.source === 'scheduler'` | 完整消息最终为 0 |
+| `regular` | 其它情况,包括 source 缺失 | 最近 80 条软窗口 |
+
+不使用 schedule 索引或标题前缀。索引会晚到且同时包含“schedule 创建”和“绑定既有
+任务”;标题可被用户修改。source 缺失时按 regular 保守处理,方向是多驻留而不是误
+回收。
+
+## 4. 生命周期与写权限
+
+每个会话拥有单调递增的 `generation`:
+
+1. 详情获得焦点且 App 在前台时 `enter(sessionId)`,生成新 authority;
+2. 失焦、切任务或 App 进入后台时 `leave(sessionId, reason, authority)`;
+3. leave 先递增 generation、撤销可见性,再考虑是否可以回收;
+4. 页面 `listMessages`、around-message、自动补历史在请求开始时捕获 authority;
+5. 断线重读对已进入过详情的任务同样捕获 authority;从未打开的 regular 只在响应返回时
+ 仍未进入详情、且仍归属原设备时更新全局镜像;
+6. 携 authority 的异步响应提交时必须同时满足 sessionId、generation、visible 三项仍一致。
+
+旧 cleanup 也必须携带自己的 authority。这样 A1 失焦、A2 重新聚焦后,A1 的 cleanup
+和响应都不能影响 A2。
+
+完整消息 push 的规则:
+
+- schedule 非当前详情拒绝正文 push;
+- regular 曾经离开详情后拒绝旧订阅 push;
+- 从未打开的 regular 保留全局消息镜像,但补读期间一旦 enter、leave、forget 或设备归属
+ 变化,旧响应即拒绝;
+- 页面离场但本地工作尚未收口时,允许必要的乐观/对账写入,排空后统一回收;
+- status、live activity、通知摘要等轻量事实不依赖完整消息 authority。
+
+## 5. 本地工作与延迟回收
+
+页面通过常驻 controller 持有工作租约,报告以下同步事实:
+
+- outbox 条目;
+- 附件上传与粘贴占位;
+- `send()` 同步在途;
+- enqueue 未落定;
+- 已出队但消息尚未回流;
+- composer 附件托盘。
+
+页面聚合租约只反映当前组件内的同步状态。`send()` 的异步发送作用域和每一条 outbox
+dispatch 都会另外获取一份 active 租约,并只在各自的 `finally` 中释放;因此页面卸载
+释放聚合租约时,不会把仍在等待上传、enqueue 或对账的异步工作误判为已结束。
+
+Store 另外保护:
+
+- `inputProjection.pendingQueue`;
+- 运行中状态与 maker turn;
+- pending interaction;
+- regular 的文本草稿、富文本草稿和引用。
+
+回收请求若遇到保护事实,只记录 pending,不在页面 effect 内轮询。页面卸载后租约仍按
+cleanup 收口;最后一份租约释放或 Store 保护状态归零时,在 microtask 中重试。若期间
+重新聚焦,新 generation 会取消旧 pending reclaim。
+
+## 6. 窗口与预算
+
+### 6.1 单会话窗口
+
+- schedule 当前详情始终保持一个 80 条软窗口,不提供“加载更早”;
+- regular 在详情内仍可加载历史,离开详情时压回 80 条;
+- 以下行优先保留,必要时可使软上限略微超出:
+ - `mobile-system-*` 本地系统卡;
+ - 未落库的 live assistant;
+ - 尚无服务端 id 的乐观 user 行。
+
+### 6.2 regular 全局预算
+
+regular 完整消息的软预算为:
+
+- 约 800 条;或
+- 估算 64 MiB。
+
+任一维度超限时,按最近访问顺序淘汰非保护任务。字节估算包含 content、agentMeta、
+systemCardData 与固定结构开销,只用于量级保护,不作为精确内存统计。
+
+LRU 只删除内存消息与相应连续性结论,不删除 AsyncStorage 缓存。
+
+LRU 是整窗淘汰:只要某个候选任务仍含本地系统卡、乐观用户行或未落库 assistant 行,
+就跳过整个任务,避免把不可重取行单独留下后又被缓存 hook 误当成完整窗口落盘。
+
+regular 离场压窗和 LRU 淘汰都会释放 live plan、task update、parked task update 与 input
+projection,并抬升 input projection authority epoch,阻止离场前启动的慢查询污染下次打开。
+
+## 7. 缓存语义
+
+缓存与内存驻留分离:
+
+- regular:可读取、去抖写入最新窗口;
+- schedule:不读取、不写入,识别后定点删除存量缓存;
+- 空内存快照不再自动等价为删除磁盘缓存;
+- 远端删除、权威空窗与 schedule 回收使用显式删除;
+- 同一缓存 key 的 set/remove 串行,避免较早开始的写在较晚删除后完成并复活正文;
+- 登出全清期间禁止铸造新缓存写权,避免 `getAllKeys` 取完快照后的卸载 flush 创建漏删 key;
+- hydrate、debounce 回调和卸载 flush 都在提交前二次检查 retention;
+- 缓存归一化同样保护窗口外的 `mobile-system-*`。
+
+## 8. 页面行为
+
+- focus 与 AppState 分别上报,二者都满足才授予可见 authority;
+- 从后台回前台时 regular 与 schedule 都重新登记当前详情并补一次同步;
+- schedule 隐藏“加载更早”入口,并拒绝程序化翻历史;
+- 页面不自行拼接消息清理步骤,只上报生命周期与本地工作事实。
+
+## 9. 验证矩阵
+
+自动化覆盖:
+
+- blur → refocus 后旧代际拒写、新代际可写;
+- 旧 cleanup 不撤销新 authority;
+- 页面卸载后最后一份工作租约释放仍能回收;
+- 重新聚焦取消旧 deferred reclaim;
+- schedule 失焦归零且迟到 push 不复活;
+- regular 离场拒绝旧订阅与旧流式 flush;
+- 从未打开的 regular 重连补读可写;请求期间首次进入、已离场 regular 与从未打开的
+ schedule 均拒绝旧补读;
+- pending queue 排空触发补回收;
+- regular 压窗保留本地系统卡;
+- regular LRU 保护当前详情并压回约 800 条;
+- async send 与 outbox dispatch 使用跨页面卸载的独立工作租约;
+- regular 离场/LRU 释放详情投影并拒绝旧 projection 回写;
+- regular LRU 跳过仍含不可重取行的整个任务;
+- source 晚到改判 schedule 后压窗并清缓存;
+- schedule 删除消息不持久化剩余正文;
+- regular LRU 不删除磁盘缓存;
+- 缓存写/删乱序最终以删除为准;
+- 显式空窗、内存已淘汰后的删除 push、登出全清都不会被旧在途写复活。
+
+已执行(2026-08-15):
+
+- `pnpm --filter mobile test`:301 个测试文件通过、1 个跳过;3514 个测试通过、9 个跳过;
+- `pnpm --filter mobile test:scope`:通过;
+- `pnpm --filter mobile test:smoke`:2 个测试文件、2 个测试通过;
+- `pnpm --filter mobile run --if-present typecheck`:通过;
+- `pnpm test:unit:related`:Mobile related unit 通过。
+
+模拟器验证项目见架构文档的交付检查清单;未执行的项目必须在 PR 中如实说明。
diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
index 2b03060e87..3fd0788d1d 100644
--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
@@ -35,7 +35,9 @@ describe('history window backfill wiring', () => {
// 取消判据对着 seq 比,不是"当前会话 id 是否仍等于启动时的"——后者会随切回来而摆回。
expect(source).toContain('isCancelled: () => backfillLatestRunSeqRef.current !== runSeq');
// 结论写入同样要求"我还是最新那一轮"。
- expect(source).toContain('if (backfillLatestRunSeqRef.current !== runSeq) return;');
+ expect(source).toMatch(
+ /if \(\s*backfillLatestRunSeqRef\.current !== runSeq\s*\|\| !remoteSessionStore\.isSessionMessageAuthorityCurrent\(messageAuthority\)\s*\) return;/,
+ );
// 收尾按 seq 精确清标记:按 sid 比会把切回同一会话后新起那一轮的标记误清。
expect(source).toContain('setBackfillInFlightRun((current) => (current?.seq === runSeq ? null : current));');
// 作废收敛成一个函数,三个入口共用(单向,不启动新轮):
diff --git a/apps/mobile/src/__tests__/mobileRemoteFlowSmoke.test.ts b/apps/mobile/src/__tests__/mobileRemoteFlowSmoke.test.ts
index e6b4f0d8c7..5231291919 100644
--- a/apps/mobile/src/__tests__/mobileRemoteFlowSmoke.test.ts
+++ b/apps/mobile/src/__tests__/mobileRemoteFlowSmoke.test.ts
@@ -543,6 +543,7 @@ describe('mobile remote-control headless UI flow smoke', () => {
deviceLinkDeviceId: DEVICE_ID,
deviceLinkDeviceName: 'Studio Mac',
});
+ let messageAuthority = remoteSessionStore.enterSessionMessageDetail(SESSION_ID);
const syncSession = createRemoteSyncRunner(async () => {
await openLink(DEVICE_ID);
@@ -552,7 +553,7 @@ describe('mobile remote-control headless UI flow smoke', () => {
maker.getPendingInteractions(SESSION_ID),
maker.input.getProjection(SESSION_ID),
]);
- remoteSessionStore.mergeMessages(SESSION_ID, history);
+ remoteSessionStore.mergeMessages(SESSION_ID, history, { authority: messageAuthority });
remoteSessionStore.setPendingInteractions(SESSION_ID, interactions);
remoteSessionStore.setInputProjection(SESSION_ID, projection);
});
@@ -778,6 +779,12 @@ describe('mobile remote-control headless UI flow smoke', () => {
'CaroldeMacBook-Pro.local',
await maker.getSession(SESSION_ID),
);
+ messageAuthority = remoteSessionStore.enterSessionMessageDetail(SESSION_ID);
+ remoteSessionStore.setMessages(
+ SESSION_ID,
+ await maker.listMessages(SESSION_ID, { limit: 80 }),
+ { authority: messageAuthority },
+ );
expect(remoteSessionStore.getSessions().some((item) => item.id === SESSION_ID)).toBe(true);
const forked = await maker.fork(SESSION_ID, 'm2');
@@ -881,7 +888,11 @@ describe('mobile remote-control headless UI flow smoke', () => {
expect(isCommitReadyRewindState(rewindPreview)).toBe(true);
const rewound = await maker.rewindCommit(SESSION_ID, 'm3');
remoteSessionStore.applySessionPatch(DEVICE_ID, SESSION_ID, rewound);
- remoteSessionStore.setMessages(SESSION_ID, await maker.listMessages(SESSION_ID, { limit: 80 }));
+ remoteSessionStore.setMessages(
+ SESSION_ID,
+ await maker.listMessages(SESSION_ID, { limit: 80 }),
+ { authority: messageAuthority },
+ );
expect(normalizeRemoteMessages(remoteSessionStore.getMessages(SESSION_ID)).map((item) => item.body)).toEqual([
'hello from desktop',
'ready from desktop',
diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
index 2062e5a9a2..99a2bb5262 100644
--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { RemoteMessage } from '@/session/types';
+import type { RemoteMessage, RemoteSession } from '@/session/types';
// 内存版 AsyncStorage:覆盖 getItem/setItem/removeItem/getAllKeys/multiRemove,贴近真实 RN API。
const store = vi.hoisted(() => new Map<string, string>());
@@ -41,6 +41,26 @@ function isoAt(index: number): string {
return new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString();
}
+function makeSession(id: string, patch: Partial<RemoteSession> = {}): RemoteSession {
+ return {
+ id,
+ userId: 'user-1',
+ title: id,
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ model: 'claude',
+ effort: 'medium',
+ permissionMode: 'default',
+ fastMode: false,
+ status: 'active',
+ agentKind: 'cc',
+ userSendAt: null,
+ createdAt: isoAt(0),
+ updatedAt: isoAt(0),
+ ...patch,
+ };
+}
+
describe('mobileSessionMessageCache', () => {
beforeEach(() => {
store.clear();
@@ -248,11 +268,11 @@ describe('mobileSessionMessageCache', () => {
await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);
});
- it('does not persist an empty render snapshot before cache hydration finishes', () => {
+ it('does not treat an empty in-memory render snapshot as a cache deletion', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');
- expect(source).toContain('const hydrationReadyKeyRef = useRef<string | null>(null);');
- expect(source).toContain('if (hydrationReadyKeyRef.current !== key) return;');
- expect(source).toContain('if (deviceId) void cacheSessionMessages(deviceId, sessionId, next).catch(() => undefined);');
+ expect(source).toContain('空内存可能只是 regular LRU 淘汰');
+ expect(source).toContain('if (messages.length === 0) return;');
+ expect(source).toContain("if (retentionForSession(sessionId) === 'schedule')");
});
it('clears every cached session on logout but leaves unrelated keys', async () => {
@@ -270,4 +290,258 @@ describe('mobileSessionMessageCache', () => {
expect([...store.keys()].some((key) => key.startsWith(`${__testing.storageKeyPrefix}.`))).toBe(false);
expect(store.get('xdt.unrelated.key')).toBe('keep-me');
});
+
+ it('keeps local system cards outside the latest cache window', async () => {
+ const { MAX_CACHED_SESSION_MESSAGES, cacheSessionMessages, getCachedSessionMessages } =
+ await import('@/session/mobileSessionMessageCache');
+ const localCard = makeMessage({
+ id: 'mobile-system-pwd-old',
+ clientId: 'mobile-system-pwd-old',
+ createdAt: isoAt(0),
+ });
+ const rows = Array.from({ length: MAX_CACHED_SESSION_MESSAGES + 5 }, (_, index) =>
+ makeMessage({ id: `m-${index}`, createdAt: isoAt(index + 1) }),
+ );
+
+ await cacheSessionMessages('host-a', 'session-1', [localCard, ...rows]);
+ const restored = await getCachedSessionMessages('host-a', 'session-1');
+
+ expect(restored.some((row) => row.id === localCard.id)).toBe(true);
+ expect(restored.at(-1)?.id).toBe(`m-${rows.length - 1}`);
+ });
+
+ it('serializes a schedule cache clear after an already-started regular write', async () => {
+ const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;
+ const { cacheSessionMessages, getCachedSessionMessages } =
+ await import('@/session/mobileSessionMessageCache');
+ let finishSetItem!: () => void;
+ vi.mocked(AsyncStorage.setItem).mockImplementationOnce((key: string, value: string) =>
+ new Promise<void>((resolve) => {
+ finishSetItem = () => {
+ store.set(key, value);
+ resolve();
+ };
+ }));
+
+ const oldWrite = cacheSessionMessages('host-a', 'session-1', [
+ makeMessage({ id: 'body', createdAt: isoAt(1) }),
+ ]);
+ for (let index = 0; index < 5 && !finishSetItem; index += 1) await Promise.resolve();
+ const scheduleClear = cacheSessionMessages('host-a', 'session-1', []);
+ expect(finishSetItem).toBeTypeOf('function');
+ finishSetItem();
+ await Promise.all([oldWrite, scheduleClear]);
+
+ await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);
+ });
+
+ it('removeMessages on a schedule task clears cache instead of persisting the remaining body', async () => {
+ const { cacheSessionMessages, getCachedSessionMessages } =
+ await import('@/session/mobileSessionMessageCache');
+ const { remoteSessionStore } = await import('@/session/remoteSessionStore');
+ remoteSessionStore.clear();
+ remoteSessionStore.setDeviceSessions('host-a', 'Mac', [
+ makeSession('session-1', { source: 'scheduler' }),
+ ]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('session-1');
+ const rows = [
+ makeMessage({ id: 'a', clientId: 'a', createdAt: isoAt(1) }),
+ makeMessage({ id: 'b', clientId: 'b', createdAt: isoAt(2) }),
+ ];
+ await cacheSessionMessages('host-a', 'session-1', rows);
+ remoteSessionStore.setMessages('session-1', rows, { authority });
+
+ remoteSessionStore.removeMessages('session-1', ['a'], 'host-a');
+
+ await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);
+ expect(remoteSessionStore.getMessages('session-1').map((row) => row.id)).toEqual(['b']);
+ });
+
+ it('regular LRU eviction removes only memory and preserves the disk window', async () => {
+ const { cacheSessionMessages, getCachedSessionMessages } =
+ await import('@/session/mobileSessionMessageCache');
+ const { remoteSessionStore } = await import('@/session/remoteSessionStore');
+ remoteSessionStore.clear();
+ const sessions = Array.from({ length: 9 }, (_, index) => makeSession(`s${index}`));
+ remoteSessionStore.setDeviceSessions('host-a', 'Mac', sessions);
+ const cached = makeMessage({ id: 'cached-s0', sessionId: 's0', createdAt: isoAt(1) });
+ await cacheSessionMessages('host-a', 's0', [cached]);
+
+ for (const item of sessions) {
+ remoteSessionStore.setMessages(
+ item.id,
+ Array.from({ length: 100 }, (_, index) => makeMessage({
+ id: `${item.id}-${index}`,
+ sessionId: item.id,
+ createdAt: isoAt(index),
+ })),
+ );
+ }
+
+ expect(remoteSessionStore.getMessages('s0')).toEqual([]);
+ await expect(getCachedSessionMessages('host-a', 's0')).resolves.toEqual([cached]);
+ });
+
+ it('an explicit cache replacement rejects a later stale debounce snapshot', async () => {
+ const {
+ cacheSessionMessagesIfCurrent,
+ captureSessionMessageCacheWriteAuthority,
+ getCachedSessionMessages,
+ replaceCachedSessionMessages,
+ } = await import('@/session/mobileSessionMessageCache');
+ const stale = makeMessage({ id: 'stale', createdAt: isoAt(1) });
+ const authority = captureSessionMessageCacheWriteAuthority('host-a', 'session-1');
+
+ await replaceCachedSessionMessages('host-a', 'session-1', []);
+ await cacheSessionMessagesIfCurrent(authority, [stale]);
+
+ await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);
+ });
+
+ it('an authoritative clear rejects a cache read that started before the clear', async () => {
+ const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;
+ const {
+ cacheSessionMessages,
+ captureSessionMessageCacheWriteAuthority,
+ getCachedSessionMessages,
+ isSessionMessageCacheWriteAuthorityCurrent,
+ } = await import('@/session/mobileSessionMessageCache');
+ const { remoteSessionStore } = await import('@/session/remoteSessionStore');
+ remoteSessionStore.clear();
+ remoteSessionStore.setDeviceSessions('host-a', 'Mac', [makeSession('session-1')]);
+ const stale = makeMessage({ id: 'stale', createdAt: isoAt(1) });
+ await cacheSessionMessages('host-a', 'session-1', [stale]);
+
+ let finishGetItem!: () => void;
+ vi.mocked(AsyncStorage.getItem).mockImplementationOnce((key: string) => {
+ const snapshot = store.get(key) ?? null;
+ return new Promise<string | null>((resolve) => {
+ finishGetItem = () => resolve(snapshot);
+ });
+ });
+ const pageAuthority = remoteSessionStore.enterSessionMessageDetail('session-1');
+ const cacheAuthority = captureSessionMessageCacheWriteAuthority('host-a', 'session-1');
+ const read = getCachedSessionMessages('host-a', 'session-1');
+ for (let index = 0; index < 5 && !finishGetItem; index += 1) await Promise.resolve();
+ expect(finishGetItem).toBeTypeOf('function');
+
+ remoteSessionStore.setMessages('session-1', [], { authority: pageAuthority });
+ finishGetItem();
+ const cached = await read;
+ if (isSessionMessageCacheWriteAuthorityCurrent(cacheAuthority)) {
+ remoteSessionStore.hydrateMessagesIfEmpty('session-1', cached, { authority: pageAuthority });
+ }
+
+ expect(cached.map((row) => row.id)).toEqual(['stale']);
+ expect(isSessionMessageCacheWriteAuthorityCurrent(cacheAuthority)).toBe(false);
+ expect(remoteSessionStore.getMessages('session-1')).toEqual([]);
+ });
+
+ it('logout waits for an in-flight cache write before deleting owned keys', async () => {
+ const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;
+ const {
+ cacheSessionMessages,
+ clearCachedSessionMessages,
+ getCachedSessionMessages,
+ } = await import('@/session/mobileSessionMessageCache');
+ let finishSetItem!: () => void;
+ vi.mocked(AsyncStorage.setItem).mockImplementationOnce((key: string, value: string) =>
+ new Promise<void>((resolve) => {
+ finishSetItem = () => {
+ store.set(key, value);
+ resolve();
+ };
+ }));
+
+ const write = cacheSessionMessages('host-a', 'session-1', [
+ makeMessage({ id: 'body', createdAt: isoAt(1) }),
+ ]);
+ for (let index = 0; index < 5 && !finishSetItem; index += 1) await Promise.resolve();
+ const clear = clearCachedSessionMessages();
+ expect(finishSetItem).toBeTypeOf('function');
+ finishSetItem();
+ await Promise.all([write, clear]);
+
+ await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);
+ });
+
+ it('logout rejects a cache write authority captured after global clear starts', async () => {
+ const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;
+ const {
+ cacheSessionMessagesIfCurrent,
+ captureSessionMessageCacheWriteAuthority,
+ clearCachedSessionMessages,
+ getCachedSessionMessages,
+ } = await import('@/session/mobileSessionMessageCache');
+ let finishGetAllKeys!: () => void;
+ vi.mocked(AsyncStorage.getAllKeys).mockImplementationOnce(() => {
+ const snapshot = [...store.keys()];
+ return new Promise<string[]>((resolve) => {
+ finishGetAllKeys = () => resolve(snapshot);
+ });
+ });
+
+ const clear = clearCachedSessionMessages();
+ for (let index = 0; index < 5 && !finishGetAllKeys; index += 1) await Promise.resolve();
+ expect(finishGetAllKeys).toBeTypeOf('function');
+
+ // 模拟页面在登出 clear 已开始后才执行卸载 flush。旧实现会在 getAllKeys 的
+ // 快照之外创建新 key,导致 multiRemove 完成后正文仍残留。
+ const lateAuthority = captureSessionMessageCacheWriteAuthority('host-a', 'session-late');
+ const lateWrite = cacheSessionMessagesIfCurrent(lateAuthority, [
+ makeMessage({ id: 'stale-after-logout', createdAt: isoAt(1) }),
+ ]);
+ finishGetAllKeys();
+ await Promise.all([clear, lateWrite]);
+
+ expect(lateAuthority).toBeNull();
+ await expect(getCachedSessionMessages('host-a', 'session-late')).resolves.toEqual([]);
+ });
+
+ it('an authoritative empty window clears disk even when memory is already empty', async () => {
+ const { cacheSessionMessages, getCachedSessionMessages } =
+ await import('@/session/mobileSessionMessageCache');
+ const { remoteSessionStore } = await import('@/session/remoteSessionStore');
+ remoteSessionStore.clear();
+ remoteSessionStore.setDeviceSessions('host-a', 'Mac', [makeSession('session-1')]);
+ await cacheSessionMessages('host-a', 'session-1', [
+ makeMessage({ id: 'stale', createdAt: isoAt(1) }),
+ ]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('session-1');
+
+ remoteSessionStore.setMessages('session-1', [], { authority });
+
+ await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);
+ });
+
+ it('a delete push clears disk after the regular in-memory window was LRU-evicted', async () => {
+ const { cacheSessionMessages, getCachedSessionMessages } =
+ await import('@/session/mobileSessionMessageCache');
+ const { remoteSessionStore } = await import('@/session/remoteSessionStore');
+ remoteSessionStore.clear();
+ const sessions = Array.from({ length: 9 }, (_, index) => makeSession(`s${index}`));
+ remoteSessionStore.setDeviceSessions('host-a', 'Mac', sessions);
+ const cached = makeMessage({
+ id: 'deleted-row',
+ clientId: 'deleted-row',
+ sessionId: 's0',
+ createdAt: isoAt(1),
+ });
+ await cacheSessionMessages('host-a', 's0', [cached]);
+ for (const item of sessions) {
+ remoteSessionStore.setMessages(
+ item.id,
+ Array.from({ length: 100 }, (_, index) => makeMessage({
+ id: `${item.id}-${index}`,
+ sessionId: item.id,
+ createdAt: isoAt(index),
+ })),
+ );
+ }
+ expect(remoteSessionStore.getMessages('s0')).toEqual([]);
+
+ remoteSessionStore.removeMessages('s0', ['deleted-row'], 'host-a');
+
+ await expect(getCachedSessionMessages('host-a', 's0')).resolves.toEqual([]);
+ });
});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 5007fddbcc..cb9ffd4660 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -3153,3 +3153,273 @@ describe('maker:event 微批拆包(CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1)',
}
});
});
+
+describe('任务消息内存治理', () => {
+ beforeEach(() => remoteSessionStore.clear());
+
+ const manyMessages = (sessionId: string, count: number): RemoteMessage[] =>
+ Array.from({ length: count }, (_, index) => messageAt(
+ `${sessionId}-m-${index}`,
+ sessionId,
+ new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
+ ));
+
+ const flushReclaim = async (): Promise<void> => {
+ await Promise.resolve();
+ await Promise.resolve();
+ };
+
+ it('只按 source=scheduler 分类,标题与 source 缺失均保守按 regular', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [
+ session('schedule', { source: 'scheduler', title: '普通标题' }),
+ session('legacy-title', { title: '[Schedule] 旧标题' }),
+ session('bound', { source: 'user', title: '被定时器绑定' }),
+ ]);
+
+ expect(remoteSessionStore.getSessionRetention('schedule')).toBe('schedule');
+ expect(remoteSessionStore.getSessionRetention('legacy-title')).toBe('regular');
+ expect(remoteSessionStore.getSessionRetention('bound')).toBe('regular');
+ });
+
+ it('旧详情代际的读取在 blur→refocus 后不能覆盖新窗口', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);
+ const first = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('first', 's1')], { authority: first });
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', first);
+ const second = remoteSessionStore.enterSessionMessageDetail('s1');
+
+ remoteSessionStore.setMessages('s1', [message('stale', 's1')], { authority: first });
+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['first']);
+
+ remoteSessionStore.setMessages('s1', [message('fresh', 's1')], { authority: second });
+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['fresh']);
+ });
+
+ it('从未打开的 regular 可更新全局镜像,首次进入或离场后不再接受无 authority 补读', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(false);
+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow('s1', 'dev-1')).toBe(true);
+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow('s1', 'dev-2')).toBe(false);
+
+ remoteSessionStore.setLatestMessageWindow('s1', [message('global-mirror', 's1')]);
+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['global-mirror']);
+
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(true);
+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow('s1', 'dev-1')).toBe(false);
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);
+ remoteSessionStore.setLatestMessageWindow('s1', [message('stale-reconnect', 's1')]);
+
+ expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'stale-reconnect')).toBe(false);
+ });
+
+ it('从未打开的 schedule 不接受无 authority 的重连补读', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [
+ session('s1', { source: 'scheduler' }),
+ ]);
+
+ expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(false);
+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow('s1', 'dev-1')).toBe(false);
+ remoteSessionStore.setLatestMessageWindow('s1', [message('schedule-reconnect', 's1')]);
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+
+ it('schedule 失焦后回收到 0,后续 push 不会复活完整正文', async () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });
+
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);
+ await flushReclaim();
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: message('late-push', 's1'),
+ });
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+
+ it('regular 离场后旧订阅 push 与尚未 flush 的流式批次都不能复活窗口', async () => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', manyMessages('s1', 2), { authority });
+ pushMakerText('s1', 'stream-1', 'queued delta', false);
+
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);
+ const nextAuthority = remoteSessionStore.enterSessionMessageDetail('s1');
+ vi.runOnlyPendingTimers();
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: message('late-subscription-push', 's1'),
+ });
+
+ expect(remoteSessionStore.isSessionMessageAuthorityCurrent(nextAuthority)).toBe(true);
+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual([
+ 's1-m-0',
+ 'late-subscription-push',
+ 's1-m-1',
+ ]);
+ // 上面的 push 是在新代际可见期间到达,应该保留;旧代际排队的 delta 不得出现。
+ expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'stream-1')).toBe(false);
+
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', nextAuthority);
+ await flushReclaim();
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: message('push-after-leave', 's1'),
+ });
+ expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'push-after-leave')).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('页面卸载后本地工作排空仍会完成 deferred reclaim', async () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);
+ const work = remoteSessionStore.acquireSessionMessageWork('s1', true);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'session-switch', authority);
+
+ await flushReclaim();
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);
+ work.release();
+ await flushReclaim();
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+
+ it('pending queue 暂缓 schedule 回收,queue 排空后由 store 主动补回收', async () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });
+ remoteSessionStore.setInputProjection('s1', projection('s1'));
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'app-background', authority);
+
+ await flushReclaim();
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);
+ remoteSessionStore.setInputProjection('s1', {
+ ...projection('s1'),
+ pendingQueue: [],
+ });
+ await flushReclaim();
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+
+ it('regular 失焦压回单窗,同时保留窗口外的本地系统卡', async () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ const localCard = {
+ ...messageAt('mobile-system-pwd-old', 's1', '2025-12-31T23:59:59.000Z'),
+ role: 'system' as const,
+ };
+ remoteSessionStore.setMessages('s1', [localCard, ...manyMessages('s1', 100)], { authority });
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);
+ await flushReclaim();
+
+ const rows = remoteSessionStore.getMessages('s1');
+ expect(rows).toHaveLength(80);
+ expect(rows.some((row) => row.id === localCard.id)).toBe(true);
+ expect(rows.at(-1)?.id).toBe('s1-m-99');
+ });
+
+ it('regular 全局 LRU 不淘汰当前详情,且总量压回约 800 条', () => {
+ const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);
+ remoteSessionStore.enterSessionMessageDetail('s0');
+ for (const item of sessions) {
+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));
+ }
+
+ const total = sessions.reduce(
+ (sum, item) => sum + remoteSessionStore.getMessages(item.id).length,
+ 0,
+ );
+ expect(total).toBeLessThanOrEqual(800);
+ expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);
+ expect(sessions.slice(1).some((item) => remoteSessionStore.getMessages(item.id).length === 0)).toBe(true);
+ });
+
+ it('regular LRU 只淘汰可重取正文,不丢尚未落盘的本地系统卡', () => {
+ const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);
+ const localCard = {
+ ...messageAt('mobile-system-local-only', 's0', '2025-12-31T23:59:59.000Z'),
+ role: 'system' as const,
+ };
+ remoteSessionStore.setMessages('s0', [localCard, ...manyMessages('s0', 99)]);
+ for (const item of sessions.slice(1)) {
+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));
+ }
+
+ expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);
+ expect(remoteSessionStore.getMessages('s0').some((row) => row.id === localCard.id)).toBe(true);
+ });
+
+ it('regular 离场释放详情投影并拒绝离场前启动的旧投影查询', async () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });
+ remoteSessionStore.setInputProjection('s1', {
+ ...projection('s1'),
+ pendingQueue: [],
+ });
+ const queryEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');
+
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);
+ await flushReclaim();
+
+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);
+ expect(remoteSessionStore.setInputProjectionIfCurrent(
+ 's1',
+ projection('s1'),
+ queryEpoch,
+ )).toBe(false);
+ });
+
+ it('source 晚到改判 schedule:当前详情立即压窗,失焦后归零', async () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', manyMessages('s1', 100), { authority });
+
+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', { source: 'scheduler' }));
+ expect(remoteSessionStore.getSessionRetention('s1')).toBe('schedule');
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(80);
+
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur');
+ await flushReclaim();
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+
+ it('归档会话会撤销旧 authority,并拒绝迟到 push 复活正文', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('before-archive', 's1')], { authority });
+
+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' });
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: message('late-after-archive', 's1'),
+ });
+
+ expect(remoteSessionStore.isSessionMessageAuthorityCurrent(authority)).toBe(false);
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+
+ it('显式失效 rewind 窗口会清正文、sync marker 并登记刷新', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', [message('before-rewind', 's1')], { authority });
+ const row = remoteSessionStore.getSessions().find((item) => item.id === 's1')!;
+ remoteSessionStore.markSessionMessagesSynced('s1', row);
+
+ remoteSessionStore.invalidateSessionMessageWindow('s1', 'dev-1');
+
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ expect(remoteSessionStore.isSessionMessageWindowSynced('s1', row)).toBe(false);
+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);
+ expect(remoteSessionStore.isSessionMessageAuthorityCurrent(authority)).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/__tests__/scrollWindowModel.test.ts b/apps/mobile/src/__tests__/scrollWindowModel.test.ts
index 15fde2aebe..cb7dd79a30 100644
--- a/apps/mobile/src/__tests__/scrollWindowModel.test.ts
+++ b/apps/mobile/src/__tests__/scrollWindowModel.test.ts
@@ -105,7 +105,9 @@ describe('scrollWindowModel', () => {
// 「加载更早」,也决定能不能信任早于本页的缓存段。
expect(source).toContain('const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);');
expect(source).toContain('setHasOlderMessages(moreBeyondWindow);');
- expect(source).toContain('setLatestMessageWindow(sessionId, historyPage, { moreBeyondWindow })');
+ expect(source).toMatch(
+ /setLatestMessageWindow\(sessionId, historyPage, \{\s*authority: messageAuthority,\s*moreBeyondWindow,\s*\}\)/,
+ );
});
});
diff --git a/apps/mobile/src/__tests__/sessionMessageLifecycle.test.ts b/apps/mobile/src/__tests__/sessionMessageLifecycle.test.ts
new file mode 100644
index 0000000000..28730cde4a
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionMessageLifecycle.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createSessionMessageLifecycleController,
+ type SessionMessageReclaimReason,
+} from '@/session/sessionMessageLifecycle';
+
+async function flushMicrotasks(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('sessionMessageLifecycle', () => {
+ it('blur 后重进会让第一代读取永久失效,第二代可提交', () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const first = lifecycle.enter('s1');
+ expect(lifecycle.canCommit(first)).toBe(true);
+
+ lifecycle.leave('s1', 'detail-blur', first);
+ const second = lifecycle.enter('s1');
+
+ expect(lifecycle.canCommit(first)).toBe(false);
+ expect(lifecycle.canCommit(second)).toBe(true);
+ });
+
+ it('旧 cleanup 晚到不能撤销重新聚焦后的新 authority', () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const first = lifecycle.enter('s1');
+ lifecycle.leave('s1', 'detail-blur', first);
+ const second = lifecycle.enter('s1');
+
+ expect(lifecycle.leave('s1', 'session-switch', first)).toBe(false);
+ expect(lifecycle.canCommit(second)).toBe(true);
+ });
+
+ it('页面卸载后等待最后一份本地工作释放再执行回收', async () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const reclaim = vi.fn((_sessionId: string, _reason: SessionMessageReclaimReason) => true);
+ lifecycle.setReclaimer(reclaim);
+ const first = lifecycle.acquireWork('s1', true);
+ const second = lifecycle.acquireWork('s1', true);
+ const authority = lifecycle.enter('s1');
+
+ lifecycle.leave('s1', 'session-switch', authority);
+ first.release();
+ await flushMicrotasks();
+ expect(reclaim).not.toHaveBeenCalled();
+
+ second.release();
+ await flushMicrotasks();
+ expect(reclaim).toHaveBeenCalledTimes(1);
+ expect(reclaim).toHaveBeenCalledWith('s1', 'session-switch');
+ });
+
+ it('页面 lease 释放后,独立异步操作 lease 仍能跨卸载保护到 finally', async () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const reclaim = vi.fn((_sessionId: string, _reason: SessionMessageReclaimReason) => true);
+ lifecycle.setReclaimer(reclaim);
+ const pageLease = lifecycle.acquireWork('s1', true);
+ const operationLease = lifecycle.acquireWork('s1', true);
+ const authority = lifecycle.enter('s1');
+
+ lifecycle.leave('s1', 'session-switch', authority);
+ pageLease.release();
+ await flushMicrotasks();
+ expect(reclaim).not.toHaveBeenCalled();
+
+ operationLease.release();
+ await flushMicrotasks();
+ expect(reclaim).toHaveBeenCalledTimes(1);
+ });
+
+ it('旧 deferred reclaim 在重新聚焦后即使排空也不能清新窗口', async () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const reclaim = vi.fn((_sessionId: string, _reason: SessionMessageReclaimReason) => true);
+ lifecycle.setReclaimer(reclaim);
+ const work = lifecycle.acquireWork('s1', true);
+ const first = lifecycle.enter('s1');
+ lifecycle.leave('s1', 'detail-blur', first);
+
+ const second = lifecycle.enter('s1');
+ work.release();
+ await flushMicrotasks();
+
+ expect(reclaim).not.toHaveBeenCalled();
+ expect(lifecycle.canCommit(second)).toBe(true);
+ });
+
+ it('不同 session 隔离,release 幂等', async () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const reclaim = vi.fn((_sessionId: string, _reason: SessionMessageReclaimReason) => true);
+ lifecycle.setReclaimer(reclaim);
+ const workA = lifecycle.acquireWork('a', true);
+ const a = lifecycle.enter('a');
+ const b = lifecycle.enter('b');
+ lifecycle.leave('a', 'detail-blur', a);
+ lifecycle.leave('b', 'app-background', b);
+
+ await flushMicrotasks();
+ expect(reclaim).toHaveBeenCalledWith('b', 'app-background');
+ expect(reclaim).not.toHaveBeenCalledWith('a', 'detail-blur');
+
+ workA.release();
+ workA.release();
+ await flushMicrotasks();
+ expect(reclaim.mock.calls.filter(([id]) => id === 'a')).toHaveLength(1);
+ });
+
+ it('store 保护返回 false 时保留 pending,状态变化可显式重试', async () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const reclaim = vi.fn((_sessionId: string, _reason: SessionMessageReclaimReason) => true)
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(true);
+ lifecycle.setReclaimer(reclaim);
+ const authority = lifecycle.enter('s1');
+ lifecycle.leave('s1', 'detail-blur', authority);
+ await flushMicrotasks();
+
+ expect(lifecycle.inspect('s1').pendingReclaim).toBe('detail-blur');
+ lifecycle.retryPendingReclaim('s1');
+ await flushMicrotasks();
+ expect(reclaim).toHaveBeenCalledTimes(2);
+ expect(lifecycle.inspect('s1').pendingReclaim).toBeNull();
+ });
+
+ it('后来的 leave 不会让已经排队的回收请求永久丢失', async () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const reclaim = vi.fn((_sessionId: string, _reason: SessionMessageReclaimReason) => true);
+ lifecycle.setReclaimer(reclaim);
+ const authority = lifecycle.enter('s1');
+
+ lifecycle.leave('s1', 'detail-blur', authority);
+ lifecycle.leave('s1', 'session-switch');
+ await flushMicrotasks();
+
+ expect(reclaim).toHaveBeenCalledTimes(1);
+ expect(reclaim).toHaveBeenCalledWith('s1', 'session-switch');
+ expect(lifecycle.inspect('s1').pendingReclaim).toBeNull();
+ });
+
+ it('forget 和 reset 后不会复用旧 authority 的 generation', () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const beforeForget = lifecycle.enter('s1');
+ lifecycle.forget('s1');
+ const afterForget = lifecycle.enter('s1');
+
+ expect(afterForget.generation).toBeGreaterThan(beforeForget.generation);
+ expect(lifecycle.canCommit(beforeForget)).toBe(false);
+
+ lifecycle.reset();
+ const afterReset = lifecycle.enter('s1');
+ expect(afterReset.generation).toBeGreaterThan(afterForget.generation);
+ expect(lifecycle.canCommit(afterForget)).toBe(false);
+ });
+
+ it('forget/reset 后旧 work lease 不能污染同 ID 的新生命周期', () => {
+ const lifecycle = createSessionMessageLifecycleController();
+ const beforeForget = lifecycle.acquireWork('s1', true);
+ lifecycle.forget('s1');
+ beforeForget.update(true);
+ expect(lifecycle.hasLocalWork('s1')).toBe(false);
+
+ const beforeReset = lifecycle.acquireWork('s1', true);
+ lifecycle.reset();
+ beforeReset.update(true);
+ expect(lifecycle.hasLocalWork('s1')).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
new file mode 100644
index 0000000000..34f8271875
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
@@ -0,0 +1,73 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+function source(path: string): string {
+ return readFileSync(resolve(process.cwd(), path), 'utf8').replace(/\r\n/g, '\n');
+}
+
+describe('任务消息内存治理页面接线', () => {
+ const screen = source('app/sessions/[sessionId].tsx');
+ const deviceLink = source('src/device-link/DeviceLinkContext.tsx');
+
+ it('只有 focus 与 AppState active 同时成立时 enter,离场立即携 authority 撤权', () => {
+ expect(screen).toContain('useFocusEffect(');
+ expect(screen).toContain('messageScreenFocusedRef.current = true;');
+ expect(screen).toContain("const messageAppActiveRef = useRef(AppState.currentState === 'active');");
+ expect(screen).toContain('remoteSessionStore.enterSessionMessageDetail(sessionId)');
+ expect(screen).toContain("remoteSessionStore.leaveSessionMessageDetail(sessionId, 'detail-blur', authority)");
+ expect(screen).toContain("remoteSessionStore.leaveSessionMessageDetail(sessionId, 'app-background', authority)");
+ expect(screen).toContain('setMessageReloadRevision((value) => value + 1);');
+ expect(screen).toContain('handledMessageReloadRevisionRef.current === messageReloadRevision');
+ expect(screen).toContain('handledMessageReloadRevisionRef.current = messageReloadRevision;');
+ });
+
+ it('详情读取在请求开始捕获 authority,并在所有消息写入口提交', () => {
+ expect(screen).toContain('const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);');
+ expect(screen).toContain('remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)');
+ expect(screen).toContain('remoteSessionStore.setMessages(sessionId, historyPage, { authority: messageAuthority });');
+ expect(screen).toContain('authority: messageAuthority,\n moreBeyondWindow,');
+ expect(screen).toContain('{ authority: messageAuthority },\n );');
+ expect(screen).toContain('remoteSessionStore.mergeEarlierMessages(sessionId, pageList, { authority: messageAuthority });');
+ expect(screen).toContain('remoteSessionStore.mergeMessages(sessionIdAtStart, rows, { authority: messageAuthority });');
+ expect(screen.match(/maker\.listMessages\(/g)).toHaveLength(4);
+ });
+
+ it('schedule 关闭翻历史入口,页面工作租约覆盖发送与附件状态', () => {
+ expect(screen).toContain('if (isScheduleDetail) return;');
+ expect(screen).toContain('hasOlderMessages && !isScheduleDetail');
+ expect(screen).toContain('canLoadEarlier={hasOlderMessages && messages.length > 0 && !isScheduleDetail}');
+ expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(sessionId, pageHasMessageWork)');
+ expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(item.sessionId, true)');
+ expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(sessionId, true)');
+ expect(screen.match(/messageWorkLease\.release\(\);/g)).toHaveLength(2);
+ for (const signal of [
+ 'outboxItems.length > 0',
+ 'pendingUploads.length > 0',
+ 'pastePlaceholderCount > 0',
+ 'sendInFlightRef.current',
+ 'sendingQueueClientIds.size > 0',
+ 'settlingQueueItems.length > 0',
+ 'attachments.length > 0',
+ ]) {
+ expect(screen).toContain(signal);
+ }
+ });
+
+ it('断线补读区分已进入详情与从未打开的 regular,跨代 rewind 不再无条件写正文', () => {
+ expect(deviceLink).toContain('remoteSessionStore.hasSessionMessageDetailEntered(sessionId)');
+ expect(deviceLink).toContain('? remoteSessionStore.captureSessionMessageAuthority(sessionId)');
+ expect(deviceLink).toContain('authority: messageAuthorityAtRequestStart');
+ expect(deviceLink).toContain('remoteSessionStore.canCommitUnenteredSessionMessageWindow(sessionId, deviceId)');
+ expect(deviceLink).toContain('remoteSessionStore.setLatestMessageWindow(sessionId, history.value, windowOptions);');
+ expect(screen).toContain('remoteSessionStore.invalidateSessionMessageWindow(sessionId, deviceId);');
+ expect(screen).not.toContain('remoteSessionStore.setMessages(sessionId, Array.isArray(history.messages)');
+ });
+
+ it('缓存 hydrate 同时校验页面 authority 与缓存 key epoch', () => {
+ const store = source('src/session/remoteSessionStore.ts');
+ expect(store).toContain('const cacheAuthority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);');
+ expect(store).toContain('isSessionMessageCacheWriteAuthorityCurrent(cacheAuthority)');
+ expect(store).toContain('remoteSessionStore.isSessionMessageAuthorityCurrent(authority)');
+ });
+});
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 04ed69334f..71a1a8701e 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1202,6 +1202,11 @@ async function rebuildSessionSnapshot(
};
const projectionEpochAtRequestStart =
remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);
+ const messageDetailEnteredAtRequestStart =
+ remoteSessionStore.hasSessionMessageDetailEntered(sessionId);
+ const messageAuthorityAtRequestStart = messageDetailEnteredAtRequestStart
+ ? remoteSessionStore.captureSessionMessageAuthority(sessionId)
+ : null;
// 四路快照独立拉取、独立落库:断连补齐窗口本就脆弱,一个子请求失败不应拖垮
// 其余(旧实现共用一个 catch,任一失败三份快照全丢)。goal 覆盖断连窗口内
// 丢失的 maker:goal:status-changed push;model-pref / turn-cost 无对应查询通道,
@@ -1237,9 +1242,20 @@ async function rebuildSessionSnapshot(
// moreBeyondWindow:这一页上沿之外服务端还有历史(满 80 条,或被 device-link 裁过行)。为真时
// store 不保留早于本页的缓存段 —— 断连期间漏收的 push 可能正落在两段之间,保留就在窗口里
// 留下孤岛,而漏收的量不大时两侧时间差很小、时间阈值的空洞检测发现不了(#1222)。
- remoteSessionStore.setLatestMessageWindow(sessionId, history.value, {
+ const windowOptions = {
moreBeyondWindow: hasMoreOlderMessages(history.value, RECONNECT_MESSAGE_WINDOW_LIMIT),
- });
+ };
+ if (messageAuthorityAtRequestStart) {
+ remoteSessionStore.setLatestMessageWindow(sessionId, history.value, {
+ ...windowOptions,
+ authority: messageAuthorityAtRequestStart,
+ });
+ } else if (remoteSessionStore.canCommitUnenteredSessionMessageWindow(sessionId, deviceId)) {
+ // 从未打开过的 regular 仍承担首页/全局消息镜像;但请求飞行期间只要发生过
+ // enter / leave / forget,hasEntered 就会变为 true,旧重连响应不得越过新生命周期。
+ // Store 同时校验 regular retention 与物理设备归属,避免旧设备响应写回新 shard。
+ remoteSessionStore.setLatestMessageWindow(sessionId, history.value, windowOptions);
+ }
}
if (pending.status === 'fulfilled' && Array.isArray(pending.value)) {
remoteSessionStore.setPendingInteractions(sessionId, pending.value, { finalizeStreaming: true });
diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.ts
index 719beb6bed..e18fe3ad92 100644
--- a/apps/mobile/src/session/mobileSessionMessageCache.ts
+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts
@@ -27,6 +27,92 @@ type StoredSessionMessageCache = {
messages: RemoteMessage[];
};
+// 同一缓存 key 的写/删严格串行。schedule 分类晚到时会在旧写之后排一个删除,
+// 不允许较早开始、较晚结束的 setItem 把已经清掉的完整正文复活。
+const pendingOperations = new Map<string, Promise<void>>();
+const keyWriteEpochs = new Map<string, number>();
+let globalWriteEpoch = 0;
+let globalClearInProgress = false;
+let activeGlobalClear: Promise<void> | null = null;
+
+export interface SessionMessageCacheWriteAuthority {
+ readonly key: string;
+ readonly globalEpoch: number;
+ readonly keyEpoch: number;
+}
+
+function enqueueCacheOperation(key: string, operation: () => Promise<void>): Promise<void> {
+ const previous = pendingOperations.get(key) ?? Promise.resolve();
+ const next = previous.catch(() => undefined).then(operation).catch(() => undefined);
+ pendingOperations.set(key, next);
+ void next.finally(() => {
+ if (pendingOperations.get(key) === next) pendingOperations.delete(key);
+ });
+ return next;
+}
+
+export function isSessionMessageCacheWriteAuthorityCurrent(
+ authority: SessionMessageCacheWriteAuthority | null | undefined,
+): authority is SessionMessageCacheWriteAuthority {
+ if (!authority) return false;
+ return authority.globalEpoch === globalWriteEpoch
+ && authority.keyEpoch === (keyWriteEpochs.get(authority.key) ?? 0);
+}
+
+export function captureSessionMessageCacheWriteAuthority(
+ deviceId: string,
+ sessionId: string,
+): SessionMessageCacheWriteAuthority | null {
+ // 登出全清从推进 global epoch 到 multiRemove 完成之间禁止铸造新写权。
+ // 否则卸载 flush 可在 getAllKeys 已取完快照后创建新 key,并晚于删除落盘。
+ if (globalClearInProgress) return null;
+ const key = safeStorageKey(deviceId, sessionId);
+ if (!key) return null;
+ return {
+ key,
+ globalEpoch: globalWriteEpoch,
+ keyEpoch: keyWriteEpochs.get(key) ?? 0,
+ };
+}
+
+/**
+ * 去抖/卸载 flush 使用的条件写:显式删除、rewind 或 schedule 改判会推进 epoch,
+ * 此后才触发的旧 timer 即使携带旧快照也不能覆盖新语义。
+ */
+export async function cacheSessionMessagesIfCurrent(
+ authority: SessionMessageCacheWriteAuthority | null,
+ messages: readonly RemoteMessage[],
+): Promise<void> {
+ if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;
+ const normalized = normalizeCachedMessages(messages);
+ await enqueueCacheOperation(authority.key, async () => {
+ if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;
+ if (normalized.length === 0) {
+ await AsyncStorage.removeItem(authority.key);
+ return;
+ }
+ const payload: StoredSessionMessageCache = {
+ version: 1,
+ updatedAt: Date.now(),
+ messages: normalized,
+ };
+ await AsyncStorage.setItem(authority.key, JSON.stringify(payload));
+ });
+}
+
+/** 显式替换/删除会推进 key epoch,使已排队但尚未提交的旧 render 快照失效。 */
+export async function replaceCachedSessionMessages(
+ deviceId: string,
+ sessionId: string,
+ messages: readonly RemoteMessage[],
+): Promise<void> {
+ const key = safeStorageKey(deviceId, sessionId);
+ if (!key) return;
+ keyWriteEpochs.set(key, (keyWriteEpochs.get(key) ?? 0) + 1);
+ const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);
+ await cacheSessionMessagesIfCurrent(authority, messages);
+}
+
// 读取某 (host, session) 的缓存消息;无缓存 / 解析失败一律返回空数组(乐观 hydrate 不应抛错)。
export async function getCachedSessionMessages(
deviceId: string,
@@ -34,6 +120,7 @@ export async function getCachedSessionMessages(
): Promise<RemoteMessage[]> {
const key = safeStorageKey(deviceId, sessionId);
if (!key) return [];
+ await pendingOperations.get(key)?.catch(() => undefined);
const raw = await AsyncStorage.getItem(key).catch(() => null);
if (!raw) return [];
try {
@@ -56,30 +143,34 @@ export async function cacheSessionMessages(
sessionId: string,
messages: readonly RemoteMessage[],
): Promise<void> {
- const key = safeStorageKey(deviceId, sessionId);
- if (!key) return;
- const normalized = normalizeCachedMessages(messages);
- if (normalized.length === 0) {
- await AsyncStorage.removeItem(key).catch(() => undefined);
- return;
- }
- const payload: StoredSessionMessageCache = {
- version: 1,
- updatedAt: Date.now(),
- messages: normalized,
- };
- await AsyncStorage.setItem(key, JSON.stringify(payload)).catch(() => undefined);
+ const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);
+ await cacheSessionMessagesIfCurrent(authority, messages);
}
// 登出清空:遍历所有本前缀的 key 一次性删除(AsyncStorage 支持枚举,无需手动维护 host 索引)。
-export async function clearCachedSessionMessages(): Promise<void> {
- const keys = await AsyncStorage.getAllKeys().catch(() => [] as readonly string[]);
- const owned = keys.filter((key) => key.startsWith(`${STORAGE_KEY_PREFIX}.`));
- if (owned.length === 0) return;
- await AsyncStorage.multiRemove(owned).catch(() => undefined);
+export function clearCachedSessionMessages(): Promise<void> {
+ if (activeGlobalClear) return activeGlobalClear;
+ // 先让所有旧条件写失效,再等已经进入 AsyncStorage 的旧操作结束;删除必须排在
+ // 它们之后,否则较慢的 setItem 会在登出清理完成后复活缓存。清理完成前保持
+ // globalClearInProgress=true,禁止卸载 flush 等路径在 getAllKeys 后铸造新写权。
+ globalWriteEpoch += 1;
+ globalClearInProgress = true;
+ activeGlobalClear = (async () => {
+ await Promise.all([...pendingOperations.values()].map((operation) =>
+ operation.catch(() => undefined)));
+ const keys = await AsyncStorage.getAllKeys().catch(() => [] as readonly string[]);
+ const owned = keys.filter((key) => key.startsWith(`${STORAGE_KEY_PREFIX}.`));
+ if (owned.length > 0) await AsyncStorage.multiRemove(owned).catch(() => undefined);
+ keyWriteEpochs.clear();
+ })().finally(() => {
+ globalClearInProgress = false;
+ activeGlobalClear = null;
+ });
+ return activeGlobalClear;
}
-// 排序(升序 createdAt)+ 按 messageKey 去重(对账:同 id 保留最后一次)+ 取最新 N 条 + 剥 content 大块。
+// 排序(升序 createdAt)+ 按 messageKey 去重(对账:同 id 保留最后一次)+ 取最新 N 条。
+// mobile-system-* 没有服务端副本,必须跨窗口保留;保护行可以让软上限略微超出。
function normalizeCachedMessages(input: readonly unknown[]): RemoteMessage[] {
const byKey = new Map<string, RemoteMessage>();
for (const item of input) {
@@ -88,7 +179,12 @@ function normalizeCachedMessages(input: readonly unknown[]): RemoteMessage[] {
byKey.set(messageKey(message), message);
}
const sorted = [...byKey.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
- return sorted.slice(-MAX_CACHED_SESSION_MESSAGES);
+ const protectedRows = sorted.filter((message) => messageKey(message).startsWith('mobile-system-'));
+ const protectedKeys = new Set(protectedRows.map(messageKey));
+ const latestRows = sorted
+ .filter((message) => !protectedKeys.has(messageKey(message)))
+ .slice(-MAX_CACHED_SESSION_MESSAGES);
+ return [...protectedRows, ...latestRows].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
// 与 remoteSessionStore.messageKey 对齐:id → clientId → role:createdAt,保证对账去重口径一致。
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 5e93ecdfbe..aac31fb53e 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -27,11 +27,27 @@ import {
createPendingWriteTracker,
createSessionWriteQueue,
} from '@/session/swipeRowRegistry';
-import { cacheSessionMessages, getCachedSessionMessages } from '@/session/mobileSessionMessageCache';
+import {
+ cacheSessionMessagesIfCurrent,
+ captureSessionMessageCacheWriteAuthority,
+ getCachedSessionMessages,
+ isSessionMessageCacheWriteAuthorityCurrent,
+ replaceCachedSessionMessages,
+} from '@/session/mobileSessionMessageCache';
+import { readComposerDocumentDraftSync, readComposerDraftSync } from '@/session/composerDraftStore';
+import { composerDocumentHasContent } from '@/session/composerDocument';
+import { getQuotes } from '@/session/chatQuoteStore';
+import {
+ sessionMessageLifecycle,
+ type SessionMessageAuthority,
+ type SessionMessageReclaimReason,
+ type SessionMessageWorkLease,
+} from '@/session/sessionMessageLifecycle';
+import { classifySessionRetention, type SessionRetentionKind } from '@/session/sessionRetention';
import { contentToPreview } from '@/utils/contentPreview';
import type { MobileSystemCardType } from '@/session/systemCard';
import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';
-import { compareMessageOrder } from '@/session/messagePaging';
+import { compareMessageOrder, MESSAGE_PAGE_SIZE } from '@/session/messagePaging';
import { normalizeRemoteMoney } from '@/session/remoteMoney';
interface DeviceShard {
@@ -105,6 +121,8 @@ interface SessionMessageSyncMarker {
}
export interface SetLatestMessageWindowOptions {
+ /** 读取发起时捕获的详情代际;失焦或重新聚焦后旧响应必须拒写。 */
+ authority?: SessionMessageAuthority;
/**
* 本页**上沿之外服务端还有历史**(满页,或被 device-link 裁过行)。
*
@@ -117,6 +135,10 @@ export interface SetLatestMessageWindowOptions {
moreBeyondWindow?: boolean;
}
+export interface SessionMessageWriteOptions {
+ authority?: SessionMessageAuthority;
+}
+
interface LivePlanSnapshot {
content: Record<string, unknown>;
persistId?: string;
@@ -510,6 +532,225 @@ 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;
+const messageBytesEstimates = new WeakMap<RemoteMessage, number>();
+const sessionLastAccessOrder = new Map<string, number>();
+let nextSessionAccessOrder = 0;
+
+function sessionById(sessionId: string): RemoteSession | undefined {
+ return mergedSessions.find((session) => session.id === sessionId);
+}
+
+function retentionForSession(sessionId: string): SessionRetentionKind {
+ return classifySessionRetention(sessionById(sessionId));
+}
+
+function touchSessionAccess(sessionId: string): void {
+ sessionLastAccessOrder.set(sessionId, ++nextSessionAccessOrder);
+}
+
+function estimateMessageBytes(message: RemoteMessage): number {
+ const cached = messageBytesEstimates.get(message);
+ if (cached !== undefined) return cached;
+ let bytes = MESSAGE_STRUCTURAL_BYTES_ESTIMATE;
+ if (typeof message.content === 'string') bytes += message.content.length * 2;
+ else if (message.content != null) bytes += safeStableStringify(message.content).length * 2;
+ if (message.agentMeta) bytes += safeStableStringify(message.agentMeta).length * 2;
+ if (message.systemCardData) bytes += safeStableStringify(message.systemCardData).length * 2;
+ messageBytesEstimates.set(message, bytes);
+ return bytes;
+}
+
+function isMessageWindowProtectedRow(sessionId: string, message: RemoteMessage): boolean {
+ if (messageKey(message).startsWith('mobile-system-')) return true;
+ if (isPendingLiveAssistantMessage(sessionId, message)) return true;
+ return message.role === 'user' && !message.id;
+}
+
+/**
+ * 软窗口:不可重取的本地/在途行全部保留,剩余额度给最新服务端行。保护行较多时
+ * 允许略超上限,数据安全优先于精确条数。
+ */
+function trimMessageWindow(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+ limit = MESSAGE_PAGE_SIZE,
+): RemoteMessage[] {
+ if (list.length <= limit) return [...list];
+ const protectedRows: RemoteMessage[] = [];
+ const evictableRows: RemoteMessage[] = [];
+ for (const row of list) {
+ if (isMessageWindowProtectedRow(sessionId, row)) protectedRows.push(row);
+ else evictableRows.push(row);
+ }
+ const keepEvictable = Math.max(0, limit - protectedRows.length);
+ return normalizeMessages([
+ ...protectedRows,
+ ...evictableRows.slice(Math.max(0, evictableRows.length - keepEvictable)),
+ ]);
+}
+
+function hasComposerDraft(sessionId: string): boolean {
+ if ((readComposerDraftSync(sessionId) ?? '').trim().length > 0) return true;
+ const document = readComposerDocumentDraftSync(sessionId);
+ if (document && composerDocumentHasContent(document)) return true;
+ return getQuotes(sessionId).length > 0;
+}
+
+function sessionStoreProtected(sessionId: string, includeVisible = true): boolean {
+ if (includeVisible && sessionMessageLifecycle.isVisible(sessionId)) return true;
+ if (readSessionRunStatus(sessionId).isRunning) return true;
+ if (sessionMakerTurnRunning.get(sessionId) === true) return true;
+ if ((pendingInteractions.get(sessionId)?.length ?? 0) > 0) return true;
+ if ((inputProjections.get(sessionId)?.pendingQueue.length ?? 0) > 0) return true;
+ if (sessionMessageLifecycle.hasLocalWork(sessionId)) return true;
+ if (retentionForSession(sessionId) === 'regular' && hasComposerDraft(sessionId)) return true;
+ return false;
+}
+
+function messageWriteAllowed(
+ sessionId: string,
+ authority?: SessionMessageAuthority,
+): boolean {
+ if (authority && (
+ authority.sessionId !== sessionId
+ || !sessionMessageLifecycle.canCommit(authority)
+ )) return false;
+ if (
+ sessionMessageLifecycle.isVisible(sessionId)
+ || sessionMessageLifecycle.hasLocalWork(sessionId)
+ ) return true;
+ // schedule 从未打开时也不能被全局 push 灌入正文;regular 在详情离场后同样
+ // 拒绝旧订阅/流式 flush,未曾打开的普通任务仍保留既有全局镜像行为。
+ if (retentionForSession(sessionId) === 'schedule') return false;
+ return !sessionMessageLifecycle.hasEntered(sessionId);
+}
+
+function normalizeWindowForRetention(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+): RemoteMessage[] {
+ return retentionForSession(sessionId) === 'schedule'
+ ? trimMessageWindow(sessionId, list)
+ : [...list];
+}
+
+function clearSessionMessageCache(sessionId: string, deviceId?: string): void {
+ const resolvedDeviceId = deviceId ?? sessionDeviceIndex.get(sessionId);
+ if (!resolvedDeviceId) return;
+ void replaceCachedSessionMessages(resolvedDeviceId, sessionId, []).catch(() => undefined);
+}
+
+function invalidateSessionMessageWindowState(
+ sessionId: string,
+ requestRefresh: boolean,
+): boolean {
+ let changed = messages.delete(sessionId);
+ changed = livePlanSnapshots.delete(sessionId) || changed;
+ changed = sessionTaskUpdates.delete(sessionId) || changed;
+ changed = sessionParkedTaskUpdates.delete(sessionId) || changed;
+ changed = sessionMessageSyncMarkers.delete(sessionId) || changed;
+ changed = streamingAssistantClientIds.delete(sessionId) || changed;
+ changed = pendingLiveAssistantClientIds.delete(sessionId) || changed;
+ if (pendingTextDeltaBatches.has(sessionId)) {
+ discardPendingTextDelta(sessionId);
+ changed = true;
+ }
+ if (sessionWindowCoverage.has(sessionId)) changed = true;
+ forgetWindowCoverage(sessionId);
+ changed = sessionLiveStreamAcked.delete(sessionId) || changed;
+ sessionLastAccessOrder.delete(sessionId);
+ if (requestRefresh && !pendingRefreshSessions.has(sessionId)) {
+ pendingRefreshSessions.add(sessionId);
+ changed = true;
+ } else if (!requestRefresh) {
+ changed = pendingRefreshSessions.delete(sessionId) || changed;
+ }
+ return changed;
+}
+
+function releaseSessionDetailProjections(sessionId: string): boolean {
+ let changed = livePlanSnapshots.delete(sessionId);
+ changed = sessionTaskUpdates.delete(sessionId) || changed;
+ changed = sessionParkedTaskUpdates.delete(sessionId) || changed;
+ changed = inputProjections.delete(sessionId) || changed;
+ // 即使投影已经为空也要抬升 authority:离场/LRU 前启动的慢查询不能在下一次
+ // 打开同一任务后把旧 pending queue 或 continuation owner 写回来。
+ bumpInputProjectionAuthorityEpoch(sessionId);
+ return changed;
+}
+
+function reclaimScheduleRuntimeMaps(sessionId: string): boolean {
+ let changed = invalidateSessionMessageWindowState(sessionId, false);
+ changed = releaseSessionDetailProjections(sessionId) || changed;
+ return changed;
+}
+
+function enforceRegularMessageBudget(): boolean {
+ let totalCount = 0;
+ let totalBytes = 0;
+ const candidates: Array<{
+ sessionId: string;
+ accessOrder: number;
+ count: number;
+ bytes: number;
+ }> = [];
+ for (const [sessionId, list] of messages) {
+ if (retentionForSession(sessionId) !== 'regular') continue;
+ const bytes = list.reduce((sum, message) => sum + estimateMessageBytes(message), 0);
+ totalCount += list.length;
+ totalBytes += bytes;
+ if (!sessionStoreProtected(sessionId)) {
+ const protectedRows = list.filter((message) => isMessageWindowProtectedRow(sessionId, message));
+ // LRU 是整窗淘汰;只要含无服务端副本/尚未落库的保护行,就跳过整个会话。
+ // 否则保留保护行会被缓存 hook 误当成完整窗口落盘,反而覆盖磁盘上的最新页。
+ if (protectedRows.length > 0) continue;
+ candidates.push({
+ sessionId,
+ accessOrder: sessionLastAccessOrder.get(sessionId) ?? 0,
+ count: list.length,
+ bytes,
+ });
+ }
+ }
+ if (
+ totalCount <= REGULAR_SESSION_GLOBAL_MESSAGE_BUDGET
+ && totalBytes <= REGULAR_SESSION_GLOBAL_MESSAGE_BYTES_BUDGET
+ ) return false;
+ candidates.sort((left, right) => left.accessOrder - right.accessOrder);
+ let changed = false;
+ for (const candidate of candidates) {
+ if (
+ totalCount <= REGULAR_SESSION_GLOBAL_MESSAGE_BUDGET
+ && totalBytes <= REGULAR_SESSION_GLOBAL_MESSAGE_BYTES_BUDGET
+ ) break;
+ if (!messages.delete(candidate.sessionId)) continue;
+ forgetWindowCoverage(candidate.sessionId);
+ sessionLiveStreamAcked.delete(candidate.sessionId);
+ releaseSessionDetailProjections(candidate.sessionId);
+ totalCount -= candidate.count;
+ totalBytes -= candidate.bytes;
+ changed = true;
+ // 这里只淘汰内存,不删除磁盘缓存。重开仍可乐观 hydrate 最新窗口。
+ }
+ return changed;
+}
+
+function applyMessageWriteRetention(sessionId: string): void {
+ touchSessionAccess(sessionId);
+ const current = messages.get(sessionId);
+ if (current && retentionForSession(sessionId) === 'schedule') {
+ const trimmed = trimMessageWindow(sessionId, current);
+ if (!remoteMessageListsEqual(current, trimmed)) {
+ forgetWindowCoverage(sessionId);
+ messages.set(sessionId, trimmed);
+ }
+ }
+ enforceRegularMessageBudget();
+}
+
let mergedSessions: RemoteSession[] = [];
let messageVersion = 0;
let storeVersion = 0;
@@ -530,13 +771,20 @@ function bumpInputProjectionAuthorityEpoch(sessionId: string): number {
}
function commitInputProjection(sessionId: string, next: InputProjection): boolean {
- if (deepValueEqual(inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION, next)) return false;
+ if (deepValueEqual(inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION, next)) {
+ if (next.pendingQueue.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
+ return false;
+ }
inputProjections.set(sessionId, next);
+ if (next.pendingQueue.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
emit();
return true;
}
function recomputeSessions(): void {
+ const previousRetention = new Map(
+ mergedSessions.map((session) => [session.id, classifySessionRetention(session)] as const),
+ );
sessionDeviceIndex.clear();
// 跨 shard 去重 + 设备身份归一化。re-link 后同一 session.id 可能同时存在于 stale / current 两个 shard;
// 保留「物理 deviceId 是当前已知设备」的那条(current shard 优先,它路由正确且是真身),都不是已知设备
@@ -583,6 +831,25 @@ function recomputeSessions(): void {
// 数组级同样调和:全部元素引用与序都未变时保留旧数组引用——useRemoteSessions 的
// useSyncExternalStore 快照经 Object.is 即可短路,消费屏对无关 emit 零重渲染。
mergedSessions = sameElementRefs(mergedSessions, next) ? mergedSessions : next;
+ for (const session of mergedSessions) {
+ const nextRetention = classifySessionRetention(session);
+ if (nextRetention !== 'schedule' || previousRetention.get(session.id) === 'schedule') continue;
+ // source 晚到后立即切断旧缓存路径。旧 hydrate / debounce 回调还会在提交前
+ // 二次检查 retention;这里的串行删除负责收掉已经开始的旧写。
+ clearSessionMessageCache(session.id, session.deviceLinkDeviceId);
+ const current = messages.get(session.id);
+ if (!current) continue;
+ if (sessionMessageLifecycle.isVisible(session.id)) {
+ const trimmed = trimMessageWindow(session.id, current);
+ if (!remoteMessageListsEqual(current, trimmed)) {
+ messages.set(session.id, trimmed);
+ forgetWindowCoverage(session.id);
+ bumpMessageVersion();
+ }
+ } else {
+ sessionMessageLifecycle.leave(session.id, 'session-switch');
+ }
+ }
emit();
}
@@ -983,6 +1250,7 @@ function upsertMessage(sessionId: string, message: RemoteMessage): boolean {
const next = existing.slice();
next[fallbackIndex] = message;
messages.set(sessionId, normalizeMessages(next));
+ applyMessageWriteRetention(sessionId);
retireGeneratedStreamingFallback(sessionId);
bumpMessageVersion();
return true;
@@ -990,6 +1258,7 @@ function upsertMessage(sessionId: string, message: RemoteMessage): boolean {
}
if (index < 0) {
messages.set(sessionId, normalizeMessages([...existing, message]));
+ applyMessageWriteRetention(sessionId);
if (isPersistedAssistantMessage(message) && fallbackIndex < 0) {
retireGeneratedStreamingFallback(sessionId);
}
@@ -1001,6 +1270,7 @@ function upsertMessage(sessionId: string, message: RemoteMessage): boolean {
const next = existing.slice();
next[index] = replacement;
messages.set(sessionId, normalizeMessages(next));
+ applyMessageWriteRetention(sessionId);
if (message.role === 'assistant') {
forgetPendingLiveAssistantMessageIdentity(
sessionId,
@@ -1272,6 +1542,107 @@ export const remoteSessionStore = {
return deviceList ?? [];
},
+ getSessionRetention(sessionId: string): SessionRetentionKind {
+ return retentionForSession(sessionId);
+ },
+
+ enterSessionMessageDetail(sessionId: string): SessionMessageAuthority {
+ const authority = sessionMessageLifecycle.enter(sessionId);
+ touchSessionAccess(sessionId);
+ if (enforceRegularMessageBudget()) {
+ bumpMessageVersion();
+ emit();
+ }
+ return authority;
+ },
+
+ leaveSessionMessageDetail(
+ sessionId: string,
+ reason: SessionMessageReclaimReason,
+ authority?: SessionMessageAuthority | null,
+ ): boolean {
+ const left = sessionMessageLifecycle.leave(sessionId, reason, authority);
+ if (left) {
+ noteLiveStreamInterrupted(sessionId);
+ discardPendingTextDelta(sessionId);
+ }
+ return left;
+ },
+
+ /**
+ * rewind 等远端权威改写后,目标详情已不再拥有可证明正确的连续窗口。
+ * 清内存与磁盘预览并登记一次刷新;页面可见时立即 load,隐藏时下次打开再拉。
+ */
+ invalidateSessionMessageWindow(sessionId: string, deviceId?: string): void {
+ const changed = invalidateSessionMessageWindowState(sessionId, true);
+ clearSessionMessageCache(sessionId, deviceId);
+ if (changed) {
+ bumpMessageVersion();
+ emit();
+ }
+ },
+
+ captureSessionMessageAuthority(sessionId: string): SessionMessageAuthority {
+ return sessionMessageLifecycle.capture(sessionId);
+ },
+
+ isSessionMessageAuthorityCurrent(authority: SessionMessageAuthority): boolean {
+ return sessionMessageLifecycle.canCommit(authority);
+ },
+
+ isSessionMessageDetailVisible(sessionId: string): boolean {
+ return sessionMessageLifecycle.isVisible(sessionId);
+ },
+
+ hasSessionMessageDetailEntered(sessionId: string): boolean {
+ return sessionMessageLifecycle.hasEntered(sessionId);
+ },
+
+ canCommitUnenteredSessionMessageWindow(sessionId: string, deviceId: string): boolean {
+ return retentionForSession(sessionId) === 'regular'
+ && sessionDeviceIndex.get(sessionId) === deviceId
+ && !sessionMessageLifecycle.hasEntered(sessionId);
+ },
+
+ acquireSessionMessageWork(sessionId: string, active = false): SessionMessageWorkLease {
+ return sessionMessageLifecycle.acquireWork(sessionId, active);
+ },
+
+ releaseSessionRuntimeState(
+ sessionId: string,
+ options: { reason: SessionMessageReclaimReason },
+ ): boolean {
+ if (!sessionId || sessionMessageLifecycle.isVisible(sessionId)) return true;
+ if (sessionStoreProtected(sessionId, false)) return false;
+ if (retentionForSession(sessionId) === 'schedule') {
+ const changed = reclaimScheduleRuntimeMaps(sessionId);
+ clearSessionMessageCache(sessionId);
+ if (changed) {
+ bumpMessageVersion();
+ emit();
+ }
+ return true;
+ }
+
+ const current = messages.get(sessionId);
+ let changed = releaseSessionDetailProjections(sessionId);
+ if (current && current.length > MESSAGE_PAGE_SIZE) {
+ const compacted = trimMessageWindow(sessionId, current);
+ if (!remoteMessageListsEqual(current, compacted)) {
+ messages.set(sessionId, compacted);
+ forgetWindowCoverage(sessionId);
+ changed = true;
+ }
+ }
+ changed = enforceRegularMessageBudget() || changed;
+ if (changed) {
+ bumpMessageVersion();
+ emit();
+ }
+ void options.reason;
+ return true;
+ },
+
// 注入当前权威设备列表(首页从 /api/device-link/devices reconcile 后调用),用于设备身份归一化。
// 仅在身份索引实际变化时重算,避免每次设备列表引用变动都刷新全部会话。
setDeviceIdentity(devices: readonly { deviceId: string; name: string }[]): void {
@@ -1413,6 +1784,11 @@ export const remoteSessionStore = {
if (patch.status === 'deleted' || patch.status === 'archived') {
shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);
sessionLiveActivity.delete(sessionId);
+ let messageStateChanged = invalidateSessionMessageWindowState(sessionId, false);
+ messageStateChanged = releaseSessionDetailProjections(sessionId) || messageStateChanged;
+ sessionMessageLifecycle.forget(sessionId);
+ if (patch.status === 'deleted') clearSessionMessageCache(sessionId, deviceId);
+ if (messageStateChanged) bumpMessageVersion();
} else {
const wasPinned = shard.sessions[idx].pinnedAt != null;
const unpinned = Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;
@@ -1425,25 +1801,39 @@ export const remoteSessionStore = {
if (shouldReseedAfterPatch) this.requestReseed(deviceId);
},
- setMessages(sessionId: string, list: readonly RemoteMessage[]): void {
+ setMessages(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+ options: SessionMessageWriteOptions = {},
+ ): void {
+ if (!messageWriteAllowed(sessionId, options.authority)) return;
const textFlushed = flushPendingTextDelta(sessionId);
- const next = normalizeMessages(list);
+ const next = normalizeWindowForRetention(sessionId, normalizeMessages(list));
// 记账在相等早退**之前**:这一页是服务端一次给出的连续段,它带来的连续性结论与"窗口内容有没有
// 变"无关。冷开缓存恰好与服务端最新页逐行相同时(常态)若被早退跳过,这次权威响应就白来了 ——
// 之后会话涨过一页、再遇一次满页重连刷新,本可保留的历史会被当成来源不明全丢(#1210 review)。
coverReplacedWindow(sessionId, next);
+ if (next.length === 0) clearSessionMessageCache(sessionId);
if (remoteMessageListsEqual(messages.get(sessionId) ?? emptyMessages, next)) {
if (textFlushed) emit();
return;
}
messages.set(sessionId, next);
+ applyMessageWriteRetention(sessionId);
bumpMessageVersion();
emit();
},
// 乐观 hydrate:仅当该会话当前还没有任何消息时,用本地缓存(冷开预览)种入。
// 「if empty」是关键不变量——fresh 数据若已先到则不覆盖;fresh 之后到也会按 messageKey 对账替换。
- hydrateMessagesIfEmpty(sessionId: string, list: readonly RemoteMessage[]): void {
+ hydrateMessagesIfEmpty(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+ options: SessionMessageWriteOptions = {},
+ ): void {
+ // schedule 从不读取长期完整消息缓存,即使当前详情可见也不例外。
+ if (retentionForSession(sessionId) === 'schedule') return;
+ if (!messageWriteAllowed(sessionId, options.authority)) return;
const textFlushed = flushPendingTextDelta(sessionId);
if ((messages.get(sessionId)?.length ?? 0) > 0) {
if (textFlushed) emit();
@@ -1455,6 +1845,7 @@ export const remoteSessionStore = {
return;
}
messages.set(sessionId, next);
+ applyMessageWriteRetention(sessionId);
bumpMessageVersion();
emit();
},
@@ -1464,8 +1855,9 @@ export const remoteSessionStore = {
list: readonly RemoteMessage[],
options: SetLatestMessageWindowOptions = {},
): void {
+ if (!messageWriteAllowed(sessionId, options.authority)) return;
const textFlushed = flushPendingTextDelta(sessionId);
- const latestWindow = normalizeMessages(list);
+ const latestWindow = normalizeWindowForRetention(sessionId, normalizeMessages(list));
if (latestWindow.length === 0) {
// 空窗口仍需保留本地系统卡(mobile-system-*):新会话首条消息发出后服务端
// 消息列表可能仍为空,下一次 setLatestMessageWindow 传空数组不能把刚追加的
@@ -1483,6 +1875,8 @@ export const remoteSessionStore = {
// 服务端行被清空(只余本地卡):旧覆盖区间连同它背书的那些行一起没了,不能留着背书。
forgetWindowCoverage(sessionId);
messages.set(sessionId, next);
+ applyMessageWriteRetention(sessionId);
+ if (next.length === 0) clearSessionMessageCache(sessionId);
bumpMessageVersion();
emit();
} else if (textFlushed) {
@@ -1598,7 +1992,7 @@ export const remoteSessionStore = {
}
}
- const next = normalizeMessages([...byKey.values()]);
+ const next = normalizeWindowForRetention(sessionId, normalizeMessages([...byKey.values()]));
// 记账在相等早退**之前**(同 setMessages):这一页是服务端一次给出的连续段,它带来的结论与
// "窗口内容有没有变"无关。被早退跳过时这次权威响应就白来了(#1210 review)。
coverLatestPage(sessionId, latestOldestCreatedAt, latestNewestCreatedAt, joinedCoverage);
@@ -1607,6 +2001,7 @@ export const remoteSessionStore = {
return;
}
messages.set(sessionId, next);
+ applyMessageWriteRetention(sessionId);
bumpMessageVersion();
emit();
},
@@ -1634,7 +2029,12 @@ export const remoteSessionStore = {
return true;
},
- mergeMessages(sessionId: string, list: readonly RemoteMessage[]): void {
+ mergeMessages(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+ options: SessionMessageWriteOptions = {},
+ ): void {
+ if (!messageWriteAllowed(sessionId, options.authority)) return;
const textFlushed = flushPendingTextDelta(sessionId);
const byKey = new Map<string, RemoteMessage>();
for (const item of messages.get(sessionId) ?? []) {
@@ -1657,12 +2057,13 @@ export const remoteSessionStore = {
);
}
}
- const next = normalizeMessages([...byKey.values()]);
+ const next = normalizeWindowForRetention(sessionId, normalizeMessages([...byKey.values()]));
if (remoteMessageListsEqual(messages.get(sessionId) ?? emptyMessages, next)) {
if (textFlushed) emit();
return;
}
messages.set(sessionId, next);
+ applyMessageWriteRetention(sessionId);
bumpMessageVersion();
emit();
},
@@ -1676,20 +2077,34 @@ export const remoteSessionStore = {
*
* 只有真正沿窗口最旧端连续翻页的调用方可以用它;补内部空洞请继续用 `mergeMessages`。
*/
- mergeEarlierMessages(sessionId: string, list: readonly RemoteMessage[]): void {
+ mergeEarlierMessages(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+ options: SessionMessageWriteOptions = {},
+ ): void {
+ if (retentionForSession(sessionId) === 'schedule') return;
+ if (!messageWriteAllowed(sessionId, options.authority)) return;
// 合并前窗口的最旧行 = 这一页接上的那一行,尚无结论时它就是区间上界(见 coverEarlierPage)。
const joinsAt = oldestCreatedAt(messages.get(sessionId) ?? emptyMessages);
- this.mergeMessages(sessionId, list);
+ this.mergeMessages(sessionId, list, options);
const pageOldest = oldestCreatedAt(list);
if (pageOldest) coverEarlierPage(sessionId, pageOldest, joinsAt);
},
- appendMessage(sessionId: string, message: RemoteMessage): void {
+ appendMessage(
+ sessionId: string,
+ message: RemoteMessage,
+ options: SessionMessageWriteOptions = {},
+ ): void {
+ if (!messageWriteAllowed(sessionId, options.authority)) return;
let changed = flushPendingTextDelta(sessionId);
changed = upsertMessage(sessionId, overlayLivePlanSnapshot(sessionId, message)) || changed;
// 订阅内到达的实时行可以把覆盖区间的上界往后推;断流后收到的不行(见 liveTailTrusted)。
coverLiveRow(sessionId, message);
- if (changed) emit();
+ if (changed) {
+ applyMessageWriteRetention(sessionId);
+ emit();
+ }
},
/**
@@ -1761,14 +2176,23 @@ export const remoteSessionStore = {
for (const deletedClientId of deletedClientIds) {
forgetPendingLiveAssistantMessageIdentity(sessionId, deletedClientId);
}
+ // 磁盘窗口可能在 regular LRU 后仍存在,即使当前内存里找不到被删行,也必须
+ // 失效缓存,避免下次 hydrate 把远端已删除的正文复活。显式替换会推进 cache
+ // epoch,使更晚触发的旧 debounce/unmount flush 失去提交资格。
+ if (retentionForSession(sessionId) === 'schedule' || !messagesChanged) {
+ clearSessionMessageCache(sessionId, deviceId);
+ } else {
+ const resolvedDeviceId = deviceId ?? sessionDeviceIndex.get(sessionId);
+ if (resolvedDeviceId) {
+ void replaceCachedSessionMessages(resolvedDeviceId, sessionId, next).catch(() => undefined);
+ }
+ }
+ if (messagesChanged) {
+ applyMessageWriteRetention(sessionId);
+ }
if (!messagesChanged && !tasksChanged) return;
bumpMessageVersion();
emit();
- // useSessionMessageCacheSync 对空数组会跳过持久化;删除最后一条消息时在这里
- // 主动清理 AsyncStorage,避免下次冷开又 hydrate 出已删除正文。
- if (messagesChanged) {
- if (deviceId) void cacheSessionMessages(deviceId, sessionId, next).catch(() => undefined);
- }
},
/** 旧调用点兼容:精确移除一个 clientId。 */
@@ -1853,6 +2277,7 @@ export const remoteSessionStore = {
// (#1493 review)。因此 authority 的翻转本身就是一次需要通知的变化。
const authorityChanged = !pendingInteractionsAuthoritative.has(sessionId);
pendingInteractionsAuthoritative.add(sessionId);
+ if (next.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
if (deepValueEqual(pendingInteractions.get(sessionId) ?? emptyPendingInteractions, next)) {
if (streamingChanged || authorityChanged) emit();
return;
@@ -2010,6 +2435,7 @@ export const remoteSessionStore = {
const next = existing.filter((i) => i.request.requestId !== requestId);
if (next.length === existing.length) return;
pendingInteractions.set(sessionId, next);
+ if (next.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
emit();
},
@@ -2072,6 +2498,7 @@ export const remoteSessionStore = {
|| !isInteractionResolveSuppressed(sessionId, item));
if (next.length === existing.length) return;
pendingInteractions.set(sessionId, next);
+ if (next.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
emit();
},
@@ -2406,7 +2833,12 @@ export const remoteSessionStore = {
const reconnectCleared = type !== null && type !== 'error' && type !== 'done'
? clearSessionReconnectAttempt(sessionId)
: false;
+ const fullMessageWriteAllowed = messageWriteAllowed(sessionId);
if (type === 'text') {
+ if (!fullMessageWriteAllowed) {
+ if (reconnectCleared) emit();
+ return;
+ }
if (isRemoteTextDeltaEvent(event)) {
if (enqueueRemoteTextDelta(sessionId, event, persistId) || reconnectCleared) emit();
return;
@@ -2425,7 +2857,7 @@ export const remoteSessionStore = {
|| (!isTurnContinuationBoundaryEvent(event) && isTerminalMakerErrorEvent(event))
) {
let terminalPlanChanged = false;
- if (type === 'done' && readString(event, 'source') === 'codex') {
+ if (fullMessageWriteAllowed && type === 'done' && readString(event, 'source') === 'codex') {
const data = isRecord(event.data) ? event.data : null;
const rawTurn = isRecord(data?.raw) ? data.raw : null;
const turnId = readString(rawTurn, 'id');
@@ -2462,7 +2894,7 @@ export const remoteSessionStore = {
);
}
}
- } else if (readString(event, 'source') === 'codex') {
+ } else if (fullMessageWriteAllowed && readString(event, 'source') === 'codex') {
// 没有 done 的 codex 终态 error:这一轮的计划行等不到章,也等不到
// persistCodexPlanOnDone 的 turnCompleted:false。与 desktop renderer 的
// markCodexPlanTurnFailed 同款补印记,否则全勾完的失败计划会按旧数据
@@ -2496,7 +2928,7 @@ export const remoteSessionStore = {
return;
}
- const textFlushed = flushPendingTextDelta(sessionId);
+ const textFlushed = fullMessageWriteAllowed ? flushPendingTextDelta(sessionId) : false;
if (type === 'error') {
const data = isRecord(event.data) ? event.data : null;
const reconnectAttempt = data?.willRetry === true
@@ -2516,6 +2948,10 @@ export const remoteSessionStore = {
return;
}
if (type === 'tool_use') {
+ if (!fullMessageWriteAllowed) {
+ if (reconnectCleared) emit();
+ return;
+ }
// Finalize before applying update_plan so its row update and the streaming
// row transition are published in one snapshot notification.
const streamingChanged = finalizeRemoteStreamingMessages(
@@ -2531,6 +2967,10 @@ export const remoteSessionStore = {
return;
}
if (type === 'agent_task_update') {
+ if (!fullMessageWriteAllowed) {
+ if (reconnectCleared) emit();
+ return;
+ }
const rawSource = readString(event, 'source');
const source = rawSource === 'codex' || rawSource === 'claude-code' || rawSource === 'pi'
? rawSource
@@ -2550,6 +2990,10 @@ export const remoteSessionStore = {
return;
}
if (type === 'compact_boundary') {
+ if (!fullMessageWriteAllowed) {
+ if (reconnectCleared) emit();
+ return;
+ }
const data = isRecord(event.data) ? event.data : {};
const boundaryId = readString(data, 'boundaryId');
// 新 producer 都会给 provider boundaryId;兼容旧事件时以完整 data 的 canonical
@@ -2711,6 +3155,8 @@ export const remoteSessionStore = {
pendingLiveAssistantClientIds.delete(sessionId);
sessionMakerTurnRunning.delete(sessionId);
sessionParkedTaskUpdates.delete(sessionId);
+ sessionMessageLifecycle.forget(sessionId);
+ sessionLastAccessOrder.delete(sessionId);
sessionDeviceIndex.delete(sessionId);
// revision 下限按会话回收:它不参与单轮快照回收(那会把覆盖权还给晚到的
// 旧快照),所以只能在会话本身消失时清,保持有界。
@@ -2762,6 +3208,9 @@ export const remoteSessionStore = {
clearTextDeltaFlushTimer();
sessionMakerTurnRunning.clear();
sessionParkedTaskUpdates.clear();
+ sessionMessageLifecycle.reset();
+ sessionLastAccessOrder.clear();
+ nextSessionAccessOrder = 0;
sessionDeviceIndex.clear();
reseedHandlers.clear();
mergedSessions = [];
@@ -2941,6 +3390,9 @@ export const remoteSessionStore = {
},
};
+sessionMessageLifecycle.setReclaimer((sessionId, reason) =>
+ remoteSessionStore.releaseSessionRuntimeState(sessionId, { reason }));
+
function dedupeInteractions(list: readonly PendingInteraction[]): PendingInteraction[] {
const byId = new Map<string, PendingInteraction>();
for (const item of list) {
@@ -3065,7 +3517,10 @@ function writeMakerTurnRunning(sessionId: string, running: boolean): boolean {
const prev = sessionMakerTurnRunning.get(sessionId) === true;
if (running === prev) return false;
if (running) sessionMakerTurnRunning.set(sessionId, true);
- else sessionMakerTurnRunning.delete(sessionId);
+ else {
+ sessionMakerTurnRunning.delete(sessionId);
+ sessionMessageLifecycle.retryPendingReclaim(sessionId);
+ }
return true;
}
@@ -3076,7 +3531,10 @@ function writeSessionRunStatus(sessionId: string, next: RemoteSessionRunStatus):
}
sessionRunStatus.set(sessionId, next);
if (next.isRunning) sessionRunning.set(sessionId, true);
- else sessionRunning.delete(sessionId);
+ else {
+ sessionRunning.delete(sessionId);
+ sessionMessageLifecycle.retryPendingReclaim(sessionId);
+ }
return true;
}
@@ -3264,8 +3722,15 @@ function useSessionMessageCacheSync(
messages: RemoteMessage[],
): void {
const hydratedKeyRef = useRef<string | null>(null);
- const hydrationReadyKeyRef = useRef<string | null>(null);
const persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const retention = useSyncExternalStore(
+ remoteSessionStore.subscribe,
+ () => remoteSessionStore.getSessionRetention(sessionId),
+ );
+ const authoritySnapshot = useSyncExternalStore(
+ sessionMessageLifecycle.subscribe,
+ () => sessionMessageLifecycle.getSnapshot(sessionId),
+ );
// 持久化在定时器回调里读最新值,避免把每次渲染的 messages 都闭包进 timer。
const ctxRef = useRef<{ deviceId?: string; sessionId: string; messages: RemoteMessage[] }>({
deviceId,
@@ -3276,44 +3741,61 @@ function useSessionMessageCacheSync(
// 乐观 hydrate:每个 (deviceId, sessionId) 只跑一次;缓存回来时若 store 仍为空才种入。
useEffect(() => {
- if (!deviceId || !sessionId) return;
+ if (!deviceId || !sessionId || retention !== 'regular') return;
+ const authority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
+ if (!remoteSessionStore.isSessionMessageAuthorityCurrent(authority)) return;
+ const cacheAuthority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);
+ if (!cacheAuthority) return;
const key = `${deviceId}::${sessionId}`;
if (hydratedKeyRef.current === key) return;
hydratedKeyRef.current = key;
- hydrationReadyKeyRef.current = null;
let cancelled = false;
void getCachedSessionMessages(deviceId, sessionId)
.then((cached) => {
if (cancelled || cached.length === 0) return;
- remoteSessionStore.hydrateMessagesIfEmpty(sessionId, cached);
+ // 消息 authority 只表示页面仍是同一详情代际;权威空窗口、删除、rewind 或
+ // schedule 改判不会撤销页面本身。缓存 key epoch 必须另行校验,防止这些
+ // 事件发生前启动的旧 getItem 在清空后把已删除正文重新 hydrate 回内存。
+ if (!isSessionMessageCacheWriteAuthorityCurrent(cacheAuthority)) return;
+ if (remoteSessionStore.getSessionRetention(sessionId) !== 'regular') return;
+ if (!remoteSessionStore.isSessionMessageAuthorityCurrent(authority)) return;
+ remoteSessionStore.hydrateMessagesIfEmpty(sessionId, cached, { authority });
})
- .catch(() => undefined)
- .finally(() => {
- if (!cancelled) hydrationReadyKeyRef.current = key;
- });
+ .catch(() => undefined);
return () => {
cancelled = true;
+ if (hydratedKeyRef.current === key) hydratedKeyRef.current = null;
};
- }, [deviceId, sessionId]);
+ }, [authoritySnapshot, deviceId, retention, sessionId]);
+
+ // schedule 不读写长期完整消息缓存。分类晚到时也会走这条定点删除;缓存模块
+ // 对同 key 串行,能保证删除排在已经开始的旧写之后。
+ useEffect(() => {
+ if (!deviceId || !sessionId || retention !== 'schedule') return;
+ if (persistTimerRef.current) clearTimeout(persistTimerRef.current);
+ persistTimerRef.current = null;
+ void replaceCachedSessionMessages(deviceId, sessionId, []).catch(() => undefined);
+ }, [deviceId, retention, sessionId]);
// 去抖持久化:messages 变化时重排定时器,静默后落盘最新快照。
useEffect(() => {
if (persistTimerRef.current) clearTimeout(persistTimerRef.current);
persistTimerRef.current = null;
- if (!deviceId || !sessionId) return;
+ if (!deviceId || !sessionId || retention !== 'regular') return;
const key = `${deviceId}::${sessionId}`;
- if (messages.length === 0) {
- if (hydrationReadyKeyRef.current !== key) return;
- void cacheSessionMessages(deviceId, sessionId, []).catch(() => undefined);
- return;
- }
+ // 空内存可能只是 regular LRU 淘汰,绝不能据此删除磁盘缓存。真正的远端
+ // 删除由 removeMessages / 权威空窗显式处理。
+ if (messages.length === 0) return;
+ const cacheAuthority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);
persistTimerRef.current = setTimeout(() => {
persistTimerRef.current = null;
const ctx = ctxRef.current;
if (!ctx.deviceId || !ctx.sessionId || ctx.messages.length === 0) return;
- void cacheSessionMessages(ctx.deviceId, ctx.sessionId, ctx.messages).catch(() => undefined);
+ if (`${ctx.deviceId}::${ctx.sessionId}` !== key) return;
+ if (remoteSessionStore.getSessionRetention(ctx.sessionId) !== 'regular') return;
+ void cacheSessionMessagesIfCurrent(cacheAuthority, ctx.messages).catch(() => undefined);
}, SESSION_MESSAGE_CACHE_PERSIST_DEBOUNCE_MS);
- }, [deviceId, sessionId, messages]);
+ }, [deviceId, messages, retention, sessionId]);
// 卸载时把尚未落盘的最新快照立即 flush(防止快速返回导致最后一次更新丢失)。
useEffect(() => () => {
@@ -3322,7 +3804,9 @@ function useSessionMessageCacheSync(
persistTimerRef.current = null;
const ctx = ctxRef.current;
if (!ctx.deviceId || !ctx.sessionId || ctx.messages.length === 0) return;
- void cacheSessionMessages(ctx.deviceId, ctx.sessionId, ctx.messages).catch(() => undefined);
+ if (remoteSessionStore.getSessionRetention(ctx.sessionId) !== 'regular') return;
+ const cacheAuthority = captureSessionMessageCacheWriteAuthority(ctx.deviceId, ctx.sessionId);
+ void cacheSessionMessagesIfCurrent(cacheAuthority, ctx.messages).catch(() => undefined);
}, []);
}
diff --git a/apps/mobile/src/session/sessionMessageLifecycle.ts b/apps/mobile/src/session/sessionMessageLifecycle.ts
new file mode 100644
index 0000000000..d0e80adfa9
--- /dev/null
+++ b/apps/mobile/src/session/sessionMessageLifecycle.ts
@@ -0,0 +1,241 @@
+export type SessionMessageReclaimReason =
+ | 'detail-blur'
+ | 'session-switch'
+ | 'app-background';
+
+export interface SessionMessageAuthority {
+ readonly sessionId: string;
+ readonly generation: number;
+}
+
+export interface SessionMessageWorkLease {
+ /** 更新这份工作租约是否仍持有不可回收的本地状态。 */
+ update(active: boolean): void;
+ /** 幂等释放;最后一份租约释放后会在 microtask 中重试暂缓回收。 */
+ release(): void;
+}
+
+type Reclaimer = (sessionId: string, reason: SessionMessageReclaimReason) => boolean;
+
+interface SessionLifecycleState {
+ generation: number;
+ visible: boolean;
+ pendingReclaim: SessionMessageReclaimReason | null;
+ work: Map<symbol, boolean>;
+ workEpoch: number;
+ reclaimScheduled: boolean;
+}
+
+function createState(): SessionLifecycleState {
+ return {
+ generation: 0,
+ visible: false,
+ pendingReclaim: null,
+ work: new Map(),
+ workEpoch: 0,
+ reclaimScheduled: false,
+ };
+}
+
+/**
+ * 纯状态控制器:页面只报告 focus / AppState / 本地工作事实,真正回收由 store
+ * 注册的单一 reclaimer 完成。状态常驻模块级,不依赖页面 effect 是否仍挂载。
+ */
+export function createSessionMessageLifecycleController() {
+ const states = new Map<string, SessionLifecycleState>();
+ const listeners = new Set<() => void>();
+ let reclaimer: Reclaimer | null = null;
+ // 不随 forget/reset 回绕。session 被删除、设备移除或登出后,旧异步请求即使在
+ // 同一个 sessionId 重新出现后才返回,也不能撞上复用的 generation。
+ let nextGeneration = 0;
+
+ const notify = (): void => {
+ for (const listener of listeners) listener();
+ };
+
+ const stateFor = (sessionId: string): SessionLifecycleState => {
+ let state = states.get(sessionId);
+ if (!state) {
+ state = createState();
+ states.set(sessionId, state);
+ }
+ return state;
+ };
+
+ const hasWork = (state: SessionLifecycleState): boolean => {
+ for (const active of state.work.values()) {
+ if (active) return true;
+ }
+ return false;
+ };
+
+ const schedulePendingReclaim = (sessionId: string): void => {
+ const state = stateFor(sessionId);
+ if (
+ state.reclaimScheduled
+ || state.visible
+ || state.pendingReclaim === null
+ || hasWork(state)
+ ) return;
+ state.reclaimScheduled = true;
+ const generationAtSchedule = state.generation;
+ queueMicrotask(() => {
+ const current = states.get(sessionId);
+ if (!current) return;
+ current.reclaimScheduled = false;
+ if (current.generation !== generationAtSchedule) {
+ // 另一份 leave 可能在本 microtask 执行前推进了代际。当时由于
+ // reclaimScheduled=true 没有另排任务,这里负责把仍有效的 pending 补上。
+ schedulePendingReclaim(sessionId);
+ return;
+ }
+ if (
+ current.visible
+ || current.pendingReclaim === null
+ || hasWork(current)
+ ) return;
+ const reason = current.pendingReclaim;
+ // false = store 侧仍有运行中、交互、pending queue 或草稿等保护事实。
+ // 保留 pending,等相应状态变化时 retryPendingReclaim 再试。
+ if (reclaimer?.(sessionId, reason) === true) current.pendingReclaim = null;
+ });
+ };
+
+ return {
+ setReclaimer(next: Reclaimer | null): void {
+ reclaimer = next;
+ },
+
+ enter(sessionId: string): SessionMessageAuthority {
+ const state = stateFor(sessionId);
+ state.generation = ++nextGeneration;
+ state.visible = true;
+ state.pendingReclaim = null;
+ notify();
+ return { sessionId, generation: state.generation };
+ },
+
+ /**
+ * token 可选:传入时只有同一代 cleanup 才能撤权,防止第一代 cleanup 晚到
+ * 误伤已经重新聚焦的第二代。
+ */
+ leave(
+ sessionId: string,
+ reason: SessionMessageReclaimReason,
+ token?: SessionMessageAuthority | null,
+ ): boolean {
+ const state = stateFor(sessionId);
+ if (token && (
+ token.sessionId !== sessionId
+ || token.generation !== state.generation
+ || !state.visible
+ )) return false;
+ state.generation = ++nextGeneration;
+ state.visible = false;
+ state.pendingReclaim = reason;
+ notify();
+ schedulePendingReclaim(sessionId);
+ return true;
+ },
+
+ capture(sessionId: string): SessionMessageAuthority {
+ const state = stateFor(sessionId);
+ return { sessionId, generation: state.generation };
+ },
+
+ canCommit(authority: SessionMessageAuthority | null | undefined): boolean {
+ if (!authority) return false;
+ const state = stateFor(authority.sessionId);
+ return state.visible && state.generation === authority.generation;
+ },
+
+ isVisible(sessionId: string): boolean {
+ return stateFor(sessionId).visible;
+ },
+
+ hasEntered(sessionId: string): boolean {
+ return stateFor(sessionId).generation > 0;
+ },
+
+ getSnapshot(sessionId: string): string {
+ const state = stateFor(sessionId);
+ return `${state.generation}:${state.visible ? 1 : 0}`;
+ },
+
+ subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+
+ hasLocalWork(sessionId: string): boolean {
+ return hasWork(stateFor(sessionId));
+ },
+
+ acquireWork(sessionId: string, active = false): SessionMessageWorkLease {
+ const state = stateFor(sessionId);
+ const id = Symbol(sessionId);
+ const workEpoch = state.workEpoch;
+ let released = false;
+ state.work.set(id, active);
+ return {
+ update(nextActive: boolean): void {
+ if (released) return;
+ const current = states.get(sessionId);
+ if (!current || current !== state || current.workEpoch !== workEpoch) return;
+ current.work.set(id, nextActive);
+ if (!nextActive) schedulePendingReclaim(sessionId);
+ },
+ release(): void {
+ if (released) return;
+ released = true;
+ const current = states.get(sessionId);
+ if (!current || current !== state || current.workEpoch !== workEpoch) return;
+ current.work.delete(id);
+ // 页面其它 cleanup(outbox 回草稿、上传取消等)需先完成,故不在当前
+ // cleanup 栈里同步做破坏性回收。
+ schedulePendingReclaim(sessionId);
+ },
+ };
+ },
+
+ retryPendingReclaim(sessionId: string): void {
+ schedulePendingReclaim(sessionId);
+ },
+
+ forget(sessionId: string): void {
+ // 保留一个已撤权 tombstone:删除/归档/移除设备后的迟到 push 不能重新被当成
+ // “从未打开过的 regular 会话”而获准写正文。下次真正 enter 会推进到新代际。
+ const state = stateFor(sessionId);
+ state.generation = ++nextGeneration;
+ state.visible = false;
+ state.pendingReclaim = null;
+ state.work.clear();
+ state.workEpoch += 1;
+ state.reclaimScheduled = false;
+ notify();
+ },
+
+ reset(): void {
+ states.clear();
+ notify();
+ },
+
+ /** 测试与 store 诊断使用,不暴露可变内部对象。 */
+ inspect(sessionId: string): {
+ generation: number;
+ visible: boolean;
+ pendingReclaim: SessionMessageReclaimReason | null;
+ workCount: number;
+ } {
+ const state = stateFor(sessionId);
+ return {
+ generation: state.generation,
+ visible: state.visible,
+ pendingReclaim: state.pendingReclaim,
+ workCount: [...state.work.values()].filter(Boolean).length,
+ };
+ },
+ };
+}
+
+export const sessionMessageLifecycle = createSessionMessageLifecycleController();
diff --git a/apps/mobile/src/session/sessionRetention.ts b/apps/mobile/src/session/sessionRetention.ts
new file mode 100644
index 0000000000..e55c8d2670
--- /dev/null
+++ b/apps/mobile/src/session/sessionRetention.ts
@@ -0,0 +1,16 @@
+import type { RemoteSession } from '@/session/types';
+
+/**
+ * Mobile 消息驻留策略只由任务创建来源决定。
+ *
+ * `source` 缺失时保守按普通任务处理:宁可多驻留,也不能因为标题、schedule
+ * 索引等可变/晚到信息误回收用户任务。schedule 绑定既有任务时不会改写 source,
+ * 因而仍属于 regular。
+ */
+export type SessionRetentionKind = 'regular' | 'schedule';
+
+export function classifySessionRetention(
+ session: Pick<RemoteSession, 'source'> | null | undefined,
+): SessionRetentionKind {
+ return session?.source === 'scheduler' ? 'schedule' : 'regular';
+}