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): 补齐终态正文交接并兼容主干历史索引

Dash772653260031
diff --cc apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
index ffb2d6c4b2,a4bf663617..4c60d81ddd
--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
@@@ -48,8 -53,11 +53,11 @@@ vi.mock('@/lib/composerDraftStore', ()
plainTextToTiptapDoc: (s: string) => ({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }] }),
}));
- import { makerChatStore } from '@/lib/makerChatStore';
-import { makerChatStore, getRemoteHistoryView } from '@/lib/makerChatStore';
-import { projectHistoryView } from '@cindy/maker-shared/message-window';
++import { makerChatStore, getRemoteHistoryView, type HistoryChatMessage } from '@/lib/makerChatStore';
++import { projectHistoryView, HistoryViewHandoff } 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';
// ─── 忠实的被控端内存替身(单一真相源)───────────────────────────────────────────
@@@ -115,10 -140,9 +140,12 @@@ function makeFakeHost(deviceId: string
return {
deviceId,
deviceName,
+ enableHistoryView: () => { historyViewEnabled = true; },
+ disableHistoryView: () => { historyViewEnabled = false; },
invoke,
+ push(channel: string, payload: unknown): void {
+ pushCb?.({ deviceId, channel, payload });
+ },
/** 注册控制端 onRemotePush 回调(被控端经此向控制端转发广播)。 */
registerPush(cb: (p: RemotePush) => void): () => void {
pushCb = (push) => cb({ ...push, ownerStamp: push.ownerStamp ?? TEST_OWNER_STAMP });
@@@ -206,73 -234,458 +237,573 @@@ afterEach(() =>
});
describe('device-link controller mirror — end-to-end scenarios', () => {
+ it('does not lose repair signals received while the first historical page is in flight', async () => {
+ const s = sid();
+ const old = dbMessage(s, 'h1', 'old page', '2026-09-08T00:00:00Z');
+ host.seedSession(s, {}, [old]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ let resolveFirst!: (rows: Message[]) => void;
+ const first = new Promise<Message[]>((resolve) => { resolveFirst = resolve; });
+ const original = host.invoke.getMockImplementation()!;
+ let hold = true;
+ host.invoke.mockImplementation((...args) => {
+ if (args[1] === 'local-db:messages:list' && hold) { hold = false; return first; }
+ return original(...args);
+ });
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ host.hostMessage(s, dbMessage(s, 'missed', 'new history', '2026-09-08T00:00:01Z'), { lossy: true });
+ // Invalid text must not throw or prevent the independent history repair.
+ host.push('maker:session-sync', { sessionId: s, event: { type: 'text' }, resyncRequired: true });
+ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
+ resolveFirst([old]);
+ await flush();
+ await flush();
+ expect(makerChatStore.getSnapshot(s).messages.map((message) => message.content)).toEqual(['old page', 'new history']);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list')).toHaveLength(2);
+ });
+
++ it.each([[false, false], [false, true], [true, false], [true, true]])('hands lost terminal text to history (projected=%s, concurrent=%s)', async (projected, concurrent) => {
++ const s = sid();
++ if (projected) host.enableHistoryView();
++ host.seedSession(s, {}, [dbMessage(s, 'h1', 'history', '2026-09-08T00:00:00Z')]);
++ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
++ makerChatStore.ensureInitialMessages(s);
++ await flush();
++ await flush();
++ host.push('maker:event', { sessionId: s, event: { type: 'status', data: { status: 'Running', isRunning: true } } });
++ host.push('maker:session-sync', { sessionId: s, persistId: 'live', event: {
++ type: 'text', data: { text: 'prefix', isFinal: false, isFullText: true },
++ } });
++ const durable = { ...dbMessage(s, 'live-db', 'prefix complete', '2026-09-08T00:00:02Z'), clientId: 'live' };
++ let finish!: (rows: Message[]) => void;
++ const pending = new Promise<Message[]>((resolve) => { finish = resolve; });
++ const original = host.invoke.getMockImplementation()!;
++ host.invoke.mockImplementation((...args) => {
++ if (args[1] === 'local-db:messages:list') return pending;
++ if (args[1] === 'local-db:messages:view') return pending.then((rows) => ({
++ version: 1, items: projectHistoryView(rows, false), hasMore: false, nextCursor: null,
++ }));
++ return original(...args);
++ });
++ // Both the final text event and persistence push were lost. A sealed Host
++ // block has no in-flight snapshot; history alone must repair the same row.
++ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
++ await flush();
++ if (concurrent) {
++ host.push('maker:event', { sessionId: s, persistId: 'live', event: {
++ type: 'text', data: { text: ' newer', isFinal: false },
++ } });
++ await new Promise((resolve) => setTimeout(resolve, 50));
++ }
++ finish([durable]);
++ await flush();
++ await flush();
++ const row = makerChatStore.getSnapshot(s).messages.find((message) => message.clientId === 'live');
++ expect(row?.content).toBe(concurrent ? 'prefix newer' : 'prefix complete');
++ expect(row?.isStreaming).toBe(concurrent);
++ if (projected) {
++ const view = getRemoteHistoryView(s)!;
++ const handoff = new HistoryViewHandoff<HistoryChatMessage>((message) => message.isStreaming === true);
++ const raw = makerChatStore.getSnapshot(s).messages.map((message) => ({ ...message, id: message.id ?? message.clientId, createdAt: message.createdAt ?? '' }));
++ const rendered = handoff.reconcile(view.getSnapshot(), raw);
++ expect(rendered.messages.find((message) => message?.clientId === 'live')?.content).toBe(concurrent ? 'prefix newer' : 'prefix complete');
++ }
++ });
++
+ it.each([true, false])('repairs missing history during a live stream without replacing its newer text (overlap=%s)', async (overlap) => {
+ const s = sid();
+ host.seedSession(s, {}, [dbMessage(s, 'h1', 'history', '2026-09-08T00:00:00Z')]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ await flush();
+ host.push('maker:event', { sessionId: s, event: { type: 'status', data: { status: 'Running', isRunning: true } } });
+ host.push('maker:session-sync', { sessionId: s, persistId: 'live', event: {
+ type: 'text', data: { text: 'live prefix', isFinal: false, isFullText: true, createdAt: '2026-09-08T00:00:02Z' },
+ } });
+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.content).toBe('live prefix');
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+ if (!overlap) host.seedSession(s, {}, []);
+ host.hostMessage(s, dbMessage(s, 'missed', 'missed history', '2026-09-08T00:00:01Z'), { lossy: true });
+ const before = host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list').length;
+ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
+ await flush();
+ await flush();
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list').length).toBeGreaterThan(before);
+ expect(makerChatStore.getSnapshot(s).messages.map((message) => message.content)).toEqual([
+ ...(overlap ? ['history'] : []), 'missed history', 'live prefix',
+ ]);
+ host.push('maker:event', { sessionId: s, persistId: 'live', event: {
+ type: 'text', data: { text: ' tail', isFinal: false },
+ } });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.content).toBe('live prefix tail');
+ const durable = { ...dbMessage(s, 'live-db', 'persisted', '2026-09-08T00:00:02Z'), clientId: 'live' };
+ host.hostMessage(s, durable);
+ expect(makerChatStore.getSnapshot(s).streamingClientId).toBe('live');
+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.isStreaming).toBe(false);
+ // The assembly pointer outlives persistence. It must not prevent repair of
+ // a later durable correction whose push was lost.
+ host.seedSession(s, {}, [{ ...durable, content: 'corrected durable' }]);
+ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
+ await flush();
+ await flush();
+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.content).toBe('corrected durable');
+ });
+
+ it.each(['migration', 'purge', 'failed-intent'])('orders old release before a replacement same-Host expansion (%s)', async (transition) => {
+ const s = sid();
+ const other = makeFakeHost('dev-B', 'Mac B');
+ host.enableHistoryView();
+ other.enableHistoryView();
+ const rows = [dbMessage(s, 'user', 'Work', '2026-06-15T00:00:00.000Z', 'user'),
+ dbMessage(s, 'work', 'Thinking', '2026-06-15T00:00:01.000Z', 'thinking'),
+ dbMessage(s, 'answer', 'Done', '2026-06-15T00:00:02.000Z')];
+ host.seedSession(s, {}, rows);
+ other.seedSession(s, {}, rows);
+ const original = host.invoke.getMockImplementation()!;
+ const applied: unknown[][] = [];
+ let finish = () => {};
+ let pause = true;
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ if (device === other.deviceId) return other.invoke(device, channel, args);
+ if (channel === 'local-db:messages:view-intent') {
+ if (pause && (args[1] as unknown[]).length) {
+ pause = false;
+ await new Promise<void>((resolve) => { finish = resolve; });
+ if (transition === 'failed-intent') throw new Error('late intent failure');
+ }
+ applied.push(args[1] as unknown[]);
+ }
+ return original(device, channel, args);
+ });
+ try {
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ const oldView = getRemoteHistoryView(s)!;
+ oldView.setExpanded(oldView.getSnapshot().items.find((item) => item.type === 'work')!.key, true);
+ await flush();
+ if (transition === 'purge') {
+ makerChatStore.purgeSession(s);
+ makerChatStore.ensureInitialMessages(s);
+ } else {
+ remoteProjectsStore.setDeviceSessions(other.deviceId, 'Mac B', [{ id: s } as Session]);
+ await flush();
+ // B's page is independent of the unfinished A intent.
+ expect(getRemoteHistoryView(s)?.getSnapshot().ready).toBe(true);
+ remoteProjectsStore.removeDevice(other.deviceId);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ }
+ await flush();
+ const current = getRemoteHistoryView(s)!;
+ expect(remoteProjectsStore.getSessionDeviceId(s)).toBe(DEVICE_ID);
+ expect(current).not.toBe(oldView);
+ expect(current.getSnapshot().ready).toBe(true);
+ const work = current.getSnapshot().items.find((item) => item.type === 'work')!;
+ current.setExpanded(work.key, true);
+ await flush();
+ finish();
+ await flush();
+ await flush();
+ expect(applied.at(-1)).toEqual([work.type === 'work' ? work.summary : undefined]);
+ expect(getRemoteHistoryView(s)).toBe(current);
+ } finally {
+ finish();
+ makerChatStore.purgeSession(s);
+ await flush();
+ }
+ });
+
+ it.each(['initial', 'older', 'reconcile', 'details', 'intent', 'aba'])('retires every old-source history path before replacement (%s)', async (scenario) => {
+ const s = sid();
+ const other = makeFakeHost('dev-B', 'Mac B');
+ host.enableHistoryView();
+ other.enableHistoryView();
+ const oldRows = [
+ dbMessage(s, 'old-user', 'old user', '2026-06-15T00:00:00.000Z', 'user'),
+ dbMessage(s, 'old-work', 'old thinking', '2026-06-15T00:00:01.000Z', 'thinking'),
+ dbMessage(s, 'old-answer', 'old answer', '2026-06-15T00:00:02.000Z'),
+ ];
+ const newRows = [dbMessage(s, 'new-user', 'new source', '2026-06-15T00:01:00.000Z', 'user')];
+ host.seedSession(s, {}, oldRows);
+ other.seedSession(s, {}, newRows);
+ const original = host.invoke.getMockImplementation()!;
+ let pause = scenario === 'initial';
+ let finish: () => void = () => {};
+ const channelToPause = scenario === 'details' ? 'local-db:messages:work-details'
+ : scenario === 'intent' ? 'local-db:messages:view-intent' : 'local-db:messages:view';
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ if (device === other.deviceId) return other.invoke(device, channel, args);
+ // Capture the old response before migration, including an old-Host failure.
+ const value = await original(device, channel, args);
+ if (pause && channel === channelToPause && (scenario !== 'intent' || (args[1] as unknown[]).length)) {
+ pause = false;
+ await new Promise<void>((resolve) => { finish = resolve; });
+ if (scenario === 'older' || scenario === 'reconcile') throw new Error('[CHANNEL_NOT_ALLOWED] No handler');
+ }
+ return value;
+ });
+ try {
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ const oldView = getRemoteHistoryView(s)!;
+ let pending: Promise<unknown> | undefined;
+ if (scenario !== 'initial') {
+ const work = oldView.getSnapshot().items.find((item) => item.type === 'work')!;
+ if (scenario === 'older') {
+ // Give the real pagination entry point an older cursor to request.
+ host.seedSession(s, {}, Array.from({ length: 25 }, (_, index) =>
+ dbMessage(s, `past-${index}`, `past ${index}`, new Date(Date.UTC(2026, 5, 14) + index * 1000).toISOString(), 'user')));
+ await oldView.refresh();
+ pause = true;
+ pending = makerChatStore.loadOlderMessages(s);
+ } else if (scenario === 'reconcile' || scenario === 'aba') {
+ pause = true;
+ pending = makerChatStore.reconcileRemoteMessages(s);
+ } else {
+ pause = true;
+ oldView.setExpanded(work.key, true);
+ }
+ await flush();
+ }
+ if (scenario === 'aba') {
+ remoteProjectsStore.removeDevice(DEVICE_ID);
+ expect(getRemoteHistoryView(s)).toBeUndefined();
+ expect(oldView.isActive()).toBe(false);
+ host.seedSession(s, {}, newRows);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ } else {
+ remoteProjectsStore.setDeviceSessions(other.deviceId, 'Mac B', [{ id: s } as Session]);
+ }
+ await flush();
+ const newView = getRemoteHistoryView(s)!;
+ expect(newView).toBeDefined();
+ expect(newView).not.toBe(oldView);
+ expect(oldView.isActive()).toBe(false);
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.content)).toEqual(['new source']);
+ finish();
+ await pending;
+ await flush();
+ expect(getRemoteHistoryView(s)).toBe(newView);
+ expect(newView.getSnapshot().error).toBeNull();
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.content)).toEqual(['new source']);
+ const reads = host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view').length;
+ // A retained old reference cannot issue more page/detail reads.
+ await oldView.refresh();
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(reads);
+ if (scenario === 'intent') {
+ const oldIntents = host.invoke.mock.calls.filter(([device, channel]) => device === DEVICE_ID && channel === 'local-db:messages:view-intent');
+ expect(oldIntents.at(-1)?.[2]).toEqual([s, []]);
+ }
+ } finally {
+ finish();
+ makerChatStore.purgeSession(s);
+ await flush();
+ }
+ });
+
+ it('keeps a same-source controller on ordinary mirror updates', async () => {
+ const s = sid();
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'one', 'same source', '2026-06-15T00:00:00.000Z')]);
+ try {
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ const view = getRemoteHistoryView(s);
+ const reads = host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view').length;
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s, title: 'new title' } as Session]);
+ await flush();
+ expect(getRemoteHistoryView(s)).toBe(view);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(reads);
+ } finally {
+ makerChatStore.purgeSession(s);
+ await flush();
+ }
+ });
+
+ 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();
+ let leave: (() => void) | undefined;
+ const settle = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); };
+ try {
+ const row = (index: number, content: string, role: Message['role'] = 'assistant') =>
+ dbMessage(s, String(index), content, new Date(Date.UTC(2026, 5, 15) + index * 1000).toISOString(), role);
+ const create = { ...row(1, '', 'tool_use'), toolUseId: 'create',
+ content: { toolName: 'TaskCreate', input: { subject: 'Collect logs' }, toolUseId: 'create' } } as unknown as Message;
+ const result = { ...row(2, 'Task #abc created successfully: Collect logs', 'tool_result'), toolUseId: 'create' };
+ const update = { ...row(44, '', 'tool_use'), toolUseId: 'update',
+ ...(entry === 'discovered' ? { createdAt: row(23.5, '').createdAt } : {}),
+ content: { toolName: 'TaskUpdate', input: { taskId: 'abc', status: 'in_progress' }, toolUseId: 'update' } } as unknown as Message;
+ host.enableHistoryView();
+ host.seedSession(s, {}, [row(0, 'Investigate', 'user'), create, result, row(3, 'hidden', 'thinking'),
+ ...Array.from({ length: 40 }, (_, i) => row(i + 4, `# Result ${i}\nUseful output`)), update]
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt)));
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ if (entry !== 'prefetched') leave = makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await settle();
+ const view = getRemoteHistoryView(s)!;
+ expect(view.getSnapshot().items).toHaveLength(20);
+ expect(getLatestMessageTodoState(makerChatStore.getSnapshot(s).messages, { taskHistoryMayBeIncomplete: true }).hasPlanEvent).toBe(entry !== 'discovered');
+ if (entry === 'stalled') {
+ const invoke = host.invoke.getMockImplementation()!;
+ host.invoke.mockImplementation((device, channel, args) => invoke(device, channel,
+ channel === 'local-db:messages:view' ? [args[0], {}] : args));
+ }
+ if (entry === 'resumed') { leave!(); leave = undefined; }
+ if (entry === 'prefetched' || entry === 'resumed') {
+ await vi.advanceTimersByTimeAsync(200);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(1);
+ leave = makerChatStore.enterView(s);
+ await settle();
+ }
+ await vi.advanceTimersByTimeAsync(200);
+ await settle();
+ const state = makerChatStore.getSnapshot(s);
+ const plan = getLatestMessageTodoState(state.messages, { taskHistoryMayBeIncomplete: state.hasMoreMessages });
+ if (entry === 'stalled') {
+ expect(plan.isResolved).toBe(false);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(2);
+ return;
+ }
+ expect(plan).toMatchObject({ hasPlanEvent: true, isResolved: true });
+ expect(JSON.stringify(plan.insertion)).toContain('Collect logs');
+ expect(view.getSnapshot().hasMore).toBe(false);
+ expect(view.getSnapshot().details.size).toBe(0);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(entry === 'resumed' ? 4 : 3);
+ expect(host.invoke.mock.calls.some(([, channel]) => channel === 'local-db:messages:list' || channel === 'local-db:messages:work-details')).toBe(false);
+ } finally {
+ leave?.();
+ makerChatStore.purgeSession(s);
+ vi.useRealTimers();
+ }
+ });
+
+ it.each([false, true])('bounds idle discovery without a plan, including a failed page (fails=%s)', async (fails) => {
+ vi.useFakeTimers();
+ const s = sid();
+ let leave: (() => void) | undefined;
+ try {
+ host.enableHistoryView();
+ host.seedSession(s, {}, Array.from({ length: 60 }, (_, i) => dbMessage(s, String(i), `# Result ${i}\nUseful output`, new Date(Date.UTC(2026, 5, 15) + i * 1000).toISOString())));
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ leave = makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await vi.advanceTimersByTimeAsync(0);
+ const invoke = host.invoke.getMockImplementation()!;
+ if (fails) host.invoke.mockImplementation(async (device, channel, args) => {
+ if (channel === 'local-db:messages:view' && (args[1] as { before?: string })?.before) throw new Error('timeout');
+ return invoke(device, channel, args);
+ });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(2);
+ const snapshot = getRemoteHistoryView(s)!.getSnapshot();
+ expect(snapshot.items).toHaveLength(fails ? 20 : 40);
+ expect(snapshot.hasMore).toBe(true);
+ expect(snapshot.error ? String(snapshot.error) : null).toBe(fails ? 'Error: timeout' : null);
+ } finally {
+ leave?.();
+ makerChatStore.purgeSession(s);
+ vi.useRealTimers();
+ }
+ });
+
+ it.each(['delete', 'clear'])('retires loaded older projection pages after a remote %s', async (operation) => {
+ const s = sid();
+ host.enableHistoryView();
+ const rows = Array.from({ length: 30 }, (_, index) => dbMessage(s, String(index), 'visible',
+ new Date(1_750_000_000_000 + index * 1000).toISOString(), 'user'));
+ host.seedSession(s, { clearedAt: null }, rows);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ const view = getRemoteHistoryView(s)!;
+ await view.refresh(true);
+ expect(view.getSnapshot().items).toHaveLength(30);
+ host.hostPatch(s, { title: 'ordinary metadata' });
+ expect(view.getSnapshot().items).toHaveLength(30);
+ if (operation === 'delete') host.hostDelete(s, [rows[0].clientId]);
+ else {
+ host.seedSession(s, {}, []);
+ host.hostPatch(s, { clearedAt: '2026-09-08T10:00:00Z' });
+ }
+ expect(view.getSnapshot().items).toEqual([]);
+ expect(makerChatStore.getSnapshot(s).messages.some((row) => row.clientId === rows[0].clientId)).toBe(false);
+ await flush(); await flush();
+ expect(view.getSnapshot().ready).toBe(true);
+ expect(view.getSnapshot().items).toHaveLength(operation === 'delete' ? 20 : 0);
+ view.setActive(false);
+ });
+
+ it('returns to raw history when a previously capable Host is downgraded', async () => {
+ const s = sid();
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'old', 'old', '2026-06-15T00:00:00.000Z')]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ await flush();
+ const view = getRemoteHistoryView(s)!;
+ expect(view.getSnapshot().ready).toBe(true);
+ host.disableHistoryView();
+ host.hostMessage(s, dbMessage(s, 'new', 'new', '2026-06-15T00:00:01.000Z'), { lossy: true });
+ await makerChatStore.reconcileRemoteMessages(s, { force: true });
+ expect(view.getSnapshot().ready).toBe(false);
+ expect(getRemoteHistoryView(s)).toBeUndefined();
+ expect(host.invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual(['client-old', 'client-new']);
+ });
+ it.each([false, true])('registers a fresh history page after ACK; reset during wait=%s', async (reset) => {
+ const s = sid();
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:00.000Z')]);
+ const original = host.invoke.getMockImplementation()!;
+ let finish!: () => void;
+ let finishReset!: () => void;
+ let pageReads = 0;
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ const value = await original(device, channel, args);
+ if (channel === 'local-db:messages:view' && ++pageReads === 1) await new Promise<void>(done => { finish = done; });
+ else if (reset && channel === 'local-db:messages:view') await new Promise<void>(done => { finishReset = done; });
+ return value;
+ });
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ const view = getRemoteHistoryView(s)!;
+ expect(view.getSnapshot().ready).toBe(false);
+ const recovered = makerChatStore.reconcileRemoteMessages(s, { freshHistory: true });
+ if (reset) { view.reset(); await flush(); }
+ finish();
+ expect(await recovered).toBe(!reset);
+ expect(pageReads).toBe(2);
+ expect(view.getSnapshot().ready).toBe(!reset);
+ if (reset) { finishReset(); await flush(); }
+ view.setActive(false);
+ });
+ it('reads visible history first and fetches a collapsed work range only after expansion', async () => {
+ const s = sid();
+ host.enableHistoryView();
+ const history = [dbMessage(s, 'u', 'question', '2026-06-15T00:00:00.000Z', 'user'),
+ { ...dbMessage(s, 'thought', '', '2026-06-15T00:00:01.000Z', 'thinking'), content: { kind: 'thinking', text: 'hidden body', durationMs: 500, isRedacted: false } },
+ dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:02.000Z')];
+ host.seedSession(s, {}, history);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ await flush();
+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual(['client-u', 'client-answer']);
+ const view = getRemoteHistoryView(s)!;
+ const group = view.getSnapshot().items.find((item) => item.type === 'work')!;
+ expect(view.getSnapshot().details.size).toBe(0);
+ view.setExpanded(group.key, true);
+ await flush();
+ expect(view.getSnapshot().details.get(group.key)?.messages[0].content).toBe('hidden body');
+ expect(makerChatStore.getSnapshot(s).messages.some((row) => row.clientId === 'client-thought')).toBe(true);
+ view.setActive(false);
+ });
+
it('完整镜像回路:开会话见历史 → live push 追加 → 丢帧 reconcile heal → 设置变更镜像', async () => {
const s = sid();
// 被控端已有 1 条历史 + 注册到远程项目(getSessionDeviceId 命中 → 传输层走隧道)。
diff --cc apps/desktop/src/renderer/lib/makerChatStore.ts
index 89dca1667b,471551e40a..6ab7e8897c
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@@ -21,9 -21,8 +21,10 @@@
* - User-initiated stopSession (NOT called on session switch anymore)
*/
+ import { HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, type HistoryViewPage, type HistoryDetailPage } from '@cindy/maker-shared/message-window';
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
+import { SESSION_SYNC_CHANNEL } from '@cindy/device-link';
+import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';
import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
import {
getDataOwnerGeneration,
@@@ -8446,27 -8448,12 +8462,35 @@@ function initGlobalListeners(options: G
}
// stall 看门狗信号:只用重会话流刷新 lastInboundEventAt。列表级轻量 activity/patch
// 可能仍在持续抵达,但 maker:event 重 topic 已经断流;若这里也刷新会掩盖卡死。
+ if (push.channel === SESSION_SYNC_CHANNEL
+ && (!inboundSid || remoteProjectsStore.getSessionDeviceId(inboundSid) !== push.deviceId)) return;
if (inboundSid && isRemoteHeavyInboundChannel(push.channel)) _markInboundEvent(inboundSid);
+ if (inboundSid) {
+ const view = getRemoteHistoryView(inboundSid);
+ if (view && ['maker:history-view-changed', 'local-db:messages:created', 'maker:status-changed'].includes(push.channel)) view.invalidate();
+ }
switch (push.channel) {
+ case SESSION_SYNC_CHANNEL:
+ consumeRemoteSessionSync(push.payload, {
+ applyEvent: (event) => handleMakerEventRaw(event, remoteIngress),
+ invalidateHistory: (sessionId) => {
+ const state = sessions.get(sessionId);
+ if (!state) return;
++ if (getRemoteHistoryView(sessionId)) {
++ void reconcileRemoteMessages(sessionId, { repair: true, freshHistory: true });
++ return;
++ }
+ if (!state.historyLoaded) {
+ // A first page captured before the repair must not clear its
+ // meaning. Existing invalidated-load settlement starts one new read.
+ bumpMessagesEpoch(sessionId);
+ ensureInitialMessages(sessionId);
+ return;
+ }
+ void reconcileRemoteMessages(sessionId, { repair: true });
+ },
+ });
+ break;
case 'maker:event':
handleMakerEventRaw(push.payload, remoteIngress);
break;
@@@ -11409,7 -11539,6 +11576,7 @@@ function reconcileOpenSessionOrigins()
* - isStreaming=true → 跳过(不打断在串的 turn;turn 结束会再触发一次)。
* 例外:`opts.force`(仅 stall 看门狗在**被控端权威报 not-running 之后**才传)放行 ——
* 此时 isStreaming 是「卡死残留」而非真在串,必须能补回丢失的终态/消息。
- * repair 为已授权的补流信号:允许在途对账,但保留当前 live 行,不以旧 DB 页覆盖它。
++ * repair 为已授权的补流信号:允许在途对账,保留历史未覆盖或拉取期间更新的 live 行。
* - 无新 clientId → no-op(不产生新数组引用,避免无谓重渲染)。
*/
/**
@@@ -11430,10 -11559,22 +11597,36 @@@
*/
const _remoteReconcileInFlight = new Map<
string,
- { run: Promise<boolean>; rerun: boolean; rerunForce: boolean }
+ { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean }
>();
- function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; repair?: boolean }): Promise<boolean> {
-function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; freshHistory?: boolean }): Promise<boolean> {
++function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; freshHistory?: boolean; repair?: boolean }): Promise<boolean> {
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) return Promise.resolve(false);
+ const view = getRemoteHistoryView(sessionId);
++ const repairRows = opts?.repair && view
++ ? new Map(sessions.get(sessionId)?.messages.map((row) => [row.clientId, row])) : undefined;
+ if (view && (view.getSnapshot().ready || opts?.freshHistory)) return Promise.all([view.refresh(false, opts?.freshHistory), reconcilePendingInteractions(sessionId)]).then(() => {
+ if (getRemoteHistoryView(sessionId) !== view || !view.isActive()) return false;
+ if (isHistoryViewUnavailable(view.getSnapshot().error)) {
+ releaseRemoteHistoryView(sessionId, view);
+ return reconcileRemoteMessages(sessionId, { force: true });
+ }
+ if (view.getSnapshot().error) throw view.getSnapshot().error;
++ if (repairRows && view.getSnapshot().ready) {
++ const snapshot = view.getSnapshot();
++ const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);
++ // The projection's add-only subscription preserves live rows. Complete
++ // this repair only for unchanged assistant streams. Cached work details
++ // refresh separately and cannot prove that their contents are current.
++ setState(sessionId, (state) => ({ ...state, messages: mergeMessages(available, state.messages, {
++ addOnly: true,
++ addOnlyExcept: new Set(state.messages.filter((row) => row.role === 'assistant'
++ && row.isStreaming === true && repairRows.get(row.clientId) === row).map((row) => row.clientId)),
++ }) }));
++ }
+ return view.getSnapshot().ready;
+ });
// 返回完成 promise 供调用方需要时等待;既有调用方均按 fire-and-forget 使用。
if (!sessionId || !isRemoteSession(sessionId)) return Promise.resolve(false);
const inFlight = _remoteReconcileInFlight.get(sessionId);
@@@ -11609,8 -11747,7 +11802,10 @@@ function runRemoteReconcile(sessionId:
// 这些行的就是 live push(messages:created),它比本次快照更新,不该被旧快照盖回去。
const untouchedSinceStart = new Set<string>();
for (const message of s.messages) {
- if (rowsAtStart.get(message.clientId) === message
- && !(opts?.repair && message.isStreaming === true)) {
++ // A missing terminal push can leave isStreaming stuck. The existing
++ // reference guard protects concurrent deltas; an unchanged row must
++ // still accept its durable counterpart, including the terminal state.
+ if (rowsAtStart.get(message.clientId) === message) {
untouchedSinceStart.add(message.clientId);
}
}
diff --cc apps/mobile/app/sessions/[sessionId].tsx
index b6aeb8b826,3df979970d..e76d6eb022
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@@ -1,3 -1,7 +1,6 @@@
+ import { getActiveMobileSessionRealm } from '@/config/env';
+ import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';
-import { loadLightweightSessionScheduleIndex, loadSessionScheduleIndex } from '@/session/scheduleIndex';
+ import { shouldShowFailedScheduleNotice, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { isInFlightDeviceLinkError } from '@cindy/device-link';
@@@ -2110,20 -2128,31 +2127,20 @@@ export default function SessionScreen(
return () => subscription.remove();
}, []);
useFocusEffect(useCallback(() => {
- if (!appStateActive || !deviceId || !sessionId) return;
+ if (!appStateActive || !deviceId || !sessionId || !remoteHistoryAvailable) return;
let active = true;
- const isActive = () => active && AppState.currentState === 'active' && navigation.isFocused();
+ const isActive = () => active && messageScreenFocusedRef.current && messageAppActiveRef.current;
const cancel = deferScheduleIndexHydration(() => {
- void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId, deviceId, isActive))
- .catch(() => undefined);
- void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId, {
- isActive,
- // The same read supplies the notice and existing read receipts. Old
- // Hosts retain their original query; no second schedule scan is added.
- loadIndex: async () => {
- try { return await loadLightweightSessionScheduleIndex(deviceId, invoke); }
- catch (error) {
- if (!isHistoryViewUnavailable(error)) throw error;
- if (!isActive()) return new Map();
- return loadSessionScheduleIndex(maker, { throwOnTransientRunListError: true });
- }
- },
++ void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId, deviceId, isActive, {
+ onIndex: (index) => setScheduleFailure({ source: scheduleNoticeSource, run: index.get(sessionId)?.latestFailedRun }),
+ })).catch(() => undefined);
});
return () => { active = false; cancel(); };
- }, [appStateActive, connectionEpoch, deviceId, maker, navigation, scheduleUnreadAddedVersion, sessionId]));
- // The event fast path also belongs only to the task actually being viewed.
+ }, [appStateActive, connectionEpoch, deviceId, invoke, maker, remoteHistoryAvailable, scheduleEventSnapshot.sessionIndexVersion, scheduleNoticeSource, sessionId]));
useFocusEffect(useCallback(() => {
- if (!appStateActive || !completedRunId) return;
+ if (!appStateActive || !remoteHistoryAvailable || !completedRunId) return;
void maker.schedule.markRunRead(completedRunId).catch(() => undefined);
- }, [appStateActive, completedRunId, maker]));
+ }, [appStateActive, completedRunId, maker, remoteHistoryAvailable]));
useFocusEffect(
useCallback(() => {
if (!appStateActive || !deviceId || !sessionId || !hasRenderedMessages) return undefined;
diff --cc apps/mobile/src/__tests__/scheduleIndex.test.ts
index fca3d91307,b191694fb6..30c7aaf2ac
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@@ -7,9 -7,9 +7,10 @@@ import
invalidateRunningSessionScheduleEntries,
invalidateScheduleIndexForDevice,
invalidateTransientScheduleIndexFailureFor,
- invalidateTransientScheduleIndexFailures,
+ invalidateScheduleIndexesAfterLinkRecovery,
+ loadLightweightSessionScheduleIndex,
loadSessionScheduleIndex,
+ loadSharedSessionScheduleIndex,
loadSessionScheduleIndexThrottled,
replaceSessionScheduleIndexEntries,
resetScheduleIndexThrottleForTesting,
@@@ -33,29 -33,6 +34,57 @@@ function makerWithSchedules
}
describe('scheduleIndex', () => {
++ it.each([false, true])('shares complete schedule metadata and historical failures with legacy fallback=%s', async (legacy) => {
++ resetScheduleIndexThrottleForTesting();
++ const list = vi.fn(async () => [
++ { id: 'sched-1', name: 'run', status: 'active', targetSessionId: 'current' },
++ { id: 'zero', name: 'no runs', status: 'paused', targetSessionId: 'zero-task' },
++ ]);
++ const run = { runId: 'old-failure', scheduleId: 'sched-1', scheduleName: 'run', scheduleStatus: 'active',
++ sessionId: 'current', status: 'failed', firedAt: 1, readAt: 2 };
++ const listSidebarIndexRuns = vi.fn(async () => {
++ if (legacy) throw new Error('[CHANNEL_NOT_ALLOWED] unsupported');
++ return { runs: [run, { ...run, runId: 'old-binding', sessionId: 'previous' }] };
++ });
++ const listRuns = vi.fn(async (id: string) => id === 'zero' ? [] : [{ ...run, id: run.runId }]);
++ const maker = { schedule: { list, listRuns, listSidebarIndexRuns } } as unknown as Pick<MobileMakerTransport, 'schedule'>;
++ const [home, task] = await Promise.all([
++ loadSharedSessionScheduleIndex('shared-lightweight', maker),
++ loadSharedSessionScheduleIndex('shared-lightweight', maker),
++ ]);
++ expect(home).toBe(task);
++ expect(home.get('current')?.latestFailedRun).toEqual({ runId: 'old-failure', firedAt: 1 });
++ expect(home.has('previous')).toBe(false);
++ expect(home.get('zero-task')?.allSchedulesStopped).toBe(true);
++ expect(list).toHaveBeenCalledTimes(1);
++ expect(listSidebarIndexRuns).toHaveBeenCalledTimes(1);
++ expect(listRuns).toHaveBeenCalledTimes(legacy ? 2 : 0);
++ resetScheduleIndexThrottleForTesting();
++ });
++
+ it('stops retries after blur without negative-caching cancellation for the next screen', async () => {
+ vi.useFakeTimers();
+ resetScheduleIndexThrottleForTesting();
+ try {
+ let active = true;
+ const list = vi.fn().mockRejectedValueOnce(new Error('[NOT_CONNECTED] offline')).mockResolvedValue([]);
+ const maker = { schedule: { list, listRuns: vi.fn() } } as unknown as Pick<MobileMakerTransport, 'schedule'>;
+ const first = loadSharedSessionScheduleIndex('blur-device', maker, () => active);
+ const rejected = expect(first).rejects.toThrow('consumer inactive');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(list).toHaveBeenCalledTimes(1);
+ active = false;
+ await vi.runAllTimersAsync();
+ await rejected;
+ expect(list).toHaveBeenCalledTimes(1);
+ await expect(loadSharedSessionScheduleIndex('blur-device', maker)).resolves.toEqual(new Map());
+ expect(list).toHaveBeenCalledTimes(2);
+ } finally {
+ resetScheduleIndexThrottleForTesting();
+ vi.useRealTimers();
+ }
+ });
+
it('loads schedule unread and running metadata without failing the whole index on one bad schedule', async () => {
const listRuns = vi.fn(async (scheduleId: string) => {
if (scheduleId === 'broken') throw new Error('remote schedule runs unavailable');
diff --cc apps/mobile/src/__tests__/scheduleRunRead.test.ts
index 0261e92e92,83fbe40de0..afa02cde01
--- a/apps/mobile/src/__tests__/scheduleRunRead.test.ts
+++ b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
@@@ -229,3 -147,20 +229,20 @@@ describe('unreadRunIdFromProjection', (
expect(unreadRunIdFromProjection(failedEvent, 'session-1')).toBeNull();
});
});
+
-it('shares the supplied index with the notice and ignores a late result after leaving', async () => {
++it('shares the cached index with the notice and ignores a late result after leaving', async () => {
++ resetScheduleIndexThrottleForTesting();
+ const markRunRead = vi.fn(async () => undefined);
- const maker = makerWith([], markRunRead);
++ const runs = [{ id: 'r', scheduleId: 'sched-1', sessionId: 'session-1', status: 'failed', firedAt: 1 }];
++ let finish!: (value: typeof runs) => void;
++ const rows = new Promise<typeof runs>((resolve) => { finish = resolve; });
++ const maker = makerWith([], markRunRead, () => rows);
+ const onIndex = vi.fn();
- const index = new Map([['session-1', { scheduleId: 's', scheduleName: 's', unreadRunIds: ['r'], unreadCount: 1,
- running: false, latestRunAt: 1, latestFailedRun: { runId: 'r', firedAt: 1 } }]]);
+ let active = true;
- let finish!: (value: typeof index) => void;
- const pending = markSessionScheduleRunsRead(maker, 'session-1', {
- isActive: () => active, onIndex, loadIndex: () => new Promise((resolve) => { finish = resolve; }),
- });
- active = false; finish(index); await pending;
++ const pending = markSessionScheduleRunsRead(maker, 'session-1', 'notice-device', () => active, { onIndex });
++ active = false; finish(runs); await pending;
+ expect(onIndex).not.toHaveBeenCalled(); expect(markRunRead).not.toHaveBeenCalled();
- await markSessionScheduleRunsRead(maker, 'session-1', { isActive: () => true, onIndex, loadIndex: async () => index });
- expect(onIndex).toHaveBeenCalledWith(index); expect(markRunRead).toHaveBeenCalledWith('r');
++ await markSessionScheduleRunsRead(maker, 'session-1', 'notice-device', () => true, { onIndex });
++ expect(onIndex.mock.calls[0][0].get('session-1')).toMatchObject({ latestFailedRun: { runId: 'r', firedAt: 1 } });
++ expect(markRunRead).toHaveBeenCalledWith('r');
+ });
diff --cc apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
index e2925db816,df645ab25c..e061537d0e
--- a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
+++ b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
@@@ -17,6 -19,6 +19,8 @@@ const native = vi.hoisted(() => (
sections: [] as HomeSection[],
search: { query: "", onChangeQuery: (_value: string) => {} },
invoke: vi.fn(),
++ appState: 'active',
++ appStateListeners: new Set<(state: string) => void>(),
}));
vi.mock("react-native", async () => {
@@@ -67,6 -69,6 +71,13 @@@
);
},
AccessibilityInfo: { setAccessibilityFocus: vi.fn() },
++ AppState: {
++ get currentState() { return native.appState; },
++ addEventListener: (_event: string, listener: (state: string) => void) => {
++ native.appStateListeners.add(listener);
++ return { remove: () => native.appStateListeners.delete(listener) };
++ },
++ },
BackHandler: { addEventListener: () => ({ remove() {} }) },
findNodeHandle: () => null,
StyleSheet: {
@@@ -235,6 -237,8 +246,10 @@@ describe("drawer selective updates", (
};
beforeEach(async () => {
++ native.appState = 'active';
++ native.appStateListeners.clear();
+ clearSessionScheduleIndexCache();
+ remoteScheduleEventStore.clearAll();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.useFakeTimers();
remoteSessionStore.clear();
@@@ -380,6 -384,20 +395,36 @@@
expect(row("new")?.textContent).toContain("newer run");
});
+ it("refreshes failed unread from the lightweight host index when read elsewhere", async () => {
+ let readAt: number | undefined;
+ native.invoke.mockImplementation(async (_device, channel) => {
++ if (channel === 'maker:schedule:list') return [{ id: 'auto', name: 'auto', status: 'active', targetSessionId: 's1' }];
+ expect(channel).toBe("maker:schedule:list-sidebar-index-runs");
+ return { runs: [{ sessionId: "s1", scheduleId: "auto", runId: "run", scheduleName: "auto", scheduleStatus: "active", status: "failed", firedAt: 1, readAt }] };
+ });
+ await render();
+ expect(status("s1", "error")).not.toBeNull();
+ readAt = 10;
+ await act(async () => remoteScheduleEventStore.apply("dev-1", { type: "read", scheduleId: "auto" }));
+ expect(status("s1", "error")).toBeNull();
- expect(native.invoke).toHaveBeenCalledTimes(2);
++ expect(native.invoke).toHaveBeenCalledTimes(4);
++ });
++
++ it('does not retry or start schedule scans in the background and refreshes on return', async () => {
++ native.invoke.mockRejectedValue(new Error('[INVOKE_TIMEOUT] timeout'));
++ await render();
++ expect(native.invoke).toHaveBeenCalledTimes(1);
++ native.appState = 'background';
++ await act(async () => native.appStateListeners.forEach((listener) => listener('background')));
++ await tick(5000);
++ await act(async () => remoteScheduleEventStore.apply('dev-1', { type: 'read', scheduleId: 'auto' }));
++ expect(native.invoke).toHaveBeenCalledTimes(1);
++ native.invoke.mockImplementation(async (_device, channel) => channel === 'maker:schedule:list' ? [] : { runs: [] });
++ native.appState = 'active';
++ await act(async () => native.appStateListeners.forEach((listener) => listener('active')));
++ expect(native.invoke).toHaveBeenCalledTimes(3);
+ });
+
it("refreshes device search reachability without a session-array change", async () => {
remoteSessionStore.setConversationSearchDeviceModels([
{ deviceId: "dev-1", name: "Studio", canOpen: false, state: "offline" },
diff --cc apps/mobile/src/device-link/mobileMakerTransport.ts
index 5668ed6e9f,34764cc611..120fbe5dfa
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@@ -569,6 -573,6 +573,7 @@@ export interface MobileMakerTransport
): Promise<void>;
};
schedule: {
++ listSidebarIndexRuns?(): Promise<{ runs?: unknown[] }>;
list(filter?: ScheduleListFilter): Promise<RemoteSchedule[]>;
get(id: string): Promise<RemoteSchedule>;
listTemplates(): Promise<RemoteScheduleTemplate[]>;
@@@ -801,6 -808,6 +809,7 @@@ export function createMobileMakerTransp
update: (sessionId, patch) => call('maker:goal:update', [{ sessionId, patch }]),
},
schedule: {
++ listSidebarIndexRuns: () => call('maker:schedule:list-sidebar-index-runs'),
list: (filter) => call('maker:schedule:list', filter ? [filter] : []),
get: (id) => call('maker:schedule:get', [id]),
listTemplates: () => call('maker:schedule:list-templates'),
diff --cc apps/mobile/src/session/SessionListDrawer.tsx
index 2326677b92,e39a8121b2..3e760ffcf6
--- a/apps/mobile/src/session/SessionListDrawer.tsx
+++ b/apps/mobile/src/session/SessionListDrawer.tsx
@@@ -1,3 -1,6 +1,6 @@@
-import { loadLightweightSessionScheduleIndex } from './scheduleIndex';
++import { loadDeviceSessionScheduleIndex } from './scheduleIndex';
+ import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+ import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
/**
* SessionListDrawer —— 宽屏(iPad / 折叠屏展开 / 横屏手机)会话页的任务列表抽屉。
*
@@@ -20,6 -23,6 +23,7 @@@ import { House, LoaderCircle, SquarePe
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
AccessibilityInfo,
++ AppState,
BackHandler,
findNodeHandle,
Pressable,
@@@ -304,6 -307,37 +308,42 @@@ export function SessionListDrawer(
sort: t(`devices.list.search.filter.sort.${indexedSearch.sortBy}`),
status: t(`devices.list.search.filter.status.${indexedSearch.statusFilter}`),
});
+ const { invoke } = useDeviceLink();
+ const [scheduleIndex, setScheduleIndex] = useState<ReadonlyMap<string, import('./sessionList').RemoteSessionScheduleInfo>>(() => new Map());
+ const scheduleDeviceIdsKey = devices.map((device) => device.deviceId).sort().join(',');
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ const perDevice = new Map<string, ReadonlyMap<string, import('./sessionList').RemoteSessionScheduleInfo>>();
+ const requestVersions = new Map<string, number>();
+ const ids = scheduleDeviceIdsKey.split(',').filter(Boolean);
+ const versions = new Map(ids.map((id) => [id, remoteScheduleEventStore.getSnapshot(id).sessionIndexVersion]));
++ const canStart = () => !cancelled && openRef.current && AppState.currentState === 'active';
+ const refresh = (id: string) => {
++ if (!canStart()) return;
+ const request = (requestVersions.get(id) ?? 0) + 1;
+ requestVersions.set(id, request);
- void loadLightweightSessionScheduleIndex(id, invoke).then((index) => {
- if (cancelled || requestVersions.get(id) !== request) return;
++ void loadDeviceSessionScheduleIndex(id, invoke, canStart).then((index) => {
++ if (!canStart() || requestVersions.get(id) !== request) return;
+ perDevice.set(id, index);
+ setScheduleIndex(new Map([...perDevice.values()].flatMap((entries) => [...entries])));
+ }).catch(() => undefined);
+ };
+ ids.forEach(refresh);
++ const appStateSubscription = AppState.addEventListener('change', (state) => {
++ if (state === 'active') ids.forEach(refresh);
++ });
+ const off = remoteScheduleEventStore.subscribe(() => {
+ for (const id of ids) {
+ const version = remoteScheduleEventStore.getSnapshot(id).sessionIndexVersion;
+ const previous = versions.get(id) ?? 0;
+ versions.set(id, version);
+ if (version <= previous) continue;
+ refresh(id);
+ }
+ });
- return () => { cancelled = true; off(); };
++ return () => { cancelled = true; off(); appStateSubscription.remove(); };
+ }, [open, scheduleDeviceIdsKey, invoke]);
const sections = useMemo<HomeSection[]>(() => {
if (!mounted) return [];
if (shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status)) {
diff --cc apps/mobile/src/session/scheduleIndex.ts
index e796c5e67a,61800340ce..cd7018c806
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@@ -1,7 -1,7 +1,8 @@@
import { isDeviceUnresponsiveRemoteError } from '@cindy/maker-shared/device-link-contract';
++import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { createMobileMakerTransport, type MobileMakerTransport, type RemoteInvoke } from '@/device-link/mobileMakerTransport';
import { unresponsiveDevicesStore } from '@/device-link/unresponsiveDevicesStore';
-import { isTransientRemoteError } from '@/device-link/remoteRetry';
+import { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { normalizeScheduleList, normalizeScheduleRuns } from '@/scheduler/scheduleModel';
import type { RemoteScheduleRun } from '@/scheduler/types';
import { buildSessionScheduleIndex, type RemoteSessionScheduleInfo } from '@/session/sessionList';
@@@ -23,6 -23,6 +24,13 @@@ export async function loadSessionSchedu
options: LoadSessionScheduleIndexOptions = {},
): Promise<Map<string, RemoteSessionScheduleInfo>> {
const schedules = normalizeScheduleList(await maker.schedule.list());
++ if (maker.schedule.listSidebarIndexRuns) {
++ try {
++ return buildLightweightSessionScheduleIndex(await maker.schedule.listSidebarIndexRuns(), schedules);
++ } catch (error) {
++ if (!isHistoryViewUnavailable(error)) throw error;
++ }
++ }
// listRuns 逐个串行而非 Promise.all 全并发:device-link 是无优先级的单 WS 管道,
// N 个背景 listRuns 一齐压上去会把会话打开的关键读(messages / getSession / projection)
// 挤到队尾(2026-07 实测:并发轮次叠加时 list-runs 均值 8.8s、messages:list 被拖到 6s+)。
@@@ -351,3 -309,24 +362,28 @@@ function stringListsEqual(a: readonly s
if (a.length !== b.length) return false;
return a.every((item, index) => item === b[index]);
}
+
+ export const resetScheduleIndexThrottleForTesting = clearSessionScheduleIndexCache;
+
+ /** Existing lightweight host query; never starts the schedule list + per-run scan. */
+ export async function loadLightweightSessionScheduleIndex(deviceId: string, invoke: RemoteInvoke): Promise<Map<string, RemoteSessionScheduleInfo>> {
+ const raw = await invoke<{ runs?: unknown[] }>(deviceId, 'maker:schedule:list-sidebar-index-runs', []);
++ return buildLightweightSessionScheduleIndex(raw);
++}
++
++function buildLightweightSessionScheduleIndex(raw: { runs?: unknown[] }, authoritativeSchedules?: ReturnType<typeof normalizeScheduleList>): Map<string, RemoteSessionScheduleInfo> {
+ if (!raw || !Array.isArray(raw.runs)) throw new Error('Invalid schedule index');
+ const schedules = new Map<string, import('@/scheduler/types').RemoteSchedule>();
+ const runs = new Map<string, RemoteScheduleRun[]>();
+ for (const value of raw.runs) {
+ if (!value || typeof value !== 'object') throw new Error('Invalid schedule index row');
+ const row = value as Record<string, unknown>;
+ if (typeof row.scheduleId !== 'string' || typeof row.runId !== 'string' || typeof row.scheduleName !== 'string') throw new Error('Invalid schedule index row');
+ const schedule = normalizeScheduleList([{ id: row.scheduleId, name: row.scheduleName, status: row.scheduleStatus }])[0];
+ const run = normalizeScheduleRuns([{ ...row, id: row.runId }])[0];
+ if (!schedule || !run) throw new Error('Invalid schedule index row');
+ schedules.set(schedule.id, schedule);
+ runs.set(schedule.id, [...(runs.get(schedule.id) ?? []), run]);
+ }
- return buildSessionScheduleIndex([...schedules.values()], runs);
++ return buildSessionScheduleIndex(authoritativeSchedules ?? [...schedules.values()], runs);
+ }
diff --cc apps/mobile/src/session/scheduleRunRead.ts
index 8a8f564c86,8c55be0c25..01a199df8b
--- a/apps/mobile/src/session/scheduleRunRead.ts
+++ b/apps/mobile/src/session/scheduleRunRead.ts
@@@ -23,18 -24,22 +24,20 @@@ type ScheduleReadTransport = Pick<Mobil
export async function markSessionScheduleRunsRead(
maker: ScheduleReadTransport,
sessionId: string,
- options: {
- loadIndex?: () => Promise<Map<string, RemoteSessionScheduleInfo>>;
- onIndex?: (index: Map<string, RemoteSessionScheduleInfo>) => void;
- isActive?: () => boolean;
- } = {},
+ deviceId: string,
+ isActive: () => boolean = () => true,
++ options: { onIndex?: (index: Map<string, RemoteSessionScheduleInfo>) => void } = {},
): Promise<string[]> {
- if (!sessionId || options.isActive?.() === false) return [];
- const index = await (options.loadIndex?.() ?? loadSessionScheduleIndex(maker, { throwOnTransientRunListError: true }));
- if (options.isActive?.() === false) return [];
+ if (!sessionId || !deviceId || !isActive()) return [];
+ const index = await loadSharedSessionScheduleIndex(deviceId, maker, isActive);
+ if (!isActive()) return [];
+ options.onIndex?.(index);
const unreadRunIds = index.get(sessionId)?.unreadRunIds ?? [];
if (unreadRunIds.length === 0) return [];
// 单个永久失败不阻塞其它 run;瞬态失败需要抛出,让外层 retry 重新探测并补标。
// allSettled 后按原 unreadRunIds 顺序收集成功项,返回值保序。
const results = await Promise.allSettled(
- unreadRunIds.map((runId) => maker.schedule.markRunRead(runId)),
- unreadRunIds.map((runId) => options.isActive?.() === false ? Promise.reject(new Error('READ_INACTIVE')) : maker.schedule.markRunRead(runId)),
++ unreadRunIds.map((runId) => !isActive() ? Promise.reject(new Error('READ_INACTIVE')) : maker.schedule.markRunRead(runId)),
);
const transientError = results.find(
(result): result is PromiseRejectedResult => result.status === 'rejected' && isTransientRemoteError(result.reason),
diff --cc packages/maker-shared/src/messageWindow.ts
index 722e1e366c,a5a136a13c..2649068ef3
--- a/packages/maker-shared/src/messageWindow.ts
+++ b/packages/maker-shared/src/messageWindow.ts
@@@ -1,4 -1,8 +1,9 @@@
+export { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from './remoteTextStream.js';
+ export * from './historyView.js';
+ export { projectHistoryView, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';
+ export * from './historyViewController.js';
+ export { renderHistoryView } from './historyViewRender.js';
+ export { HistoryViewHandoff } from './historyViewHandoff.js';
export interface MessageScrollMetrics {
contentHeight: number;