Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(group-chat): preserve hidden state on remount and share sync
zqchrisd701791d3786
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 79ceef9bb0..5b55358ba5 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -179,7 +179,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet supportsDissolve = false;let supportsListRemoval = false;const personalList = createConversationListState();- const syncPersonalList = async () => { if (supportsListRemoval) await personalList.sync(api); };+ const syncPersonalList = async (force = false) => {+ if (supportsListRemoval) await (force ? personalList.sync(api) : personalList.ensureSynced(api));+ };personalList.subscribe(row => {if (!current()) return;deps.onChanged?.({ groupId: row.conversationId, change: 'list', listState: row }, scope);@@ -568,7 +570,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreconnectDelay = 500; connected = true;ws.send(JSON.stringify({ type: 'subscribe', scope: `actor:${selfId}`, after: '0' }));for (const [roomId, cursor] of rooms) ws.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: cursor }));- void syncPersonalList().then(() => { if (current() && socket === ws) { for (const roomId of rooms.keys()) changed(roomId); changed(''); } }).catch(() => ws.close());+ void syncPersonalList(true).then(() => { if (current() && socket === ws) { for (const roomId of rooms.keys()) changed(roomId); changed(''); } }).catch(() => ws.close());} else if (event.type === 'changes') {// 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.diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex fd62621cfe..16b5580d0a 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -371,5 +371,10 @@ it('merges a computer-confirmed personal removal without requiring direct serverexpect(chat.state.kind).toBe('missing');expect(h.auth.apiFetch).not.toHaveBeenCalled();expect(h.link.invoke.mock.calls.find(call => call[1] === 'maker:remote-resources:invoke')?.[2][0]).toMatchObject({ actionId: 'hide', resourceRef: { id } });+ await act(async () => root!.unmount()); root = undefined;+ h.targets = [target]; h.legacy.isOnline.mockReturnValue(true);+ h.legacy.items = [{ host: target, item: { ref: { id, kind: 'bot-group', collectionId: 'bot-groups' } } }];+ await render();+ expect(roster.items).toEqual([]);h.link.status = 'offline'; h.link.getPresenceAvailability = () => false;});diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 922c5dcfaf..42b01f99f5 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -212,7 +212,10 @@ export function createChatServerClient(request: ChatRequest, personalList = creareturn {personalList,lifecycleCapabilities: () => ({ supportsDissolve, supportsListRemoval }),- async syncListState() { await identity(); if (supportsListRemoval) await personalList.sync(request); },+ async syncListState(force = false) {+ await identity();+ if (supportsListRemoval) await (force ? personalList.sync(request) : personalList.ensureSynced(request));+ },async hide(roomId: string, operationId: string) {await identity();if (!supportsListRemoval) throw new Error('LIFECYCLE_UNAVAILABLE');diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex 537887d37f..f098f4af72 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -64,13 +64,15 @@ export function useChatServerRoster(enabled: boolean) {const api = useChatClient();const known = useRef({ owner: api.owner, ids: new Set<string>() });if (known.current.owner !== api.owner) known.current = { owner: api.owner, ids: new Set() };+ // A remounted roster must suppress already-known hidden rooms even if HTTP is offline.+ for (const id of api.client.personalList.ids()) known.current.ids.add(id);const snapshots = useRef(new Map<string, { owner: string; head: string | undefined; value: ChatSnapshot }>());const [state, setState] = useState({ owner: api.owner, rooms: [] as ReturnType<typeof chatRoomRow>[], loading: true, refreshing: false, error: null as string | null });const read = useRemoteSyncCoordinator(async run => {if (!api.enabled || !enabled) return;setState(old => ({ ...old, refreshing: run.reasons.includes('visible') }));try {- await api.client.syncListState();+ await api.client.syncListState(run.reasons.some(reason => ['focus', 'visible', 'connected'].includes(reason)));const [rooms, self] = await Promise.all([api.client.list(), api.client.me()]);const rows: ReturnType<typeof chatRoomRow>[] = [];const fresh = new Map<string, { owner: string; head: string | undefined; value: ChatSnapshot }>();@@ -174,7 +176,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {const generation = accessGeneration.current;freshRead.current = false;try {- await api.client.syncListState();+ await api.client.syncListState(run.reasons.some(reason => ['focus', 'visible', 'connected'].includes(reason)));const previous = page.current?.identity === identity ? page.current.page : null;const oldest = previous?.messages.reduce<string | undefined>((oldest, message) => !oldest || BigInt(message.seq) < BigInt(oldest) ? message.seq : oldest, undefined);const [next, self] = await Promise.all([api.client.load(groupId, oldest), api.client.me()]);@@ -213,7 +215,6 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {if ((error as { code?: string }).code !== 'RESET_REQUIRED') throw error;return '0';}) : null;- await api.client.syncListState();await request({ reason: 'connected' });const latest = page.current;if (!freshRead.current || !latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 2185ec2191..41f4784d58 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -40,6 +40,8 @@ Desktop 收到终态后还会中止本机未完成的规划,沿原 lease 链`GET /conversation-list-state` 获取状态,无需先读已无权限的群快照。启动及重连先取个人状态,只合入更新的修订;成功回包或本人 human actor scope 的 `conversation.list.changed` 才清理本地列表、选择与未读镜像,失败保留列表。手机同时订阅群和本人 human scope,代演不替换账号订阅。+同账号并发全量同步共用一次请求;普通聊天刷新复用已同步状态与事件,启动、重连及手机主动刷新重新读取。+同步失败不把缓存标记为已就绪。手机列表重新挂载时先纳入已有个人状态,直连离线也不恢复旧电脑回包。现有 `bot-group-chat` 投影可选追加 supportsDissolve、supportsListRemoval、supportsGroupLeave、dissolvedAt;远程资源动作 `dissolve` / `leave` / `hide` 分别转发相同的服务端动作。hide 的 opaque result 返回diff --git a/packages/maker-shared/src/__tests__/chatConversationList.test.ts b/packages/maker-shared/src/__tests__/chatConversationList.test.tsindex 14f3512176..60b5d5ea6d 100644--- a/packages/maker-shared/src/__tests__/chatConversationList.test.ts+++ b/packages/maker-shared/src/__tests__/chatConversationList.test.ts@@ -2,6 +2,34 @@ import { expect, it, vi } from 'vitest';import { createConversationListState } from '../chatConversationList';const id = '00000000-0000-4000-8000-000000000001';+it('shares concurrent reads and avoids full-page downloads until an explicit reconnect', async () => {+ const list = createConversationListState();+ let resolve!: (value: unknown) => void;+ const request = vi.fn().mockImplementation(() => new Promise(done => { resolve = done; }));+ const first = list.ensureSynced(request);+ const concurrent = list.sync(request);+ expect(request).toHaveBeenCalledTimes(1);+ resolve([]); await Promise.all([first, concurrent]);+ await list.ensureSynced(request);+ expect(request).toHaveBeenCalledTimes(1);+ request.mockResolvedValue([{ conversationId: id, hidden: true, revision: 1 }]);+ await list.sync(request);+ expect(request).toHaveBeenCalledTimes(2);+ expect(list.hidden(id)).toBe(true);+});++it('retries a failed reconnect before allowing an ordinary refresh to trust the cache', async () => {+ const list = createConversationListState();+ const request = vi.fn().mockResolvedValue([]);+ await list.ensureSynced(request);+ request.mockRejectedValueOnce(new Error('offline'));+ await expect(list.sync(request)).rejects.toThrow('offline');+ request.mockResolvedValue([{ conversationId: id, hidden: true, revision: 2 }]);+ await list.ensureSynced(request);+ expect(request).toHaveBeenCalledTimes(3);+ expect(list.hidden(id)).toBe(true);+});+it('keeps newer account events over a delayed startup/reconnect page', async () => {const list = createConversationListState();let resolve!: (value: unknown) => void;diff --git a/packages/maker-shared/src/chatConversationList.ts b/packages/maker-shared/src/chatConversationList.tsindex 685900e1ee..241519a8ab 100644--- a/packages/maker-shared/src/chatConversationList.ts+++ b/packages/maker-shared/src/chatConversationList.ts@@ -13,20 +13,21 @@ function state(value: unknown): ConversationListState {export function createConversationListState() {const rows = new Map<string, ConversationListState>();const listeners = new Set<(row: ConversationListState) => void>();+ let synced = false;+ let syncing: Promise<void> | null = null;const merge = (value: unknown) => {const row = state(value);if ((rows.get(row.conversationId)?.revision ?? 0) >= row.revision) return;rows.set(row.conversationId, row);for (const notify of listeners) notify(row);};- return {- merge,- hidden: (id: string) => rows.get(id)?.hidden === true,- get: (id: string) => rows.get(id),- revision: (id: string) => rows.get(id)?.revision ?? 0,- ids: () => [...rows.keys()],- subscribe(notify: (row: ConversationListState) => void) { listeners.add(notify); return () => { listeners.delete(notify); }; },- async sync(request: Request) {+ // Reconnects force a full authoritative read; ordinary refreshes share the initial+ // read and then rely on account events, rather than downloading every page again.+ const sync = (request: Request, force = true): Promise<void> => {+ if (syncing) return syncing;+ if (!force && synced) return Promise.resolve();+ synced = false;+ syncing = (async () => {let after: string | undefined;do {const page = await request<unknown[]>(`/conversation-list-state?limit=100${after ? `&after=${after}` : ''}`);@@ -36,7 +37,19 @@ export function createConversationListState() {if (next && after && next <= after) throw new Error('INVALID_CHAT_PAGE');after = next;} while (after);- },+ synced = true;+ })().finally(() => { syncing = null; });+ return syncing;+ };+ return {+ merge,+ hidden: (id: string) => rows.get(id)?.hidden === true,+ get: (id: string) => rows.get(id),+ revision: (id: string) => rows.get(id)?.revision ?? 0,+ ids: () => [...rows.keys()],+ subscribe(notify: (row: ConversationListState) => void) { listeners.add(notify); return () => { listeners.delete(notify); }; },+ sync,+ ensureSynced: (request: Request) => sync(request, false),async setHidden(request: Request, id: string, hidden: boolean, operationId: string) {if (!uuid.test(id)) throw new Error('INVALID_CHAT_ID');// Read first, including after leaving. A lost acknowledgement is safe to retry.