Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 防止迟到缓存写入覆盖已确认消息
Dash4910a52700e8
diff --git a/apps/mobile/src/__tests__/outboxHistoryCache.test.ts b/apps/mobile/src/__tests__/outboxHistoryCache.test.tsindex e5dc7bc8ab..b1af800a9a 100644--- a/apps/mobile/src/__tests__/outboxHistoryCache.test.ts+++ b/apps/mobile/src/__tests__/outboxHistoryCache.test.ts@@ -1,9 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'node:fs';+import ts from 'typescript';import { HistoryViewController, projectHistoryView, type HistoryViewPage } from '@cindy/maker-shared/message-window';import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { cacheOutboxHistory } from '@/session/outboxHistoryCache';import { clearHistoryDisk, historyDiskAuthority, readHistoryDisk } from '@/session/remoteHistoryDiskCache';-import { getCachedSessionMessages } from '@/session/mobileSessionMessageCache';+import { cacheSessionMessagesIfCurrent, captureSessionMessageCacheWriteAuthority, getCachedSessionMessages } from '@/session/mobileSessionMessageCache';+import { remoteSessionStore } from '@/session/remoteSessionStore';import { clearRemoteHistoryViews, getRemoteHistoryView, mountRemoteHistoryView } from '@/session/remoteHistoryViews';import type { RemoteMessage } from '@/session/types';@@ -50,6 +53,27 @@ async function opened(rows: RemoteMessage[], error?: string) {return { entry, source };}const save = (current = () => true) => cacheOutboxHistory('d', 's', 'sent', current);+// Execute the actual unmount effect without mounting the native message screen.+const source = ts.createSourceFile('remoteSessionStore.ts', readFileSync(+ new URL('../session/remoteSessionStore.ts', import.meta.url), 'utf8'), ts.ScriptTarget.Latest, true);+const hook = source.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'useSessionMessageCacheSync')!;+let cleanupSource = '';+function findCleanup(node: ts.Node) {+ if (ts.isCallExpression(node) && node.expression.getText(source) === 'useEffect') {+ const callback = node.arguments[0];+ if (ts.isArrowFunction(callback) && ts.isArrowFunction(callback.body)) cleanupSource = callback.body.getText(source);+ }+ ts.forEachChild(node, findCleanup);+}+findCleanup(hook);+function flushUnmount(rendered: RemoteMessage[]) {+ const bindings = { persistTimerRef: { current: setTimeout(() => {}, 60_000) },+ ctxRef: { current: { deviceId: 'd', sessionId: 's', messages: rendered } },+ remoteSessionStore, captureSessionMessageCacheWriteAuthority, cacheSessionMessagesIfCurrent, clearTimeout };+ const js = ts.transpileModule(`const { ${Object.keys(bindings).join(',')} } = bindings; (${cleanupSource})();`,+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ new Function('bindings', js)(bindings);+}beforeEach(() => { state.rows = [row('sent', 2)]; state.fail = false; setMobileAuthOwner('a'); });afterEach(async () => {state.fail = false;@@ -134,6 +158,30 @@ describe('outbox to offline history handoff', () => {expect(await save()).toBe(true);expect(await getCachedSessionMessages('d', 's')).toEqual(state.rows);});+ it('rejects a pre-handoff debounce write queued after raw fallback was saved', async () => {+ await opened([], 'UNSUPPORTED_CAPABILITY');+ const staleAuthority = captureSessionMessageCacheWriteAuthority('d', 's');+ expect(await save()).toBe(true);+ expect(await cacheSessionMessagesIfCurrent(staleAuthority, [row('previous', 1)])).toBe(false);+ expect(await getCachedSessionMessages('d', 's')).toEqual(state.rows);+ });+ it.each(['before', 'after'])('unmount %s handoff reads store ingress newer than the last render', async (order) => {+ await opened([], 'UNSUPPORTED_CAPABILITY');+ const rendered = [row('previous', 1)];+ state.rows = [...rendered, row('sent', 2)];+ if (order === 'before') flushUnmount(rendered);+ expect(await save()).toBe(true);+ if (order === 'after') flushUnmount(rendered);+ expect(await getCachedSessionMessages('d', 's')).toEqual(state.rows);+ });+ it('unmount after raw store eviction preserves the confirmed disk window', async () => {+ await opened([], 'UNSUPPORTED_CAPABILITY');+ expect(await save()).toBe(true);+ const saved = state.rows;+ state.rows = [];+ flushUnmount([row('previous', 1)]);+ expect(await getCachedSessionMessages('d', 's')).toEqual(saved);+ });it('does not release on logout or a stale sender', async () => {await opened([row('sent', 2)]);expect(await save(() => false)).toBe(false);diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.tsindex e89ed55882..3629cfb200 100644--- a/apps/mobile/src/session/mobileSessionMessageCache.ts+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts@@ -114,12 +114,12 @@ export async function replaceCachedSessionMessages(deviceId: string,sessionId: string,messages: readonly RemoteMessage[],-): Promise<void> {+): Promise<boolean> {const key = safeStorageKey(deviceId, sessionId);- if (!key) return;+ if (!key) return false;keyWriteEpochs.set(key, (keyWriteEpochs.get(key) ?? 0) + 1);const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);- await cacheSessionMessagesIfCurrent(authority, messages);+ return cacheSessionMessagesIfCurrent(authority, messages);}// 读取某 (host, session) 的缓存消息;无缓存 / 解析失败一律返回空数组(乐观 hydrate 不应抛错)。diff --git a/apps/mobile/src/session/outboxHistoryCache.ts b/apps/mobile/src/session/outboxHistoryCache.tsindex 58b523cec6..13ac23f01f 100644--- a/apps/mobile/src/session/outboxHistoryCache.ts+++ b/apps/mobile/src/session/outboxHistoryCache.ts@@ -1,5 +1,5 @@import { historyViewLeaves, isHistoryViewUnavailable, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';-import { cacheSessionMessagesIfCurrent, captureSessionMessageCacheWriteAuthority } from './mobileSessionMessageCache';+import { replaceCachedSessionMessages } from './mobileSessionMessageCache';import { historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from './remoteHistoryDiskCache';import { findRemoteHistoryView } from './remoteHistoryViews';import { remoteSessionStore } from './remoteSessionStore';@@ -37,8 +37,8 @@ export async function cacheOutboxHistory(if (snapshot && isHistoryViewUnavailable(snapshot.error)) {// Older hosts render the raw window. Do not turn a scheduled task into a long-term cache.if (remoteSessionStore.getSessionRetention(sessionId) !== 'regular') return true;- const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);- return await cacheSessionMessagesIfCurrent(authority, messages) && isCurrent();+ // Revoke pre-handoff debounce writes before the existing serialized replacement.+ return await replaceCachedSessionMessages(deviceId, sessionId, messages) && isCurrent();}const authority = historyDiskAuthority(deviceId, sessionId);if (snapshot && coversMessage(snapshot, message)) {diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 808fc769e2..c01fb00543 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -5969,10 +5969,14 @@ function useSessionMessageCacheSync(clearTimeout(persistTimerRef.current);persistTimerRef.current = null;const ctx = ctxRef.current;- if (!ctx.deviceId || !ctx.sessionId || ctx.messages.length === 0) return;+ if (!ctx.deviceId || !ctx.sessionId) return;if (remoteSessionStore.getSessionRetention(ctx.sessionId) !== 'regular') return;+ // Store ingress can precede the last React render. A fresh write authority+ // must use fresh rows, never the render snapshot from before an outbox handoff.+ const latestMessages = remoteSessionStore.getMessages(ctx.sessionId);+ if (latestMessages.length === 0) return;const cacheAuthority = captureSessionMessageCacheWriteAuthority(ctx.deviceId, ctx.sessionId);- void cacheSessionMessagesIfCurrent(cacheAuthority, ctx.messages).catch(() => undefined);+ void cacheSessionMessagesIfCurrent(cacheAuthority, latestMessages).catch(() => undefined);}, []);}