Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 伙伴私聊长按菜单、引用回复与回复对应的消息
zqchris4d2f634baea8
diff --git a/apps/desktop/src/shared/chatReplyQuote.ts b/apps/desktop/src/shared/chatReplyQuote.tsindex c249d2b209..9a80c7e0ec 100644--- a/apps/desktop/src/shared/chatReplyQuote.ts+++ b/apps/desktop/src/shared/chatReplyQuote.ts@@ -1,33 +1 @@-/**- * 伙伴私聊的「引用回复」(docs/product-rules/cindy-bots-runtime.md「私聊引用回复」)。- *- * 主人引用私聊里的某条消息回复:用户消息的内容信封带上 `replyQuote`,气泡在正文上方显示引用块,- * 宿主把原消息作为背景附在发给伙伴的这一条 wire 消息前。引用只指向同一任务里的消息。- * `excerpt` 是发送时的摘要快照:原消息不在已加载记录里时按它显示,模型侧一律按 clientId 从库里重读。- */-export interface ChatReplyQuote {- /** The quoted message, in the same Session. */- clientId: string;- role: 'user' | 'assistant';- /** Display snapshot taken when the quote was sent. */- excerpt: string;-}--export const CHAT_REPLY_QUOTE_EXCERPT_MAX = 280;--export function chatReplyQuoteExcerpt(text: string): string {- const line = text.replace(/\s+/g, ' ').trim();- return line.length > CHAT_REPLY_QUOTE_EXCERPT_MAX- ? `${line.slice(0, CHAT_REPLY_QUOTE_EXCERPT_MAX - 1)}…`- : line;-}--/** Field-by-field validation of a persisted or received quote; anything malformed is no quote. */-export function readChatReplyQuote(value: unknown): ChatReplyQuote | null {- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;- const raw = value as Record<string, unknown>;- if (typeof raw.clientId !== 'string' || !raw.clientId || raw.clientId.length > 256) return null;- if (raw.role !== 'user' && raw.role !== 'assistant') return null;- if (typeof raw.excerpt !== 'string') return null;- return { clientId: raw.clientId, role: raw.role, excerpt: chatReplyQuoteExcerpt(raw.excerpt) };-}+export { CHAT_REPLY_QUOTE_EXCERPT_MAX, chatReplyQuoteExcerpt, readChatReplyQuote, type ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex de8bfec7bf..8619d83ae4 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -177,9 +177,20 @@ import { InteractionPanel, type MobilePlanViewerState } from '@/session/Interactimport {COMPANION_AVATAR_SIZE,MessageRenderer,+ type CompanionQuoteOptions,type MobileMessageActionBusyKind,type MobileMessageDraft,} from '@/session/MessageRenderer';+import { BotGroupQuote } from '@/session/BotGroupQuote';+import { CompanionSelectTextSheet } from '@/session/CompanionSelectTextSheet';+import {+ clearSentCompanionReplyQuote,+ companionReplyQuoteDisplay,+ getPendingCompanionReplyQuote,+ setPendingCompanionReplyQuote,+ usePendingCompanionReplyQuote,+} from '@/session/companionReplyQuote';+import { useCompanionReplyTargetPreference } from '@/session/companionReplyTargetPreference';import {bundledAssetToDataUri,cleanupConversationSharePngTemps,@@ -410,6 +421,7 @@ import {buildQueueRowPresentation,createQueueEditTextState,queuedMessageHasEncodedQuotes,+ queuedMessageReplyQuote,resolveQueueEditTextSubmission,stopOptionsForProjection,type QueueEditTextState,@@ -6220,6 +6232,29 @@ function SessionScreenContent() {companionName, companionOnline, deviceId]);const companionReplyAvatar = useMemo(() => companionChat ? companionPortrait(COMPANION_AVATAR_SIZE) : undefined,[companionChat, companionPortrait]);+ const showCompanionReplyTargets = useCompanionReplyTargetPreference();+ const pendingCompanionReplyQuote = usePendingCompanionReplyQuote(companionChat ? sessionId : null);+ const companionQuoteNames = useMemo(() => ({ owner: t('message.renderer.you'), companion: companionName }), [companionName, t]);+ const [companionSelectText, setCompanionSelectText] = useState<string | null>(null);+ useEffect(() => setCompanionSelectText(null), [sessionId]);+ const companionQuoteOptions = useMemo<CompanionQuoteOptions | undefined>(() => (companionChat && sessionId ? {+ names: companionQuoteNames,+ showReplyTargets: showCompanionReplyTargets,+ onQuote: (quote) => {+ setPendingCompanionReplyQuote(sessionId, quote);+ requestAnimationFrame(() => composerInputRef.current?.focus());+ },+ onLocate: (clientId) => router.setParams({ focusClientId: clientId, focusRequestKey: String(Date.now()) }),+ onSelectText: (text) => setCompanionSelectText(text),+ } : undefined), [companionChat, companionQuoteNames, router, sessionId, showCompanionReplyTargets]);+ const pendingCompanionQuoteOriginal = useMemo(() => {+ const clientId = pendingCompanionReplyQuote?.clientId;+ if (!clientId) return undefined;+ for (const entry of messageListItems) {+ if (entry.type === 'message' && (entry.message.source.clientId || entry.message.source.id) === clientId) return entry.message;+ }+ return undefined;+ }, [messageListItems, pendingCompanionReplyQuote?.clientId]);const companionInteractionIdentity = useMemo(() => companionChat && companionName? { name: companionName, avatar: companionPortrait(COMPANION_AVATAR_SIZE) } : null,[companionChat, companionName, companionPortrait]);@@ -6462,6 +6497,8 @@ function SessionScreenContent() {// 立刻撞回断链。真正恢复后的 load / connection epoch 会负责清理并唤醒 pump。if (!connectionDispatchBlockedAtSend) setError(null);const outboxEligible = !queueEditAtSendStart;+ // 伙伴私聊的待发引用随这条消息写进信封;送达交接后才撤下,失败时保留以便重发。+ const replyQuoteAtSend = outboxEligible ? getPendingCompanionReplyQuote(sessionId) ?? undefined : undefined;const uploadsInFlight = outboxEligible ? getPendingUploadCount() : 0;const willHaveAttachments = attachmentsRef.current.length > 0 || uploadsInFlight > 0;const earlyLocalCommand = willHaveAttachments ? null : parseMobileLocalSystemCommand(body);@@ -6731,6 +6768,7 @@ function SessionScreenContent() {clientId: outboxClientId!, sessionId, text, quotesEncoded: quotesEncodedAtSend,sessionRefs: sessionRefsAtSend, agentReferences: agentReferencesAtSend,pastedTextRanges: pastedTextRangesAtSend, slashCommandRanges: slashCommandRangesAtSend ?? [],+ ...(replyQuoteAtSend ? { replyQuote: replyQuoteAtSend } : {}),permissionModeAtSend, planModeAtSend, readyAttachments, readyPreviews,attachmentOrder: incomingShareSlotOrder([...readyAttachments.map(attachment => getUploadedSource(attachment.id)?.incomingShareOrder),@@ -6759,6 +6797,7 @@ function SessionScreenContent() {noteLocalSend(record.item.clientId);await mobileDurableOutbox.add(record);committed = true;+ if (replyQuoteAtSend) clearSentCompanionReplyQuote(sessionId, replyQuoteAtSend);handoff.release(true);// Durable ownership precedes clearing the composer or deleting annotation sources.if (!isMobileAuthOwnerCurrent(ownerAtSend) || !sendScopeStillAlive()) {@@ -6864,6 +6903,7 @@ function SessionScreenContent() {agentReferences: agentReferencesAtSend,pastedTextRanges: pastedTextRangesAtSend,slashCommandRanges: slashCommandRangesAtSend,+ replyQuote: queuedMessageReplyQuote(original),}),...(original.sessionRefs && original.sessionRefs.length > 0? { sessionRefs: [...original.sessionRefs] }@@ -7079,6 +7119,7 @@ function SessionScreenContent() {agentReferences: agentReferencesAtSend,pastedTextRanges: pastedTextRangesAtSend,slashCommandRanges: slashCommandRangesAtSend,+ replyQuote: replyQuoteAtSend,});let queued: QueuedRemoteMessage;try {@@ -7150,6 +7191,7 @@ function SessionScreenContent() {queued.clientId,);enqueueAccepted = true;+ if (replyQuoteAtSend) clearSentCompanionReplyQuote(sessionId, replyQuoteAtSend);} catch (err) {// 回滚前先分辨「确实没应用」vs「已应用但响应丢了」:优先 refetch 权威// projection 判断。只有权威证据能保留乐观气泡;证据不可用时回到现有@@ -9911,6 +9953,10 @@ function SessionScreenContent() {/>) : null)}</MountOnFirstOpen>+ {companionSelectText !== null ? (+ <CompanionSelectTextSheet key={`select-text:${deviceId}:${sessionId}`} text={companionSelectText}+ onClose={() => setCompanionSelectText(null)} />+ ) : null}{currentSession ? <SideChatsSheet key={`${deviceId}:${sessionId}`} visible={sideChatsOpen}session={currentSession} maker={maker} onClose={() => setSideChatsOpen(false)}onCreate={() => createSideChat()} onSelect={openSideChat} /> : null}@@ -10313,7 +10359,7 @@ function SessionScreenContent() {interactive={!sessionListDrawerOverlayMounted}><ChatFilePathContext.Provider value={chatFilePathContextValue}>- <MessageRenderer companion={companionChat}+ <MessageRenderer companion={companionChat} companionQuote={companionQuoteOptions}onOpenCompanionSettings={openCompanionSettings} onCompanionReadThrough={companionChat ? companionEntry.markReadThrough : undefined} companionWorkingLabel={companionWorkGroupLabel}companionAvatar={companionReplyAvatar}companionPluginInvocations={companionPluginInvocations}@@ -10859,6 +10905,27 @@ function SessionScreenContent() {<ChevronRight size={iconSize.sm} color={colors.textTertiary} strokeWidth={iconStroke.regular} /></Pressable>) : null}+ {companionChat && pendingCompanionReplyQuote && sessionId && !shareSelectionActive+ && sessionOperationLayout.composerSlot === 'editable' ? (+ <View+ style={[styles.companionQuoteBar, { marginHorizontal: composerTouchLayout.composerPaddingHorizontal }]}+ testID="session.companionQuoteBar"+ >+ <View style={styles.companionQuoteBarBody}>+ <BotGroupQuote display={companionReplyQuoteDisplay(pendingCompanionReplyQuote,+ pendingCompanionQuoteOriginal, companionQuoteNames)} />+ </View>+ <RouteActionButton+ accessibilityLabel={t('message.quote.remove')}+ hitSlop={COMPOSER_CONTROL_HIT_SLOP}+ onPress={() => setPendingCompanionReplyQuote(sessionId, null)}+ style={styles.queueEditBarClose}+ testID="session.companionQuoteRemove"+ >+ <X color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />+ </RouteActionButton>+ </View>+ ) : null}<SessionResourceCards state={sessionResourceCards} />{!sessionResourceCards.blocked ? <SessionComposerInputpromptRecommendation={promptRecommendation}@@ -12983,6 +13050,21 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({backgroundColor: 'transparent',overflow: 'visible',},+ // Same card as the other bars above the composer, so the transcript never shows through.+ companionQuoteBar: {+ alignItems: 'center',+ backgroundColor: colors.surfaceElevated,+ borderColor: colors.border,+ borderRadius: radius.container,+ borderWidth: StyleSheet.hairlineWidth,+ flexDirection: 'row',+ gap: spacing.sm,+ marginBottom: spacing.xs,+ paddingLeft: spacing.md,+ paddingRight: spacing.xs,+ paddingVertical: spacing.sm,+ },+ companionQuoteBarBody: { flex: 1, minWidth: 0 },// 排队消息编辑提示条(composer 上方):✎ + 「正在编辑第 N 条排队消息」 + × 放弃。queueEditBar: {alignItems: 'center',diff --git a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsxindex 5e0337ef05..1d671dcdcf 100644--- a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx@@ -6,6 +6,10 @@ import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';import { openBrowserAsync } from 'expo-web-browser';// The shared renderer imports site-video; replace only its native surface.+vi.mock('@/platform/gestureHandler', () => {+ const chain = (): any => new Proxy({}, { get: (_target, key) => key === 'then' ? undefined : () => chain() });+ return { GestureDetector: ({ children }: { children: unknown }) => children, Gesture: { LongPress: chain } };+});vi.mock('react-native-webview', () => ({ WebView: () => null }));vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => null }));diff --git a/apps/mobile/src/__tests__/CompanionProfileSheetDraft.android.test.tsx b/apps/mobile/src/__tests__/CompanionProfileSheetDraft.android.test.tsxindex c09ee3bee9..512ad1a3b1 100644--- a/apps/mobile/src/__tests__/CompanionProfileSheetDraft.android.test.tsx+++ b/apps/mobile/src/__tests__/CompanionProfileSheetDraft.android.test.tsx@@ -28,7 +28,7 @@ vi.mock('@/device-link/remoteResources', () => ({ invokeRemoteResourceAction: (.vi.mock('@/components/AppText', () => ({ Text: 'span', TextInput: (p: any) => { h.inputs[p.accessibilityLabel] = p; return null; } }));vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: (p: any) => { h.buttons[p.action.label] = p.action; return null; } }));vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));-vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, usesNativePullDownMenu: () => false }));+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, NativeSwitch: () => null, usesNativePullDownMenu: () => false }));vi.mock('@/session/CompanionSettingsRow', () => ({ CompanionSettingsRow: (p: any) => { if (p.testID) h.pressables[p.testID] = p; return null; } }));vi.mock('@/session/CompanionSheet', async () => {const { createElement: el } = await import('react');diff --git a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsxindex b3465ba6e7..1f7bf3dea5 100644--- a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx+++ b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx@@ -6,6 +6,10 @@ import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';// This suite exercises attachment layout; keep the unrelated native App surface out of Node.+vi.mock('@/platform/gestureHandler', () => {+ const chain = (): any => new Proxy({}, { get: (_target, key) => key === 'then' ? undefined : () => chain() });+ return { GestureDetector: ({ children }: { children: unknown }) => children, Gesture: { LongPress: chain } };+});vi.mock('@/session/McpAppCard', () => ({ McpAppCard: () => null }));vi.mock('react-native-webview', () => ({ WebView: () => null }));vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => null }));diff --git a/apps/mobile/src/__tests__/inputProjection.test.ts b/apps/mobile/src/__tests__/inputProjection.test.tsindex 3f2c70f801..d238848617 100644--- a/apps/mobile/src/__tests__/inputProjection.test.ts+++ b/apps/mobile/src/__tests__/inputProjection.test.ts@@ -8,6 +8,7 @@ import {isOrcaQueueItem,normalizeInputProjection,queuedMessageHasEncodedQuotes,+ queuedMessageReplyQuote,queueMoveTargetIndex,resolveQueueEditTextSubmission,stopOptionsForProjection,@@ -16,7 +17,8 @@ import { buildMobileUploadedAttachment } from '@/session/attachments';import { parseAttachmentOssRef } from '@/session/attachmentOssRef';import { textComposerDocument } from '@/session/composerDocument';import { localizeAgentError } from '@/session/agentErrorI18n';-import type { RemoteSession } from '@/session/types';+import type { RemoteMessage, RemoteSession } from '@/session/types';+import { normalizeRemoteMessages } from '@/session/messageNormalize';import { buildOutboxItem } from '@/session/sessionOutbox';import { buildMobileMessageRenderItems } from '@/session/messageRenderModel';import { CONTINUE_AFTER_ERROR_PROMPT, CONTINUE_AFTER_APP_EXIT_PROMPT } from '@cindy/maker-shared/synthetic-trigger';@@ -158,6 +160,25 @@ describe('inputProjection', () => {expect(queuedMessageHasEncodedQuotes({ persistedContent: '{broken' })).toBe(false);});+ it('carries a companion reply quote from the queued envelope to the rendered message', () => {+ const replyQuote = { clientId: 'reply-1', role: 'assistant' as const, excerpt: 'Ship it on Friday.' };+ const queued = buildQueuedTextMessage(session(), 'Why Friday?', new Date('2026-01-01T00:00:05.000Z'), 'q-reply', { replyQuote });++ // Desktop reads this envelope field to give the companion the quoted original.+ expect(JSON.parse(queued.persistedContent).replyQuote).toEqual(replyQuote);+ // A queue edit rebuilds the message and must keep the quote that belongs to it.+ expect(queuedMessageReplyQuote(queued)).toEqual(replyQuote);+ expect(queuedMessageReplyQuote({ persistedContent: '{broken' })).toBeUndefined();+ const [rendered] = normalizeRemoteMessages([{ id: 'm-1', clientId: 'q-reply', sessionId: 'session-1', role: 'user',+ content: queued.persistedContent, createdAt: '2026-01-01T00:00:05.000Z' } as RemoteMessage]);+ expect(rendered.replyQuote).toEqual(replyQuote);+ // Anything malformed is no quote, not a broken block.+ const [malformed] = normalizeRemoteMessages([{ id: 'm-2', clientId: 'q-bad', sessionId: 'session-1', role: 'user',+ content: JSON.stringify({ text: 'x', images: [], files: [], replyQuote: { clientId: 'reply-1', role: 'system', excerpt: '' } }),+ createdAt: '2026-01-01T00:00:06.000Z' } as RemoteMessage]);+ expect(malformed.replyQuote).toBeUndefined();+ });+it('hides private markers in queue edits and only preserves encoding while text is unchanged', () => {const encoded = '> <!-- cindy-composer-quote -->\n> selected\n\nreply';const queued = buildQueuedTextMessage(diff --git a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.tsindex 25f70e4c57..8a38ceea32 100644--- a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts+++ b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts@@ -77,7 +77,7 @@ describe('mobile message media thumbnail wiring', () => {expect(rendererSource).toContain('{attachmentStripNode}');// 普通消息仍按原判据省略空气泡;外层现在先分流独立错误卡片。expect(rendererSource).toContain(- 'hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? bubble : null}',+ 'hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? (',);const attachmentStrip = rendererSource.slice(rendererSource.indexOf('function AttachmentStrip'),diff --git a/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts b/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.tsindex d96c6b38ad..7cf7be3a96 100644--- a/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts+++ b/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts@@ -299,10 +299,12 @@ it('renders message bodies natively with in-place per-block selectable text', ()const markdownBodyEnd = source.indexOf('function renderInline', markdownBodyStart);const markdownBodySource = source.slice(markdownBodyStart, markdownBodyEnd);- // 完成态才可选中;正文与 secondaryBody 都走原生 selectable。+ // 完成态才可选中;正文与 secondaryBody 都走原生 selectable。伙伴私聊的长按交给系统菜单,+ // 正文改由菜单里的「选择文字」选取,其余任务照旧就地选择。expect(source).toContain('const canSelectVisibleText = canUseCompletedActions && copyText.trim().length > 0;');- expect(bubbleSource).toContain('selectable={canSelectVisibleText}');- expect(bubbleSource).toContain('<MarkdownSelectableText selectable={canSelectVisibleText} style={styles.detailText}>');+ expect(source).toContain('const bubbleTextSelectable = canSelectVisibleText && !companionMenuEnabled;');+ expect(bubbleSource).toContain('selectable={bubbleTextSelectable}');+ expect(bubbleSource).toContain('<MarkdownSelectableText selectable={bubbleTextSelectable} style={styles.detailText}>');// iOS 部分选择:RN Text 底层是 UILabel 只能整块拷贝(facebook/react-native#13938),// 可选中块在 iOS 换用 react-native-uitextview(真 UITextView,系统选择手柄);@@ -315,9 +317,11 @@ it('renders message bodies natively with in-place per-block selectable text', ()expect(source).toContain('const SpanText = ctx.SpanText ?? MessageBodyText;');expect(markdownBodySource).toContain('blockSelectable && allowIosUITextView && Platform.OS === \'ios\'');- // 气泡是纯 View,不挂 Pressable/onLongPress(避免干扰横向 ScrollView 手势)。+ // 气泡是纯 View,不挂 Pressable/onLongPress(避免干扰横向 ScrollView 手势)。伙伴私聊的长按+ // 只用 RNGH LongPress:手指一移动就失败,表格与代码块照旧横向滚动。expect(bubbleSource).not.toContain('<Pressable');expect(bubbleSource).not.toContain('onLongPress');+ expect(bubbleSource).toContain('Gesture.LongPress().minDuration(450).runOnJS(true)');// 列表内正文只有原生渲染路径:无选择 WebView、无全屏选择查看器。expect(markdownBodySource).toContain('testID="message.markdownBody"');diff --git a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsxindex bf7627950a..5f620d2c0a 100644--- a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx+++ b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx@@ -6,6 +6,10 @@import { act, createElement, useImperativeHandle, useState } from "react";import { createRoot } from "react-dom/client";import { beforeAll, describe, expect, it, vi } from "vitest";+vi.mock('@/platform/gestureHandler', () => {+ const chain = (): any => new Proxy({}, { get: (_target, key) => key === 'then' ? undefined : () => chain() });+ return { GestureDetector: ({ children }: { children: unknown }) => children, Gesture: { LongPress: chain } };+});vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => null }));const viewportHarness = vi.hoisted(() => ({diff --git a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts b/apps/mobile/src/__tests__/mobileGoalCommands.test.tsindex 5160bb2e8d..7e49a3d18d 100644--- a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts+++ b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts@@ -106,6 +106,7 @@ function existingHarness(args = 'target') {releaseUploadedSources: noop, setMediaAssetAttachments: noop, setAttachmentPreviews: noop,composerAnnotationsRef: { current: null }, setAttachments: noop, setAttachmentError: noop,voiceDictionaryLearningTrackerRef: { current: null }, formatRemoteError: String,+ getPendingCompanionReplyQuote: () => null, clearSentCompanionReplyQuote: noop,};bindings.setSending = vi.fn((value: boolean) => { bindings.sending = value; });bindings.applyComposerDocument = vi.fn((doc: typeof initial) => { bindings.composerDocumentRef.current = doc; });diff --git a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsxindex 0266ecab24..5dce0236a4 100644--- a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx+++ b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx@@ -6,6 +6,10 @@ import { describe, expect, it, vi } from 'vitest';const viewportHarness = vi.hoisted(() => ({ list: null as any, finishReveal: null as any, renders: 0, expanded: false }));// Keep site-video's native surface out of this Node message-rendering test.+vi.mock('@/platform/gestureHandler', () => {+ const chain = (): any => new Proxy({}, { get: (_target, key) => key === 'then' ? undefined : () => chain() });+ return { GestureDetector: ({ children }: { children: unknown }) => children, Gesture: { LongPress: chain } };+});vi.mock('react-native-webview', () => ({ WebView: () => null }));vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => null }));diff --git a/apps/mobile/src/__tests__/userMessageCollapse.test.ts b/apps/mobile/src/__tests__/userMessageCollapse.test.tsindex 1178eac2aa..8aead710c0 100644--- a/apps/mobile/src/__tests__/userMessageCollapse.test.ts+++ b/apps/mobile/src/__tests__/userMessageCollapse.test.ts@@ -212,6 +212,12 @@ function BubbleHarness({ body, kind = 'user', automationOrigin: origin }) {const presentation = {};const rendersSentInlineBody = false;const canSelectVisibleText = true;+ const bubbleTextSelectable = canSelectVisibleText;+ const companionMenuEnabled = false;+ const companionQuote = undefined;+ const replyQuote = undefined;+ const replyTarget = null;+ const replyTargetId = null;const isStreamingAssistant = false;const contentLayout = buildMessageContentLayout({ screenWidth: 402 });const t = i18n.t.bind(i18n);diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex 094bc2080e..674b119103 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -761,7 +761,10 @@"uploadAvatar": "Upload Avatar","avatarFailed": "Could not open this image. Try another.","nameTaken": "That name is already in use. Choose another.",- "home": "Main Computer"+ "home": "Main Computer",+ "chat": "Chat",+ "showReplyTarget": "Show which message a reply answers",+ "showReplyTargetHint": "Above a teammate’s reply, show which of your messages it answers. Applies to all teammates. Older replies don’t show this."},"companionImport": {"title": "Import a teammate",diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex cfc1c1f1fd..572617649a 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -171,7 +171,9 @@"diffEditCount": "{{n}} edits","groupSentNamed": "Sent from group “{{name}}”","groupSent": "Sent from a group",- "sourceGroupId": "Group ID: {{id}}"+ "sourceGroupId": "Group ID: {{id}}",+ "selectText": "Select Text",+ "you": "You"},"actions": {"attachmentsPrefix": "Attachments: {{names}}",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 4f5d977674..9ce96edeeb 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -761,7 +761,10 @@"uploadAvatar": "アバターをアップロード","avatarFailed": "この画像を開けません。別の画像を選んでください。","nameTaken": "この名前は使用されています。別の名前を選んでください。",- "home": "メインのパソコン"+ "home": "メインのパソコン",+ "chat": "チャット",+ "showReplyTarget": "返信の対象メッセージを表示",+ "showReplyTargetHint": "チームメイトの返信の上に、どのメッセージへの返信かを表示します。すべてのチームメイトに適用されます。以前の返信には表示されません。"},"companionImport": {"title": "仲間をインポート",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex 1f69210e5c..d625eec5d5 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -171,7 +171,9 @@"diffEditCount": "{{n}} 件の編集","groupSentNamed": "グループ「{{name}}」から送信","groupSent": "グループから送信",- "sourceGroupId": "グループ ID: {{id}}"+ "sourceGroupId": "グループ ID: {{id}}",+ "selectText": "テキストを選択",+ "you": "あなた"},"actions": {"attachmentsPrefix": "添付ファイル:{{names}}",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 5cc71eb727..76281b1e41 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -761,7 +761,10 @@"uploadAvatar": "아바타 업로드","avatarFailed": "이미지를 열 수 없습니다. 다른 이미지를 선택하세요.","nameTaken": "이미 사용 중인 이름입니다. 다른 이름을 선택하세요.",- "home": "주 컴퓨터"+ "home": "주 컴퓨터",+ "chat": "채팅",+ "showReplyTarget": "답장 대상 메시지 표시",+ "showReplyTargetHint": "팀원 답장 위에 어떤 메시지에 대한 답장인지 표시합니다. 모든 팀원에게 적용되며, 이전 답장에는 표시되지 않습니다."},"companionImport": {"title": "동료 가져오기",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex fb4c8b6937..db23581552 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -171,7 +171,9 @@"diffEditCount": "{{n}}개 편집","groupSentNamed": "그룹 「{{name}}」에서 보냄","groupSent": "그룹에서 보냄",- "sourceGroupId": "그룹 ID: {{id}}"+ "sourceGroupId": "그룹 ID: {{id}}",+ "selectText": "텍스트 선택",+ "you": "나"},"actions": {"attachmentsPrefix": "첨부파일: {{names}}",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex 2419a19feb..77bbbff8fc 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -761,7 +761,10 @@"uploadAvatar": "上传头像","avatarFailed": "无法打开此图片,请换一张。","nameTaken": "已有同名伙伴,请换一个名字。",- "home": "主力电脑"+ "home": "主力电脑",+ "chat": "聊天",+ "showReplyTarget": "显示回复对应的消息",+ "showReplyTargetHint": "伙伴回复上方标出它回的是你哪条消息。对所有伙伴生效,较早的回复不显示。"},"companionImport": {"title": "导入伙伴",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 924743b392..2e828a7994 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -171,7 +171,9 @@"diffEditCount": "{{n}} 处编辑","groupSentNamed": "从群聊「{{name}}」发送","groupSent": "从群聊发送",- "sourceGroupId": "群聊 ID:{{id}}"+ "sourceGroupId": "群聊 ID:{{id}}",+ "selectText": "选择文字",+ "you": "你"},"actions": {"attachmentsPrefix": "附件:{{names}}",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex 3f294dd40a..f90f53dd05 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -761,7 +761,10 @@"uploadAvatar": "上傳頭像","avatarFailed": "無法開啟此圖片,請換一張。","nameTaken": "已有同名夥伴,請換一個名字。",- "home": "主力電腦"+ "home": "主力電腦",+ "chat": "聊天",+ "showReplyTarget": "顯示回覆對應的訊息",+ "showReplyTargetHint": "夥伴回覆上方標出它回的是你哪則訊息。對所有夥伴生效,較早的回覆不顯示。"},"companionImport": {"title": "匯入夥伴",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex cfab977f38..2c5dfa374e 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -171,7 +171,9 @@"diffEditCount": "{{n}} 處編輯","groupSentNamed": "從群聊「{{name}}」傳送","groupSent": "從群聊傳送",- "sourceGroupId": "群聊 ID:{{id}}"+ "sourceGroupId": "群聊 ID:{{id}}",+ "selectText": "選取文字",+ "you": "你"},"actions": {"attachmentsPrefix": "附件:{{names}}",diff --git a/apps/mobile/src/session/BotGroupQuote.tsx b/apps/mobile/src/session/BotGroupQuote.tsxindex 8f476f2262..2c2a5bc4fa 100644--- a/apps/mobile/src/session/BotGroupQuote.tsx+++ b/apps/mobile/src/session/BotGroupQuote.tsx@@ -1,16 +1,21 @@/*** 群聊「引用回复」的引用块(docs/product-rules/bot-group-chat.md §10「引用回复」)。* 手机只显示:作者与一到两行摘要,竖线与 Markdown 引用同一样式;原消息已删除时只显示- * 作者与「原消息已删除」。发起引用与跳转原消息目前只在电脑上。+ * 作者与「原消息已删除」。群聊的发起引用与跳转原消息目前只在电脑上;伙伴私聊在手机上也能发起和跳转。*/-import { StyleSheet, View } from 'react-native';+import { Pressable, StyleSheet, View } from 'react-native';import { useTranslation } from 'react-i18next';import type { BotGroupQuoteDisplay } from '@cindy/maker-shared/botGroupChat';import { Text } from '@/components/AppText';import { useThemedStyles, type ThemeColors } from '@/theme';import { fontWeight, lineHeight, spacing, typeScale } from '@/theme/tokens';-export function BotGroupQuote({ display, align = 'left' }: { display: BotGroupQuoteDisplay; align?: 'left' | 'right' }) {+export function BotGroupQuote({ display, align = 'left', onPress }: {+ display: BotGroupQuoteDisplay;+ align?: 'left' | 'right';+ /** 伙伴私聊:点引用块跳到原消息。群聊暂不跳转。 */+ onPress?: () => void;+}) {const { t } = useTranslation();const styles = useThemedStyles(makeStyles);const deleted = display.state === 'deleted';@@ -19,15 +24,29 @@ export function BotGroupQuote({ display, align = 'left' }: { display: BotGroupQu: display.excerpt || (display.attachmentName && display.attachmentCount > 1? t('groupChat.quote.attachments', { name: display.attachmentName, total: display.attachmentCount }): display.attachmentName ?? '');- return (+ const content = <>+ <Text numberOfLines={1} style={styles.author}>{display.authorName}</Text>+ <Text numberOfLines={2} style={deleted ? styles.deleted : styles.excerpt}>{summary}</Text>+ </>;+ const label = t('groupChat.quote.label', { name: display.authorName, summary });+ return onPress ? (+ <Pressable+ accessibilityLabel={label}+ accessibilityRole="button"+ onPress={onPress}+ style={({ pressed }) => [styles.quote, styles.fill, pressed && styles.pressed]}+ testID="botGroup.quote"+ >+ {content}+ </Pressable>+ ) : (<Viewaccessible- accessibilityLabel={t('groupChat.quote.label', { name: display.authorName, summary })}+ accessibilityLabel={label}style={[styles.quote, align === 'right' && styles.right]}testID="botGroup.quote">- <Text numberOfLines={1} style={styles.author}>{display.authorName}</Text>- <Text numberOfLines={2} style={deleted ? styles.deleted : styles.excerpt}>{summary}</Text>+ {content}</View>);}@@ -36,6 +55,9 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({// Same rail as a Markdown quote in group messages (BotGroupMessageText).quote: { maxWidth: '86%', borderLeftWidth: 2, borderLeftColor: colors.border, paddingLeft: spacing.md, gap: 2 },right: { alignSelf: 'flex-end' },+ // Inside a private-chat bubble the quote spans the bubble's text column.+ fill: { maxWidth: '100%' },+ pressed: { opacity: 0.72 },author: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },excerpt: { color: colors.textSecondary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular },deleted: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },diff --git a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsxindex 858a27e5a0..3007565ef8 100644--- a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx+++ b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx@@ -13,6 +13,7 @@ import type { CompanionProfileNativeViewProps } from './CompanionProfileNativeViimport type { ProfilePanel, ProfileValues } from './companionProfileData';import { CompanionPortraitPicker } from './CompanionPortraitPicker';import { CompanionNativeContent } from './CompanionNativeContent.ios';+import { saveCompanionReplyTargetPreference, useCompanionReplyTargetPreference } from './companionReplyTargetPreference';export function CompanionNativeField({ field, values, onChange, busy }: { field: RemoteActionField; values: ProfileValues; onChange(values: ProfileValues): void; busy: boolean }) {const { i18n } = useTranslation();@@ -39,6 +40,7 @@ const Field = CompanionNativeField;export function CompanionProfileNativeView(p: CompanionProfileNativeViewProps) {const { t, i18n } = useTranslation(); const { colors } = useTheme();+ const showReplyTargets = useCompanionReplyTargetPreference();const tr = (key: string) => t(`devices.companionProfile.${key}`, { deviceName: p.deviceName });const label = (value: Parameters<typeof resolveRemoteText>[0]) => resolveRemoteText(value, i18n.language);const note = (text: string, error = false) => <Section><Text modifiers={[font({ textStyle: 'footnote' }), foregroundStyle(error ? colors.errorText : colors.textSecondary)]}>{text}</Text></Section>;@@ -57,6 +59,11 @@ export function CompanionProfileNativeView(p: CompanionProfileNativeViewProps) {<Text modifiers={[font({ textStyle: 'headline' }), lineLimit(2)]}>{p.name}</Text><Spacer /></HStack></Section><Section>{row('profile', 'person.crop.circle')}{row('memory', 'brain')}{row('models', 'slider.horizontal.3')}{row('skills', 'sparkles')}</Section>+ {/* Device preference for every teammate's chat, not part of this teammate's host profile. */}+ <Section title={tr('chat')} footer={<Text modifiers={[font({ textStyle: 'footnote' }), foregroundStyle(colors.textSecondary)]}>{tr('showReplyTargetHint')}</Text>}>+ <Toggle label={tr('showReplyTarget')} isOn={showReplyTargets} onIsOnChange={value => void saveCompanionReplyTargetPreference(value)}+ modifiers={[tint(colors.inputCaret)]} testID="companionProfile.showReplyTarget" />+ </Section>{p.data?.panels.find(item => item.id === 'followUp')?.entries?.map(entry => <Section key={entry.id}>{action(label(entry.title), () => p.onEditor(entry.resourceId), !p.online)}</Section>)}<Section>{row('artifacts', 'doc.text')}{p.onSearch ? row('search', 'magnifyingglass', p.onSearch) : null}{row('permissions', 'hand.raised')}</Section>{p.onHome ? <Section>{row('home', 'desktopcomputer', p.onHome)}</Section> : null}diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsxindex 85de3399ac..5eb6cca44c 100644--- a/apps/mobile/src/session/CompanionProfileSheet.tsx+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx@@ -27,6 +27,7 @@ import { CompanionProfileArtifacts } from './CompanionProfileArtifacts';import { loadCompanionProfile, profileFormDirty, type CompanionProfileData, type ProfilePanel, type ProfileValues } from './companionProfileData';import { CompanionMemoryPage } from './CompanionMemoryPage';import { useCompanionMemory } from './useCompanionMemory';+import { saveCompanionReplyTargetPreference, useCompanionReplyTargetPreference } from './companionReplyTargetPreference';// Same identity block as iOS: a 48pt avatar and the name, not a navigation target.const AVATAR_SIZE = 48;@@ -68,6 +69,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {const { accountGeneration } = useAuth();const styles = useThemedStyles(makeStyles);const { colors } = useTheme();+ const showReplyTargets = useCompanionReplyTargetPreference();const [data, setData] = useState<CompanionProfileData | null>(null);const [page, setPage] = useState('home');const [modelStage, setModelStage] = useState<'profile' | 'closing-profile' | 'picker' | 'closing-picker'>('profile');@@ -383,6 +385,15 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {<Text accessibilityRole="header" numberOfLines={2} style={styles.name}>{name}</Text></View><View style={styles.group}>{row('profile', Info)}{row('memory', Brain)}{row('models', Sparkles)}{row('skills', Settings2)}</View>+ {/* Device preference for every teammate's chat, not part of this teammate's host profile. */}+ <View style={styles.field}>+ <View style={styles.group}><View style={styles.inline}>+ <Text style={styles.switchLabel}>{t('devices.companionProfile.showReplyTarget')}</Text>+ <NativeSwitch accessibilityLabel={t('devices.companionProfile.showReplyTarget')} value={showReplyTargets}+ onValueChange={value => void saveCompanionReplyTargetPreference(value)} seedColor={colors.inputCaret} />+ </View></View>+ {note('showReplyTargetHint')}+ </View>{data?.panels.find(item => item.id === 'followUp')?.entries?.map(entry => <View style={styles.group} key={entry.id}><ContextSheetRow icon={null} trailing="chevron" label={label(entry.title)} onPress={() => void openEditor(entry.resourceId)} disabled={!online} /></View>)}<View style={styles.group}>{row('artifacts', FileText)}{onOpenSearch ? row('search', History, onOpenSearch) : null}{row('permissions', Hand)}</View>{onOpenHome ? <View style={styles.group}>{row('home', Monitor, onOpenHome)}</View> : null}@@ -615,6 +626,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({note: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, color: colors.textSecondary },body: { fontSize: typeScale.body, lineHeight: lineHeight.body, color: colors.textPrimary },heading: { fontSize: typeScale.body, lineHeight: lineHeight.body, color: colors.textPrimary, fontWeight: fontWeight.medium },+ switchLabel: { flex: 1, fontSize: typeScale.body, lineHeight: lineHeight.body, color: colors.textPrimary },group: { backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.container, overflow: 'hidden', paddingHorizontal: spacing.lg },groupText: { paddingVertical: spacing.md },spinner: { paddingVertical: spacing.md },diff --git a/apps/mobile/src/session/CompanionSelectTextSheet.tsx b/apps/mobile/src/session/CompanionSelectTextSheet.tsxnew file mode 100644index 0000000000..ef968618a1--- /dev/null+++ b/apps/mobile/src/session/CompanionSelectTextSheet.tsx@@ -0,0 +1,45 @@+/**+ * 伙伴私聊长按菜单的「选择文字」:长按交给系统菜单后,正文改在这里用系统文字选择挑一部分复制。+ * 挂载即打开;关闭先播完系统收起,再由 onClose 卸载,不叠第二个面板。iOS 用 UITextView,可只选一部分。+ */+import { useState } from 'react';+import { Platform, StyleSheet, View } from 'react-native';+import { UITextView } from 'react-native-uitextview';+import { useTranslation } from 'react-i18next';+import { Text } from '@/components/AppText';+import { useThemedStyles, type ThemeColors } from '@/theme';+import { lineHeight, spacing, typeScale } from '@/theme/tokens';+import { CompanionSheet } from './CompanionSheet';++/** What the reader sees, without Markdown syntax: emphasis marks, link targets and heading hashes go. */+export function selectableMessageText(markdown: string): string {+ return markdown+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/^#{1,6}\s+/gm, '')+ .replace(/^(\s*)[-*+]\s+/gm, '$1• ')+ .replace(/(\*\*|__)(.+?)\1/g, '$2')+ .replace(/`([^`\n]+)`/g, '$1');+}++export function CompanionSelectTextSheet({ text, onClose }: { text: string; onClose: () => void }) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const [visible, setVisible] = useState(true);+ return (+ <CompanionSheet visible={visible} title={t('message.renderer.selectText')} onClose={() => setVisible(false)}+ onClosed={onClose} testID="companion.selectTextSheet">+ <View style={styles.content}>+ {/* iOS RN Text can only copy the whole block; UITextView gives system handles for part of it. */}+ {Platform.OS === 'ios'+ ? <UITextView selectable uiTextView style={styles.text}>{selectableMessageText(text)}</UITextView>+ : <Text selectable style={styles.text}>{selectableMessageText(text)}</Text>}+ </View>+ </CompanionSheet>+ );+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ content: { paddingBottom: spacing.lg },+ text: { color: colors.textPrimary, fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge },+});diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 44b4518bab..1cba1020a8 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -15,6 +15,11 @@ import { AgentErrorDetails } from './AgentErrorDetails';import { ErrorNotice } from '@/components/ErrorNotice';import { FileTypeIcon } from '@/components/FileTypeIcon';import { CompanionMessageActions } from './CompanionMessageActions';+import { BotGroupQuote } from './BotGroupQuote';+import { companionReplyQuoteDisplay, companionReplyQuoteFor } from './companionReplyQuote';+import type { ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';+import type { NativePullDownAction } from '@/platform/chrome/NativePullDownMenu';+import { Gesture, GestureDetector } from '@/platform/gestureHandler';import { useMessageHistoryActive, useMessageHistoryPositioning } from './messageHistoryActivity';import { usePaneViewport } from '@/platform/AdaptiveWindowContext';import { messageReadingPosition } from './messageReadingPosition';@@ -650,9 +655,30 @@ export type MobileMessageActionBusyKind = 'fork' | 'rewind' | 'delete';export const COMPANION_AVATAR_SIZE = 28;const COMPANION_AVATAR_GAP = 10;+/** 伙伴私聊引用回复与「回复对应的消息」(docs/product-rules/cindy-bots-runtime.md)。 */+export interface CompanionQuoteOptions {+ names: { owner: string; companion: string };+ /** 「显示回复对应的消息」本机偏好。 */+ showReplyTargets: boolean;+ /** Put a quote of this message above the composer. */+ onQuote: (quote: ChatReplyQuote) => void;+ /** Scroll to and highlight a message of this chat, loading it first when needed. */+ onLocate: (clientId: string) => void;+ /** 「选择文字」: the page shows this message's text where the system text selection works. */+ onSelectText: (text: string) => void;+}++interface CompanionQuoteActions extends CompanionQuoteOptions {+ /** The message as this chat has it loaded; reads the latest list without re-rendering every row. */+ getMessage: (clientId: string) => NormalizedRemoteMessage | undefined;+ /** Whether `assistantClientId` is the last loaded reply of the turn it answers. */+ isLastReplyFor: (assistantClientId: string) => boolean;+}+interface MessageActions {onRetryImageDelivery?: (imageId: string) => Promise<void>;companion?: boolean;+ companionQuoteActions?: CompanionQuoteActions;onCompanionReadThrough?: (at: number) => void;onOpenCompanionSettings?: (page: 'memory' | 'capabilities') => void;companionWorkingLabel?: string | null;@@ -729,6 +755,7 @@ interface MessageActions {export function MessageRenderer({companion = false,+ companionQuote,companionWorkingLabel,onOpenCompanionSettings,companionAvatar,@@ -791,6 +818,8 @@ export function MessageRenderer({devRecycleItems = false,}: {companion?: boolean;+ /** Companion private chats only; ordinary tasks keep their existing message actions. */+ companionQuote?: CompanionQuoteOptions;onOpenCompanionSettings?: (page: 'memory' | 'capabilities') => void;companionWorkingLabel?: string | null;companionAvatar?: ReactNode;@@ -1762,8 +1791,42 @@ export function MessageRenderer({return item.type === 'message' && (item.message.kind === 'user' || item.message.kind === 'assistant' || item.message.companion)? [{ clientId: item.key, createdAt: pendingSentAtRef.current.get(item.key) ?? localSendStartedAt(item.key) ?? item.message.createdAt }] : [];})) : undefined, [companion, items]);+ const quoteItemsRef = useRef(items);+ quoteItemsRef.current = items;+ const showCompanionReplyTargets = !!(companion && companionQuote?.showReplyTargets);+ // The last reply of each turn, as a stable key: rows re-render when a later reply of the same turn+ // arrives (so the earlier one drops its reply target), not on every streaming update.+ const lastCompanionReplyKey = useMemo(() => {+ if (!showCompanionReplyTargets) return '';+ const answered = new Set<string>();+ const lastReplies: string[] = [];+ for (let index = items.length - 1; index >= 0; index -= 1) {+ const entry = items[index];+ if (entry.type !== 'message' || entry.message.kind !== 'assistant') continue;+ const target = readReplyToClientId(entry.message);+ if (!target || answered.has(target)) continue;+ answered.add(target);+ lastReplies.push(messageClientId(entry));+ }+ return lastReplies.join('\n');+ }, [items, showCompanionReplyTargets]);+ const companionQuoteActions = useMemo<CompanionQuoteActions | undefined>(() => {+ if (!companion || !companionQuote) return undefined;+ const lastReplies = new Set(lastCompanionReplyKey ? lastCompanionReplyKey.split('\n') : []);+ return {+ ...companionQuote,+ getMessage: (clientId) => {+ for (const entry of quoteItemsRef.current) {+ if (entry.type === 'message' && messageClientId(entry) === clientId) return entry.message;+ }+ return undefined;+ },+ isLastReplyFor: (assistantClientId) => lastReplies.has(assistantClientId),+ };+ }, [companion, companionQuote, lastCompanionReplyKey]);const actions: MessageActions & { firstUserMessageClientId?: string } = useMemo(() => ({companion,+ companionQuoteActions,companionWorkingLabel,onOpenCompanionSettings,companionAvatar,@@ -1806,6 +1869,7 @@ export function MessageRenderer({screenWidth: viewportLayout.contentWidth,}), [companion,+ companionQuoteActions,companionWorkingLabel,onOpenCompanionSettings,companionAvatar,@@ -3027,6 +3091,12 @@ const RenderItemView = memo(function RenderItemView({<PendingSendBubbleactions={actions.pendingSend}item={item}+ renderReplyQuote={actions.companionQuoteActions ? (quote) => (+ <View style={styles.companionQuote}>+ <BotGroupQuote display={companionReplyQuoteDisplay(quote,+ actions.companionQuoteActions!.getMessage(quote.clientId), actions.companionQuoteActions!.names)} />+ </View>+ ) : undefined}onOpenImage={actions.onOpenPayload}screenWidth={actions.screenWidth}viewerDeviceId={actions.viewerDeviceId}@@ -3619,6 +3689,37 @@ function MessageBubble({const actionBusy = !!clientId && actions.busyClientId === clientId;const forkBusy = actionBusy && actions.busyAction === 'fork';const disabled = !!actions.busyClientId;+ // 伙伴私聊:长按消息弹出系统菜单(对应桌面悬停时的「回复」等按钮),消息下方不再常驻图标。+ // iOS 用系统操作表(MenuView 的长按预览在新架构下抬不起气泡,不改原生代码时不用它);+ // Android 用平台下拉菜单。都不可用时退回原来的操作行。长按交给菜单后正文不再就地选字,改由「选择文字」打开。+ const companionQuote = actions.companionQuoteActions;+ const companionMenuEnabled = !!(actions.companion && hasActions+ && (Platform.OS === 'ios' ? usesSystemActionMenu() : usesNativePullDownMenu()));+ const bubbleTextSelectable = canSelectVisibleText && !companionMenuEnabled;+ const replyQuote = companionQuote && item.message.kind === 'user' ? item.message.replyQuote : undefined;+ const replyTargetId = companionQuote?.showReplyTargets && item.message.kind === 'assistant' && clientId+ ? readReplyToClientId(item.message) : null;+ const replyTargetMessage = replyTargetId ? companionQuote?.getMessage(replyTargetId) : undefined;+ const replyTarget = replyTargetId && isOwnerTypedMessage(replyTargetMessage)+ && companionQuote?.isLastReplyFor(clientId)+ ? companionReplyQuoteFor(replyTargetMessage) : null;+ const companionMenuActions = useMemo<NativePullDownAction[]>(() => {+ if (!companionMenuEnabled) return [];+ const quick: NativePullDownAction[] = [+ ...(companionQuote && canAddToChat ? [{ id: 'reply', title: t('message.renderer.reply'), image: 'bubble.left' }] : []),+ ...(canCopy ? [{ id: 'copy', title: t('message.renderer.copyStateCopy'), image: 'doc.on.doc' }] : []),+ ];+ return [+ // Reply and copy first, in their own group (Desktop's hover bar leads with Reply).+ ...(quick.length ? [{ id: 'quick', title: '', displayInline: true, subactions: quick }] : []),+ ...(canSelectVisibleText ? [{ id: 'select-text', title: t('message.renderer.selectText'), image: 'character.cursor.ibeam' }] : []),+ ...(canShare ? [{ id: 'share', title: t('session.shareImage.shareMessage'), image: 'square.and.arrow.up' }] : []),+ // Teammates own one timeline: no fork or per-turn cost here, the same as Desktop.+ ...messageMenu.filter(entry => entry.id !== 'add-to-chat').map(entry => ({+ id: entry.id, title: entry.label, image: entry.image, destructive: entry.destructive, disabled,+ })),+ ];+ }, [disabled, canAddToChat, canCopy, canSelectVisibleText, canShare, companionMenuEnabled, companionQuote, messageMenu, t]);useEffect(() => {if (copyState === 'idle' || copyState === 'copying') return;@@ -3686,6 +3787,28 @@ function MessageBubble({if (id === 'side-chat') return actions.onSideChatMessage?.(copyText);actions.onCopyMessageLink?.(clientId);}, [actions, clientId, copyText, selectControlAction]);+ const selectCompanionMenuAction = useCallback((id: string) => {+ if (id === 'reply') {+ const quote = companionReplyQuoteFor(item.message);+ if (quote) companionQuote?.onQuote(quote);+ } else if (id === 'copy') copyMessage();+ else if (id === 'select-text') companionQuote?.onSelectText(copyText);+ else if (id === 'share') actions.onEnterShareSelection?.(clientId);+ else if (messageMenu.some(entry => entry.id === id)) selectMenuAction(id as MobileMessageMenuActionId);+ }, [actions, clientId, companionQuote, copyMessage, copyText, item.message, messageMenu, selectMenuAction]);+ const openCompanionActionSheet = useCallback(() => {+ const items = companionMenuActions.flatMap(entry => entry.subactions ?? [entry])+ .map(entry => ({ key: entry.id, label: entry.title, destructive: entry.destructive, disabled: entry.disabled }));+ void showActionMenu({+ ...(absoluteTime ? { title: absoluteTime } : {}),+ items,+ cancelLabel: t('session.common.cancel'),+ userInterfaceStyle: mode,+ }).then(result => { if (result.kind === 'action') selectCompanionMenuAction(result.key); });+ }, [absoluteTime, companionMenuActions, mode, selectCompanionMenuAction, t]);+ // 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)+ .onStart(() => openCompanionActionSheet()), [openCompanionActionSheet]);const openMessageActionMenu = useCallback(() => {if (usesSystemActionMenu()) {const disabled = actionBusy@@ -3767,6 +3890,7 @@ function MessageBubble({presentation.density === 'compact' && styles.bubbleCompact,presentation.density === 'rich' && styles.bubbleRich,isUser ? styles.userBubble : styles.agentBubble,+ companionMenuEnabled && styles.companionMenuBubble,actions.companion && !isUser && !item.message.systemCardType && styles.companionAnswer,hookSource && styles.hookSourceBubble,isUser && !item.message.systemCardType && userBubbleColors@@ -3799,6 +3923,17 @@ function MessageBubble({) : null}</View>) : null}+ {replyQuote && companionQuote ? (+ <View style={styles.companionQuote}>+ <BotGroupQuote display={companionReplyQuoteDisplay(replyQuote, companionQuote.getMessage(replyQuote.clientId), companionQuote.names)}+ onPress={() => companionQuote.onLocate(replyQuote.clientId)} />+ </View>+ ) : replyTarget && replyTargetId && companionQuote ? (+ <View style={styles.companionQuote} testID="message.replyTarget">+ <BotGroupQuote display={companionReplyQuoteDisplay(replyTarget, replyTargetMessage, companionQuote.names)}+ onPress={() => companionQuote.onLocate(replyTargetId)} />+ </View>+ ) : null}{item.message.systemCardType === 'mcp-app' ? (<ViewabilityGatedMcpAppCard deviceId={actions.remoteDeviceId} sessionId={item.message.source.sessionId}clientId={item.message.source.clientId} title={String(item.message.systemCardData?.title ?? '')}@@ -3822,7 +3957,7 @@ function MessageBubble({interactiveAtoms={false}maxVisibleLines={collapsedLineCount}numberOfLines={collapsedLineCount}- selectable={canSelectVisibleText}+ selectable={bubbleTextSelectable}testID="message.collapsedSentInlineAtoms"textStyle={styles.messageText}tokens={sentInlineTokens}@@ -3833,7 +3968,7 @@ function MessageBubble({// MarkdownSelectableText(iOS UITextView 原生支持 numberOfLines)。<MarkdownSelectableTextnumberOfLines={collapsedLineCount}- selectable={canSelectVisibleText}+ selectable={bubbleTextSelectable}style={styles.messageText}testID="message.collapsedBody">@@ -3851,7 +3986,7 @@ function MessageBubble({onOpenPayload={actions.onOpenPayload}onOpenSessionLink={actions.onOpenSessionLink}pinContentWidth={!isUser}- selectable={canSelectVisibleText}+ selectable={bubbleTextSelectable}streaming={false}text={text}/>@@ -3869,7 +4004,7 @@ function MessageBubble({onOpenPayload={actions.onOpenPayload}onOpenSessionLink={actions.onOpenSessionLink}pinContentWidth={!isUser}- selectable={canSelectVisibleText}+ selectable={bubbleTextSelectable}streaming={isStreamingAssistant}text={bubbleBody}/>@@ -3920,7 +4055,7 @@ function MessageBubble({</Text>) : null}{item.message.secondaryBody ? (- <MarkdownSelectableText selectable={canSelectVisibleText} style={styles.detailText}>+ <MarkdownSelectableText selectable={bubbleTextSelectable} style={styles.detailText}>{item.message.secondaryBody}</MarkdownSelectableText>) : null}@@ -3993,7 +4128,21 @@ function MessageBubble({<ErrorNotice message={displayBubbleBody}>{item.message.rawError ? <AgentErrorDetails key={item.message.key} message={item.message.rawError} /> : null}</ErrorNotice>- ) : hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? bubble : null}+ ) : hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? (+ companionMenuEnabled ? (Platform.OS === 'ios' ? (+ <GestureDetector gesture={companionMenuGesture}>+ <View style={isUser ? styles.companionMenuUser : styles.companionMenuAgent} testID="companion.messageMenu">+ {bubble}+ </View>+ </GestureDetector>+ ) : (+ <NativePullDownMenu longPress actions={companionMenuActions}+ onAction={selectCompanionMenuAction} style={isUser ? styles.companionMenuUser : styles.companionMenuAgent}+ testID="companion.messageMenu">+ {bubble}+ </NativePullDownMenu>+ )) : bubble+ ) : null}{actions.companion && item.message.kind === 'assistant' && item.message.body.trim() ? (<CompanionLearningFooter receipts={item.message.source.agentMeta?.botLearning}onOpenSettings={actions.onOpenCompanionSettings} />@@ -4017,7 +4166,7 @@ function MessageBubble({</Text></View>) : null}- {hasActions && actions.companion ? <CompanionMessageActions user={isUser} copied={copyState === 'copied'} copying={copyState === 'copying'} disabled={disabled}+ {companionMenuEnabled ? null : hasActions && actions.companion ? <CompanionMessageActions user={isUser} copied={copyState === 'copied'} copying={copyState === 'copying'} disabled={disabled}onCopy={canCopy ? copyMessage : undefined}actions={[...(canCopy ? [{ id: 'copy', title: copyActionLabel(copyState), image: 'doc.on.doc', disabled: copyState === 'copying' }] : []),@@ -8528,6 +8677,18 @@ function messageClientId(item: MobileMessageItem): string {return item.message.source.clientId || item.message.source.id || item.message.key;}+/** Host-stamped input a companion reply answers (agentMeta.replyToClientId). */+function readReplyToClientId(message: NormalizedRemoteMessage): string | null {+ const value = message.source.agentMeta?.replyToClientId;+ return typeof value === 'string' && value ? value : null;+}++/** A message the companion's reply can point back to: a visible message the owner typed. */+function isOwnerTypedMessage(message: NormalizedRemoteMessage | undefined): message is NormalizedRemoteMessage {+ return !!message && message.kind === 'user' && !message.isSyntheticTrigger && !message.automationOrigin+ && !message.hookSource && !message.sessionOrigin && !message.systemCardType;+}+/** 语法 kind → 样式。plain 不走这里(直接当字符串塞进父 Text,少一层节点)。 */function syntaxStyleFor(styles: ReturnType<typeof makeStyles>,@@ -8694,6 +8855,12 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({gap: spacing.sm,},companionAnswer: { backgroundColor: colors.surface, borderWidth: 0, paddingHorizontal: 0 },+ // The long-press menu wraps the bubble, so it takes the bubble's place in the row.+ companionMenuUser: { alignSelf: 'flex-end', maxWidth: '86%', minWidth: 0 },+ companionMenuAgent: { alignSelf: 'stretch' },+ // The bubble fills its long-press wrapper, so the wrapper is exactly the bubble.+ companionMenuBubble: { alignSelf: 'stretch', maxWidth: '100%' },+ companionQuote: { alignSelf: 'stretch', marginBottom: spacing.xs },// Desktop BotAvatar sm (28) + gap-2.5; the task card reuses the same inset.companionAvatarRow: { flexDirection: 'row', alignItems: 'flex-start', gap: COMPANION_AVATAR_GAP },companionAvatarSlot: { flexShrink: 0, marginTop: 2 },diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsxindex 6e2e2798a4..77d8564bd4 100644--- a/apps/mobile/src/session/MobileOutboxBridge.tsx+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx@@ -1,3 +1,4 @@+import { readChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';import { useEffect, useRef, useSyncExternalStore } from "react";import { Alert, AppState } from "react-native";import { useAuth } from "@/auth/AuthContext";@@ -322,6 +323,7 @@ export function MobileOutboxBridge() {agentReferences: item.agentReferences,pastedTextRanges: item.pastedTextRanges,slashCommandRanges: item.slashCommandRanges,+ replyQuote: readChatReplyQuote(item.replyQuote) ?? undefined,},);return prepareMobileQueuedSessionReferences(diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsxindex 3913859a50..3bce96f113 100644--- a/apps/mobile/src/session/PendingSendBubble.tsx+++ b/apps/mobile/src/session/PendingSendBubble.tsx@@ -298,6 +298,7 @@ export function PendingSendBubble({renderImage,renderText,renderFile,+ renderReplyQuote,screenWidth,viewerDeviceId,onOpenImage,@@ -307,6 +308,8 @@ export function PendingSendBubble({renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;renderText: (text: string, index: number) => ReactNode;renderFile: (name: string, index: number) => ReactNode;+ /** 伙伴私聊的引用回复块;普通任务不传。 */+ renderReplyQuote?: (quote: NonNullable<MobilePendingSendItem['replyQuote']>) => ReactNode;screenWidth?: number;item: MobilePendingSendItem;actions: PendingSendBubbleActions;@@ -535,6 +538,7 @@ export function PendingSendBubble({]}testID={`pendingSend.body.${item.clientId}`}>+ {item.replyQuote && renderReplyQuote ? renderReplyQuote(item.replyQuote) : null}{rendersSentInlineBody ? (<SentInlineAtomBodyinteractiveAtoms={false}diff --git a/apps/mobile/src/session/companionReplyQuote.ts b/apps/mobile/src/session/companionReplyQuote.tsnew file mode 100644index 0000000000..a7a2c09a85--- /dev/null+++ b/apps/mobile/src/session/companionReplyQuote.ts@@ -0,0 +1,79 @@+/**+ * 伙伴私聊的引用回复(docs/product-rules/cindy-bots-runtime.md「私聊引用回复」「回复对应的消息」),+ * 与 Desktop 同一份信封字段:长按「回复」先在输入框上方放一条待发引用(按任务记在本次运行中),+ * 发送时随消息写进 `replyQuote`;气泡与「回复对应的消息」都画成群聊同款引用块。+ */+import { useSyncExternalStore } from 'react';+import type { BotGroupQuoteDisplay } from '@cindy/maker-shared/botGroupChat';+import { chatReplyQuoteExcerpt, type ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';+import { richAnswerText } from '@cindy/maker-shared/rich-answer';+import type { NormalizedRemoteMessage } from '@/session/messageNormalize';++const pending = new Map<string, ChatReplyQuote>();+const listeners = new Set<() => void>();+const notify = () => { for (const listener of listeners) listener(); };++export function setPendingCompanionReplyQuote(sessionId: string, quote: ChatReplyQuote | null): void {+ if (quote) pending.set(sessionId, quote);+ else if (!pending.delete(sessionId)) return;+ notify();+}++export function getPendingCompanionReplyQuote(sessionId: string | null | undefined): ChatReplyQuote | null {+ return sessionId ? pending.get(sessionId) ?? null : null;+}++/** Drop the quote that was just sent, unless another one replaced it meanwhile. */+export function clearSentCompanionReplyQuote(sessionId: string, sent: ChatReplyQuote): void {+ if (pending.get(sessionId) === sent) setPendingCompanionReplyQuote(sessionId, null);+}++const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+};++export function usePendingCompanionReplyQuote(sessionId: string | null | undefined): ChatReplyQuote | null {+ return useSyncExternalStore(subscribe, () => getPendingCompanionReplyQuote(sessionId), () => null);+}++export type QuotableMessage = Pick<NormalizedRemoteMessage, 'kind' | 'body' | 'attachments'> & {+ source: Pick<NormalizedRemoteMessage['source'], 'clientId' | 'id'>;+};++/** What the user reads: a companion reply's components as their visible text, not their source. */+function readableText(message: QuotableMessage): string {+ return message.kind === 'assistant' ? richAnswerText(message.body) : message.body;+}++function attachmentSummary(message: QuotableMessage | undefined): { count: number; name: string | null } {+ const names = (message?.attachments ?? []).map(attachment => attachment.name).filter(name => !!name);+ return { count: names.length, name: names[0] ?? null };+}++/** The quote a reply on `message` carries; only owner and companion messages can be quoted. */+export function companionReplyQuoteFor(message: QuotableMessage): ChatReplyQuote | null {+ if (message.kind !== 'user' && message.kind !== 'assistant') return null;+ const clientId = message.source.clientId ?? message.source.id;+ if (!clientId) return null;+ const excerpt = chatReplyQuoteExcerpt(readableText(message));+ return { clientId, role: message.kind, excerpt: excerpt || attachmentSummary(message).name || '' };+}++/** From the original while it is loaded here, otherwise from the snapshot taken when sending. */+export function companionReplyQuoteDisplay(+ quote: ChatReplyQuote,+ original: QuotableMessage | undefined,+ names: { owner: string; companion: string },+): BotGroupQuoteDisplay {+ const authorName = quote.role === 'assistant' ? names.companion : names.owner;+ if (!original) return { state: 'snapshot', authorName, excerpt: quote.excerpt, attachmentCount: 0, attachmentName: null };+ const attachments = attachmentSummary(original);+ return {+ state: 'live',+ authorName,+ excerpt: chatReplyQuoteExcerpt(readableText(original)),+ attachmentCount: attachments.count,+ attachmentName: attachments.name,+ };+}diff --git a/apps/mobile/src/session/companionReplyTargetPreference.ts b/apps/mobile/src/session/companionReplyTargetPreference.tsnew file mode 100644index 0000000000..b4a4171ce7--- /dev/null+++ b/apps/mobile/src/session/companionReplyTargetPreference.ts@@ -0,0 +1,48 @@+/**+ * 「显示回复对应的消息」本机偏好(docs/product-rules/cindy-bots-runtime.md「回复对应的消息」):打开后+ * 伙伴回复上方标出它回的是主人哪一条消息,对所有伙伴生效。默认关;只存 override(开时写入,关回默认即删除),+ * 与 Desktop 的本机偏好各自独立。+ */+import { useEffect, useSyncExternalStore } from 'react';+import AsyncStorage from '@react-native-async-storage/async-storage';++const key = 'cindy.mobile.companion-reply-target.v1';+let current = false;+let loaded: Promise<void> | undefined;+let revision = 0;+let writes = Promise.resolve();+const listeners = new Set<() => void>();+const notify = () => listeners.forEach(listener => listener());+const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+};++function load() {+ if (!loaded) {+ const initialRevision = revision;+ loaded = AsyncStorage.getItem(key).then(raw => {+ if (initialRevision === revision) {+ current = raw === 'true';+ notify();+ }+ }).catch(() => undefined);+ }+ return loaded;+}++export function saveCompanionReplyTargetPreference(enabled: boolean): Promise<void> {+ revision += 1;+ current = enabled;+ notify();+ const write = writes.catch(() => undefined)+ .then(() => (enabled ? AsyncStorage.setItem(key, 'true') : AsyncStorage.removeItem(key)));+ writes = write;+ return write;+}++export function useCompanionReplyTargetPreference(): boolean {+ const enabled = useSyncExternalStore(subscribe, () => current, () => false);+ useEffect(() => { void load(); }, []);+ return enabled;+}diff --git a/apps/mobile/src/session/inputProjection.ts b/apps/mobile/src/session/inputProjection.tsindex fcd569b844..8a298e039c 100644--- a/apps/mobile/src/session/inputProjection.ts+++ b/apps/mobile/src/session/inputProjection.ts@@ -1,3 +1,4 @@+import { readChatReplyQuote, type ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';import {buildAttachmentPersistFileRefs,buildAttachmentPersistImageRefs,@@ -142,6 +143,8 @@ export function buildQueuedTextMessage(agentReferences?: AgentInputReference[];pastedTextRanges?: Array<{ start: number; end: number; display: string }>;slashCommandRanges?: Array<{ start: number; end: number }>;+ /** 伙伴私聊引用回复:写进信封,宿主据此给伙伴附上原消息。 */+ replyQuote?: ChatReplyQuote;} = {},): QueuedRemoteMessage {const trimmed = text.trim();@@ -162,6 +165,7 @@ export function buildQueuedTextMessage(options.pastedTextRanges,options.slashCommandRanges,options.agentReferences,+ options.replyQuote,);const createdAt = now.toISOString();const uiLanguage = resolveSystemLocale(i18n.resolvedLanguage || i18n.language);@@ -219,6 +223,7 @@ function stringifyUserContent(pastedTextRanges: Array<{ start: number; end: number; display: string }> = [],slashCommandRanges?: Array<{ start: number; end: number }>,agentReferences: AgentInputReference[] = [],+ replyQuote?: ChatReplyQuote,): string {return JSON.stringify({text,@@ -228,9 +233,21 @@ function stringifyUserContent(...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),...(agentReferences.length > 0 ? { agentReferences } : {}),+ ...(replyQuote ? { replyQuote } : {}),});}+/** 排队编辑整条替换时沿用原消息的引用回复:引用属于这条消息,不属于被编辑的正文。 */+export function queuedMessageReplyQuote(+ message: Pick<QueuedRemoteMessage, 'persistedContent'>,+): ChatReplyQuote | undefined {+ try {+ return readChatReplyQuote(readRecord(JSON.parse(message.persistedContent))?.replyQuote) ?? undefined;+ } catch {+ return undefined;+ }+}+/** 排队编辑时从持久化信封恢复引用标志,避免整条替换后 marker 退化为正文。 */export function queuedMessageHasEncodedQuotes(message: Pick<QueuedRemoteMessage, 'persistedContent'>,diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex f6279e8c04..f981838f59 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -1,3 +1,4 @@+import { readChatReplyQuote, type ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';import { formatDuration } from '@cindy/maker-shared/message-render';import { parseMcpAppHistory } from '@cindy/maker-shared/mcp-apps';import { collectPluginInvocations, type PluginInvocation } from './pluginInvocations';@@ -100,6 +101,8 @@ export interface NormalizedRemoteMessage {slashCommandRanges?: Array<{ start: number; end: number }>;/** user Composer 的结构化语义引用;用于 fork / rewind 恢复同款 chip。 */agentReferences?: AgentInputReference[];+ /** user 专用:伙伴私聊的引用回复(信封 replyQuote),气泡正文上方显示引用块。 */+ replyQuote?: ChatReplyQuote;secondaryBody?: string;authorization?: Record<string, unknown>;systemCardData?: Record<string, unknown>;@@ -606,6 +609,7 @@ export function normalizeRemoteMessages(...(userContent?.agentReferences?.length? { agentReferences: userContent.agentReferences }: {}),+ ...(userContent?.replyQuote ? { replyQuote: userContent.replyQuote } : {}),align: message.role === 'user' && hookSource === undefined ? 'user' : 'agent',createdAt: message.createdAt,isStreaming: readMessageStreaming(message) || undefined,@@ -753,6 +757,7 @@ function parseUserContent(content: unknown): {pastedTextRanges?: Array<{ start: number; end: number; display: string }>;slashCommandRanges?: Array<{ start: number; end: number }>;agentReferences?: AgentInputReference[];+ replyQuote?: ChatReplyQuote;} {const parsed = parseMaybeJsonObject(content);if (!parsed) {@@ -767,8 +772,10 @@ function parseUserContent(content: unknown): {const pastedTextRanges = readSentPastedTextRanges(parsed.pastedTextRanges, text);const slashCommandRanges = readSentSlashCommandRanges(parsed.slashCommandRanges, text);const agentReferences = readAgentInputReferences(parsed.agentReferences, text);+ const replyQuote = readChatReplyQuote(parsed.replyQuote);return {text,+ ...(replyQuote ? { replyQuote } : {}),quotesEncoded: parsed.quotesEncoded === true,...(pastedTextRanges ? { pastedTextRanges } : {}),...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.tsindex 6a182bd1d6..4e4309f43f 100644--- a/apps/mobile/src/session/pendingSendItems.ts+++ b/apps/mobile/src/session/pendingSendItems.ts@@ -35,6 +35,8 @@ import {type SentInlineToken,} from '@/session/sentMessageAtoms';import type { QueuedRemoteMessage } from '@/session/types';+import type { ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';+import { queuedMessageReplyQuote } from '@/session/inputProjection';import { sentImageGalleryKey, type GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';import type { MobileMessageRenderItem } from '@/session/messageRenderModel';import {@@ -113,6 +115,8 @@ export interface MobilePendingSendItem {waitingFor?: MobilePendingSendWaitingFor;/** 本机发出的时刻(手机时钟),伙伴对话的时间分隔按它分组,回流后同 key 沿用。 */sentAt?: number;+ /** 伙伴私聊的引用回复:乐观气泡同样先画出引用块,回流后原位不跳。 */+ replyQuote?: ChatReplyQuote;}export interface MobileMessageListExtraData {@@ -406,6 +410,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobileconst agentText = pendingSendAgentText(item);// 合成指令只显示标签:结构化 atom 也不能从原文里重建出来。const synthetic = pendingSendSyntheticKind(item, agentText) !== null;+ const replyQuote = item.persistedContent ? queuedMessageReplyQuote({ persistedContent: item.persistedContent }) : undefined;items.push({type: 'pending_send',key: pendingSendItemKey(item.clientId),@@ -429,6 +434,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobilehint: presentation?.hint ?? null,source: pendingSendSource(item),...(readMessageSourceDevice(item) ? { sourceDevice: readMessageSourceDevice(item) } : {}),+ ...(replyQuote ? { replyQuote } : {}),});};@@ -474,6 +480,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobileactions: null,hint: null,source: null,+ ...(item.replyQuote ? { replyQuote: item.replyQuote } : {}),});}return items;diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.tsindex 217b777546..9db5aeb831 100644--- a/apps/mobile/src/session/sessionOutbox.ts+++ b/apps/mobile/src/session/sessionOutbox.ts@@ -3,6 +3,7 @@* live in durableOutbox.ts / durableOutboxDelivery.ts; this module has no page ownership.* Recovery helpers remain for legacy direct sends and composer editing.*/+import type { ChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';import { i18n } from '@/i18n';import { isDurableOutboxHandedOff, type DurableOutboxRecord } from '@/session/durableOutbox';import type { MobileSessionReference } from '@/session/sessionReferences';@@ -148,6 +149,8 @@ export interface MobileOutboxItem {agentReferences: AgentInputReference[];pastedTextRanges: Array<{ start: number; end: number; display: string }>;slashCommandRanges: Array<{ start: number; end: number }>;+ /** 伙伴私聊引用回复;旧记录没有该字段。 */+ replyQuote?: ChatReplyQuote;/*** 发送时刻的权限档快照:plan 一次性语义在点发送时就恢复会话档,dispatch 重读* store 拿到的已是恢复后的值,消息本身必须仍按发送时刻的档位派发。@@ -198,6 +201,7 @@ export interface MobileOutboxDisplayItem {quotesEncoded: boolean;pastedTextRanges?: Array<{ start: number; end: number; display: string }>;slashCommandRanges?: Array<{ start: number; end: number }>;+ replyQuote?: ChatReplyQuote;attachmentCount: number;uploadedCount: number;/** 图片槽缩略格(按槽序);非图片附件走 fileCount 计数行。 */@@ -244,6 +248,7 @@ export function buildOutboxItem(input: {agentReferences?: AgentInputReference[];pastedTextRanges?: Array<{ start: number; end: number; display: string }>;slashCommandRanges?: Array<{ start: number; end: number }>;+ replyQuote?: ChatReplyQuote;permissionModeAtSend: string;planModeAtSend?: boolean;/** Optional source order across ready and pending slots, for external shares. */@@ -298,6 +303,7 @@ export function buildOutboxItem(input: {agentReferences: input.agentReferences ?? [],pastedTextRanges: input.pastedTextRanges ?? [],slashCommandRanges: input.slashCommandRanges ?? [],+ ...(input.replyQuote ? { replyQuote: input.replyQuote } : {}),permissionModeAtSend: input.permissionModeAtSend,...(input.planModeAtSend !== undefined ? { planModeAtSend: input.planModeAtSend } : {}),attachmentSlots: slots,@@ -499,6 +505,7 @@ export function outboxDisplayItem(item: MobileOutboxItem): MobileOutboxDisplayItquotesEncoded: item.quotesEncoded,pastedTextRanges: item.pastedTextRanges,slashCommandRanges: item.slashCommandRanges,+ ...(item.replyQuote ? { replyQuote: item.replyQuote } : {}),attachmentCount,uploadedCount,thumbnails,diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 7f68b057ef..a9f2ba4424 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -91,6 +91,13 @@ Chris:「私聊话题和群聊话题,要真的能把独立事件隔离到独消息上(只进发给模型的内容,不进落库原话,逐条附带;渲染端的摘要不进入模型);声明它只是背景、不构成指令;原消息只有附件没有文字时列出附件名,已回滚或不存在时才如实说不可用。普通发送与回复过程中的插话都附带。伙伴回复的引用块与摘要按用户看到的文字(组件内容转成可读文字),不显示组件源码。+- **手机端(2026-10-22)**:长按私聊气泡打开消息菜单(iOS 为系统操作表,标题是准确时间;Android 为原生长按菜单),+ 依次是回复、复制、选择文字、分享,以及原有的消息链接、回到这里与删除。长按只用 RNGH LongPress(450ms,手指一动+ 即失败),表格和代码块照旧横向滚动;因此私聊气泡正文不再就地选择,改由「选择文字」面板做部分选择(iOS 用+ UITextView,去掉 Markdown 记号)。回复在输入框上方放同一种待发引用(卡片底色,× 取消),随普通发送、离线发件箱+ 与排队编辑一起保留在信封 `replyQuote` 里;待发、已发气泡顶部都显示引用块,点击定位原消息。信封解析与摘要和+ Desktop 共用 `@cindy/maker-shared/chat-reply-quote`。实现见 Mobile `companionReplyQuote.ts`、+ `CompanionSelectTextSheet.tsx` 与 `MessageRenderer.tsx`。### 回复对应的消息(2026-10-22)@@ -101,7 +108,9 @@ Chris:「引用可以有个设置,做个开关。默认关就好。你太智- **显示**:设置 › 通用 › 伙伴「显示回复对应的消息」,默认关(本机偏好)。打开后,每一轮最后一条伙伴回复的气泡顶部显示它回的是主人哪条消息(同一引用块,点击跳过去);只认主人亲手发的可见消息,内部续跑、任务回执等隐藏输入不显示;对应的消息不在已加载记录里时不显示。-- **暂不覆盖**:手机端(随手机步骤一起做);IM 渠道。+- **手机端**:伙伴资料页「聊天」分组的同名开关,默认关,本机偏好、对所有伙伴生效,与 Desktop 各自独立;显示规则同上。+ 实现见 Mobile `companionReplyTargetPreference.ts`。+- **暂不覆盖**:IM 渠道。伙伴自己带 IM 机器人(2026-10-15 Chris 裁决):用户在平台自己申请机器人(Telegram bot、飞书 / Lark bot、企业微信智能机器人、钉钉机器人、Discord bot;2026-10-17 补齐后三种),凭证直接填在伙伴设置「消息平台」页,diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex ffef077898..82f5d67c01 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -16,6 +16,7 @@"./branding": "./src/branding.ts","./brand-identity": "./src/brandIdentity.ts","./chat-quotes": "./src/chatQuotes.ts",+ "./chat-reply-quote": "./src/chatReplyQuote.ts","./command-display": "./src/commandDisplay.ts","./client-endpoints": "./src/clientEndpoints.ts","./cindy-make-feature": "./src/cindyMakeFeature.ts",diff --git a/packages/maker-shared/src/chatReplyQuote.ts b/packages/maker-shared/src/chatReplyQuote.tsnew file mode 100644index 0000000000..f85d77e09f--- /dev/null+++ b/packages/maker-shared/src/chatReplyQuote.ts@@ -0,0 +1,33 @@+/**+ * 伙伴私聊的「引用回复」(docs/product-rules/cindy-bots-runtime.md「私聊引用回复」),Desktop 与 Mobile 共用。+ *+ * 主人引用私聊里的某条消息回复:用户消息的内容信封带上 `replyQuote`,气泡在正文上方显示引用块,+ * 宿主把原消息作为背景附在发给伙伴的这一条 wire 消息前。引用只指向同一任务里的消息。+ * `excerpt` 是发送时的摘要快照:原消息不在已加载记录里时按它显示,模型侧一律按 clientId 从库里重读。+ */+export interface ChatReplyQuote {+ /** The quoted message, in the same Session. */+ clientId: string;+ role: 'user' | 'assistant';+ /** Display snapshot taken when the quote was sent. */+ excerpt: string;+}++export const CHAT_REPLY_QUOTE_EXCERPT_MAX = 280;++export function chatReplyQuoteExcerpt(text: string): string {+ const line = text.replace(/\s+/g, ' ').trim();+ return line.length > CHAT_REPLY_QUOTE_EXCERPT_MAX+ ? `${line.slice(0, CHAT_REPLY_QUOTE_EXCERPT_MAX - 1)}…`+ : line;+}++/** Field-by-field validation of a persisted or received quote; anything malformed is no quote. */+export function readChatReplyQuote(value: unknown): ChatReplyQuote | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const raw = value as Record<string, unknown>;+ if (typeof raw.clientId !== 'string' || !raw.clientId || raw.clientId.length > 256) return null;+ if (raw.role !== 'user' && raw.role !== 'assistant') return null;+ if (typeof raw.excerpt !== 'string') return null;+ return { clientId: raw.clientId, role: raw.role, excerpt: chatReplyQuoteExcerpt(raw.excerpt) };+}