Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(chat): 复用群聊话题缓存并同步历史回复 (#7396)
boboc1dfa7fee38c
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.tsindex ab406d8ac6..ed00169cd2 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts@@ -122,6 +122,104 @@ describe('Chat Server group open latency (simulated 100ms per request)', () => {});afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); });+ // Unit: the production topic entry used to bypass persisted history on every open.+ // Restart, old-page edits and a permission reset must all share the room projection.+ it('reopens topics without downloading members, roots or covered pages and updates old replies', async () => {+ const disk = new Map<string, ChatHistoryState>();+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ const open = () => withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ const old = { ...message, id: '50000000-0000-4000-8000-000000000002', seq: '2', revision: 1, threadRootId: message.id };+ const latest = { ...old, id: '50000000-0000-4000-8000-000000000003', seq: '3' };+ let revoked = false;+ fixture.handle.mockImplementation(route => route.startsWith('/changes?')+ ? revoked ? { status: 403, body: { error: { code: 'NOT_MEMBER' } } }+ : { body: { cursor: '58', changes: [{ type: 'message.updated', data: { message: { ...old, revision: 2,+ content: [{ type: 'text', text: 'old reply edited' }] } } }], hasMore: false } }+ : route.endsWith(`/messages/${message.id}`) ? { body: message }+ : route.endsWith('/members') ? { body: [] }+ : revoked && route.includes('/execution-failures?') ? { status: 403, body: { error: { code: 'NOT_MEMBER' } } }+ : route.includes('/messages?') ? { body: route.includes('before=3') ? [old] : [latest] } : response(route));+ service.dispose(); service = open();+ const input = { groupId: rooms[0], rootId: message.id };+ const initial = await timed(() => service.chatServer!.thread(input));+ expect(initial.value).toMatchObject({ ok: true, root: { id: message.id }, replies: [{ id: latest.id }] });+ await timed(() => service.chatServer!.thread({ ...input, before: 3 }));+ const warm = await timed(() => service.chatServer!.thread(input));+ expect(warm.routes.filter(route => /\/(snapshot|members|messages)(\?|\/|$)/.test(route))).toEqual([]);+ expect(warm.routes).toHaveLength(1); // Only execution failures; no changed read position in this scenario.+ service.dispose(); service = open();+ const restored = await timed(() => service.chatServer!.thread({ ...input, sourceMessageIds: [old.id] }));+ expect(restored.value).toMatchObject({ ok: true, historyRevision: expect.any(String),+ messageUpdates: [{ id: old.id, content: 'old reply edited' }] });+ expect(restored.routes.filter(route => /\/(snapshot|members|messages)(\?|\/|$)/.test(route))).toEqual([]);+ revoked = true;+ expect((await timed(() => service.chatServer!.thread(input))).value).toMatchObject({ ok: false, errorCode: 'NOT_MEMBER' });+ expect(disk.size).toBe(0);+ });++ // Unit, PR #7396: a missing root and a lost membership both use HTTP 404.+ // Only the latter may discard another topic's durable history and page coverage.+ it.each(['MESSAGE_NOT_FOUND', 'CONVERSATION_NOT_FOUND'])('scopes a topic HTTP 404 to its server error code (%s)', async code => {+ const disk = new Map<string, ChatHistoryState>();+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ const missingRoot = '50000000-0000-4000-8000-000000000099';+ const reply = { ...message, id: '50000000-0000-4000-8000-000000000002', seq: '2', threadRootId: message.id };+ fixture.handle.mockImplementation(route => route.startsWith('/changes?')+ ? { body: { cursor: '57', changes: [], hasMore: false } }+ : route.endsWith(`/messages/${missingRoot}`) ? { status: 404, body: { error: { code } } }+ : route.endsWith(`/messages/${message.id}`) ? { body: message }+ : route.includes('/messages?') ? { body: route.includes(missingRoot) ? [] : [reply] } : response(route));+ service.dispose(); service = withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ const input = { groupId: rooms[0], rootId: message.id };+ const initial = await timed(() => service.chatServer!.thread(input));+ expect(initial.value).toMatchObject({ ok: true, replies: [{ id: reply.id }] });+ expect((await timed(() => service.chatServer!.thread({ ...input, rootId: missingRoot }))).value)+ .toMatchObject({ ok: false, errorCode: code });+ if (code === 'CONVERSATION_NOT_FOUND') {+ expect(disk.size).toBe(0);+ } else {+ expect(disk.size).toBe(1);+ const resumed = await timed(() => service.chatServer!.thread(input));+ expect(resumed.value).toMatchObject({ ok: true, replies: [{ id: reply.id }],+ historyRevision: initial.value.ok && initial.value.historyRevision });+ // The failed topic's parallel page may still finish; the surviving topic+ // must not download its root/page or re-bootstrap the room.+ expect(resumed.routes.filter(route => !route.includes(missingRoot) && /\/(snapshot|members|messages)(\?|\/|$)/.test(route))).toEqual([]);+ }+ });++ // Unit: the topic composes independently awaited root, page and failure reads;+ // a membership reset between them must retry, just like the group entry point.+ it('retries a topic if membership resets while execution failures are loading', async () => {+ const disk = new Map<string, ChatHistoryState>();+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ fixture.page = [{ ...message, id: '50000000-0000-4000-8000-000000000002', seq: '2', threadRootId: message.id }];+ fixture.handle.mockImplementation(route => route.startsWith('/changes?')+ ? { body: { cursor: '57', changes: [], hasMore: false } }+ : route.endsWith(`/messages/${message.id}`) ? { body: message } : response(route));+ service.dispose(); service = withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ const input = { groupId: rooms[0], rootId: message.id };+ const before = await timed(() => service.chatServer!.thread(input)); await connected();+ fixture.timing = route => ({ serve: 100, deliver: route.includes('/execution-failures?') ? 500 : 100 });+ const pending = service.chatServer!.thread(input);+ await vi.advanceTimersByTimeAsync(120);+ fixture.page = [];+ fixture.sockets[0].emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${rooms[0]}`, cursor: '58',+ changes: [{ type: 'membership.changed' }] }));+ const after = await timed(() => pending);+ expect(after.value).toMatchObject({ ok: true, replies: [] });+ expect(after.value.ok && after.value.historyRevision).not.toBe(before.value.ok && before.value.historyRevision);+ });+// Unit: a membership reset while execution metadata is loading must not relabel old messages as the new history.it('retries a composed group view if its cached history resets during another HTTP read', async () => {const disk = new Map<string, ChatHistoryState>();diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex a7885050fb..11670af03f 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1434,8 +1434,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD* A server without read state, or a failed write, leaves unread as it was. Returns the position* before this read, or undefined without read state.*/- async function markThreadRead(roomId: string, root: Message, newestFirst: Message[]): Promise<number | undefined> {- const reads = threadReads(await recentSnapshot(roomId));+ async function markThreadRead(roomId: string, root: Message, newestFirst: Message[], snapshot?: Snapshot): Promise<number | undefined> {+ const reads = threadReads(snapshot ?? await recentSnapshot(roomId));if (!reads) return undefined;const before = reads.get(root.id) ?? 0n;const newest = newestFirst.reduce((max, m) => BigInt(m.seq) > max ? BigInt(m.seq) : max, BigInt(root.seq));@@ -1463,6 +1463,62 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDoperationId: randomUUID(), threadRootId: rootId, readSeq: read?.read_seq ?? '0', following: next });return written.following;}+ async function threadDetail(input: Parameters<ChatServerApi['thread']>[0], attempt = 0): Promise<{+ root: BotGroupMessageView; replies: BotGroupMessageView[]; hasMore: boolean; historyRevision?: string;+ messageUpdates?: BotGroupMessageView[]; executionFailures: BotGroupExecutionFailureView[]; readBefore?: number; following?: boolean;+ }> {+ const i = z.object({ groupId: id, rootId: id, before: z.number().int().positive().optional(), sourceMessageIds: z.array(id).optional(),+ markRead: z.boolean().optional() }).parse(input);+ i.groupId = await resolveGroup(i.groupId);+ await ensureRegistered();+ const cache = history();+ try {+ const s = cache ? await cache.snapshot<Snapshot>(i.groupId) : await groupSnapshot(i.groupId);+ if (!isGroupRoom(s.room)) throw new Error('NOT_A_GROUP');+ const revision = cache ? (s as Snapshot & { cacheGeneration: string }).cacheGeneration : undefined;+ subscribe(i.groupId, s.cursor);+ const query = new URLSearchParams({ threadRootId: i.rootId, limit: '50' });+ if (i.before) query.set('before', String(i.before));+ // Root and replies use the same room cursor and durable, account-scoped message map.+ const membersRead = cache ? Promise.resolve(s.members) : api<Member[]>(`/conversations/${i.groupId}/members`);+ const rootRead = cache?.message<Message>(i.groupId, i.rootId) ?? api<Message>(`/conversations/${i.groupId}/messages/${i.rootId}`);+ const pageRead = cache?.page<Message>(i.groupId, query) ?? api<Message[]>(`/conversations/${i.groupId}/messages?${query}`);+ for (const read of [rootRead, pageRead]) read.catch(() => undefined);+ const members = await membersRead;+ const root = await rootRead;+ const page = await pageRead;+ const executionFailures = await failureSnapshot(i.groupId, members, [...(i.sourceMessageIds ?? []), root.id, ...page.map(m => m.id)]);+ const projection = await cache?.projection<Message>(i.groupId, i.sourceMessageIds ?? []);+ const rootViews = await messageViews(i.groupId, [root], members);+ await decorateThreads(i.groupId, rootViews, [root], page, members, false);+ const replies = await messageViews(i.groupId, [...page].reverse(), members);+ const messageUpdates = projection ? await messageViews(i.groupId, projection.messages.filter(m => m.threadRootId === i.rootId), members) : undefined;+ const retry = () => {+ if (attempt >= 2) throw new Error('CHAT_HISTORY_CHANGED');+ return threadDetail(input, attempt + 1);+ };+ if (revision && cache?.generation(i.groupId) !== revision) return retry();+ // Reuse the already validated personal reads; writing read state still goes to the server.+ const following = i.before ? undefined : cache+ ? s.reads ? s.reads.find(read => read.thread_key === root.id)?.following === true : undefined+ : await threadFollowing(i.groupId, root.id);+ const readBefore = i.markRead && !i.before ? await markThreadRead(i.groupId, root, page, cache ? s : undefined) : undefined;+ if (revision && cache?.generation(i.groupId) !== revision) return retry();+ return { root: rootViews[0]!, executionFailures, replies, hasMore: page.length === 50,+ ...(revision ? { historyRevision: revision, messageUpdates } : {}),+ ...(readBefore !== undefined ? { readBefore } : {}), ...(following !== undefined ? { following } : {}) };+ } catch (error) {+ if (error instanceof ChatResponseError && [403, 404].includes(error.status) && error.message !== 'MESSAGE_NOT_FOUND') {+ // Execution metadata is read outside the history transaction, but its denial+ // also revokes the warm projection. A missing root only invalidates that topic,+ // not this room's membership or other cached messages. Preserve the original error.+ await cache?.clear(i.groupId).catch(() => undefined);+ displayHistory.forget(i.groupId);+ threads.reset();+ }+ throw error;+ }+ }async function detail(roomId: string, options?: unknown, summaryOnly = false, attempt = 0): Promise<BotGroupDetail> {id.parse(roomId);const attentionGeneration = generation(roomId);@@ -2633,29 +2689,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDchanged(target); return {};}),status: async () => ({ enabled: true, connected: current() && connected }),- thread: input => result(async () => {- const i = z.object({ groupId: id, rootId: id, before: z.number().int().positive().optional(), sourceMessageIds: z.array(id).optional(),- markRead: z.boolean().optional() }).parse(input);- i.groupId = await groupRoom(i.groupId);- // One round trip; awaited in the former order so the same failure is reported first.- const membersRead = api<Member[]>(`/conversations/${i.groupId}/members`);- const rootRead = api<Message>(`/conversations/${i.groupId}/messages/${i.rootId}`);- const pageRead = api<Message[]>(`/conversations/${i.groupId}/messages?threadRootId=${i.rootId}&limit=50${i.before ? `&before=${i.before}` : ''}`);- for (const read of [rootRead, pageRead]) read.catch(() => undefined);- const members = await membersRead;- const root = await rootRead;- const page = await pageRead;- const executionFailures = await failureSnapshot(i.groupId, members, [...(i.sourceMessageIds ?? []), root.id, ...page.map(m => m.id)]);- // A share in the main chat can itself be a thread root.- const rootViews = await messageViews(i.groupId, [root], members);- await decorateThreads(i.groupId, rootViews, [root], page, members, false);- // An older page is history being scrolled: it says nothing about the Thread's switches.- const following = i.before ? undefined : await threadFollowing(i.groupId, root.id);- const readBefore = i.markRead && !i.before ? await markThreadRead(i.groupId, root, page) : undefined;- return { root: rootViews[0], executionFailures,- replies: await messageViews(i.groupId, page.reverse(), members), hasMore: page.length === 50,- ...(readBefore !== undefined ? { readBefore } : {}), ...(following !== undefined ? { following } : {}) };- }),+ thread: input => result(() => threadDetail(input)),followThread: input => result(async () => {const i = z.object({ groupId: id, rootId: id, following: z.boolean() }).strict().parse(input);const room = await groupRoom(i.groupId);diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsxindex 40ea170540..8bd8a9d65d 100644--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx@@ -43,6 +43,20 @@ const api = () => window.electronAPI.maker.chatServer;const STICK_TO_BOTTOM_PX = 48;/** Earlier pages read while looking for a reply opened from the main chat. */const FOCUS_PAGE_LIMIT = 5;+const threadAccessLost = (code: string) => ['NOT_FOUND', 'PERMISSION_DENIED', 'FORBIDDEN', 'NOT_MEMBER', 'NOT_A_MEMBER',+ 'CONVERSATION_NOT_FOUND', 'MESSAGE_NOT_FOUND', 'ACTOR_NOT_FOUND', 'ACCOUNT_UNAVAILABLE'].includes(code);++interface ThreadWindow {+ revision: string; root: BotGroupMessageView; replies: BotGroupMessageView[];+ executionFailures: BotGroupExecutionFailureView[]; hasMore: boolean;+}+// Disposable warm views only. Durable messages and coverage remain in main's room projection.+const threadWindows = new Map<string, ThreadWindow>();+let windowsOwner = getDataOwnerGeneration();+function windows() {+ if (!isDataOwnerGenerationCurrent(windowsOwner)) { threadWindows.clear(); windowsOwner = getDataOwnerGeneration(); }+ return threadWindows;+}/** Shares of this thread's replies that the main chat has loaded. */export type BotGroupSharedReplies = ReadonlyMap<string, { messageId: string; bySelf: boolean }>;@@ -177,10 +191,21 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,shareSelectionStore.exitIfNotSession(shareScope);return () => { if (shareSelectionStore.isActive(shareScope)) shareSelectionStore.exit(); };}, [shareScope]);- const [root, setRoot] = useState<BotGroupMessageView | null>(null);- const [executionFailures, setExecutionFailures] = useState<BotGroupExecutionFailureView[]>([]);- const [replies, setReplies] = useState<BotGroupMessageView[]>([]);- const [hasMore, setHasMore] = useState(false);+ const windowKey = `${group.id}:${rootId}`;+ const windowOwner = useRef(getDataOwnerGeneration());+ const [initial] = useState(() => {+ const cached = windows().get(windowKey);+ if (cached && cached.revision === group.historyRevision) return cached;+ windows().delete(windowKey);+ return undefined;+ });+ const revisionRef = useRef(initial?.revision);+ const historyEpochRef = useRef(0);+ const latestReadRef = useRef(0);+ const [root, setRoot] = useState<BotGroupMessageView | null>(initial?.root ?? null);+ const [executionFailures, setExecutionFailures] = useState<BotGroupExecutionFailureView[]>(initial?.executionFailures ?? []);+ const [replies, setReplies] = useState<BotGroupMessageView[]>(initial?.replies ?? []);+ const [hasMore, setHasMore] = useState(initial?.hasMore ?? false);const [error, setError] = useState('');// Off by default: a reply stays in the thread unless the user asks for both.const [alsoSend, setAlsoSend] = useState(false);@@ -197,6 +222,8 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,const aliveRef = useRef(true);const inFlightRef = useRef(false);const queuedRef = useRef(false);+ const queuedSourcesRef = useRef(new Set<string>());+ const changedRepliesRef = useRef(new Set<string>());/** Lowest sequence of the last latest-page read; replies below it live only on opened older pages. */const latestFloorRef = useRef(Number.POSITIVE_INFINITY);@@ -206,6 +233,27 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,/** Whether the reader follows this Thread; undefined until known, or when the server keeps no read state. */const [following, setFollowing] = useState<boolean | undefined>(undefined);const followKey = `${group.id}:${rootId}`;+ useEffect(() => {+ if (!isDataOwnerGenerationCurrent(windowOwner.current)) return;+ if (!root || !revisionRef.current) { windows().delete(windowKey); return; }+ const cache = windows();+ cache.delete(windowKey);+ cache.set(windowKey, { revision: revisionRef.current, root, replies: replies.slice(-500), executionFailures,+ hasMore: hasMore || replies.length > 500 });+ if (cache.size > 20) cache.delete(cache.keys().next().value!);+ }, [windowKey, root, replies, executionFailures, hasMore]);++ const clearHistory = useCallback((wholeRoom = true) => {+ historyEpochRef.current++;+ queuedSourcesRef.current.clear();+ changedRepliesRef.current.clear();+ for (const key of windows().keys())+ if (key === windowKey || (wholeRoom && key.startsWith(`${group.id}:`))) windows().delete(key);+ repliesRef.current = [];+ setReplies([]); setRoot(null); setExecutionFailures([]); setHasMore(false);+ readBeforeRef.current = null; setReadBefore(null); setFollowing(undefined);+ latestFloorRef.current = Number.POSITIVE_INFINITY;+ }, [group.id, windowKey]);/*** Reads the latest page, or the page before `before`. `rereadOnly` re-reads an opened page for a@@ -213,8 +261,16 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,*/const read = useCallback(async (before?: number, rereadOnly = false, onAccepted?: () => void) => {const owner = getDataOwnerGeneration();- const current = () => aliveRef.current && isDataOwnerGenerationCurrent(owner);+ const epoch = historyEpochRef.current;+ const latestRead = latestReadRef.current;+ const current = () => aliveRef.current && isDataOwnerGenerationCurrent(owner) && epoch === historyEpochRef.current;const shown = repliesRef.current;+ // A page can land before React commits its rows. Keep those sources explicit+ // so the coalesced refresh also validates their execution state.+ const extraSources = before ? [] : [...queuedSourcesRef.current];+ if (!before) queuedSourcesRef.current.clear();+ const changedReplies = before ? [] : [...changedRepliesRef.current];+ if (!before) changedRepliesRef.current.clear();// An older page belongs below the reply it was read from; a latest page that started over// meanwhile dropped that reply, and the page would sit under the new one with the gap still in it.const anchorId = before ? shown[0]?.id : undefined;@@ -225,9 +281,22 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,const markRead = !before && stickToBottomRef.current;const save = followSave(followKey);const followWrites = save.writes;- const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: shown.map(message => message.id), markRead });+ const result = await api().thread({ groupId: group.id, rootId, before,+ sourceMessageIds: [...new Set([...shown.map(message => message.id), ...extraSources])], markRead });if (!current()) return;- if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }+ if (!result.ok) {+ if (threadAccessLost(result.errorCode)) clearHistory(result.errorCode !== 'MESSAGE_NOT_FOUND');+ setError(t(chatErrorKey(result.errorCode))); return;+ }+ const reset = !!result.historyRevision && !!revisionRef.current && result.historyRevision !== revisionRef.current;+ if (reset) {+ clearHistory();+ revisionRef.current = result.historyRevision;+ if (before) { refreshRef.current(); return; }+ } else if (result.historyRevision) revisionRef.current = result.historyRevision;+ // A later latest-page refresh owns updates to already visible rows and metadata.+ const stalePage = !!before && latestRead !== latestReadRef.current;+ if (!before) latestReadRef.current++;// A read that overlaps a follow save may carry the old choice; the save's own answer wins.if (!before && followWrites === save.writes && !save.saving) {save.saved = result.following;@@ -237,27 +306,62 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,readBeforeRef.current = result.readBefore;setReadBefore(result.readBefore);}- setRoot(previous => (previous && JSON.stringify(previous) === JSON.stringify(result.root) ? previous : result.root));+ if (!stalePage) setRoot(previous => (previous && JSON.stringify(previous) === JSON.stringify(result.root) ? previous : result.root));setError('');- setExecutionFailures(result.executionFailures ?? []);const floor = result.replies.reduce((min, reply) => Math.min(min, reply.sequence), Number.POSITIVE_INFINITY);// A latest page that neither overlaps nor directly adjoins the shown replies may leave a gap:// start over from it, as on first load, so 「查看更早」 reads on from right below it.const gap = !before && result.hasMore && result.replies.length > 0 && shown.length > 0&& floor > shown.reduce((max, reply) => Math.max(max, reply.sequence), Number.NEGATIVE_INFINITY) + 1;- if (!anchored(repliesRef.current)) return;+ if (!reset && !anchored(repliesRef.current)) return;+ const addedSources = new Set(stalePage+ ? result.replies.filter(reply => !repliesRef.current.some(shown => shown.id === reply.id)).map(reply => reply.id) : []);+ if (!stalePage) setExecutionFailures(result.executionFailures ?? []);+ else if (addedSources.size) setExecutionFailures(previous => [+ ...previous.filter(failure => !addedSources.has(failure.sourceMessageId)),+ ...(result.executionFailures ?? []).filter(failure => addedSources.has(failure.sourceMessageId)),+ ]);onAccepted?.();- setReplies(previous => (anchored(previous)- ? stabilizeById(previous, gap ? result.replies : mergeBotGroupMessages(previous, result.replies))- : previous));+ setReplies(previous => {+ if (reset || gap) return result.replies;+ if (!anchored(previous)) return previous;+ const incoming = stalePage ? result.replies.filter(reply => !previous.some(old => old.id === reply.id))+ : mergeBotGroupMessages(result.replies, result.messageUpdates ?? []);+ return stabilizeById(previous, mergeBotGroupMessages(previous, incoming));+ });if (!before) latestFloorRef.current = floor;- if (!rereadOnly && (before || shown.length === 0 || gap)) setHasMore(result.hasMore);+ if (!rereadOnly && (before || shown.length === 0 || gap || reset)) setHasMore(result.hasMore);+ if (addedSources.size) {+ for (const id of addedSources) queuedSourcesRef.current.add(id);+ refreshRef.current();+ }+ // Recheck local reactions after the latest page settles, inside the same+ // coalesced refresh. Otherwise that refresh can invalidate this recheck.+ // A durable projection already returns the changed reply in messageUpdates.+ if (!before && !gap && !reset) {+ const refreshedIds = new Set([...result.replies, ...(result.messageUpdates ?? [])].map(reply => reply.id));+ for (const reply of shown) {+ if (!changedReplies.includes(reply.id) || refreshedIds.has(reply.id)) continue;+ if (!current()) return;+ await readRef.current(reply.sequence + 1, true);+ }+ }// A refresh reads only the latest page: replies on opened older pages keep the attachments they// arrived with, so re-read the pages whose attachments were not here yet.- if (!before && !gap && result.replies.length > 0) {+ if (!before && !gap && !reset && result.replies.length > 0) {const refreshed = await refreshPendingBotGroupAttachments(shown, floor, async page => {const earlier = await api().thread({ groupId: group.id, rootId, before: page });- return earlier.ok && current() ? earlier.replies : null;+ if (!current()) return null;+ if (!earlier.ok) {+ if (threadAccessLost(earlier.errorCode)) {+ clearHistory(earlier.errorCode !== 'MESSAGE_NOT_FOUND'); setError(t(chatErrorKey(earlier.errorCode)));+ }+ return null;+ }+ if (earlier.historyRevision && earlier.historyRevision !== revisionRef.current) {+ clearHistory(); revisionRef.current = earlier.historyRevision; refreshRef.current(); return null;+ }+ return earlier.replies;});if (refreshed && current()) {const fresh = new Map(refreshed.map(message => [message.sequence, message]));@@ -265,7 +369,7 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,}}} catch { if (current()) setError(t(key('requestFailed'))); }- }, [group.id, rootId, t]);+ }, [group.id, rootId, t, clearHistory]);const readRef = useRef(read);readRef.current = read;/** One refresh in flight; pushes meanwhile collapse into one follow-up read. */@@ -282,6 +386,14 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,}, [read]);const refreshRef = useRef(refresh);refreshRef.current = refresh;+ const groupRevisionRef = useRef(group.historyRevision);+ useEffect(() => {+ const previous = groupRevisionRef.current;+ groupRevisionRef.current = group.historyRevision;+ if (group.historyRevision && previous !== group.historyRevision && revisionRef.current !== group.historyRevision) {+ clearHistory(); revisionRef.current = group.historyRevision; refreshRef.current();+ }+ }, [group.historyRevision, clearHistory]);/** Following is the reader's own switch, off by default: replying or being named never turns it on. */const toggleFollowing = useCallback(() => {if (following === undefined) return;@@ -340,9 +452,9 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,// The root and the latest page come with every refresh; a reply opened through 「加载更早」 sits// below that page, so the page holding it is re-read for its new reaction state.const onChanged = useCallback((messageId: string) => {- refreshRef.current();const reply = repliesRef.current.find(candidate => candidate.id === messageId);- if (reply && reply.sequence < latestFloorRef.current) void readRef.current(reply.sequence + 1, true);+ if (reply && reply.sequence < latestFloorRef.current) changedRepliesRef.current.add(messageId);+ refreshRef.current();}, []);const onSendStart = useCallback((message: BotGroupOutgoingMessage) => {stickToBottomRef.current = true;diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 79cd74811d..2484f30d1a 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -3396,6 +3396,7 @@ describe('Telegram / Slack-grade timeline', () => {});describe('thread previews and posting to the main chat', () => {+ afterEach(() => { mocks.ownerGeneration = { dataOwnerId: 'account-a', generation: 1 }; });const t = (name: string) => `bots.groupChat.server.thread.${name}`;const preview = (id: string, authorName: string, text: string, extra: Record<string, unknown> = {}) => ({id, authorKind: 'bot' as const, authorBotId: 'xiaoman', authorName, text, attachments: [], createdAt: 1_700_000_000_000, ...extra });@@ -3407,6 +3408,133 @@ describe('thread previews and posting to the main chat', () => {}beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });+ // Unit: opening a downloaded topic must show it before IPC completes; a permission+ // failure must erase that preview. Existing tests never reopened with a pending read.+ it('shows a reopened topic immediately and clears its cached replies when access is revoked', async () => {+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, historyRevision: 'topic-warm' }) });+ const value = { ok: true, historyRevision: 'topic-warm', root: msg({ id: 'u1', content: 'Root' }),+ replies: [msg({ id: 'r1', content: 'Cached topic reply' })], hasMore: false };+ mocks.thread.mockResolvedValue(value);+ const user = userEvent.setup(); renderView();+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ await within(screen.getByRole('complementary')).findByText('Cached topic reply');+ await user.keyboard('{Escape}');+ let finish!: (result: unknown) => void;+ mocks.thread.mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ expect(within(screen.getByRole('complementary')).getByText('Cached topic reply')).toBeTruthy();+ await act(async () => finish({ ok: false, errorCode: 'NOT_MEMBER' }));+ expect(screen.queryByText('Cached topic reply')).toBeNull();+ await user.keyboard('{Escape}');+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ expect(screen.queryByText('Cached topic reply')).toBeNull();+ });++ it('repairs loaded topic history and rejects an old page after a room generation reset', async () => {+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true }) });+ const root = msg({ id: 'u1', content: 'Root' });+ const latest = msg({ id: 'r100', sequence: 100, content: 'Latest reply' });+ const old = msg({ id: 'r50', sequence: 50, content: 'Old reply' });+ const value = { ok: true, historyRevision: 'topic-before', root, replies: [latest], hasMore: true };+ mocks.thread.mockResolvedValueOnce(value).mockResolvedValueOnce({ ...value, replies: [old] });+ const user = userEvent.setup(); renderView();+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ const panel = screen.getByRole('complementary');+ await within(panel).findByText('Latest reply');+ await user.click(within(panel).getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await within(panel).findByText('Old reply');+ mocks.thread.mockResolvedValue({ ...value, messageUpdates: [{ ...old, content: 'Edited old reply' }] });+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await within(panel).findByText('Edited old reply');+ let finish!: (result: unknown) => void;+ mocks.thread.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }))+ .mockResolvedValue({ ...value, historyRevision: 'topic-after', replies: [{ ...latest, content: 'New history reply' }], hasMore: false });+ await user.click(within(panel).getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await within(panel).findByText('New history reply');+ await act(async () => finish({ ...value, replies: [msg({ id: 'r1', sequence: 1, content: 'Revoked reply' })] }));+ expect(within(panel).queryByText('Edited old reply')).toBeNull();+ expect(within(panel).queryByText('Revoked reply')).toBeNull();+ expect(within(panel).queryByText('Latest reply')).toBeNull();+ });++ // Unit, PR #7396: topic pagination was tested for history resets, but not failure+ // snapshots overtaken by a latest-page refresh. Newly added replies still need+ // their own notices, without restoring a cleared notice on an already shown source.+ it('keeps failures for newly loaded topic replies when a newer refresh overtakes pagination', async () => {+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true }) });+ const root = msg({ id: 'u1', content: 'Root' });+ const latest = msg({ id: 'r100', sequence: 100, content: 'Latest reply' });+ const older = msg({ id: 'r50', sequence: 50, content: 'Earlier reply' });+ const failure = (source: string, name: string) => ({ executionId: `failure-${source}`, epoch: 1,+ sourceMessageId: source, botId: name, botName: name, code: 'AUTH_REQUIRED' as const, planId: null });+ const rootFailure = failure(root.id, 'Root bot');+ const latestFailure = failure(latest.id, 'Latest bot');+ const olderFailure = failure(older.id, 'Earlier bot');+ const page = { ok: true, historyRevision: 'topic-failures', root, replies: [latest], hasMore: true };+ let finishOlder!: (value: unknown) => void;+ let finishRecheck!: (value: unknown) => void;+ mocks.thread.mockResolvedValueOnce({ ...page, executionFailures: [rootFailure] })+ .mockImplementationOnce(() => new Promise(resolve => { finishOlder = resolve; }))+ .mockResolvedValueOnce({ ...page, executionFailures: [latestFailure] })+ .mockImplementation(() => new Promise(resolve => { finishRecheck = resolve; }));+ const user = userEvent.setup(); renderView();+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ const panel = screen.getByRole('complementary');+ await within(panel).findByText('Latest reply');+ await user.click(within(panel).getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await within(panel).findByText('bots.groupChat.notice.runtimeFailure.AUTH_REQUIRED:Latest bot');+ await act(async () => finishOlder({ ...page, replies: [older], executionFailures: [olderFailure, rootFailure] }));+ expect(within(panel).getByText('Earlier reply')).toBeTruthy();+ expect(within(panel).getByText('bots.groupChat.notice.runtimeFailure.AUTH_REQUIRED:Earlier bot')).toBeTruthy();+ expect(within(panel).getByText('bots.groupChat.notice.runtimeFailure.AUTH_REQUIRED:Latest bot')).toBeTruthy();+ expect(within(panel).queryByText('bots.groupChat.notice.runtimeFailure.AUTH_REQUIRED:Root bot')).toBeNull();+ expect(mocks.thread.mock.calls.at(-1)?.[0].sourceMessageIds).toContain(older.id);+ // The extra reconciliation is scoped to newly visible sources and can clear their old notice.+ await act(async () => finishRecheck({ ...page, executionFailures: [latestFailure] }));+ expect(within(panel).queryByText('bots.groupChat.notice.runtimeFailure.AUTH_REQUIRED:Earlier bot')).toBeNull();+ expect(within(panel).getByText('Earlier reply')).toBeTruthy();+ });++ // Unit: a reset discovered by pagination must clear even the latest page while+ // its replacement is in flight, instead of displaying a mixed history window.+ it('clears the topic window when an older page first discovers a history reset', async () => {+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true }) });+ const value = { ok: true, historyRevision: 'before-pagination', root: msg({ id: 'u1', content: 'Old root' }),+ replies: [msg({ id: 'r100', sequence: 100, content: 'Old visible reply' })], hasMore: true };+ let finish!: (result: unknown) => void;+ mocks.thread.mockResolvedValueOnce(value).mockResolvedValueOnce({ ...value, historyRevision: 'after-pagination', replies: [] })+ .mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ const user = userEvent.setup(); renderView();+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ const panel = screen.getByRole('complementary');+ await within(panel).findByText('Old visible reply');+ await user.click(within(panel).getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await waitFor(() => expect(finish).toBeTypeOf('function'));+ expect(within(panel).queryByText('Old root')).toBeNull();+ expect(within(panel).queryByText('Old visible reply')).toBeNull();+ await act(async () => finish({ ...value, historyRevision: 'after-pagination', root: msg({ content: 'New root' }),+ replies: [], hasMore: false }));+ expect(within(panel).getByText('New root')).toBeTruthy();+ });++ // Unit: two owners may open the same room/root; display caching must not cross login boundaries.+ it('never restores another account’s warm topic window', async () => {+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, historyRevision: 'same-room' }) });+ mocks.thread.mockResolvedValue({ ok: true, historyRevision: 'same-room', root: msg({ id: 'u1' }),+ replies: [msg({ id: 'r1', content: 'Account A reply' })], hasMore: false });+ const user = userEvent.setup(); const view = renderView();+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ await within(screen.getByRole('complementary')).findByText('Account A reply');+ view.unmount();+ mocks.ownerGeneration = { dataOwnerId: 'account-b', generation: 2 };+ mocks.thread.mockImplementation(() => new Promise(() => {}));+ renderView();+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);+ expect(within(screen.getByRole('complementary')).queryByText('Account A reply')).toBeNull();+ });+it('describes the newest replies on the thread entry under the root and opens the thread from it', async () => {mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: '去哪玩', replyCount: 3, threadPreview: { replies: [diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsxindex 9934799444..eb2a562b8a 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx@@ -476,14 +476,17 @@ describe('chat interaction controls', () => {expect(mocks.react).toHaveBeenCalledWith({ groupId: 'room', messageId: 'root', emoji: '👍', present: false });});- it('re-reads the opened older Thread page after reacting to a reply on it', async () => {+ // Unit, PR #7396: a latest refresh must not invalidate the reaction recheck for+ // an opened older reply. The projection path must avoid that extra page read.+ it.each([false, true])('refreshes an opened older Thread reaction (projection: %s)', async projection => {const latest = { ...message, id: 'latest', sequence: 100, content: 'Latest reply', reactions: [] };const older = { ...message, id: 'older', sequence: 4, content: 'Earlier reply', reactions: [{ emoji: '👍', count: 1, me: false }] };+ const updated = { ...older, reactions: [{ emoji: '👍', count: 2, me: true }] };let reacted = false;mocks.thread.mockImplementation(async (input: { before?: number }) => input.before// The re-read page's hasMore is not about the oldest loaded page, so it must be ignored.- ? { ok: true, root: message, replies: [reacted ? { ...older, reactions: [{ emoji: '👍', count: 2, me: true }] } : older], hasMore: input.before === 5 }- : { ok: true, root: message, replies: [latest], hasMore: true });+ ? { ok: true, root: message, replies: [reacted ? updated : older], hasMore: input.before === 5 }+ : { ok: true, root: message, replies: [latest], hasMore: true, ...(projection && reacted ? { messageUpdates: [updated] } : {}) });mocks.react.mockImplementation(async () => { reacted = true; return { ok: true }; });render(<ChatThreadPanel group={group} rootId="root" onClose={vi.fn()} />);fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));@@ -498,11 +501,39 @@ describe('chat interaction controls', () => {// from avatar placeholders back to the authoritative count.await waitFor(() => expect(earlierChip().textContent).toContain('2'));expect(mocks.react).toHaveBeenCalledWith({ groupId: 'room', messageId: 'older', emoji: '👍', present: true });- expect(mocks.thread.mock.calls.map(([input]) => input.before)).toEqual([undefined, 100, undefined, 5]);+ expect(mocks.thread.mock.calls.map(([input]) => input.before)).toEqual(projection+ ? [undefined, 100, undefined] : [undefined, 100, undefined, 5]);expect(screen.queryByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })).toBeNull();expect(screen.getByText('Latest reply')).toBeTruthy();});+ // Unit, PR #7396: two warm topics share a room, but losing one root must not+ // erase the other. Room revocation must still remove both cached previews.+ it.each(['MESSAGE_NOT_FOUND', 'CONVERSATION_NOT_FOUND'])('scopes warm topic eviction to the error (%s)', async errorCode => {+ const room = { ...group, id: `scope-${errorCode}`, historyRevision: `scope-${errorCode}` };+ mocks.thread.mockImplementation(async ({ rootId }: { rootId: string }) => ({ ok: true,+ historyRevision: room.historyRevision, root: { ...message, id: rootId, reactions: [] },+ replies: [{ ...message, id: `${rootId}-reply`, sequence: 2, content: `${rootId} cached reply`, reactions: [] }], hasMore: false }));+ const open = (rootId: string) => render(<ChatThreadPanel group={room} rootId={rootId} onClose={vi.fn()} />);+ for (const rootId of ['other', 'root']) {+ const view = open(rootId);+ await screen.findByText(`${rootId} cached reply`);+ view.unmount();+ }+ let finish!: (value: unknown) => void;+ mocks.thread.mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ const missing = open('root');+ expect(screen.getByText('root cached reply')).toBeTruthy();+ await act(async () => finish({ ok: false, errorCode }));+ expect(screen.queryByText('root cached reply')).toBeNull();+ missing.unmount();+ const retry = open('root');+ expect(screen.queryByText('root cached reply')).toBeNull();+ retry.unmount();+ open('other');+ expect(Boolean(screen.queryByText('other cached reply'))).toBe(errorCode === 'MESSAGE_NOT_FOUND');+ });+it('re-reads Thread reactors only when this message or the whole room changed, even if the page is not reloaded', async () => {const thread = (revisions: Pick<BotGroupDetail, 'reactionRevision' | 'reactionRevisions'>) =><ChatThreadPanel group={{ ...group, ...revisions }} rootId="root" onClose={vi.fn()} />;diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex aed21db3ec..52ec68e9da 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest';import { i18n } from '@/i18n';import { botGroupNewMessageCount } from '@cindy/maker-shared/botGroupPresentation';+import { createChatHistory, type ChatHistoryState } from '@cindy/maker-shared/chat-history';import { chatGroupView, chatRoomRow, chatReadAt, createChatServerClient, type ChatMessage, type ChatPage, type ChatRoom, type ChatSnapshot } from '@/chat/chatServerClient';import { botGroupQuoteFromMessage, resolveBotGroupQuote, buildBotGroupQuoteCard, buildBotGroupTaskCard } from '@cindy/maker-shared/botGroupChat';const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;@@ -14,6 +15,25 @@ const snapshot = (): ChatSnapshot => ({ room: room(), cursor: '9007199254741099'] });describe('direct Chat Server client', () => {+ // Unit: topic loads already cached replies but still fetched the root on every open.+ it('reuses the durable root and reply page when reopening a topic', async () => {+ const request = vi.fn().mockImplementation(async (path: string) => {+ if (path === '/me') return { actor: { id: id(10), kind: 'human' } };+ if (path.endsWith('/snapshot')) return snapshot();+ if (path.endsWith(`/messages/${id(20)}`)) return message(20);+ if (path.includes('/messages?')) return [{ ...message(21), threadRootId: id(20) }];+ return [];+ });+ let saved: ChatHistoryState | undefined;+ const history = createChatHistory({ api: request, current: () => true, newGeneration: () => 'topic',+ store: { read: async () => saved, write: async (_, state) => { saved = state ?? undefined; } } });+ const client = createChatServerClient(request, undefined, async () => history);+ const first = await client.load(id(1), undefined, id(20));+ request.mockClear();+ expect((await client.load(id(1), undefined, id(20))).messages).toEqual(first.messages);+ expect(first.messages.map(m => m.id)).toEqual([id(21), id(20)]);+ expect(request.mock.calls.every(([path]) => path.includes('/execution-failures?'))).toBe(true);+ });// #6907: existing fixtures never pair a human's group name A with account ownerName B (unit tier).it('keeps owner labels scoped to each group and follows refreshed names without changing identities', () => {const human = { ...snapshot().members[0], name: 'Nickname A' };diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 103c0021b9..693964618c 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -450,7 +450,8 @@ export function createChatServerClient(request: ChatRequest, personalList = creamessages.push(...batch); before = next;}if (threadRootId) {- const root = await request<ChatMessage>(`/conversations/${room}/messages/${chatId(threadRootId)}`);+ const root = stored ? await stored.message<ChatMessage>(room, chatId(threadRootId))+ : await request<ChatMessage>(`/conversations/${room}/messages/${chatId(threadRootId)}`);messages.push(root);}const executionFailures = await failures(room, messages);diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 9eeb132f75..0dbb7639c3 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -847,8 +847,7 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;## 11. 聊天本地数据与同步优化(2026-10-26)-> 状态:首批降耗与消息投影已在优化分支实现,尚未发布。主干已补展示缓存与持久发送队列;后续 inbox、显式私聊镜像修订仍是设计目标,不能将整节视为全部上线。-> 客户端核对基线 `0e5057e36f001c0b241104cdc8741deeb15c0e10`;服务端 `9524de9deda2e6313b29a11652d2f90bf3c2788c`。+> 状态:首批降耗与消息投影已合并主干;本节描述实现边界,部署版本需单独核验。后续 inbox、显式私聊镜像修订仍是设计目标,不能将整节视为全部上线。> SGP 观测、服务器实际表结构与降耗计划维护在服务端仓现有 [Chat Server 合同](https://github.com/xindong/cindy-server/blob/main/docs/chat-server.md),不在客户端重复维护完整运维记录。实现核对入口:[chatServer.ts](../../apps/desktop/src/main/maker-ipc/chatServer.ts)、[BotGroupChatView.tsx](../../apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx)、[手机 Chat 客户端](../../apps/mobile/src/chat/chatServerClient.ts)。原有文档中的本地群分期不能替代当前代码事实。@@ -905,6 +904,12 @@ SGP 采样改变了优化顺序:当前请求主要是伙伴领取工作、身`BotGroupChatView` 在 groupId 变化时加载详情;生产 `getGroup → detail` 通过持久投影读取 snapshot 与主时间线,30 秒内可复用已校验状态,过期/重连/本地写入后补 changes。管理、发送授权准备和执行上下文继续走现有权威读取。约 60 秒 summary 缓存仍供侧栏使用。旧页通过可选 `messageUpdates` 和 `historyRevision` 接收修正与重建信号。+话题与主时间线共用服务器 `chat_message`:`conversation_id` 指向群,主消息的 `thread_root_id` 为空,话题回复指向同群根消息;编辑版本、删除标记与房间变更游标共用。话题的运行时 Session 负责伙伴上下文,不是另一套聊天消息库,也不需要独立同步游标。++Desktop `chatServer.thread → threadDetail` 复用同一房间的 snapshot/成员、根消息和 `threadRootId + before + limit` 分页覆盖;Mobile 直连的 `load` 同样从该投影读取话题根消息。根消息可能已不在最新页,因而在房间状态中增加可选 `lookups`/`staleLookups` ID 索引(最多 100 个独立读取),正文仍只存在 `messages` 中。它们随既有事务与游标一起保存,不新增表或 migration,不改变服务端 API。新消息只失效匹配主时间线/话题筛选的最新页;新回复、删除、表情变更同时失效相关根消息聚合。++Desktop 关闭后重开话题,先复用同账号运行代次、同房间 `historyRevision` 的窗口,再后台同步;窗口缓存最多 20 个话题、每个 500 条回复,持久记录仍由上述投影管理。刷新用 `messageUpdates` 修正已展开旧回复;本机表情操作优先复用该修正,未返回目标消息时在同一合并刷新内顺序补读其旧页,不能让最新页刷新把表情回包误判为过期。旧页晚于最新刷新返回时,只补入新加载回复的失败状态,保留已显示源消息的较新状态,并把新增源 ID 带入合并后的补读以核对当前状态。历史代次变化、撤权或主群重置时丢弃旧窗口及在途分页,不能混入旧正文;根消息返回 `MESSAGE_NOT_FOUND` 只清除当前话题窗口,保留群持久投影和其他话题,不能与房间级 `CONVERSATION_NOT_FOUND` 或成员撤权混同。首次打开或缺页仍请求服务器,重启/重连先补增量;执行失败状态和必要的已读写入继续请求服务器,因此缓存命中不等于完全零 HTTP。+主干已为 Desktop 增加持久 outbox 与发送 journal,为 Mobile 接入 durable outbox;保存的展示窗口与增量投影分工见 [本地接入合同](../dev-rules/chat-server-local-test.md)。本轮手机增加独立的持久消息投影,复用原列表缓存、读位和 endpoint 规则;直连服务器和经电脑 Remote Resource 仍是同一房间的两种访问路径。伙伴私聊以 canonical 主 Session 为本机界面入口;在线远端通过 device-link,离线远端读取服务器房间。主力电脑镜像用户可见消息及最终回复,按 `sourceId` 导入去重;重复 sourceId 返回既有记录,不会自动把旧记录更新为新内容。Desktop 云端转录首次可能多页回读后按消息时间排序,之后从持久覆盖范围读取并按 cursor 修正。手机私聊保留按需翻页,刷新时修正已展示旧页。显式修改的反向镜像仍待协议设计。diff --git a/packages/maker-shared/src/__tests__/chatHistory.test.ts b/packages/maker-shared/src/__tests__/chatHistory.test.tsindex 8d02da2981..22b24f2d10 100644--- a/packages/maker-shared/src/__tests__/chatHistory.test.ts+++ b/packages/maker-shared/src/__tests__/chatHistory.test.ts@@ -24,6 +24,44 @@ function fixture() {}describe('durable chat history', () => {+ // Unit: unrelated room activity must not evict another topic's downloaded head page.+ it('invalidates only the latest pages whose filter includes a new message', async () => {+ const f = fixture(); const cache = f.open();+ const topic = new URLSearchParams('threadRootId=root&limit=50');+ const main = new URLSearchParams('limit=100');+ await cache.page('room', topic); await cache.page('room', main);+ await cache.receive('room', { cursor: '11', changes: [{ type: 'message.created', data: { message: f.message('11') } }] }, '10');+ f.api.mockClear();+ await cache.page('room', topic);+ expect(f.api).not.toHaveBeenCalled();+ await cache.page('room', main);+ expect(f.api).toHaveBeenCalledWith('/conversations/room/messages?limit=100');+ });++ // Unit: old topic roots need durable single-message coverage and aggregate refreshes,+ // while edits/tombstones must share the room cursor and survive a process restart.+ it('retains topic roots across restarts and repairs them from the room change stream', async () => {+ const f = fixture(); let replies = 0;+ const original = f.api.getMockImplementation()!;+ f.api.mockImplementation(async route => route.endsWith('/messages/1')+ ? { ...f.message('1'), replyCount: replies } : original(route));+ const cache = f.open();+ await cache.message('room', '1');+ const restarted = f.open(); f.api.mockClear();+ expect(await restarted.message('room', '1')).toMatchObject({ replyCount: 0 });+ expect(f.api.mock.calls.map(([route]) => route)).toEqual(['/changes?scope=conversation:room&after=10&limit=100']);+ replies = 1;+ await restarted.receive('room', { cursor: '11', changes: [{ type: 'message.created', data: { message: { ...f.message('11'), threadRootId: '1' } } }] }, '10');+ expect(await restarted.message('room', '1')).toMatchObject({ replyCount: 1 });+ await restarted.receive('room', { cursor: '12', changes: [{ type: 'message.deleted', data: { message: f.message('1', 2, true) } }] }, '10');+ f.setBatch({ cursor: '12', changes: [] });+ expect(await f.open().message('room', '1')).toMatchObject({ deleted: true, revision: 2 });+ restarted.invalidate('room');+ f.api.mockImplementationOnce(async () => { throw new Error('NOT_MEMBER'); });+ await expect(restarted.message('room', '1')).rejects.toThrow('NOT_MEMBER');+ expect(f.disk.has('room')).toBe(false);+ });+it('retries a concurrent writer conflict without overwriting its newer historical edit', async () => {const f = fixture(); const cache = f.open(); await cache.page('room', f.page);vi.mocked(f.store.write).mockImplementationOnce(async () => {diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex d7a0115102..44a6ac5870 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -835,6 +835,9 @@ export interface ChatServerApi {*/thread(input: { groupId: string; rootId: string; before?: number; sourceMessageIds?: string[]; markRead?: boolean }): Promise<ChatServerResult<{root: BotGroupMessageView; replies: BotGroupMessageView[]; hasMore: boolean;+ /** Same room generation as the main timeline; reset before merging older pages. */+ historyRevision?: string;+ messageUpdates?: BotGroupMessageView[];/** Same authoritative state as the main timeline; root and replies use one projection. */executionFailures?: BotGroupExecutionFailureView[];readBefore?: number;diff --git a/packages/maker-shared/src/chatHistory.ts b/packages/maker-shared/src/chatHistory.tsindex 59d0f12f10..d1afeb5f91 100644--- a/packages/maker-shared/src/chatHistory.ts+++ b/packages/maker-shared/src/chatHistory.ts@@ -14,6 +14,9 @@ export interface ChatHistoryState {pages: Record<string, string[]>;/** Aggregates absent from change bodies (reactions/reply counts) need a page refresh. */stalePages?: string[];+ /** Individually fetched roots outside covered pages; bodies live in messages, as usual. */+ lookups?: string[];+ staleLookups?: string[];metadataDirty: boolean;}export interface ChatHistoryStore {@@ -71,7 +74,8 @@ export function createChatHistory(input: { api: Api; store: ChatHistoryStore; cuassertCurrent();state.stalePages = state.stalePages?.filter(key => state.pages[key]);// Keep only covered pages and the snapshot, never every change in the room's history.- const retained = new Set([...state.snapshot.messages.map(m => m.id), ...Object.values(state.pages).flat()]);+ const retained = new Set([...state.snapshot.messages.map(m => m.id), ...Object.values(state.pages).flat(), ...(state.lookups ?? [])]);+ state.staleLookups = state.staleLookups?.filter(id => state.lookups?.includes(id));for (const id of Object.keys(state.messages)) if (!retained.has(id)) delete state.messages[id];await input.store.write(room, state);assertCurrent(); states.set(room, state);@@ -105,6 +109,7 @@ export function createChatHistory(input: { api: Api; store: ChatHistoryStore; cuif (!message) return false;if (change.type === 'reaction.changed') {for (const [key, ids] of Object.entries(state.pages)) if (ids.includes(message.id)) stale(state, key);+ staleLookup(state, message.id);}if (message) {merge(state, message);@@ -114,13 +119,16 @@ export function createChatHistory(input: { api: Api; store: ChatHistoryStore; custate.snapshot.messages = state.snapshot.messages.slice(0, 100);}// A new reply also changes its root's reply count. Refresh only pages containing that root.- if (message.threadRootId && ['message.created', 'message.deleted'].includes(change.type))+ if (message.threadRootId && ['message.created', 'message.deleted'].includes(change.type)) {for (const [key, ids] of Object.entries(state.pages)) if (ids.includes(message.threadRootId)) stale(state, key);+ staleLookup(state, message.threadRootId);+ }}if (change.type === 'message.created') {for (const key of Object.keys(state.pages)) {const query = new URLSearchParams(key);if (query.has('before')) continue;+ if (query.get('all') !== 'true' && (query.get('threadRootId') ?? null) !== (message.threadRootId ?? null)) continue;const ids = state.pages[key]!;// Preserve the old window as bounded coverage: new arrivals shift pagination// boundaries, but must not make every older page download again.@@ -142,6 +150,11 @@ export function createChatHistory(input: { api: Api; store: ChatHistoryStore; custate.stalePages ??= [];if (!state.stalePages.includes(key)) state.stalePages.push(key);}+ function staleLookup(state: ChatHistoryState, id: string) {+ if (!state.lookups?.includes(id)) return;+ state.staleLookups ??= [];+ if (!state.staleLookups.includes(id)) state.staleLookups.push(id);+ }async function fetchPage<M extends ChatHistoryMessage>(room: string, state: ChatHistoryState, key: string) {const messages = await input.api<M[]>(`/conversations/${room}/messages?${key}`);if (!Array.isArray(messages)) throw new Error('CHAT_RESPONSE_INVALID');@@ -231,6 +244,18 @@ export function createChatHistory(input: { api: Api; store: ChatHistoryStore; cureturn undefined;}return {+ message: <M extends ChatHistoryMessage>(room: string, id: string): Promise<M> => serial(room, async () => {+ const state = await ensure(room);+ if (!state.lookups?.includes(id) || !state.messages[id] || state.staleLookups?.includes(id)) {+ const message = await input.api<M>(`/conversations/${room}/messages/${encodeURIComponent(id)}`);+ if (message?.id !== id || !isCursor(message.seq)) throw new Error('CHAT_RESPONSE_INVALID');+ merge(state, message);+ state.lookups = [...(state.lookups ?? []).filter(value => value !== id), id].slice(-100);+ state.staleLookups = state.staleLookups?.filter(value => value !== id);+ await save(room, state);+ }+ return state.messages[id] as M;+ }),snapshot: <S extends ChatHistorySnapshot>(room: string): Promise<S & { cacheGeneration: string }> => serial(room, async () => {const state = await ensure(room);return { ...state.snapshot, cursor: state.cursor, cacheGeneration: state.generation } as S & { cacheGeneration: string };