Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot-group): save the Thread follow switch on its own, in click order
zqchris525c24b2d8bf
diff --git a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsxindex e24d290492..00c4817669 100644--- a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx+++ b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx@@ -175,8 +175,11 @@ void mountPage({const data = ctx.data as unknown as GroupData;const group = groupFrom(data);let following = false;- const thread = async (input: { rootId: string; following?: boolean }) => {- if (input.following !== undefined) following = input.following;+ const followThread = async (input: { following: boolean }) => {+ following = input.following;+ return { ok: true, following };+ };+ const thread = async (input: { rootId: string }) => {const root = group.messages.find(m => m.id === input.rootId);const replies = ((root?.threadPreview as { replies?: Array<Record<string, unknown>> } | undefined)?.replies ?? []).map((reply, index) => message({id: reply.id, sequence: 100 + index, threadRootId: input.rootId, authorKind: reply.authorKind, authorBotId: reply.authorBotId,@@ -194,7 +197,7 @@ void mountPage({chatServer: {reactors: async () => ({ ok: true, reactors: [{ actorId: 'me', isSelf: true, name: 'You', formerMember: false }] }),react: forbid('maker.chatServer.react'),- ...(data.threadPanel ? { thread } : {}),+ ...(data.threadPanel ? { thread, followThread } : {}),},},deviceLink: {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 530f959ac3..c289172ded 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -2493,13 +2493,15 @@ describe('Chat Server result delivery and refresh', () => {const writes = () => fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/read` && method === 'POST');expect(await service.chatServer!.thread({ groupId: roomId, rootId })).toMatchObject({ ok: true, following: false });expect(writes()).toHaveLength(0);- expect(await service.chatServer!.thread({ groupId: roomId, rootId, following: true })).toMatchObject({ ok: true, following: true });+ expect(await service.chatServer!.followThread({ groupId: roomId, rootId, following: true })).toEqual({ ok: true, following: true });expect(writes()).toHaveLength(1);expect(writes()[0]![2]).toMatchObject({ threadRootId: rootId, readSeq: '3', following: true });await vi.advanceTimersByTimeAsync(150);const listed = await service.getGroup(roomId);if (!listed.ok) throw new Error('Expected group');expect(listed.group.threads?.find(thread => thread.rootId === rootId)?.following).toBe(true);+ // Saving the switch reads no Thread page, so a failing page read cannot turn a saved choice into an error.+ expect(fixture.handle.mock.calls.filter(([route]) => route.includes('threadRootId=')).length).toBe(1);});it('projects distinct responders independently of repeated-author summaries', async () => {diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex e7454e0928..029700e879 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -809,6 +809,7 @@ export const MAKER_INVOKE = {CHAT_SERVER_REFRESHPROFILE: 'maker:chat-server:refreshProfile',CHAT_SERVER_STATUS: 'maker:chat-server:status',CHAT_SERVER_THREAD: 'maker:chat-server:thread',+ CHAT_SERVER_FOLLOWTHREAD: 'maker:chat-server:followThread',CHAT_SERVER_REPLY: 'maker:chat-server:reply',CHAT_SERVER_SHARETOMAIN: 'maker:chat-server:shareToMain',CHAT_SERVER_REACT: 'maker:chat-server:react',diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 987a7a7082..1e42d2bc12 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1983,10 +1983,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDstatus: 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(), following: z.boolean().optional() }).parse(input);+ markRead: z.boolean().optional() }).parse(input);i.groupId = await groupRoom(i.groupId);- const followingWrite = i.following === undefined ? undefined : threadFollowing(i.groupId, i.rootId, i.following);- followingWrite?.catch(() => undefined);// 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}`);@@ -2000,12 +1998,20 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst 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 = await (followingWrite ?? (i.before ? undefined : threadFollowing(i.groupId, root.id)));+ 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 } : {}) };}),+ followThread: input => result(async () => {+ const i = z.object({ groupId: id, rootId: id, following: z.boolean() }).strict().parse(input);+ const room = await groupRoom(i.groupId);+ const following = await threadFollowing(room, i.rootId, i.following);+ // The switch only shows when the server keeps read state.+ if (following === undefined) throw new Error('CHAT_UNAVAILABLE');+ return { following };+ }),shareToMain: input => result(async () => {const i = z.object({ groupId: id, messageId: id }).strict().parse(input);const room = await groupRoom(i.groupId);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex f078453d79..49a7fe4b53 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12628,6 +12628,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const chat = botGroupChatServiceHolder?.chatServer;return chat ? chat.react(input) : { ok: false, errorCode: 'HOST_NOT_READY' };});+ ipcMain.handle(MAKER_INVOKE.CHAT_SERVER_FOLLOWTHREAD, async (event, input) => {+ assertTrustedAppRendererEvent(event);+ const chat = botGroupChatServiceHolder?.chatServer;+ return chat ? chat.followThread(input) : { ok: false, errorCode: 'HOST_NOT_READY' };+ });ipcMain.handle(MAKER_INVOKE.CHAT_SERVER_REACTORS, async (event, input) => {assertTrustedAppRendererEvent(event);const chat = botGroupChatServiceHolder?.chatServer;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex b1bd916750..508fbe8375 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6190,6 +6190,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:chat-server:status'),thread: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['thread']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['thread']> =>ipcRenderer.invoke('maker:chat-server:thread', input),+ followThread: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['followThread']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['followThread']> =>+ ipcRenderer.invoke('maker:chat-server:followThread', input),reply: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['reply']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['reply']> =>ipcRenderer.invoke('maker:chat-server:reply', input),shareToMain: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['shareToMain']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['shareToMain']> =>diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsxindex ae0dcc6d3d..9bcb360383 100644--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx@@ -140,8 +140,16 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,const readBeforeRef = useRef<number | null>(null);/** Whether the reader follows this Thread; undefined until known, or when the server keeps no read state. */const [following, setFollowing] = useState<boolean | undefined>(undefined);- /** A follow change being written: reads that started before it must not undo it on screen. */+ /**+ * Bumped when a follow change starts and again when it is saved: a read that began before the+ * save finished may carry the old value and must not undo the switch on screen.+ */const followWriteRef = useRef(0);+ /**+ * Follow changes are saved one at a time and the newest click is saved last, so the server+ * keeps the reader's final choice however fast they toggle.+ */+ const followSaveRef = useRef<{ saving: boolean; wanted: boolean | null; saved: boolean | undefined }>({ saving: false, wanted: null, saved: undefined });/*** Reads the latest page, or the page before `before`. `rereadOnly` re-reads an opened page for a@@ -163,7 +171,10 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: shown.map(message => message.id), markRead });if (!current()) return;if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }- if (!before && followWrite === followWriteRef.current) setFollowing(result.following);+ if (!before && followWrite === followWriteRef.current) {+ followSaveRef.current.saved = result.following;+ setFollowing(result.following);+ }if (readBeforeRef.current === null && result.readBefore !== undefined) {readBeforeRef.current = result.readBefore;setReadBefore(result.readBefore);@@ -216,18 +227,34 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,/** Following is the reader's own switch, off by default: replying or being named never turns it on. */const toggleFollowing = useCallback(async () => {if (following === undefined) return;- const next = !following;- const write = ++followWriteRef.current;+ const save = followSaveRef.current;+ save.wanted = !following;+ setFollowing(save.wanted);+ if (save.saving) return;+ save.saving = true;+ followWriteRef.current += 1;const owner = getDataOwnerGeneration();- setFollowing(next);+ const current = () => aliveRef.current && isDataOwnerGenerationCurrent(owner);try {- const result = await api().thread({ groupId: group.id, rootId, following: next });- if (!aliveRef.current || !isDataOwnerGenerationCurrent(owner) || write !== followWriteRef.current) return;- if (result.ok) { setFollowing(result.following); return; }- setFollowing(!next);- toast.error(t(chatErrorKey(result.errorCode)));- } catch {- if (aliveRef.current && write === followWriteRef.current) { setFollowing(!next); toast.error(t(key('requestFailed'))); }+ while (save.wanted !== null && save.wanted !== save.saved) {+ const wanted: boolean = save.wanted;+ save.wanted = null;+ let failure: string | null = null;+ try {+ const result = await api().followThread({ groupId: group.id, rootId, following: wanted });+ if (result.ok) save.saved = result.following;+ else failure = t(chatErrorKey(result.errorCode));+ } catch { failure = t(key('requestFailed')); }+ if (!current()) return;+ // A newer click is saved next; only the last outcome is shown.+ if (save.wanted !== null) continue;+ setFollowing(save.saved);+ if (failure) toast.error(failure);+ }+ } finally {+ save.saving = false;+ save.wanted = null;+ followWriteRef.current += 1;}}, [following, group.id, rootId, t]);useEffect(() => {diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex d531c53283..94c638bd19 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -768,16 +768,21 @@ export interface ChatServerApi {/*** `markRead` (latest page only): the reader is looking at the Thread, so its server read state* moves to the newest reply read here; `readBefore` is where it stood before this read.- * `following` first sets whether the reader follows the Thread (bot-group-chat.md §10); the- * result's `following` is absent when the server keeps no read state.+ * `following` (latest page only) is whether the reader follows the Thread; absent when the+ * server keeps no read state.*/- thread(input: { groupId: string; rootId: string; before?: number; sourceMessageIds?: string[]; markRead?: boolean; following?: boolean }): Promise<ChatServerResult<{+ thread(input: { groupId: string; rootId: string; before?: number; sourceMessageIds?: string[]; markRead?: boolean }): Promise<ChatServerResult<{root: BotGroupMessageView; replies: BotGroupMessageView[]; hasMore: boolean;/** Same authoritative state as the main timeline; root and replies use one projection. */executionFailures?: BotGroupExecutionFailureView[];readBefore?: number;following?: boolean;}>>;+ /**+ * Sets whether the reader follows a Thread (bot-group-chat.md §10「关注开关」) and answers what+ * the server saved. Only the reader's own choice ever follows a Thread.+ */+ followThread(input: { groupId: string; rootId: string; following: boolean }): Promise<ChatServerResult<{ following: boolean }>>;reply(input: { groupId: string; rootId: string; text: string; clientId: string; mentions: BotGroupMention }): Promise<ChatServerResult<{ messageId: string }>>;/*** Re-post a thread reply to the main chat as the current user. Repeating it for the same