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): connect existing group chats directly to Chat Server

zqchrisd27960aca059
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 53045fe936..4b7cc81474 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -24,6 +24,7 @@ const h = vi.hoisted(() => ({
platform: { OS: 'ios' },
}));
+vi.mock('expo-web-browser', () => ({ openBrowserAsync: vi.fn(async () => ({})) }));
vi.mock('react-native', () => {
const box = (tag: string) => ({ children, testID, accessibilityLabel }: any) =>
el(tag, { 'data-testid': testID, 'aria-label': accessibilityLabel }, children);
@@ -769,3 +770,29 @@ describe('offline computer', () => {
expect(h.row.editable).toBe(false);
});
});
+
+
+describe('direct server group presentation', () => {
+ it('uses server failure copy, keeps other humans incoming and loads older history', async () => {
+ h.chat = { ...h.chat, server: true, online: false, loadOlder: vi.fn(async () => {}) };
+ await render(null, 'error');
+ expect(byId('botGroup.loadFailed')?.textContent).toContain('groupChat.server.loadFailed');
+ expect(node.textContent).not.toContain('devices.resources.hostOffline');
+ h.chat.online = true;
+ await render(group({ messages: [message('other', 1, { authorKind: 'user', authorName: 'Other member', isSelf: false, content: 'hello' })], plans: [], openPlan: null, hasMoreBefore: true }));
+ expect(all('botGroup.message.user')).toHaveLength(0);
+ expect(node.textContent).toContain('Other member');
+ await click('botGroup.loadOlder'); expect(h.chat.loadOlder).toHaveBeenCalledOnce();
+ await click('botGroup.settingsButton');
+ expect(byId('botGroup.settings.delete')?.disabled).toBe(true);
+ expect(byId('botGroup.settings.replyMode.mentioned')?.disabled).toBe(true);
+ });
+ it('reauthorizes a server attachment on tap and opens the existing image viewer', async () => {
+ const attachment = { id: 'media', name: 'picture.png', mimeType: 'image/png', size: 10, category: 'image' as const, url: 'https://media.example.invalid/one-use', path: null };
+ h.chat = { ...h.chat, server: true, media: vi.fn(async () => attachment) };
+ await render(group({ messages: [message('picture', 1, { authorKind: 'user', isSelf: false, attachments: [{ ...attachment, url: null, category: 'file' }] })], plans: [], openPlan: null }));
+ expect(h.chat.media).not.toHaveBeenCalled();
+ await click('attachment.file'); expect(h.chat.media).toHaveBeenCalledExactlyOnceWith('media');
+ expect(byId('lightbox')?.getAttribute('data-url')).toBe(attachment.url);
+ });
+});
diff --git a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
index 86478dd420..5270b3d7d0 100644
--- a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
@@ -7,6 +7,7 @@ import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';
// Keep the real group attachment, AttachmentStrip, MediaPreview and LegendList hooks.
// Only native surfaces and unrelated viewers are replaced for Node rendering.
const imageEvents = vi.hoisted(() => new Map<string, { onLoad: (event: unknown) => void; onError: () => void }>());
+vi.mock('expo-web-browser', () => ({ openBrowserAsync: vi.fn(async () => ({})) }));
vi.mock('react-native', async () => {
const React = await import('react');
const view = ({ children, testID, accessibilityLabel, onPress }: any) => React.createElement('div', { 'data-testid': testID, 'aria-label': accessibilityLabel, onClick: onPress }, children);
diff --git a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx
index 6bcfccc599..d9120f61fc 100644
--- a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx
+++ b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx
@@ -12,7 +12,7 @@ const h = vi.hoisted(() => ({
saveFailed: false, openTeammate: vi.fn(), setMode: vi.fn() },
roster: { createTargets: [], authoritative: true, items: [] as HostedRemoteCollectionItem[], loading: false, refreshing: false, error: null as string | null,
isOnline: vi.fn(() => true), refresh: vi.fn(), groupTargets: [] as { deviceId: string; deviceName: string }[] },
- groups: { items: [] as HostedRemoteCollectionItem[], supported: false, isOnline: () => true, refresh: vi.fn() },
+ groups: { loading: false, refreshing: false, error: null as string | null, items: [] as HostedRemoteCollectionItem[], supported: false, isOnline: () => true, refresh: vi.fn() },
groupTargetsSeen: [] as unknown[],
create: {} as any,
}));
@@ -64,6 +64,7 @@ beforeEach(() => {
h.auth.user = { id: `owner-${++serial}` }; h.auth.accountGeneration = serial;
vi.clearAllMocks(); h.focused = true; h.nav.lastTeammate = teammateIdentity(teammate); h.roster.items = [teammate];
h.nav.mode = 'teammates'; h.roster.authoritative = true;
+ h.groups.loading = false; h.groups.refreshing = false; h.groups.error = null;
h.roster.loading = false; h.roster.error = null; h.roster.isOnline.mockReturnValue(true);
});
afterEach(() => { act(() => root?.unmount()); root = undefined; });
@@ -133,7 +134,7 @@ describe('explicit sidebar entry through the home page', () => {
describe('group chats in the teammate list', () => {
const group: HostedRemoteCollectionItem = { key: 'mac:g1', host: { deviceId: 'mac', deviceName: 'Mac' },
item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' }, revision: '1', display: { title: '官网' }, links: [] } };
- afterEach(() => { h.roster.groupTargets = []; h.groups = { items: [], supported: false, isOnline: () => true, refresh: vi.fn() }; h.create = {}; });
+ afterEach(() => { h.roster.groupTargets = []; h.groups = { loading: false, refreshing: false, error: null, items: [], supported: false, isOnline: () => true, refresh: vi.fn() }; h.create = {}; });
it('leaves group chats out when no computer supports them (older desktops)', async () => {
h.nav.lastTeammate = null; await render();
@@ -156,3 +157,14 @@ describe('group chats in the teammate list', () => {
expect(h.nav.openTeammate).not.toHaveBeenCalled();
});
});
+
+
+describe('server groups in the actual teammate home', () => {
+ it('shows group loading/failure and refreshes it even without any computer target', async () => {
+ h.roster.items = []; h.groups.items = []; h.groups.supported = true; h.groups.loading = true;
+ await render(); expect(h.list.loading).toBe(true);
+ h.groups.loading = false; h.groups.error = 'CHAT_LIST_FAILED';
+ await render(); expect(h.list.error).toBe('CHAT_LIST_FAILED');
+ await act(async () => h.list.onRefresh()); expect(h.groups.refresh).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.ts
new file mode 100644
index 0000000000..5c5d0ce619
--- /dev/null
+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it, vi } from 'vitest';
+import { chatGroupView, chatRoomRow, createChatServerClient, type ChatMessage, type ChatRoom, type ChatSnapshot } from '@/chat/chatServerClient';
+const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
+const room = (n = 1, state = 'joined'): ChatRoom => ({ id: id(n), name: 'Discussion', kind: 'group', state, archived: false,
+ revision: 1, created_at: '2026-10-01', updated_at: '2026-10-09', response_mode: 'all', speaking_mode: 'auto' });
+const message = (n: number): ChatMessage => ({ id: id(n), seq: String(9007199254740992n + BigInt(n)), authorId: id(10),
+ author: { kind: 'human', name: 'Other member' }, createdAt: '2026-10-09', deleted: false, threadRootId: null,
+ content: [{ type: 'text', text: String(n) }] });
+const snapshot = (): ChatSnapshot => ({ room: room(), cursor: '9007199254741099', messages: [], members: [
+ { id: id(10), kind: 'human', name: 'Other member', state: 'joined', ownerActorId: id(10), ownerName: '', avatar: null, role: 'member' },
+] });
+
+describe('direct Chat Server client', () => {
+ it('pages joined groups without devices, local bots, registration, imports or duplicated host copies', async () => {
+ const first = Array.from({ length: 100 }, (_, n) => room(n + 1, n === 0 ? 'invited' : 'joined'));
+ const request = vi.fn().mockResolvedValueOnce(first).mockResolvedValueOnce([room(101)]);
+ const groups = await createChatServerClient(request).list();
+ expect(groups).toHaveLength(100);
+ expect(groups.some(group => group.id === id(1))).toBe(false);
+ expect(request.mock.calls.map(call => call[0])).toEqual(['/conversations?limit=100', `/conversations?limit=100&after=${id(100)}`]);
+ expect(chatRoomRow(groups[0]).host.deviceId).toBe('');
+ });
+ it('keeps empty success distinct from denied/failed list reads', async () => {
+ const request = vi.fn().mockResolvedValueOnce([]).mockRejectedValueOnce(Object.assign(new Error('FORBIDDEN'), { status: 403 }));
+ const client = createChatServerClient(request);
+ expect(await client.list()).toEqual([]);
+ await expect(client.list()).rejects.toMatchObject({ status: 403 });
+ });
+ it('opens and paginates main history, preserving exact sequence cursors and author identity', async () => {
+ const messages = Array.from({ length: 100 }, (_, n) => message(200 - n));
+ const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(messages).mockResolvedValueOnce([message(100)]);
+ const client = createChatServerClient(request);
+ const page = await client.load(id(1));
+ expect(page.before).toBe(messages.at(-1)!.seq);
+ const older = await client.older(id(1), page);
+ expect(request.mock.calls[2][0]).toBe(`/conversations/${id(1)}/messages?limit=100&before=${messages.at(-1)!.seq}`);
+ expect(older.before).toBeNull();
+ const view = chatGroupView(older, id(11));
+ expect(view.messages).toHaveLength(101);
+ expect(view.messages[0]).toMatchObject({ content: '100', authorKind: 'user', isSelf: false });
+ expect(view.members[0].actorKind).toBe('human');
+ });
+ it('rechecks media authorization on every open and accepts only HTTPS signed downloads', async () => {
+ const request = vi.fn().mockResolvedValueOnce({ name: 'report.pdf', type: 'application/pdf', size: '42', url: 'https://media.example.invalid/report?signature=test' })
+ .mockRejectedValueOnce(Object.assign(new Error('NOT_MEMBER'), { status: 403 }))
+ .mockResolvedValueOnce({ name: 'bad', type: 'text/plain', size: 1, url: 'file:///private/test' });
+ const client = createChatServerClient(request);
+ expect(await client.media(id(1), id(2))).toMatchObject({ category: 'file', path: null, size: 42 });
+ await expect(client.media(id(1), id(2))).rejects.toMatchObject({ status: 403 });
+ await expect(client.media(id(1), id(2))).rejects.toThrow('INVALID_CHAT_URL');
+ expect(request).toHaveBeenCalledTimes(3);
+ });
+ it('sends text with the original operation ID and never registers an executor', async () => {
+ const request = vi.fn().mockResolvedValue({ id: id(9) });
+ const client = createChatServerClient(request);
+ const input = { text: 'hello', clientId: 'same-operation', mentions: { all: false, botIds: [id(3)] } };
+ await client.send(id(1), input); await client.send(id(1), input);
+ expect(request).toHaveBeenNthCalledWith(1, `/conversations/${id(1)}/messages`, 'POST', {
+ operationId: 'same-operation', content: [{ type: 'text', text: 'hello' }], mentions: [id(3)],
+ });
+ expect(request.mock.calls[0]).toEqual(request.mock.calls[1]);
+ });
+ it('reauthorizes and replaces loaded older history on refresh instead of retaining deleted text', async () => {
+ const recent = Array.from({ length: 100 }, (_, n) => message(200 - n));
+ const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(recent)
+ .mockResolvedValueOnce([{ ...message(100), content: [{ type: 'text', text: 'edited' }] }]);
+ const page = await createChatServerClient(request).load(id(1), message(100).seq);
+ expect(chatGroupView(page, id(10)).messages[0].content).toBe('edited');
+ expect(request.mock.calls[2][0]).toContain(`before=${message(101).seq}`);
+ });
+
+});
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
new file mode 100644
index 0000000000..4f0c103663
--- /dev/null
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({
+ auth: { user: { id: 'owner' }, accountGeneration: 1, apiFetch: vi.fn(), getAccessToken: vi.fn(async () => 'fixture') },
+ link: { status: 'offline', connectionEpoch: 1, presenceVersion: 1, invoke: vi.fn(), openLink: vi.fn(),
+ getPresenceAvailability: () => false, onRemoteResourceChanged: () => () => {}, subscribe: vi.fn(), unsubscribe: vi.fn() },
+ legacy: { items: [] as any[], loading: false, refreshing: false, error: null as string | null, isOnline: () => false, refresh: vi.fn() },
+ targets: [] as { deviceId: string; deviceName: string }[],
+ foreground: new Set<(state: string) => void>(),
+}));
+vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: (_: string, fn: (state: string) => void) => { h.foreground.add(fn); return { remove: () => h.foreground.delete(fn) }; } } }));
+vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (fn: any) => useEffect(fn, [fn]) }; });
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));
+vi.mock('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global', getMobileEndpointForRealm: () => 'https://chat.example.invalid' }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
+vi.mock('@/device-link/revokedDevicesStore', () => ({ useRevokedDevices: () => new Set() }));
+vi.mock('@/session/useRemoteResourceList', () => ({ useRemoteResourceList: () => h.legacy }));
+vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));
+import { useBotGroupChat } from '@/session/useBotGroupChat';
+import { useBotGroupRoster } from '@/session/useBotGroupRoster';
+import { botGroupRoute } from '@/session/botGroupNavigation';
+const id = '00000000-0000-4000-8000-000000000001';
+const self = '00000000-0000-4000-8000-000000000002';
+const room = { id, name: 'Discussion', kind: 'group', state: 'joined', revision: 1, archived: false,
+ created_at: '2026-10-01', updated_at: '2026-10-09', response_mode: 'all', speaking_mode: 'auto' };
+const host = { deviceId: '', deviceName: '' };
+let root: Root | undefined;
+let roster: ReturnType<typeof useBotGroupRoster>;
+let chat: ReturnType<typeof useBotGroupChat>;
+let showChat = false;
+function Probe() { roster = useBotGroupRoster(h.targets, !showChat); chat = useBotGroupChat(host, showChat ? id : ''); return null; }
+async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+beforeEach(() => {
+ vi.clearAllMocks(); h.foreground.clear(); showChat = false; h.auth.accountGeneration = 1; h.legacy.items = []; h.targets = [];
+ vi.stubGlobal('WebSocket', class { close() {} });
+ h.auth.apiFetch.mockImplementation(async (path: string, options: any) => {
+ options.assertCurrent();
+ if (path.startsWith('/v1/conversations?')) return [room];
+ if (path === '/v1/me') return { actor: { id: self } };
+ 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 };
+ throw new Error('Unexpected request');
+ });
+});
+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.unstubAllGlobals(); });
+it('lists and opens an existing joined server group with all computers and the relay offline', async () => {
+ await render();
+ expect(roster.items).toHaveLength(1);
+ expect(botGroupRoute(roster.items[0].host, id)).toEqual({ pathname: '/companions/groups/[groupId]', params: { groupId: id } });
+ showChat = true; await render();
+ expect(chat.state).toMatchObject({ kind: 'ready', group: { id, messages: [{ content: 'Fixture message' }] } });
+ expect(chat.online).toBe(true);
+ expect(h.link.invoke).not.toHaveBeenCalled(); expect(h.link.openLink).not.toHaveBeenCalled();
+ expect(h.auth.apiFetch.mock.calls.every(([, options]) => options.baseUrl === 'https://chat.example.invalid')).toBe(true);
+ await act(async () => { await chat.act('send', { text: 'hello', clientId: 'fixture-operation', mentions: { all: false, botIds: [] } }); });
+ expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: 'fixture-operation', content: [{ type: 'text', text: 'hello' }], mentions: [] } }));
+});
+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.targets = ['mac', 'pc'].map(deviceId => ({ deviceId, deviceName: deviceId }));
+ h.legacy.items.push({ ...h.legacy.items[0], key: 'local', item: { ...h.legacy.items[0].item, ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'old-local-group' } } });
+ await render(); expect(roster.items.map(row => row.item.ref.id)).toEqual([id, 'old-local-group']);
+ expect(roster.items[0].host.deviceId).toBe('');
+ h.auth.apiFetch.mockImplementation(async path => path === '/v1/me' ? { actor: { id: self } } : []);
+ await act(async () => { await roster.refresh(); });
+ expect(roster.items.map(row => row.item.ref.id)).toEqual(['old-local-group']);
+});
+it('clears removed membership, exposes first-read failures and recovers on foreground', async () => {
+ showChat = true; h.auth.apiFetch.mockRejectedValue(new Error('offline'));
+ await render(); expect(chat.state.kind).toBe('error');
+ h.auth.apiFetch.mockImplementation(async path => path === '/v1/me' ? { actor: { id: self } } : path.endsWith('/snapshot') ? { room, members: [], messages: [], cursor: '1' } : []);
+ await act(async () => h.foreground.forEach(fn => fn('active')));
+ expect(chat.state.kind).toBe('ready');
+ h.auth.apiFetch.mockRejectedValue(Object.assign(new Error('NOT_MEMBER'), { status: 403 }));
+ await act(async () => { chat.reload(); }); expect(chat.state.kind).toBe('missing');
+});
+it('ignores an old account response after switching accounts', async () => {
+ let finish!: (value: unknown) => void;
+ h.auth.apiFetch.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ await render(); h.auth.accountGeneration++; h.auth.apiFetch.mockResolvedValue([]); await render();
+ await act(async () => finish([room])); expect(roster.items).toEqual([]);
+});
diff --git a/apps/mobile/src/__tests__/chatServerSubscription.test.ts b/apps/mobile/src/__tests__/chatServerSubscription.test.ts
new file mode 100644
index 0000000000..6a3cf63bcb
--- /dev/null
+++ b/apps/mobile/src/__tests__/chatServerSubscription.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { subscribeChatServer, type ChatSocket } from '@/chat/chatServerSubscription';
+const actorId = '00000000-0000-4000-8000-000000000001';
+type MockSocket = ChatSocket & { send: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> };
+const sockets: MockSocket[] = [];
+function socket(): MockSocket {
+ const ws = { readyState: 1, onopen: null, onmessage: null, onclose: null, onerror: null,
+ send: vi.fn(), close: vi.fn(() => ws.onclose?.({} as CloseEvent)) } as ChatSocket & { send: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> };
+ sockets.push(ws); return ws;
+}
+const receive = async (ws: ChatSocket, data: unknown) => { ws.onmessage?.({ data: JSON.stringify(data) } as MessageEvent); await Promise.resolve(); await Promise.resolve(); };
+let stop = () => {};
+afterEach(() => { stop(); sockets.length = 0; vi.useRealTimers(); });
+it('authenticates inside the socket, acknowledges string cursors and reconnects without replaying writes', async () => {
+ vi.useFakeTimers(); const changed = vi.fn(); const token = vi.fn(async () => 'fixture-token');
+ const ready = vi.fn(async () => ({ scope: `actor:${actorId}`, cursor: '9007199254740993' }));
+ const create = vi.fn(socket);
+ stop = subscribeChatServer({ baseUrl: 'https://chat.example.invalid', token, current: () => true, socket: create, ready, changed, unavailable: vi.fn() });
+ await Promise.resolve(); const first = sockets[0]; first.onopen?.({} as Event);
+ expect(create).toHaveBeenCalledWith('wss://chat.example.invalid/v1/ws');
+ expect(first.send).toHaveBeenCalledWith(JSON.stringify({ type: 'auth', token: 'fixture-token' }));
+ await receive(first, { type: 'ready', actorId });
+ await receive(first, { type: 'changes', scope: `actor:${actorId}`, cursor: '9007199254740994', changes: [] });
+ expect(changed).toHaveBeenCalledOnce();
+ expect(first.send).toHaveBeenLastCalledWith(JSON.stringify({ type: 'ack', scope: `actor:${actorId}`, cursor: '9007199254740994' }));
+ first.close(); await vi.advanceTimersByTimeAsync(1000);
+ expect(sockets).toHaveLength(2); expect(token).toHaveBeenCalledTimes(2);
+ await receive(sockets[1], { type: 'ready', actorId }); expect(ready).toHaveBeenCalledTimes(2);
+});
+it('recovers reset cursors and stops revoked scopes instead of retrying membership indefinitely', async () => {
+ vi.useFakeTimers(); const changed = vi.fn();
+ stop = subscribeChatServer({ baseUrl: 'https://chat.example.invalid', token: async () => 'fixture', current: () => true,
+ socket, ready: async () => ({ scope: `actor:${actorId}`, cursor: '0' }), changed, unavailable: vi.fn() });
+ await Promise.resolve(); const ws = sockets[0];
+ await receive(ws, { type: 'ready', actorId });
+ await receive(ws, { type: 'scope_error', scope: `actor:${actorId}`, error: { code: 'RESET_REQUIRED', details: { head: '50' } } });
+ expect(ws.send).toHaveBeenLastCalledWith(JSON.stringify({ type: 'subscribe', scope: `actor:${actorId}`, after: '50' }));
+ await receive(ws, { type: 'scope_error', scope: `actor:${actorId}`, error: { code: 'NOT_MEMBER' } });
+ await vi.advanceTimersByTimeAsync(60000); expect(sockets).toHaveLength(1); expect(changed).toHaveBeenCalledTimes(2);
+});
+it('does not authenticate or reconnect after owner change or disposal', async () => {
+ let resolve!: (token: string) => void; let current = true;
+ stop = subscribeChatServer({ baseUrl: 'https://chat.example.invalid', token: () => new Promise(r => { resolve = r; }), current: () => current,
+ socket, ready: vi.fn(), changed: vi.fn(), unavailable: vi.fn() });
+ current = false; resolve('old-owner'); await Promise.resolve(); expect(sockets).toHaveLength(0);
+});
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
new file mode 100644
index 0000000000..d6f17cf030
--- /dev/null
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -0,0 +1,156 @@
+/** The existing Chat Server HTTP contract; no device-link or executor registration. */
+import type { BotGroupAttachment, BotGroupMemberView, BotGroupMessageView, BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';
+import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';
+
+export interface ChatRoom {
+ id: string; name: string; state?: string; kind: string; archived: boolean;
+ created_at: string; updated_at: string; revision: number; head?: string;
+ response_mode: 'all' | 'mentioned'; speaking_mode: 'auto' | 'sequential'; organizer_id?: string | null;
+}
+export interface ChatMember {
+ id: string; kind: 'human' | 'bot' | 'integration'; name: string; state: string;
+ ownerActorId: string; ownerName: string; avatar: string | null;
+ role: 'owner' | 'admin' | 'member' | 'guest';
+}
+export interface ChatMessage {
+ id: string; seq: string; authorId: string; author: { kind: string; name: string };
+ createdAt: string; deleted: boolean; threadRootId: string | null; origin?: string;
+ content: Array<{ type: string; text?: string; fallback?: string; mediaId?: string; caption?: string;
+ namespace?: string; schemaRevision?: number; data?: Record<string, unknown> }>;
+}
+export interface ChatSnapshot { room: ChatRoom; members: ChatMember[]; messages: ChatMessage[]; cursor: string }
+export interface ChatPage { snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null }
+export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST', body?: unknown) => Promise<T>;
+
+export function chatId(value: string): string {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw new Error('INVALID_CHAT_ID');
+ return value;
+}
+export function chatCursor(value: unknown): string {
+ if (typeof value !== 'string' || !/^\d{1,30}$/.test(value)) throw new Error('INVALID_CHAT_CURSOR');
+ return value;
+}
+export function chatHttpsUrl(value: string): string {
+ const url = new URL(value);
+ if (url.protocol !== 'https:' || url.username || url.password) throw new Error('INVALID_CHAT_URL');
+ return url.href;
+}
+export function chatAccessLost(error: unknown): boolean {
+ return !!error && typeof error === 'object' && 'status' in error && (error.status === 403 || error.status === 404);
+}
+const memberName = (member: ChatMember) => member.kind === 'bot' && member.ownerName?.trim()
+ ? `${member.name} (${member.ownerName.trim()})` : member.name;
+const contentText = (message: ChatMessage) => message.deleted ? '' : message.content
+ .map(block => block.text ?? block.fallback ?? (block.type === 'media' ? block.caption ?? '' : '')).join('\n');
+
+/** Empty device identity means a server-owned conversation, never a fictitious computer. */
+export function chatRoomRow(room: ChatRoom, snapshot?: ChatSnapshot): HostedRemoteCollectionItem {
+ const members = snapshot?.members.filter(member => member.state === 'joined') ?? [];
+ const last = snapshot?.messages.filter(message => !message.threadRootId && !message.deleted)
+ .sort((a, b) => BigInt(chatCursor(a.seq)) < BigInt(chatCursor(b.seq)) ? 1 : -1)[0];
+ return { key: `chat:${room.id}`, host: { deviceId: '', deviceName: '' }, item: {
+ ref: { collectionId: 'bot-groups', kind: 'bot-group', id: room.id },
+ revision: String(room.head ?? room.revision), display: { title: room.name,
+ subtitle: members.map(memberName).join(' · '),
+ ...(snapshot ? { preview: last ? contentText(last).slice(0, 160) || members.map(memberName).join(' · ') : '' } : {}),
+ timestamp: Date.parse(last?.createdAt ?? room.updated_at) },
+ links: members.map(member => ({ rel: 'member', label: memberName(member),
+ target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: member.id } } })),
+ } };
+}
+
+/** Sequence strings stay on the wire; numeric positions below are presentation order only. */
+export function chatGroupView(page: ChatPage, selfId: string): BotGroupRemoteChatData {
+ const { room, members } = page.snapshot;
+ const active = members.filter(member => member.state === 'joined');
+ const memberViews: BotGroupMemberView[] = active.map(member => ({
+ botId: member.id, actorId: member.id, actorKind: member.kind, isSelf: member.id === selfId,
+ isOwned: member.ownerActorId === selfId, role: member.role,
+ name: memberName(member), avatar: member.avatar?.startsWith('https://') ? member.avatar : '', avatarColor: '', status: 'active',
+ }));
+ const sorted = [...new Map(page.messages.map(message => [message.id, message])).values()].filter(message => !message.deleted)
+ .sort((a, b) => BigInt(chatCursor(a.seq)) < BigInt(chatCursor(b.seq)) ? -1 : BigInt(a.seq) > BigInt(b.seq) ? 1 : 0);
+ const messages: BotGroupMessageView[] = sorted.map((message, index) => {
+ const member = active.find(candidate => candidate.id === message.authorId);
+ const joined = message.origin === 'system' && !message.deleted && message.content.find(block =>
+ block.type === 'card' && block.namespace === 'cindy.membership' && block.schemaRevision === 1 && block.data?.type === 'member.joined');
+ return { id: message.id, sequence: index + 1, kind: message.origin === 'system' ? 'notice' : 'message',
+ authorKind: message.origin === 'system' ? 'system' : message.author.kind === 'human' ? 'user' : 'bot',
+ authorBotId: message.authorId, authorName: joined && typeof joined.data?.displayName === 'string' ? joined.data.displayName
+ : member ? memberName(member) : message.author.name,
+ isSelf: message.authorId === selfId, content: contentText(message), mentions: { all: false, botIds: [] },
+ noticeCode: joined ? 'member-joined' : null, planId: null, files: [],
+ attachments: message.deleted ? [] : message.content.flatMap(block => {
+ if (block.type !== 'media' || !block.mediaId) return [];
+ return [{ id: block.mediaId, name: block.caption ?? '', category: 'file' as const,
+ mimeType: '', size: 0, url: null, path: null }];
+ }), createdAt: Date.parse(message.createdAt) };
+ });
+ const last = messages.at(-1);
+ return { id: room.id, name: room.name, serverBacked: true, archived: room.archived, selfActorId: selfId,
+ revision: room.revision, members: memberViews, replyMode: room.response_mode, speakingMode: room.speaking_mode,
+ organizerBotId: room.organizer_id ?? null, projectDir: null, projectDirName: null,
+ createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),
+ lastMessage: last ? { authorKind: last.authorKind, authorName: last.authorName, preview: last.content.slice(0, 80), createdAt: last.createdAt } : null,
+ speakingBotIds: [], planningBotId: null, openPlan: null, plans: [], messages,
+ hasMoreBefore: page.before !== null, round: { status: 'idle', speakers: [], canContinue: false }, supportsAttachments: false };
+}
+
+export function createChatServerClient(request: ChatRequest) {
+ return {
+ async list(): Promise<ChatRoom[]> {
+ const rooms = new Map<string, ChatRoom>();
+ let after: string | undefined;
+ do {
+ const page = await request<ChatRoom[]>(`/conversations?limit=100${after ? `&after=${after}` : ''}`);
+ if (!Array.isArray(page)) throw new Error('INVALID_CHAT_LIST');
+ for (const room of page) {
+ chatId(room.id);
+ if (room.state === 'joined' && room.kind === 'group') rooms.set(room.id, room);
+ }
+ const next = page.length === 100 ? chatId(page.at(-1)!.id) : undefined;
+ if (next && next === after) throw new Error('INVALID_CHAT_PAGE');
+ after = next;
+ } while (after);
+ return [...rooms.values()];
+ },
+ async me(): Promise<string> { return chatId((await request<{ actor: { id: string } }>('/me')).actor.id); },
+ async snapshot(roomId: string): Promise<ChatSnapshot> {
+ return request(`/conversations/${chatId(roomId)}/snapshot`);
+ },
+ async load(roomId: string, oldest?: string): Promise<ChatPage> {
+ const room = chatId(roomId);
+ const snapshot = await request<ChatSnapshot>(`/conversations/${room}/snapshot`);
+ if (snapshot.room.id !== room || !Array.isArray(snapshot.members)) throw new Error('INVALID_CHAT_SNAPSHOT');
+ chatCursor(snapshot.cursor);
+ // Snapshot includes Thread replies; the message endpoint selects the main timeline.
+ let batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100`);
+ const messages = [...batch];
+ let before = batch.length === 100 ? chatCursor(batch.at(-1)!.seq) : null;
+ // Reauthorize and re-read the displayed window on invalidation, including edits/removals.
+ while (oldest && before && BigInt(before) > BigInt(chatCursor(oldest))) {
+ batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100&before=${before}`);
+ const next = batch.length === 100 ? chatCursor(batch.at(-1)!.seq) : null;
+ if (next && BigInt(next) >= BigInt(before)) throw new Error('INVALID_CHAT_PAGE');
+ messages.push(...batch); before = next;
+ }
+ return { snapshot, messages, before };
+ },
+ async older(roomId: string, page: ChatPage): Promise<ChatPage> {
+ if (!page.before) return page;
+ const messages = await request<ChatMessage[]>(`/conversations/${chatId(roomId)}/messages?limit=100&before=${chatCursor(page.before)}`);
+ return { ...page, messages: [...page.messages, ...messages], before: messages.length === 100 ? chatCursor(messages.at(-1)!.seq) : null };
+ },
+ async media(roomId: string, mediaId: string): Promise<BotGroupAttachment> {
+ const media = await request<{ name: string; type: string; size: string | number; url: string }>(`/conversations/${chatId(roomId)}/media/${chatId(mediaId)}`);
+ const size = Number(media.size);
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error('INVALID_MEDIA_SIZE');
+ return { id: mediaId, name: media.name, mimeType: media.type, size, category: media.type.startsWith('image/') ? 'image' : 'file',
+ url: chatHttpsUrl(media.url), path: null };
+ },
+ async send(roomId: string, input: { clientId: string; text: string; mentions: { all: boolean; botIds: string[] } }) {
+ return request(`/conversations/${chatId(roomId)}/messages`, 'POST', { operationId: input.clientId,
+ content: [{ type: 'text', text: input.text }], mentions: input.mentions.botIds.map(chatId) });
+ },
+ };
+}
diff --git a/apps/mobile/src/chat/chatServerSubscription.ts b/apps/mobile/src/chat/chatServerSubscription.ts
new file mode 100644
index 0000000000..8f4f223797
--- /dev/null
+++ b/apps/mobile/src/chat/chatServerSubscription.ts
@@ -0,0 +1,71 @@
+import { chatCursor, chatHttpsUrl, chatId } from './chatServerClient';
+
+export interface ChatSocket {
+ onopen: ((event: Event) => void) | null;
+ onmessage: ((event: MessageEvent) => void) | null;
+ onclose: ((event: CloseEvent) => void) | null;
+ onerror: ((event: Event) => void) | null;
+ send(data: string): void;
+ close(): void;
+ readonly readyState: number;
+}
+/** One focused view owns one socket. Reconnect re-reads state, never replays a write. */
+export function subscribeChatServer(options: {
+ baseUrl: string; token(): Promise<string | null>; current(): boolean;
+ socket(url: string): ChatSocket;
+ ready(actorId: string): Promise<{ scope: string; cursor: string }>;
+ changed(): void; unavailable(): void;
+}) {
+ let stopped = false;
+ let socket: ChatSocket | undefined;
+ let retry: ReturnType<typeof setTimeout> | undefined;
+ let deadline: ReturnType<typeof setTimeout> | undefined;
+ let delay = 1000;
+ const current = (candidate: ChatSocket) => !stopped && options.current() && socket === candidate;
+ const connect = async () => {
+ try {
+ const token = await options.token();
+ if (stopped || !options.current()) return;
+ if (!token) throw new Error('UNAUTHENTICATED');
+ const url = new URL(chatHttpsUrl(options.baseUrl));
+ url.pathname = `${url.pathname.replace(/\/$/, '')}/v1/ws`; url.protocol = 'wss:';
+ const ws = options.socket(url.href); socket = ws;
+ deadline = setTimeout(() => ws.close(), 15000);
+ ws.onopen = () => { if (current(ws)) ws.send(JSON.stringify({ type: 'auth', token })); else ws.close(); };
+ let scope: string | undefined;
+ ws.onmessage = event => {
+ if (!current(ws)) return;
+ void (async () => {
+ const value = JSON.parse(String(event.data));
+ if (value.type === 'ready') {
+ clearTimeout(deadline);
+ const subscription = await options.ready(chatId(value.actorId));
+ if (current(ws) && ws.readyState === 1) {
+ scope = subscription.scope; delay = 1000;
+ ws.send(JSON.stringify({ type: 'subscribe', scope, after: chatCursor(subscription.cursor) }));
+ }
+ } else if (value.type === 'changes' && scope && value.scope === scope) {
+ options.changed();
+ ws.send(JSON.stringify({ type: 'ack', scope: value.scope, cursor: chatCursor(value.cursor) }));
+ } else if (value.type === 'scope_error' && scope && value.scope === scope) {
+ // A full authenticated reload clears removed membership and resets expired cursors.
+ options.changed();
+ if (value.error?.code === 'RESET_REQUIRED' && value.error?.details?.head) {
+ ws.send(JSON.stringify({ type: 'subscribe', scope: value.scope, after: chatCursor(value.error.details.head) }));
+ } else { stopped = true; options.unavailable(); ws.close(); }
+ } else if (value.type === 'error') ws.close();
+ })().catch(() => { if (current(ws)) ws.close(); });
+ };
+ ws.onerror = () => { if (current(ws)) ws.close(); };
+ ws.onclose = () => { if (current(ws)) { clearTimeout(deadline); schedule(); } };
+ } catch { if (!stopped && options.current()) schedule(); }
+ };
+ const schedule = () => {
+ options.unavailable();
+ clearTimeout(retry);
+ retry = setTimeout(() => { void connect(); }, delay);
+ delay = Math.min(delay * 2, 15000);
+ };
+ void connect();
+ return () => { stopped = true; clearTimeout(retry); clearTimeout(deadline); socket?.close(); };
+}
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
new file mode 100644
index 0000000000..bc7d919537
--- /dev/null
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -0,0 +1,188 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { AppState } from 'react-native';
+import { useFocusEffect } from 'expo-router';
+import type { RemoteActionInvokeResponse } from '@cindy/device-link';
+import type { BotGroupAttachment, BotGroupRemoteActionId } from '@cindy/maker-shared/botGroupChat';
+import { useAuth } from '@/auth/AuthContext';
+import { getActiveMobileSessionRealm, getMobileEndpointForRealm } from '@/config/env';
+import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';
+import type { BotGroupChatState } from '@/session/useBotGroupChat';
+import { chatAccessLost, chatCursor, chatGroupView, chatHttpsUrl, chatRoomRow, createChatServerClient, type ChatPage, type ChatRequest, type ChatSnapshot } from './chatServerClient';
+import { subscribeChatServer } from './chatServerSubscription';
+
+function useChatClient() {
+ const auth = useAuth();
+ const owner = `${auth.user?.id ?? ''}:${auth.accountGeneration}:${getActiveMobileSessionRealm()}`;
+ const active = useRef(owner); active.current = owner;
+ const mounted = useRef(true);
+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
+ const deps = useRef(auth); deps.current = auth;
+ return useMemo(() => {
+ const current = () => mounted.current && active.current === owner;
+ const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };
+ const baseUrl = () => chatHttpsUrl(getMobileEndpointForRealm(getActiveMobileSessionRealm(), 'chatApiBaseUrl')).replace(/\/$/, '');
+ const request: ChatRequest = async <T,>(path: string, method: 'GET' | 'POST' = 'GET', body?: unknown) => {
+ check();
+ const result = await deps.current.apiFetch<T>(`/v1${path}`, { baseUrl: baseUrl(), method, cache: 'no-store', ...(body !== undefined ? { body } : {}), assertCurrent: check });
+ check(); return result;
+ };
+ return { owner, current, baseUrl, request, client: createChatServerClient(request),
+ token: async () => { check(); await request('/me'); const token = await deps.current.getAccessToken(); check(); return token; }, enabled: !!auth.user };
+ }, [owner, !!auth.user]);
+}
+
+/** Direct server roster, independent of device discovery and presence. */
+export function useChatServerRoster(enabled: boolean) {
+ const api = useChatClient();
+ const known = useRef({ owner: api.owner, ids: new Set<string>() });
+ if (known.current.owner !== api.owner) known.current = { owner: api.owner, ids: new Set() };
+ const snapshots = useRef(new Map<string, { owner: string; head: string | undefined; value: ChatSnapshot }>());
+ const [state, setState] = useState({ owner: api.owner, rooms: [] as ReturnType<typeof chatRoomRow>[], loading: true, refreshing: false, error: null as string | null });
+ const read = useRemoteSyncCoordinator(async run => {
+ if (!api.enabled || !enabled) return;
+ setState(old => ({ ...old, refreshing: run.reasons.includes('visible') }));
+ try {
+ const rooms = await api.client.list();
+ const rows: ReturnType<typeof chatRoomRow>[] = [];
+ const fresh = new Map<string, { owner: string; head: string | undefined; value: ChatSnapshot }>();
+ let partial = false;
+ // List provides room heads, so unchanged rooms need no history download on polling.
+ for (let offset = 0; offset < rooms.length; offset += 4) {
+ await Promise.all(rooms.slice(offset, offset + 4).map(async room => {
+ try {
+ const cached = snapshots.current.get(room.id);
+ const value = cached?.owner === api.owner && room.head !== undefined && cached.head === room.head
+ ? cached.value : await api.client.snapshot(room.id);
+ fresh.set(room.id, { owner: api.owner, head: room.head, value });
+ rows.push(chatRoomRow(room, value));
+ } catch (error) {
+ if (!chatAccessLost(error)) { partial = true; rows.push(chatRoomRow(room)); }
+ }
+ }));
+ if (run.isStale() || !api.current()) return;
+ }
+ if (!run.isStale() && api.current()) {
+ snapshots.current = fresh;
+ for (const room of rooms) known.current.ids.add(room.id);
+ setState({ owner: api.owner, rooms: rows, loading: false, refreshing: false, error: partial ? 'CHAT_LIST_FAILED' : null });
+ }
+ } catch (error) {
+ if (!run.isStale() && api.current()) setState(old => ({ owner: api.owner, rooms: old.owner === api.owner && !chatAccessLost(error) ? old.rooms : [], loading: false, refreshing: false, error: 'CHAT_LIST_FAILED' }));
+ }
+ }, api.owner);
+ const refresh = useCallback(() => read({ reason: 'visible' }), [read]);
+ useFocusEffect(useCallback(() => {
+ if (!enabled || !api.enabled) return;
+ let stop: (() => void) | undefined;
+ let poll: ReturnType<typeof setInterval> | undefined;
+ const start = () => {
+ stop?.(); clearInterval(poll);
+ if (AppState.currentState !== 'active') return;
+ void read({ reason: 'focus' });
+ // Actor events cover membership; room heads also catch messages and renames without
+ // subscribing every group (the service limits each socket to 16 scopes).
+ poll = setInterval(() => { void read({ reason: 'poll' }); }, 30000);
+ try { stop = subscribeChatServer({ baseUrl: api.baseUrl(), token: api.token, current: api.current, socket: url => new WebSocket(url),
+ ready: async actorId => {
+ let cursor: string;
+ try { cursor = chatCursor((await api.request<{ head: string }>(`/changes?scope=actor:${actorId}&after=0&limit=1`)).head); }
+ catch (error) {
+ if ((error as { code?: string }).code !== 'RESET_REQUIRED') throw error;
+ cursor = '0'; // The socket returns the reset head without changing shared API errors.
+ }
+ await read({ reason: 'connected' });
+ return { scope: `actor:${actorId}`, cursor };
+ }, changed: () => { void read({ reason: 'changed' }); }, unavailable: () => {} }); } catch { /* HTTP read presents endpoint errors. */ }
+ };
+ start();
+ const foreground = AppState.addEventListener('change', value => { if (value === 'active') start(); else { stop?.(); clearInterval(poll); } });
+ return () => { stop?.(); clearInterval(poll); foreground.remove(); };
+ }, [api, enabled, read]));
+ const own = state.owner === api.owner;
+ return { items: own ? state.rooms : [], serverIds: known.current.ids, loading: api.enabled && (!own || state.loading),
+ refreshing: own && state.refreshing, error: own ? state.error : null, refresh };
+}
+
+/** Reads and sends use the account's Chat Server identity, never its computer identity. */
+export function useChatServerGroup(groupId: string, enabled: boolean) {
+ const api = useChatClient();
+ const identity = `${api.owner}:${groupId}`;
+ 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 freshRead = useRef(false);
+ const olderPending = useRef(false);
+ const valid = () => api.current() && active.current === identity;
+ const request = useRemoteSyncCoordinator(async run => {
+ if (!enabled || !api.enabled) return;
+ 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;
+ // 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 }); }
+ else setState(old => ({ identity, value: old.identity === identity && old.value.kind === 'ready' ? old.value : { kind: 'error', message: 'CHAT_READ_FAILED' }, online: false, loadingOlder: false }));
+ }
+ }, identity);
+ const reload = useCallback(() => { void request({ reason: 'changed' }); }, [request]);
+ useFocusEffect(useCallback(() => {
+ if (!enabled || !api.enabled || !groupId) return;
+ let stop: (() => void) | undefined;
+ let recovery: ReturnType<typeof setInterval> | undefined;
+ const start = () => {
+ stop?.(); clearInterval(recovery);
+ if (AppState.currentState !== 'active') return;
+ reload();
+ // A failed read after an acknowledged event must recover even without another event.
+ recovery = setInterval(() => { if (!freshRead.current) reload(); }, 30000);
+ try { stop = subscribeChatServer({ baseUrl: api.baseUrl(), token: api.token, current: () => api.current() && active.current === identity,
+ socket: url => new WebSocket(url), ready: async () => {
+ await request({ reason: 'connected' });
+ 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, unavailable: () => { freshRead.current = false; if (api.current() && active.current === identity) setState(old => ({ ...old, online: false })); } }); } catch { /* Read presents errors. */ }
+ };
+ start();
+ const foreground = AppState.addEventListener('change', value => { if (value === 'active') start(); else { stop?.(); clearInterval(recovery); } });
+ return () => { stop?.(); clearInterval(recovery); foreground.remove(); };
+ }, [api, enabled, groupId, identity, reload, request]));
+ const loadOlder = async () => {
+ const previous = page.current;
+ if (!previous || previous.identity !== identity || olderPending.current) return;
+ olderPending.current = true;
+ setState(old => ({ ...old, loadingOlder: true }));
+ try {
+ const next = await api.client.older(groupId, previous.page);
+ if (!valid() || page.current !== previous) return;
+ 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 }); }
+ throw error;
+ } finally { olderPending.current = false; if (valid()) setState(old => ({ ...old, loadingOlder: false })); }
+ };
+ const act = async (action: BotGroupRemoteActionId, input?: Record<string, unknown>): Promise<RemoteActionInvokeResponse> => {
+ 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[] };
+ await api.client.send(groupId, { clientId: String(input.clientId), text: String(input.text),
+ mentions: { all: false, botIds: mentions.all ? latest.page.snapshot.members.filter(member => member.state === 'joined' && member.id !== latest.self).map(member => member.id) : mentions.botIds } });
+ reload(); return { effects: [] };
+ };
+ const media = async (mediaId: string): Promise<BotGroupAttachment> => {
+ const attachment = await api.client.media(groupId, mediaId);
+ if (!valid()) throw new Error('OWNER_CHANGED');
+ return attachment;
+ };
+ return { state: state.identity === identity ? state.value : { kind: 'loading' } as BotGroupChatState,
+ online: state.identity === identity && state.online, reload, act, loadOlder, loadingOlder: state.loadingOlder, media };
+}
diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.json
index 5bcf89255e..3bb7351c0f 100644
--- a/apps/mobile/src/i18n/locales/en/groupChat.json
+++ b/apps/mobile/src/i18n/locales/en/groupChat.json
@@ -174,5 +174,12 @@
"followUp": {
"next": "Plan · Next step",
"failedStep": "Step {{step}} didn't finish"
+ },
+ "server": {
+ "offline": "Can’t connect to group chat. Try again.",
+ "loadFailed": "Can’t load this group chat right now. Try again.",
+ "loadOlder": "Load Earlier Messages",
+ "attachmentFailed": "Couldn’t open the attachment. Try again.",
+ "previewUnavailable": "Preview unavailable"
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.json
index a4f3012b40..a09d3c4154 100644
--- a/apps/mobile/src/i18n/locales/ja/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json
@@ -174,5 +174,12 @@
"followUp": {
"next": "分担 · 次のステップ",
"failedStep": "ステップ {{step}} は完了できませんでした"
+ },
+ "server": {
+ "offline": "グループチャットに接続できません。もう一度お試しください。",
+ "loadFailed": "グループチャットを読み込めません。もう一度お試しください。",
+ "loadOlder": "以前のメッセージを読み込む",
+ "attachmentFailed": "添付ファイルを開けませんでした。もう一度お試しください。",
+ "previewUnavailable": "プレビューを読み込めません"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.json
index 050549a8fe..a62ab8e68a 100644
--- a/apps/mobile/src/i18n/locales/ko/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json
@@ -174,5 +174,12 @@
"followUp": {
"next": "분담 · 다음 단계",
"failedStep": "{{step}}단계를 끝내지 못했어요"
+ },
+ "server": {
+ "offline": "그룹 채팅에 연결할 수 없습니다. 다시 시도해 주세요.",
+ "loadFailed": "그룹 채팅을 불러올 수 없습니다. 다시 시도해 주세요.",
+ "loadOlder": "이전 메시지 불러오기",
+ "attachmentFailed": "첨부 파일을 열지 못했습니다. 다시 시도해 주세요.",
+ "previewUnavailable": "미리보기를 불러올 수 없습니다"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
index 43f0642693..4ffba2ed5f 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
@@ -174,5 +174,12 @@
"followUp": {
"next": "分工 · 下一步",
"failedStep": "第 {{step}} 步没做完"
+ },
+ "server": {
+ "offline": "暂时无法连接群聊,请重试。",
+ "loadFailed": "暂时无法读取群聊,请重试。",
+ "loadOlder": "加载更早的消息",
+ "attachmentFailed": "附件打开失败,请重试。",
+ "previewUnavailable": "暂时无法读取消息预览"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
index d40d38a3ea..64a5f90a14 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
@@ -174,5 +174,12 @@
"followUp": {
"next": "分工 · 下一步",
"failedStep": "第 {{step}} 步沒做完"
+ },
+ "server": {
+ "offline": "暫時無法連線群聊,請重試。",
+ "loadFailed": "暫時無法讀取群聊,請重試。",
+ "loadOlder": "載入更早的訊息",
+ "attachmentFailed": "附件開啟失敗,請重試。",
+ "previewUnavailable": "暫時無法讀取訊息預覽"
}
}
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index 8341e94dcb..067d099dac 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -25,6 +25,7 @@ import { useTranslation } from 'react-i18next';
import { resolveRemoteText } from '@cindy/device-link';
import {
BOT_GROUP_REMOTE_COLLECTION_ID,
+ type BotGroupAttachment,
type BotGroupMemberView,
type BotGroupMessageView,
type BotGroupPlanAction,
@@ -173,9 +174,10 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
if (hasGroupRef.current) { leaveAfterSettings.current = true; setSettings(false); } else leave();
}, [leave]);
+ const offlineKey = chat.server ? 'groupChat.server.offline' : 'devices.resources.hostOffline';
const report = useCallback((error: unknown, fallbackKey: string) => {
- Alert.alert(chat.online ? botGroupActionErrorText(t, error, fallbackKey) : t('devices.resources.hostOffline'));
- }, [chat.online, t]);
+ Alert.alert(chat.online ? botGroupActionErrorText(t, error, fallbackKey) : t(offlineKey));
+ }, [chat.online, offlineKey, t]);
const continueRound = async () => {
if (continuing) return;
@@ -259,7 +261,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
if (chat.state.kind === 'loading' && !chat.online) {
// Nothing to show until the computer is reachable again; the screen re-reads on reconnect.
body = <View style={styles.center}>
- <MainWindowEmptyState centered testID="botGroup.offline" title={t('groupChat.loadFailedTitle')} copy={t('devices.resources.hostOffline')}>
+ <MainWindowEmptyState centered testID="botGroup.offline" title={t('groupChat.loadFailedTitle')} copy={t(offlineKey)}>
<View style={styles.emptyActions}>
<MainWindowActionButton action={{ label: t('shared.back'), onPress: leave, testID: 'botGroup.leave' }} />
</View>
@@ -272,7 +274,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
body = <View style={styles.center}>
<MainWindowEmptyState centered testID={failed ? 'botGroup.loadFailed' : 'botGroup.unavailable'}
title={t(failed ? 'groupChat.loadFailedTitle' : 'groupChat.unavailableTitle')}
- copy={t(failed ? 'groupChat.loadFailedDescription' : 'groupChat.unavailableDescription')}>
+ copy={t(failed ? (chat.server ? 'groupChat.server.loadFailed' : 'groupChat.loadFailedDescription') : 'groupChat.unavailableDescription')}>
<View style={styles.emptyActions}>
<MainWindowActionButton action={{ label: t('shared.back'), onPress: leave, testID: 'botGroup.leave' }} />
{failed ? <MainWindowActionButton action={{ label: t('devices.resources.retry'), tone: 'primary', onPress: chat.reload, testID: 'botGroup.retry' }} /> : null}
@@ -287,7 +289,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'web',
)}
>
- {!chat.online ? <Text accessibilityRole="alert" style={styles.offline} testID="botGroup.offlineNote">{t('devices.resources.hostOffline')}</Text> : null}
+ {!chat.online ? <Text accessibilityRole="alert" style={styles.offline} testID="botGroup.offlineNote">{t(offlineKey)}</Text> : null}
<ScrollView ref={scrollRef} style={styles.flex} contentContainerStyle={styles.timeline} keyboardShouldPersistTaps="handled"
keyboardDismissMode="interactive" onScroll={onScroll} scrollEventThrottle={64}
onLayout={event => { viewport.current.viewportHeight = event.nativeEvent.layout.height; acknowledge(); }}
@@ -299,15 +301,17 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
}}
testID="botGroup.timeline">
<BotGroupTimeline group={group} deviceId={deviceId} online={chat.online} identityFor={identityFor}
- resolveMedia={resolveMedia} continuing={continuing} planPending={planPending}
+ resolveMedia={resolveMedia} resolveServerMedia={chat.media}
+ loadOlder={chat.loadOlder ? () => { stickToBottom.current = false; void chat.loadOlder!().catch(error => report(error, 'groupChat.loadFailedTitle')); } : undefined}
+ loadingOlder={chat.loadingOlder} continuing={continuing} planPending={planPending}
onContinue={() => void continueRound()}
onPlanAction={(action, planId) => void runPlanAction(action, planId)}
onEditStep={(planId, step, action, botId) => void editPlanStep(planId, step, action, botId)}
onInteractionError={(message) => { if (message) Alert.alert(message); }} />
</ScrollView>
- <BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={chat.online}
+ <BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={chat.online && !group.archived}
running={group.round.status === 'running'} planState={botGroupComposerPlanState(openBotGroupPlan(group))}
- attachmentsSupported={group.supportsAttachments === true} onSend={send} onStop={stop} />
+ divisionSupported={!chat.server} attachmentsSupported={group.supportsAttachments === true} onSend={send} onStop={stop} />
</KeyboardAvoidingView>;
}
@@ -315,7 +319,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
<Stack.Screen options={{ headerShown: false }} />
{header}
{body}
- {group ? <BotGroupSettingsSheet visible={settings} group={group} host={host} identityFor={identityFor} online={chat.online}
+ {group ? <BotGroupSettingsSheet readOnly={chat.server} visible={settings} group={group} host={host} identityFor={identityFor} online={chat.online}
act={chat.act} onClose={() => setSettings(false)}
onClosed={() => { if (leaveAfterSettings.current) { leaveAfterSettings.current = false; leave(); } }}
onDeleted={onGroupDeleted} /> : null}
@@ -331,7 +335,7 @@ function followUpPending(action: PlanPending['action'] | null): BotGroupFollowUp
}
export function BotGroupTimeline({
- group, deviceId, online, identityFor, resolveMedia, continuing, planPending, onContinue, onPlanAction, onEditStep, onInteractionError,
+ group, deviceId, online, identityFor, resolveMedia, resolveServerMedia, loadOlder, loadingOlder, continuing, planPending, onContinue, onPlanAction, onEditStep, onInteractionError,
}: {
group: BotGroupRemoteChatData;
deviceId: string;
@@ -339,6 +343,9 @@ export function BotGroupTimeline({
identityFor: BotGroupIdentityLookup;
/** Reads a picture attached to a message from the computer. */
resolveMedia: ResolveRemoteMediaFn;
+ resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
+ loadOlder?: () => void;
+ loadingOlder?: boolean;
continuing: boolean;
planPending: PlanPending | null;
onContinue(): void;
@@ -363,7 +370,7 @@ export function BotGroupTimeline({
: [];
const pendingFor = (planId: string | null) => planId && planPending?.planId === planId ? planPending.action : null;
return <>
- {group.hasMoreBefore ? <Text style={styles.olderNote} testID="botGroup.olderOnComputer">{t('groupChat.timeline.olderOnComputer')}</Text> : null}
+ {group.hasMoreBefore && loadOlder ? <MainWindowActionButton action={{ label: t('groupChat.server.loadOlder'), busy: loadingOlder, onPress: loadOlder, testID: 'botGroup.loadOlder' }} /> : group.hasMoreBefore ? <Text style={styles.olderNote} testID="botGroup.olderOnComputer">{t('groupChat.timeline.olderOnComputer')}</Text> : null}
{messages.length === 0 && !running ? <MainWindowEmptyState centered testID="botGroup.empty"
title={t('groupChat.timeline.emptyTitle')} copy={t('groupChat.timeline.emptyDescription')} /> : null}
{messages.map((message, index) => {
@@ -377,7 +384,7 @@ export function BotGroupTimeline({
<CompanionEntering id={message.id} createdAt={message.createdAt} kind={message.authorKind === 'user' ? 'send' : 'reply'}>
<BotGroupTimelineItem message={message} continued={continued} member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}
members={group.members} deviceId={deviceId} online={online} identityFor={identityFor} mentionLabels={mentionLabels}
- resolveMedia={resolveMedia}
+ resolveMedia={resolveMedia} resolveServerMedia={resolveServerMedia}
canContinue={message.id === continueId} continuing={continuing} onContinue={onContinue}
plan={message.planId ? planById.get(message.planId) : undefined}
planActionable={message.kind === 'plan' && openPlan?.id === message.planId && openPlan.status === 'proposed'}
@@ -406,7 +413,7 @@ export function BotGroupTimeline({
}
function BotGroupTimelineItem({
- message, continued = false, member, members, deviceId, online, identityFor, mentionLabels, resolveMedia, canContinue, continuing, onContinue,
+ message, continued = false, member, members, deviceId, online, identityFor, mentionLabels, resolveMedia, resolveServerMedia, canContinue, continuing, onContinue,
plan, planActionable, planReassignable, planPending, onPlanAction, onEditStep,
}: {
message: BotGroupMessageView;
@@ -419,6 +426,7 @@ function BotGroupTimelineItem({
identityFor: BotGroupIdentityLookup;
mentionLabels: readonly string[];
resolveMedia: ResolveRemoteMediaFn;
+ resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
canContinue: boolean;
continuing: boolean;
onContinue(): void;
@@ -445,7 +453,7 @@ function BotGroupTimelineItem({
const variant = botGroupNoticeVariant(message.noticeCode, message.planId !== null);
return <Text style={styles.notice} testID="botGroup.notice">{variant ? t(`groupChat.notice.${variant}`, { name }) : message.content}</Text>;
}
- if (message.authorKind === 'user') {
+ if (message.authorKind === 'user' && message.isSelf !== false) {
// Older computers send no attachments; a message with only attachments has no bubble.
const attachments = message.attachments ?? [];
const bubble = message.content.trim().length > 0 || attachments.length === 0;
@@ -454,7 +462,7 @@ function BotGroupTimelineItem({
return <View style={styles.userRow} testID="botGroup.message.user">
<View style={styles.userColumn}>
{attachments.length > 0
- ? <BotGroupMessageAttachments messageId={message.id} attachments={attachments} onResolveRemoteMedia={resolveMedia} />
+ ? <BotGroupMessageAttachments messageId={message.id} attachments={attachments} onResolveRemoteMedia={resolveMedia} resolveServerMedia={resolveServerMedia} />
: null}
{bubble ? <View style={[styles.userBubble, compact && styles.userBubbleCompact]} testID="botGroup.message.userBubble">
<BotGroupUserText content={message.content} mentionLabels={mentionLabels} />
@@ -479,6 +487,7 @@ function BotGroupTimelineItem({
actionable={planActionable} reassignable={planReassignable} pending={planPending}
onStart={() => onPlanAction('start')} onDismiss={() => onPlanAction('dismiss')} onEditStep={onEditStep} />
: <>
+ {message.attachments?.length ? <BotGroupMessageAttachments messageId={message.id} attachments={message.attachments} onResolveRemoteMedia={resolveMedia} resolveServerMedia={resolveServerMedia} /> : null}
{message.content.trim() ? <BotGroupMarkdownText content={message.content} /> : null}
<BotGroupHandoffFiles files={message.files} />
</>}
diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsx
index c923e8d62c..a08a8eca2b 100644
--- a/apps/mobile/src/session/BotGroupComposer.tsx
+++ b/apps/mobile/src/session/BotGroupComposer.tsx
@@ -72,7 +72,7 @@ type MentionOption =
| { kind: 'member'; label: string; member: BotGroupMemberView };
export function BotGroupComposer({
- members, identityFor, deviceId, online, running, planState, attachmentsSupported, onSend, onStop,
+ members, identityFor, deviceId, online, running, planState, attachmentsSupported, divisionSupported = true, onSend, onStop,
}: {
members: readonly BotGroupMemberView[];
identityFor: BotGroupIdentityLookup;
@@ -82,6 +82,7 @@ export function BotGroupComposer({
planState: BotGroupComposerPlanState | null;
/** The computer takes attachments on `send` (`BotGroupRemoteChatData.supportsAttachments`). */
attachmentsSupported: boolean;
+ divisionSupported?: boolean;
/** Rejects with the host's error; the draft (and its tag) come back and the attachments stay. */
onSend(input: BotGroupSendInput): Promise<void>;
onStop(): Promise<void>;
@@ -241,7 +242,7 @@ export function BotGroupComposer({
testID="botGroup.composer.more">
<Plus size={iconSize.sm} color={colors.textSecondary} strokeWidth={iconStroke.regular} />
</Pressable>;
- const plus = attachmentsEnabled
+ const plus = !divisionSupported && !attachmentsSupported ? null : attachmentsEnabled
// The same panel as a 1:1 chat's 「+」: attachments, then the group's own 安排分工.
? plusButton(() => { tray.armMediaTap(); setSheetOpen(true); })
: divisionBlocked
diff --git a/apps/mobile/src/session/BotGroupList.tsx b/apps/mobile/src/session/BotGroupList.tsx
index aa6d96371d..f700a3d5d2 100644
--- a/apps/mobile/src/session/BotGroupList.tsx
+++ b/apps/mobile/src/session/BotGroupList.tsx
@@ -34,7 +34,7 @@ export function BotGroupListRow({ row, online, last = false, onPress }: {
const title = resolveRemoteText(display.title, i18n.language);
const preview = display.preview ? parseMobileMarkdownInlines(resolveRemoteText(display.preview, i18n.language))
.map((inline) => inline.type === 'image' ? inline.alt : inline.text).join('').replace(/\s+/g, ' ').trim() : '';
- const summary = preview || t('groupChat.list.noMessages');
+ const summary = preview || t(!row.host.deviceId && display.preview === undefined ? 'groupChat.server.previewUnavailable' : 'groupChat.list.noMessages');
const running = online && !!display.generation;
const members = botGroupMemberLinks(row.item, i18n.language).map((member) => identityFor(member.botId, member.label));
const time = display.timestamp !== undefined && Number.isFinite(new Date(display.timestamp).getTime())
diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
index a09926fcf2..7053e03ddd 100644
--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx
+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
@@ -1,12 +1,14 @@
/**
- * 群聊时间线里用户消息的附件(docs/product-rules/bot-group-chat.md §8)。
+ * 群聊时间线里各成员消息的附件(docs/product-rules/bot-group-chat.md §8)。
*
* 复用会话消息的附件条(MessageRenderer 的 AttachmentStrip):图片按原始比例显示缩略图,
* 经远程媒体从电脑取件,点开进入与聊天相同的看图器;文件是「类型图标 + 文件名」的小条。
- * 文件留在电脑上(手机拿不到路径),点一下只说明去电脑上打开,与交接文件一致。
+ * 旧电脑文件仍提示在电脑打开;服务器附件点击时独立授权,图片复用看图器,文件使用短期下载地址。
*/
-import { useMemo, useState } from 'react';
-import { Alert, useWindowDimensions } from 'react-native';
+import { openBrowserAsync } from 'expo-web-browser';
+import { useTheme } from '@/theme';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { ActivityIndicator, Alert, View, useWindowDimensions } from 'react-native';
import { useTranslation } from 'react-i18next';
import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';
import { ImageLightbox } from './ImageLightbox';
@@ -35,10 +37,11 @@ export function botGroupAttachmentGallery(messageId: string, attachments: readon
});
}
-export function BotGroupMessageAttachments({ messageId, attachments, onResolveRemoteMedia }: {
+export function BotGroupMessageAttachments({ messageId, attachments, onResolveRemoteMedia, resolveServerMedia }: {
messageId: string;
attachments: readonly BotGroupAttachment[];
onResolveRemoteMedia: ResolveRemoteMediaFn;
+ resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
}) {
const { t } = useTranslation();
const { width } = useWindowDimensions();
@@ -46,6 +49,7 @@ export function BotGroupMessageAttachments({ messageId, attachments, onResolveRe
const items = useMemo(() => attachments.map(botGroupAttachmentForDisplay), [attachments]);
const gallery = useMemo(() => botGroupAttachmentGallery(messageId, items), [items, messageId]);
const [openUrl, setOpenUrl] = useState<string | null>(null);
+ if (resolveServerMedia) return <ServerAttachments attachments={attachments} resolve={resolveServerMedia} />;
const open = (payload: MessagePayload) => {
if (payload.kind === 'media' && payload.media.kind === 'image') {
setOpenUrl(payload.media.url);
@@ -60,3 +64,39 @@ export function BotGroupMessageAttachments({ messageId, attachments, onResolveRe
onResolveRemoteMedia={onResolveRemoteMedia} /> : null}
</>;
}
+
+/** Signed download URLs are acquired on tap and kept only in the open viewer. */
+function ServerAttachments({ attachments, resolve }: {
+ attachments: readonly BotGroupAttachment[]; resolve(id: string): Promise<BotGroupAttachment>;
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const { width } = useWindowDimensions();
+ const layout = useMemo(() => buildMessageContentLayout({ screenWidth: width }), [width]);
+ const [image, setImage] = useState<BotGroupAttachment | null>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+ const pending = useRef(false);
+ const mounted = useRef(true);
+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
+ const open = async (id: string) => {
+ if (pending.current) return;
+ pending.current = true; setBusy(id);
+ try {
+ const value = await resolve(id);
+ if (!mounted.current) return;
+ if (!value.url) throw new Error('MEDIA_NOT_FOUND');
+ if (value.category === 'image') setImage(value);
+ else await openBrowserAsync(value.url);
+ } catch { if (mounted.current) Alert.alert(t('groupChat.server.attachmentFailed')); }
+ finally { pending.current = false; if (mounted.current) setBusy(null); }
+ };
+ return <>
+ {attachments.map(attachment => <View key={attachment.id}>
+ <AttachmentStrip attachments={[{ kind: 'file', name: attachment.name, previewable: false }]}
+ messageKey={attachment.id} align="right" layout={layout} onOpen={() => { void open(attachment.id); }} usePreviewState={useState} />
+ {busy === attachment.id ? <ActivityIndicator color={colors.textSecondary} /> : null}
+ </View>)}
+ {image?.url ? <ImageLightbox images={botGroupAttachmentGallery(image.id, [botGroupAttachmentForDisplay(image)])}
+ initialUrl={image.url} onClose={() => setImage(null)} /> : null}
+ </>;
+}
diff --git a/apps/mobile/src/session/BotGroupSettingsSheet.tsx b/apps/mobile/src/session/BotGroupSettingsSheet.tsx
index 4522b8efe5..b9c79e9832 100644
--- a/apps/mobile/src/session/BotGroupSettingsSheet.tsx
+++ b/apps/mobile/src/session/BotGroupSettingsSheet.tsx
@@ -38,8 +38,9 @@ import { BotGroupMenu } from './BotGroupMenu';
type Busy = 'name' | 'members' | 'organizer' | 'replyMode' | 'speakingMode' | 'delete' | null;
type Act = (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>) => Promise<unknown>;
-export function BotGroupSettingsSheet({ visible, group, host, identityFor, online, act, onClose, onClosed, onDeleted }: {
+export function BotGroupSettingsSheet({ visible, group, host, identityFor, online, act, onClose, onClosed, onDeleted, readOnly = false }: {
visible: boolean;
+ readOnly?: boolean;
group: BotGroupRemoteChatData;
host: RemoteResourceHostTarget;
identityFor: BotGroupIdentityLookup;
@@ -59,7 +60,7 @@ export function BotGroupSettingsSheet({ visible, group, host, identityFor, onlin
const [errors, setErrors] = useState<Partial<Record<Exclude<Busy, null>, string>>>({});
const [picking, setPicking] = useState(false);
const nameFocused = useRef(false);
- const teammates = useHostTeammates(host, visible && picking);
+ const teammates = useHostTeammates(host, visible && picking && !readOnly);
// Follow renames that land from the computer while the field is not being edited.
useEffect(() => { if (!nameFocused.current) setName(group.name); }, [group.name]);
@@ -69,11 +70,11 @@ export function BotGroupSettingsSheet({ visible, group, host, identityFor, onlin
const canRemove = group.members.length > BOT_GROUP_MIN_MEMBERS;
const canAdd = group.members.length < BOT_GROUP_MAX_MEMBERS;
const addable = teammates.rows.filter((row) => !memberIds.includes(row.item.ref.id));
- const locked = busy !== null || !online;
+ const locked = readOnly || busy !== null || !online;
/** Run one change; the section shows the failure copy, or clears it on success. */
const run = async (section: Exclude<Busy, null>, actionId: BotGroupRemoteActionId, input: Record<string, unknown>, fallbackKey: string) => {
- if (busyRef.current) return false;
+ if (readOnly || busyRef.current) return false;
busyRef.current = section;
setBusy(section);
setErrors((current) => ({ ...current, [section]: undefined }));
@@ -90,6 +91,7 @@ export function BotGroupSettingsSheet({ visible, group, host, identityFor, onlin
};
const saveName = async () => {
+ if (readOnly) return;
const trimmed = name.trim();
if (!trimmed) { setName(group.name); return; }
if (trimmed === group.name) return;
diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsx
index b22b145d22..f329a7e658 100644
--- a/apps/mobile/src/session/TeammateHomeScreen.tsx
+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx
@@ -82,6 +82,9 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {
</View>
{navigation.saveFailed ? <Text accessibilityRole="alert" style={styles.notice}>{t('devices.companions.preferenceSaveFailed')}</Text> : null}
<TeammateList key={searchEpoch} {...roster} autoFocusSearch={searchEpoch > 0}
+ loading={roster.items.length + groups.items.length === 0 && (roster.loading || groups.loading)}
+ refreshing={roster.refreshing || groups.refreshing}
+ error={roster.error ?? groups.error}
onRefresh={() => { void roster.refresh(); if (groups.supported) void groups.refresh(); }}
onSelect={(item) => { void navigation.openTeammate(item); }}
groups={groups.supported || groups.items.length > 0 ? {
diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsx
index ab13076b75..699efe0fa2 100644
--- a/apps/mobile/src/session/TeammateList.tsx
+++ b/apps/mobile/src/session/TeammateList.tsx
@@ -122,7 +122,7 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, conn
</Pressable> : null}
</View>
{error ? <View style={styles.noticeRow}>
- <Text accessibilityRole="alert" style={[styles.notice, styles.noticeText]} testID="teammates.error">{t(items.length ? 'devices.companions.stale' : 'devices.resources.loadFailed')}</Text>
+ <Text accessibilityRole="alert" style={[styles.notice, styles.noticeText]} testID="teammates.error">{t(items.length + (groups?.items.length ?? 0) ? 'devices.companions.stale' : 'devices.resources.loadFailed')}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={t('devices.resources.retry')} disabled={refreshing}
onPress={onRefresh} style={styles.retry} testID="teammates.refresh">
{refreshing ? <ActivityIndicator color={colors.textSecondary} /> : <RefreshCw size={iconSize.sm} color={colors.textSecondary} />}
diff --git a/apps/mobile/src/session/botGroupNavigation.ts b/apps/mobile/src/session/botGroupNavigation.ts
index e28bd1dbce..bd215a8fab 100644
--- a/apps/mobile/src/session/botGroupNavigation.ts
+++ b/apps/mobile/src/session/botGroupNavigation.ts
@@ -1,9 +1,9 @@
import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';
-/** The group screen; a group lives on one computer, so the route always names it. */
+/** The group screen; server groups have no computer parameter; existing device routes remain compatible. */
export function botGroupRoute(host: RemoteResourceHostTarget, groupId: string) {
return {
pathname: '/companions/groups/[groupId]' as const,
- params: { groupId, deviceId: host.deviceId, deviceName: host.deviceName },
+ params: { groupId, ...(host.deviceId ? { deviceId: host.deviceId, deviceName: host.deviceName } : {}) },
};
}
diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.ts
index 7c204ad2e9..4f203ad66d 100644
--- a/apps/mobile/src/session/useBotGroupChat.ts
+++ b/apps/mobile/src/session/useBotGroupChat.ts
@@ -1,3 +1,4 @@
+import { useChatServerGroup } from '@/chat/useChatServer';
import { useCallback, useRef, useState } from 'react';
import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
@@ -28,6 +29,7 @@ const PUSH_COALESCE_MS = 150;
* through the same resource and are followed by a read.
*/
export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string) {
+ const server = useChatServerGroup(groupId, !host.deviceId);
const { invoke, openLink, status, connectionEpoch, presenceVersion, getPresenceAvailability, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
const { accountGeneration } = useAuth();
const { i18n } = useTranslation();
@@ -107,5 +109,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 { state: value, reload, act, online };
+ return !host.deviceId ? { ...server, server: true } : { state: value, reload, act, online, server: false, loadOlder: undefined, loadingOlder: false, media: undefined };
}
diff --git a/apps/mobile/src/session/useBotGroupRoster.ts b/apps/mobile/src/session/useBotGroupRoster.ts
index 778214c996..8cd9744686 100644
--- a/apps/mobile/src/session/useBotGroupRoster.ts
+++ b/apps/mobile/src/session/useBotGroupRoster.ts
@@ -1,3 +1,4 @@
+import { useChatServerRoster } from '@/chat/useChatServer';
import { BOT_GROUP_REMOTE_COLLECTION_ID, BOT_GROUP_REMOTE_RESOURCE_KIND } from '@cindy/maker-shared/botGroupChat';
import { useRevokedDevices } from '@/device-link/revokedDevicesStore';
import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';
@@ -6,20 +7,25 @@ import { useRemoteResourceList } from './useRemoteResourceList';
const NO_TARGETS: RemoteResourceHostTarget[] = [];
/**
- * Group chats of the computers whose manifest advertises them (`useTeammateRoster().groupTargets`).
- * The list re-reads on the host's `maker:remote-resources:changed` push like every resource list.
+ * Server memberships are primary; advertised computer collections preserve legacy access.
*/
export function useBotGroupRoster(targets: readonly RemoteResourceHostTarget[], enabled: boolean) {
+ const server = useChatServerRoster(enabled);
const revoked = useRevokedDevices();
const hosts = targets.length ? targets : NO_TARGETS;
const list = useRemoteResourceList(BOT_GROUP_REMOTE_COLLECTION_ID, hosts, enabled && hosts.length > 0);
- const items = list.items.filter((row) => row.item.ref.kind === BOT_GROUP_REMOTE_RESOURCE_KIND
- && !revoked.has(row.host.deviceId) && hosts.some((host) => host.deviceId === row.host.deviceId));
+ // A removed server membership must not reappear through a stale computer cache.
+ const serverIds = server.serverIds;
+ const legacy = list.items.filter((row) => row.item.ref.kind === BOT_GROUP_REMOTE_RESOURCE_KIND
+ && !serverIds.has(row.item.ref.id) && !revoked.has(row.host.deviceId) && hosts.some((host) => host.deviceId === row.host.deviceId));
return {
- items,
- /** The section shows only when some computer supports group chats. */
- supported: hosts.length > 0,
- isOnline: (host: RemoteResourceHostTarget) => !revoked.has(host.deviceId) && list.isOnline(host),
- refresh: list.refresh,
+ items: [...server.items, ...legacy],
+ loading: server.loading || (hosts.length > 0 && list.loading),
+ refreshing: server.refreshing || list.refreshing,
+ error: server.error ?? (hosts.length ? list.error : null),
+ /** Server membership discovery needs no supporting computer. */
+ supported: true,
+ isOnline: (host: RemoteResourceHostTarget) => !host.deviceId || (!revoked.has(host.deviceId) && list.isOnline(host)),
+ refresh: async () => { await Promise.all([server.refresh(), ...(hosts.length ? [list.refresh()] : [])]); },
};
}
diff --git a/apps/mobile/src/session/useTeammateRoster.ts b/apps/mobile/src/session/useTeammateRoster.ts
index 786e51ad49..f4539fc6ba 100644
--- a/apps/mobile/src/session/useTeammateRoster.ts
+++ b/apps/mobile/src/session/useTeammateRoster.ts
@@ -107,5 +107,5 @@ export function useTeammateRoster(enabled = true) {
authoritative: ready && !discovery.loading && !list.loading && !list.syncing && status === 'online' && !discovery.error && (!discovery.targets.length || !list.error),
loading: items.length === 0 && (!ready || list.loading),
refreshing: list.refreshing,
- error: ready ? discovery.error ?? list.error : null, refresh };
+ error: ready ? discovery.error ?? (discovery.targets.length ? list.error : null) : null, refresh };
}
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 8dc6f22b6a..ce3154f553 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -124,7 +124,7 @@
- 群设置:群名称、成员(添加与移出、设为负责人)、项目文件夹、「没有 @ 人的时候」回复方式、「发言方式」(自动/始终轮流)、删除群聊(二次确认)。
- 视觉遵循 [`DESIGN.md`](../design-rules/DESIGN.md);Light 与 Dark 同时实现。
-## 6. 当前限制
+## 6. 本地旧群的限制(服务器群见第 10 节)
- 仅同账号伙伴;群和伙伴都在同一台电脑上,不支持跨电脑、跨账号的群。手机端见第 8 节。
- 只属于单个任务的设置(模型、权限模式、计划模式、目标、协同、额外目录)不出现在群输入框:群没有单一任务,
@@ -213,7 +213,8 @@
## 8. 手机端(第三阶段)
-手机是控制端:群、伙伴与分工都在电脑上运行,手机只查看、发言和点按钮,所有规则仍由电脑判断。
+服务器群的列表、历史和消息同步由 Chat Server 负责,不以建群电脑在线为条件;伙伴执行仍依赖其运行电脑。
+以下 8.1–8.3 描述电脑 Remote Resource 兼容路径;手机直连接入见 8.4。
### 8.1 接入方式
@@ -248,6 +249,26 @@
同一台电脑同一个群的推送在系统层合并。不认识该深链的旧手机点开只进入 App。
- 聊天里的普通接话不推送。
- 只推送手机能看到的群:与群列表同一条规则(全部成员都是手机可见的伙伴),隐藏了成员的群不推送。
+
+### 8.4 手机直连 Chat Server
+
+- 伙伴列表使用当前账号所属 realm 的端点清单 `chatApiBaseUrl` 与既有 Bearer/401 续期;
+ 从 `/v1/conversations` 分页列出 `joined` 群,不注册伙伴或执行器,不触发本地旧群迁移。
+ 成员、历史范围及附件访问由服务器当前成员权限决定,不要求成员有本地伙伴 Profile。
+- 手机列表以服务器群 ID 去重,优先直连;电脑声明的 `bot-groups` 继续提供本地旧群和旧入口兼容。
+ 无电脑参数的群路由直连,带电脑参数的既有推送/创建路由仍走原资源协议。
+- 列表在前台订阅账号成员事件,每 30 秒核对群 head,仅重读变化群的快照;打开群后订阅该群事件,
+ 用字符串游标 ack,断线/前后台切换重连并重读授权快照。离开页面或切换账号即停止订阅。
+ 群详情分页读取主时间线;通知使已展示的历史窗口重新核权读取,撤权清空页面。
+- 直连页支持已有群的列表、成员查看、主时间线与旧历史、文字及 @ 发言;
+ 私有附件点击时重新授权,图片走已有看图器,其他文件打开短期签名 HTTPS URL,不转交账号 token。
+ 列表失败与空列表分开呈现,服务器故障使用服务器文案,不误报电脑离线。
+- 直连页暂不提供新建群、修改群设置/成员、上传附件、分工编排/审批、Thread 与表情操作;
+ 卡片保留服务器可读 fallback。原电脑兼容入口保留既有操作,不能把两条入口的能力混为一谈。
+ 同账号另一台 Desktop 已经通过自身 Chat Server 适配器访问群,不应依赖远程伙伴列表再聚合一遍。
+- 本次仅改 Mobile JS,无原生 fingerprint 或服务端 schema 变更。客户端代码接通不代表服务器部署与真机验收;
+ 发布需确认当前 realm 的 Chat Server 可达、既有账号 token 可鉴权,再从手机伙伴列表验收电脑离线场景。
+
## 10. Chat Server 多账号群的授权补充(2026-10-03)
Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授权」。正式群聊统一使用 Chat Server;已有本地群及消息自动迁移,不保留并行本地群入口。Agent 工作目录与私人资料仍留在执行端,外部成员的访问继续受下述授权边界约束。服务端群历史与 Agent 本机/云端执行分离,人和伙伴共用成员、群角色和消息合同,国内与国际账号可以互邀。