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。

perf(bot-groups): 打开群聊立即显示群框架,并缩短 Chat Server 串行读取 (#6012)

Dasha3aa86a6babe
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
new file mode 100644
index 0000000000..9d29a3f3a6
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
@@ -0,0 +1,487 @@
+/**
+ * Opening a server group waits on main's Chat Server reads. Every request here answers after
+ * a fixed simulated round trip, so the elapsed fake time counts the serial request rounds on
+ * the open path. These are simulated latencies, not production measurements.
+ *
+ * The realtime cases run against a small model of the Chat Server contract (chat-server
+ * sync.ts / realtime.ts): a snapshot returns its scope head as `cursor`, a subscription
+ * delivers every change after its cursor, and the next batch waits for the ack.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const fixture = vi.hoisted(() => ({ handle: vi.fn(), latencyMs: 100, profiles: [] as unknown[], localGroupIds: [] as string[],
+ sockets: [] as Array<import('ws').WebSocket>, routes: [] as string[], download: vi.fn(), page: [] as unknown[],
+ /** When the server reads its state and when the answer reaches the client, in ms after the request. */
+ timing: null as null | ((route: string) => { serve: number; deliver: number }),
+ offline: false, onFrame: null as null | ((socket: unknown, frame: Record<string, unknown>) => void) }));
+vi.mock('../../authManager.js', () => ({ getAccessToken: () => 'isolated-test-token', refresh: vi.fn(async () => true) }));
+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));
+vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: vi.fn(async () => []), download: fixture.download }) }));
+vi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('electron', () => ({ app: { isPackaged: false, getPath: () => '/isolated' } }));
+vi.mock('node:fs', () => ({ existsSync: () => true, readFileSync: () => '{"baseUrl":"http://127.0.0.1:3018","auth":"cindy"}' }));
+vi.mock('../botGroupChatService.js', () => ({ readPersistedReplyText: vi.fn() }));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: {
+ select: () => ({ from: () => ({ where: () => Object.assign(Promise.resolve(fixture.profiles), {
+ limit: async () => fixture.localGroupIds.map(id => ({ id })),
+ }) }) }),
+} }) }));
+vi.mock('node:http', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { request: (url: string, options: { method: string }, callback: (response: unknown) => void) => {
+ const req = Object.assign(new EventEmitter(), {
+ end: (data?: string) => {
+ const route = new URL(url).pathname.slice(3) + new URL(url).search;
+ fixture.routes.push(route);
+ const { serve, deliver } = fixture.timing?.(route) ?? { serve: fixture.latencyMs, deliver: fixture.latencyMs };
+ setTimeout(() => {
+ if (fixture.offline) { setTimeout(() => req.emit('error', Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })), deliver - serve); return; }
+ const answered = Promise.resolve(fixture.handle(route, options.method, data ? JSON.parse(data) : undefined));
+ const answer = () => void answered.then(result => {
+ const response = Object.assign(new EventEmitter(), { statusCode: result?.status ?? 200, headers: {} });
+ callback(response);
+ response.emit('data', Buffer.from(JSON.stringify(result?.body ?? {})));
+ response.emit('end');
+ }, error => req.emit('error', error));
+ if (deliver > serve) setTimeout(answer, deliver - serve); else answer();
+ }, serve);
+ },
+ destroy: (error: Error) => req.emit('error', error),
+ });
+ return req;
+ } };
+});
+vi.mock('node:https', async () => ({ request: (await import('node:http')).request }));
+vi.mock('ws', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { default: class extends EventEmitter {
+ static OPEN = 1; readyState = 1;
+ send = vi.fn((frame: string) => fixture.onFrame?.(this, JSON.parse(frame)));
+ constructor() { super(); fixture.sockets.push(this as unknown as import('ws').WebSocket); }
+ close() { this.emit('close'); }
+ } };
+});
+import { withChatServer } from '../chatServer.js';
+import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';
+
+const selfId = '30000000-0000-4000-8000-000000000001';
+const rooms = Array.from({ length: 8 }, (_, index) => `10000000-0000-4000-8000-00000000000${index + 1}`);
+const room = (id: string) => ({ id, name: `Room ${id.slice(-1)}`, state: 'joined', response_mode: 'all', speaking_mode: 'auto',
+ created_at: '2026-10-03T00:00:00Z', updated_at: '2026-10-03T00:00:00Z', revision: 1, archived: false });
+const message = { id: '50000000-0000-4000-8000-000000000001', seq: '1', authorId: selfId, author: { kind: 'human', name: 'Me' },
+ content: [{ type: 'text', text: 'hello' }], createdAt: '2026-10-03T00:00:00Z', deleted: false, threadRootId: null };
+function response(route: string) {
+ if (route === '/me') return { body: { actor: { id: selfId } } };
+ if (route === '/actors') return { body: [] };
+ if (route.startsWith('/conversations?')) return { body: rooms.map(room) };
+ if (route.endsWith('/snapshot')) return { body: { room: room(route.split('/')[2]), members: [], messages: [], cursor: '57' } };
+ if (route === '/executions/claim') return { body: { execution: null } };
+ if (route.includes('/messages?')) return { body: fixture.page };
+ if (route.endsWith('/executions') || route.includes('/execution-failures?') || route.includes('/plans')) return { body: [] };
+ return { body: {} };
+}
+
+async function timed<T>(run: () => Promise<T>): Promise<{ ms: number; value: T; routes: string[] }> {
+ const start = Date.now();
+ const from = fixture.routes.length;
+ let settled: { value: T } | undefined;
+ void run().then(value => { settled = { value }; });
+ while (!settled) await vi.advanceTimersByTimeAsync(5);
+ // Background claims/leases are independent of the open path.
+ const routes = fixture.routes.slice(from).filter(route => !route.startsWith('/executions/'));
+ return { ms: Date.now() - start, value: settled.value, routes };
+}
+
+describe('Chat Server group open latency (simulated 100ms per request)', () => {
+ let service: BotGroupChatService;
+ let local: { listGroups: ReturnType<typeof vi.fn>; settleLaneTurn: ReturnType<typeof vi.fn>; dispose: ReturnType<typeof vi.fn> };
+ let onChanged: ReturnType<typeof vi.fn>;
+ // Each scenario starts right after an actor registration, as the two-second poll keeps it.
+ const warm = async () => { await timed(() => service.chatServer!.ownedBots()); };
+ const sent = () => vi.mocked(fixture.sockets[0].send).mock.calls.map(([frame]) => JSON.parse(String(frame)));
+ async function connected() {
+ await vi.advanceTimersByTimeAsync(2500);
+ fixture.sockets[0].emit('message', JSON.stringify({ type: 'ready' }));
+ }
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'Date'] });
+ vi.setSystemTime(new Date('2026-10-03T00:00:00Z'));
+ vi.stubEnv('XDT_ISOLATED', '1');
+ fixture.routes = []; fixture.sockets = []; fixture.profiles = []; fixture.localGroupIds = []; fixture.latencyMs = 100;
+ fixture.timing = null; fixture.offline = false; fixture.onFrame = null;
+ fixture.page = [message];
+ fixture.handle.mockImplementation(response);
+ fixture.download.mockResolvedValue(null);
+ onChanged = vi.fn();
+ local = { listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() };
+ service = withChatServer(local as unknown as BotGroupChatService, { onChanged } as unknown as BotGroupChatServiceDeps);
+ });
+ afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); });
+
+ it('opens a group in three request rounds and a followed group in two', async () => {
+ const firstOpen = await timed(() => service.getGroup(rooms[0]));
+ await warm();
+ const firstVisit = await timed(() => service.getGroup(rooms[1]));
+ await warm();
+ const revisit = await timed(() => service.getGroup(rooms[0]));
+ await warm();
+ const firstList = await timed(() => service.listGroups());
+ await warm();
+ const nextList = await timed(() => service.listGroups());
+ // Before: 800 / 500 / 500 / 400 / 400 ms, every open reading snapshot → messages →
+ // executions → failures → plans one after another.
+ console.info(`[group-open-latency] ${JSON.stringify({ firstOpenMs: firstOpen.ms, firstVisitMs: firstVisit.ms, revisitMs: revisit.ms,
+ firstSidebarListMs: firstList.ms, nextSidebarListMs: nextList.ms, revisitRequests: revisit.routes.length })}`);
+ expect([firstOpen, firstVisit, revisit, firstList, nextList].every(read => read.value.ok)).toBe(true);
+ expect(firstVisit.ms).toBe(300);
+ expect(revisit.ms).toBe(200);
+ expect(nextList.ms).toBe(300);
+ // Shorter, not more: the same five reads per open.
+ expect(revisit.routes).toHaveLength(5);
+ });
+
+ it('reads a new room only after the snapshot whose cursor it follows from', async () => {
+ await warm();
+ const from = fixture.routes.length;
+ let snapshotAnswered = false;
+ fixture.handle.mockImplementation(route => {
+ if (route.endsWith('/snapshot')) snapshotAnswered = true;
+ return response(route);
+ });
+ const early: string[] = [];
+ const watch = setInterval(() => { if (!snapshotAnswered) early.push(...fixture.routes.slice(from)); }, 1);
+ await timed(() => service.getGroup(rooms[2]));
+ clearInterval(watch);
+ expect(early.filter(route => !route.startsWith('/executions/') && !route.endsWith('/snapshot'))).toEqual([]);
+ });
+
+ it('follows a newly opened room from its snapshot cursor and resumes after the last acked cursor', async () => {
+ await connected();
+ await timed(() => service.getGroup(rooms[0]));
+ expect(sent()).toContainEqual({ type: 'subscribe', scope: `conversation:${rooms[0]}`, after: '57' });
+ fixture.sockets[0].emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${rooms[0]}`, cursor: '58', changes: [] }));
+ vi.mocked(fixture.sockets[0].send).mockClear();
+ onChanged.mockClear();
+ fixture.sockets[0].emit('message', JSON.stringify({ type: 'ready' }));
+ expect(sent()).toContainEqual({ type: 'subscribe', scope: `conversation:${rooms[0]}`, after: '58' });
+ // A reconnect still re-reads every followed room once.
+ expect(onChanged).toHaveBeenCalledWith({ groupId: rooms[0], change: 'messages' }, undefined);
+ });
+
+ it('keeps the membership answer when a parallel read of a followed room fails first', async () => {
+ await timed(() => service.getGroup(rooms[0]));
+ await warm();
+ fixture.handle.mockImplementation(route => route.endsWith('/snapshot') ? { status: 404, body: { error: { code: 'CONVERSATION_NOT_FOUND' } } }
+ : route.includes('/messages?') ? { status: 403, body: { error: { code: 'FORBIDDEN' } } } : response(route));
+ fixture.timing = route => route.endsWith('/snapshot') ? { serve: 80, deliver: 80 } : { serve: 10, deliver: 10 };
+ const left = await timed(() => service.getGroup(rooms[0]));
+ expect(left.value).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });
+ });
+
+ it('reports the first failure in the former read order, not the fastest one', async () => {
+ await timed(() => service.getGroup(rooms[0]));
+ await warm();
+ fixture.handle.mockImplementation(route => route.includes('/messages?') ? { status: 403, body: { error: { code: 'FORBIDDEN' } } }
+ : route.endsWith('/executions') ? { status: 503, body: { error: { code: 'UNAVAILABLE' } } } : response(route));
+ fixture.timing = route => route.includes('/messages?') ? { serve: 90, deliver: 90 } : { serve: 10, deliver: 10 };
+ const denied = await timed(() => service.getGroup(rooms[0]));
+ // Serially, messages failed before executions was ever requested.
+ expect(denied.value).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ });
+
+ it('re-reads a room once for a page of attachments instead of once per file', async () => {
+ const media = Array.from({ length: 20 }, (_, index) => ({ ...message, id: `50000000-0000-4000-8000-0000000001${String(index).padStart(2, '0')}`,
+ content: [{ type: 'media', mediaId: `60000000-0000-4000-8000-0000000001${String(index).padStart(2, '0')}` }] }));
+ fixture.page = media;
+ fixture.download.mockImplementation((_room: string, mediaId: string) => new Promise(resolve => setTimeout(
+ () => resolve({ id: mediaId, name: 'image.png', category: 'image', path: '/test/image.png', url: null }), 10 + Number(mediaId.slice(-2)) * 5)));
+ await timed(() => service.getGroup(rooms[0]));
+ onChanged.mockClear();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onChanged.mock.calls.filter(([payload]) => payload.groupId === rooms[0])).toHaveLength(1);
+ const reread = await timed(() => service.getGroup(rooms[0]));
+ expect(reread.value.ok && reread.value.group.messages.every(item => item.attachments.length === 1)).toBe(true);
+ });
+
+ it('keeps attachment order, failures and a later retry when completions share one re-read', async () => {
+ const ids = ['60000000-0000-4000-8000-000000000201', '60000000-0000-4000-8000-000000000202', '60000000-0000-4000-8000-000000000203'];
+ fixture.page = [{ ...message, content: [{ type: 'text', text: 'three files' }, ...ids.map(mediaId => ({ type: 'media', mediaId }))] }];
+ const attachment = (mediaId: string) => ({ id: mediaId, name: `${mediaId.slice(-3)}.png`, category: 'image', path: `/test/${mediaId.slice(-3)}.png`, url: null });
+ let secondFails = true;
+ fixture.download.mockImplementation((_room: string, mediaId: string) => new Promise((resolve, reject) => setTimeout(() => {
+ if (mediaId === ids[1] && secondFails) reject(new Error('OBJECT_STORE_UNAVAILABLE'));
+ else resolve(attachment(mediaId));
+ // The last finishes first: order must come from the message, not from completion.
+ }, mediaId === ids[2] ? 10 : mediaId === ids[1] ? 40 : 60)));
+ await timed(() => service.getGroup(rooms[0]));
+ onChanged.mockClear();
+ await vi.advanceTimersByTimeAsync(1000);
+ // Two successes and one failure settle inside one window: one re-read shows their states.
+ expect(onChanged.mock.calls.filter(([payload]) => payload.groupId === rooms[0])).toHaveLength(1);
+ const settled = await timed(() => service.getGroup(rooms[0]));
+ expect(settled.value.ok && settled.value.group.messages[0].attachments.map(item => item.id)).toEqual([ids[0], ids[2]]);
+ // A failed file is not retried during its backoff, then is retried by the next read.
+ expect(fixture.download).toHaveBeenCalledTimes(3);
+ secondFails = false;
+ await vi.advanceTimersByTimeAsync(30_000);
+ onChanged.mockClear();
+ await timed(() => service.getGroup(rooms[0]));
+ expect(fixture.download).toHaveBeenCalledTimes(4);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onChanged.mock.calls.filter(([payload]) => payload.groupId === rooms[0])).toHaveLength(1);
+ const recovered = await timed(() => service.getGroup(rooms[0]));
+ expect(recovered.value.ok && recovered.value.group.messages[0].attachments.map(item => item.id)).toEqual(ids);
+ });
+
+ it('notifies again for an attachment that settles after a coalesced re-read was sent', async () => {
+ const ids = ['60000000-0000-4000-8000-000000000301', '60000000-0000-4000-8000-000000000302'];
+ fixture.page = [{ ...message, content: ids.map(mediaId => ({ type: 'media', mediaId })) }];
+ fixture.download.mockImplementation((_room: string, mediaId: string) => new Promise(resolve => setTimeout(
+ () => resolve({ id: mediaId, name: 'late.png', category: 'image', path: '/test/late.png', url: null }), mediaId === ids[0] ? 10 : 900)));
+ await timed(() => service.getGroup(rooms[0]));
+ onChanged.mockClear();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(onChanged.mock.calls.filter(([payload]) => payload.groupId === rooms[0])).toHaveLength(2);
+ const read = await timed(() => service.getGroup(rooms[0]));
+ expect(read.value.ok && read.value.group.messages[0].attachments.map(item => item.id)).toEqual(ids);
+ });
+
+ describe('attachment notices across the coalescing window', () => {
+ const media = (index: number) => `60000000-0000-4000-8000-0000000004${String(index).padStart(2, '0')}`;
+ const attachment = (mediaId: string) => ({ id: mediaId, name: 'file.png', category: 'image', path: '/test/file.png', url: null });
+ /** Downloads settle at the given ms after the first read; returns their settle times. */
+ function scheduleDownloads(plan: Array<{ at: number; fails?: boolean }>) {
+ fixture.page = [{ ...message, content: plan.map((_, index) => ({ type: 'media', mediaId: media(index) })) }];
+ const settled: number[] = [];
+ fixture.download.mockImplementation((_room: string, mediaId: string) => {
+ const step = plan[Number(mediaId.slice(-2))]!;
+ return new Promise((resolve, reject) => setTimeout(() => {
+ settled.push(Date.now());
+ if (step.fails) reject(new Error('OBJECT_STORE_UNAVAILABLE')); else resolve(attachment(mediaId));
+ }, step.at));
+ });
+ return settled;
+ }
+ let notices: number[] = [];
+ beforeEach(() => {
+ notices = [];
+ onChanged.mockImplementation((payload: { groupId: string }) => { if (payload.groupId === rooms[0]) notices.push(Date.now()); });
+ });
+
+ it.each([
+ ['the last one succeeds', false],
+ ['the last one fails', true],
+ ])('delivers a notice after every settle when %s, across the window boundary', async (_name, lastFails) => {
+ // The last settle lands inside the window opened by the one before it.
+ const settled = scheduleDownloads([{ at: 0 }, { at: 150 }, { at: 199 }, { at: 200 }, { at: 201 }, { at: 399 }, { at: 650 }, { at: 700, fails: lastFails }]);
+ await timed(() => service.getGroup(rooms[0]));
+ notices = [];
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(settled).toHaveLength(8);
+ // No settle is left without a later notice, so the last state is always re-read.
+ for (const at of settled) expect(notices.some(time => time >= at)).toBe(true);
+ expect(Math.max(...notices)).toBeGreaterThanOrEqual(Math.max(...settled));
+ expect(notices.length).toBeLessThan(settled.length);
+ const read = await timed(() => service.getGroup(rooms[0]));
+ expect(read.value.ok && read.value.group.messages[0].attachments).toHaveLength(lastFails ? 7 : 8);
+ });
+
+ it('re-reads again when a download settles while the previous refresh is still in flight', async () => {
+ scheduleDownloads([{ at: 0 }, { at: 260 }]);
+ await timed(() => service.getGroup(rooms[0]));
+ // Each notice starts a refresh, as the group page does; the newest answer is shown.
+ let shown: string[] = [];
+ let version = 0;
+ onChanged.mockImplementation((payload: { groupId: string }) => {
+ if (payload.groupId !== rooms[0]) return;
+ notices.push(Date.now());
+ const current = ++version;
+ void service.getGroup(rooms[0]).then(result => {
+ if (current === version && result.ok) shown = result.group.messages[0].attachments.map(item => item.id);
+ });
+ });
+ await vi.advanceTimersByTimeAsync(3000);
+ // The first refresh (sent at ~200ms, reads ~200ms) was in flight when the second file settled.
+ expect(notices.length).toBe(2);
+ expect(shown).toEqual([media(0), media(1)]);
+ });
+
+ it('keeps notices per group', async () => {
+ fixture.page = [{ ...message, content: [{ type: 'media', mediaId: media(0) }] }];
+ fixture.download.mockImplementation((_room: string, mediaId: string) => new Promise(resolve => setTimeout(() => resolve(attachment(mediaId)), 50)));
+ await Promise.all([timed(() => service.getGroup(rooms[0])), timed(() => service.getGroup(rooms[1]))]);
+ onChanged.mockClear();
+ await vi.advanceTimersByTimeAsync(1000);
+ const groups = onChanged.mock.calls.map(([payload]) => payload.groupId);
+ expect(groups.filter(id => id === rooms[0])).toHaveLength(1);
+ expect(groups.filter(id => id === rooms[1])).toHaveLength(1);
+ });
+
+ it('drops a pending notice of the previous account after a switch', async () => {
+ service.dispose();
+ let epoch = 0;
+ const ownerChanged = vi.fn();
+ service = withChatServer(local as unknown as BotGroupChatService, {
+ captureOwnerScope: () => ({ epoch }),
+ isOwnerScopeCurrent: (scope: { epoch: number }) => scope.epoch === epoch,
+ onChanged: ownerChanged,
+ } as unknown as BotGroupChatServiceDeps);
+ scheduleDownloads([{ at: 0 }, { at: 100 }]);
+ await timed(() => service.getGroup(rooms[0]));
+ await vi.advanceTimersByTimeAsync(50);
+ ownerChanged.mockClear();
+ epoch += 1;
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(ownerChanged).not.toHaveBeenCalled();
+ });
+ });
+
+ it('does not summarize every local history to open a server room', async () => {
+ await timed(() => service.getGroup(rooms[0]));
+ expect(local.listGroups).not.toHaveBeenCalled();
+ fixture.localGroupIds = [rooms[1]];
+ await warm();
+ await timed(() => service.getGroup(rooms[1]));
+ expect(local.listGroups).toHaveBeenCalled();
+ });
+});
+
+describe('Chat Server realtime cursor against a server model', () => {
+ const roomId = rooms[0];
+ const peer = '30000000-0000-4000-8000-000000000002';
+ let service: BotGroupChatService;
+ let head = 0;
+ let history: Array<Record<string, unknown>> = [];
+ /** Per socket: the subscription cursor and the batch awaiting its ack, as realtime.ts keeps them. */
+ const subscriptions = new Map<unknown, Map<string, { cursor: number; pending?: number }>>();
+ /** The renderer's rule: the newest request wins, a failed refresh keeps what is shown. */
+ let shown: string[] = [];
+ let requestVersion = 0;
+ const show = () => {
+ const version = ++requestVersion;
+ void service.getGroup(roomId).then(result => {
+ if (version === requestVersion && result.ok) shown = result.group.messages.map(item => item.content);
+ });
+ };
+ const commit = (text: string) => {
+ head += 1;
+ history.push({ id: `50000000-0000-4000-8000-${String(head).padStart(12, '0')}`, seq: String(head), authorId: peer, author: { kind: 'human', name: 'Peer' },
+ content: [{ type: 'text', text }], createdAt: '2026-10-03T00:00:00Z', deleted: false, threadRootId: null });
+ };
+ const socket = () => fixture.sockets.at(-1)!;
+ /** One realtime poll: each idle subscription behind the head receives one batch. */
+ const pump = () => {
+ for (const [scope, entry] of subscriptions.get(socket()) ?? []) {
+ if (entry.pending !== undefined || entry.cursor >= head) continue;
+ entry.pending = head;
+ socket().emit('message', JSON.stringify({ type: 'changes', scope, cursor: String(head), changes: [{ type: 'message.created' }] }));
+ }
+ };
+ const ready = () => socket().emit('message', JSON.stringify({ type: 'ready' }));
+ const subscribeFrames = () => fixture.sockets.flatMap(item => vi.mocked(item.send).mock.calls.map(([frame]) => JSON.parse(String(frame))))
+ .filter(frame => frame.type === 'subscribe' && frame.scope === `conversation:${roomId}`);
+
+ beforeEach(async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'Date'] });
+ vi.setSystemTime(new Date('2026-10-03T00:00:00Z'));
+ vi.stubEnv('XDT_ISOLATED', '1');
+ fixture.routes = []; fixture.sockets = []; fixture.profiles = []; fixture.localGroupIds = []; fixture.latencyMs = 20;
+ fixture.timing = null; fixture.offline = false;
+ head = 0; history = []; shown = []; requestVersion = 0; subscriptions.clear();
+ for (const text of ['one', 'two', 'three']) commit(text);
+ fixture.onFrame = (owner, frame) => {
+ const scopes = subscriptions.get(owner) ?? new Map();
+ subscriptions.set(owner, scopes);
+ if (frame.type === 'subscribe') scopes.set(String(frame.scope), { cursor: Number(frame.after) });
+ if (frame.type === 'ack') {
+ const entry = scopes.get(String(frame.scope));
+ if (entry?.pending === Number(frame.cursor)) { entry.cursor = entry.pending; entry.pending = undefined; }
+ }
+ };
+ fixture.handle.mockImplementation(route => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members: [], messages: [...history].reverse().slice(0, 100), cursor: String(head) } };
+ if (route.includes('/messages?')) return { body: [...history].reverse().slice(0, 100) };
+ return response(route);
+ });
+ service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() } as unknown as BotGroupChatService,
+ { onChanged: vi.fn(payload => { if (payload.groupId === roomId) show(); }) } as unknown as BotGroupChatServiceDeps);
+ await vi.advanceTimersByTimeAsync(2500);
+ ready();
+ show();
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); });
+
+ it('shows a change that a parallel read missed, even when its refresh fails during a disconnect', async () => {
+ expect(shown).toEqual(['one', 'two', 'three']);
+ expect(subscribeFrames()).toEqual([{ type: 'subscribe', scope: `conversation:${roomId}`, after: '3' }]);
+ // A followed room: messages are read before "four" commits, the snapshot after it.
+ fixture.timing = route => route.endsWith('/snapshot') ? { serve: 90, deliver: 100 } : { serve: 10, deliver: 20 };
+ show();
+ setTimeout(() => commit('four'), 50);
+ await vi.advanceTimersByTimeAsync(200);
+ expect(shown).toEqual(['one', 'two', 'three']);
+ // The change arrives, but its refresh fails and the connection drops before any re-read.
+ fixture.offline = true;
+ pump();
+ socket().emit('close');
+ await vi.advanceTimersByTimeAsync(200);
+ expect(shown).not.toContain('four');
+ fixture.offline = false;
+ fixture.timing = null;
+ await vi.advanceTimersByTimeAsync(600);
+ expect(fixture.sockets).toHaveLength(2);
+ ready();
+ await vi.advanceTimersByTimeAsync(500);
+ // Resumes after what was read, without replaying the history, and re-reads the room.
+ expect(subscribeFrames().at(-1)).toEqual({ type: 'subscribe', scope: `conversation:${roomId}`, after: '4' });
+ expect(shown).toEqual(['one', 'two', 'three', 'four']);
+ commit('five');
+ pump();
+ await vi.advanceTimersByTimeAsync(500);
+ expect(shown).toEqual(['one', 'two', 'three', 'four', 'five']);
+ });
+
+ it('follows a new room from the first snapshot answer and never rewinds to a late older one', async () => {
+ service.dispose();
+ fixture.sockets = []; subscriptions.clear(); shown = [];
+ service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() } as unknown as BotGroupChatService,
+ { onChanged: vi.fn(payload => { if (payload.groupId === roomId) show(); }) } as unknown as BotGroupChatServiceDeps);
+ await vi.advanceTimersByTimeAsync(2500);
+ ready();
+ let snapshots = 0;
+ // The first snapshot is read at "three" but answers last; the second is read at "four" and answers first.
+ fixture.timing = route => {
+ if (!route.endsWith('/snapshot')) return { serve: 10, deliver: 20 };
+ snapshots += 1;
+ return snapshots === 1 ? { serve: 10, deliver: 300 } : { serve: 60, deliver: 100 };
+ };
+ const results: string[][] = [];
+ const read = () => void service.getGroup(roomId).then(result => { if (result.ok) results.push(result.group.messages.map(item => item.content)); });
+ read();
+ setTimeout(() => commit('four'), 30);
+ setTimeout(read, 40);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(subscribeFrames()).toEqual([{ type: 'subscribe', scope: `conversation:${roomId}`, after: '4' }]);
+ expect(results).toEqual([['one', 'two', 'three', 'four'], ['one', 'two', 'three', 'four']]);
+ fixture.timing = null;
+ socket().emit('close');
+ await vi.advanceTimersByTimeAsync(600);
+ ready();
+ expect(subscribeFrames().at(-1)).toEqual({ type: 'subscribe', scope: `conversation:${roomId}`, after: '4' });
+ commit('five');
+ pump();
+ await vi.advanceTimersByTimeAsync(500);
+ expect(shown.at(-1)).toBe('five');
+ });
+
+ it('starts a new room from a stale cursor only through the server reset path', async () => {
+ // A cursor below the server floor answers RESET_REQUIRED; the room is re-read from a new snapshot.
+ commit('four');
+ socket().emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'RESET_REQUIRED' } }));
+ await vi.advanceTimersByTimeAsync(500);
+ expect(subscribeFrames().at(-1)).toEqual({ type: 'subscribe', scope: `conversation:${roomId}`, after: '4' });
+ expect(shown).toEqual(['one', 'two', 'three', 'four']);
+ });
+});
+
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index b344f58787..994d86245f 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -82,6 +82,7 @@ class ChatResponseError extends Error {
const CHAT_AUTH_RETRY_MS = 60_000;
/** Main-group messages kept as background for a Thread request (the Thread itself is read separately). */
const THREAD_BACKGROUND_LIMIT = 30;
+const ATTACHMENT_REFRESH_COALESCE_MS = 200;
const CHAT_REFRESHABLE_ERROR_CODES = new Set(['TOKEN_EXPIRED', 'INVALID_TOKEN', 'AUTH_REQUIRED']);
const recoverableAuth = (error: ChatResponseError) => error.status === 401
&& (CHAT_REFRESHABLE_ERROR_CODES.has(error.message) || error.message === 'INVALID_CHAT_RESPONSE');
@@ -188,7 +189,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
let profileRefreshedAt = 0;
const running = new Map<string, Running>();
const metadata = new Map<string, Promise<void>>();
- const rooms = new Set<string>();
+ /**
+ * Followed room scopes, each with the newest cursor this process has read or acked. It only
+ * chooses where a reconnect resumes; every reconnect also re-reads each followed room.
+ */
+ const rooms = new Map<string, string>();
+ /** Keep a room's newer cursor: a late snapshot or event must not rewind where it resumes. */
+ const advanceRoom = (roomId: string, cursor: string) => {
+ const known = rooms.get(roomId);
+ if (known === undefined || /^\d+$/.test(cursor) && /^\d+$/.test(known) && BigInt(cursor) > BigInt(known)) rooms.set(roomId, cursor);
+ };
let socket: WebSocket | undefined;
let reconnect: ReturnType<typeof setTimeout> | undefined;
let reconnectDelay = 500;
@@ -364,8 +374,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const resolveGroup = async (groupId: string) => {
await register();
if (upgradedGroups.has(groupId)) return upgradedGroups.get(groupId)!;
- const localGroups = await localSources();
- if (localGroups.some(group => group.id === groupId)) {
+ // A server room has no local row; only an existing local history may still need its upgrade.
+ const [localRow] = await getDbClient().drizzle.select({ id: botGroups.id }).from(botGroups).where(eq(botGroups.id, groupId)).limit(1);
+ if (localRow && (await localSources()).some(group => group.id === groupId)) {
await ensureUpgrade();
if (!upgradedGroups.has(groupId)) throw new Error('IMPORT_PENDING');
}
@@ -408,9 +419,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
})().finally(() => { refreshActors = undefined; });
return refreshActors;
}
- function subscribe(roomId: string) {
- const fresh = !rooms.has(roomId); rooms.add(roomId);
- if (fresh && connected && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: '0' }));
+ /**
+ * Follow a room from a cursor whose state has already been read. A snapshot cursor skips
+ * replaying the room's whole change log, one full re-read per hundred old changes.
+ */
+ function subscribe(roomId: string, cursor = '0') {
+ const fresh = !rooms.has(roomId); advanceRoom(roomId, cursor);
+ if (fresh && connected && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: cursor }));
}
function connect() {
if (!current()) return;
@@ -429,13 +444,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
memberJoinedClaims = true;
reconnectDelay = 500; connected = true;
ws.send(JSON.stringify({ type: 'subscribe', scope: `actor:${selfId}`, after: '0' }));
- for (const roomId of rooms) ws.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: '0' }));
- for (const roomId of rooms) changed(roomId);
+ for (const [roomId, cursor] of rooms) ws.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: cursor }));
+ for (const roomId of rooms.keys()) changed(roomId);
} else if (event.type === 'changes') {
- // This adapter stores no client history/cursor. Each invalidation re-reads
- // authoritative state; reconnect always starts from zero.
+ // This adapter stores no client history. Each invalidation re-reads authoritative
+ // state; a reconnect resumes after the last cursor this process has read or acked.
if (event.scope.startsWith('conversation:')) {
const roomId = event.scope.slice(13);
+ if (rooms.has(roomId)) advanceRoom(roomId, event.cursor);
changed(roomId);
for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);
}
@@ -449,6 +465,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (event.error?.code === 'RESET_REQUIRED') {
void api<Snapshot>(`/conversations/${roomId}/snapshot`).then(value => {
if (!current() || socket !== ws || ws.readyState !== WebSocket.OPEN) return;
+ if (rooms.has(roomId)) advanceRoom(roomId, value.cursor);
changed(roomId);
ws.send(JSON.stringify({ type: 'subscribe', scope: event.scope, after: value.cursor }));
}).catch(() => ws.close());
@@ -470,7 +487,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
async function snapshot(roomId: string) {
id.parse(roomId); await register();
const value = await api<Snapshot>(`/conversations/${roomId}/snapshot`);
- subscribe(roomId);
+ subscribe(roomId, value.cursor);
return value;
}
function managementActor(s: Snapshot) {
@@ -518,6 +535,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
// Attachments are independent of the text projection. A failed object store
// request never rejects a room/Thread; subsequent reads retry after a backoff.
const downloads = new Map<string, { value?: BotGroupAttachment; retryAt: number }>();
+ // A page's attachments settle close together; one re-read of the room and sidebar shows
+ // them all instead of one full re-read per file.
+ const attachmentRefreshes = new Map<string, ReturnType<typeof setTimeout>>();
+ function attachmentsChanged(roomId: string) {
+ if (!current() || attachmentRefreshes.has(roomId)) return;
+ attachmentRefreshes.set(roomId, setTimeout(() => {
+ attachmentRefreshes.delete(roomId);
+ changed(roomId);
+ }, ATTACHMENT_REFRESH_COALESCE_MS));
+ }
async function messageViews(roomId: string, messages: Message[], members: Member[]) {
return messages.map(message => {
const view = messageView(message, members);
@@ -532,7 +559,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
void media.download(roomId, mediaId).then(value => {
if (current()) entry.value = value;
}).catch(() => { entry.retryAt = Date.now() + 30000; })
- .finally(() => { if (current()) changed(roomId); });
+ .finally(() => attachmentsChanged(roomId));
}
if (cached.value) view.attachments.push(cached.value);
}
@@ -540,16 +567,29 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
});
}
async function detail(roomId: string, options?: unknown, summaryOnly = false): Promise<BotGroupDetail> {
- const s = await snapshot(roomId);
+ id.parse(roomId);
const o = z.object({ beforeSequence: z.number().int().positive().optional(), limit: z.number().int().min(1).max(100).optional(),
sourceMessageIds: z.array(id).optional() }).parse(options ?? {});
const query = new URLSearchParams({ limit: String(o.limit ?? 100) });
if (o.beforeSequence) query.set('before', String(o.beforeSequence));
- const page = summaryOnly ? s.messages : await api<Message[]>(`/conversations/${roomId}/messages?${query}`);
- const executions = await api<Execution[]>(`/conversations/${roomId}/executions`);
- const executionFailures = summaryOnly ? undefined : await failureSnapshot(roomId, s.members, [...(o.sourceMessageIds ?? []), ...page.map(m => m.id)], executions);
+ // Independent reads share a round trip. Each is awaited in the former serial order, so the
+ // first failure in snapshot → messages → executions → failures → plans is still the one
+ // reported (a left room stays 「not found」), whichever request fails first in time.
+ // A followed room reports every later change, so its snapshot may run alongside. A new
+ // room first takes the snapshot cursor it will follow from, before the rest is read.
+ const snapshotRead = snapshot(roomId);
+ if (!rooms.has(roomId)) await snapshotRead;
+ const messagesRead = summaryOnly ? null : api<Message[]>(`/conversations/${roomId}/messages?${query}`);
+ const executionsRead = api<Execution[]>(`/conversations/${roomId}/executions`);
+ for (const read of [messagesRead, executionsRead]) read?.catch(() => undefined);
+ const s = await snapshotRead;
+ const page = (await messagesRead) ?? s.messages;
+ const executions = await executionsRead;
const ids = page.flatMap(m => m.content.flatMap(b => b.namespace === 'cindy.plan' && typeof b.data?.planId === 'string' ? [id.parse(b.data.planId)] : []));
- const serverPlans = await api<ServerPlan[]>(`/conversations/${roomId}/plans${ids.length ? `?ids=${ids.join(',')}` : ''}`);
+ const plansRead = api<ServerPlan[]>(`/conversations/${roomId}/plans${ids.length ? `?ids=${ids.join(',')}` : ''}`);
+ plansRead.catch(() => undefined);
+ const executionFailures = summaryOnly ? undefined : await failureSnapshot(roomId, s.members, [...(o.sourceMessageIds ?? []), ...page.map(m => m.id)], executions);
+ const serverPlans = await plansRead;
const workspace = workspaces().read(roomId);
const plans = serverPlans.map(plan => planView(plan, s.members, workspace));
const open = plans.find(p => ['proposed', 'running', 'waiting'].includes(p.status));
@@ -1086,7 +1126,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
ownedBots: () => result(async () => { await register(); return { bots: actors.filter(a => a.kind === 'bot' && localBot(a.id)?.status === 'active').map(a => ({ actorId: a.id, name: a.name })) }; }),
refreshProfile: () => result(async () => {
await api('/profile/refresh', 'POST'); profileRefreshedAt = Date.now();
- for (const roomId of rooms) changed(roomId);
+ for (const roomId of rooms.keys()) changed(roomId);
changed(''); return {};
}),
manage: input => result(async () => {
@@ -1319,6 +1359,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
editPlanStep: input => safe(() => actPlan(input, 'reassign')),
dispose: () => {
disposed = true; clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); socket?.close();
+ for (const refresh of attachmentRefreshes.values()) clearTimeout(refresh);
+ attachmentRefreshes.clear();
for (const run of running.values()) {
run.releaseToolAuthority?.();
if (run.sessionId) void deps.abortLane(run.sessionId).catch(() => undefined);
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index fdf20a7fa2..ba078e50de 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -31,6 +31,7 @@ import { UserAttachmentChip } from '@/components/chat/UserAttachmentChip';
import { CHAT_BODY_CLASS } from '@/components/chat/chatChrome';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
import {
getDataOwnerGeneration,
@@ -92,7 +93,7 @@ import {
mergeBotGroupPlans,
openBotGroupPlan,
} from './botGroupPresentation';
-import { botGroupApi, editBotGroupPlanStep, runBotGroupPlanAction } from './botGroupStore';
+import { botGroupApi, editBotGroupPlanStep, runBotGroupPlanAction, useBotGroupSummary } from './botGroupStore';
import { botGroupReadKey, markBotRead } from './botReadState';
import { collectBotMessageTimeGroups, formatBotMessageGroupTime } from './botConversationTimeline';
@@ -120,6 +121,9 @@ const PLAN_ACTION_FAILED: Record<BotGroupPlanAction, string> = {
type PlanPending = { planId: string; action: BotGroupPlanAction | 'edit' };
+/** A read that lands within this needs no progress indicator, so a fast switch does not flash. */
+const TIMELINE_LOADING_REVEAL_MS = 200;
+
/** Stable identity for header memoization; member arrays are new on every read. */
function memberKey(members: readonly BotGroupMemberView[]): string {
return JSON.stringify(members.map((member) => [member.botId, member.name, member.avatar, member.avatarColor]));
@@ -237,6 +241,9 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
}, [groupId, reloadVersion]);
const group = state.kind === 'ready' ? state.group : null;
+ // Until the timeline arrives, the header comes from the group's sidebar row (same account).
+ const listed = useBotGroupSummary(state.kind === 'loading' || state.kind === 'error' ? groupId : null);
+ const headerGroup = group ?? listed;
const messages = useMemo(
() => (state.kind === 'ready' ? projectBotGroupExecutionFailures(mergeBotGroupMessages(state.older, state.group.messages), state.group.executionFailures) : []),
[state],
@@ -315,10 +322,10 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
return () => document.removeEventListener('keydown', onKeyDown);
}, [group?.serverBacked, threadRootId, closeThread, shareScope]);
const settingsLabel = t('bots.groupChat.settings.open');
- const headerMembers = group ? memberKey(group.members) : '';
+ const headerMembers = headerGroup ? memberKey(headerGroup.members) : '';
const header = useMemo(() => {
- if (!group) return null;
- const names = botGroupMemberNames(group.members, separator);
+ if (!headerGroup) return null;
+ const names = botGroupMemberNames(headerGroup.members, separator);
return (
<div ref={threadHeaderRef} data-testid="bot-group-content-header" className="flex h-full w-full min-w-0 items-center gap-2 pr-2">
<button
@@ -327,14 +334,14 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
className="flex min-w-0 items-center gap-2 rounded-full px-2 py-1 text-left hover:bg-[var(--surface-hover)]"
style={WINDOW_NO_DRAG_STYLE}
>
- <BotGroupAvatarStack members={group.members} />
- <span className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">{group.name}</span>
+ <BotGroupAvatarStack members={headerGroup.members} />
+ <span className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">{headerGroup.name}</span>
<span className="hidden min-w-0 truncate text-12 text-[var(--text-tertiary)] sm:inline" title={names}>
{names}
</span>
</button>
<div className="ml-auto flex shrink-0 items-center">
- {group.serverBacked && group.canInvite && <ChatInviteButton groupId={group.id} />}
+ {headerGroup.serverBacked && headerGroup.canInvite && <ChatInviteButton groupId={headerGroup.id} />}
<Tip text={settingsLabel}>
<button
type="button"
@@ -350,7 +357,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
</div>
);
// headerMembers stands in for the member array, which is new on every read.
- }, [group?.name, group?.id, group?.serverBacked, group?.canInvite, headerMembers, openSettings, separator, settingsLabel]);
+ }, [headerGroup?.name, headerGroup?.id, headerGroup?.serverBacked, headerGroup?.canInvite, headerMembers, openSettings, separator, settingsLabel]);
useRegisterContentHeader(header);
// Follow new messages and banner viewport changes only while the reader is at the bottom.
@@ -517,8 +524,11 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
};
if (state.kind === 'loading') {
- // Local reads are fast; an empty surface avoids a spinner flash.
- return <main className="h-full bg-[var(--surface)]" />;
+ return (
+ <main className="flex h-full items-center justify-center bg-[var(--surface)]">
+ <BotGroupTimelineLoading />
+ </main>
+ );
}
if (state.kind !== 'ready' || !group) {
const failed = state.kind === 'error';
@@ -759,6 +769,25 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
);
}
+function BotGroupTimelineLoading() {
+ const { t } = useTranslation();
+ const [visible, setVisible] = useState(false);
+ useEffect(() => {
+ const timer = setTimeout(() => setVisible(true), TIMELINE_LOADING_REVEAL_MS);
+ return () => clearTimeout(timer);
+ }, []);
+ if (!visible) return null;
+ return (
+ <Spinner
+ size={20}
+ data-testid="bot-group-timeline-loading"
+ className="text-[var(--text-tertiary)]"
+ role="status"
+ aria-label={t('ccAgent.common.loading')}
+ />
+ );
+}
+
function planCardPending(action: PlanPending['action'] | null): BotGroupPlanCardAction | null {
return action === 'start' || action === 'dismiss' || action === 'edit' ? action : null;
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index ac37c20b07..61aa6f5bec 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -12,6 +12,7 @@ import { clearDraft, getDraft } from '@/lib/composerDraftStore';
import { FeatureSidebarSlotProvider, useFeatureContentHeader } from '../../feature-context';
import { markBotRead, getBotLastReadAt, botGroupReadKey, resetBotReadStateForTests } from '../botReadState';
import { botGroupAttachmentScope } from '../botGroupAttachments';
+import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests } from '../botGroupStore';
import { BotGroupChatView } from '../BotGroupChatView';
import { ControlledBanner, __resetControlledBannerForTests } from '../../remote-device/ControlledBanner';
import type {
@@ -1048,6 +1049,130 @@ describe('BotGroupChatView', () => {
expect(mocks.sendBotGroupMessage.mock.calls[0]![0].mentions).toEqual({ all: false, botIds: [removed === 'picked' ? 'other' : 'picked'] });
});
+ describe('while the timeline loads', () => {
+ function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+ }
+ /** The sidebar list as main reports it; the view only borrows the row for its header. */
+ async function listGroups(groups: BotGroupDetail[]) {
+ resetBotGroupStoreForTests();
+ window.electronAPI.maker.listBotGroups = vi.fn(async () => ({ ok: true as const, groups }));
+ refreshBotGroups();
+ await waitFor(() => expect(getBotGroupListSnapshot().loaded).toBe(true));
+ }
+ afterEach(() => resetBotGroupStoreForTests());
+
+ it('shows the listed header at once and a progress indicator only for a slow read', async () => {
+ await listGroups([detail({ messages: [] })]);
+ const read = deferred<{ ok: true; group: BotGroupDetail }>();
+ mocks.getBotGroup.mockReturnValue(read.promise);
+ renderView();
+ const header = screen.getByTestId('content-header');
+ expect(header.textContent).toContain('周末出游');
+ expect(header.textContent).toContain('咪咪');
+ expect(screen.queryByTestId('bot-group-timeline-loading')).toBeNull();
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(await screen.findByRole('status', { name: 'ccAgent.common.loading' })).toBeTruthy();
+ await act(async () => read.resolve({ ok: true, group: detail() }));
+ expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
+ expect(screen.queryByTestId('bot-group-timeline-loading')).toBeNull();
+ expect(screen.getByRole('textbox')).toBeTruthy();
+ });
+
+ it('never shows a fast read’s progress indicator', async () => {
+ await listGroups([detail()]);
+ renderView();
+ expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
+ await new Promise((done) => setTimeout(done, 250));
+ expect(screen.queryByTestId('bot-group-timeline-loading')).toBeNull();
+ });
+
+ it('keeps a quickly left group’s late timeline and header out of the next group', async () => {
+ await listGroups([detail(), detail({ id: 'g2', name: '读书会', members: [{ botId: 'ajie', name: '阿杰', avatar: '', avatarColor: 'green', status: 'active' }] })]);
+ const first = deferred<{ ok: true; group: BotGroupDetail }>();
+ const second = deferred<{ ok: true; group: BotGroupDetail }>();
+ mocks.getBotGroup.mockImplementation((id: string) => (id === 'g1' ? first.promise : second.promise));
+ const view = renderView();
+ expect(screen.getByTestId('content-header').textContent).toContain('周末出游');
+ mocks.groupId = 'g2';
+ view.rerender(
+ <Tooltip.Provider>
+ <FeatureSidebarSlotProvider isCollapsed={false}>
+ <HeaderSlot />
+ <BotGroupChatView />
+ </FeatureSidebarSlotProvider>
+ </Tooltip.Provider>,
+ );
+ const header = screen.getByTestId('content-header');
+ expect(header.textContent).toContain('读书会');
+ expect(header.textContent).not.toContain('周末出游');
+ await act(async () => first.resolve({ ok: true, group: detail() }));
+ expect(screen.queryByText('周六 8:10 有票')).toBeNull();
+ expect(header.textContent).not.toContain('周末出游');
+ await act(async () => second.resolve({ ok: true, group: detail({ id: 'g2', name: '读书会', messages: [msg({ id: 'r1', content: '这周读哪本' })] }) }));
+ expect(await screen.findByText('这周读哪本')).toBeTruthy();
+ expect(screen.queryByText('周六 8:10 有票')).toBeNull();
+ });
+
+ it('opens the route-owned settings from the loading header without re-reading the timeline', async () => {
+ await listGroups([detail()]);
+ mocks.getBotGroup.mockReturnValue(new Promise(() => {}));
+ renderView();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.settings.open' }));
+ expect(mocks.navigate).toHaveBeenCalledWith('/bots/groups/g1?groupSettings=1');
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows only the second visit’s read after A → B → A', async () => {
+ await listGroups([detail(), detail({ id: 'g2', name: '读书会' })]);
+ const reads: Array<{ id: string; resolve: (value: { ok: true; group: BotGroupDetail }) => void }> = [];
+ mocks.getBotGroup.mockImplementation((id: string) => new Promise((resolve) => { reads.push({ id, resolve }); }));
+ const view = renderView();
+ const rerender = (id: string) => {
+ mocks.groupId = id;
+ view.rerender(
+ <Tooltip.Provider>
+ <FeatureSidebarSlotProvider isCollapsed={false}>
+ <HeaderSlot />
+ <BotGroupChatView />
+ </FeatureSidebarSlotProvider>
+ </Tooltip.Provider>,
+ );
+ };
+ rerender('g2');
+ rerender('g1');
+ expect(reads.map((read) => read.id)).toEqual(['g1', 'g2', 'g1']);
+ await act(async () => reads[0]!.resolve({ ok: true, group: detail({ messages: [msg({ id: 'old', content: '第一次打开的旧回包' })] }) }));
+ await act(async () => reads[1]!.resolve({ ok: true, group: detail({ id: 'g2', name: '读书会', messages: [msg({ id: 'b', content: '读书会的回包' })] }) }));
+ expect(screen.queryByText('第一次打开的旧回包')).toBeNull();
+ expect(screen.queryByText('读书会的回包')).toBeNull();
+ expect(screen.getByTestId('content-header').textContent).toContain('周末出游');
+ await act(async () => reads[2]!.resolve({ ok: true, group: detail() }));
+ expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
+ });
+
+ it('keeps the header with a retry when the first read fails', async () => {
+ await listGroups([detail()]);
+ mocks.getBotGroup.mockResolvedValueOnce({ ok: false, errorCode: 'REQUEST_TIMEOUT', message: '' });
+ renderView();
+ expect(await screen.findByText('bots.groupChat.loadFailedTitle')).toBeTruthy();
+ expect(screen.getByTestId('content-header').textContent).toContain('周末出游');
+ fireEvent.click(screen.getByRole('button', { name: /bots.retry/ }));
+ expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
+ });
+
+ it('shows no header for a group that is no longer listed, then the unavailable state', async () => {
+ await listGroups([]);
+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'NOT_FOUND', message: '' });
+ renderView();
+ expect(screen.getByTestId('content-header').textContent).toBe('');
+ expect(await screen.findByText('bots.groupChat.unavailableTitle')).toBeTruthy();
+ expect(screen.getByTestId('content-header').textContent).toBe('');
+ });
+ });
+
it('refreshes on a push for this group and shows the unavailable state after delete', async () => {
renderView();
await screen.findByText('周六 8:10 有票');
diff --git a/apps/desktop/src/renderer/features/bots/botGroupStore.ts b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
index 49b11b5cb9..37581c9f28 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
@@ -7,7 +7,7 @@
* 再来的推送合并成一次补取。账号(data owner)切换时立即清空,旧账号的迟到响应
* 一律丢弃(electron-security-and-process-boundaries §4–5:renderer 不持有真相)。
*/
-import { useSyncExternalStore } from 'react';
+import { useCallback, useSyncExternalStore } from 'react';
import { seedBotGroupReadState } from './botReadState';
import {
@@ -145,6 +145,15 @@ export function useBotGroupList(): BotGroupListSnapshot {
return useSyncExternalStore(subscribeBotGroups, getBotGroupListSnapshot, getBotGroupListSnapshot);
}
+/** One listed group, or null; a null id reads nothing and never re-renders on list refreshes. */
+export function useBotGroupSummary(groupId: string | null): BotGroupSummary | null {
+ const read = useCallback(
+ () => (groupId ? getBotGroupListSnapshot().groups.find((group) => group.id === groupId) ?? null : null),
+ [groupId],
+ );
+ return useSyncExternalStore(subscribeBotGroups, read, read);
+}
+
const NOT_READY: BotGroupMutationResult = { ok: false, errorCode: 'HOST_NOT_READY', message: '' };
/**
diff --git a/docs/dev-rules/chat-server-local-test.md b/docs/dev-rules/chat-server-local-test.md
index be5e5b247c..0787c246ca 100644
--- a/docs/dev-rules/chat-server-local-test.md
+++ b/docs/dev-rules/chat-server-local-test.md
@@ -57,7 +57,7 @@ XDT_CDP_PORT=9239 pnpm restart:desktop:remote --region=global -- --isolated=chat
人和 Bot 使用同一成员、消息、回复、回应及邀请合同。Bot 通过稳定本地 ID 注册;服务器分发执行请求,Main 复用现有群专线、权限同步、输入队列和终态回传。成员资格不授予另一账号的电脑或工具权限。
-本地数据库只保存执行所需的群成员元数据及 Agent 上下文,群时间线始终读服务器,不镜像写入 `bot_group_messages`。WebSocket 推动刷新;测试适配器不持久化客户端游标,重连后重新读取。执行每两秒领取,租约每十五秒续期。
+本地数据库只保存执行所需的群成员元数据及 Agent 上下文,群时间线始终读服务器,不镜像写入 `bot_group_messages`。WebSocket 推动刷新:新打开的群从快照游标开始订阅,不回放整段变更日志;游标只在本进程内存里保留,断线重连从最后读取或确认的游标续订并重新读取,不持久化。打开群时,已订阅的群快照与消息、执行状态并行读取,新群先取快照游标再读其余部分;附件下载完成按群合并为一次刷新。执行每两秒领取,租约每十五秒续期。
终态回传遇到网络或临时服务错误时,当前进程保留同一份结果,每十五秒使用相同操作 ID 补交,不重新运行 Agent。收到成功收据或明确的过期/撤权等拒绝后结束;账号切换或退出会清理该账号的待发送结果。这是运行期重试,不是跨应用重启的持久 outbox。每次续租使用独立操作 ID,避免服务端幂等缓存导致租约无法延长;恢复只作用于该次执行,不重启共享远控连接。