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(device-link): 完成冷缓存交接并释放空闲历史视图

Dash90b8cec950cd
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
index 0453792960..a9770f43af 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
@@ -37,6 +37,11 @@ vi.mock('@/lib/sessionService', () => ({
touchUserSend: vi.fn(async () => ({})),
}));
vi.mock('@/lib/sessionsBus', () => ({ emitPatch: vi.fn() }));
+vi.mock('@/features/device-link/mirrorCacheClient', async (importOriginal) => ({
+ ...await importOriginal<typeof import('@/features/device-link/mirrorCacheClient')>(),
+ readCachedMessages: vi.fn(async () => []),
+ clearCachedMessages: vi.fn(),
+}));
vi.mock('@/lib/userPromptStore', () => ({ getUserPrompt: () => '' }));
vi.mock('@/lib/imageRef', () => ({
parseUserContent: vi.fn((c: string) => ({ text: c, images: [], files: [] })),
@@ -52,6 +57,7 @@ import { makerChatStore, getRemoteHistoryView } from '@/lib/makerChatStore';
import { projectHistoryView } from '@cindy/maker-shared/message-window';
import { getLatestMessageTodoState } from '@cindy/maker-shared/message-render';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { readCachedMessages, clearCachedMessages } from '@/features/device-link/mirrorCacheClient';
// ─── 忠实的被控端内存替身(单一真相源)───────────────────────────────────────────
@@ -224,6 +230,101 @@ afterEach(() => {
});
describe('device-link controller mirror — end-to-end scenarios', () => {
+ it.each(['empty', 'rewound', 'failure', 'late-cache'])('hands off cold cache to authoritative history (%s)', async (scenario) => {
+ const s = sid();
+ const create = { ...dbMessage(s, 'create', '', '2026-06-15T00:00:00.000Z', 'tool_use'),
+ content: { toolName: 'TodoWrite', input: { todos: [{ content: 'Deleted plan', status: 'pending', activeForm: 'Working' }] } } } as unknown as Message;
+ const cached = [create, dbMessage(s, 'same', 'stale text', '2026-06-15T00:00:01.000Z', 'user')];
+ let finishCache: (rows: Message[]) => void = () => {};
+ vi.mocked(readCachedMessages).mockImplementationOnce(() => scenario === 'late-cache'
+ ? new Promise((resolve) => { finishCache = resolve; }) : Promise.resolve(cached));
+ host.enableHistoryView();
+ host.seedSession(s, {}, scenario === 'rewound'
+ ? [dbMessage(s, 'same', 'current text', '2026-06-15T00:00:01.000Z', 'user')] : []);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ const invoke = host.invoke.getMockImplementation()!;
+ let finishPage: () => void = () => {};
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ if (channel === 'local-db:messages:view') {
+ await new Promise<void>((resolve) => { finishPage = resolve; });
+ if (scenario === 'failure') throw new Error('timeout');
+ }
+ return invoke(device, channel, args);
+ });
+ try {
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ if (scenario !== 'late-cache') {
+ expect(getLatestMessageTodoState(makerChatStore.getSnapshot(s).messages).hasPlanEvent).toBe(true);
+ expect(makerChatStore.getSnapshot(s).messages.every((row) => row.cacheHydrated)).toBe(true);
+ }
+ // A push arriving during the cache handoff is not part of the stale cache.
+ if (scenario === 'rewound') host.hostMessage(s, dbMessage(s, 'live', 'live output', '2026-06-15T00:00:02.000Z'));
+ finishPage();
+ await flush();
+ finishCache(cached);
+ await flush();
+ const state = makerChatStore.getSnapshot(s);
+ if (scenario === 'failure') {
+ expect(state.messages).toHaveLength(2);
+ expect(state.historyLoaded).toBe(false);
+ expect(clearCachedMessages).not.toHaveBeenCalled();
+ } else {
+ expect(state.historyLoaded).toBe(true);
+ expect(state.messages.some((row) => row.cacheHydrated)).toBe(false);
+ expect(getLatestMessageTodoState(state.messages).hasPlanEvent).toBe(false);
+ expect(clearCachedMessages).toHaveBeenCalledWith(DEVICE_ID, s);
+ if (scenario === 'rewound') {
+ expect(state.messages.map((row) => row.content)).toEqual(['current text', 'live output']);
+ } else expect(state.messages).toHaveLength(0);
+ }
+ } finally {
+ makerChatStore.purgeSession(s);
+ }
+ });
+
+ it.each(['demote', 'in-flight-demote', 'purge'])('releases unmounted prefetch without starting another read (%s)', async (mode) => {
+ vi.useFakeTimers();
+ const s = sid();
+ let finishPage: () => void = () => {};
+ try {
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'old', 'old text', '2026-06-15T00:00:00.000Z')]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await vi.advanceTimersByTimeAsync(0);
+ const view = getRemoteHistoryView(s)!;
+ const invoke = host.invoke.getMockImplementation()!;
+ if (mode === 'in-flight-demote') {
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ if (channel === 'local-db:messages:view') await new Promise<void>((resolve) => { finishPage = resolve; });
+ return invoke(device, channel, args);
+ });
+ void view.refresh();
+ }
+ const reads = host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view').length;
+ if (mode === 'purge') makerChatStore.purgeSession(s);
+ else await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(view.isActive()).toBe(false);
+ expect(getRemoteHistoryView(s)).toBeUndefined();
+ finishPage();
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(reads);
+ expect(makerChatStore.getSnapshot(s).messages).toHaveLength(0);
+ host.invoke.mockImplementation(invoke);
+ host.seedSession(s, {}, [dbMessage(s, 'new', 'new text', '2026-06-15T00:00:01.000Z')]);
+ // Re-prefetch must work even without a mounted view to reactivate it.
+ makerChatStore.ensureInitialMessages(s);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.content)).toEqual(['new text']);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(reads + 1);
+ } finally {
+ finishPage();
+ makerChatStore.purgeSession(s);
+ vi.useRealTimers();
+ }
+ });
+
it.each(['mounted', 'prefetched', 'resumed', 'discovered', 'stalled'])('discovers plans through visible pages and stops without progress (%s)', async (entry) => {
vi.useFakeTimers();
const s = sid();
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 8b69c21aa5..587965153b 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -3417,6 +3417,8 @@ function _purgeSession(sessionId: string): void {
backgroundTaskStaleRetrySessions.delete(sessionId);
// 代际递增(bump 而非 delete,原因见 _messagesEpoch 注释):作废 in-flight 翻页,
// 避免其提交把旧窗口 merge 进 purge 后重建的空 slice。
+ getRemoteHistoryView(sessionId)?.setActive(false);
+ remoteHistoryViews.delete(sessionId);
invalidateMessageHistoryWindow(sessionId);
invalidateInputProjectionRequests(sessionId);
// 删除 / 归档 / LRU 都是 renderer owner 边界。作废仍在附件物化或 composer
@@ -3425,8 +3427,6 @@ function _purgeSession(sessionId: string): void {
cancelRemoteOptimisticSendsForSessionPurge(sessionId);
clearWakeBridgeReconcileTimer(sessionId);
cancelIdlePlanDiscovery(sessionId);
- getRemoteHistoryView(sessionId)?.setActive(false);
- remoteHistoryViews.delete(sessionId);
sessions.delete(sessionId);
localSentUserMessageIds.delete(sessionId);
pendingLocalRetryIntents.delete(sessionId);
@@ -4051,6 +4051,10 @@ function _demoteIdleSessions(): void {
// 分页锁。漏 bump 的后果是 in-flight 那一页按 demote 前的游标提交,把一段脱离上下文
// 的旧历史 merge 进空切片(或重开后的新切片),最近的消息反而缺席(#676 review)。
cancelIdlePlanDiscovery(sessionId);
+ // Discard the view with its message slice. Resetting an active prefetch would
+ // start another read and immediately repopulate the cache being evicted.
+ getRemoteHistoryView(sessionId)?.setActive(false);
+ remoteHistoryViews.delete(sessionId);
invalidateMessageHistoryWindow(sessionId);
setState(sessionId, (s) => ({
...s,
@@ -10678,7 +10682,7 @@ function createRemoteHistoryView(sessionId: string) {
const available = snapshot.items.flatMap((item) => item.type === 'messages' ? item.messages : []);
for (const detail of snapshot.details.values()) available.push(...detail.messages);
setState(sessionId, (state) => ({ ...state, historyLoaded: true,
- messages: mergeMessages(available, state.messages, { addOnly: true }),
+ messages: mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated), { addOnly: true }),
hasMoreMessages: snapshot.hasMore, isLoadingMore: snapshot.loading,
oldestMessageId: snapshot.nextCursor,
historyWindowHasIsland: false,
@@ -10817,6 +10821,12 @@ function ensureInitialMessages(sessionId: string): void {
await view.refresh();
const snapshot = view.getSnapshot();
if (!snapshot.error && snapshot.ready) {
+ if (isCurrentHistoryLoad()) {
+ // This path bypasses the raw latest-page cache write. Retire that old
+ // cache instead of persisting an incomplete projection as raw history.
+ clearCachedMessages(historyOriginAtStart!, sessionId);
+ settleCacheHydration(sessionId);
+ }
releaseHistoryFetchIfCurrent(sessionId, historyFetchToken);
void reconcilePendingInteractions(sessionId);
scheduleIdlePlanDiscoveryIfNeeded(sessionId);