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。

Merge origin/main into fix/5875-bot-group-image-preview

ficowangdbc23044515d
diff --cc apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
index f38f0ae9ef,0000000000..5e87e6af1a
mode 100644,000000..100644
--- a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
+++ b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
@@@ -1,207 -1,0 +1,201 @@@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';
+import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';
+
+// Group attachments open the real shared ImageLightbox here (#5875): the timeline strip, the payload
+// conversion and the viewer are production code; only native surfaces and unrelated views are replaced.
+const runtime = vi.hoisted(() => ({
+ alerts: [] as unknown[][],
+ imageEvents: new Map<string, { onLoad?: (event: unknown) => void; onError?: () => void }>(),
+}));
+const openBrowserAsync = vi.hoisted(() => vi.fn(async (_url: string) => ({})));
+vi.mock('expo-web-browser', () => ({ openBrowserAsync }));
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('react-native', async () => {
+ const React = await import('react');
+ const view = ({ children, testID, accessibilityLabel, onPress }: any) => React.createElement('div', {
+ 'data-testid': testID, 'aria-label': accessibilityLabel,
+ onClick: onPress ? (event: any) => onPress({ stopPropagation: () => event.stopPropagation() }) : undefined,
+ }, children);
+ class Value { constructor(public value: number) {} interpolate() { return 0; } setValue() {} stopAnimation() {} }
+ return {
+ View: view, Text: view, Pressable: view, ScrollView: view, Modal: view, ActivityIndicator: view,
+ Image: Object.assign(view, { getSize() {} }), StatusBar: () => null,
+ FlatList: ({ data, renderItem }: any) => React.createElement('div', null,
+ data.map((item: unknown, index: number) => React.createElement(React.Fragment, { key: index }, renderItem({ item, index })))),
+ Animated: { Value, View: view, Text: view, createAnimatedComponent: (c: any) => c,
+ timing: () => ({ start() {}, stop() {} }), loop: () => ({ start() {}, stop() {} }), sequence: () => ({ start() {}, stop() {} }) },
+ Platform: { OS: 'android', select: (s: any) => s.android ?? s.default },
+ StyleSheet: { create: (s: any) => s, flatten: (s: any) => s, hairlineWidth: 1, absoluteFill: {}, absoluteFillObject: {} },
+ Easing: { linear: (n: number) => n, bezier: () => (n: number) => n },
+ AccessibilityInfo: {}, Linking: {},
+ Alert: { alert: (...args: unknown[]) => runtime.alerts.push(args) },
+ useWindowDimensions: () => ({ width: 393, height: 851, scale: 2.75, fontScale: 1 }),
+ };
+});
+vi.mock('lucide-react-native', () => Object.fromEntries([
+ 'Database', 'FileArchive', 'FileAudio', 'FileChartColumn', 'FileCode', 'FileImage', 'FileSpreadsheet', 'FileText', 'FileVideo',
+ 'ArrowLeftRight', 'ArrowUp', 'Bot', 'Check', 'ChevronDown', 'ChevronRight', 'ChevronUp', 'Circle', 'CircleAlert', 'CircleCheck',
+ 'CircleDashed', 'CircleStop', 'Copy', 'Ellipsis', 'ExternalLink', 'File', 'Ghost', 'Layers', 'ListTodo', 'LoaderCircle',
+ 'MessageSquarePlus', 'Pen', 'PencilLine', 'RefreshCw', 'Send', 'Share', 'Sparkles', 'Split', 'Timer', 'Trash2', 'TriangleAlert',
+ 'Undo2', 'X',
+].map(name => [name, () => null])));
+vi.mock('react-native-svg', () => ({ default: () => null, Circle: () => null, Path: () => null }));
+vi.mock('react-native-uitextview', () => ({ UITextView: () => null }));
+vi.mock('expo-image', async () => {
+ const { createElement } = await import('react');
+ return { Image: ({ source, onLoad, onError }: any) => {
+ runtime.imageEvents.set(source.uri, { onLoad, onError });
+ return createElement('img', { src: source.uri });
+ } };
+});
+vi.mock('expo-router', () => ({
+ useRouter: () => ({ push: vi.fn() }), useFocusEffect: vi.fn(),
+ useNavigation: () => ({ isFocused: () => true, addListener: () => () => {}, setOptions: () => undefined }),
+}));
+vi.mock('@/device-link/DeviceLinkContext', () => ({
+ useDeviceLink: () => ({ status: 'offline', connectionEpoch: 0, getPresenceAvailability: () => false, invoke: vi.fn(), openLink: vi.fn() }),
+ subscribeRemoteBotChanges: () => () => {},
+}));
+vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ const colors = new Proxy({}, { get: () => '#777777' });
+ return { ...tokens, monoFont: 'monospace', useTheme: () => ({ colors, mode: 'light' }), useThemedStyles: (make: any) => make(colors) };
+});
+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text, MAX_FONT_SIZE_MULTIPLIER: 2 }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));
+vi.mock('@/session/usePluginResultCard', () => ({ usePluginResultCard: () => ({}), useSessionPluginResource: () => ({ title: 'Art' }) }));
+vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({ downloadRemoteMediaShareTemp: vi.fn() }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
+vi.mock('@/session/expandedBlockMemory', () => ({ useFoldableExpandedState: () => [false, vi.fn()] }));
+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, showActionMenu: vi.fn(), usesNativePullDownMenu: () => false, usesSystemActionMenu: () => false }));
+vi.mock('@/session/MobileComposerInputRow', () => ({ MobileComposerInputRow: () => null, MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT: 0, MOBILE_COMPOSER_CONTROL_SIZE: 44 }));
+vi.mock('@/session/NativeVideoPlayer', () => ({ NativeVideoPlayer: () => null }));
+vi.mock('@/session/mermaidWebView', () => ({ MermaidDiagram: () => null }));
+vi.mock('@/session/mathWebView', () => ({ MathFormulaWebView: () => null }));
+vi.mock('@/session/mediaPlayerWebView', () => ({ RemoteMediaPlayerWebView: () => null }));
+vi.mock('@/session/MarkdownBlockContent', () => ({ MarkdownBlockContent: () => null }));
+vi.mock('@/session/MessageActionSheet', () => ({ MessageActionSheet: () => null }));
+vi.mock('@/session/AuthorizationMessageCard', () => ({ AuthorizationMessageCard: () => null }));
+vi.mock('@/session/CompanionMessageActions', () => ({ CompanionMessageActions: () => null }));
+vi.mock('@/session/CompanionMessageCard', () => ({ CompanionMessageCard: () => null }));
+vi.mock('@/session/PendingSendBubble', () => ({ PendingSendBubble: () => null }));
+vi.mock('@/session/messageActions', async (original) => ({ ...await original<object>(), copyMessageText: vi.fn(), writeClipboardText: vi.fn() }));
+vi.mock('@/platform/gestureHandler', async () => {
+ const { View } = await import('react-native');
+ const make = (): any => new Proxy({}, { get: (_target, key) => key === 'then' ? undefined : () => make() });
+ return {
+ GestureHandlerRootView: View,
+ GestureDetector: ({ children }: { children: unknown }) => children,
+ Gesture: { Pan: make, Pinch: make, Tap: make, Exclusive: make, Simultaneous: make },
+ };
+});
+vi.mock('react-native-reanimated', async () => {
+ const { useRef } = await import('react');
+ const native = await import('react-native');
+ return {
+ default: { View: native.View, createAnimatedComponent: (component: unknown) => component },
+ useSharedValue: (initial: number) => useRef({ value: initial }).current,
+ useAnimatedStyle: (calculate: () => unknown) => ({ get current() { return calculate(); } }),
+ runOnJS: (fn: (...args: unknown[]) => unknown) => fn,
+ cancelAnimation: () => undefined,
+ withTiming: (target: number) => target,
+ withSpring: (target: number) => target,
+ withDecay: () => 0,
+ };
+});
+
+import { BotGroupMessageAttachments } from '@/session/BotGroupMessageAttachments';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+let host: HTMLDivElement | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; host?.remove(); host = undefined; });
+beforeEach(() => { runtime.alerts = []; runtime.imageEvents.clear(); openBrowserAsync.mockClear(); });
+
+// Placeholder for a short-lived authorized address; never a real signed URL.
+const signedImageUrl = 'https://chat.example.invalid/media/group-picture.png?signature=placeholder';
+const serverAttachment: BotGroupAttachment = { id: 'media-1', name: '1.png', category: 'file', mimeType: '', size: 0, url: null, path: null };
+
+async function render(props: Partial<Parameters<typeof BotGroupMessageAttachments>[0]>) {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
+ messageId: 'message-1', align: 'right', attachments: [serverAttachment],
+ onResolveRemoteMedia: vi.fn<ResolveRemoteMediaFn>(), ...props,
+ })));
+ return host;
+}
+
+const click = (element: Element | null | undefined) => act(async () => { (element as HTMLElement).click(); });
+const loadFailedKey = 'message.lightbox.loadFailed';
+
+describe('Chat Server group image attachments (#5875)', () => {
+ it('shows an authorized HTTPS image in the real lightbox, re-authorizing on every tap', async () => {
+ const resolveServerMedia = vi.fn(async (id: string): Promise<BotGroupAttachment> => ({
+ id, name: '1.png', category: 'image', mimeType: 'image/png', size: 10, url: signedImageUrl, path: null,
+ }));
+ const container = await render({ resolveServerMedia });
+ // The timeline keeps a file chip and never holds the signed address.
+ expect(container.querySelector('img')).toBeNull();
+ expect(container.innerHTML).not.toContain(signedImageUrl);
+
+ await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
+ expect(resolveServerMedia).toHaveBeenCalledWith('media-1');
+ const viewer = container.querySelector('[data-testid="message.imageLightbox"]');
+ expect(viewer?.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
+ expect(container.textContent).not.toContain(loadFailedKey);
+ act(() => runtime.imageEvents.get(signedImageUrl)!.onLoad?.({ source: { width: 1200, height: 900 } }));
+ expect(container.textContent).not.toContain(loadFailedKey);
+
+ await click(container.querySelector('[data-testid="message.imageLightboxCloseButton"]'));
+ expect(container.querySelector('[data-testid="message.imageLightbox"]')).toBeNull();
+ expect(container.innerHTML).not.toContain(signedImageUrl);
+
+ await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);
+ expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);
+ });
+
+ it('opens a non-image server file through its short-lived download address, not the viewer', async () => {
+ const fileUrl = 'https://chat.example.invalid/media/report.pdf?signature=placeholder';
+ const resolveServerMedia = vi.fn(async (id: string): Promise<BotGroupAttachment> => ({
+ id, name: 'report.pdf', category: 'file', mimeType: 'application/pdf', size: 10, url: fileUrl, path: null,
+ }));
+ const container = await render({ resolveServerMedia, attachments: [{ ...serverAttachment, name: 'report.pdf' }] });
+ await click(container.querySelector('[data-testid^="message.filePreviewButton"]'));
+ expect(openBrowserAsync).toHaveBeenCalledWith(fileUrl);
+ expect(container.querySelector('[data-testid="message.imageLightbox"]')).toBeNull();
+ });
-
- it('names an attachment whose message has no caption', async () => {
- const container = await render({ resolveServerMedia: vi.fn(), attachments: [{ ...serverAttachment, name: '' }] });
- const chip = container.querySelector('[data-testid="message.filePreviewButton"]');
- expect(chip?.textContent).toBe('groupChat.server.attachmentName');
- });
+});
+
+describe('computer-hosted group image attachments', () => {
+ it.each(['cindy-media://blobs/aa11bb22.png', 'xdt-image://cache/group-picture.png'])(
+ 'still fetches %s from the computer for the real lightbox',
+ async (mediaUrl) => {
+ const originalUrl = 'file:///cache/group-picture-original.png';
+ const resolveMedia = vi.fn<ResolveRemoteMediaFn>(async (media) => ({
+ url: media.thumbnail ? 'https://example.invalid/thumbnail.png' : originalUrl,
+ previewable: true, mimeType: 'image/png', ossKey: 'group-picture', size: 10, expiresAt: '',
+ }));
+ const container = await render({
+ onResolveRemoteMedia: resolveMedia,
+ attachments: [{ id: 'local', name: 'group-picture.png', category: 'image', mimeType: 'image/png', size: 10, url: mediaUrl, path: null }],
+ });
+ await click(container.querySelector('[data-testid="message.mediaPreviewButton"]'));
+ expect(resolveMedia).toHaveBeenCalledWith(expect.objectContaining({ url: mediaUrl, previewable: false }), expect.anything());
+ expect(resolveMedia).toHaveBeenCalledWith(expect.not.objectContaining({ thumbnail: true }), expect.anything());
+ const viewer = container.querySelector('[data-testid="message.imageLightbox"]');
+ expect(viewer?.querySelector(`img[src="${originalUrl}"]`)).not.toBeNull();
+ expect(container.textContent).not.toContain(loadFailedKey);
+ },
+ );
+});
diff --cc apps/mobile/src/__tests__/fileChipNameWidth.test.tsx
index e4a5f7fe42,0000000000..bdad157500
mode 100644,000000..100644
--- a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx
+++ b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx
@@@ -1,159 -1,0 +1,159 @@@
+// @vitest-environment jsdom
+import { act, createElement, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';
+import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';
+
+// Keeps the rendered React Native styles of the real file chip (#5875). Node has no Yoga, so the
+// content-sized width below applies Yoga's own flex-basis rule to those styles instead of a layout pass.
+vi.mock('react-native', async () => {
+ const React = await import('react');
+ const flatten = (style: unknown): Record<string, unknown> => Array.isArray(style)
+ ? Object.assign({}, ...style.map(flatten))
+ : style && typeof style === 'object' ? style as Record<string, unknown> : {};
+ const view = ({ children, testID, style }: any) => React.createElement('div', {
+ 'data-testid': testID,
+ 'data-style': JSON.stringify(flatten(typeof style === 'function' ? style({ pressed: false }) : style)),
+ }, children);
+ class Value { constructor(public value: number) {} interpolate() { return 0; } setValue() {} stopAnimation() {} }
+ return {
+ View: view, Text: view, Pressable: view, ScrollView: view, Modal: () => null, ActivityIndicator: view,
+ Image: Object.assign(view, { getSize() {} }), StatusBar: () => null,
+ Animated: { Value, View: view, Text: view, createAnimatedComponent: (c: any) => c,
+ timing: () => ({ start() {}, stop() {} }), loop: () => ({ start() {}, stop() {} }), sequence: () => ({ start() {}, stop() {} }) },
+ Platform: { OS: 'android', select: (s: any) => s.android ?? s.default },
+ StyleSheet: { create: (s: any) => s, flatten, hairlineWidth: 1, absoluteFill: {}, absoluteFillObject: {} },
+ Easing: { linear: (n: number) => n, bezier: () => (n: number) => n },
+ AccessibilityInfo: {}, Alert: { alert: vi.fn() }, Linking: {},
+ useWindowDimensions: () => ({ width: 393, height: 851, scale: 2.75, fontScale: 1 }),
+ };
+});
+vi.mock('expo-web-browser', () => ({ openBrowserAsync: vi.fn() }));
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('lucide-react-native', () => Object.fromEntries([
+ 'Database', 'FileArchive', 'FileAudio', 'FileChartColumn', 'FileCode', 'FileImage', 'FileSpreadsheet', 'FileText', 'FileVideo',
+ 'ArrowLeftRight', 'ArrowUp', 'Bot', 'Check', 'ChevronDown', 'ChevronRight', 'ChevronUp', 'Circle', 'CircleAlert', 'CircleCheck',
+ 'CircleDashed', 'CircleStop', 'Copy', 'Ellipsis', 'ExternalLink', 'File', 'Ghost', 'Layers', 'ListTodo', 'LoaderCircle',
+ 'PencilLine', 'RefreshCw', 'Send', 'Share', 'Sparkles', 'Split', 'Timer', 'Trash2', 'TriangleAlert', 'Undo2', 'X',
+].map(name => [name, () => null])));
+vi.mock('react-native-svg', () => ({ default: () => null, Circle: () => null, Path: () => null }));
+vi.mock('react-native-uitextview', () => ({ UITextView: () => null }));
+vi.mock('expo-image', () => ({ Image: () => null }));
+vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }), useFocusEffect: vi.fn(), useNavigation: () => ({ isFocused: () => true, addListener: () => () => {} }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({
+ useDeviceLink: () => ({ status: 'offline', connectionEpoch: 0, getPresenceAvailability: () => false, invoke: vi.fn(), openLink: vi.fn() }),
+ subscribeRemoteBotChanges: () => () => {},
+}));
+vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ const colors = new Proxy({}, { get: () => '#777777' });
+ return { ...tokens, monoFont: 'monospace', useTheme: () => ({ colors, mode: 'light' }), useThemedStyles: (make: any) => make(colors) };
+});
+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text, MAX_FONT_SIZE_MULTIPLIER: 2 }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));
+vi.mock('@/session/usePluginResultCard', () => ({ usePluginResultCard: () => ({}), useSessionPluginResource: () => ({ title: 'Art' }) }));
+vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({ downloadRemoteMediaShareTemp: vi.fn() }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
+vi.mock('@/session/expandedBlockMemory', () => ({ useFoldableExpandedState: () => [false, vi.fn()] }));
+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, showActionMenu: vi.fn(), usesNativePullDownMenu: () => false, usesSystemActionMenu: () => false }));
+vi.mock('@/session/MobileComposerInputRow', () => ({ MobileComposerInputRow: () => null, MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT: 0, MOBILE_COMPOSER_CONTROL_SIZE: 44 }));
+vi.mock('@/session/ImageLightbox', () => ({ ImageLightbox: () => null }));
+vi.mock('@/session/mermaidWebView', () => ({ MermaidDiagram: () => null }));
+vi.mock('@/session/mathWebView', () => ({ MathFormulaWebView: () => null }));
+vi.mock('@/session/mediaPlayerWebView', () => ({ RemoteMediaPlayerWebView: () => null }));
+vi.mock('@/session/MarkdownBlockContent', () => ({ MarkdownBlockContent: () => null }));
+vi.mock('@/session/MessageActionSheet', () => ({ MessageActionSheet: () => null }));
+vi.mock('@/session/AuthorizationMessageCard', () => ({ AuthorizationMessageCard: () => null }));
+vi.mock('@/session/CompanionMessageActions', () => ({ CompanionMessageActions: () => null }));
+vi.mock('@/session/CompanionMessageCard', () => ({ CompanionMessageCard: () => null }));
+vi.mock('@/session/PendingSendBubble', () => ({ PendingSendBubble: () => null }));
+vi.mock('@/session/messageActions', async (original) => ({ ...await original<object>(), copyMessageText: vi.fn(), writeClipboardText: vi.fn() }));
+
+import { BotGroupMessageAttachments } from '@/session/BotGroupMessageAttachments';
+import { AttachmentStrip } from '@/session/MessageRenderer';
+import { buildMessageContentLayout } from '@/session/messageContentLayout';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+let host: HTMLDivElement | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; host?.remove(); host = undefined; });
+
+type Style = Record<string, unknown>;
+const styleOf = (element: Element): Style => JSON.parse(element.getAttribute('data-style') ?? '{}');
+const px = (value: unknown) => (typeof value === 'number' ? value : 0);
+/** Deterministic stand-in for measured text: caption glyphs at about 7pt each. */
+const textWidth = (name: string) => name.length * 7;
+
+/**
+ * The chip's width when its row is content-sized (left-aligned strip, unstretched wrapper), with
+ * Yoga's rule from `Node::processFlexBasis`: `flex > 0` without an explicit basis resolves to 0 points,
+ * otherwise the basis is the content. Only a shrinkable name gives way to the chip's max width.
+ */
+function contentSizedChip(chip: Element) {
+ const chipStyle = styleOf(chip);
+ const [iconFrame, nameBox] = Array.from(chip.children);
+ const nameStyle = styleOf(nameBox);
+ const name = nameBox.textContent ?? '';
+ const basis = typeof nameStyle.flexBasis === 'number' ? nameStyle.flexBasis
+ : px(nameStyle.flex) > 0 ? 0 : textWidth(name);
+ const fixed = px(chipStyle.paddingHorizontal) * 2 + px(styleOf(iconFrame).width) + px(chipStyle.gap);
+ const maxWidth = px(chipStyle.maxWidth);
+ const shrinks = px(nameStyle.flexShrink) > 0 || px(nameStyle.flex) > 0;
+ const nameWidth = fixed + basis > maxWidth && shrinks ? Math.max(0, maxWidth - fixed) : basis;
+ return { chip: Math.min(maxWidth, fixed + nameWidth), name: nameWidth, maxWidth };
+}
+
+const shortName = '1.png';
+const longName = `${'quarterly-group-report-'.repeat(8)}.png`;
+
+async function renderServerGroup(align: 'left' | 'right', name: string) {
+ const attachment: BotGroupAttachment = { id: 'media-1', name, category: 'file', mimeType: '', size: 0, url: null, path: null };
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
+ messageId: 'message-1', align, attachments: [attachment],
+ onResolveRemoteMedia: vi.fn<ResolveRemoteMediaFn>(), resolveServerMedia: vi.fn(),
+ })));
+ return host.querySelector('[data-testid^="message.filePreviewButton"]')!;
+}
+
+async function renderSessionStrip(align: 'left' | 'right', name: string) {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => root!.render(createElement(AttachmentStrip, {
+ attachments: [{ kind: 'file', name, previewable: false }], messageKey: 'message-1', align,
+ layout: buildMessageContentLayout({ screenWidth: 393 }), usePreviewState: useState, onOpen: vi.fn(),
+ })));
+ return host.querySelector('[data-testid^="message.filePreviewButton"]')!;
+}
+
+describe('file chip names keep their width when the chip is content-sized (#5875)', () => {
+ it.each([
+ ['server group', 'right', 'short', shortName], ['server group', 'left', 'short', shortName],
+ ['server group', 'right', 'long', longName], ['server group', 'left', 'long', longName],
- ['server group', 'right', 'empty caption', ''], ['task message', 'left', 'short', shortName], ['task message', 'left', 'long', longName],
++ ['task message', 'left', 'short', shortName], ['task message', 'left', 'long', longName],
+ ] as const)('%s, %s aligned, %s name', async (surface, align, _label, name) => {
+ const chip = surface === 'server group' ? await renderServerGroup(align, name) : await renderSessionStrip(align, name);
+ const width = contentSizedChip(chip);
+ expect(width.maxWidth).toBe(228);
+ expect(width.name).toBeGreaterThan(0);
+ expect(width.chip).toBeLessThanOrEqual(228);
+ if (name === longName) expect(width.chip).toBe(228);
+ });
+
+ it('stretches each server attachment like a task strip, so the user side keeps the task-message chip width', async () => {
+ for (const align of ['left', 'right'] as const) {
+ const chip = await renderServerGroup(align, shortName);
+ const wrapper = chip.parentElement!.parentElement!.parentElement!;
+ expect(styleOf(wrapper).alignSelf).toBe('stretch');
+ act(() => root?.unmount()); root = undefined; host?.remove();
+ }
+ });
+});
diff --cc apps/mobile/src/session/BotGroupMessageAttachments.tsx
index fe90831aad,a879877bdc..1722bc8e4c
--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx
+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
@@@ -6,9 -6,10 +6,10 @@@
* 旧电脑文件仍提示在电脑打开;服务器附件点击时独立授权,图片复用看图器,文件使用短期下载地址。
*/
import { openBrowserAsync } from 'expo-web-browser';
- import { useTheme } from '@/theme';
+ import { Text } from '@/components/AppText';
+ import { spacing, textStyles, useTheme } from '@/theme';
import { useEffect, useMemo, useRef, useState } from 'react';
-import { ActivityIndicator, Alert, View, useWindowDimensions } from 'react-native';
+import { ActivityIndicator, Alert, StyleSheet, View, useWindowDimensions } from 'react-native';
import { useTranslation } from 'react-i18next';
import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';
import { ImageLightbox } from './ImageLightbox';
@@@ -97,14 -140,15 +144,18 @@@ function ServerAttachments({ runs, alig
finally { pending.current = false; if (mounted.current) setBusy(null); }
};
return <>
+ {/* Stretch like a session strip, so the chip keeps the same width as in a task message. */}
- {attachments.map(attachment => <View key={attachment.id} style={styles.serverAttachment}>
- <AttachmentStrip attachments={[{ kind: 'file', name: attachment.name || t('groupChat.server.attachmentName'), previewable: false }]}
- messageKey={attachment.id} align={align} layout={layout} onOpen={() => { void open(attachment.id); }} usePreviewState={useState} />
- {busy === attachment.id
- ? <ActivityIndicator color={colors.textSecondary} style={align === 'right' ? styles.busyRight : styles.busyLeft} />
- : null}
- </View>)}
+ {runs.map(run => run.kind === 'pending'
+ ? <PendingAttachment key={run.attachment.id} attachment={run.attachment} align={align} layout={layout} />
- : <View key={run.attachments[0]!.id}>
++ : <View key={run.attachments[0]!.id} style={styles.serverAttachment}>
+ {/* No URL before tapping: every entry is a file chip, addressed by position rather than name. */}
+ <AttachmentStrip attachments={run.attachments.map(attachment => ({ kind: 'file', name: attachment.name, previewable: false }))}
+ messageKey={run.attachments[0]!.id} align={align} layout={layout}
+ onOpenFile={index => { void open(run.attachments[index]!.id); }} usePreviewState={useState} />
- {run.attachments.some(attachment => busy === attachment.id) ? <ActivityIndicator color={colors.textSecondary} /> : null}
++ {run.attachments.some(attachment => busy === attachment.id)
++ ? <ActivityIndicator color={colors.textSecondary} style={align === 'right' ? styles.busyRight : styles.busyLeft} />
++ : null}
+ </View>)}
{image?.url ? <ImageLightbox images={botGroupAttachmentGallery(image.id, [botGroupAttachmentForDisplay(image)])}
initialUrl={image.url} onClose={() => setImage(null)} /> : null}
</>;