Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): stabilize message arrival and delivery layout
Chris1c4c60f36349
diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsxindex b0d83a5272..6a5413fbf7 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -17,8 +17,8 @@ import { botTaskResultKey, type BotCollaborationMeta } from '@cindy/maker-shared* F-MSG-1: assistant message styling (left-aligned, no bubble)* F-MSG-2: Markdown rendering* message-actions V1.2: hover-revealed bar below the markdown body, left-aligned,- * order [copy][fork][more][time][cost]. Streaming messages do NOT mount the bar (per spec- * "流式期间不挂载"); 且仅当父层标记本消息为 turn 收尾正文(showActionBar)+ * order [copy][fork][more][time][cost]. Streaming messages reserve the bar's height,+ * without mounting its actions; 且仅当父层标记本消息为 turn 收尾正文(showActionBar)* 时才挂载 —— 任务执行过程中的中间句没有操作行。The bar* owns its own fade lifecycle (see MessageActionBar) so this component* only tracks raw hover state.@@ -502,10 +502,9 @@ export const AssistantMessage = memo(function AssistantMessage({data={{ ...card }} sessionId={currentSessionId} attached />)}</div>) : null}- {/* Streaming → bar not mounted at all (V1.2 验收 "流式期间不挂载");- 非 turn 收尾正文(showActionBar=false)同样不挂,消息流保持紧凑。- 伙伴私聊的气泡把操作栏挂在气泡右侧(BubbleHoverToolbar),这里不再另起一行。 */}- {!botBubble && actionBar}+ {/* Reserve the completed toolbar's space while streaming, without showing premature actions.+ Companion hover tools are outside flow and need no footer reservation. */}+ {!botBubble && (isStreaming || showActionBar) ? <div className="min-h-6">{actionBar}</div> : null}</div>);});diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 65bb7159e0..1421d0dc84 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -3,6 +3,7 @@ import { historyAfter } from './historyAfter';import { readMailCard } from '@cindy/maker-shared/ghost-card-form';import { animateFocusScroll } from './animateFocusScroll';import { simplifyBotRenderItems } from '@/features/bots/botConversationPresentation';+import { useMessageEntrance } from './useMessageEntrance';import { isVisibleVoiceCallMessage } from '@/features/bots/voice/voiceCallPresentation';import { MessageViewport, type MessageViewportApi } from './MessageViewport';import { PAGE_TEXT_NAVIGATION_EVENT } from '@/lib/pageTextAccess';@@ -3393,6 +3394,12 @@ export function MessageStream({workGroupProjection,]);const renderMetadataItems = renderMetadataProjection(allRenderItems);+ const entranceSignature = allRenderItems.flatMap(item => item.type === 'message'+ && (item.message.role === 'user' || item.message.role === 'assistant') && !item.message.systemCardType+ && (item.message.content.trim().length > 0 || item.message.images?.length || item.message.files?.length)+ ? [item.key] : []).join('\0');+ const entranceKeys = useMemo(() => entranceSignature ? entranceSignature.split('\0') : [], [entranceSignature]);+ const enterMessage = useMessageEntrance(entranceKeys, !isLoadingMore && (!historySnapshot || historySnapshot.ready));const botMessageTimeGroups = useMemo(() => {if (!simplifiedBotConversation) return new Map<string, number>();return collectBotMessageTimeGroups(@@ -6756,6 +6763,7 @@ export function MessageStream({key={item.key}data-render-item-key={item.key}data-message-client-id={msg.clientId}+ ref={node => enterMessage(node, item.key)}className={cn('scroll-mt-20 transition-colors', highlightClass)}>{startsUnread ? (@@ -6797,6 +6805,7 @@ export function MessageStream({key={item.key}data-render-item-key={item.key}data-message-client-id={msg.clientId}+ ref={node => enterMessage(node, item.key)}{...shareAttributes}className={cn('scroll-mt-20 transition-colors',diff --git a/apps/desktop/src/renderer/components/chat/__tests__/useMessageEntrance.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/useMessageEntrance.test.tsxnew file mode 100644index 0000000000..790578fc4c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/useMessageEntrance.test.tsx@@ -0,0 +1,61 @@+// @vitest-environment jsdom+import { render } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { useMessageEntrance } from '../useMessageEntrance';++// Unit regression for the real DOM entrance hook: history and stream updates must not replay;+// the existing action-bar tests do not mount arriving rows or exercise reduced-motion changes.+const animate = vi.fn();+const cancel = vi.fn();+let reduced: MediaQueryList;+let onChange: (() => void) | undefined;+function Timeline({ keys, visible = keys, ready = true }: { keys: string[]; visible?: string[]; ready?: boolean }) {+ const enter = useMessageEntrance(keys, ready);+ return <>{visible.map(key => <div key={key} ref={node => enter(node, key)}+ style={{ '--motion-base': '200ms', '--motion-ease-out': 'ease-out' } as React.CSSProperties}>{key}</div>)}</>;+}+beforeEach(() => {+ animate.mockReset(); cancel.mockReset(); onChange = undefined;+ animate.mockReturnValue({ cancel, finished: new Promise(() => {}) });+ vi.stubGlobal('matchMedia', vi.fn(() => reduced));+ vi.stubGlobal('getComputedStyle', (node: HTMLElement) => node.style);+ reduced = { matches: false, addEventListener: (_: string, listener: () => void) => { onChange = listener; },+ removeEventListener: vi.fn() } as unknown as MediaQueryList;+ Object.defineProperty(HTMLElement.prototype, 'animate', { configurable: true, value: animate });+});+afterEach(() => { vi.unstubAllGlobals(); delete (HTMLElement.prototype as Partial<HTMLElement>).animate; });++it('animates a live append once, retaining the same node across streaming and acknowledgement', () => {+ const view = render(<Timeline keys={['history']} />);+ expect(animate).not.toHaveBeenCalled();+ view.rerender(<Timeline keys={['history', 'reply']} />);+ const node = view.getByText('reply');+ expect(animate).toHaveBeenCalledTimes(1);+ view.rerender(<Timeline keys={['history', 'reply']} />);+ expect(view.getByText('reply')).toBe(node);+ expect(animate).toHaveBeenCalledTimes(1);+});++it('does not animate initial async history, prepends or virtualization remounts', () => {+ const view = render(<Timeline keys={[]} ready={false} />);+ view.rerender(<Timeline keys={['history']} />);+ view.rerender(<Timeline keys={['older', 'history']} />);+ expect(animate).not.toHaveBeenCalled();+ const keys = ['older', 'history', 'reply'];+ view.rerender(<Timeline keys={keys} />);+ view.rerender(<Timeline keys={keys} visible={['history']} />);+ view.rerender(<Timeline keys={keys} />);+ expect(animate).toHaveBeenCalledTimes(1);+});++it('keeps messages immediate under reduced motion and stops an entrance when the preference changes', () => {+ const view = render(<Timeline keys={[]} />);+ Object.assign(reduced, { matches: true });+ view.rerender(<Timeline keys={['first']} />);+ expect(animate).not.toHaveBeenCalled();+ Object.assign(reduced, { matches: false });+ view.rerender(<Timeline keys={['first', 'next']} />);+ expect(animate).toHaveBeenCalledTimes(1);+ Object.assign(reduced, { matches: true }); onChange?.();+ expect(cancel).toHaveBeenCalledTimes(1);+});diff --git a/apps/desktop/src/renderer/components/chat/useMessageEntrance.ts b/apps/desktop/src/renderer/components/chat/useMessageEntrance.tsnew file mode 100644index 0000000000..1c6846216d--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/useMessageEntrance.ts@@ -0,0 +1,30 @@+import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';+import { appendedMessageKeys } from '@cindy/maker-shared/message-presentation';++/** Animate the existing row, without inserting a wrapper or changing scroll geometry. */+export function useMessageEntrance(keys: readonly string[], ready = true) {+ const previous = useRef<readonly string[] | undefined>(undefined);+ const played = useRef(new Set<string>());+ const arriving = useMemo(() => ({ keys: ready ? appendedMessageKeys(previous.current, keys) : new Set<string>(), at: Date.now() }), [keys, ready]);+ useLayoutEffect(() => { previous.current = ready ? keys : undefined; }, [keys, ready]);++ return useCallback((node: HTMLDivElement | null, key: string) => {+ if (!node || !arriving.keys.has(key) || played.current.has(key) || Date.now() - arriving.at > 1000) return;+ played.current.add(key);+ if (played.current.size > 200) played.current.delete(played.current.values().next().value!);+ if (!window.matchMedia || !node.animate) return;+ const reduced = window.matchMedia('(prefers-reduced-motion: reduce)');+ if (reduced.matches) return;+ const style = getComputedStyle(node);+ const duration = style.getPropertyValue('--motion-base').trim();+ const milliseconds = Number.parseFloat(duration) * (duration.endsWith('ms') ? 1 : 1000);+ if (!Number.isFinite(milliseconds)) return;+ const animation = node.animate([+ { opacity: 0, transform: 'translateY(6px)' },+ { opacity: 1, transform: 'translateY(0)' },+ ], { duration: milliseconds, easing: style.getPropertyValue('--motion-ease-out').trim() });+ const stop = () => { if (reduced.matches) animation.cancel(); };+ reduced.addEventListener('change', stop);+ void animation.finished.catch(() => {}).finally(() => reduced.removeEventListener('change', stop));+ }, [arriving]);+}diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex fdb34ef1b1..47e381ec03 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -1,4 +1,5 @@import { RemoveChatFromListButton } from './RemoveChatFromListButton';+import { useMessageEntrance } from '@/components/chat/useMessageEntrance';import { useThreadPanelResize } from './useThreadPanelResize';import { cn } from '@/lib/utils';/**@@ -476,10 +477,9 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {useEffect(() => { if (unreadReceipts) loadRef.current(); }, [unreadReceipts]);const messageByIdRef = useRef(new Map<string, BotGroupMessageView>());messageByIdRef.current = new Map(realMessages.map((message) => [message.id, message]));- const lastRealSequence = realMessages[realMessages.length - 1]?.sequence ?? 0;- /** Rows after this sequence arrived while the page was open: they fade in. */- const enterAfterRef = useRef<number | null>(null);- if (enterAfterRef.current === null && state.kind === 'ready') enterAfterRef.current = lastRealSequence;+ const entranceSignature = rows.map(message => adoptedKeysRef.current.get(message.id) ?? message.id).join('\0');+ const entranceKeys = useMemo(() => entranceSignature ? entranceSignature.split('\0') : [], [entranceSignature]);+ const enterMessage = useMessageEntrance(entranceKeys, state.kind === 'ready' && !loadingOlder);// Quotes resolve against verified copies only; an unverified original falls back to the snapshot.const quoteSources = useMemo(@@ -1071,7 +1071,6 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {const pendingFor = (planId: string | null) =>planId && planPending?.planId === planId ? planPending.action : null;const canQuote = !!group.serverBacked && !group.archived && !group.dissolvedAt;- const enterAfter = enterAfterRef.current;return (<div ref={threadLayoutRef} className={cn('flex h-full min-w-0 overflow-hidden', threadResize.isDragging && 'select-none [&_*]:cursor-col-resize')}>@@ -1175,7 +1174,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {onChanged={onChanged}highlighted={highlightId === message.id}focusable={jumpTarget === message.id || highlightId === message.id}- entering={enterAfter !== null && (message.pending === true || message.sequence > enterAfter)}+ entranceRef={node => enterMessage(node, adoptedKeysRef.current.get(message.id) ?? message.id)}canContinue={message.id === continueId}continuing={continuing}onContinue={onContinue}diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsxindex 7ac9b70ad7..82067ab267 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx@@ -259,8 +259,8 @@ export interface BotGroupTimelineItemProps {highlighted?: boolean;/** Focusable only as a jump target, so a click elsewhere keeps its usual focus. */focusable?: boolean;- /** Arrived while the reader was watching: fade in (opacity only). */- entering?: boolean;+ /** The timeline owns arrival identity across pending/confirmed delivery and history loads. */+ entranceRef?: (node: HTMLDivElement | null) => void;// Round and plan pieces; the Thread panel leaves them out.canContinue?: boolean;continuing?: boolean;@@ -280,20 +280,20 @@ export interface BotGroupTimelineItemProps {onPlanAutoContinue?: (planId: string, on: boolean) => void;}-function Row({ message, highlighted, focusable, entering, block, children }: {- message: BotGroupTimelineMessage; highlighted?: boolean; focusable?: boolean; entering?: boolean;+function Row({ message, highlighted, focusable, entranceRef, block, children }: {+ message: BotGroupTimelineMessage; highlighted?: boolean; focusable?: boolean; entranceRef?: (node: HTMLDivElement | null) => void;/** Space above: a new author block, a merged line, or a compact system line. */block: 'author' | 'continued' | 'system';children: ReactNode;}) {return (<div+ ref={entranceRef}data-bot-group-message-id={message.id}tabIndex={focusable ? -1 : undefined}className={cn('rounded-lg outline-none transition-colors first:mt-0',block === 'continued' ? 'mt-0.5' : block === 'author' ? 'mt-3.5' : 'mt-3',- entering && 'animate-fade-in motion-reduce:animate-none',highlighted && 'bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)]',)}>@@ -321,7 +321,7 @@ export function botGroupTaskOwned(authorBotId: string | null, members: readonlyfunction BotGroupTimelineItemImpl(props: BotGroupTimelineItemProps) {const { t } = useTranslation();const { message, continued, authorName, members, mentionLabels, locale, shareScope, sharing } = props;- const rowProps = { message, highlighted: props.highlighted, focusable: props.focusable, entering: props.entering };+ const rowProps = { message, highlighted: props.highlighted, focusable: props.focusable, entranceRef: props.entranceRef };if (message.kind === 'round-end') {return (diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsxindex 464a76ae68..a97ab881a6 100644--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx@@ -10,6 +10,7 @@ import { Fragment, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRimport { Bell, BellRing, Check, CornerDownRight, MessageSquareShare, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';+import { useMessageEntrance } from '@/components/chat/useMessageEntrance';import { cn } from '@/lib/utils';import { findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';import { Button } from '@/components/ui/button';@@ -333,6 +334,9 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,[realReplies, pendingSends, pendingMatches],);const rootRows = useMemo(() => projectBotGroupExecutionFailures(root ? [root] : [], executionFailures), [root, executionFailures]);+ const entranceSignature = replyRows.map(message => adoptedKeysRef.current.get(message.id) ?? message.id).join('\0');+ const entranceKeys = useMemo(() => entranceSignature ? entranceSignature.split('\0') : [], [entranceSignature]);+ const enterMessage = useMessageEntrance(entranceKeys, root !== null);const layout = useMemo(() => layoutBotGroupTimeline(replyRows), [replyRows]);const lastRealSequenceRef = useRef(0);lastRealSequenceRef.current = realReplies[realReplies.length - 1]?.sequence ?? 0;@@ -457,6 +461,7 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,return (<BotGroupTimelineItemmessage={message}+ entranceRef={node => enterMessage(node, adoptedKeysRef.current.get(message.id) ?? message.id)}continued={continued}authorName={authorName}avatar={{ name: authorName, avatar: member?.avatar ?? null, avatarUrl: member?.avatarUrl, avatarColor: member?.avatarColor ?? null }}diff --git a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsxindex 9630c70a19..cfb908ac03 100644--- a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx+++ b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx@@ -91,11 +91,12 @@ function show(selectedClientId: string | null = null,viewerDeviceId: string | null = null,busy = false,+ reserveActionRow = true,) {handlers.clear();const actions: PendingSendBubbleActions = { selectedClientId, onSelect: select, onRemove: remove,onBeginEdit: edit, onSteer: steer, onMove: move, onRetryOutbox: retryOutbox, onRemoveOutbox: removeOutbox, busy };- act(() => root.render(<PendingSendBubble item={{ ...item, ...overrides }} actions={actions} viewerDeviceId={viewerDeviceId}+ act(() => root.render(<PendingSendBubble item={{ ...item, ...overrides }} actions={actions} viewerDeviceId={viewerDeviceId} reserveActionRow={reserveActionRow}onOpenImage={openImage}renderImage={() => null} renderFile={() => null}renderText={() => <MessageBodyText testID="link" onPress={openLink}>link</MessageBodyText>} />));@@ -107,6 +108,18 @@ function touch(type: 'Start' | 'Move' | 'End' | 'Cancel', x = 0, y = 0, count =function flush() {act(() => { for (const [id, callback] of [...frames]) { frames.delete(id); callback(0); } });}+// Regression: companion messages settle to a long-press menu, not a 46pt toolbar.+// The pending footer used to collapse on every acknowledgement. Keep failure controls available.+// Unit, real PendingSendBubble entry; existing touch tests only covered the ordinary toolbar layout.+it('does not add an empty toolbar to a companion send, but still exposes retry on failure', () => {+ show({ phase: 'sending', actions: null }, null, null, false, false);+ expect(host.querySelector('[data-testid="pendingSend.statusRow.a"]')).toBeNull();+ show({ phase: 'failed', actions: null }, null, null, false, false);+ const retry = host.querySelector('[data-testid="pendingSend.outboxRetry.a"]') as HTMLButtonElement;+ expect(retry).not.toBeNull();+ act(() => retry.click());+ expect(retryOutbox).toHaveBeenCalledWith('a');+});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();diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex a9c4cb3462..ae08879d4c 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -68,7 +68,7 @@ import {} from './BotGroupAvatars';import { CHAT_HEADER_BLUR_FADE_INSIDE, ChatIdentityHeader } from './ChatIdentityHeader';import { SessionHeaderNativeBlur } from './SessionHeaderNativeControls';-import { CompanionEntering } from './CompanionEntering';+import { CompanionEntering, useMessageEntrances } from './CompanionEntering';import { BotGroupComposer, type BotGroupSendInput } from './BotGroupComposer';import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';import { BotGroupTaskCard } from './BotGroupTaskCard';@@ -432,6 +432,9 @@ export function BotGroupTimeline({const { t, i18n } = useTranslation();const styles = useThemedStyles(makeStyles);const messages = group.messages;+ const entranceSignature = messages.map(message => message.id).join('\0');+ const entranceKeys = useMemo(() => entranceSignature ? entranceSignature.split('\0') : [], [entranceSignature]);+ const enteringMessageKeys = useMessageEntrances(entranceKeys, group.id);const planById = new Map(group.plans.map((plan) => [plan.id, plan]));const openPlan = openBotGroupPlan(group);const followUp = botGroupPlanFollowUp(openPlan);@@ -457,7 +460,7 @@ export function BotGroupTimeline({&& previous?.kind === 'message' && previous.authorKind === 'bot' && previous.authorBotId === message.authorBotId;return <View key={message.id} style={styles.item}>{groupTime !== undefined ? <Text style={styles.time}>{formatBotMessageGroupTime(groupTime, i18n.language)}</Text> : null}- <CompanionEntering id={message.id} createdAt={message.createdAt} kind={message.authorKind === 'user' ? 'send' : 'reply'}>+ <CompanionEntering id={message.id} arrivedAt={enteringMessageKeys.get(message.id)}><BotGroupTimelineItem message={message} continued={continued} member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}quoteDisplay={message.quote ? resolveBotGroupQuote(message.quote, messages) : undefined}members={group.members} deviceId={deviceId} online={online} identityFor={identityFor} mentionLabels={mentionLabels}diff --git a/apps/mobile/src/session/CompanionEntering.tsx b/apps/mobile/src/session/CompanionEntering.tsxindex 71d5d9d412..0aa774ede3 100644--- a/apps/mobile/src/session/CompanionEntering.tsx+++ b/apps/mobile/src/session/CompanionEntering.tsx@@ -1,11 +1,22 @@-import { useEffect, useRef, type ReactNode } from 'react';+import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from 'react';+import { appendedMessageKeys } from '@cindy/maker-shared/message-presentation';import { Animated, Easing } from 'react-native';import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';import { motionDuration, motionEasing } from '@/theme';-/** Only messages this recent animate: history loads, remounts and recycled cells stay still. */-const FRESH_MS = 15_000;-/** Fresh ids already played, so a remount inside FRESH_MS stays still. Old rows never need an entry. */+/** Only live tail additions animate; creation time does not tell us when a reply was revealed. */+export function useMessageEntrances(keys: readonly string[], scope: string | undefined, ready = true) {+ const previous = useRef<{ scope: string | undefined; keys: readonly string[] } | null>(null);+ const arriving = useMemo(() => {+ const added = ready ? appendedMessageKeys(previous.current && previous.current.scope === scope ? previous.current.keys : undefined, keys) : [];+ const now = Date.now();+ return new Map([...added].map(key => [key, now]));+ }, [keys, scope, ready]);+ useLayoutEffect(() => { previous.current = ready ? { scope, keys } : null; }, [keys, scope, ready]);+ return arriving;+}++/** A recycled or acknowledged message must not replay its entrance. */const MAX_REMEMBERED = 200;const animated = new Set<string>();@@ -22,13 +33,13 @@ export function CompanionFadeIn({ play, distance, scaleFrom, duration = motionDuif (run.current === null) run.current = play && reduceMotion === false;const progress = useRef(new Animated.Value(run.current ? 0 : 1)).current;useEffect(() => {- if (!run.current) return;+ if (!run.current || reduceMotion !== false) { progress.setValue(1); return; }const timing = Animated.timing(progress, {toValue: 1, duration, delay, easing: Easing.bezier(...motionEasing.out), useNativeDriver: true,});timing.start();return () => timing.stop();- }, [delay, duration, progress]);+ }, [delay, duration, progress, reduceMotion]);if (!run.current) return <>{children}</>;const transform = [{ translateY: progress.interpolate({ inputRange: [0, 1], outputRange: [distance, 0] }) },@@ -39,23 +50,34 @@ export function CompanionFadeIn({ play, distance, scaleFrom, duration = motionDu/*** Entering motion for a companion conversation row (M4 / M5). Keyed by message: a row animates at- * most once and only while it is new (created within FRESH_MS). Your message rises 8pt from 0.96;- * a teammate's finished reply rises 6pt (replies never stream).+ * most once, when it is appended to an already open timeline. History stays still and a slow+ * reply gets the same entrance as a fast one. Never scale text or change row layout.*/-export function CompanionEntering({ id, createdAt, kind, children }: {- id: string; createdAt: string | number | undefined; kind: 'send' | 'reply'; children: ReactNode;+export function CompanionEntering({ id, arrivedAt, children }: {+ id: string; arrivedAt?: number; children: ReactNode;}) {- const fresh = useRef<boolean | null>(null);- if (fresh.current === null) {- const at = typeof createdAt === 'number' ? createdAt : createdAt ? Date.parse(createdAt) : Number.NaN;- fresh.current = !animated.has(id) && Number.isFinite(at) && Date.now() - at < FRESH_MS;- if (fresh.current) {- animated.add(id);- // Insertion order: the oldest id is almost always past FRESH_MS; at worst a remount replays it once.- if (animated.size > MAX_REMEMBERED) animated.delete(animated.values().next().value!);- }- }- return <CompanionFadeIn play={fresh.current} distance={kind === 'send' ? 8 : 6} scaleFrom={kind === 'send' ? 0.96 : undefined}>+ // Cells first mounted later by scrolling are history, even if their list projection is unchanged.+ const entering = arrivedAt !== undefined && Date.now() - arrivedAt < 1000;+ const reduceMotion = useReduceMotionEnabled();+ const progress = useRef(new Animated.Value(entering && !animated.has(id) && reduceMotion === false ? 0 : 1)).current;+ const animation = useRef<Animated.CompositeAnimation | null>(null);+ useLayoutEffect(() => {+ if (!entering || animated.has(id)) return;+ animated.add(id);+ if (animated.size > MAX_REMEMBERED) animated.delete(animated.values().next().value!);+ if (reduceMotion !== false) { progress.setValue(1); return; }+ progress.setValue(0);+ animation.current = Animated.timing(progress, { toValue: 1, duration: motionDuration.base,+ easing: Easing.bezier(...motionEasing.out), useNativeDriver: true });+ animation.current.start();+ }, [entering, id, progress, reduceMotion]);+ useLayoutEffect(() => {+ if (reduceMotion !== false) { animation.current?.stop(); progress.setValue(1); }+ return () => { animation.current?.stop(); progress.setValue(1); };+ }, [id, progress, reduceMotion]);+ return <Animated.View style={{ opacity: progress, transform: [+ { translateY: progress.interpolate({ inputRange: [0, 1], outputRange: [6, 0] }) },+ ] }}>{children}- </CompanionFadeIn>;+ </Animated.View>;}diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 5813ff8ae2..5f2785f750 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -34,7 +34,7 @@ import { extractPayloadToolResultMedia, managedToolMediaKind } from '@cindy/makeimport { AuthorizationMessageCard } from './AuthorizationMessageCard';import { collectBotMessageTimeGroups, formatBotMessageGroupTime, type BotTimelineMessage } from '@cindy/maker-shared/botTimeline';import { CompanionMessageCard } from '@/session/CompanionMessageCard';-import { CompanionEntering } from '@/session/CompanionEntering';+import { CompanionEntering, useMessageEntrances } from '@/session/CompanionEntering';import { LOCAL_SEND_FRESH_MS, localSendStartedAt } from '@/session/localSendMotion';import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';import { createScrollDebugSampler } from '@/debug/scrollDebugSampler';@@ -477,7 +477,9 @@ const MOBILE_MESSAGE_DRAW_DISTANCE = 800;const FOLDABLE_HEADER_HIT_SLOP = { bottom: 10, left: 4, right: 4, top: 10 };function mobileMessageListItemType(item: MobileMessageRenderItem): MobileMessageRenderItem['type'] {- return item.type;+ // An acknowledgement is the same list cell. Changing LegendList's item type here+ // discards its measured row just as the local bubble becomes a persisted message.+ return item.type === 'pending_send' ? 'message' : item.type;}function resolveMobileMessageHistoryAnchorOffset(@@ -683,6 +685,7 @@ interface MessageActions {companionQuoteActions?: CompanionQuoteActions;/** VoiceOver / TalkBack on: the long-press menu has no screen-reader entry, keep the action row. */screenReaderEnabled?: boolean;+ enteringMessageKeys?: ReadonlyMap<string, number>;onCompanionReadThrough?: (at: number) => void;onOpenCompanionSettings?: (page: 'memory' | 'capabilities') => void;companionWorkingLabel?: string | null;@@ -1829,10 +1832,18 @@ export function MessageRenderer({};}, [companion, companionQuote, lastCompanionReplyKey]);const screenReaderEnabled = useScreenReaderEnabled();+ const entranceSignature = listData.flatMap(item => item.type === 'pending_send'+ || item.type === 'message' && !item.message.systemCardType+ && (item.message.body.trim().length > 0 || item.message.attachments?.length)+ && (item.message.kind === 'user' || item.message.kind === 'assistant') ? [item.key] : []).join('\0');+ const entranceKeys = useMemo(() => entranceSignature ? entranceSignature.split('\0') : [], [entranceSignature]);+ const enteringMessageKeys = useMessageEntrances(entranceKeys, scrollResetKey,+ !syncingWhileEmpty && !historyPositioning && historyActive && !loadingEarlier);const actions: MessageActions & { firstUserMessageClientId?: string } = useMemo(() => ({companion,companionQuoteActions,screenReaderEnabled,+ enteringMessageKeys,companionWorkingLabel,onOpenCompanionSettings,companionAvatar,@@ -1877,6 +1888,7 @@ export function MessageRenderer({companion,companionQuoteActions,screenReaderEnabled,+ enteringMessageKeys,companionWorkingLabel,onOpenCompanionSettings,companionAvatar,@@ -3098,6 +3110,8 @@ const RenderItemView = memo(function RenderItemView({<PendingSendBubbleactions={actions.pendingSend}item={item}+ reserveActionRow={!(actions.companion && !actions.screenReaderEnabled+ && (Platform.OS === 'ios' ? usesSystemActionMenu() : usesNativePullDownMenu()))}renderReplyQuote={actions.companionQuoteActions ? (quote) => (<View style={styles.companionQuote}><BotGroupQuote display={companionReplyQuoteDisplay(quote,@@ -3147,16 +3161,10 @@ const RenderItemView = memo(function RenderItemView({const alignWithReplies = !!actions.companionAvatar && actions.companion&& (item.type === 'work_group' || (item.type === 'message' && !!item.message.companion));const aligned = alignWithReplies ? <View style={styles.companionAvatarInset}>{node}</View> : node;- // Your own send eases in once, as its local bubble (both chats). Its echo keeps the same key and- // wrapper, so it neither remounts nor replays. Companion chats also ease in a new message or- // finished reply (M4 / M5).- const localSendAt = item.type === 'pending_send' || item.type === 'message'- ? localSendStartedAt(item.key) : null;- const entering = localSendAt !== null- ? <CompanionEntering key={item.key} id={item.key} createdAt={localSendAt} kind="send">{aligned}</CompanionEntering>- : actions.companion && item.type === 'message' && !item.message.systemCardType+ // Keep the same entrance shell across local send, acknowledgement and streaming updates.+ const entering = item.type === 'pending_send' || item.type === 'message' && !item.message.systemCardType&& (item.message.kind === 'user' || item.message.kind === 'assistant')- ? <CompanionEntering key={item.key} id={item.key} createdAt={item.message.createdAt} kind={item.message.kind === 'user' ? 'send' : 'reply'}>{aligned}</CompanionEntering>+ ? <CompanionEntering key={item.key} id={item.key} arrivedAt={actions.enteringMessageKeys?.get(item.key)}>{aligned}</CompanionEntering>: aligned;return (<View style={focused ? styles.focusedItem : undefined} testID={focused ? 'message.focusedItem' : undefined}>@@ -3574,7 +3582,7 @@ function MessageBubble({// 操作行只挂在每轮收尾正文、且该行确实是一条发言(判据见// mobileMessageShowsActionBar):中间句不再逐条带复制/分叉/时间,系统边界卡整行// 不挂。分享态只保留与导出图片一致的消息内容,不显示操作图标、时间或费用。- // 流式回复不挂操作行或状态占位;任务运行状态由底部状态栏展示。+ // 流式期间不显示操作,但保留它最终占用的位置,避免收尾时把正在看的正文推走。const showCompletedActionBar = !shareSelectionActive && mobileMessageShowsActionBar({hasSystemCard: !!item.message.systemCardType,isStreamingAssistant,@@ -3705,8 +3713,9 @@ function MessageBubble({// 都不可用、或开着读屏(长按手势没有读屏入口)时退回原来的操作行,其中「回复」同样放引用。// 长按交给菜单后正文不再就地选字,改由「选择文字」打开。const companionQuote = actions.companionQuoteActions;- const companionMenuEnabled = !!(actions.companion && hasActions && !actions.screenReaderEnabled+ const companionMenuAvailable = !!(actions.companion && !actions.screenReaderEnabled&& (Platform.OS === 'ios' ? usesSystemActionMenu() : usesNativePullDownMenu()));+ const companionMenuEnabled = companionMenuAvailable && hasActions;const bubbleTextSelectable = canSelectVisibleText && !companionMenuEnabled;const replyQuote = companionQuote && item.message.kind === 'user' ? item.message.replyQuote : undefined;const replyTargetId = companionQuote?.showReplyTargets && item.message.kind === 'assistant' && clientId@@ -3821,11 +3830,11 @@ function MessageBubble({// Android's anchored menu opens here rather than wrapping the bubble, which would swallow its taps.const [companionMenuOpen, setCompanionMenuOpen] = useRecyclingState(false);// Long press fails as soon as the finger moves, so tables and code blocks keep scrolling sideways.- const companionMenuGesture = useMemo(() => Gesture.LongPress().minDuration(450).runOnJS(true)+ const companionMenuGesture = useMemo(() => Gesture.LongPress().enabled(companionMenuEnabled).minDuration(450).runOnJS(true).onStart(() => {if (Platform.OS === 'ios') openCompanionActionSheet();else setCompanionMenuOpen(true);- }), [openCompanionActionSheet, setCompanionMenuOpen]);+ }), [companionMenuEnabled, openCompanionActionSheet, setCompanionMenuOpen]);const openMessageActionMenu = useCallback(() => {if (usesSystemActionMenu()) {const disabled = actionBusy@@ -3903,7 +3912,7 @@ function MessageBubble({// The long-press menu lives on the bubble; without one (attachment-only, error) the action row stays.const bubbleShown = item.message.role !== 'error'&& (hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0));- const companionMenuMounted = companionMenuEnabled && bubbleShown;+ const companionMenuMounted = companionMenuAvailable && bubbleShown;// 气泡是纯 View,不承接任何手势:文本选择走正文原生 Text selectable(长按文字就地选择复制),// 气泡上不能挂 Pressable——它会参与触摸协商,干扰正文里表格/代码块横向 ScrollView 的拖动。const bubble = (@@ -3913,7 +3922,7 @@ function MessageBubble({presentation.density === 'compact' && styles.bubbleCompact,presentation.density === 'rich' && styles.bubbleRich,isUser ? styles.userBubble : styles.agentBubble,- companionMenuEnabled && styles.companionMenuBubble,+ companionMenuAvailable && styles.companionMenuBubble,actions.companion && !isUser && !item.message.systemCardType && styles.companionAnswer,hookSource && styles.hookSourceBubble,isUser && !item.message.systemCardType && userBubbleColors@@ -4152,7 +4161,7 @@ function MessageBubble({{item.message.rawError ? <AgentErrorDetails key={item.message.key} message={item.message.rawError} /> : null}</ErrorNotice>) : bubbleShown ? (- companionMenuEnabled ? (+ companionMenuAvailable ? (<GestureDetector gesture={companionMenuGesture}><View style={isUser ? styles.companionMenuUser : styles.companionMenuAgent} testID="companion.messageMenu">{Platform.OS === 'ios' ? bubble : (@@ -4204,10 +4213,11 @@ function MessageBubble({else if (id === 'copy') selectControlAction(id);else if (id === 'share') actions.onEnterShareSelection?.(clientId);else if (messageMenu.some(item => item.id === id)) selectMenuAction(id as MobileMessageMenuActionId);- }} /> : hasActions ? (+ }} /> : hasActions || (!actions.companion && isStreamingAssistant && !shareSelectionActive) ? (<Viewstyle={[styles.messageActionBar,+ styles.messageActionSlot,actionBar.align === 'right' ? styles.userMessageActionBar : styles.agentMessageActionBar,]}testID="message.actionBar"@@ -9470,6 +9480,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({gap: 2,marginTop: 0,},+ messageActionSlot: { minHeight: MESSAGE_CONTROL_TOUCH_SIZE },userMessageActionBar: { justifyContent: 'flex-end' },agentMessageActionBar: { justifyContent: 'flex-start' },messageIconAction: {diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsxindex a3909b22ff..601cfda772 100644--- a/apps/mobile/src/session/PendingSendBubble.tsx+++ b/apps/mobile/src/session/PendingSendBubble.tsx@@ -309,7 +309,10 @@ export function PendingSendBubble({screenWidth,viewerDeviceId,onOpenImage,+ reserveActionRow = true,}: {+ /** Companion long-press menus have no settled footer; don't reserve one while sending. */+ reserveActionRow?: boolean;/** 当前查看设备:排队消息就是本机发的时不显示设备标签(与已发送消息同一规则)。 */viewerDeviceId?: string | null;renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;@@ -609,6 +612,7 @@ export function PendingSendBubble({</Animated.View></View>{/* 气泡下方这一行:送达后正式消息的「复制 / …」也占这一行,状态与操作都放这里,前后行高不变。 */}+ {reserveActionRow || failed || waiting && statusShown || queued && statusShown || selected && outbox ? (<View style={styles.statusRow} testID={`pendingSend.statusRow.${item.clientId}`}>{failed ? (<>@@ -652,6 +656,7 @@ export function PendingSendBubble({</View>) : null}</View>+ ) : null}{/* 有具体原因的失败(比如模型不支持图片)直接写出来,用户才知道该怎么处理;图片没传上去的通用提示由那张图上的重传按钮表达,轻点气泡才看。 */}{item.errorText && (failedImages === 0 || selected) ? (diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex d3fd7804b6..915b19e26e 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -1199,6 +1199,22 @@ existing actions. Other composers keep their existing behavior.#### Motion tokens (the only tier source)+**Message arrival and delivery continuity (2026-10-24).** Keep the existing bubble+colors, shape and typography. Newly appended visible messages enter once with opacity+and a 6px/pt upward translation on `base` / `ease-out`, without scaling text or changing+layout dimensions. Decide arrival from the open timeline's visible message identities,+not the age of the first token: a slow final reply still enters naturally. Initial+history, older pages, window replacement and recycled cells do not replay; streaming+updates and delivery acknowledgement retain their row identity. Reduced motion shows+the final state immediately, including when enabled during an entrance.++Pending mobile sends reserve a footer only where the settled message has an action+row. Companion chats using long-press menus have no empty send footer; real queue,+offline and failure actions remain accessible. Ordinary streamed replies reserve the+eventual action row without exposing unfinished-message actions. Companion menu shells+and avatar columns stay mounted across streaming completion, so enabling actions cannot+recreate the body or change its width. Historical bubble styling stays unchanged.+Global tokens live in `:root` of `apps/desktop/src/renderer/styles/globals.css`; mobile (`apps/mobile`) mirrors same-name same-value constants in `src/theme/tokens.ts` (dual-platform isomorphism, same policy as color tokens, landing with the mobile motion overhaul). **New transitions/animations must reference tokens — no hardcoded durations or cubic-beziers**; 5 interaction-duration tiers + 3 curves, the same philosophy as the §5 radius scale. Values outside the tiers require design review first. Narrow semantic exceptions are recorded directly below.| Token | Value | Use |diff --git a/packages/maker-shared/src/__tests__/messagePresentation.test.ts b/packages/maker-shared/src/__tests__/messagePresentation.test.tsindex 4caa6fac0f..18a8db5214 100644--- a/packages/maker-shared/src/__tests__/messagePresentation.test.ts+++ b/packages/maker-shared/src/__tests__/messagePresentation.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ appendedMessageKeys,buildMessageActionBarPresentation,countMessageRenderItemDiffs,isToolErrorLike,@@ -20,6 +21,23 @@ import type {MessageRenderWorkGroupItem,} from '../messageRender';+// Message entrance timing regression: visible arrivals, not the reply's creation timestamp,+// decide motion. Existing presentation tests did not cover history/acknowledgement transitions.+// Unit: the same classifier is consumed by Desktop and Mobile's real message lists.+describe('appendedMessageKeys', () => {+ it.each([+ [undefined, ['recent-history'], []],+ [[], ['first-send'], ['first-send']],+ [['user'], ['user', 'slow-final-reply'], ['slow-final-reply']],+ [['pending'], ['pending'], []],+ [['user', 'reply'], ['older', 'user', 'reply'], []],+ [['user', 'reply'], ['older', 'user', 'reply', 'next'], ['next']],+ [['user', 'reply'], ['another-window'], []],+ ] as const)('keeps history and stable identities still (%j → %j)', (before, after, expected) => {+ expect([...appendedMessageKeys(before, after)]).toEqual(expected);+ });+});+type TestMessage = MessageRenderNormalizedMessage<MessageRenderSourceMessageLike> & {diff?: unknown;media?: readonly unknown[];diff --git a/packages/maker-shared/src/messagePresentation.ts b/packages/maker-shared/src/messagePresentation.tsindex ce7fa302ad..75c36347f9 100644--- a/packages/maker-shared/src/messagePresentation.ts+++ b/packages/maker-shared/src/messagePresentation.ts@@ -19,6 +19,21 @@ import {type PresentationLocalizer,} from './presentationLocalization';+/** New tail rows only: initial history, prepends and window replacement stay still.+ * Use visible message identities, not creation times: a final reply may become visible+ * minutes after its first token. Streaming and delivery acknowledgements retain the key.+ */+export function appendedMessageKeys(previous: readonly string[] | undefined, next: readonly string[]): Set<string> {+ if (!previous) return new Set();+ const known = new Set(previous);+ let boundary = -1;+ for (let index = next.length - 1; index >= 0; index--) {+ if (known.has(next[index])) { boundary = index; break; }+ }+ if (previous.length > 0 && boundary < 0) return new Set();+ return new Set(next.slice(boundary + 1).filter(key => !known.has(key)));+}+export type MessageFoldHeaderChevronPosition = 'leading' | 'trailing';export type MessageFoldHeaderVariant = 'card' | 'plain';