Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 扩大排队消息气泡点击范围 (#4500)
Dash4371950358d2
diff --git a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsxnew file mode 100644index 0000000000..00400a6f76--- /dev/null+++ b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx@@ -0,0 +1,99 @@+// @vitest-environment jsdom+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { GestureResponderEvent } from 'react-native';+import { PendingSendBubble, type PendingSendBubbleActions } from '@/session/PendingSendBubble';+import { MessageBodyText } from '@/session/ShareMessageCheckbox';+import type { MobilePendingSendItem } from '@/session/pendingSendItems';++const { handlers, frames } = vi.hoisted(() => ({+ handlers: new Map<string, Record<string, unknown>>(),+ frames: new Map<number, FrameRequestCallback>(),+}));+vi.mock('react-native', async () => {+ const { createElement } = await import('react');+ const view = (tag: string) => (props: Record<string, unknown> & { children?: ReactNode }) => {+ if (props.testID) handlers.set(String(props.testID), props);+ return createElement(tag, { 'data-testid': props.testID, onClick: props.disabled ? undefined : props.onPress }, props.children);+ };+ return { View: view('div'), Text: view('span'), Pressable: view('button'), ActivityIndicator: () => null,+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 } };+});+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));+vi.mock('lucide-react-native', () => ({ Check: () => null, AlertCircle: () => null, ArrowUp: () => null,+ ListEnd: () => null, Paperclip: () => null, Pencil: () => null, RotateCcw: () => null, Trash2: () => null }));+vi.mock('@/session/SentInlineAtomBody', () => ({ SentInlineAtomBody: () => null }));+vi.mock('@/session/sentAttachmentThumbStore', () => ({ getSentAttachmentThumbUri: () => null,+ useSentAttachmentThumbsVersion: () => 0 }));+vi.mock('react-i18next', () => ({ initReactI18next: { type: '3rdParty', init: () => undefined },+ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/theme', async () => {+ const tokens = await import('@/theme/tokens');+ return { ...tokens, useTheme: () => ({ colors: tokens.lightColors }),+ useThemedStyles: (make: (colors: typeof tokens.lightColors) => unknown) => make(tokens.lightColors) };+});++let root: Root;+let host: HTMLDivElement;+let frameId = 0;+const select = vi.fn();+const openLink = vi.fn();+const item: MobilePendingSendItem = {+ type: 'pending_send', key: 'message-a', clientId: 'a', phase: 'queued', text: 'hello',+ queueIndex: 1, sentInlineTokens: [], thumbs: [], fileCount: 0, attachmentCount: 0, uploadedCount: 0,+ errorText: null, hint: null, actions: {+ remove: { disabled: false, disabledReason: null }, edit: { disabled: false, disabledReason: null },+ steer: { disabled: false, disabledReason: null },+ },+};+beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ handlers.clear(); frames.clear();+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { frames.set(++frameId, cb); return frameId; });+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id));+ host = document.createElement('div'); root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); vi.useRealTimers(); vi.unstubAllGlobals(); });+function show(overrides: Partial<MobilePendingSendItem> = {}, selectedClientId: string | null = null) {+ handlers.clear();+ const actions: PendingSendBubbleActions = { selectedClientId, onSelect: select, onRemove: vi.fn(),+ onBeginEdit: vi.fn(), onSteer: vi.fn(), onRetryOutbox: vi.fn(), onRemoveOutbox: vi.fn() };+ act(() => root.render(<PendingSendBubble item={{ ...item, ...overrides }} actions={actions}+ renderImage={() => null} renderFile={() => null}+ renderText={() => <MessageBodyText testID="link" onPress={openLink}>link</MessageBodyText>} />));+}+function touch(type: 'Start' | 'Move' | 'End' | 'Cancel', x = 0, y = 0, count = type === 'End' ? 0 : 1) {+ const handler = handlers.get('pendingSend.body.a')?.[`onTouch${type}`] as ((e: GestureResponderEvent) => void) | undefined;+ act(() => handler?.({ nativeEvent: { pageX: x, pageY: y, touches: Array(count).fill({}) } } as GestureResponderEvent));+}+function flush() {+ act(() => { for (const [id, callback] of [...frames]) { frames.delete(id); callback(0); } });+}+it.each([null, 'a'])('toggles the same message for selection %s, allowing finger jitter', (selected) => {+ show({}, selected); touch('Start'); touch('Move', 3, 2); touch('End', 3, 2);+ expect(select).not.toHaveBeenCalled(); flush(); flush();+ expect(select.mock.calls).toEqual([[selected ? null : 'a']]);+});+it.each(['move', 'end', 'cancel', 'long', 'multi', 'disabled', 'unmount', 'recycle', 'deselect'])(+ 'does not commit a %s gesture', (kind) => {+ show(); touch('Start');+ if (kind === 'move') touch('Move', 30);+ if (kind === 'cancel') touch('Cancel');+ if (kind === 'long') vi.advanceTimersByTime(500);+ if (kind === 'multi') touch('Start', 0, 0, 2);+ if (kind === 'disabled') show({ actions: null, phase: 'sending' });+ touch('End', kind === 'end' ? 30 : 0);+ if (kind === 'unmount') act(() => root.render(null));+ if (kind === 'recycle') show({ clientId: 'b' });+ if (kind === 'deselect') show({}, 'a');+ flush(); expect(select).not.toHaveBeenCalled();+ },+);+it('lets a real body link consume the pending tap before the frame commits', () => {+ show(); touch('Start'); touch('End');+ act(() => host.querySelector<HTMLElement>('[data-testid="link"]')!.click());+ flush(); expect(openLink).toHaveBeenCalledOnce(); expect(select).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.tsindex ec7de7a728..de506719b2 100644--- a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts@@ -32,7 +32,7 @@ describe('mobile message text selection', () => {expect(source).toContain("if (selectable && allowIosUITextView && Platform.OS === 'ios') {");expect(source).toContain('uiTextView');expect(source).toContain('function MarkdownSelectableSpan(');- expect(source).toContain('const SpanText = ctx.SpanText ?? Text;');+ expect(source).toContain('const SpanText = ctx.SpanText ?? MessageBodyText;');expect(markdownBodySource).toContain('blockSelectable && allowIosUITextView && Platform.OS === \'ios\'');// 气泡是纯 View,不挂 Pressable/onLongPress(避免干扰横向 ScrollView 手势)。diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.tsindex b5e66c57ee..1dd1f826c4 100644--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts@@ -436,7 +436,7 @@ describe('pending_send 渲染接线', () => {expect(bubbleSource).toContain('interactiveAtoms={false}');expect(bubbleSource).toContain('maxVisibleLines={collapsedLines}');expect(bubbleSource).toContain('LONG_USER_MESSAGE_COLLAPSED_LINES');- // 队列操作仅由状态徽标承接,Markdown 横向滚动不嵌套在 Pressable 中。+ // 状态徽标保留独立入口和定位,气泡正文通过 touch end 展开队列操作;移动手势不触发菜单。const badgeStart = bubbleSource.indexOf('<Pressable\n accessibilityHint={item.hint');const badgeEnd = bubbleSource.indexOf('\n </Pressable>', badgeStart);expect(badgeStart).toBeGreaterThan(-1);@@ -448,6 +448,7 @@ describe('pending_send 渲染接线', () => {expect(bubbleSource).toContain('event.nativeEvent.layout.x - 28 - spacing.sm');expect(bubbleSource).toContain('onLayout={hasAttachments ? undefined : measureBadgeAnchor}');expect(bubbleSource.indexOf('testID={`pendingSend.bubble.${item.clientId}`}')).toBeGreaterThan(badgeEnd);+ expect(bubbleSource).toContain('onTouchEnd={interactive ? handleBubbleTouchEnd : undefined}');expect(bubbleSource).toContain('const collapseLatched = collapseLatchBody === displayBody;');expect(bubbleSource).toContain('if (collapseResolved && !collapseLatched) setCollapseLatchBody(displayBody);');expect(bubbleSource).toContain('(measureBody && collapseLatched) || collapseResolved');diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex ac7ad51b48..2629c912df 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -94,6 +94,7 @@ import { isShareableMessage } from '@/session/shareSelectionStore';import {ShareMessageCheckbox,useCancelShareSelectionRowTap,+ MessageBodyText,} from '@/session/ShareMessageCheckbox';import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';import { selectableTextVerticalOffset } from '@/session/selectableTextAlignment';@@ -5583,7 +5584,7 @@ function renderInline(streaming?: boolean;} = {},): ReactNode {- const SpanText = ctx.SpanText ?? Text;+ const SpanText = ctx.SpanText ?? MessageBodyText;const openImage = ctx.onOpenImage ?? (ctx.onOpenPayload? (url: string, alt?: string) => {const title = mobileMarkdownImageTitle(url, alt);diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsxindex d94df86f90..224c650d90 100644--- a/apps/mobile/src/session/PendingSendBubble.tsx+++ b/apps/mobile/src/session/PendingSendBubble.tsx@@ -10,15 +10,17 @@* - ⚠ = 失败,可重试 / 删除。* 「排入队尾」是个事实断言,未确认时画它就是谎报,所以未确认一律转圈。*/-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import { ActivityIndicator, Pressable, StyleSheet, View, type LayoutChangeEvent } from 'react-native';+import { ActivityIndicator, Pressable, StyleSheet, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';import { Text } from '@/components/AppText';import { buildMessageContentLayout } from '@/session/messageContentLayout';import { summarizeMessageBubblePresentation } from '@/session/messagePresentation';import { LONG_USER_MESSAGE_COLLAPSED_LINES, LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD, mayExceedVisualLineThreshold, resolveUserMessageCollapse } from '@/session/userMessageCollapse';import { sentInlineTokensDisplayText } from '@/session/sentMessageAtoms';import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';+import { MessageBodyTapBoundary } from '@/session/ShareMessageCheckbox';+import { shareSelectionTapMoved, shouldCommitShareSelectionTap, type ShareSelectionTapPoint } from '@/session/shareSelectionTap';import {AlertCircle,ArrowUp,@@ -231,6 +233,39 @@ export function PendingSendBubble({const hasBody = !!displayBody;const hasAttachments = item.thumbs.length > 0 || !!item.fileNames?.length;const [badgeAnchor, setBadgeAnchor] = useState<{ clientId: string; left: number } | null>(null);+ const bubbleTouchOriginRef = useRef<{ start: ShareSelectionTapPoint; startedAt: number } | null>(null);+ const pendingCommitFrameRef = useRef<number | null>(null);+ const cancelBubbleTouch = useCallback(() => {+ bubbleTouchOriginRef.current = null;+ if (pendingCommitFrameRef.current !== null) cancelAnimationFrame(pendingCommitFrameRef.current);+ pendingCommitFrameRef.current = null;+ }, []);+ // Invalidate pending taps before a recycled row, disabled state or selection can take over.+ useLayoutEffect(() => cancelBubbleTouch, [cancelBubbleTouch, item.clientId, interactive, selected]);+ const handleBubbleTouchStart = (event: GestureResponderEvent) => {+ cancelBubbleTouch();+ if (event.nativeEvent.touches.length !== 1) return;+ bubbleTouchOriginRef.current = { start: event.nativeEvent, startedAt: Date.now() };+ };+ const handleBubbleTouchMove = (event: GestureResponderEvent) => {+ const origin = bubbleTouchOriginRef.current;+ if (!origin) return;+ if (shareSelectionTapMoved(origin.start, event.nativeEvent)) cancelBubbleTouch();+ };+ const handleBubbleTouchEnd = (event: GestureResponderEvent) => {+ const origin = bubbleTouchOriginRef.current;+ bubbleTouchOriginRef.current = null;+ if (origin && event.nativeEvent.touches.length === 0 && shouldCommitShareSelectionTap({+ durationMs: Date.now() - origin.startedAt,+ moved: shareSelectionTapMoved(origin.start, event.nativeEvent),+ })) {+ // Match share rows: child link onPress gets a turn to consume the gesture.+ pendingCommitFrameRef.current = requestAnimationFrame(() => {+ pendingCommitFrameRef.current = null;+ actions.onSelect(selected ? null : item.clientId);+ });+ }+ };const measureBadgeAnchor = (event: LayoutChangeEvent) => {const left = Math.max(0, event.nativeEvent.layout.x - 28 - spacing.sm);setBadgeAnchor((current) => current?.clientId === item.clientId && current.left === left@@ -295,7 +330,17 @@ export function PendingSendBubble({</View>) : null}{hasBody ? (- <View key={`body:${item.clientId}`} onLayout={hasAttachments ? undefined : measureBadgeAnchor} style={[styles.bubble, density === 'compact' && styles.bubbleCompact, density === 'rich' && styles.bubbleRich]}>+ <MessageBodyTapBoundary value={cancelBubbleTouch}>+ <View+ key={`body:${item.clientId}`}+ onLayout={hasAttachments ? undefined : measureBadgeAnchor}+ onTouchEnd={interactive ? handleBubbleTouchEnd : undefined}+ onTouchMove={interactive ? handleBubbleTouchMove : undefined}+ onTouchStart={interactive ? handleBubbleTouchStart : undefined}+ onTouchCancel={cancelBubbleTouch}+ style={[styles.bubble, density === 'compact' && styles.bubbleCompact, density === 'rich' && styles.bubbleRich]}+ testID={`pendingSend.body.${item.clientId}`}+ >{rendersSentInlineBody ? (<SentInlineAtomBodyinteractiveAtoms={false}@@ -324,12 +369,17 @@ export function PendingSendBubble({{shouldCollapse ? (<Text accessibilityRole="button" suppressHighlightingaccessibilityLabel={expanded ? t('message.renderer.collapseMessage') : t('message.renderer.expandMessage')}- onPress={(event) => { event.stopPropagation(); setExpandedBody(expanded ? null : displayBody); }}+ onPress={(event) => {+ event.stopPropagation();+ cancelBubbleTouch();+ setExpandedBody(expanded ? null : displayBody);+ }}style={styles.collapseToggleText}>{expanded ? t('message.renderer.collapse') : t('message.renderer.expand')}</Text>) : null}</View>+ </MessageBodyTapBoundary>) : null}{(item.fileCount > 0 && !item.fileNames?.length) || uploadsPending ? (<View style={styles.attachmentLine}>diff --git a/apps/mobile/src/session/ShareMessageCheckbox.tsx b/apps/mobile/src/session/ShareMessageCheckbox.tsxindex e291228d79..c119976042 100644--- a/apps/mobile/src/session/ShareMessageCheckbox.tsx+++ b/apps/mobile/src/session/ShareMessageCheckbox.tsx@@ -1,5 +1,6 @@import {createContext,+ type ComponentProps,type ReactNode,useCallback,useContext,@@ -7,6 +8,7 @@ import {useRef,} from "react";import { Check } from "lucide-react-native";+import { Text } from "@/components/AppText";import {Pressable,StyleSheet,@@ -34,6 +36,16 @@ interface ShareSelectionRowGesture {}const ShareSelectionRowInteractionContext = createContext<(() => void) | null>(null);+// Queued bubbles and share rows use the same child-interaction cancellation channel.+export const MessageBodyTapBoundary = ShareSelectionRowInteractionContext.Provider;++export function MessageBodyText(props: ComponentProps<typeof Text>) {+ const cancelRowTap = useCancelShareSelectionRowTap();+ return <Text {...props} onPress={props.onPress ? (event) => {+ cancelRowTap?.();+ props.onPress?.(event);+ } : undefined} />;+}export function useCancelShareSelectionRowTap(): (() => void) | null {return useContext(ShareSelectionRowInteractionContext);