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): render server avatars and clear revoked media access

zqchris3aeb1958f898
diff --git a/apps/mobile/src/__tests__/BotGroupAvatars.test.tsx b/apps/mobile/src/__tests__/BotGroupAvatars.test.tsx
new file mode 100644
index 0000000000..e5a868326f
--- /dev/null
+++ b/apps/mobile/src/__tests__/BotGroupAvatars.test.tsx
@@ -0,0 +1,69 @@
+// @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(() => {
+ // 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),
+ auth: { user: { id: 'owner' }, accountGeneration: 1, apiFetch: vi.fn() } };
+});
+vi.mock('react-native', async () => {
+ const { createElement } = await import('react');
+ return { View: ({ children }: any) => createElement('div', null, children),
+ Image: ({ source, onError }: any) => { h.failImage = onError; return createElement('img', { src: source.uri }); },
+ StyleSheet: { create: (value: any) => value } };
+});
+vi.mock('@/components/AppText', async () => {
+ const { createElement } = await import('react');
+ return { Text: ({ children }: any) => createElement('span', null, children) };
+});
+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('@/theme', async () => ({ ...await import('@/theme/tokens'), useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
+vi.mock('lucide-react-native', () => ({ Users: () => null }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));
+vi.mock('@/session/CompanionPresenceRing', () => ({ CompanionPresenceRing: () => null }));
+vi.mock('@/device-link/remoteResourceCache', () => ({ cachedBotItem: () => null, readRemoteResourceSnapshot: async () => ({}),
+ remoteResourceCacheRevision: () => 0, subscribeRemoteResourceCache: () => () => {} }));
+import { chatGroupView, type ChatSnapshot } from '@/chat/chatServerClient';
+import { BotGroupAvatar, useBotGroupIdentities } from '@/session/BotGroupAvatars';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+beforeEach(() => { h.remoteMedia.mockClear(); h.invoke.mockClear(); });
+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.unstubAllGlobals(); });
+
+it('renders a server member public avatar without computer resolution and recovers after a changed image', async () => {
+ const snapshot: ChatSnapshot = { room: { id: 'group', name: 'Discussion', kind: 'group', archived: false, revision: 1,
+ created_at: '', updated_at: '', response_mode: 'all', speaking_mode: 'auto' }, cursor: '1', messages: [], members: [
+ { id: 'bot', kind: 'bot', name: 'Teammate', state: 'joined', ownerActorId: 'owner', ownerName: '', avatar: 'https://avatars.example.invalid/bot.png', role: 'member' },
+ ] };
+ const Probe = () => {
+ const identityFor = useBotGroupIdentities('');
+ const member = chatGroupView({ snapshot, messages: [], before: null }, 'owner').members[0];
+ return createElement(BotGroupAvatar, { deviceId: '', identity: identityFor(member.botId, member.name, member), size: 28, online: true });
+ };
+ const host = document.createElement('div'); root = createRoot(host);
+ await act(async () => root!.render(createElement(Probe)));
+ expect(host.querySelector('img')?.getAttribute('src')).toBe(snapshot.members[0].avatar);
+ expect(h.remoteMedia).not.toHaveBeenCalled(); expect(h.invoke).not.toHaveBeenCalled();
+ act(() => h.failImage!());
+ expect(host.querySelector('img')).toBeNull(); expect(host.textContent).toBe('T');
+ snapshot.members[0].avatar = 'https://avatars.example.invalid/replaced.png';
+ await act(async () => root!.render(createElement(Probe)));
+ expect(host.querySelector('img')?.getAttribute('src')).toBe(snapshot.members[0].avatar);
+});
+
+it('keeps computer local media avatars on the existing resolver', async () => {
+ h.remoteMedia.mockResolvedValueOnce({ url: 'https://media.example.invalid/thumbnail.png', previewable: true, mimeType: 'image/png' });
+ const host = document.createElement('div'); root = createRoot(host);
+ await act(async () => root!.render(createElement(BotGroupAvatar, {
+ deviceId: 'mac', identity: { botId: 'bot', name: 'Teammate', avatar: { kind: 'media', value: 'cindy-media://avatar/a.png', fallbackText: 'T' } }, size: 28, online: true,
+ })));
+ expect(h.remoteMedia).toHaveBeenCalledExactlyOnceWith({ kind: 'image', url: 'cindy-media://avatar/a.png' }, expect.anything(), { thumbnail: true });
+ expect(host.querySelector('img')?.getAttribute('src')).toBe('https://media.example.invalid/thumbnail.png');
+});
diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.ts
index 3383ca44bd..54d542cf52 100644
--- a/apps/mobile/src/__tests__/chatServerClient.test.ts
+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts
@@ -48,6 +48,17 @@ describe('direct Chat Server client', () => {
expect(view.messages[0]).toMatchObject({ content: '100', authorKind: 'user', isSelf: false });
expect(view.members[0].actorKind).toBe('human');
});
+ it('preserves public, preset and emoji avatars while rejecting private or credentialed addresses', () => {
+ const data = snapshot();
+ const avatars = ['https://avatars.example.invalid/a.png', 'cindy://avatar/preset/cindy', '🐱',
+ 'http://avatars.example.invalid/a.png', 'https://user:[email protected]/a.png', 'cindy-media://avatar/a.png'];
+ data.members = avatars.map((avatar, index) => ({ ...data.members[0], id: id(index + 10), avatar }));
+ const members = chatGroupView({ snapshot: data, messages: [], before: null }, id(1)).members;
+ expect(members.map(member => ({ avatar: member.avatar, avatarUrl: member.avatarUrl }))).toEqual([
+ { avatar: '', avatarUrl: avatars[0] }, { avatar: avatars[1], avatarUrl: null }, { avatar: '🐱', avatarUrl: null },
+ ...Array.from({ length: 3 }, () => ({ avatar: '', avatarUrl: null })),
+ ]);
+ });
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 }))
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
index 7b9708ff36..867e7dc6c9 100644
--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -128,6 +128,23 @@ it.each([403, 404])('clears revoked access immediately when a send returns %s',
expect(chat.online).toBe(false);
await expect(chat.act('send', { text: 'again', clientId: 'fixture-no-page', mentions: { all: false, botIds: [] } })).rejects.toThrow('CHAT_READ_FAILED');
});
+it.each([403, 404])('clears revoked access when attachment authorization returns %s', async (status) => {
+ showChat = true; await render();
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.includes('/media/')) throw Object.assign(new Error('NOT_MEMBER'), { status });
+ return original(path, options);
+ });
+ await act(async () => { await expect(chat.media!(self)).rejects.toMatchObject({ status }); });
+ expect(chat.state.kind).toBe('missing');
+ expect(chat.online).toBe(false);
+});
+it('keeps authorized history when only the attachment is missing', async () => {
+ showChat = true; await render();
+ h.auth.apiFetch.mockRejectedValue(Object.assign(new Error('MEDIA_NOT_FOUND'), { status: 404, code: 'MEDIA_NOT_FOUND' }));
+ await act(async () => { await expect(chat.media!(self)).rejects.toMatchObject({ code: 'MEDIA_NOT_FOUND' }); });
+ expect(chat.state.kind).toBe('ready'); expect(chat.online).toBe(true);
+});
it('clears access on everyone member-read rejection and ignores an older authorized history reply', async () => {
showChat = true; await render();
const original = h.auth.apiFetch.getMockImplementation()!;
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
index 959b164dbf..2cd9aa5bcf 100644
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -73,6 +73,16 @@ export function chatReadAt(snapshot: ChatSnapshot, selfId: string): number {
return chatLastReplyAt(snapshot.messages.filter(message => BigInt(chatCursor(message.seq)) <= BigInt(chatCursor(sequence))), selfId);
}
+/** Public profile images never enter the computer's local media resolver. */
+function chatMemberAvatar(value: string | null): Pick<BotGroupMemberView, 'avatar' | 'avatarUrl'> {
+ const raw = value ?? '';
+ try { return { avatar: '', avatarUrl: chatHttpsUrl(raw) }; } catch { /* Not a public HTTPS image. */ }
+ // The server also accepts the existing bundled presets and short emoji identities.
+ const avatar = /^cindy:\/\/avatar\/preset\/(cindy|dash|lizi)$/.test(raw)
+ || (raw.length <= 16 && !/[a-zA-Z0-9/:\x00-\x1f]/.test(raw)) ? raw : '';
+ return { avatar, avatarUrl: null };
+}
+
/** 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;
@@ -80,7 +90,7 @@ export function chatGroupView(page: ChatPage, selfId: string): BotGroupRemoteCha
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',
+ name: memberName(member), ...chatMemberAvatar(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);
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
index 4fa2785365..5b35879263 100644
--- a/apps/mobile/src/chat/useChatServer.ts
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -238,9 +238,17 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
}
};
const media = async (mediaId: string): Promise<BotGroupAttachment> => {
- const attachment = await api.client.media(groupId, mediaId);
- if (!valid()) throw new Error('OWNER_CHANGED');
- return attachment;
+ const generation = accessGeneration.current;
+ try {
+ const attachment = await api.client.media(groupId, mediaId);
+ if (!valid() || generation !== accessGeneration.current) throw new Error('OWNER_CHANGED');
+ return attachment;
+ } catch (error) {
+ // A missing/deleted attachment is distinct from losing the room's membership.
+ if (valid() && generation === accessGeneration.current && chatAccessLost(error)
+ && (error as { code?: string }).code !== 'MEDIA_NOT_FOUND') loseAccess();
+ throw error;
+ }
};
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/components/RemoteCompanionAvatar.tsx b/apps/mobile/src/components/RemoteCompanionAvatar.tsx
index a3fb2fe884..4474cad9b7 100644
--- a/apps/mobile/src/components/RemoteCompanionAvatar.tsx
+++ b/apps/mobile/src/components/RemoteCompanionAvatar.tsx
@@ -17,18 +17,18 @@ const presets: Record<string, number> = {
};
/** `framed` draws its own circle for callers without an avatar container (inline rows and status lines). */
-export function RemoteCompanionAvatar({ avatar, deviceId, name, online, size = 40, framed = false }: { avatar?: RemoteResourceAvatar; deviceId: string; name: string; online: boolean; size?: number; framed?: boolean }) {
+export function RemoteCompanionAvatar({ avatar, imageUrl, deviceId, name, online, size = 40, framed = false }: { avatar?: RemoteResourceAvatar; imageUrl?: string | null; deviceId: string; name: string; online: boolean; size?: number; framed?: boolean }) {
const { colors } = useTheme();
const auth = useAuth();
const { invoke } = useDeviceLink();
const value = avatar?.value || '';
- const binding = `${auth.accountGeneration}:${deviceId}:${value}`;
+ const binding = `${auth.accountGeneration}:${deviceId}:${value}:${imageUrl ?? ''}`;
const [image, setImage] = useState<{ binding: string; uri: string } | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let cancelled = false;
setFailed(false);
- if (avatar?.kind !== 'media' || !online) return;
+ if (imageUrl || avatar?.kind !== 'media' || !online) return;
const maker = createMobileMakerTransport({ deviceId, invoke });
void resolveMobileRemoteMedia({ kind: 'image', url: value }, {
fetchRemoteMedia: maker.fetchRemoteMedia,
@@ -37,8 +37,8 @@ export function RemoteCompanionAvatar({ avatar, deviceId, name, online, size = 4
if (!cancelled && result.previewable && result.mimeType.startsWith('image/')) setImage({ binding, uri: result.url });
}).catch(() => undefined);
return () => { cancelled = true; };
- }, [auth.apiFetch, avatar?.kind, binding, deviceId, invoke, online, value]);
- const source = presets[value] || (image?.binding === binding ? { uri: image.uri } : null);
+ }, [auth.apiFetch, avatar?.kind, binding, deviceId, imageUrl, invoke, online, value]);
+ const source = imageUrl ? { uri: 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/session/BotGroupAvatars.tsx b/apps/mobile/src/session/BotGroupAvatars.tsx
index e5fbec40a3..70a32fed62 100644
--- a/apps/mobile/src/session/BotGroupAvatars.tsx
+++ b/apps/mobile/src/session/BotGroupAvatars.tsx
@@ -27,6 +27,7 @@ export interface BotGroupIdentity {
botId: string;
name: string;
avatar?: RemoteResourceAvatar;
+ avatarUrl?: string | null;
}
/** Timeline and plan rows: Desktop BotAvatar `sm` / `xs` on a phone. */
@@ -56,20 +57,20 @@ export function useBotGroupIdentities(deviceId: string) {
void readRemoteResourceSnapshot(userId).then(() => { if (current) setLoaded((value) => value + 1); });
return () => { current = false; };
}, [userId]);
- return useCallback((botId: string, fallbackName = '', member?: Pick<BotGroupMemberView, 'name' | 'avatar' | 'avatarColor'>): BotGroupIdentity => {
+ return useCallback((botId: string, fallbackName = '', member?: Pick<BotGroupMemberView, 'name' | 'avatar' | 'avatarColor' | 'avatarUrl'>): BotGroupIdentity => {
void revision; void loaded;
const cached = botId ? cachedBotItem(userId, BOT_GROUP_TEAMMATES_COLLECTION_ID, deviceId, botId) : null;
const cachedName = cached ? resolveRemoteText(cached.display.title, i18n.language) : '';
const name = fallbackName.trim() || member?.name.trim() || cachedName || '';
const avatar = cached?.display.avatar ?? (member ? botGroupMemberAvatar({ ...member, name: member.name || name }) : undefined);
- return { botId, name, ...(avatar ? { avatar } : {}) };
+ return { botId, name, ...(avatar ? { avatar } : {}), ...(member?.avatarUrl ? { avatarUrl: member.avatarUrl } : {}) };
}, [deviceId, i18n.language, loaded, revision, userId]);
}
export function BotGroupAvatar({ deviceId, identity, size, online }: {
deviceId: string; identity: BotGroupIdentity; size: number; online: boolean;
}) {
- return <RemoteCompanionAvatar avatar={identity.avatar} deviceId={deviceId} name={identity.name} online={online} size={size} framed />;
+ return <RemoteCompanionAvatar avatar={identity.avatar} imageUrl={identity.avatarUrl} deviceId={deviceId} name={identity.name} online={online} size={size} framed />;
}
/**