Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): reauthorize group sends and isolate realtime failures

zqchris5ae673e5d6b1
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
index 9811912f96..7b9708ff36 100644
--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -42,6 +42,7 @@ beforeEach(() => {
options.assertCurrent();
if (path.startsWith('/v1/conversations?')) return [room];
if (path === '/v1/me') return { actor: { id: self, kind: 'human' } };
+ if (path.endsWith('/members')) return [{ id: self, kind: 'human', state: 'joined', name: 'Me', ownerActorId: self, ownerName: '', role: 'member', avatar: null }];
if (path.endsWith('/snapshot')) return { room, members: [{ id: self, kind: 'human', state: 'joined', name: 'Me', ownerActorId: self, ownerName: '', role: 'member', avatar: null }], messages: [], cursor: '1' };
if (path.includes('/messages?')) return [{ id: self, seq: '9007199254740993', authorId: self, author: { kind: 'human', name: 'Me' }, content: [{ type: 'text', text: 'Fixture message' }], createdAt: '2026-10-09', deleted: false, threadRootId: null }];
if (path.endsWith('/messages')) return { id: self };
@@ -66,6 +67,7 @@ it('never includes the current human actor in explicit or everyone server mentio
const original = h.auth.apiFetch.getMockImplementation()!;
h.auth.apiFetch.mockImplementation(async (path, options) => {
const value = await original(path, options);
+ if (path.endsWith('/members')) return [...value, { ...value[0], id: other, name: 'Other', ownerActorId: other }];
return path.endsWith('/snapshot') ? { ...value, members: [...value.members, { ...value.members[0], id: other, name: 'Other', ownerActorId: other }] } : value;
});
showChat = true; await render();
@@ -74,6 +76,80 @@ it('never includes the current human actor in explicit or everyone server mentio
expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: `fixture-${all}`, content: [{ type: 'text', text: 'hello' }], mentions: [other] } }));
}
});
+it('resolves everyone using authorized members at send time instead of the displayed snapshot', async () => {
+ const joined = '00000000-0000-4000-8000-000000000003';
+ const invited = '00000000-0000-4000-8000-000000000004';
+ const left = '00000000-0000-4000-8000-000000000005';
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/members')) {
+ const [member] = await original(path, options);
+ return [member, { ...member, id: joined, kind: 'bot', name: 'New teammate' },
+ { ...member, id: invited, state: 'invited' }, { ...member, id: left, state: 'left' }];
+ }
+ return original(path, options);
+ });
+ showChat = true; await render();
+ await act(async () => { await chat.act('send', { text: 'everyone', clientId: 'fixture-new-member', mentions: { all: true, botIds: [] } }); });
+ expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: 'fixture-new-member', content: [{ type: 'text', text: 'everyone' }], mentions: [joined] } }));
+});
+
+it('keeps REST sending available after the group WebSocket disconnects', async () => {
+ vi.useFakeTimers();
+ const sockets: any[] = [];
+ vi.stubGlobal('WebSocket', class {
+ readyState = 1; onclose?: Function;
+ constructor() { sockets.push(this); }
+ close() { this.onclose?.({}); }
+ });
+ showChat = true; await render();
+ expect(chat.online).toBe(true);
+ await act(async () => { sockets[0].close(); });
+ expect(chat.online).toBe(true);
+ await act(async () => { await chat.act('send', { text: 'REST works', clientId: 'fixture-ws-offline', mentions: { all: false, botIds: [] } }); });
+ expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST' }));
+ h.auth.apiFetch.mockRejectedValue(new Error('REST offline'));
+ await act(async () => { chat.reload(); });
+ expect(chat.online).toBe(false);
+});
+
+it.each([403, 404])('clears revoked access immediately when a send returns %s', async (status) => {
+ showChat = true; await render();
+ expect(chat.state.kind).toBe('ready');
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/messages')) throw Object.assign(new Error('NOT_MEMBER'), { status });
+ return original(path, options);
+ });
+ await act(async () => {
+ await expect(chat.act('send', { text: 'fixture', clientId: 'fixture-revoked', mentions: { all: false, botIds: [] } })).rejects.toMatchObject({ status });
+ });
+ expect(chat.state.kind).toBe('missing');
+ expect(chat.online).toBe(false);
+ await expect(chat.act('send', { text: 'again', clientId: 'fixture-no-page', mentions: { all: false, botIds: [] } })).rejects.toThrow('CHAT_READ_FAILED');
+});
+it('clears access on everyone member-read rejection and ignores an older authorized history reply', async () => {
+ showChat = true; await render();
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ let finish!: () => void;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/members')) throw Object.assign(new Error('NOT_MEMBER'), { status: 403 });
+ const value = await original(path, options);
+ if (path.endsWith('/snapshot')) await new Promise<void>(resolve => { finish = resolve; });
+ return value;
+ });
+ await act(async () => { chat.reload(); });
+ await act(async () => {
+ await expect(chat.act('send', { text: 'everyone', clientId: 'fixture-member-rejected', mentions: { all: true, botIds: [] } })).rejects.toMatchObject({ status: 403 });
+ });
+ expect(chat.state.kind).toBe('missing');
+ expect(h.auth.apiFetch.mock.calls.some(([, options]) => options.method === 'POST')).toBe(false);
+ await act(async () => { finish(); });
+ expect(chat.state.kind).toBe('missing');
+ h.auth.apiFetch.mockImplementation(original);
+ await act(async () => { chat.reload(); });
+ expect(chat.state.kind).toBe('ready');
+});
it('deduplicates server copies from multiple computers while retaining a local legacy group', async () => {
h.legacy.items = ['mac', 'pc'].map(deviceId => ({ key: deviceId, host: { deviceId, deviceName: deviceId }, item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id }, revision: '1', display: { title: 'Discussion' }, links: [] } }));
h.legacy.isOnline.mockReturnValue(true);
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
index c2bd06cbff..959b164dbf 100644
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -137,6 +137,11 @@ export function createChatServerClient(request: ChatRequest) {
async snapshot(roomId: string): Promise<ChatSnapshot> {
return request(`/conversations/${chatId(roomId)}/snapshot`);
},
+ async members(roomId: string): Promise<ChatMember[]> {
+ const members = await request<ChatMember[]>(`/conversations/${chatId(roomId)}/members`);
+ if (!Array.isArray(members)) throw new Error('INVALID_CHAT_MEMBERS');
+ return members;
+ },
async load(roomId: string, oldest?: string): Promise<ChatPage> {
const room = chatId(roomId);
const snapshot = await request<ChatSnapshot>(`/conversations/${room}/snapshot`);
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
index 9f7db65a3b..4fa2785365 100644
--- a/apps/mobile/src/chat/useChatServer.ts
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -142,24 +142,30 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
const active = useRef(identity); active.current = identity;
const [state, setState] = useState<{ identity: string; value: BotGroupChatState; online: boolean; loadingOlder: boolean }>({ identity, value: { kind: 'loading' }, online: true, loadingOlder: false });
const page = useRef<{ identity: string; page: ChatPage; self: string } | null>(null);
+ const accessGeneration = useRef(0);
const freshRead = useRef(false);
const olderPending = useRef(false);
const valid = () => api.current() && active.current === identity;
+ const loseAccess = () => {
+ accessGeneration.current++; freshRead.current = false; page.current = null;
+ setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false });
+ };
const request = useRemoteSyncCoordinator(async run => {
if (!enabled || !api.enabled) return;
+ const generation = accessGeneration.current;
freshRead.current = false;
try {
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()]);
- if (run.isStale() || !valid()) return;
+ if (run.isStale() || !valid() || generation !== accessGeneration.current) return;
// Replace the reauthorized window; no stale history survives changed access.
freshRead.current = true;
page.current = { identity, page: next, self };
setState({ identity, value: { kind: 'ready', group: chatGroupView(next, self) }, online: true, loadingOlder: false });
} catch (error) {
- if (run.isStale() || !valid()) return;
- if (chatAccessLost(error)) { page.current = null; setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false }); }
+ if (run.isStale() || !valid() || generation !== accessGeneration.current) return;
+ if (chatAccessLost(error)) loseAccess();
else setState(old => ({ identity, value: old.identity === identity && old.value.kind === 'ready' ? old.value : { kind: 'error', message: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_READ_FAILED' }, online: false, loadingOlder: false }));
}
}, identity);
@@ -186,7 +192,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
const latest = page.current;
if (!freshRead.current || !latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');
return { scope: `conversation:${groupId}`, cursor: latest.page.snapshot.cursor };
- }, changed: reload, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; if (api.current() && active.current === identity) setState(old => ({ ...old, online: false })); } });
+ }, changed: reload, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; } });
}).catch(() => {}); // Read presents endpoint errors.
};
start();
@@ -204,7 +210,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
page.current = { ...previous, page: next };
setState({ identity, value: { kind: 'ready', group: chatGroupView(next, previous.self) }, online: true, loadingOlder: false });
} catch (error) {
- if (valid() && chatAccessLost(error)) { page.current = null; setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false }); }
+ if (valid() && page.current === previous && chatAccessLost(error)) loseAccess();
throw error;
} finally { olderPending.current = false; if (valid()) setState(old => ({ ...old, loadingOlder: false })); }
};
@@ -212,13 +218,24 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
if (action !== 'send' || !input || input.division || (Array.isArray(input.attachments) && input.attachments.length)) throw new Error('UNSUPPORTED_CHAT_ACTION');
const latest = page.current;
if (!latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');
- const mentions = input.mentions as { all: boolean; botIds: string[] };
- const recipients = mentions.all
- ? latest.page.snapshot.members.filter(member => member.state === 'joined').map(member => member.id)
- : mentions.botIds;
- await api.client.send(groupId, { clientId: String(input.clientId), text: String(input.text),
- mentions: { all: false, botIds: recipients.filter(id => id !== latest.self) } });
- reload(); return { effects: [] };
+ try {
+ const mentions = input.mentions as { all: boolean; botIds: string[] };
+ const recipients = mentions.all
+ ? (await api.client.members(groupId)).filter(member => member.state === 'joined').map(member => member.id)
+ : mentions.botIds;
+ if (!valid() || page.current?.identity !== identity) throw new Error('OWNER_CHANGED');
+ await api.client.send(groupId, { clientId: String(input.clientId), text: String(input.text),
+ mentions: { all: false, botIds: recipients.filter(id => id !== latest.self) } });
+ if (valid()) reload();
+ return { effects: [] };
+ } catch (error) {
+ if (valid()) {
+ freshRead.current = false;
+ if (chatAccessLost(error)) loseAccess();
+ else setState(old => ({ ...old, online: false }));
+ }
+ throw error;
+ }
};
const media = async (mediaId: string): Promise<BotGroupAttachment> => {
const attachment = await api.client.media(groupId, mediaId);
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index b8020eef58..5e5a1cf0db 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -265,8 +265,10 @@
- 列表在前台订阅账号成员事件,每 30 秒核对群 head,仅重读变化群的快照;打开群后订阅该群事件,
用字符串游标 ack,断线/前后台切换重连并重读授权快照。离开页面或切换账号即停止订阅。
群详情分页读取主时间线;通知使已展示的历史窗口重新核权读取,撤权清空页面,恢复成员权限后重新建立订阅。
+ 实时订阅断线仅触发重连与定时核对,HTTP 可用时仍可发言;HTTP 读写失败进入读取恢复,发送被撤权拒绝时立即清空群页。
列表从当前账号投影其他成员消息的未读时间;复用本地已读镜像与可见尾部确认,读取列表不向服务器提交已读。
- 直连页支持已有群的列表、成员查看、主时间线与旧历史、文字及 @ 发言;
+ `@所有人` 在发送前读取当前授权成员,只展开已加入且非本人的 actor,避免使用旧页面快照漏掉新成员。
私有附件点击时重新授权,图片走已有看图器,其他文件打开短期签名 HTTPS URL,不转交账号 token。
列表失败与空列表分开呈现,服务器故障使用服务器文案,不误报电脑离线。
- 直连页暂不提供新建群、修改群设置/成员、上传附件、分工编排/审批、Thread 与表情操作;