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): close lifecycle races in leases and mobile state
zqchris7c981981daca
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex bb8cea44fc..f44a941a6b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -1088,6 +1088,34 @@ describe('Chat Server result delivery and refresh', () => {expect(deliveries()).toHaveLength(2);});+ it('rechecks a dissolved execution as soon as an already accepted heartbeat returns', async () => {+ let finish!: (value: unknown) => void;+ let hold = false, dissolved = false, laterChecks = 0;+ fixture.handle.mockImplementation((route, _method, body) => {+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupLifecycleVersion: 1 } } };+ if (route.endsWith('/snapshot')) return { body: { room: { ...room(roomId), kind: 'group' }, cursor: '1', messages: [], members: [+ { id: selfId, ownerActorId: selfId, state: 'joined', role: 'owner' },+ ] } };+ if (route.endsWith('/dissolve')) { dissolved = true; return { body: { revision: 2, dissolvedAt: '2026-10-15T00:00:00Z', dissolvedBy: selfId } }; }+ if (body?.action === 'heartbeat') {+ if (hold && !dissolved) return new Promise(resolve => { finish = resolve; });+ if (dissolved) { laterChecks++; return { status: 409, body: { error: { code: 'GROUP_DISSOLVED' } } }; }+ }+ return response(route);+ });+ await start();+ hold = true;+ await vi.advanceTimersByTimeAsync(13000);+ expect(finish).toBeTypeOf('function');+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'dissolve', expectedRevision: 1 } })).toMatchObject({ ok: true });+ expect(deps.abortLane).not.toHaveBeenCalled();+ finish({ body: {} });+ await vi.advanceTimersByTimeAsync(0);+ expect(laterChecks).toBe(1);+ expect(deps.abortLane).toHaveBeenCalledExactlyOnceWith('lane');+ expect(deps.dispatch).toHaveBeenCalledOnce();+ });+it('does not let an earlier heartbeat failure delete a pending terminal result', async () => {let rejectHeartbeat: (error: Error) => void = () => {};let heartbeatCount = 0, completes = 0;diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 5441ace8b6..0d4a56eb3c 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1249,6 +1249,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}).finally(() => { polling = false; });}, 2000);const checking = new Set<Running>();+ const recheck = new Set<Running>();async function checkLease(run: Running) {if (run.settlement) {// Auth/rate-limit waits need lease renewal; ordinary lost-response retries@@ -1268,7 +1269,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}await deliverSettlement(run); return;}- if (checking.has(run) || running.get(run.execution.bot_id) !== run) return;+ if (running.get(run.execution.bot_id) !== run) return;+ if (checking.has(run)) { recheck.add(run); return; }checking.add(run);try {// Ordinary group replies can wait for approval too, just like plan steps.@@ -1289,7 +1291,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (run.sessionId) await deps.abortLane(run.sessionId).catch(() => undefined);changed(run.execution.conversation_id);}- } finally { checking.delete(run); }+ } finally {+ checking.delete(run);+ // A dissolve or change can arrive while an older heartbeat is in flight.+ // Check the new authority once that response settles, without waiting 15s.+ if (recheck.delete(run) && running.get(run.execution.bot_id) === run) void checkLease(run);+ }}const heartbeat = setInterval(() => { for (const run of running.values()) void checkLease(run); }, 15000);timer.unref(); heartbeat.unref();diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsxindex 43d5c1d9a7..511909d5d2 100644--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx@@ -10,6 +10,7 @@ const h = vi.hoisted(() => ({alert: vi.fn(),confirm: vi.fn(),leave: vi.fn(),+ closeSettings: null as null | (() => void),row: null as any,inputs: {} as Record<string, any>,teammates: { rows: [] as any[], loading: false, failed: false },@@ -117,7 +118,8 @@ vi.mock('@/session/HomeHeaderGlassButton', () => ({HomeHeaderGlassButton: ({ onPress, testID, disabled, children }: any) => el('button', { 'data-testid': testID, disabled, onClick: onPress }, children),}));vi.mock('@/session/CompanionSheet', () => ({- CompanionSheet: ({ visible, children, onClosed, testID }: any) => {+ CompanionSheet: ({ visible, children, onClose, onClosed, testID }: any) => {+ if (testID === 'botGroup.settings') h.closeSettings = onClose;const was = useRef(visible);useEffect(() => { if (was.current && !visible) onClosed?.(); was.current = visible; }, [visible]);return visible ? el('div', { 'data-testid': testID }, children) : null;@@ -852,6 +854,49 @@ describe('group settings', () => {expect(h.leave).toHaveBeenCalledOnce();});+ it.each([true, false])('leaves once for authoritative hide without a local action (direct=%s)', async direct => {+ h.chat.server = direct;+ await render(group({ serverBacked: true }));+ h.chat.listHidden = true;+ await render(null, 'missing');+ expect(h.leave).toHaveBeenCalledOnce();+ expect(h.chat.act).not.toHaveBeenCalled();+ await render(null, 'missing');+ expect(h.leave).toHaveBeenCalledOnce();+ });++ it('does not navigate twice when the authoritative event precedes the local hide receipt', async () => {+ let finish!: () => void;+ h.chat.act.mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve({ effects: [] }); }));+ await openSettings(group({ serverBacked: true, supportsListRemoval: true }));+ await click('botGroup.settings.hide');+ h.chat.listHidden = true;+ await render(null, 'missing');+ expect(h.leave).toHaveBeenCalledOnce();+ await act(async () => { finish(); });+ expect(h.leave).toHaveBeenCalledOnce();+ });++ it('resets lifecycle busy on reopen and keeps an old reply out of a new request', async () => {+ const data = group({ serverBacked: true, supportsDissolve: true, revision: 1,+ members: [{ botId: 'mimi', actorId: 'mimi', name: 'Mimi', avatar: '', avatarColor: '', status: 'active', isOwned: true, role: 'owner' }] });+ let finishOld!: () => void, finishNew!: () => void;+ h.chat.act.mockImplementationOnce(() => new Promise(resolve => { finishOld = () => resolve({ effects: [] }); }))+ .mockImplementationOnce(() => new Promise(resolve => { finishNew = () => resolve({ effects: [] }); }));+ await openSettings(data);+ await click('botGroup.settings.dissolve');+ expect(byId('botGroup.settings.dissolve')?.disabled).toBe(true);+ await act(async () => h.closeSettings!());+ await click('botGroup.settingsButton');+ expect(byId('botGroup.settings.dissolve')?.disabled).toBe(false);+ await click('botGroup.settings.dissolve');+ expect(h.chat.act).toHaveBeenCalledTimes(2);+ await act(async () => { finishOld(); });+ expect(byId('botGroup.settings.dissolve')?.disabled).toBe(true);+ await act(async () => { finishNew(); });+ expect(byId('botGroup.settings.dissolve')?.disabled).toBe(false);+ });+it('does not navigate from an old hide acknowledgement after leaving the screen', async () => {let finish!: () => void;h.chat.act.mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve({ effects: [] }); }));diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex 984b76bc99..a7748b4328 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -311,6 +311,37 @@ it('rebuilds realtime after membership returns while the same group page remainsexpect(chat.state.kind).toBe('ready');});+it('exposes an actor-scope personal hide to the current screen and clears it after an account switch', async () => {+ vi.useFakeTimers();+ h.auth.accountGeneration = 105;+ const sockets: any[] = [];+ vi.stubGlobal('WebSocket', class {+ readyState = 1; onopen?: Function; onmessage?: Function; onclose?: Function; onerror?: Function;+ send = vi.fn();+ constructor() { sockets.push(this); }+ close() { this.onclose?.({}); }+ });+ const allowed = h.auth.apiFetch.getMockImplementation()!;+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ if (path === '/v1/me') return { actor: { id: self, kind: 'human' }, capabilities: { conversationListStateVersion: 1 } };+ if (path.startsWith('/v1/conversation-list-state?')) return [];+ if (path.startsWith('/v1/changes?')) return { head: '10' };+ return allowed(path, options);+ });+ showChat = true; await render();+ await act(async () => { sockets[0].onmessage({ data: JSON.stringify({ type: 'ready', actorId: self }) }); });+ expect(chat.listHidden).toBe(false);+ await act(async () => { sockets[0].onmessage({ data: JSON.stringify({ type: 'changes', scope: `actor:${self}`, cursor: '11', changes: [+ { type: 'conversation.list.changed', data: { conversationId: id, hidden: true, revision: 1 } },+ ] }) }); });+ expect(chat.state.kind).toBe('missing');+ expect(chat.listHidden).toBe(true);+ expect(h.auth.apiFetch.mock.calls.some(([path, options]) => path.endsWith('/list-state') && options.method === 'POST')).toBe(false);+ h.auth.accountGeneration++;+ await render();+ expect(chat.listHidden).toBe(false);+});+it('supports direct leave, then personal removal independently without a readable snapshot', async () => {h.auth.accountGeneration = 101;const allowed = h.auth.apiFetch.getMockImplementation()!;diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex d1b8408c28..3ab1009e31 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -320,6 +320,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {if (api.current() && api.client.personalList.hidden(groupId)) await forgetRemoteResource(api.userId, groupId);}, [api, groupId]);return { state: state.identity === identity ? state.value : { kind: 'loading' } as BotGroupChatState,+ listHidden: api.current() && api.client.personalList.hidden(groupId),online: state.identity === identity && state.online, reload, act,acceptListState, isListHidden: () => api.client.personalList.hidden(groupId), loadOlder, loadingOlder: state.loadingOlder, media, markRead };}diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex 824bab1337..a003096e95 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -198,12 +198,21 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceIdconst currentHideScope = `${groupId}:${deviceId}:${accountGeneration}`;hideScope.current = currentHideScope;useEffect(() => () => { hideScope.current = ''; }, []);+ const leftScope = useRef('');+ const leaveCurrentChat = useCallback((captured: string) => {+ if (hideScope.current !== captured || leftScope.current === captured) return;+ leftScope.current = captured;+ leave();+ }, [leave]);+ useEffect(() => {+ if (chat.listHidden) leaveCurrentChat(currentHideScope);+ }, [chat.listHidden, currentHideScope, leaveCurrentChat]);const actFromSettings: typeof chat.act = async (action, input) => {const captured = currentHideScope;const receipt = await chat.act(action, input);// The list listener may already have unmounted settings; the screen still// owns this route and can complete navigation after the acknowledgement.- if ((action === 'hide' || action === 'leave') && hideScope.current === captured) leave();+ if (action === 'hide' || action === 'leave') leaveCurrentChat(captured);return receipt;};const removeFromList = async () => {@@ -214,7 +223,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceIdif (!await showConfirm({ title: t('groupChat.lifecycle.hide'), message: t('groupChat.lifecycle.hideNote'),cancelLabel: t('devices.common.cancel'), confirmLabel: t('groupChat.lifecycle.hide'), destructive: true }) || hideScope.current !== captured) return;await chat.act('hide');- if (hideScope.current === captured) leave();+ leaveCurrentChat(captured);} catch (error) { if (hideScope.current === captured) Alert.alert(botGroupActionErrorText(t, error, 'groupChat.lifecycle.failed')); }finally { hidePending.current = false; }};diff --git a/apps/mobile/src/session/BotGroupSettingsSheet.tsx b/apps/mobile/src/session/BotGroupSettingsSheet.tsxindex 5fca7132f7..07445f2ac9 100644--- a/apps/mobile/src/session/BotGroupSettingsSheet.tsx+++ b/apps/mobile/src/session/BotGroupSettingsSheet.tsx@@ -1,5 +1,5 @@/** 群设置由管理电脑保存;项目文件夹仅可查看。 */-import { useEffect, useRef, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';import { ChevronDown, Ellipsis, Folder, Plus } from 'lucide-react-native';import { useTranslation } from 'react-i18next';@@ -75,15 +75,17 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acconst lifecycleProps = lifecycle ?? { visible, group, host, online, act, onDeleted };const lifecycleGroup = lifecycleProps.group;const membership = chatGroupMembership(lifecycleGroup);- const scope = `${accountGeneration}:${lifecycleGroup.id}:${lifecycleProps.host.deviceId}:${visible}`;- const active = useRef(scope); active.current = scope;- useEffect(() => () => { active.current = ''; }, []);+ const scope = useMemo(() => ({ accountGeneration, groupId: lifecycleGroup.id, deviceId: lifecycleProps.host.deviceId, visible }),+ [accountGeneration, lifecycleGroup.id, lifecycleProps.host.deviceId, visible]);+ const active = useRef<typeof scope | null>(scope); active.current = scope;+ useEffect(() => () => { active.current = null; }, []);const { colors } = useTheme();const styles = useThemedStyles(makeStyles);const [name, setName] = useState(group.name);const [busy, setBusy] = useState<Busy>(null);const busyRef = useRef<Busy>(null);const [errors, setErrors] = useState<Partial<Record<Exclude<Busy, null>, string>>>({});+ useEffect(() => { busyRef.current = null; setBusy(null); setErrors({}); }, [scope]);const [picking, setPicking] = useState(false);const [memberQuery, setMemberQuery] = useState('');const serverManaged = group.serverBacked === true && group.supportsSettingsManagement === true;@@ -114,18 +116,19 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acconst run = async (section: Exclude<Busy, null>, actionId: BotGroupRemoteActionId, input: Record<string, unknown>, fallbackKey: string) => {const leaving = actionId === 'delete' && leavesGroup;if (readOnly || (permissionLocked && !leaving) || !online || busyRef.current) return false;+ const captured = scope;busyRef.current = section;setBusy(section);setErrors((current) => ({ ...current, [section]: undefined }));try {await act(actionId, serverManaged && !leaving ? { expectedRevision: group.revision, ...input } : input);+ // Legacy deletion reports success to the owning screen even if this sheet unmounted.return true;} catch (error) {- setErrors((current) => ({ ...current, [section]: botGroupActionErrorText(t, error, fallbackKey) }));+ if (active.current === captured) setErrors((current) => ({ ...current, [section]: botGroupActionErrorText(t, error, fallbackKey) }));return false;} finally {- busyRef.current = null;- setBusy(null);+ if (active.current === captured) { busyRef.current = null; setBusy(null); }}};@@ -169,7 +172,7 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac// The owning screen completes hide/leave navigation even if this sheet unmounted.} catch (error) {if (active.current === captured) setErrors(current => ({ ...current, lifecycle: botGroupActionErrorText(t, error, 'groupChat.lifecycle.failed') }));- } finally { busyRef.current = null; if (active.current === captured) setBusy(null); }+ } finally { if (active.current === captured) { busyRef.current = null; setBusy(null); } }};const error = (section: Exclude<Busy, null>) => errors[section]diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.tsindex 5269622ca7..0dc5b79b64 100644--- a/apps/mobile/src/session/useBotGroupChat.ts+++ b/apps/mobile/src/session/useBotGroupChat.ts@@ -115,5 +115,5 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string)void presenceVersion;// Unknown presence still allows actions; the host answers or the link reports offline.const online = status === 'online' && !!host.deviceId && getPresenceAvailability(host.deviceId) !== false;- return !host.deviceId ? { ...server, server: true } : { state: value, reload, act, online, server: false, loadOlder: undefined, loadingOlder: false, media: undefined, markRead: undefined };+ return !host.deviceId ? { ...server, server: true } : { state: value, reload, act, online, server: false, listHidden: server.listHidden, loadOlder: undefined, loadingOlder: false, media: undefined, markRead: undefined };}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex fcc9c4f2c2..a0f3333882 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -45,6 +45,9 @@ Desktop 收到终态后还会中止本机未完成的规划,沿原 lease 链actor scope 遇到 RESET_REQUIRED 时,在在途读取完成后重新读取个人状态,再按服务端 head 续订;Desktop 与 Mobile 均受当前账号、socket 身份保护。个人移除成功时由仍挂载的聊天页完成返回列表,设置面板因列表更新先卸载不会吞掉成功导航,离开页面后的旧回包也不能改变新页面。+手机收到跨设备本人 hidden 事件也由当前聊天页返回列表,本机回执与事件共用一次导航;+设置面板每次关闭/身份切换都会清空 busy,旧打开周期的请求不能覆盖新周期状态。+Desktop 解散或变更期间遇到在途 heartbeat,会合并排队一次后续租约检查,避免漏掉权威终止。现有 `bot-group-chat` 投影可选追加 supportsDissolve、supportsListRemoval、supportsGroupLeave、dissolvedAt;远程资源动作 `dissolve` / `leave` / `hide` 分别转发相同的服务端动作。hide 的 opaque result 返回