Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): recover chat endpoint discovery with account identity
zqchris1a16e6843f38
diff --git a/apps/mobile/src/__tests__/TeammateList.test.tsx b/apps/mobile/src/__tests__/TeammateList.test.tsxindex b742e7a927..7487be9561 100644--- a/apps/mobile/src/__tests__/TeammateList.test.tsx+++ b/apps/mobile/src/__tests__/TeammateList.test.tsx@@ -43,6 +43,11 @@ vi.mock('@/device-link/remoteResourceCache', () => ({ isRemoteResourceUnread: ()vi.mock('@/session/sessionList', () => ({ formatRemoteSessionSidebarTime: () => '' }));vi.mock('@/utils/useMinuteNow', () => ({ useMinuteNow: () => Date.now() }));import { TeammateList } from '../session/TeammateList';+it('shows the localized cloud configuration error even alongside cached teammate rows', async () => {+ await act(async () => root.render(el(TeammateList, { items: [item], error: 'CHAT_ENDPOINT_UNAVAILABLE', isOnline: () => false,+ loading: false, refreshing: false, onRefresh: vi.fn(), onSelect: vi.fn(), embedded: true })));+ expect(node.querySelector('[data-testid="teammates.error"]')?.textContent).toBe('groupChat.server.endpointUnavailable');+});const item = { key: 'host:bot', host: { deviceId: 'host', deviceName: 'Computer identity' }, item: {ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', links: [], display: { title: 'Mimi', preview: 'Last reply' },} };diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex a372acf97f..3383ca44bd 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -11,6 +11,14 @@ const snapshot = (): ChatSnapshot => ({ room: room(), cursor: '9007199254741099'] });describe('direct Chat Server client', () => {+ it('uses the account human actor and rejects a companion identity', async () => {+ const request = vi.fn().mockResolvedValueOnce({ actor: { id: id(10), kind: 'human' } })+ .mockResolvedValueOnce({ actor: { id: id(11), kind: 'bot' } });+ const client = createChatServerClient(request);+ expect(await client.me()).toBe(id(10));+ await expect(client.me()).rejects.toThrow('INVALID_CHAT_IDENTITY');+ expect(request.mock.calls.every(([path]) => path === '/me')).toBe(true);+ });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)]);diff --git a/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx b/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsxnew file mode 100644index 0000000000..e23588d629--- /dev/null+++ b/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx@@ -0,0 +1,128 @@+// @vitest-environment jsdom+import { act, createElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { getBundledEndpointManifest } from '@cindy/maker-shared/client-endpoints';++const h = vi.hoisted(() => ({+ auth: { user: { id: 'phone-owner' }, accountGeneration: 1, apiFetch: vi.fn(), getAccessToken: vi.fn() },+ storage: new Map<string, string>(),+ sockets: [] as any[],+}));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {+ getItem: async (key: string) => h.storage.get(key) ?? null,+ setItem: async (key: string, value: string) => { h.storage.set(key, value); },+} }));+vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));+vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (fn: any) => useEffect(fn, [fn]) }; });++const bases = { cn: 'https://hotfix.cindy.com.cn/cindy', global: 'https://hotfix.cindy.app/cindy' };+const texts = Object.fromEntries(Object.entries(bases).map(([region, base]) => [region,+ process.env.CINDY_CHAT_PUBLIC_MANIFEST_DIR+ ? readFileSync(join(process.env.CINDY_CHAT_PUBLIC_MANIFEST_DIR, `${region}.json`), 'utf8')+ : getBundledEndpointManifest(region as 'cn' | 'global', `${base}/endpoint.json`)!,+])) as Record<'cn' | 'global', string>;+const roomId = '00000000-0000-4000-8000-000000000001';+const self = '00000000-0000-4000-8000-000000000002';+const room = { id: roomId, kind: 'group', state: 'joined', name: 'Fixture', archived: false,+ revision: 1, head: '1', created_at: '2026-10-09', updated_at: '2026-10-09', response_mode: 'all', speaking_mode: 'auto' };+let root: Root | undefined;+let roster: any;+let group: any;+let hooks: typeof import('@/chat/useChatServer');+function Probe() { roster = hooks.useChatServerRoster(true); group = hooks.useChatServerGroup(roomId, true); 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.resetModules(); vi.clearAllMocks(); h.storage.clear(); h.sockets = [];+ vi.stubGlobal('__DEV__', false);+ vi.stubEnv('EXPO_PUBLIC_CINDY_AUTH_REGION', 'global');+ vi.stubEnv('EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL', bases.global);+ vi.stubEnv('EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL', bases.cn);+ h.auth.user = { id: 'phone-owner' }; h.auth.accountGeneration = 1;+ h.auth.getAccessToken.mockImplementation(async () => `fixture-token:${h.auth.user.id}`);+ h.auth.apiFetch.mockImplementation(async (path: string, options: any) => {+ options.assertCurrent();+ if (path === '/v1/me') return { actor: { id: self, kind: 'human' } };+ if (path.startsWith('/v1/conversations?')) return [room];+ if (path.endsWith('/snapshot')) return { room, members: [], messages: [], cursor: '1' };+ if (path.includes('/messages?')) return [];+ if (path.includes('/changes?')) return { head: '1' };+ if (options.method === 'POST') return { id: self };+ throw new Error('Unexpected fixture request');+ });+ vi.stubGlobal('WebSocket', class {+ readyState = 1; onopen?: Function; onmessage?: Function; onclose?: Function; onerror?: Function;+ send = vi.fn(); close = vi.fn();+ constructor(public url: string) { h.sockets.push(this); }+ });+});+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.useRealTimers(); });++it.each(['cn', 'global'] as const)('release %s discovery feeds HTTP, WS and the phone owner identity', async region => {+ vi.stubEnv('EXPO_PUBLIC_CINDY_AUTH_REGION', region);+ vi.stubEnv('EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL', bases[region]);+ vi.stubEnv('EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL', bases[region === 'cn' ? 'global' : 'cn']);+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, text: async () => texts[region] })));+ const startup = await import('@/config/clientEndpointStartup');+ const env = await import('@/config/env');+ expect(() => env.getMobileEndpointForRealm(region, 'chatApiBaseUrl')).toThrow();+ expect(await startup.runStartupEndpointResolve()).toEqual({ ok: true, source: 'cdn' });+ hooks = await import('@/chat/useChatServer'); await render();+ const endpoint = JSON.parse(texts[region]).chatApiBaseUrl;+ expect(roster.items).toHaveLength(1); expect(group.state.kind).toBe('ready');+ expect(h.auth.apiFetch.mock.calls.every(([, options]) => options.baseUrl === endpoint)).toBe(true);+ expect(h.sockets.length).toBeGreaterThan(0);+ const ws = new URL(endpoint); ws.protocol = 'wss:'; ws.pathname = '/v1/ws';+ expect(h.sockets.every(socket => socket.url === ws.href)).toBe(true);+ await act(async () => h.sockets.forEach(socket => socket.onopen({})));+ expect(h.sockets[0].send).toHaveBeenCalledWith(JSON.stringify({ type: 'auth', token: 'fixture-token:phone-owner' }));+ await act(async () => { await group.act('send', { text: 'fixture', clientId: 'fixture-operation', mentions: { all: false, botIds: [] } }); });+ const sent = h.auth.apiFetch.mock.calls.find(([path, options]) => path.endsWith('/messages') && options.method === 'POST')!;+ expect(sent[1].body).toEqual({ operationId: 'fixture-operation', content: [{ type: 'text', text: 'fixture' }], mentions: [] });+ const oldSockets = [...h.sockets];+ const other = region === 'cn' ? 'global' : 'cn';+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, text: async () => texts[other] })));+ await env.loadMobileEndpointsForRealm(other); env.activateMobileSessionRealm(other);+ h.auth.user = { id: 'another-phone-owner' }; h.auth.accountGeneration++;+ h.auth.apiFetch.mockClear(); await render();+ expect(oldSockets.every(socket => socket.close.mock.calls.length > 0)).toBe(true);+ expect(h.auth.apiFetch.mock.calls.every(([, options]) => options.baseUrl === JSON.parse(texts[other]).chatApiBaseUrl)).toBe(true);+ await act(async () => h.sockets.filter(socket => !oldSockets.includes(socket)).forEach(socket => socket.onopen({})));+ expect(h.sockets.at(-1).send).toHaveBeenCalledWith(JSON.stringify({ type: 'auth', token: 'fixture-token:another-phone-owner' }));+});++it('old cached discovery without chat reports configuration failure and retries the trusted source', async () => {+ vi.useFakeTimers();+ const sourceUrl = `${bases.global}/endpoint.json`;+ const old = JSON.parse(texts.global); delete old.chatApiBaseUrl;+ h.storage.set(`cindy.mobile.endpoint-manifest.v1.global.${encodeURIComponent(sourceUrl)}`, JSON.stringify({+ savedAt: '2026-10-09T00:00:00Z', sourceUrl, manifestText: JSON.stringify(old),+ }));+ const fetch = vi.fn().mockRejectedValue(new TypeError('offline')); vi.stubGlobal('fetch', fetch);+ const startup = await import('@/config/clientEndpointStartup');+ expect(await startup.runStartupEndpointResolve()).toEqual({ ok: true, source: 'cache' });+ hooks = await import('@/chat/useChatServer'); await render();+ expect(roster.error).toBe('CHAT_ENDPOINT_UNAVAILABLE');+ expect(group.state).toEqual({ kind: 'error', message: 'CHAT_ENDPOINT_UNAVAILABLE' });+ expect(h.auth.apiFetch).not.toHaveBeenCalled(); expect(h.sockets).toHaveLength(0);+ fetch.mockResolvedValue({ ok: true, text: async () => texts.global });+ await act(async () => { await roster.refresh(); group.reload(); });+ expect(roster.error).toBeNull(); expect(group.state.kind).toBe('ready');+ await act(async () => { await vi.advanceTimersByTimeAsync(30000); });+ expect(h.sockets.length).toBeGreaterThan(0);+});++it('invalid discovered chat URL blocks startup; a corrected trusted manifest recovers', async () => {+ const manifest = JSON.parse(texts.global); manifest.chatApiBaseUrl = 'http://chat.example.invalid';+ const fetch = vi.fn(async () => ({ ok: true, text: async () => JSON.stringify(manifest) }));+ vi.stubGlobal('fetch', fetch);+ const startup = await import('@/config/clientEndpointStartup');+ expect(await startup.runStartupEndpointResolve()).toMatchObject({ ok: false });+ expect(h.auth.apiFetch).not.toHaveBeenCalled();+ manifest.chatApiBaseUrl = JSON.parse(texts.global).chatApiBaseUrl;+ expect(await startup.runStartupEndpointResolve()).toEqual({ ok: true, source: 'cdn' });+});diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex f61abcae32..d3a68cd6ef 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -15,7 +15,7 @@ vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventLisvi.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('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global', getMobileEndpointForRealm: () => 'https://chat.example.invalid', loadMobileEndpointsForRealm: vi.fn() }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));vi.mock('@/device-link/revokedDevicesStore', () => ({ useRevokedDevices: () => new Set() }));vi.mock('@/session/useRemoteResourceList', () => ({ useRemoteResourceList: () => h.legacy }));@@ -41,7 +41,7 @@ beforeEach(() => {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 === '/v1/me') return { actor: { id: self, kind: 'human' } };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 };@@ -68,14 +68,14 @@ it('deduplicates server copies from multiple computers while retaining a local lh.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 } } : []);+ h.auth.apiFetch.mockImplementation(async path => path === '/v1/me' ? { actor: { id: self, kind: 'human' } } : []);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' } : []);+ h.auth.apiFetch.mockImplementation(async path => path === '/v1/me' ? { actor: { id: self, kind: 'human' } } : 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 }));@@ -92,7 +92,7 @@ it('ignores an old account response after switching accounts', async () => {it('does not restore unverified computer cache rows on a cold offline mount', async () => {h.targets = [{ deviceId: 'mac', deviceName: 'Mac' }];h.legacy.items = [{ key: 'cached', host: h.targets[0], item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id }, revision: '1', display: { title: 'Removed' }, links: [] } }];- h.auth.apiFetch.mockImplementation(async path => path === '/v1/me' ? { actor: { id: self } } : []);+ h.auth.apiFetch.mockImplementation(async path => path === '/v1/me' ? { actor: { id: self, kind: 'human' } } : []);await render(); expect(roster.items).toEqual([]);});diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex f755fb2c89..c2bd06cbff 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -129,7 +129,11 @@ export function createChatServerClient(request: ChatRequest) {} while (after);return [...rooms.values()];},- async me(): Promise<string> { return chatId((await request<{ actor: { id: string } }>('/me')).actor.id); },+ async me(): Promise<string> {+ const { actor } = await request<{ actor: { id: string; kind: string } }>('/me');+ if (actor.kind !== 'human') throw new Error('INVALID_CHAT_IDENTITY');+ return chatId(actor.id);+ },async snapshot(roomId: string): Promise<ChatSnapshot> {return request(`/conversations/${chatId(roomId)}/snapshot`);},diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex 7177ff2bc5..5a1d64b8e4 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -4,7 +4,7 @@ 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 { getActiveMobileSessionRealm, getMobileEndpointForRealm, loadMobileEndpointsForRealm } from '@/config/env';import { markRemoteResourceRead } from '@/device-link/remoteResourceCache';import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';import type { BotGroupChatState } from '@/session/useBotGroupChat';@@ -19,16 +19,32 @@ function useChatClient() {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 realm = getActiveMobileSessionRealm();+ const current = () => mounted.current && active.current === owner && getActiveMobileSessionRealm() === realm;const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };- const baseUrl = () => chatHttpsUrl(getMobileEndpointForRealm(getActiveMobileSessionRealm(), 'chatApiBaseUrl')).replace(/\/$/, '');+ const baseUrl = () => {+ try { return chatHttpsUrl(getMobileEndpointForRealm(realm, 'chatApiBaseUrl')).replace(/\/$/, ''); }+ catch { throw new Error('CHAT_ENDPOINT_UNAVAILABLE'); }+ };+ let discovering: Promise<string> | undefined;+ const endpoint = async () => {+ check();+ try { return baseUrl(); } catch { /* An older snapshot may predate the chat endpoint. */ }+ discovering ??= loadMobileEndpointsForRealm(realm, { refresh: true })+ .then(() => { check(); return baseUrl(); })+ .catch(() => { check(); throw new Error('CHAT_ENDPOINT_UNAVAILABLE'); })+ .finally(() => { discovering = undefined; });+ return discovering;+ };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 });+ const url = await endpoint(); check();+ const result = await deps.current.apiFetch<T>(`/v1${path}`, { baseUrl: url, method, cache: 'no-store', ...(body !== undefined ? { body } : {}), assertCurrent: check });check(); return result;};- return { owner, userId: auth.user?.id ?? '', current, baseUrl, request, client: createChatServerClient(request),- token: async () => { check(); await request('/me'); const token = await deps.current.getAccessToken(); check(); return token; }, enabled: !!auth.user };+ const client = createChatServerClient(request);+ return { owner, userId: auth.user?.id ?? '', current, baseUrl, endpoint, request, client,+ token: async () => { check(); await client.me(); const token = await deps.current.getAccessToken(); check(); return token; }, enabled: !!auth.user };}, [owner, !!auth.user]);}@@ -76,22 +92,28 @@ export function useChatServerRoster(enabled: boolean) {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' }));+ if (!run.isStale() && api.current()) setState(old => ({ owner: api.owner, rooms: old.owner === api.owner && !chatAccessLost(error) ? old.rooms : [], loading: false, refreshing: false, error: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_LIST_FAILED' }));}}, api.owner);const refresh = useCallback(() => read({ reason: 'visible' }), [read]);useFocusEffect(useCallback(() => {if (!enabled || !api.enabled) return;let stop: (() => void) | undefined;+ let subscribed = false;let poll: ReturnType<typeof setInterval> | undefined;const start = () => {- stop?.(); clearInterval(poll);+ stop?.(); subscribed = false; 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),+ poll = setInterval(() => { if (!subscribed) start(); else void read({ reason: 'poll' }); }, 30000);+ let cancelled = false;+ let disposeSocket: (() => void) | undefined;+ stop = () => { cancelled = true; disposeSocket?.(); };+ void api.endpoint().then(baseUrl => {+ if (cancelled || !api.current()) return;+ disposeSocket = subscribeChatServer({ 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); }@@ -101,7 +123,8 @@ export function useChatServerRoster(enabled: boolean) {}await read({ reason: 'connected' });return { scope: `actor:${actorId}`, cursor };- }, changed: () => { void read({ reason: 'changed' }); }, unavailable: () => {} }); } catch { /* HTTP read presents endpoint errors. */ }+ }, changed: () => { void read({ reason: 'changed' }); }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; } });+ }).catch(() => {}); // HTTP read presents endpoint errors.};start();const foreground = AppState.addEventListener('change', value => { if (value === 'active') start(); else { stop?.(); clearInterval(poll); } });@@ -137,7 +160,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {} 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 }));+ 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);const reload = useCallback(() => { void request({ reason: 'changed' }); }, [request]);@@ -152,13 +175,19 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {reload();// A failed read after an acknowledged event must recover even without another event.recovery = setInterval(() => { if (!subscribed) start(); else if (!freshRead.current) reload(); }, 30000);- try { stop = subscribeChatServer({ baseUrl: api.baseUrl(), token: api.token, current: () => api.current() && active.current === identity,+ let cancelled = false;+ let disposeSocket: (() => void) | undefined;+ stop = () => { cancelled = true; disposeSocket?.(); };+ void api.endpoint().then(baseUrl => {+ if (cancelled || !api.current() || active.current !== identity) return;+ disposeSocket = subscribeChatServer({ 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, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; if (api.current() && active.current === identity) setState(old => ({ ...old, online: false })); } }); } catch { /* Read presents errors. */ }+ }, changed: reload, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; if (api.current() && active.current === identity) setState(old => ({ ...old, online: false })); } });+ }).catch(() => {}); // Read presents endpoint errors.};start();const foreground = AppState.addEventListener('change', value => { if (value === 'active') start(); else { stop?.(); clearInterval(recovery); } });diff --git a/apps/mobile/src/config/env.ts b/apps/mobile/src/config/env.tsindex 8793a7755e..842adf6907 100644--- a/apps/mobile/src/config/env.ts+++ b/apps/mobile/src/config/env.ts@@ -534,9 +534,10 @@ export function getActiveMobileSessionRealm(): ClientEndpointRegion {export async function loadMobileEndpointsForRealm(region: ClientEndpointRegion,+ options: { refresh?: boolean } = {},): Promise<ClientEndpointMap> {const cached = realmEndpointCache.get(region);- if (cached) return cached;+ if (cached && !options.refresh) return cached;const baseUrl = trustedMobileRealmManifestBaseUrls()[region];if (!baseUrl) {throw new Error('realm-manifest-url-unavailable');diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex 3bb7351c0f..f640048d59 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -180,6 +180,7 @@"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"+ "previewUnavailable": "Preview unavailable",+ "endpointUnavailable": "Group chat service configuration is unavailable. Please retry."}}diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex a09d3c4154..2d161ddf5d 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -180,6 +180,7 @@"loadFailed": "グループチャットを読み込めません。もう一度お試しください。","loadOlder": "以前のメッセージを読み込む","attachmentFailed": "添付ファイルを開けませんでした。もう一度お試しください。",- "previewUnavailable": "プレビューを読み込めません"+ "previewUnavailable": "プレビューを読み込めません",+ "endpointUnavailable": "グループチャットのサービス設定を利用できません。再試行してください。"}}diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex a62ab8e68a..5951ae232c 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -180,6 +180,7 @@"loadFailed": "그룹 채팅을 불러올 수 없습니다. 다시 시도해 주세요.","loadOlder": "이전 메시지 불러오기","attachmentFailed": "첨부 파일을 열지 못했습니다. 다시 시도해 주세요.",- "previewUnavailable": "미리보기를 불러올 수 없습니다"+ "previewUnavailable": "미리보기를 불러올 수 없습니다",+ "endpointUnavailable": "그룹 채팅 서비스 설정을 사용할 수 없습니다. 다시 시도해 주세요."}}diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex 4ffba2ed5f..908b1b9431 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -180,6 +180,7 @@"loadFailed": "暂时无法读取群聊,请重试。","loadOlder": "加载更早的消息","attachmentFailed": "附件打开失败,请重试。",- "previewUnavailable": "暂时无法读取消息预览"+ "previewUnavailable": "暂时无法读取消息预览",+ "endpointUnavailable": "群聊服务配置暂不可用,请重试。"}}diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex 64a5f90a14..e9d3f5f478 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -180,6 +180,7 @@"loadFailed": "暫時無法讀取群聊,請重試。","loadOlder": "載入更早的訊息","attachmentFailed": "附件開啟失敗,請重試。",- "previewUnavailable": "暫時無法讀取訊息預覽"+ "previewUnavailable": "暫時無法讀取訊息預覽",+ "endpointUnavailable": "群聊服務設定暫時無法使用,請重試。"}}diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex 8aff8547bd..6f3f1e7fa2 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -272,10 +272,13 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceIdbody = <View style={styles.center}><ActivityIndicator color={colors.textSecondary} /></View>;} else if (chat.state.kind !== 'ready' || !group) {const failed = chat.state.kind === 'error';+ const errorCopyKey = !failed ? 'groupChat.unavailableDescription'+ : !chat.server ? 'groupChat.loadFailedDescription'+ : chat.state.kind === 'error' && chat.state.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? 'groupChat.server.endpointUnavailable' : 'groupChat.server.loadFailed';body = <View style={styles.center}><MainWindowEmptyState centered testID={failed ? 'botGroup.loadFailed' : 'botGroup.unavailable'}title={t(failed ? 'groupChat.loadFailedTitle' : 'groupChat.unavailableTitle')}- copy={t(failed ? (chat.server ? 'groupChat.server.loadFailed' : 'groupChat.loadFailedDescription') : 'groupChat.unavailableDescription')}>+ copy={t(errorCopyKey)}><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}diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsxindex f329a7e658..90920b5a31 100644--- a/apps/mobile/src/session/TeammateHomeScreen.tsx+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx@@ -84,7 +84,7 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {<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}+ error={groups.error ?? roster.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.tsxindex 699efe0fa2..97c24cdfc6 100644--- a/apps/mobile/src/session/TeammateList.tsx+++ b/apps/mobile/src/session/TeammateList.tsx@@ -106,6 +106,9 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, connreturn names;}, [items, i18n.language]);const searchLabel = t(groups ? 'devices.companions.searchWithGroups' : 'devices.companions.search');+ const errorKey = error === 'CHAT_ENDPOINT_UNAVAILABLE' ? 'groupChat.server.endpointUnavailable'+ : error === 'CHAT_LIST_FAILED' ? 'groupChat.server.loadFailed'+ : items.length + (groups?.items.length ?? 0) ? 'devices.companions.stale' : 'devices.resources.loadFailed';const header = <View style={styles.controls}><View style={styles.search}><Search size={iconSize.md} color={colors.textPlaceholder} strokeWidth={iconStroke.regular} />@@ -122,7 +125,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 + (groups?.items.length ?? 0) ? 'devices.companions.stale' : 'devices.resources.loadFailed')}</Text>+ <Text accessibilityRole="alert" style={[styles.notice, styles.noticeText]} testID="teammates.error">{t(errorKey)}</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/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex c7eed4cb7e..b8020eef58 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -255,6 +255,10 @@- 伙伴列表使用当前账号所属 realm 的端点清单 `chatApiBaseUrl` 与既有 Bearer/401 续期;从 `/v1/conversations` 分页列出 `joined` 群,不注册伙伴或执行器,不触发本地旧群迁移。成员、历史范围及附件访问由服务器当前成员权限决定,不要求成员有本地伙伴 Profile。+ 手机使用自身登录账号的 human actor,不指定代演身份或借用电脑 token;HTTP 与 WS 共用当前 realm 的受信清单地址。+ 正式包由启动端点闸门解析 CDN 清单,网络故障沿用本区已校验缓存/随包清单;非法清单阻断并可重试。+ 旧清单缺少群聊地址时显示本地化配置错误,重试重新读取同区受信清单,恢复后重新订阅;不把缺配置视为空群列表。+ `check:endpoints` 对两份生产正本检查群聊地址非空 HTTPS,并阻止直连代码硬编码生产地址。- 手机列表以服务器群 ID 去重,优先直连;电脑声明的 `bot-groups` 继续提供本地旧群和旧入口兼容。旧缓存无法区分服务器群与本地群,因此兼容群行须有电脑当前连接代次的成功列群回包,断线缓存不能作为成员权限依据。无电脑参数的群路由直连,带电脑参数的既有推送/创建路由仍走原资源协议。diff --git a/scripts/__tests__/endpoint-consistency.test.mjs b/scripts/__tests__/endpoint-consistency.test.mjsindex f632d0b270..fbe4587e23 100644--- a/scripts/__tests__/endpoint-consistency.test.mjs+++ b/scripts/__tests__/endpoint-consistency.test.mjs@@ -2,7 +2,19 @@ import assert from 'node:assert/strict';import fs from 'node:fs';import { test } from 'node:test';-import { resolveEasBuildProfileEnv } from '../check-endpoint-literals.mjs';+import { resolveEasBuildProfileEnv, validatePublishedChatEndpoint } from '../check-endpoint-literals.mjs';++test('生产端点清单的群聊地址不能漏发或携带凭据', () => {+ for (const file of ['endpoint.json', 'endpoint.global.json']) {+ const manifest = JSON.parse(fs.readFileSync(new URL(`../../config/${file}`, import.meta.url), 'utf8'));+ assert.doesNotThrow(() => validatePublishedChatEndpoint(manifest));+ const missing = { ...manifest }; delete missing.chatApiBaseUrl;+ assert.throws(() => validatePublishedChatEndpoint(missing), /chatApiBaseUrl/);+ }+ for (const url of ['', 'http://chat.example.invalid', 'https://[email protected]', 'https://chat.example.invalid?key=secret']) {+ assert.throws(() => validatePublishedChatEndpoint({ chatApiBaseUrl: url }), /chatApiBaseUrl/);+ }+});test('提交的 EAS build profiles 不包含生产端点 env(含 extends)', () => {const eas = JSON.parse(diff --git a/scripts/check-endpoint-literals.mjs b/scripts/check-endpoint-literals.mjsindex 097f421a7e..142234d21c 100644--- a/scripts/check-endpoint-literals.mjs+++ b/scripts/check-endpoint-literals.mjs@@ -28,6 +28,9 @@ const CONTROLLED_SOURCE_FILES = Object.freeze(['apps/desktop/src/main/clientEndpointsService.ts','apps/mobile/src/config/env.ts','apps/mobile/src/config/clientEndpointStartup.ts',+ 'apps/mobile/src/chat/useChatServer.ts',+ 'apps/mobile/src/chat/chatServerClient.ts',+ 'apps/mobile/src/chat/chatServerSubscription.ts','apps/mobile/eas.json','packages/embedding-client/src/client.ts','packages/embedding-client/src/types.ts',@@ -76,9 +79,23 @@ function findAbsoluteOrigins(content) {].map((match) => match[0].toLowerCase());}+/** Production manifests must publish the endpoint required by the mobile direct client. */+export function validatePublishedChatEndpoint(manifest) {+ let url;+ try { url = new URL(manifest?.chatApiBaseUrl); } catch { throw new Error('chatApiBaseUrl must be a nonempty HTTPS URL'); }+ if (url.protocol !== 'https:' || !url.hostname || url.username || url.password || url.search || url.hash) {+ throw new Error('chatApiBaseUrl must be an HTTPS base URL without credentials, query or fragment');+ }+}+function main() {const errors = [];+ for (const file of ['config/endpoint.json', 'config/endpoint.global.json']) {+ try { validatePublishedChatEndpoint(JSON.parse(fs.readFileSync(path.join(REPO_ROOT, file), 'utf8'))); }+ catch (error) { errors.push(`${file}: ${error.message}`); }+ }+for (const file of CONTROLLED_SOURCE_FILES) {const content = fs.readFileSync(path.join(REPO_ROOT, file), 'utf8');for (const origin of findAbsoluteOrigins(content)) {