Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): restore companion and group lists with cached avatars on startup (#6503)
Chris Zhang25c5c308de57
diff --git a/apps/mobile/src/__tests__/BotGroupAvatars.test.tsx b/apps/mobile/src/__tests__/BotGroupAvatars.test.tsxindex a443503bce..0a3e30a575 100644--- a/apps/mobile/src/__tests__/BotGroupAvatars.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupAvatars.test.tsx@@ -5,7 +5,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => {// React Native bundles preset PNG requires; replace only that native asset boundary.vi.stubGlobal('require', (path: string) => { if (path.endsWith('.png')) return 1; throw new Error('Unexpected native asset'); });- return { remoteMedia: vi.fn<(media: unknown, deps: unknown, options: unknown) => Promise<{ url: string; previewable: boolean; mimeType: string }>>(async () => { throw new Error('Computer media only'); }), invoke: vi.fn(), failImage: null as null | (() => void),+ return { remoteMedia: vi.fn<(media: unknown, deps: unknown, options: unknown) => Promise<{ url: string; previewable: boolean; mimeType: string }>>(async () => { throw new Error('Computer media only'); }), invoke: vi.fn(), avatars: new Map<string, string>(), store: false, failImage: null as null | (() => void),auth: { user: { id: 'owner' }, accountGeneration: 1, apiFetch: vi.fn() } };});vi.mock('react-native', async () => {@@ -22,7 +22,7 @@ vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke }) }));vi.mock('@/device-link/mobileMakerTransport', () => ({ createMobileMakerTransport: () => ({ fetchRemoteMedia: vi.fn() }) }));vi.mock('@/session/remoteMedia', () => ({ resolveMobileRemoteMedia: h.remoteMedia }));-vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.invalid' }));+vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.invalid', getActiveMobileSessionRealm: () => 'global' }));vi.mock('@/theme', async () => ({ ...await import('@/theme/tokens'), useTheme: () => ({ colors: {} }), useThemedStyles: (factory: any) => factory({}) }));vi.mock('lucide-react-native', () => ({ Users: () => null }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));@@ -32,13 +32,17 @@ vi.mock('@/session/CompanionListRow', () => ({ CompanionListRow: ({ avatar }: anvi.mock('@/session/CompanionPresenceRing', () => ({ CompanionPresenceRing: () => null }));vi.mock('@/device-link/remoteResourceCache', () => ({ cachedBotItem: () => null, readRemoteResourceSnapshot: async () => ({}),remoteResourceCacheRevision: () => 0, subscribeRemoteResourceCache: () => () => {}, isRemoteResourceUnread: () => false }));+vi.mock('@/device-link/peerFileCache', () => ({ createPeerFileCache: async (owner: string) => ({+ lookupAvatar: async (id: string) => { const uri = h.avatars.get(owner + id); return uri ? { uri } : null; },+ storeAvatar: async (id: string, _uri: string, _mime: string, active: () => boolean) => { if (!h.store || !active()) return false; h.avatars.set(owner + id, 'file:///cached-avatar.png'); return true; },+}) }));import { chatGroupView, chatRoomRow, type ChatSnapshot } from '@/chat/chatServerClient';import { BotGroupAvatar, BotGroupDuoAvatar, useBotGroupIdentities } from '@/session/BotGroupAvatars';import { BotGroupListRow } from '@/session/BotGroupList';Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });let root: Root | undefined;-beforeEach(() => { h.remoteMedia.mockClear(); h.invoke.mockClear(); });+beforeEach(() => { h.avatars.clear(); h.store = false; h.auth.user.id = 'owner'; h.auth.accountGeneration = 1; h.remoteMedia.mockClear(); h.invoke.mockClear(); });afterEach(() => { act(() => root?.unmount()); root = undefined; vi.unstubAllGlobals(); });// Product rule §5/§8.2: previous coverage only exercised single-member image sources.@@ -124,3 +128,22 @@ it.each(['https://avatars.example.invalid/bot.png', 'cindy://avatar/preset/cindyexpect(h.remoteMedia).not.toHaveBeenCalled(); expect(h.invoke).not.toHaveBeenCalled();expect(host.querySelectorAll('img').length).toBe(avatar === '🦊' ? 0 : 1);});++// Cold/offline remount uses the same production avatar component as companion and+// group rows. Existing tests only covered live resolver rendering (unit).+it.each(['media', 'public'] as const)('restores a %s avatar before checking presence and isolates accounts', async (kind) => {+ h.store = true;+ h.remoteMedia.mockResolvedValue({ url: 'data:image/png;base64,fixture', previewable: true, mimeType: 'image/png' });+ const host = document.createElement('div'); root = createRoot(host);+ const identity = { botId: 'bot', name: 'Teammate', ...(kind === 'public' ? { avatarUrl: 'https://avatars.example.invalid/saved.png' }+ : { avatar: { kind: 'media', value: 'cindy-media://blobs/saved.png', fallbackText: 'T' } }) };+ await act(async () => root!.render(createElement(BotGroupAvatar, { deviceId: 'mac', identity, size: 28, online: true })));+ expect(host.querySelector('img')?.getAttribute('src')).toBe('file:///cached-avatar.png');+ act(() => root!.unmount()); root = createRoot(host); h.remoteMedia.mockClear();+ await act(async () => root!.render(createElement(BotGroupAvatar, { deviceId: 'mac', identity, size: 28, online: false })));+ expect(host.querySelector('img')?.getAttribute('src')).toBe('file:///cached-avatar.png');+ expect(h.remoteMedia).not.toHaveBeenCalled();+ h.store = false; h.auth.user.id = 'other'; h.auth.accountGeneration++;+ await act(async () => root!.render(createElement(BotGroupAvatar, { deviceId: 'mac', identity, size: 28, online: false })));+ expect(host.querySelector('img')?.getAttribute('src')).not.toBe('file:///cached-avatar.png');+});diff --git a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsxindex 176c564f38..c26ab0b0b2 100644--- a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx+++ b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx@@ -97,15 +97,22 @@ beforeEach(() => {});afterEach(() => { act(() => root?.unmount()); root = undefined; });describe('teammate home entry', () => {- it('hides an unverified cached roster while keeping cloud-only rows available', async () => {+ it('keeps a known conversation while discovery is pending instead of replacing it with a read-only cloud row', async () => {+ const known: HostedRemoteCollectionItem = { ...teammate, item: { ...teammate.item,+ display: { title: 'Writer', preview: 'Latest reply', timestamp: 123 },+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'existing-chat' } }] } };+ h.roster.items = [known];h.roster.loading = true; h.roster.error = null;await render();- expect(h.list.items).toEqual([]);+ expect(h.list.items).toEqual([known]);h.cloud.supported = true;h.cloud.actors = [{ id: 'actor', kind: 'bot', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'mac' }];await render();expect(h.list.items).toHaveLength(1);- expect(h.list.items[0].item.revision).toBe('cloud');+ expect(h.list.items[0]).toBe(known);+ await act(async () => h.list.onSelect(h.list.items[0]));+ expect(h.nav.openTeammate).toHaveBeenCalledWith(known);+ expect(h.push).not.toHaveBeenCalled();});it('lands on the roster and never opens the remembered teammate on its own', async () => {// A remembered, online teammate on a settled roster used to be reopened at launch (#4912); thediff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex 77d5c62415..14bb7e1401 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -8,9 +8,10 @@ const h = vi.hoisted(() => ({getPresenceAvailability: (): boolean => false, onRemoteResourceChanged: () => () => {}, subscribe: vi.fn(), unsubscribe: vi.fn() },legacy: { items: [] as any[], loading: false, refreshing: false, error: null as string | null, isOnline: vi.fn(() => false), refresh: vi.fn() },targets: [] as { deviceId: string; deviceName: string }[],+ disk: new Map<string, string>(),foreground: new Set<(state: string) => void>(),}));-vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async () => null), setItem: vi.fn(async () => {}), removeItem: vi.fn(async () => {}), getAllKeys: vi.fn(async () => []), multiRemove: vi.fn(async () => {}) } }));+vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async (key: string) => h.disk.get(key) ?? null), setItem: vi.fn(async (key: string, value: string) => { h.disk.set(key, value); }), removeItem: vi.fn(async (key: string) => { h.disk.delete(key); }), getAllKeys: vi.fn(async () => [...h.disk.keys()]), multiRemove: vi.fn(async (keys: string[]) => { keys.forEach(key => h.disk.delete(key)); }) } }));vi.mock('expo-crypto', () => ({ randomUUID: () => 'fixture-operation-id' }));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]) }; });@@ -24,7 +25,7 @@ vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));import { useBotGroupChat } from '@/session/useBotGroupChat';import { useBotGroupRoster } from '@/session/useBotGroupRoster';import { botGroupRoute } from '@/session/botGroupNavigation';-import { isRemoteResourceUnread, clearRemoteResourceCache } from '@/device-link/remoteResourceCache';+import { isRemoteResourceUnread, clearRemoteResourceCache, readCachedChatRoster } from '@/device-link/remoteResourceCache';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,@@ -37,7 +38,8 @@ 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(() => {+beforeEach(async () => {+ await clearRemoteResourceCache(); h.auth.user.id = 'owner';vi.clearAllMocks(); h.foreground.clear(); showChat = false; h.auth.accountGeneration = 1; h.legacy.items = []; h.targets = []; h.legacy.isOnline.mockReturnValue(false);vi.stubGlobal('WebSocket', class { close() {} });h.auth.apiFetch.mockImplementation(async (path: string, options: any) => {@@ -298,8 +300,9 @@ it('clears removed membership, exposes first-read failures and recovers on foreg});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();+ const original = h.auth.apiFetch.getMockImplementation()!;+ h.auth.apiFetch.mockImplementation((path, options) => path.startsWith('/v1/conversations?') ? new Promise(resolve => { finish = resolve; }) : original(path, options));+ await render(); h.auth.user.id = 'other'; h.auth.accountGeneration++; h.auth.apiFetch.mockResolvedValue([]); await render();await act(async () => finish([room])); expect(roster.items).toEqual([]);});@@ -442,3 +445,82 @@ it('merges a computer-confirmed personal removal without requiring direct serverexpect(roster.items).toEqual([]);h.link.status = 'offline'; h.link.getPresenceAvailability = () => false;});++// Regression: cold startup previously discarded every server group until the complete+// list + snapshot fanout returned. Exercise the actual hook across a disk restore (unit).+it('restores group summaries and member avatars before HTTP, retains them offline, and replaces them authoritatively', async () => {+ const original = h.auth.apiFetch.getMockImplementation()!;+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ const value = await original(path, options);+ return path.endsWith('/snapshot') ? { ...value, members: [{ ...value.members[0], avatar: 'https://avatars.example.invalid/member.png' }], messages: [+ { id: 'message', seq: '8', authorId: 'other', author: { kind: 'human', name: 'Other' }, content: [{ type: 'text', text: 'Last discussion' }], createdAt: '2026-10-09', deleted: false, threadRootId: null },+ ] } : value;+ });+ await render();+ const saved = h.disk.get('cindy.remoteResources.v1.owner')!;+ act(() => root!.unmount()); root = undefined;+ await clearRemoteResourceCache(); h.disk.set('cindy.remoteResources.v1.owner', saved);+ h.auth.accountGeneration++;+ let reject!: (error: Error) => void;+ h.auth.apiFetch.mockImplementation(() => new Promise((_, fail) => { reject = fail; }));+ await render();+ expect(roster.items).toMatchObject([{ key: `chat:${id}`, item: { display: { preview: 'Last discussion' } }, groupMembers: [{ avatarUrl: 'https://avatars.example.invalid/member.png' }], lastReplySequence: '8' }]);+ await act(async () => reject(new Error('offline')));+ expect(roster.items[0].item.display.preview).toBe('Last discussion');+ // A single snapshot timeout must not erase its known preview or group mark.+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ if (path.endsWith('/snapshot')) throw new Error('timeout');+ return original(path, options);+ });+ const links = roster.items[0].item.links;+ expect(links).not.toEqual([]);+ await act(async () => roster.refresh());+ expect(roster.items[0].item.display.preview).toBe('Last discussion');+ expect(roster.items[0].item.links).toEqual(links);+ expect((await readCachedChatRoster('owner', 'global'))?.items[0].item.links).toEqual(links);+ h.auth.apiFetch.mockImplementation(async (path, options) => path.startsWith('/v1/conversations?') ? [] : original(path, options));+ await act(async () => roster.refresh());+ expect(roster.items).toEqual([]);+ expect(await readCachedChatRoster('owner', 'global')).toEqual({ items: [], ids: [id] });+});+it('does not project a cached server group into another account or realm', async () => {+ await render();+ expect((await readCachedChatRoster('owner', 'global'))?.items).toHaveLength(1);+ expect(await readCachedChatRoster('owner', 'cn')).toBeNull();+ h.auth.user.id = 'other'; h.auth.accountGeneration++;+ h.auth.apiFetch.mockRejectedValue(new Error('offline'));+ await render();+ expect(roster.items).toEqual([]);+});++it('removes a saved roster row when opening the group confirms revoked membership', async () => {+ await render();+ expect((await readCachedChatRoster('owner', 'global'))?.items).toHaveLength(1);+ h.auth.apiFetch.mockRejectedValue(Object.assign(new Error('NOT_MEMBER'), { status: 403 }));+ showChat = true; await render();+ expect(chat.state.kind).toBe('missing');+ expect((await readCachedChatRoster('owner', 'global'))?.items).toEqual([]);+ act(() => root!.unmount()); root = undefined; showChat = false;+ h.auth.apiFetch.mockRejectedValue(new Error('offline'));+ await render();+ expect(roster.items).toEqual([]);+});++// Review regression (unit): an absent cache must not settle the first empty screen+// while HTTP is pending; an authoritative saved empty list may render immediately.+it.each(['missing', 'empty', 'read-error'] as const)('keeps initial loading correct with %s cache', async mode => {+ if (mode === 'empty') h.disk.set('cindy.remoteResources.v1.owner', JSON.stringify({ chatRosters: { global: { items: [], ids: [] } } }));+ if (mode === 'read-error') {+ const { default: storage } = await import('@react-native-async-storage/async-storage');+ vi.mocked(storage.getItem).mockRejectedValueOnce(new Error('read failed'));+ }+ const original = h.auth.apiFetch.getMockImplementation()!;+ let finish!: (rooms: typeof room[]) => void;+ h.auth.apiFetch.mockImplementation((path, options) => path.startsWith('/v1/conversations?')+ ? new Promise(resolve => { finish = resolve; }) : original(path, options));+ await render();+ expect(roster.items).toEqual([]);+ expect(roster.loading).toBe(mode !== 'empty');+ await act(async () => finish([]));+ expect(roster.loading).toBe(false);+});diff --git a/apps/mobile/src/__tests__/peerFileCache.test.ts b/apps/mobile/src/__tests__/peerFileCache.test.tsindex 682e1be054..2391df2108 100644--- a/apps/mobile/src/__tests__/peerFileCache.test.ts+++ b/apps/mobile/src/__tests__/peerFileCache.test.ts@@ -74,6 +74,16 @@ vi.mock("expo-file-system", () => ({}},}));+vi.mock('expo-file-system/legacy', () => ({+ EncodingType: { Base64: 'base64' },+ readAsStringAsync: async (uri: string, options: { position: number; length: number }) =>+ Buffer.from(disk.files.get(uri)!).subarray(options.position, options.position + options.length).toString('base64'),+ createDownloadResumable: (url: string, uri: string) => ({+ downloadAsync: async () => { disk.files.set(uri, disk.files.get(url)!.slice()); return { uri, status: 200 }; },+ cancelAsync: async () => {},+ }),+ deleteAsync: async (uri: string) => { disk.files.delete(uri); },+}));import { createRemoteMediaDiskCache } from '@/session/remoteMediaDiskCache';import { createExpoRemoteMediaDiskCacheIO } from '@/session/remoteMediaDiskCacheExpo';import { createPeerFileCache } from "@/device-link/peerFileCache";@@ -279,3 +289,43 @@ it.each(['download', 'store', 'direct'] as const)('keeps the old version when %sexpect(new Set(disk.files.keys())).toEqual(before);expect(await cache.readLatest('device', 'url', () => true)).toMatchObject(metadata);});++// Companion icons used to bypass the disk cache entirely. Verify real bytes survive+// opening a new index reader, and account/device/content identities remain separate (unit).+it('persists avatar bytes in the existing account cache and reads them without a download', async () => {+ const owner = JSON.stringify(['global', 'avatar-owner']);+ const identity = JSON.stringify(['mac', 'cindy-media://blobs/avatar.png']);+ const source = 'file:///fixture-avatar.png';+ disk.files.set(source, new Uint8Array([1, 2, 3, 4]));+ const cache = await createPeerFileCache(owner);+ expect(await cache.storeAvatar(identity, source, 'image/png', () => true)).toBe(true);+ disk.files.delete(source);+ const namespace = `files-${createHash('sha256').update(owner).digest('hex')}`;+ const reopened = createRemoteMediaDiskCache(createExpoRemoteMediaDiskCacheIO(namespace));+ const hit = await reopened.lookup(`companion-avatar:${identity}`);+ expect(hit?.size).toBe(4);+ expect(await new File(hit!.uri).base64()).toBe('AQIDBA==');+ expect((await cache.lookupAvatar(identity))?.uri).toBe(hit!.uri);+ expect(await cache.lookupAvatar(JSON.stringify(['other-mac', 'cindy-media://blobs/avatar.png']))).toBeNull();+ expect(await (await createPeerFileCache('different-avatar-owner')).lookupAvatar(identity)).toBeNull();+ disk.files.set(source, new Uint8Array([5]));+ expect(await cache.storeAvatar('cancelled', source, 'image/png', () => false)).toBe(false);+ expect(await cache.lookupAvatar('cancelled')).toBeNull();+});++// Review regression (unit): a public endpoint may return HTTP 200 with an HTML+// error page. Real cache + download adapter must reject it and allow later recovery.+it('rejects non-image avatar responses and persists recovered image bytes using their actual MIME', async () => {+ const cache = await createPeerFileCache('avatar-response-owner');+ const url = 'https://avatars.example.invalid/profile';+ disk.files.set(url, new TextEncoder().encode('<html>Temporary outage</html>'));+ expect(await cache.storeAvatar(url, url, 'image/png', () => true)).toBe(false);+ expect(await cache.lookupAvatar(url)).toBeNull();+ const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0]);+ disk.files.set(url, jpeg);+ expect(await cache.storeAvatar(url, url, 'image/png', () => true)).toBe(true);+ const hit = await cache.lookupAvatar(url);+ expect(hit?.mimeType).toBe('image/jpeg');+ expect(await new File(hit!.uri).base64()).toBe(Buffer.from(jpeg).toString('base64'));+ expect([...disk.files.keys()].filter(uri => uri.includes('/remote-media-share/'))).toEqual([]);+});diff --git a/apps/mobile/src/__tests__/remoteResourceCache.test.ts b/apps/mobile/src/__tests__/remoteResourceCache.test.tsindex b5c54fe70f..17b2aa6ba4 100644--- a/apps/mobile/src/__tests__/remoteResourceCache.test.ts+++ b/apps/mobile/src/__tests__/remoteResourceCache.test.ts@@ -7,13 +7,19 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: {getAllKeys: vi.fn(async () => [...disk.keys()]),multiRemove: vi.fn(async (keys: string[]) => { keys.forEach((key) => disk.delete(key)); }),} }));-import { cacheRemoteResourceHome, cacheRemoteResourceItems, clearRemoteResourceCache, isRemoteResourceUnread, markRemoteResourceRead, readRemoteResourceSnapshot, remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';+import { cacheChatRoster, readCachedChatRoster, cacheRemoteResourceHome, cacheRemoteResourceItems, clearRemoteResourceCache, isRemoteResourceUnread, markRemoteResourceRead, readRemoteResourceSnapshot, remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';import { chatReadAt, chatRoomRow, type ChatSnapshot } from '@/chat/chatServerClient';const rows = (deviceId: string, lastReplyAt: number) => [{key: `${deviceId}:bot:writer`, host: { deviceId, deviceName: deviceId },item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, display: { title: 'Writer', lastReplyAt }, revision: '1', links: [] },}];beforeEach(async () => { await clearRemoteResourceCache(); disk.clear(); });+it('restores the same collection-qualified row identity used by live lists', async () => {+ const live = rows('home', 100)[0];+ live.key = JSON.stringify(['home', 'teammates', 'bot', 'writer']);+ disk.set('cindy.remoteResources.v1.alice', JSON.stringify({ items: { teammates: [live] } }));+ expect((await readRemoteResourceSnapshot('alice')).items.teammates[0].key).toBe(live.key);+});it('does not restore routines from an old offline snapshot while retaining companions', async () => {const home = [{ id: 'routines', title: '例行任务', resourceKind: 'routine', targets: [{ deviceId: 'home', deviceName: 'Home' }] },@@ -130,3 +136,28 @@ it('restores portable roster data after process restart and never persists runtiawait fresh.clearRemoteResourceCache();expect(disk.size).toBe(0);});++// Review regression (unit): valid group/member data can exceed the shared 256 KiB+// budget. Exercise persistence and cold read, not just the in-memory mirror.+it('persists a bounded recent roster when group avatars exceed the disk budget', async () => {+ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 1000));+ const groups = Array.from({ length: 100 }, (_, index) => ({+ key: `chat:group-${index}`, host: { deviceId: '', deviceName: '' },+ item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id: `group-${index}` },+ display: { title: `Group ${index}`, lastReplyAt: index, preview: 'Known summary' }, revision: '1', links: [] },+ groupMembers: Array.from({ length: 20 }, (_, member) => ({ botId: `member-${member}`, name: `Member ${member}`,+ avatar: '', avatarColor: '', avatarUrl: `https://avatars.example.invalid/${'a'.repeat(700)}/${member}.png` })),+ }));+ await cacheChatRoster('alice', 'global', groups, groups.map(row => row.item.ref.id));+ expect((await readCachedChatRoster('alice', 'global'))?.items).toHaveLength(100);+ const saved = disk.get('cindy.remoteResources.v1.alice')!;+ expect(saved.length).toBeLessThanOrEqual(256 * 1024);+ await clearRemoteResourceCache(); disk.set('cindy.remoteResources.v1.alice', saved);+ const restored = await readCachedChatRoster('alice', 'global');+ expect(restored?.items.length).toBeGreaterThan(0);+ expect(restored?.items.at(-1)).toMatchObject({ item: { ref: { id: 'group-99' }, display: { preview: 'Known summary' } }, groupMembers: groups[99].groupMembers.slice(0, 5) });+ expect(restored?.ids).toHaveLength(100);+ expect((await readRemoteResourceSnapshot('alice')).items.teammates).toHaveLength(1);+ await cacheChatRoster('alice', 'global', [], groups.map(row => row.item.ref.id));+ expect(JSON.parse(disk.get('cindy.remoteResources.v1.alice')!).chatRosters.global.items).toEqual([]);+});diff --git a/apps/mobile/src/__tests__/useCloudCompanion.test.tsx b/apps/mobile/src/__tests__/useCloudCompanion.test.tsxnew file mode 100644index 0000000000..2a600eae68--- /dev/null+++ b/apps/mobile/src/__tests__/useCloudCompanion.test.tsx@@ -0,0 +1,66 @@+// @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(() => ({+ owner: 'owner:1:global', current: true, readDeviceList: vi.fn(),+ capabilities: vi.fn(), actors: vi.fn(),+}));+vi.mock('react-native', () => ({ AppState: { addEventListener: () => ({ remove() {} }) } }));+vi.mock('expo-router', async () => {+ const { useEffect } = await import('react');+ return { useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]) };+});+vi.mock('@/chat/useChatServer', async () => {+ const { useMemo } = await import('react');+ return { useChatClient: () => useMemo(() => ({ owner: h.owner, enabled: true,+ current: () => h.current, client: { capabilities: h.capabilities, actors: h.actors } }), [h.owner]) };+});+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ readDeviceList: h.readDeviceList }) }));+import { useCloudCompanionHome } from '@/chat/useCloudCompanion';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let root: Root;+let result: ReturnType<typeof useCloudCompanionHome>;+function Probe() { result = useCloudCompanionHome(true); return null; }+const render = () => act(async () => root.render(createElement(Probe)));+const actor = { id: 'actor', kind: 'bot', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'studio' };+beforeEach(() => {+ vi.resetAllMocks(); h.owner = 'owner:1:global'; h.current = true;+ h.capabilities.mockResolvedValue({ companionHome: true }); h.actors.mockResolvedValue([actor]);+ h.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'studio', name: 'Mac Studio' }] });+ root = createRoot(document.createElement('div'));+});+afterEach(() => act(() => root.unmount()));++// Tier: behavior. A successful actor refresh plus a failed optional directory read+// previously replaced a known computer name with its ID. Pure row tests miss this+// async failure path; drive the actual hook and its account fence.+it('retains known names on directory failure while accepting a changed home, without leaking across accounts', async () => {+ await render();+ expect(result.deviceNames.get('studio')).toBe('Mac Studio');+ h.readDeviceList.mockRejectedValue(new Error('directory unavailable'));+ h.actors.mockResolvedValue([{ ...actor, homeDeviceId: 'laptop' }]);+ await act(async () => result.refresh());+ expect(result.deviceNames.get('studio')).toBe('Mac Studio');+ expect(result.actors[0].homeDeviceId).toBe('laptop');+ h.owner = 'another:2:global';+ await render();+ expect(result.deviceNames.size).toBe(0);+ h.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'laptop', name: 'Renamed laptop' }] });+ await act(async () => result.refresh());+ expect([...result.deviceNames]).toEqual([['laptop', 'Renamed laptop']]);+});++it('ignores a late directory result after a newer refresh wins', async () => {+ await render();+ let complete!: (value: unknown) => void;+ h.readDeviceList.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));+ let pending!: Promise<void>;+ await act(async () => { pending = result.refresh(); });+ h.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'studio', name: 'New name' }] });+ await act(async () => result.refresh());+ await act(async () => { complete({ devices: [{ deviceId: 'studio', name: 'Old name' }] }); await pending; });+ expect(result.deviceNames.get('studio')).toBe('New name');+});diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex 72d0afad3a..c508131e08 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -6,7 +6,7 @@ import type { RemoteActionInvokeResponse } from '@cindy/device-link';import type { BotGroupAttachment, BotGroupRemoteActionId } from '@cindy/maker-shared/botGroupChat';import { useAuth } from '@/auth/AuthContext';import { getActiveMobileSessionRealm, getMobileEndpointForRealm, loadMobileEndpointsForRealm } from '@/config/env';-import { forgetRemoteResource, markRemoteResourceRead } from '@/device-link/remoteResourceCache';+import { cacheChatRoster, forgetRemoteResource, hideCachedChatRooms, markRemoteResourceRead, readCachedChatRoster } from '@/device-link/remoteResourceCache';import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';import type { BotGroupChatState } from '@/session/useBotGroupChat';import { chatAccessLost, chatCursor, chatGroupView, chatHttpsUrl, chatRoomRow, chatReadAt, chatReadSequence, chatLastReplyAt, chatLastReplySequence, createChatServerClient, type ChatActor, type ChatPage, type ChatRequest, type ChatSnapshot } from './chatServerClient';@@ -54,7 +54,7 @@ export function useChatClient() {check(); return result;};const client = createChatServerClient(request, listFor(owner));- return { owner, userId: auth.user?.id ?? '', current, baseUrl, endpoint, request, client,+ return { owner, realm, 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]);}@@ -71,6 +71,12 @@ export function useChatServerRoster(enabled: boolean) {const read = useRemoteSyncCoordinator(async run => {if (!api.enabled || !enabled) return;setState(old => ({ ...old, refreshing: run.reasons.includes('visible') }));+ const saved = await readCachedChatRoster(api.userId, api.realm);+ const cached = saved ?? { items: [], ids: [] };+ if (run.isStale() || !api.current()) return;+ for (const id of cached.ids) known.current.ids.add(id);+ if (saved) setState(old => old.owner === api.owner && !old.loading ? old : { owner: api.owner,+ rooms: cached.items.filter(row => !api.client.personalList.hidden(row.item.ref.id)), loading: false, refreshing: false, error: null });try {await api.client.syncListState(run.reasons.some(reason => ['focus', 'visible', 'connected'].includes(reason)));const [rooms, self] = await Promise.all([api.client.list(), api.client.me()]);@@ -92,7 +98,13 @@ export function useChatServerRoster(enabled: boolean) {// An archive can land between the list and the newer snapshot.if (!value.room.archived) rows.push(chatRoomRow(room, value, self));} catch (error) {- if (!chatAccessLost(error)) { partial = true; rows.push(chatRoomRow(room)); }+ if (!chatAccessLost(error)) {+ partial = true;+ const previous = cached.items.find(row => row.item.ref.id === room.id);+ const row = chatRoomRow(room);+ // Member links back the composite avatar and member search until a snapshot replaces them.+ rows.push(previous ? { ...previous, item: { ...row.item, display: { ...previous.item.display, title: row.item.display.title }, links: previous.item.links } } : row);+ }}}));if (run.isStale() || !api.current()) return;@@ -108,10 +120,15 @@ export function useChatServerRoster(enabled: boolean) {snapshots.current = fresh;for (const room of rooms) known.current.ids.add(room.id);for (const id of api.client.personalList.ids()) known.current.ids.add(id);- setState({ owner: api.owner, rooms: rows.filter(row => !api.client.personalList.hidden(row.item.ref.id)), loading: false, refreshing: false, error: partial ? 'CHAT_LIST_FAILED' : null });+ const visible = rows.filter(row => !api.client.personalList.hidden(row.item.ref.id));+ setState({ owner: api.owner, rooms: visible, loading: false, refreshing: false, error: partial ? 'CHAT_LIST_FAILED' : null });+ await cacheChatRoster(api.userId, api.realm, visible, known.current.ids);}} catch (error) {- if (!run.isStale() && api.current()) setState(old => ({ owner: api.owner, rooms: old.owner === api.owner && !chatAccessLost(error) ? old.rooms.filter(row => !api.client.personalList.hidden(row.item.ref.id)) : [], loading: false, refreshing: false, error: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_LIST_FAILED' }));+ if (!run.isStale() && api.current()) {+ setState(old => ({ owner: api.owner, rooms: old.owner === api.owner && !chatAccessLost(error) ? old.rooms.filter(row => !api.client.personalList.hidden(row.item.ref.id)) : [], loading: false, refreshing: false, error: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_LIST_FAILED' }));+ if (chatAccessLost(error)) await cacheChatRoster(api.userId, api.realm, [], known.current.ids);+ }}}, api.owner);const refresh = useCallback(() => read({ reason: 'visible' }), [read]);@@ -153,6 +170,7 @@ export function useChatServerRoster(enabled: boolean) {if (!api.current()) return;for (const id of api.client.personalList.ids()) known.current.ids.add(id);setState(old => old.owner !== api.owner ? old : { ...old, rooms: old.rooms.filter(row => !api.client.personalList.hidden(row.item.ref.id)) });+ void hideCachedChatRooms(api.userId, api.realm, api.client.personalList.ids().filter(id => api.client.personalList.hidden(id)));}), [api]);const own = state.owner === api.owner;return { items: own ? state.rooms : [], serverIds: known.current.ids, loading: api.enabled && (!own || state.loading),@@ -172,6 +190,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {const valid = () => api.current() && active.current === identity;const loseAccess = () => {accessGeneration.current++; freshRead.current = false; page.current = null;+ if (valid()) void forgetRemoteResource(api.userId, groupId);setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false });};const view = (next: ChatPage, self: string, actors: ChatActor[]) => ({ ...chatGroupView(next, self, actors), ...api.client.lifecycleCapabilities() });diff --git a/apps/mobile/src/chat/useCloudCompanion.ts b/apps/mobile/src/chat/useCloudCompanion.tsindex 59d7f95e26..eab37672ed 100644--- a/apps/mobile/src/chat/useCloudCompanion.ts+++ b/apps/mobile/src/chat/useCloudCompanion.ts@@ -26,10 +26,13 @@ export function useCloudCompanionHome(enabled: boolean) {const { companionHome } = await api.client.capabilities();const actors = companionHome ? await api.client.actors() : NO_ACTORS;const deviceNames = companionHome && actors.length- ? await readDeviceList().then(({ devices }) => new Map(devices.map(device => [device.deviceId, device.name] as const)), () => NO_NAMES)+ ? await readDeviceList().then(({ devices }) => new Map(devices.map(device => [device.deviceId, device.name] as const)), () => null): NO_NAMES;if (run !== generation.current || !api.current()) return;- setState({ owner: api.owner, supported: companionHome, actors, deviceNames });+ // A failed optional directory read is not a rename. Retain only this+ // account's last labels; the successful actor response still owns homes.+ setState(previous => ({ owner: api.owner, supported: companionHome, actors,+ deviceNames: deviceNames ?? (previous.owner === api.owner ? previous.deviceNames : NO_NAMES) }));} catch {// Keep the previous answer: rows simply behave as before when the server cannot be read.}diff --git a/apps/mobile/src/components/RemoteCompanionAvatar.tsx b/apps/mobile/src/components/RemoteCompanionAvatar.tsxindex 4474cad9b7..56c0159408 100644--- a/apps/mobile/src/components/RemoteCompanionAvatar.tsx+++ b/apps/mobile/src/components/RemoteCompanionAvatar.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { Image, StyleSheet, View } from 'react-native';import type { RemoteResourceAvatar } from '@cindy/device-link';import { Text } from '@/components/AppText';@@ -6,7 +6,8 @@ import { useAuth } from '@/auth/AuthContext';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';import { resolveMobileRemoteMedia, type MobileRemoteMediaPresignResult } from '@/session/remoteMedia';-import { DEVICE_LINK_API_BASE_URL } from '@/config/env';+import { DEVICE_LINK_API_BASE_URL, getActiveMobileSessionRealm } from '@/config/env';+import { createPeerFileCache } from '@/device-link/peerFileCache';import { useTheme } from '@/theme';import { lineHeight, radius, typeScale } from '@/theme/tokens';@@ -22,23 +23,40 @@ export function RemoteCompanionAvatar({ avatar, imageUrl, deviceId, name, onlineconst auth = useAuth();const { invoke } = useDeviceLink();const value = avatar?.value || '';- const binding = `${auth.accountGeneration}:${deviceId}:${value}:${imageUrl ?? ''}`;+ const realm = getActiveMobileSessionRealm();+ const owner = JSON.stringify([realm, auth.user?.id ?? '']);+ const identity = JSON.stringify([imageUrl ? '' : deviceId, imageUrl || value]);+ const binding = JSON.stringify([owner, auth.accountGeneration, identity]);+ const current = useRef(binding); current.current = binding;const [image, setImage] = useState<{ binding: string; uri: string } | null>(null);const [failed, setFailed] = useState(false);useEffect(() => {let cancelled = false;setFailed(false);- if (imageUrl || avatar?.kind !== 'media' || !online) return;- const maker = createMobileMakerTransport({ deviceId, invoke });- void resolveMobileRemoteMedia({ kind: 'image', url: value }, {- fetchRemoteMedia: maker.fetchRemoteMedia,- presignGet: (key) => auth.apiFetch<MobileRemoteMediaPresignResult>('/api/device-link/media/presign-get', { baseUrl: DEVICE_LINK_API_BASE_URL, method: 'POST', body: { key } }),- }, { thumbnail: true }).then((result) => {- if (!cancelled && result.previewable && result.mimeType.startsWith('image/')) setImage({ binding, uri: result.url });- }).catch(() => undefined);+ if (!imageUrl && avatar?.kind !== 'media') return;+ const active = () => !cancelled && current.current === binding && getActiveMobileSessionRealm() === realm;+ void (async () => {+ const cache = auth.user?.id ? await createPeerFileCache(owner).catch(() => null) : null;+ const hit = await cache?.lookupAvatar(identity).catch(() => null);+ if (!active()) return;+ if (hit) { setImage({ binding, uri: hit.uri }); return; }+ // Only a cache miss needs a live computer. Public URLs do not depend on it.+ if (!imageUrl && !online) return;+ const maker = createMobileMakerTransport({ deviceId, invoke, isCurrent: active });+ const result = imageUrl ? { url: imageUrl, mimeType: 'image/png', previewable: true } : await resolveMobileRemoteMedia({ kind: 'image', url: value }, {+ fetchRemoteMedia: maker.fetchRemoteMedia,+ presignGet: (key) => auth.apiFetch<MobileRemoteMediaPresignResult>('/api/device-link/media/presign-get', { baseUrl: DEVICE_LINK_API_BASE_URL, method: 'POST', body: { key } }),+ }, { thumbnail: true });+ if (!active() || !result.previewable || !result.mimeType.startsWith('image/')) return;+ setImage({ binding, uri: result.url });+ if (await cache?.storeAvatar(identity, result.url, result.mimeType, active).catch(() => false)) {+ const saved = await cache?.lookupAvatar(identity);+ if (active() && saved) setImage({ binding, uri: saved.uri });+ }+ })().catch(() => undefined);return () => { cancelled = true; };- }, [auth.apiFetch, avatar?.kind, binding, deviceId, imageUrl, invoke, online, value]);- const source = imageUrl ? { uri: imageUrl } : presets[value] || (image?.binding === binding ? { uri: image.uri } : null);+ }, [auth.apiFetch, auth.user?.id, avatar?.kind, binding, deviceId, identity, imageUrl, invoke, online, owner, realm, value]);+ const source = (!imageUrl && presets[value]) || (image?.binding === binding ? { uri: image.uri } : null);if (source && !failed) return <Image source={source} onError={() => setFailed(true)} style={[styles.image, { width: size, height: size }]} />;const glyph = avatar?.kind === 'emoji' ? value : avatar?.fallbackText || Array.from(name)[0];if (!framed) return <Text style={{ color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body }}>{glyph}</Text>;diff --git a/apps/mobile/src/device-link/peerFileCache.ts b/apps/mobile/src/device-link/peerFileCache.tsindex ff9578156d..41d334e96b 100644--- a/apps/mobile/src/device-link/peerFileCache.ts+++ b/apps/mobile/src/device-link/peerFileCache.ts@@ -1,4 +1,5 @@import { Directory, File, Paths } from "expo-file-system";+import { sniffImageMimeFromBase64 } from "@/session/imageAnnotationModel";import {CryptoDigestAlgorithm,digestStringAsync,@@ -6,7 +7,7 @@ import {} from "expo-crypto";import { FILE_INLINE_MAX_BYTES, validFileVersion, type DeviceFileResult } from "@cindy/device-link";import { createRemoteMediaDiskCache } from "@/session/remoteMediaDiskCache";-import { createExpoRemoteMediaDiskCacheIO, downloadRemoteMediaShareTemp } from "@/session/remoteMediaDiskCacheExpo";+import { createExpoRemoteMediaDiskCacheIO, downloadRemoteMediaShareTemp, withDownloadedRemoteMediaFile } from "@/session/remoteMediaDiskCacheExpo";import {PEER_FILE_DISK_RESERVE_BYTES,recordPeerMedia,@@ -41,6 +42,25 @@ async function openPeerFileCache(owner: string) {},);const api = {+ // Blob and public companion avatar URLs change with the image content. Reuse+ // the account/realm's existing disk cache, independent of device presence.+ lookupAvatar: (identity: string) => cache.lookup(`companion-avatar:${identity}`),+ storeAvatar: async (identity: string, uri: string, mime: string, active: () => boolean) => {+ // A peer file is still owned by its visible consumer. Do not release that+ // source if persistence fails; the regular staging lifetime remains intact.+ if (uri.startsWith('file://')) {+ const file = new File(uri);+ return active() && file.exists && file.size > 0 && file.size <= 5 * 1024 * 1024+ ? cache.store(`companion-avatar:${identity}`, uri, mime, file.size) : false;+ }+ return withDownloadedRemoteMediaFile(uri, mime, 5 * 1024 * 1024, async file => {+ const { readAsStringAsync, EncodingType } = await import('expo-file-system/legacy');+ const head = await readAsStringAsync(file.uri, { encoding: EncodingType.Base64, position: 0, length: 16 });+ const actualMime = sniffImageMimeFromBase64(head);+ return active() && actualMime ? cache.store(`companion-avatar:${identity}`, file.uri, actualMime, file.size) : false;+ },+ new AbortController().signal);+ },async readLatest(device: string, url: string, active: () => boolean): Promise<DeviceFileResult | null> {const hit = await cache.lookup(JSON.stringify([device, url]));if (!active() || !hit || !validFileVersion(hit.version)) return null;diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.tsindex 4133875537..3bc11f7fa2 100644--- a/apps/mobile/src/device-link/remoteResourceCache.ts+++ b/apps/mobile/src/device-link/remoteResourceCache.ts@@ -3,7 +3,8 @@ import { isMobileRemoteCollectionSupported, normalizeRemoteCollectionItems, parsconst PREFIX = 'cindy.remoteResources.v1.';const MAX_CHARS = 256 * 1024;-type Snapshot = { home: RemoteHomeCollection[]; items: Record<string, HostedRemoteCollectionItem[]>; read: Record<string, number>; readSequences?: Record<string, string> };+type ChatRoster = { items: HostedRemoteCollectionItem[]; ids: string[] };+type Snapshot = { home: RemoteHomeCollection[]; items: Record<string, HostedRemoteCollectionItem[]>; read: Record<string, number>; readSequences?: Record<string, string>; chatRosters?: Record<string, ChatRoster> };const empty = (): Snapshot => ({ home: [], items: {}, read: {}, readSequences: {} });const validSequence = (value: unknown): value is string => typeof value === 'string' && /^\d{1,30}$/.test(value);let epoch = 0;@@ -33,7 +34,7 @@ function normalize(raw: unknown): Snapshot {if (!row) return [];const [host] = parseRemoteResourceTargets(JSON.stringify([row.host]));const [item] = normalizeRemoteCollectionItems({ items: [row.item] }, id);- return host && item ? [{ host, item, key: JSON.stringify([host.deviceId, item.ref.kind, item.ref.id]) }] : [];+ return host && item ? [{ host, item, key: JSON.stringify([host.deviceId, item.ref.collectionId, item.ref.kind, item.ref.id]) }] : [];});}if (value.read && typeof value.read === 'object') for (const [key, at] of Object.entries(value.read).slice(-2000)) {@@ -42,6 +43,26 @@ function normalize(raw: unknown): Snapshot {if (value.readSequences && typeof value.readSequences === 'object') for (const [key, sequence] of Object.entries(value.readSequences).slice(-2000)) {if (key.length <= 600 && validSequence(sequence)) out.readSequences![key] = sequence;}+ // Direct server rows have no device host. Keep their display mirror separate from+ // legacy computer rows; neither cached membership nor presence grants access.+ if (value.chatRosters && typeof value.chatRosters === 'object') for (const realm of ['cn', 'global']) {+ const roster = value.chatRosters[realm];+ if (!roster || !Array.isArray(roster.items) || !Array.isArray(roster.ids)) continue;+ const items = roster.items.slice(0, 200).flatMap(row => {+ const [item] = normalizeRemoteCollectionItems({ items: [row?.item] }, 'bot-groups');+ if (!item || item.ref.kind !== 'bot-group') return [];+ const groupMembers = Array.isArray(row.groupMembers) ? row.groupMembers.slice(0, 200).flatMap(member => {+ if (!member || typeof member.botId !== 'string' || typeof member.name !== 'string') return [];+ return [{ botId: member.botId.slice(0, 160), name: member.name.slice(0, 512),+ avatar: typeof member.avatar === 'string' ? member.avatar.slice(0, 8192) : '',+ ...(typeof member.avatarUrl === 'string' && member.avatarUrl.startsWith('https://') ? { avatarUrl: member.avatarUrl.slice(0, 8192) } : {}),+ avatarColor: typeof member.avatarColor === 'string' ? member.avatarColor.slice(0, 64) : '' }];+ }) : undefined;+ return [{ key: `chat:${item.ref.id}`, host: { deviceId: '', deviceName: '' }, item, groupMembers,+ ...(validSequence(row.lastReplySequence) ? { lastReplySequence: row.lastReplySequence } : {}) }];+ });+ (out.chatRosters ??= {})[realm] = { items, ids: [...new Set(roster.ids.filter(id => typeof id === 'string' && id.length <= 160))].slice(-2000) };+ }return out;}@@ -58,6 +79,40 @@ export async function readRemoteResourceSnapshot(userId: string): Promise<Snapshreturn snapshots.get(userId)!;}+/** Trim only the disposable disk mirror; live rows and read positions stay intact. */+function diskSnapshot(raw: string): string {+ if (raw.length <= MAX_CHARS) return raw;+ const copy: Snapshot = JSON.parse(raw);+ // The group list paints at most five avatars; full membership comes from opening it.+ for (const roster of Object.values(copy.chatRosters ?? {})) {+ for (const row of roster.items) if (row.groupMembers) row.groupMembers = row.groupMembers.slice(0, 5);+ }+ let remaining = JSON.stringify(copy).length - MAX_CHARS;+ const lists = [...Object.values(copy.items), ...Object.values(copy.chatRosters ?? {}).map(roster => roster.items)];+ const candidates = lists.flat().sort((a, b) => (a.item.display.lastReplyAt ?? 0) - (b.item.display.lastReplyAt ?? 0));+ const removed = new Set<HostedRemoteCollectionItem>();+ for (const row of candidates) {+ if (remaining <= 0) break;+ removed.add(row); remaining -= JSON.stringify(row).length;+ }+ for (const list of lists) {+ const kept = list.filter(row => !removed.has(row));+ list.splice(0, list.length, ...kept);+ }+ // Pathological metadata alone can exhaust the budget too. Retain newer markers+ // before older ones, rather than silently leaving a stale whole snapshot on disk.+ for (const map of [copy.read, copy.readSequences ?? {}]) for (const key of Object.keys(map)) {+ if (remaining <= 0) break;+ remaining -= JSON.stringify(key).length + JSON.stringify(map[key]).length + 1;+ delete map[key];+ }+ for (const roster of Object.values(copy.chatRosters ?? {})) while (remaining > 0 && roster.ids.length) {+ remaining -= JSON.stringify(roster.ids.shift()).length;+ }+ while (remaining > 0 && copy.home.length) remaining -= JSON.stringify(copy.home.shift()).length;+ return JSON.stringify(copy);+}+async function update(userId: string, change: (snapshot: Snapshot) => void): Promise<void> {if (!userId) return;const expected = epoch;@@ -74,8 +129,7 @@ async function update(userId: string, change: (snapshot: Snapshot) => void): Pro// open companion chat re-acknowledges its read position on render (a JS render loop).if (raw === before && !unsaved.has(userId)) return;if (raw !== before) emit();- if (raw.length > MAX_CHARS) return;- const saved = await AsyncStorage.setItem(PREFIX + userId, raw).then(() => true, () => false);+ const saved = await AsyncStorage.setItem(PREFIX + userId, diskSnapshot(raw)).then(() => true, () => false);if (expected !== epoch) { await AsyncStorage.removeItem(PREFIX + userId).catch(() => undefined); return; }if (saved) unsaved.delete(userId); else unsaved.add(userId);});@@ -83,6 +137,15 @@ async function update(userId: string, change: (snapshot: Snapshot) => void): Proawait next.finally(() => { if (writes.get(userId) === next) writes.delete(userId); });}export const cacheRemoteResourceHome = (userId: string, home: RemoteHomeCollection[]) => update(userId, (s) => { s.home = home; });+export const readCachedChatRoster = async (userId: string, realm: string): Promise<ChatRoster | null> =>+ (await readRemoteResourceSnapshot(userId)).chatRosters?.[realm] ?? null;+export const cacheChatRoster = (userId: string, realm: string, items: HostedRemoteCollectionItem[], ids: Iterable<string>) => update(userId, s => {+ (s.chatRosters ??= {})[realm] = { items, ids: [...ids] };+});+export const hideCachedChatRooms = (userId: string, realm: string, ids: string[]) => update(userId, s => {+ const roster = s.chatRosters?.[realm];+ if (roster) { roster.items = roster.items.filter(row => !ids.includes(row.item.ref.id)); roster.ids = [...new Set([...roster.ids, ...ids])]; }+});export const remoteResourceReadKey = (deviceId: string, resourceId: string) => JSON.stringify([deviceId, resourceId]);export const cacheRemoteResourceItems = (userId: string, collectionId: string, items: HostedRemoteCollectionItem[]) => update(userId, (s) => {s.items[collectionId] = items;@@ -128,6 +191,7 @@ export async function clearRemoteResourceCache(): Promise<void> {/** Drop only this account's display/unread mirror after a confirmed personal removal. */export const forgetRemoteResource = (userId: string, resourceId: string) => update(userId, s => {for (const id of Object.keys(s.items)) s.items[id] = s.items[id].filter(row => row.item.ref.id !== resourceId);+ for (const roster of Object.values(s.chatRosters ?? {})) roster.items = roster.items.filter(row => row.item.ref.id !== resourceId);for (const map of [s.read, s.readSequences ?? {}]) for (const key of Object.keys(map)) {try { if (JSON.parse(key)[1] === resourceId) delete map[key]; } catch { /* legacy cache key */ }}diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsxindex 66514724cf..78b8441f24 100644--- a/apps/mobile/src/session/TeammateHomeScreen.tsx+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx@@ -53,10 +53,10 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {// Main computers (cloud-companions.md): only with a server that declares companionHome.const cloud = useCloudCompanionHome(focused);// One row per companion, under its main computer (a row built from the cloud when none is listed).- // Unverified disk rows stay hidden on the first roster load; cloud actors remain independently usable.- const visibleRosterItems = roster.loading && !roster.error ? [] : roster.items;- const items = useMemo(() => cloud.supported ? cloudCompanionRows(visibleRosterItems, cloud.actors, cloud.deviceNames) : visibleRosterItems,- [cloud.actors, cloud.deviceNames, cloud.supported, visibleRosterItems]);+ // Loading is freshness, not identity: preserve known conversation links and previews.+ // Otherwise an unrelated slow host turns a cached chat into a read-only cloud entry.+ const items = useMemo(() => cloud.supported ? cloudCompanionRows(roster.items, cloud.actors, cloud.deviceNames) : roster.items,+ [cloud.actors, cloud.deviceNames, cloud.supported, roster.items]);// A cloud companion opens its normal chat (cached when its computer is unreachable). Only a row// this phone knows from the cloud alone (never listed by its computer) opens the cloud conversation.const cloudActor = (row: HostedRemoteCollectionItem) => cloud.supported && row.item.revision === CLOUD_ROW_REVISION ? cloudActorForRow(cloud.actors, row) : null;diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex dfc2d32d60..c9ff35168c 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -133,6 +133,8 @@字节识别为图片、且不超过头像上限(5 MB)的内容;公开头像走共用的受控公网图片下载。两种地址各自不可变(blob 地址即内容指纹,云端换头像会生成新地址),命中不需要重新校验。Renderer 经`maker:companion-avatar:resolve` 先查本机副本,未命中时照常显示原地址并在后台保存一份。+ Mobile 的伙伴与群成员头像复用 `peerFileCache` 的账号/realm 文件缓存,按来源设备与头像地址查本地字节;+ 命中无需设备在线或重新下载,未命中才沿原媒体通道取件并保存(至多 5 MB)。远程下载落盘前复用图片头部嗅探,以实际 MIME 保存;HTML 等错误响应不入缓存,后续可重新取件。复用既有磁盘压力回收,换头像以新地址区分。- 可再生 HTML 临时快照缓存是独立副本的例外:仅在快照已物化自己的文件、HTTP 服务不依赖媒体仓 blob、且该缓存不作为持久附件提交时,使用 `isCache: true` 和空引用入仓。必须验证媒体仓缓存不可用时快照仍可读取,以及重复打开、失败、取消和重试不新增业务引用;diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 160cd0c4dc..c167bd21dd 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -367,6 +367,10 @@`check:endpoints` 对两份生产正本检查群聊地址非空 HTTPS,并阻止直连代码硬编码生产地址。- 手机列表以服务器群 ID 去重,优先直连;电脑声明的 `bot-groups` 继续提供本地旧群和旧入口兼容。旧缓存无法区分服务器群与本地群,因此兼容群行须有电脑当前连接代次的成功列群回包,断线缓存不能作为成员权限依据。+ 直连群的已同步列表按账号与 realm 保存显示副本(摘要、时间、未读序号及成员头像身份),冷启动先读本地,后台再刷新;+ 暂时读取失败保留已知显示内容,成功空列表、归档、个人移除或撤权会更新副本。保留已识别服务器 ID,避免旧电脑副本将已移除群带回。+ 无缓存记录或本地读取失败不结束首次加载;已缓存的空列表可直接显示。显示副本沿用 256 × 1024 字符预算,超限先只保留群列表可见的前五位头像,再淘汰较旧行;在线内存列表不裁剪。极端元数据超限才回收较旧标记,不能整份静默放弃写盘。+ 显示副本不授予成员权限;打开群和发送仍执行实时授权。退出账号沿用远程资源缓存清理。直连列表和电脑 `bot-groups` 列表均排除已归档群;直连仍保留其服务器 ID 用于去重,防止旧电脑回包重新带回同一群。列群后取得的较新快照已归档时也不显示该行。过滤只影响列表,既有历史访问和群管理权限保持不变;个人移除仍走账号的 list-state。回归见 `chatServerMobileEntry.test.tsx`、`BotGroupChatScreen.test.tsx` 与 `botGroupRemoteResourceProvider.test.ts`。