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。

fix(mobile): 优先用历史缓存结束旧消息发送等待

Dash099acc4be005
diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.ts
index 898bf99947..d9ebf5af62 100644
--- a/apps/mobile/src/__tests__/durableOutbox.test.ts
+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts
@@ -905,8 +905,9 @@ describe("app-owned delivery and reconciliation", () => {
restarted.deps.projection.mockResolvedValue(durable ? projection('id-1', 'accepted')
: { pendingQueue: [] } as unknown as DeliveryProjection);
const saved = deferred<boolean>();
- const run = createDurableOutboxDelivery({ ...restarted.deps, cacheHistory: () => saved.promise }).run();
- await vi.waitFor(() => expect(restarted.deps.history).toHaveBeenCalled());
+ const cacheRestoredHistory = vi.fn(() => saved.promise);
+ const run = createDurableOutboxDelivery({ ...restarted.deps, cacheHistory: cacheRestoredHistory }).run();
+ await vi.waitFor(() => expect(cacheRestoredHistory).toHaveBeenCalled());
expect(restarted.store.getSnapshot()[0]?.cleanupOutcome).toBeUndefined();
saved.resolve(true);
await run;
@@ -914,6 +915,32 @@ describe("app-owned delivery and reconciliation", () => {
expect(restarted.deps.enqueue).not.toHaveBeenCalled();
expect(restarted.deps.cleanup).toHaveBeenCalledOnce();
});
+ // Unit regression: a recovered host-owned record plus confirmed local history
+ // must retire its pending bubble even when projection/history RPCs are unavailable.
+ // Existing restart cases returned those RPCs before checking the local cache.
+ it('releases an already cached host-owned send before contacting the host', async () => {
+ const { store, deps } = await setup();
+ await store.add({ ...message(), state: 'host-owned', retrySafe: true });
+ deps.projection.mockRejectedValue(new Error('offline'));
+ await createDurableOutboxDelivery({ ...deps, cacheHistory: async () => true }).run();
+ expect(store.getSnapshot()).toEqual([]);
+ expect(deps.cleanup).toHaveBeenCalledOnce();
+ expect(deps.projection).not.toHaveBeenCalled();
+ expect(deps.history).not.toHaveBeenCalled();
+ expect(deps.enqueue).not.toHaveBeenCalled();
+ });
+ it.each(['unconfirmed', 'cancelling'] as const)('does not bypass remote reconciliation for a %s send', async (kind) => {
+ const { store, deps } = await setup();
+ await store.add({ ...message(), state: kind === 'cancelling' ? 'host-owned' : 'confirming',
+ retrySafe: true, cancelRequested: kind === 'cancelling' });
+ deps.projection.mockRejectedValue(new Error('offline'));
+ const cacheHistory = vi.fn(async () => true);
+ await createDurableOutboxDelivery({ ...deps, cacheHistory }).run();
+ expect(store.getSnapshot()).toHaveLength(1);
+ expect(cacheHistory).not.toHaveBeenCalled();
+ expect(deps.cleanup).not.toHaveBeenCalled();
+ expect(deps.projection).toHaveBeenCalledOnce();
+ });
it('does not block later legacy sends while the first confirmed row awaits caching', async () => {
const { store, deps } = await setup();
await store.add({ ...message(), state: 'host-owned', historyConfirmed: true, retrySafe: false,
diff --git a/apps/mobile/src/__tests__/outboxHistoryCache.test.ts b/apps/mobile/src/__tests__/outboxHistoryCache.test.ts
index b1af800a9a..ed9b58e10a 100644
--- a/apps/mobile/src/__tests__/outboxHistoryCache.test.ts
+++ b/apps/mobile/src/__tests__/outboxHistoryCache.test.ts
@@ -1,20 +1,22 @@
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 { cacheSessionMessagesIfCurrent, captureSessionMessageCacheWriteAuthority, getCachedSessionMessages } from '@/session/mobileSessionMessageCache';
-import { remoteSessionStore } from '@/session/remoteSessionStore';
+import { remoteSessionStore, useSessionMessages } from '@/session/remoteSessionStore';
import { clearRemoteHistoryViews, getRemoteHistoryView, mountRemoteHistoryView } from '@/session/remoteHistoryViews';
import type { RemoteMessage } from '@/session/types';
const state = vi.hoisted(() => ({ rows: [] as RemoteMessage[], fail: false,
+ effects: [] as Array<() => void | (() => void)>,
files: new Map<string, string>(), raw: new Map<string, string>() }));
-vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: {
- getMessages: () => state.rows, getSessionRetention: () => 'regular',
-} }));
+vi.mock('react', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react')>(),
+ useEffect: (effect: () => void | (() => void)) => { state.effects.push(effect); },
+ useRef: <T>(current: T) => ({ current }),
+ useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(),
+}));
vi.mock('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global' }));
vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({
read: async (name: string) => state.files.get(name) ?? null,
@@ -53,35 +55,52 @@ 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);
+// Run the production hook's effect lifecycle without loading a native renderer.
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);
+ const latest = state.rows;
+ state.rows = rendered;
+ useSessionMessages('s', 'd');
+ const cleanups = state.effects.splice(0).map(effect => effect());
+ state.rows = latest;
+ for (const cleanup of cleanups) cleanup?.();
}
-beforeEach(() => { state.rows = [row('sent', 2)]; state.fail = false; setMobileAuthOwner('a'); });
+beforeEach(() => {
+ state.rows = [row('sent', 2)]; state.fail = false; setMobileAuthOwner('a');
+ vi.spyOn(remoteSessionStore, 'getMessages').mockImplementation(() => state.rows);
+ vi.spyOn(remoteSessionStore, 'getSessionRetention').mockReturnValue('regular');
+});
afterEach(async () => {
state.fail = false;
releases.splice(0).forEach(release => release());
clearRemoteHistoryViews(); await clearHistoryDisk(); state.raw.clear(); setMobileAuthOwner(null);
+ vi.restoreAllMocks();
});
describe('outbox to offline history handoff', () => {
+ // Regression: reopened old tasks retain host-owned bubbles even though history
+ // already cached their user rows. Existing cases always populated the raw store.
+ // Unit: a cached user row, empty raw window, and no network response must suffice.
+ it('hands off a cached user row without fetching it back into the raw window', async () => {
+ const { source } = await opened([row('sent', 2)]);
+ expect(await save()).toBe(true);
+ releases.splice(0).forEach(release => release());
+ clearRemoteHistoryViews();
+ state.rows = [];
+ const entry = getRemoteHistoryView('d', 's', source);
+ entry.view.setNetworkAvailable(false);
+ releases.push(mountRemoteHistoryView(entry, source, true));
+ await entry.view.restoreCachedView(() => readHistoryDisk(historyDiskAuthority('d', 's')));
+ expect(entry.view.getSnapshot().stale).toBe(true);
+ expect(await save()).toBe(true);
+ expect(source.readHistoryView).toHaveBeenCalledTimes(1);
+ expect(JSON.stringify((await readHistoryDisk(historyDiskAuthority('d', 's')))?.items))
+ .toContain('message sent');
+ });
+ it('does not use another role with the same client id as proof of a sent user row', async () => {
+ await opened([{ ...row('sent', 2), role: 'assistant' }]);
+ state.rows = [];
+ expect(await save()).toBe(false);
+ });
it('retains display ownership when the page is absent or its snapshot predates the send', async () => {
expect(await save()).toBe(false);
await opened([row('previous', 1)]);
@@ -189,8 +208,11 @@ describe('outbox to offline history handoff', () => {
expect(await save()).toBe(false);
});
it('does not release a row removed by clear or rewind', async () => {
- const { entry } = await opened([row('sent', 2)]);
+ const { entry, source } = await opened([row('sent', 2)]);
state.rows = [];
+ // reset refreshes an active view: the host must reflect the deletion too,
+ // rather than reintroducing the row as new authoritative history.
+ source.readHistoryView.mockResolvedValue({ version: 1, items: [], hasMore: false, nextCursor: null });
entry.view.reset();
await clearHistoryDisk('d', 's');
expect(await save()).toBe(false);
diff --git a/apps/mobile/src/session/durableOutboxDelivery.ts b/apps/mobile/src/session/durableOutboxDelivery.ts
index 2dd3348a8f..edc55bdb50 100644
--- a/apps/mobile/src/session/durableOutboxDelivery.ts
+++ b/apps/mobile/src/session/durableOutboxDelivery.ts
@@ -117,6 +117,15 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
}
// Persisted completion never re-enters delivery, even after missing files or lost host history.
if (isDurableOutboxSettled(record)) return await finish();
+ // Reentry may restore history without restoring the raw message window.
+ // Its persisted user row is already sufficient proof for a host-owned
+ // send; do not keep its pending bubble behind projection/history RPCs.
+ if (hasDurableOwnership(record) && !record.cancelRequested && deps.cacheHistory
+ && await deps.cacheHistory(record)) {
+ if (current(record)) await finish();
+ return;
+ }
+ if (!current(record)) return;
let projection: DeliveryProjection;
try {
projection = await deps.projection(record);
diff --git a/apps/mobile/src/session/outboxHistoryCache.ts b/apps/mobile/src/session/outboxHistoryCache.ts
index 13ac23f01f..72a4704f22 100644
--- a/apps/mobile/src/session/outboxHistoryCache.ts
+++ b/apps/mobile/src/session/outboxHistoryCache.ts
@@ -6,11 +6,12 @@ import { remoteSessionStore } from './remoteSessionStore';
import type { RemoteMessage } from './types';
/** A sent row can age out of the latest window; it must not become a pending bubble forever. */
-function coversMessage(snapshot: HistoryViewSnapshot<RemoteMessage>, message: RemoteMessage): boolean {
+function coversMessage(snapshot: HistoryViewSnapshot<RemoteMessage>, clientId: string, message?: RemoteMessage): boolean {
if (!snapshot.ready) return false;
const leaves = historyViewLeaves(snapshot.items);
if (leaves.some(item => item.type === 'messages'
- && item.messages.some(row => row.role === 'user' && row.clientId === message.clientId))) return true;
+ && item.messages.some(row => row.role === 'user' && row.clientId === clientId))) return true;
+ if (!message) return false;
// User rows never fold into work. Skip leading work to find a stored boundary,
// and use the host's (createdAt, rowid) order, not import/insertion order alone.
const first = leaves.find(item => item.type === 'messages' && item.messages.length > 0);
@@ -31,17 +32,17 @@ export async function cacheOutboxHistory(
if (!isCurrent()) return false;
const messages = remoteSessionStore.getMessages(sessionId);
const message = messages.find(row => row.clientId === clientId && row.role === 'user');
- if (!message) return false;
const view = findRemoteHistoryView(deviceId, sessionId);
const snapshot = view?.getSnapshot();
if (snapshot && isHistoryViewUnavailable(snapshot.error)) {
+ if (!message) return false;
// Older hosts render the raw window. Do not turn a scheduled task into a long-term cache.
if (remoteSessionStore.getSessionRetention(sessionId) !== 'regular') return true;
// 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)) {
+ if (snapshot && coversMessage(snapshot, clientId, message)) {
// Only status flags change during a refresh; these items already contain the confirmed row.
const saved = await writeHistoryDisk(authority, { ...snapshot, loading: false, error: null });
return saved && authority.current() && isCurrent();
@@ -49,5 +50,5 @@ export async function cacheOutboxHistory(
// A mounted stale page still needs its local bubble even if disk is newer.
if (snapshot) return false;
const cached = await readHistoryDisk(authority);
- return !!cached && coversMessage(cached, message) && authority.current() && isCurrent();
+ return !!cached && coversMessage(cached, clientId, message) && authority.current() && isCurrent();
}
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 6be6d7376c..3cf5183db8 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -194,6 +194,9 @@ iOS 的系统选图器在确认后立即把选中项交给现有附件队列。
重开仍能显示,后续按 `clientId` 与正式历史去重。已交给电脑的消息在任务不可见时不为
显示交接继续轮询或保留原始消息窗口;重新进入后沿用现有调度完成交接。旧电脑使用原始
消息窗口缓存;消息已经早于最近缓存窗口时正常交接,不在末尾留下旧的待发送气泡。
+ 对账时已由电脑接管、且本地历史已包含同 `clientId` 用户行的记录,优先完成本地交接,
+ 不再先请求网络队列和历史;原始消息窗口为空不否定历史缓存的证据。未确认投递或正在
+ 取消的记录继续走原对账流程,缓存写入失败仍保留发件箱。
实现与回归见 `outboxHistoryCache.ts`、`outboxHistoryCache.test.ts`、`durableOutbox.test.ts`。
- 首页预读最新历史页时,复用聊天页的连续边界判据,保留能够衔接的已读历史及其分页游标,
不能直接把多页缓存缩成最新一页。已读工作详情只按内容版本是否有效保留,收起不等于
diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.json
index 7e6bccd993..bcda831f52 100644
--- a/scripts/test-hygiene-baseline.json
+++ b/scripts/test-hygiene-baseline.json
@@ -1020,9 +1020,6 @@
"apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts": {
"resetModules": 1
},
- "apps/mobile/src/__tests__/outboxHistoryCache.test.ts": {
- "realWaits": 1
- },
"apps/mobile/src/__tests__/remoteHistoryReentry.test.ts": {
"sourceReads": 1
},