Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 离线无缓存时显示历史未缓存提示 (#6527)
DavidShenXDd4972038b8b7
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 91e1dc9d48..d668973c04 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -424,6 +424,8 @@ import { findErrorTailClientId, isContinuationQueueItem, resolveSessionTailBanneimport { SessionTailBanner } from '@/session/SessionTailBanner';import { buildErrorDiagnosisPrompt, type ErrorDiagnosisSource } from '@/session/errorDiagnosisPrompt';import { useHistoryRecoveryNavigation } from '@/session/useHistoryRecoveryNavigation';+import { useSessionActivityInvalidation } from '@/session/useSessionActivityInvalidation';+import { useSessionMessageHistoryRead } from '@/session/useSessionMessageHistoryRead';import { canOfferCodexHistoryRecovery } from '@cindy/maker-shared/error-redaction';import {CONTINUE_AFTER_APP_EXIT_PROMPT,@@ -584,7 +586,10 @@ import {commitMobileStreamingPrefixItems,type MobileStreamingRenderPrefixCache,} from '@/session/messageRenderStreamingCache';-import { shouldSuppressEmptyMessageState } from '@/session/sessionEmptyState';+import {+ resolveSessionMessageEmptyState,+ shouldShowCachedHistoryNotice,+} from '@/session/sessionEmptyState';import { deferScheduleIndexHydration } from '@/session/scheduleIndexDefer';import { sessionMayHaveScheduleRuns } from '@/session/scheduleIndex';import { markSessionScheduleRunsRead, unreadRunIdFromProjection } from '@/session/scheduleRunRead';@@ -1123,8 +1128,7 @@ function SessionScreenContent() {// blocking both history and sync until a presence change happens to arrive.const remoteHistoryAvailable = status === 'online' && getPresenceAvailability(deviceId) !== false;// Unknown presence while connecting is loading, not evidence of a lost computer.- const showCachedHistoryNotice = status !== 'connecting'- && (status !== 'online' || getPresenceAvailability(deviceId) === false);+ const showCachedHistoryNotice = shouldShowCachedHistoryNotice(status, getPresenceAvailability(deviceId));const historyView = useRemoteHistoryView(deviceId, sessionId, maker,() => messageScreenFocusedRef.current && messageAppActiveRef.current, remoteHistoryAvailable);useEffect(() => {@@ -1792,6 +1796,9 @@ function SessionScreenContent() {// 后台订阅重试不能越过任务/设备/连接代切换,也不能在页面卸载后把已清理的 owner// 重新登记回来。render 阶段先发布最新 identity;旧 effect 的 cleanup 只清自己。const sessionSubscriptionIdentity = JSON.stringify([deviceId, sessionId, connectionEpoch]);+ const [messageHistoryRead, setMessageHistoryRead] = useSessionMessageHistoryRead({+ deviceId, sessionId, notificationResponse, subscriptionIdentity: sessionSubscriptionIdentity,+ });const sessionSubscriptionIdentityRef = useRef<string | null>(sessionSubscriptionIdentity);sessionSubscriptionIdentityRef.current = sessionSubscriptionIdentity;useEffect(() => () => {@@ -2539,19 +2546,21 @@ function SessionScreenContent() {// 立即渲染真壳(标题乐观显示、消息区骨架、输入框可编辑、发送禁用),而不是阻塞式占位。const showSyncingShell = sessionOperationLayout.composerSlot === 'missing-session'&& !remoteUnavailableReason;- // 同步/加载期消息区不显示「暂无消息」(会话其实在加载、不是空),改为渲染「正在同步」- // loading 占位(MessageRenderer 的 SyncingMessages);看过的会话- // 此时已被本地缓存(②)填充正常渲染,不进 empty 分支。还包含冷开首帧:currentSession 立即- // 就有但消息未到、loading 尚未翻 true 的窗口(本次打开未同步过)。只有同步完成过- // (lastSyncedAt 有值)且确实 0 条时才显示「暂无消息」;离线/被撤销(remoteUnavailableReason)- // 不进此分支,保留原占位。判定见 shouldSuppressEmptyMessageState。- const syncingWhileEmpty = shouldSuppressEmptyMessageState({+ // 无内容且读取结果未知时显示同步占位;已知远端不可用时解释历史未缓存。+ // 成功读取的历史(含恢复的空缓存)可以确认空态,新活动后的旧结果必须等待重读。+ const messageEmptyState = resolveSessionMessageEmptyState({loading,showSyncingShell,- messageCount: historyView.snapshot.ready ? historyView.snapshot.items.length : messages.length,- hasSyncedThisOpen: lastSyncedAt !== null,- remoteUnavailable: !!remoteUnavailableReason || status !== 'online' || targetAvailableForDispatch === false,+ subscriptionIdentity: sessionSubscriptionIdentity,+ historyRead: messageHistoryRead,+ historySnapshot: historyView.snapshot,+ messageCount: messages.length,+ status,+ targetAvailable: targetAvailableForDispatch,+ remoteUnavailableReason,+ historyNotCachedMessage: t('message.renderer.historyNotCached'),});+ const { syncingWhileEmpty } = messageEmptyState;const voiceIsProcessing = voiceState === 'submitting' || voiceState === 'refining';const composerSendUnavailableReason = canUseComposer ? null : composerDisabledReason;// 手机语音只保留官方托管路径,错误引导仅剩系统麦克风权限一条。@@ -3802,6 +3811,12 @@ function SessionScreenContent() {&& syncedNotificationResponseRef.current !== notificationResponse;let usedHistoryView = false;const messageRead = syncSessionMessageWindow({+ historyConfirmation: {+ key: subscriptionIdentityAtStart,+ generation: readAckGateGenAtStart,+ generationRef: readAckGateGenRef,+ commit: setMessageHistoryRead,+ },readMetadata: () => retryRead(fetchSessionMetadata),isReopen,storedSession: storedSessionAtStart,@@ -3839,7 +3854,10 @@ function SessionScreenContent() {},isCurrent,commitMessages: (history) => {- if (usedHistoryView) { messageWindowReconciledRef.current = true; return; }+ if (usedHistoryView) {+ messageWindowReconciledRef.current = true;+ return;+ }const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);if (options.replaceMessages) {@@ -4194,19 +4212,16 @@ function SessionScreenContent() {if (!activity) return 'none';return `${activity.phase}|${activity.attention === true ? 1 : 0}|${activity.compactDetail}`;});- const prevLiveActivitySigRef = useRef<string | null>(null);- useEffect(() => {- const prevSig = prevLiveActivitySigRef.current ?? liveActivitySig;- if (liveAttention && liveActivitySig !== prevSig) {- setReadAckSyncedKey(null);- setSessionMetadataSyncedKey(null);- // 代号递增:变化点之前启动的 in-flight load / 在飞重试(数据不含本 turn 终帧)- // 不得重新落 key / 不得继续发送。- readAckGateGenRef.current += 1;- void load();- }- prevLiveActivitySigRef.current = liveActivitySig;- }, [liveActivitySig, liveAttention, load]);+ useSessionActivityInvalidation({+ liveActivitySig,+ liveAttention,+ sessionSubscriptionIdentity,+ readAckGateGenRef,+ setReadAckSyncedKey,+ setSessionMetadataSyncedKey,+ setMessageHistoryRead,+ load,+ });// 领取其它路由(文件浏览器「发送到会话」等)投递的 composer 附件:会话页在// 栈下层保持挂载,返回不会重新 mount,靠 focus 时机领取信箱。@@ -10104,9 +10119,7 @@ function SessionScreenContent() {busyClientId={messageActionBusy?.clientId ?? null}canLoadEarlier={canLoadEarlierHistory}emptyTestID="session.messageList.empty"- emptyMessage={companionChat && lastSyncedAt === null- && (status !== 'online' || targetAvailableForDispatch === false)- ? t('message.renderer.historyNotCached') : undefined}+ emptyMessage={messageEmptyState.emptyMessage}focusedItemKey={focusedMessageItemKey ?? null}focusedRequestKey={focusedMessageRequestKey}followLatestRequestKey={messageListFollowLatestRequestKey}diff --git a/apps/mobile/src/__tests__/sessionEmptyState.test.ts b/apps/mobile/src/__tests__/sessionEmptyState.test.tsindex 72ee878846..dd7ef34fe8 100644--- a/apps/mobile/src/__tests__/sessionEmptyState.test.ts+++ b/apps/mobile/src/__tests__/sessionEmptyState.test.ts@@ -5,9 +5,13 @@ import * as React from 'react';import { describe, expect, it, vi } from 'vitest';import { resolveEffectiveConnectionError } from '@/components/connectionBannerVisibility';import {+ resolveSessionMessageEmptyState,+ type SessionMessageEmptyStateInput,shouldSuppressEmptyMessageState,shouldSuppressRemoteListEmptyState,} from '@/session/sessionEmptyState';+import { HistoryViewController } from '@cindy/maker-shared/message-window';+import zhMessages from '@/i18n/locales/zh-CN/message.json';// Run the real detail-page sync callback without loading native navigation.// Existing policy tests cannot detect an old active/archive response publishing@@ -132,6 +136,45 @@ const base = {remoteUnavailable: false,};+// #6519 / #6527, unit: these presentation cases import the screen's production+// selector directly. Legacy page callback fixtures could not exercise a restored+// empty cache without also extracting unrelated screen source.+describe('session message empty presentation', () => {+ const input: SessionMessageEmptyStateInput = {+ subscriptionIdentity: JSON.stringify(['d1', 's1', 1]), historyRead: null,+ historySnapshot: { ready: false, items: [] }, messageCount: 0,+ loading: false, showSyncingShell: false, remoteUnavailableReason: null,+ status: 'online', targetAvailable: true,+ historyNotCachedMessage: zhMessages.renderer.historyNotCached,+ };++ it('explains uncached offline history immediately', () => {+ expect(resolveSessionMessageEmptyState({ ...input, status: 'stopped' })).toEqual({+ syncingWhileEmpty: false, emptyMessage: '历史消息尚未缓存,连接电脑后同步',+ });+ });++ it('honors an empty restored history cache on an offline cold reopen', async () => {+ const view = new HistoryViewController({+ page: async () => ({ version: 1 as const, items: [], hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1 as const, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ view.setNetworkAvailable(false);+ await view.restoreCachedView(async () => ({ ...view.getSnapshot(), ready: true }));+ expect(resolveSessionMessageEmptyState({ ...input, status: 'stopped', historySnapshot: view.getSnapshot() }))+ .toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });++ it.each([+ { status: 'connecting', presence: null, syncing: true, copy: undefined },+ { status: 'online', presence: false, syncing: false, copy: '历史消息尚未缓存,连接电脑后同步' },+ ] as const)('distinguishes $status with presence=$presence from confirmed unavailability', ({ status, presence, syncing, copy }) => {+ expect(resolveSessionMessageEmptyState({ ...input, status, targetAvailable: presence }))+ .toEqual({ syncingWhileEmpty: syncing, emptyMessage: copy });+ });+});+describe('shouldSuppressEmptyMessageState', () => {it('suppresses the empty state on cold open before the first sync (0 msgs, not synced, online)', () => {// 冷开首帧:currentSession 立即有、消息未到、loading 还没翻 true → 抑制,渲染同步占位而非闪"暂无消息"。diff --git a/apps/mobile/src/__tests__/sessionMessageWindowSync.test.ts b/apps/mobile/src/__tests__/sessionMessageWindowSync.test.tsindex 01ec1de1db..1f5d4ebea6 100644--- a/apps/mobile/src/__tests__/sessionMessageWindowSync.test.ts+++ b/apps/mobile/src/__tests__/sessionMessageWindowSync.test.ts@@ -2,6 +2,9 @@ import { describe, expect, it, vi } from 'vitest';import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';import { shouldKeepOlderMessagesAffordance, type MessagePageRetryResult } from '@/session/messagePaging';import type { RemoteMessage, RemoteSession } from '@/session/types';+import { resolveSessionMessageEmptyState, type MessageHistoryRead, type SessionMessageEmptyStateInput } from '@/session/sessionEmptyState';+import { waitForIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';+import zhMessages from '@/i18n/locales/zh-CN/message.json';function deferred<T>() {let resolve!: (value: T) => void;@@ -28,6 +31,103 @@ function fixture(isReopen = false) {};}+function historyFixture() {+ const state = { historyRead: null as MessageHistoryRead | null };+ const generationRef = { current: 1 };+ const input = {+ ...fixture(),+ historyConfirmation: {+ key: JSON.stringify(['d1', 's1', 1]), generation: 1, generationRef,+ commit: (read: MessageHistoryRead) => { state.historyRead = read; },+ },+ };+ input.readLatest.mockResolvedValue({ ...page, messages: [] });+ const presentation = (overrides: Partial<SessionMessageEmptyStateInput> = {}) => resolveSessionMessageEmptyState({+ subscriptionIdentity: input.historyConfirmation.key, historyRead: state.historyRead,+ historySnapshot: { ready: false, items: [] }, messageCount: 0,+ loading: false, showSyncingShell: false, remoteUnavailableReason: null,+ status: 'online', targetAvailable: true,+ historyNotCachedMessage: zhMessages.renderer.historyNotCached,+ ...overrides,+ });+ return { input, state, presentation };+}++// #6519 / #6527, unit: execute the production history sync entry, including its+// visit fence and success marking, then assert the production presentation.+// Legacy AST callback cases bypassed this import boundary. Empty history plus a+// failed sibling read, reconnect, or late visit is the smallest missing input.+describe('history confirmation and empty presentation', () => {+ it('preserves invalidation across reconnect and a failed history read', async () => {+ const f = historyFixture();+ await syncSessionMessageWindow(f.input);+ f.state.historyRead = { key: f.input.historyConfirmation.key, synced: false };+ f.input.historyConfirmation.key = JSON.stringify(['d1', 's1', 2]);+ const cached = { historySnapshot: { ready: true, items: [] } };+ expect(f.presentation({ ...cached, status: 'connecting', targetAvailable: null }))+ .toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ f.input.readLatest.mockRejectedValueOnce(new Error('[INVOKE_TIMEOUT] history'));+ await expect(syncSessionMessageWindow(f.input)).rejects.toThrow('history');+ expect(f.presentation(cached)).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ expect(f.presentation({ ...cached, status: 'stopped' })).toEqual({+ syncingWhileEmpty: false, emptyMessage: '历史消息尚未缓存,连接电脑后同步',+ });+ await syncSessionMessageWindow(f.input);+ expect(f.presentation(cached)).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });++ it('requires an uncached task to read its own history after a different task synced', async () => {+ const f = historyFixture();+ await syncSessionMessageWindow(f.input);+ expect(f.presentation()).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ f.input.historyConfirmation.key = JSON.stringify(['d1', 's2', 2]);+ expect(f.presentation({ status: 'stopped' })).toEqual({+ syncingWhileEmpty: false, emptyMessage: '历史消息尚未缓存,连接电脑后同步',+ });+ expect(f.presentation()).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ f.input.readMetadata.mockResolvedValue({ ...session, id: 's2' });+ await syncSessionMessageWindow(f.input);+ expect(f.presentation()).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });++ it.each(['metadata', 'projection'])('recognizes fetched empty history even if %s fails', async (failedRead) => {+ const f = historyFixture();+ const failure = new Error(`[INVOKE_TIMEOUT] ${failedRead}`);+ if (failedRead === 'metadata') f.input.readMetadata.mockRejectedValue(failure);+ await expect(waitForIndependentSnapshotReads([+ syncSessionMessageWindow(f.input),+ failedRead === 'projection' ? Promise.reject(failure) : Promise.resolve(),+ ])).rejects.toThrow(failedRead);+ expect(f.presentation()).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });++ it.each(['visit', 'connection'])('does not let a late empty read certify a later %s', async (change) => {+ const f = historyFixture();+ const history = deferred<MessagePageRetryResult>();+ f.input.readLatest.mockReturnValueOnce(history.promise);+ const result = syncSessionMessageWindow(f.input);+ if (change === 'visit') f.input.historyConfirmation.generationRef.current += 1;+ else f.input.isCurrent.mockReturnValue(false);+ history.resolve({ ...page, messages: [] });+ await result;+ expect(f.presentation({ status: 'stopped' })).toEqual({+ syncingWhileEmpty: false, emptyMessage: '历史消息尚未缓存,连接电脑后同步',+ });+ });++ it('confirms a verified unchanged cached window without fetching another page', async () => {+ const f = historyFixture();+ const emptySession = { ...session, _count: { messages: 0 } };+ f.input.isReopen = true;+ f.input.storedSession = emptySession;+ f.input.readMetadata.mockResolvedValue(emptySession);+ f.input.isWindowSynced.mockReturnValue(true);+ await syncSessionMessageWindow(f.input);+ expect(f.input.readLatest).not.toHaveBeenCalled();+ expect(f.presentation({ status: 'stopped' })).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });+});+describe('independent session history sync', () => {it.each([false, true])('commits history and preserves pagination when projection fails (reopen=%s)', async (isReopen) => {const input = fixture(isReopen);diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.tsindex 0b3141c32c..671f695e8f 100644--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts@@ -21,11 +21,15 @@ import { HistoryViewController, isHistoryViewUnavailable, projectHistoryView } fconst source = ts.createSourceFile('screen.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8',), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const compiledCallbacks = new Map<string, string>();function pageCallback(name: string, bindings: Record<string, unknown>): (...args: any[]) => Promise<void> {+ const cached = compiledCallbacks.get(name);+ if (cached) return new Function(...Object.keys(bindings), `${cached}\nreturn callback;`)(...Object.values(bindings));let expression: ts.Expression | undefined;const visit = (node: ts.Node) => {if (ts.isVariableDeclaration(node) && node.name.getText(source) === name- && node.initializer && ts.isCallExpression(node.initializer)) {+ && node.initializer && ts.isCallExpression(node.initializer)+ && node.initializer.expression.getText(source) === 'useCallback') {expression = node.initializer.arguments[0];}ts.forEachChild(node, visit);@@ -35,6 +39,7 @@ function pageCallback(name: string, bindings: Record<string, unknown>): (...argsconst compiled = ts.transpileModule(`const callback = ${expression.getText(source)};`, {compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },}).outputText;+ compiledCallbacks.set(name, compiled);return new Function(...Object.keys(bindings), `${compiled}\nreturn callback;`)(...Object.values(bindings));}function deferred<T>() {@@ -139,6 +144,7 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {setOutboxTransportHold: (update: (value: typeof state.hold) => typeof state.hold) => { state.hold = update(state.hold); },latchOutboxTransportHold: (error: string) => { state.hold = { deviceId: 'd1', error }; },setLastSyncedAt: (value: number) => { state.synced = value; },+ setMessageHistoryRead: vi.fn(),setContentSyncedKey: vi.fn(), contentRecoveryKeyRef: { current: null },setSessionMetadataSyncedKey: vi.fn(),setReadAckSyncedKey: (value: string) => { state.readAck = value; },diff --git a/apps/mobile/src/__tests__/useSessionActivityInvalidation.test.tsx b/apps/mobile/src/__tests__/useSessionActivityInvalidation.test.tsxnew file mode 100644index 0000000000..2ee5f01e7a--- /dev/null+++ b/apps/mobile/src/__tests__/useSessionActivityInvalidation.test.tsx@@ -0,0 +1,142 @@+// @vitest-environment jsdom+import { act, createElement, useState } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { useSessionActivityInvalidation } from '@/session/useSessionActivityInvalidation';+import { useSessionMessageHistoryRead } from '@/session/useSessionMessageHistoryRead';+import { resolveSessionMessageEmptyState, type MessageHistoryRead } from '@/session/sessionEmptyState';+import zhMessages from '@/i18n/locales/zh-CN/message.json';++// #6527: exercise the production hook through React mount and dependency updates.+// AST callback tests bypassed effects and stale closures; a signature change with+// attention already true is the smallest missed input. Unit/jsdom is separate+// from the Node sync tests because only these cases need React DOM and effects.+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+const cleanups: Array<() => void> = [];+afterEach(() => { cleanups.splice(0).forEach(cleanup => cleanup()); });+const initialIdentity = JSON.stringify(['d1', 's1', 1]);+const reconnectIdentity = JSON.stringify(['d1', 's1', 2]);+type ActivityProps = Pick<Parameters<typeof useSessionActivityInvalidation>[0],+ 'liveActivitySig' | 'liveAttention' | 'sessionSubscriptionIdentity' | 'load'>+ & Pick<Parameters<typeof useSessionMessageHistoryRead>[0], 'deviceId' | 'sessionId' | 'notificationResponse'>;++function mountActivity(ready = true, notificationResponse: string | null = null) {+ const gate = { current: 1 };+ const loadGenerations: number[] = [];+ const load = vi.fn(async () => { loadGenerations.push(gate.current); });+ let props: ActivityProps = {+ deviceId: 'd1', sessionId: 's1', notificationResponse,+ liveActivitySig: 'completed|1|old result', liveAttention: true,+ sessionSubscriptionIdentity: initialIdentity, load,+ };+ let state!: {+ historyRead: MessageHistoryRead | null;+ readAck: string | null;+ metadata: string | null;+ setHistoryRead: (read: MessageHistoryRead | null) => void;+ emptyState: ReturnType<typeof resolveSessionMessageEmptyState>;+ };+ function presentation(historyRead: MessageHistoryRead | null, status: 'online' | 'stopped' = 'online') {+ return resolveSessionMessageEmptyState({+ loading: false, showSyncingShell: false, messageCount: 0,+ subscriptionIdentity: props.sessionSubscriptionIdentity,+ historyRead, historySnapshot: { ready, items: [] },+ status, targetAvailable: true, remoteUnavailableReason: null,+ historyNotCachedMessage: zhMessages.renderer.historyNotCached,+ });+ }+ function Harness({ value }: { value: ActivityProps }) {+ const [historyRead, setHistoryRead] = useSessionMessageHistoryRead({+ ...value, subscriptionIdentity: value.sessionSubscriptionIdentity,+ });+ const [readAck, setReadAck] = useState<string | null>('read');+ const [metadata, setMetadata] = useState<string | null>('metadata');+ useSessionActivityInvalidation({+ ...value, readAckGateGenRef: gate, setReadAckSyncedKey: setReadAck,+ setSessionMetadataSyncedKey: setMetadata, setMessageHistoryRead: setHistoryRead,+ });+ state = { historyRead, readAck, metadata, setHistoryRead, emptyState: presentation(historyRead) };+ return null;+ }+ const root = createRoot(document.createElement('div'));+ const rerender = (next: Partial<ActivityProps> = {}) => {+ props = { ...props, ...next };+ act(() => root.render(createElement(Harness, { value: props })));+ };+ cleanups.push(() => act(() => root.unmount()));+ rerender();+ return { gate, load, loadGenerations, rerender, get state() { return state; },+ offline: () => presentation(state.historyRead, 'stopped'),+ };+}++describe('useSessionActivityInvalidation', () => {+ // #6527 notification review, unit/jsdom: activity-only cases never changed the+ // visit. A new notification plus a ready empty cache must stay unknown before+ // a successful read, including on the first mount and after reconnect.+ it.each(['cold-open', 'new-visit'])('invalidates cached empty history for a notification %s', (entry) => {+ const h = mountActivity(true, entry === 'cold-open' ? 'notification-1' : null);+ if (entry === 'new-visit') {+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ h.rerender({ notificationResponse: 'notification-1' });+ }+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ expect(h.offline()).toEqual({ syncingWhileEmpty: false, emptyMessage: '历史消息尚未缓存,连接电脑后同步' });+ h.rerender({ sessionSubscriptionIdentity: reconnectIdentity });+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ act(() => h.state.setHistoryRead({ key: reconnectIdentity, synced: true }));+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ h.rerender({ notificationResponse: 'notification-2' });+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ h.rerender({ deviceId: 'd2', sessionId: 's2', notificationResponse: null,+ sessionSubscriptionIdentity: JSON.stringify(['d2', 's2', 1]) });+ expect(h.offline()).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });++ it('keeps the existing empty result on mount and unrelated renders', () => {+ const h = mountActivity();+ h.rerender();+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ expect(h.state.readAck).toBe('read');+ expect(h.state.metadata).toBe('metadata');+ expect(h.gate.current).toBe(1);+ expect(h.load).not.toHaveBeenCalled();+ });++ it.each([false, true])('invalidates empty history on signature changes (ready cache=%s)', (ready) => {+ const h = mountActivity(ready);+ h.rerender({ liveActivitySig: 'completed|1|new result' });+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ expect(h.offline()).toEqual({ syncingWhileEmpty: false, emptyMessage: '历史消息尚未缓存,连接电脑后同步' });+ expect(h.state.readAck).toBeNull();+ expect(h.state.metadata).toBeNull();+ expect(h.loadGenerations).toEqual([2]);+ act(() => h.state.setHistoryRead({ key: initialIdentity, synced: true }));+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });++ it('does not invalidate when activity changes without attention', () => {+ const h = mountActivity();+ h.rerender({ liveActivitySig: 'completed|0|acknowledged', liveAttention: false });+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ expect(h.gate.current).toBe(1);+ expect(h.load).not.toHaveBeenCalled();+ });++ it('retains invalidation on reconnect and uses the latest load and identity for later activity', () => {+ const h = mountActivity();+ h.rerender({ liveActivitySig: 'completed|1|new result' });+ const newLoadGenerations: number[] = [];+ const newLoad = vi.fn(async () => { newLoadGenerations.push(h.gate.current); });+ h.rerender({ sessionSubscriptionIdentity: reconnectIdentity, load: newLoad });+ expect(h.state.historyRead).toEqual({ key: initialIdentity, synced: false });+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: true, emptyMessage: undefined });+ expect(newLoad).not.toHaveBeenCalled();+ h.rerender({ liveActivitySig: 'completed|1|newer result' });+ expect(h.state.historyRead).toEqual({ key: reconnectIdentity, synced: false });+ expect(h.load).toHaveBeenCalledOnce();+ expect(newLoadGenerations).toEqual([3]);+ act(() => h.state.setHistoryRead({ key: reconnectIdentity, synced: true }));+ expect(h.state.emptyState).toEqual({ syncingWhileEmpty: false, emptyMessage: undefined });+ });+});diff --git a/apps/mobile/src/session/sessionEmptyState.ts b/apps/mobile/src/session/sessionEmptyState.tsindex 5afa273e34..1c20806427 100644--- a/apps/mobile/src/session/sessionEmptyState.ts+++ b/apps/mobile/src/session/sessionEmptyState.ts@@ -1,3 +1,5 @@+import type { DeviceLinkStatus } from '@cindy/device-link';+/*** 会话消息区"空状态"(暂无消息)是否应被抑制的纯判定。判定为 true 时消息区渲染* 「正在同步」loading 占位(MessageRenderer 的 SyncingMessages)而非「暂无消息」。@@ -16,9 +18,9 @@ export interface MessageEmptyStateInput {showSyncingShell: boolean;/** 当前已加载的消息条数。 */messageCount: number;- /** 本次打开是否已完成过至少一次同步(lastSyncedAt != null)。 */+ /** 当前消息历史是否已成功读取或恢复缓存,且尚未被新活动作废。 */hasSyncedThisOpen: boolean;- /** 远端不可用(离线/被撤销)——此时保留原阻塞占位,不进抑制分支。 */+ /** 远端不可用(离线/被撤销)——允许显示历史未缓存说明,不进同步占位分支。 */remoteUnavailable: boolean;}@@ -29,6 +31,46 @@ export function shouldSuppressEmptyMessageState(input: MessageEmptyStateInput):return false;}+/** 当前访问的历史结果:切换任务/设备时重置,通知或新活动作废旧结果,重连保留。 */+export type MessageHistoryRead = { key: string; synced: boolean };++export interface SessionMessageEmptyStateInput {+ loading: boolean;+ showSyncingShell: boolean;+ subscriptionIdentity: string;+ historyRead: MessageHistoryRead | null;+ historySnapshot: { ready: boolean; items: readonly unknown[] };+ messageCount: number;+ status: DeviceLinkStatus;+ targetAvailable: boolean | null;+ remoteUnavailableReason: string | null;+ historyNotCachedMessage: string;+}++/** 连接中且可用性未知时继续等待,不据此要求用户重新连接电脑。 */+export function shouldShowCachedHistoryNotice(status: DeviceLinkStatus, targetAvailable: boolean | null): boolean {+ return status !== 'connecting' && (status !== 'online' || targetAvailable === false);+}++/** 结合历史读取结果与连接状态,统一决定同步占位和未缓存文案。 */+export function resolveSessionMessageEmptyState(input: SessionMessageEmptyStateInput) {+ // 新活动作废的是本次访问的旧历史;连接代推进不能凭旧缓存撤销失效标记。+ const hasSyncedHistory = input.historyRead?.synced !== false+ && (input.historyRead?.key === input.subscriptionIdentity || input.historySnapshot.ready);+ const remoteUnavailable = !!input.remoteUnavailableReason+ || shouldShowCachedHistoryNotice(input.status, input.targetAvailable);+ return {+ syncingWhileEmpty: shouldSuppressEmptyMessageState({+ loading: input.loading,+ showSyncingShell: input.showSyncingShell,+ messageCount: input.historySnapshot.ready ? input.historySnapshot.items.length : input.messageCount,+ hasSyncedThisOpen: hasSyncedHistory,+ remoteUnavailable,+ }),+ emptyMessage: !hasSyncedHistory && remoteUnavailable ? input.historyNotCachedMessage : undefined,+ };+}+/*** 远端列表页(自动化列表 / 设备会话列表)"空状态插画"是否应被抑制的纯判定。*diff --git a/apps/mobile/src/session/sessionMessageWindowSync.ts b/apps/mobile/src/session/sessionMessageWindowSync.tsindex ec09a1c6e6..2b363b3bb9 100644--- a/apps/mobile/src/session/sessionMessageWindowSync.ts+++ b/apps/mobile/src/session/sessionMessageWindowSync.ts@@ -3,6 +3,7 @@ import {type MessagePageRetryResult,} from '@/session/messagePaging';import type { RemoteSession } from '@/session/types';+import type { MessageHistoryRead } from '@/session/sessionEmptyState';import { readProgressiveMessageWindow } from '@/device-link/sessionSnapshotSingleFlight';interface SessionMessageWindowSync {@@ -15,6 +16,13 @@ interface SessionMessageWindowSync {isWindowSynced(session: RemoteSession): boolean;commitMessages?(page: MessagePageRetryResult): void;commit(session: RemoteSession, page: MessagePageRetryResult | null): void;+ /** 历史读取独立确认成功;generation 为启动时快照,ref 为当前访问代次。 */+ historyConfirmation?: {+ key: string;+ generation: number;+ generationRef: { current: number };+ commit(read: MessageHistoryRead): void;+ };}/**@@ -24,6 +32,13 @@ interface SessionMessageWindowSync {* still decided by the caller after all resources succeed.*/export async function syncSessionMessageWindow(input: SessionMessageWindowSync): Promise<void> {+ const markHistorySynced = () => {+ const confirmation = input.historyConfirmation;+ if (confirmation && input.isCurrent()+ && confirmation.generationRef.current === confirmation.generation) {+ confirmation.commit({ key: confirmation.key, synced: true });+ }+ };const { metadata: session, history: page } = await readProgressiveMessageWindow({readMetadata: input.readMetadata,readMessages: input.readLatest,@@ -34,7 +49,13 @@ export async function syncSessionMessageWindow(input: SessionMessageWindowSync):storedSession: input.storedSession,messageWindowSynced: input.isWindowSynced(metadata),}),- commitMessages: (history) => input.commitMessages?.(history),+ commitMessages: (history) => {+ input.commitMessages?.(history);+ markHistorySynced();+ },});- if (input.isCurrent()) input.commit(session, page);+ if (input.isCurrent()) {+ input.commit(session, page);+ if (page === null) markHistorySynced();+ }}diff --git a/apps/mobile/src/session/useSessionActivityInvalidation.ts b/apps/mobile/src/session/useSessionActivityInvalidation.tsnew file mode 100644index 0000000000..a66f60ec2f--- /dev/null+++ b/apps/mobile/src/session/useSessionActivityInvalidation.ts@@ -0,0 +1,38 @@+import { useEffect, useRef } from 'react';+import type { MessageHistoryRead } from './sessionEmptyState';++/** 新活动后重新读取历史,避免旧窗口提前放行已读回执或确认空态。 */+export function useSessionActivityInvalidation({+ liveActivitySig,+ liveAttention,+ sessionSubscriptionIdentity,+ readAckGateGenRef,+ setReadAckSyncedKey,+ setSessionMetadataSyncedKey,+ setMessageHistoryRead,+ load,+}: {+ liveActivitySig: string;+ liveAttention: boolean;+ sessionSubscriptionIdentity: string;+ readAckGateGenRef: { current: number };+ setReadAckSyncedKey: (key: string | null) => void;+ setSessionMetadataSyncedKey: (key: string | null) => void;+ setMessageHistoryRead: (read: MessageHistoryRead | null) => void;+ load: () => Promise<void>;+}) {+ const prevLiveActivitySigRef = useRef<string | null>(null);+ useEffect(() => {+ const prevSig = prevLiveActivitySigRef.current ?? liveActivitySig;+ if (liveAttention && liveActivitySig !== prevSig) {+ setReadAckSyncedKey(null);+ setSessionMetadataSyncedKey(null);+ setMessageHistoryRead({ key: sessionSubscriptionIdentity, synced: false });+ // 变化前启动的读取不能重新确认历史;先推进代次,再启动新读取。+ readAckGateGenRef.current += 1;+ void load();+ }+ prevLiveActivitySigRef.current = liveActivitySig;+ }, [liveActivitySig, liveAttention, sessionSubscriptionIdentity, readAckGateGenRef,+ setReadAckSyncedKey, setSessionMetadataSyncedKey, setMessageHistoryRead, load]);+}diff --git a/apps/mobile/src/session/useSessionMessageHistoryRead.ts b/apps/mobile/src/session/useSessionMessageHistoryRead.tsnew file mode 100644index 0000000000..3b2b15a10a--- /dev/null+++ b/apps/mobile/src/session/useSessionMessageHistoryRead.ts@@ -0,0 +1,27 @@+import { useState } from 'react';+import type { MessageHistoryRead } from './sessionEmptyState';++/** 历史读取结果按任务访问隔离,连接代变化保留当前访问的失效状态。 */+export function useSessionMessageHistoryRead({+ deviceId,+ sessionId,+ notificationResponse,+ subscriptionIdentity,+}: {+ deviceId: string;+ sessionId: string;+ notificationResponse: string | null;+ subscriptionIdentity: string;+}) {+ const visitKey = JSON.stringify([deviceId, sessionId, notificationResponse]);+ // 通知意味着远端可能已有新消息,旧缓存不能确认本次访问为空。+ const initialHistoryRead: MessageHistoryRead | null = notificationResponse === null+ ? null : { key: subscriptionIdentity, synced: false };+ const [previousVisitKey, setPreviousVisitKey] = useState(visitKey);+ const [historyRead, setHistoryRead] = useState(initialHistoryRead);+ if (previousVisitKey !== visitKey) {+ setPreviousVisitKey(visitKey);+ setHistoryRead(initialHistoryRead);+ }+ return [historyRead, setHistoryRead] as const;+}