Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(mobile): 隔离任务输入状态并将拖拽迁到 UI 线程 (#3948)

Dash8a6c7e216c56
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 2cec659e5c..c2595b3d09 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -62,6 +62,8 @@ import {
type ViewStyle,
} from 'react-native';
import { Text, TextInput } from '@/components/AppText';
+import Reanimated, { useAnimatedStyle } from 'react-native-reanimated';
+import { GestureDetector } from '@/platform/gestureHandler';
import { MobileAgentMark } from '@/components/MobileAgentMark';
import type { TextInput as NativeTextInput } from 'react-native';
import { ScreenBackButton } from '@/components/MobilePrimitives';
@@ -143,6 +145,7 @@ import {
useShareSelectionRevision,
} from '@/session/shareSelectionStore';
import { ComposerRichInput, type ComposerRichInputHandle } from '@/session/ComposerRichInput';
+import { createComposerDraftSource, useComposerVoiceDraftWriter, type ComposerDraftSource } from '@/session/composerDraftSource';
import { InlineQueueSection } from '@/session/InlineQueueSection';
import { inputProjectionErrorI18nKey } from '@/session/inputProjectionError';
import { RewindPreviewPanel } from '@/session/RewindPreviewPanel';
@@ -1013,14 +1016,13 @@ export default function SessionScreen() {
const taskUpdates = useSessionTaskUpdates(sessionId);
const activeComposerDraftScopeKey = composerDraftScopeKey(sessionId, routeDraft);
const [composerDraftStateKey, setComposerDraftStateKey] = useState(activeComposerDraftScopeKey);
- const [composerDocument, setComposerDocumentState] = useState<ComposerDocument>(
- () => readImmediateComposerDraftScope(sessionId, routeDraft).document,
+ const [composerDraftSource, setComposerDraftSource] = useState(() =>
+ createComposerDraftSource(readImmediateComposerDraftScope(sessionId, routeDraft).document),
);
- const [draft, setDraft] = useState(() => composerDocumentProjectedText(composerDocument));
const [composerDraftHydrated, setComposerDraftHydrated] = useState(false);
const appliedRouteDraftRef = useRef<string | null>(null);
- const draftRef = useRef(draft);
- const composerDocumentRef = useRef<ComposerDocument>(composerDocument);
+ const draftRef = useRef(composerDraftSource.getSnapshot().draft);
+ const composerDocumentRef = useRef<ComposerDocument>(composerDraftSource.getSnapshot().document);
// replaceParams 复用同一 SessionScreen。任务参数变化的这次 render 仍拿着 A 的
// state;若直接让 key={sessionId} 子树挂载,B 编辑器会先用 A 文档初始化,再等
// 被动 effect 水合纠正。沿本页 read-ack 的 render-phase 换代模式同步种入 B 的
@@ -1029,8 +1031,7 @@ export default function SessionScreen() {
const nextScope = readImmediateComposerDraftScope(sessionId, routeDraft);
const nextDraft = composerDocumentProjectedText(nextScope.document);
setComposerDraftStateKey(activeComposerDraftScopeKey);
- setComposerDocumentState(nextScope.document);
- setDraft(nextDraft);
+ setComposerDraftSource(createComposerDraftSource(nextScope.document));
setComposerDraftHydrated(false);
// 旧 A 的 AsyncStorage promise 可能在 effect cleanup 前落定;先让它的 key 失配。
// 保持 null 也确保 B 的 effect 仍会继续异步 hydrate 磁盘草稿与冷启动引用。
@@ -1158,9 +1159,6 @@ export default function SessionScreen() {
});
return () => { cancelled = true; };
}, [mode, shareCharacterSrc, shareLogoSrc, shareSelectionActive]);
- const [composerFocused, setComposerFocused] = useState(false);
- const [composerInputContentHeight, setComposerInputContentHeight] = useState(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT);
- const [voiceDraftCaretFrame, setVoiceDraftCaretFrame] = useState({ left: 0, top: 0 });
// Context 面板(+ 号弹出的可拖动 sheet):open + 面板内子视图(主视图 / 截图列表 / 目标模式)。
const [contextSheetOpen, setContextSheetOpen] = useState(false);
const [contextSheetView, setContextSheetView] = useState<'main' | 'screenshots' | 'goal'>('main');
@@ -1324,6 +1322,9 @@ export default function SessionScreen() {
}
};
}, [sessionId, removePendingUpload]);
+ const [voiceStartPending, setVoiceStartPending] = useState(false);
+ const voiceStartPendingSeqRef = useRef(0);
+ const voiceStartedOnPressInRef = useRef(false);
const [voiceState, setVoiceStateInternal] = useState<MobileVoiceState>('idle');
const [voiceError, setVoiceError] = useState<string | null>(null);
const [voiceReleaseToSendActive, setVoiceReleaseToSendActive] = useState(false);
@@ -1519,13 +1520,6 @@ export default function SessionScreen() {
const [searchQuery, setSearchQuery] = useState('');
const [activeSearchIndex, setActiveSearchIndex] = useState(-1);
const [routeFocusedClientId, setRouteFocusedClientId] = useState<string | null>(null);
- const [slashCommands, setSlashCommands] = useState<MobileSlashCommand[]>([]);
- const [slashPaletteLoading, setSlashPaletteLoading] = useState(false);
- const [slashPaletteError, setSlashPaletteError] = useState<string | null>(null);
- const [atResources, setAtResources] = useState<MobileAtResourceItem[]>([]);
- const [atPaletteLoading, setAtPaletteLoading] = useState(false);
- const [atPaletteError, setAtPaletteError] = useState<string | null>(null);
- const [atResourcesTruncated, setAtResourcesTruncated] = useState(false);
const [loading, setLoading] = useState(false);
const [loadingEarlier, setLoadingEarlier] = useState(false);
const [hasOlderMessages, setHasOlderMessages] = useState(false);
@@ -1863,9 +1857,6 @@ export default function SessionScreen() {
const voiceStopAfterStartRef = useRef(false);
const finishVoiceRecordingRef = useRef<(() => void) | null>(null);
const composerInputRef = useRef<ComposerRichInputHandle | null>(null);
- const composerScrollViewRef = useRef<ScrollView>(null);
- const composerScrollEnabledRef = useRef(false);
- const voiceDraftScrollRef = useRef<ScrollView>(null);
const voiceControllerSessionRef = useRef<MobileVoiceControllerSession | null>(null);
const voiceDictionaryLearningTrackerRef = useRef<MobileVoiceDictionaryLearningTracker | null>(null);
const sendLatestRef = useRef<((options?: {
@@ -1873,9 +1864,14 @@ export default function SessionScreen() {
documentOverride?: ComposerDocument;
}) => Promise<void>) | null>(null);
const sendButtonRef = useRef<View>(null);
+ const composerSendTargetEnabledRef = useRef(false);
+ // Match the keyed palette lifetime. Old requests/cleanup retain their old
+ // reference and cannot affect command dispatch in the next draft scope.
+ const slashCommandsRef = useMemo<RefObject<MobileSlashCommand[]>>(
+ () => ({ current: [] }),
+ [activeComposerDraftScopeKey],
+ );
const sendButtonFrameRef = useRef<{ height: number; width: number; x: number; y: number } | null>(null);
- const slashLoadSeqRef = useRef(0);
- const atLoadSeqRef = useRef(0);
const capabilitiesLoadSeqRef = useRef(0);
const alternateCapabilitiesLoadSeqRef = useRef(0);
const agentSwitchIntentLoadSeqRef = useRef(0);
@@ -2253,26 +2249,9 @@ export default function SessionScreen() {
hasSyncedThisOpen: lastSyncedAt !== null,
remoteUnavailable: !!remoteUnavailableReason,
});
- const composerTrigger = useMemo(() => detectComposerTrigger(draft), [draft]);
- const visibleSlashCommands = useMemo(
- () => canUseComposer && composerTrigger.kind === 'slash'
- ? filterSlashCommands(mergeMobileLocalSlashCommands(slashCommands), composerTrigger.query, 5)
- : [],
- [canUseComposer, composerTrigger, slashCommands],
- );
- const visibleAtResources = useMemo(
- () => canUseComposer && composerTrigger.kind === 'at'
- ? filterAtResources(atResources, composerTrigger.query, 5)
- : [],
- [atResources, canUseComposer, composerTrigger],
- );
- const voiceUiAvailable = shouldShowMobileVoiceUi(Platform.OS);
- const voiceIsListening = voiceState === 'listening';
const voiceIsProcessing = voiceState === 'submitting' || voiceState === 'refining';
- const voiceIsBusy = voiceIsListening || voiceIsProcessing;
+ const composerSendUnavailableReason = canUseComposer ? null : composerDisabledReason;
// 手机语音只保留官方托管路径,错误引导仅剩系统麦克风权限一条。
- const canOpenVoiceSettings = isMobileVoiceMicPermissionError(voiceError);
- const composerHasText = draft.trim().length > 0;
const canStopQueue = !!stopOptionsForProjection(inputProjection)
&& !inputProjection.queuePaused
&& !inputProjection.queueAbortPending;
@@ -2461,104 +2440,16 @@ export default function SessionScreen() {
? t('session.screen.nextAgentSwitch', { agent: mobileAgentLabel(agentSwitchIntent.targetAgentKind), model: composerRuntimeSummary.modelSummary })
: composerRuntimeSummary.modelSummary
: '';
- const composerSendUnavailableReason = canUseComposer ? null : composerDisabledReason;
- // 引用已是 ComposerDocument 内的 atom;排队编辑同样可能只有引用而没有可见
- // 文本,因此必须计入 payload,否则「保存修改」会被错误禁用。
- const composerQuoteCount = composerDocumentQuotes(composerDocument).length;
- // Context 面板是 Modal sheet,不再有内联附件面板 → attachmentPickerOpen 恒 false。
- const composerLayout = useMemo(() => buildSessionComposerLayout({
- attachmentBusy: false,
- // pending(乐观上传中)计入:拍完照 / 选完文件立即可点发送,send() 内部会等落定。
- attachmentCount: attachments.length + pendingUploads.length,
- attachmentPickerOpen: false,
- // Stop 的可见性跟随真实运行 / 队列状态;断线时只单独禁用交互。
- canStop: canStopComposer,
- draftText: draft,
- queueBusy,
- quoteCount: composerQuoteCount,
- sendUnavailableReason: composerSendUnavailableReason,
- sending,
- voiceState,
- }), [
- attachments.length,
- pendingUploads.length,
- canStopComposer,
- canUseComposer,
- composerQuoteCount,
- composerSendUnavailableReason,
- draft,
- i18nInstance.language,
- queueBusy,
- sending,
- voiceState,
- ]);
- const compactComposer = composerLayout.density === 'compact';
- // 「按下即录」的乐观反馈(对齐桌面 activeRecording = listening || longPressActive):
- // pressIn 发起启动的同时置 pending,胶囊立刻展开计时,不等 ASR/权限链路把 state
- // 翻到 listening——否则启动慢时按钮有一段「按了没反应」。启动完成(成功进
- // listening / 失败报错)后由 finally 收回;成功路径收回时 listening 已为 true,
- // 计时输入保持连续,不会闪断重置。声明在槽位 flags 之前:pending 期就要占住发送槽。
- const [voiceStartPending, setVoiceStartPending] = useState(false);
- // pending 的世代号:本组件会随 sessionId 复用,上一个会话的启动收尾不能把
- // 当前会话刚展开的乐观胶囊收掉——finally 只在世代未前进时清 pending。
- const voiceStartPendingSeqRef = useRef(0);
- // pressIn 已起录的标记:同一次手势的松手(onPress)不能再被当作「再点一下停止」。
- const voiceStartedOnPressInRef = useRef(false);
- // 发送槽双语义(对齐桌面 ChatInput 的主槽判定,voice busy = listening|submitting|refining):
- // 任务执行中且发送不可用、又没有语音在进行时,停止任务顶替发送位;语音一旦开始,
- // 发送键回到发送位(录音期=「结束并发送」,润色期=禁用态占位),停止任务退到
- // 语音按钮**左边**的独立槽。语音按钮由此永远是发送槽的左邻,右缘位置与是否有
- // 草稿/是否录音/任务是否执行全部无关——录音胶囊只向左生长,「原地再点一下」
- // 永远是停止录音,不会误停任务。
- const composerSendSlotIsStop = composerLayout.stop.visible
- && composerLayout.send.disabled
- && !sending
- && !voiceIsBusy
- && !voiceStartPending;
- // 只有确定性不可用(撤权 / 关闭远控等)才禁发送;普通断线与自动恢复状态仍可发,
- // 消息进入本地 outbox 等连接恢复。输入框在两类状态下都保持可编辑与持久化。
- const composerSendDisabled = composerLayout.send.disabled;
- const composerStopDisabled = composerLayout.stop.disabled || !canUseRemoteSessionControls;
- const composerStopDisabledReason = !canUseRemoteSessionControls
- ? remoteUnavailableReason ?? t('session.menu.aiRenameOffline')
- : composerLayout.stop.disabledReason;
- const composerShowInlineStop = composerLayout.stop.visible && !composerSendSlotIsStop && !sending;
- const composerHasPayload = composerHasText || attachments.length > 0 || pendingUploads.length > 0 || composerQuoteCount > 0;
- // send.visible 在语音生命周期内恒 true(sessionOperation.ts),这里不再按
- // voiceIsListening 二次过滤——那正是「首段转写落地瞬间发送键冒出来」的跳变源。
- // 乐观 pending 期(state 还是 idle)同样要占住发送槽:否则空草稿按下语音时
- // 胶囊先在 12pt 档展开,listening 一到发送键出现又整体跳到 52pt 档。
- const composerShowSendButton = composerLayout.send.visible || voiceStartPending;
- const composerVoicePlacement = voiceUiAvailable
- ? resolveMobileComposerVoiceButtonPlacement({
- // 行尾有发送或占发送位的停止按钮时让位;附件-only(无文字)同样命中。
- hasTrailingAction: composerSendSlotIsStop || composerShowSendButton,
- })
- : undefined;
- // 录音计时(红点+m:ss 胶囊);pillWidth 同时驱动语音按钮与工具排占位 slot,
- // 胶囊展开时把左邻的停止任务按钮推开,而不是盖住它。expanded 含乐观 pending
- // (按下即展开),counting 只认真实采集(listening)——启动链路(权限弹窗等)
- // 不计入录音时长,pending 期显示静止的 0:00。
- const voiceRecordingTimer = useMobileVoiceRecordingTimer({
- expanded: voiceIsListening || voiceStartPending,
- counting: voiceIsListening,
- });
- const composerEffectiveContentHeight = composerInputContentHeight;
- const voiceDraftShowsListeningPrompt = voiceIsListening && draft.length === 0;
- // 状态行只承载错误信息;「正在听 / 转写中」不再占一行,对齐桌面版——
- // 录音状态由输入框内的语音按钮形态(Mic / 红点计时胶囊 / spinner)表达。
- const voiceStatusVisible = voiceUiAvailable && Boolean(voiceError);
const nativeShellLayout = useMemo(() => buildSessionNativeShellLayout({
attachmentPickerOpen: false,
keyboardHeight: keyboardState.height,
keyboardVisible: keyboardState.visible,
- paletteOpen: composerTrigger.kind === 'slash' || composerTrigger.kind === 'at',
+ paletteOpen: false,
platform: Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'web',
safeAreaBottomInset: insets.bottom,
screenHeight: windowDimensions.height,
screenWidth: windowDimensions.width,
}), [
- composerTrigger.kind,
insets.bottom,
keyboardState.height,
keyboardState.visible,
@@ -2695,129 +2586,11 @@ export default function SessionScreen() {
const handleDrawerGoHome = useCallback(() => {
queueDrawerNavigation(() => router.dismissTo('/'));
}, [queueDrawerNavigation, router]);
- // 聚焦 / 面板打开 / 语音中呈现卡片形态(输入区全宽 + 底部工具排),其余保持单行简洁态。
- // 注意不看 composerLayout.density:有草稿 / 会话运行中未聚焦时也应收回简洁态,
- // 否则「拖回单行退出激活态」永远收不回去。
- // 语音结束后草稿仍有内容时经 hold 保持展开(一行文字也不收),
- // 不随 voiceIsBusy 归零塌回简洁态。
- const composerVoiceHoldActive = resolveComposerVoiceHoldActive({
- armed: composerVoiceHoldArmed,
- draftText: draft,
- });
- const composerCardActive = (canUseComposer && composerFocused)
- || modelSheetOpen
- || permissionSheetOpen
- || voiceIsBusy
- || composerVoiceHoldActive;
- useComposerCardTransition(composerCardActive, keyboardState);
- const composerChromeHeight = useMemo(() => {
- const statusReserve = voiceStatusVisible
- ? COMPOSER_STATUS_ROW_RESERVED_HEIGHT + COMPOSER_STACK_GAP_HEIGHT
- : 0;
- const rowChrome = composerCardActive
- ? COMPOSER_CARD_ROW_CHROME_HEIGHT
- : COMPOSER_INPUT_ROW_CHROME_HEIGHT;
- return COMPOSER_VERTICAL_PADDING_HEIGHT + statusReserve + rowChrome;
- }, [composerCardActive, voiceStatusVisible]);
- const composerInputMaxContentHeight = useMemo(() => {
- const availableHeight = nativeShellLayout.composerMaxHeight - composerChromeHeight;
- return Math.min(
- COMPOSER_INPUT_MAX_CONTENT_HEIGHT,
- Math.max(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT, availableHeight),
- );
- }, [composerChromeHeight, nativeShellLayout.composerMaxHeight]);
- // 下拉收起 = 退出聚焦激活态(模型浮窗已是独立 Modal,拖拽手势够不到它,无需在此关闭)。
- // 语音结束 hold 态未聚焦,blur 是 no-op,需显式解除 hold 才能收回简洁态。
- const handleComposerSnapToAuto = useCallback(() => {
- setComposerVoiceHoldArmed(false);
- composerInputRef.current?.blur();
- }, []);
- // grabber touch-down 同步关掉外壳滚动(setNativeProps 直改原生属性)。这里
- // 绝不能走 setState:本页 re-render 很重,touch-down 触发渲染会阻塞 JS 线程,
- // 手势 move 事件被合并延后,位移在 PanResponder grant 重置 dx/dy 前全部丢失,
- // 拖拽调高变成「没反应」(实测第一个 move 到达时位移已累计 -180px)。
- const handleGrabberTouchActiveChange = useCallback((active: boolean) => {
- composerScrollViewRef.current?.setNativeProps({
- scrollEnabled: active ? false : composerScrollEnabledRef.current,
- });
- }, []);
- const composerResize = useComposerResize({
- autoMaxContentHeight: composerInputMaxContentHeight,
- // 简洁态一律收到单行(下拉收起和点别处收键盘的结果一致);
- // auto / manual 记忆保留,重新聚焦后恢复。
- collapsed: !composerCardActive,
- composerChromeHeight,
- contentHeight: composerEffectiveContentHeight,
- keyboardHeight: keyboardState.visible ? keyboardState.height : 0,
- onGrabberTouchActiveChange: handleGrabberTouchActiveChange,
- onSnapToAuto: handleComposerSnapToAuto,
- singleLineContentHeight: COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT,
- windowHeight: windowDimensions.height,
- });
- composerResizeDraggingRef.current = composerResize.dragging;
- // manual 高度跨聚焦/失焦、键盘开合保留(用户拖出的高度是显式意图);
- // 唯一自然失效点:草稿清空(发送成功/删光)回 auto,避免空输入框残留定高。
- const composerResizeReset = composerResize.reset;
- useEffect(() => {
- if (draft.length === 0) {
- composerResizeReset();
- // 草稿清空(发送成功/删光)后语音结束 hold 也失去意义,一并解除。
- setComposerVoiceHoldArmed(false);
- }
- }, [draft, composerResizeReset]);
- const composerInputIsMultiline = composerResize.dragging
- || composerResize.mode === 'manual'
- || (draft.length > 0
- && (draft.includes('\n') || composerEffectiveContentHeight > COMPOSER_INPUT_MULTILINE_CONTENT_THRESHOLD));
- const composerInputVisibleHeight = composerResize.visibleContentHeight;
- const composerInputScrollEnabled = composerResize.scrollEnabled;
- const composerShellHasScrollableContent = attachments.length > 0
- || pendingUploads.length > 0
- || attachmentError !== null
- || composerTrigger.kind === 'slash'
- || composerTrigger.kind === 'at';
- // 外壳滚动只在真有可滚内容(附件托盘/附件面板/触发面板)时启用:输入区自增长
- // 本来就被 cap 在容器内,没有附件时启用滚动只会让原生滚动手势与 grabber 拖拽
- // 竞争、吞掉 move 事件。有可滚内容时由 handleGrabberTouchActiveChange 在
- // touch-down 同步关闸(见上),这里只维护声明式的目标值。
- const composerScrollEnabled = nativeShellLayout.composerScrollEnabled
- && !composerResize.dragging
- && composerShellHasScrollableContent;
- composerScrollEnabledRef.current = composerScrollEnabled;
- const handleComposerInputContentSizeChange = useCallback((event: TextInputContentSizeChangeEvent) => {
- const nextHeight = Math.max(
- COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT,
- Math.ceil(event.nativeEvent.contentSize.height),
- );
- setComposerInputContentHeight((currentHeight) => (
- Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight
- ));
- }, []);
- const handleComposerRichInputHeight = useCallback((height: number) => {
- const nextHeight = Math.max(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT, Math.ceil(height));
- setComposerInputContentHeight((currentHeight) => (
- Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight
- ));
- }, []);
const handleComposerInputPressIn = useCallback(() => {
if (voiceRecordingActiveRef.current || voiceState === 'listening') {
finishVoiceRecordingRef.current?.();
}
}, [voiceState]);
- const handleVoiceDraftTextLayout = useCallback((event: TextLayoutEvent) => {
- const lines = event.nativeEvent.lines;
- const lastLine = lines[lines.length - 1];
- if (!lastLine) return;
- const nextFrame = {
- left: Math.max(0, Math.round(lastLine.x + lastLine.width + COMPOSER_VOICE_CARET_GAP)),
- top: Math.max(0, Math.round(lastLine.y + ((lastLine.height - COMPOSER_INPUT_LINE_HEIGHT) / 2))),
- };
- setVoiceDraftCaretFrame((currentFrame) => (
- currentFrame.left === nextFrame.left && currentFrame.top === nextFrame.top
- ? currentFrame
- : nextFrame
- ));
- }, []);
const openSessionMenu = useCallback((view: SessionMenuView = 'menu') => {
setMenuInitialView(view);
setSettingsOpen(true);
@@ -2831,199 +2604,34 @@ export default function SessionScreen() {
setSessionTreePendingOpen(false);
setSessionTreeOpen(true);
}, [sessionTreePendingOpen]);
- const renderComposerResizeHandle = () => (
- <ComposerResizeGrabber
- onAdjust={composerResize.adjustByLine}
- panHandlers={composerResize.panHandlers}
- testID="session.composerResizeGrabber"
- visible
- />
- );
- // 聚焦卡片形态的底部工具排:[+][模型] …… [语音][停止/发送]。
- // + 号打开 Context 面板(附件 / 计划模式 / 目标模式收在面板内);权限模式入口收进会话设置。
- // 权限模式图标钮(2026-07-29 用户裁决,对齐 Codex,与新建页同位同款):
- // 只显示档位图标,不带文字;危险档(auto / bypass)只染图标色。
- const renderSessionPermissionButton = () => {
- const presentation = permissionPresentation(displayPermissionMode, displayPermissionLabel);
- const accent = presentation.accent !== 'neutral'
- ? permissionAccentColor(presentation.accent, colors)
- : null;
- return (
- <RouteActionButton
- accessibilityLabel={t('models.picker.permissionModeAccessibility', { mode: presentation.label })}
- active={permissionSheetOpen}
- disabled={controlBusy || !canUseRemoteSessionControls}
- hitSlop={COMPOSER_CONTROL_HIT_SLOP}
- onPress={() => {
- setModelSheetOpen(false);
- setPermissionSheetSnap('half');
- setPermissionSheetOpen(true);
- }}
- style={[
- styles.composerInlineToolButton,
- permissionSheetOpen && styles.composerToolButtonActive,
- ]}
- testID="session.permissionIndicator"
- >
- <presentation.Icon
- color={accent ?? colors.textSecondary}
- size={iconSize.sm}
- strokeWidth={iconStroke.regular}
- />
- </RouteActionButton>
- );
- };
-
- // 工具条布局:左 = [+][权限][计划 chip][模型];右 = [停止][语音][发送]。
- // 模型放左侧组,不随发送/停止出现而横向跳动。
- const renderComposerToolbar = () => (
- <>
- <ComposerToolbarLeftGroup testID="session.composerToolbarLeft">
- {renderComposerAttachmentButton()}
- {renderSessionPermissionButton()}
- {planModeOn ? (
- <PlanModeChip
- disabled={controlBusy || !canUseRemoteSessionControls}
- onExit={() => togglePlanMode(false)}
- testID="session.planModeChip"
- />
- ) : null}
- {composerRuntimeSummary ? (
- <ComposerRuntimePill
- disabled={controlBusy || !canUseRemoteSessionControls}
- fastOn={composerPillFastOn}
- label={composerRuntimeLabel}
- leading={agentSwitchIntent ? (
- <MobileAgentMark
- agentKind={agentSwitchIntent.targetAgentKind}
- color={colors.textSecondary}
- size={iconSize.sm}
- />
- ) : composerPillSourceId ? (
- // 正常态显示真正生效来源;断开态显示 DB 中的真实来源并使用状态色,
- // 不静默换成 activeSourceId 的默认回退 Logo。
- <MobileModelIconMark
- color={composerSelectedSourceDisconnected ? colors.statusError : undefined}
- icon={currentSession && composerPillSourceProvider
- ? getModel(composerPillSourceProvider, currentSession.model, sessionAgentKind)?.icon
- : undefined}
- name={composerPillSourceProvider?.name ?? composerPillSourceId}
- providerId={composerPillSourceId}
- routing={composerPillSourceProvider?.routing}
- logoKind={composerPillSourceProvider?.logoKind}
- />
- ) : null}
- onPress={toggleComposerModelPicker}
- testID="session.composerModelButton"
- />
- ) : null}
- </ComposerToolbarLeftGroup>
- <ComposerToolbarSpacer />
- {/* 工具排右段顺序:[停止任务][语音占位][发送槽]。停止任务在语音左边(对齐桌面),
- 语音占位宽度随录音胶囊(红点+计时)展开,把停止任务推开——语音右缘与发送槽
- 的邻接关系全程不变。模型在 spacer 左侧,不随右段显隐横向跳动。 */}
- {renderComposerInlineStop()}
- {composerVoicePlacement?.inline || composerVoicePlacement?.floating
- ? <ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />
- : null}
- {renderComposerSendSlot()}
- </>
- );
- const renderComposerInputOverlay = () => voiceIsListening ? (
- // 「点输入区 = 想打字 → 停止听写」由这层 RN 覆盖层承接。听写期间真正盖在输入区上的
- // 就是它;底下的富文本 WebView 此刻是 hidden(opacity 0),iOS hitTest 会跳过 alpha≈0
- // 的 view,它根本收不到触摸——把停听写挂在 WebView 的 focus / touch 上都不成立
- // (focus 还会被 WKWebView 自己恢复焦点误触发,掐断刚开始的听写)。
- <Pressable
- accessibilityLabel={t('session.common.voiceStopRecording')}
- accessibilityRole="button"
- // onPressIn 给手指「触摸即停」的即时手感;onPress 是无障碍激活(VoiceOver /
- // TalkBack 的 activate 只走 onPress,不会派发 onPressIn)的唯一入口,两者都要挂。
- // handler 幂等:finishVoiceRecording 有 voiceStopInFlight 门,重复调用是 no-op。
- onPress={handleComposerInputPressIn}
- onPressIn={handleComposerInputPressIn}
- style={styles.voiceDraftOverlay}
- testID="session.voiceDraftOverlay"
- >
- <ScrollView
- ref={voiceDraftScrollRef}
- contentContainerStyle={[
- styles.voiceDraftOverlayContent,
- !composerCardActive && styles.voiceDraftOverlayContentGeometric,
- ]}
- onContentSizeChange={() => {
- requestAnimationFrame(() => {
- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
- });
- }}
- onLayout={() => {
- requestAnimationFrame(() => {
- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
- });
- }}
- pointerEvents="none"
- scrollEnabled={composerInputScrollEnabled}
- showsVerticalScrollIndicator={false}
- style={styles.voiceDraftScroll}
- >
- {voiceDraftShowsListeningPrompt ? (
- <View style={styles.voiceDraftListeningPrompt}>
- <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />
- <Text style={styles.voiceDraftListeningText}>{composerLayout.input.placeholder}</Text>
- </View>
- ) : (
- <View style={styles.voiceDraftMeasuredBlock}>
- <Text
- onTextLayout={handleVoiceDraftTextLayout}
- style={styles.voiceDraftText}
- >
- {draft}
- </Text>
- <View
- pointerEvents="none"
- style={[
- styles.voiceDraftCaretOverlay,
- {
- left: voiceDraftCaretFrame.left,
- top: voiceDraftCaretFrame.top,
- },
- ]}
- >
- <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />
- </View>
- </View>
- )}
- </ScrollView>
- </Pressable>
- ) : null;
- const measureSendButtonTarget = useCallback(() => {
- sendButtonRef.current?.measureInWindow((x, y, width, height) => {
- sendButtonFrameRef.current = { x, y, width, height };
- });
- }, []);
- const isPointInsideSendButton = useCallback((event: GestureResponderEvent) => {
- const frame = sendButtonFrameRef.current;
- if (!composerShowSendButton || !frame || composerLayout.send.disabled || !canUseComposer) return false;
- const { pageX, pageY } = event.nativeEvent;
- const pad = 10;
- return pageX >= frame.x - pad
- && pageX <= frame.x + frame.width + pad
- && pageY >= frame.y - pad
- && pageY <= frame.y + frame.height + pad;
- }, [canUseComposer, composerLayout.send.disabled, composerShowSendButton]);
- const updateVoiceReleaseToSendTarget = useCallback((event: GestureResponderEvent): boolean => {
- const active = voiceLongPressActiveRef.current && isPointInsideSendButton(event);
- setVoiceReleaseToSendActive(active);
- return active;
- }, [isPointInsideSendButton]);
- // Bottom padding the message list needs to clear the composer = the composer's own height only.
- // The keyboard lift is already applied once by ComposerKeyboardAvoidingView,
- // so ALSO adding keyboardBottomInset here double-counted the keyboard and shoved the conversation
- // up (badly visible once the list bottom-anchors its content). Keyboard-closed is unchanged —
- // keyboardBottomInset is 0 then, so this matches the previous value.
- const bottomOverlayHeight = useMemo(
- () => Math.ceil(bottomOverlayContentHeight),
- [bottomOverlayContentHeight],
+ const measureSendButtonTarget = useCallback(() => {
+ sendButtonRef.current?.measureInWindow((x, y, width, height) => {
+ sendButtonFrameRef.current = { x, y, width, height };
+ });
+ }, []);
+ const isPointInsideSendButton = useCallback((event: GestureResponderEvent) => {
+ const frame = sendButtonFrameRef.current;
+ if (!composerSendTargetEnabledRef.current || !frame || !canUseComposer) return false;
+ const { pageX, pageY } = event.nativeEvent;
+ const pad = 10;
+ return pageX >= frame.x - pad
+ && pageX <= frame.x + frame.width + pad
+ && pageY >= frame.y - pad
+ && pageY <= frame.y + frame.height + pad;
+ }, [canUseComposer]);
+ const updateVoiceReleaseToSendTarget = useCallback((event: GestureResponderEvent): boolean => {
+ const active = voiceLongPressActiveRef.current && isPointInsideSendButton(event);
+ setVoiceReleaseToSendActive(active);
+ return active;
+ }, [isPointInsideSendButton]);
+ // Bottom padding the message list needs to clear the composer = the composer's own height only.
+ // The keyboard lift is already applied once by ComposerKeyboardAvoidingView,
+ // so ALSO adding keyboardBottomInset here double-counted the keyboard and shoved the conversation
+ // up (badly visible once the list bottom-anchors its content). Keyboard-closed is unchanged —
+ // keyboardBottomInset is 0 then, so this matches the previous value.
+ const bottomOverlayHeight = useMemo(
+ () => Math.ceil(bottomOverlayContentHeight),
+ [bottomOverlayContentHeight],
);
const applyComposerDocument = useCallback((
@@ -3031,10 +2639,14 @@ export default function SessionScreen() {
options?: { persist?: boolean },
) => {
composerDocumentRef.current = value;
- setComposerDocumentState(value);
const projected = composerDocumentProjectedText(value);
draftRef.current = projected;
- setDraft(projected);
+ const pendingSkill = pendingSkillSelectionRef.current;
+ const head = /^\/([a-z][\w-]*)/i.exec(projected.trimStart());
+ if (pendingSkill && (pendingSkill.sid !== sessionId || head?.[1].toLowerCase() !== pendingSkill.name.toLowerCase())) {
+ pendingSkillSelectionRef.current = null;
+ }
+ composerDraftSource.setDocument(value);
voiceDictionaryLearningTrackerRef.current?.inspectDraft(projected);
if (options?.persist !== false) {
saveComposerDocumentDraft(sessionId, value);
@@ -3042,7 +2654,7 @@ export default function SessionScreen() {
// older builds do not turn a rich draft into an empty composer.
saveComposerDraft(sessionId, projected);
}
- }, [sessionId]);
+ }, [composerDraftSource, sessionId]);
const applyComposerDraft = useCallback((value: string, options?: { persist?: boolean }) => {
const document = reconcileComposerProjectedText(composerDocumentRef.current, value);
@@ -3067,24 +2679,7 @@ export default function SessionScreen() {
applyComposerDraft(value, queueEditingRef.current ? { persist: false } : undefined);
}, [applyComposerDraft]);
- // 听写期间只滚动覆盖层跟随最新文字,**不碰隐藏编辑器的 caret**(2026-07-28):
- // 旧实现每段转写都把选区挪到末尾,而富文本编辑器的选区操作底层是 WebView
- // 程序化 focus,配合 keyboardDisplayRequiresUserAction={false} 会在点语音的
- // 同时弹出软键盘。#551 之前这个 focus 表现为「听写刚开始就被掐断」(focus 即
- // 停听写),#551 修掉掐断后它幸存为弹键盘。听写中输入框本就隐藏(覆盖层渲染
- // 草稿),caret 无意义;落焦统一放在听写结束点(finishVoiceRecording)。
- useEffect(() => {
- if (!voiceIsListening) return undefined;
- const frame = requestAnimationFrame(() => {
- voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
- });
- return () => cancelAnimationFrame(frame);
- }, [composerInputContentHeight, composerInputVisibleHeight, draft, voiceIsListening]);
-
- useEffect(() => {
- if (voiceIsListening && draft.length > 0) return;
- setVoiceDraftCaretFrame({ left: 0, top: 0 });
- }, [draft.length, voiceIsListening]);
+ const writeVoiceDraft = useComposerVoiceDraftWriter(sessionId, setComposerDraft);
useEffect(() => {
const tracker = createMobileVoiceDictionaryLearningTracker({
@@ -3228,9 +2823,6 @@ export default function SessionScreen() {
}
}, [sessionId, sessionOperationLayout.messageHistoryMode]);
- useEffect(() => {
- if (!composerShowSendButton) sendButtonFrameRef.current = null;
- }, [composerShowSendButton]);
useEffect(() => {
const key = activeComposerDraftScopeKey;
@@ -3312,245 +2904,34 @@ export default function SessionScreen() {
applyComposerDocument(next, queueEditingRef.current ? { persist: false } : undefined);
}, [applyComposerDocument, composerDraftHydrated, quotes, sessionId]);
- // 点选意图的有效性跟随草稿前缀与会话:一旦草稿不再以点选的 `/name` 开头
- // (清空、整段替换、改名)或切换了会话,点选立即作废——覆盖「清稿/替换后手输
- // /learn 被旧点选绑架」与「跨会话残留」两类误让行(review P1/P2)。
- // 在 `/name` 后继续追加参数属于同一次点选的自然延续,保留。
- useEffect(() => {
- const pending = pendingSkillSelectionRef.current;
- if (!pending) return;
- if (pending.sid !== sessionId) {
- pendingSkillSelectionRef.current = null;
- return;
- }
- const head = /^\/([a-z][\w-]*)/i.exec(draft.trimStart());
- if (!head || head[1].toLowerCase() !== pending.name.toLowerCase()) {
- pendingSkillSelectionRef.current = null;
- }
- }, [draft, sessionId]);
-
useEffect(() => {
- if (!canUseRemoteSessionControls || composerTrigger.kind !== 'slash' || !currentSession || !deviceId) {
- slashLoadSeqRef.current += 1;
- setSlashCommands([]);
- setSlashPaletteLoading(false);
- setSlashPaletteError(null);
+ if (!currentAgentKind || !deviceId) {
+ capabilitiesLoadSeqRef.current += 1;
+ setCapabilities(null);
+ setCapabilitiesLoading(false);
+ setCapabilitiesError(null);
return;
}
- // palette 重新打开:之前的点选意图作废,以本次新选择为准。
- pendingSkillSelectionRef.current = null;
- const seq = ++slashLoadSeqRef.current;
- const agentKind = agentKindForSession(currentSession);
- const paletteCacheKey = buildComposerPaletteCacheKey(
- deviceId,
- agentKind,
- currentSession.workingDir ?? '',
- currentSession.id,
- );
- const cachedCommands = readSlashCommandCache(paletteCacheKey);
- if (cachedCommands) {
- // 任意年龄的缓存先画(重开面板不闪 spinner),后台静默刷新覆盖(规则 7)。
- // loading 必须同时清掉:上一轮无缓存请求可能把它置了 true 还没回来(如切会话 /
- // 切 workdir 时面板未关),不清的话 ComposerPaletteFrame 的 spinner 会盖住刚画的缓存行。
- setSlashCommands([...cachedCommands]);
- setSlashPaletteLoading(false);
+ const seq = ++capabilitiesLoadSeqRef.current;
+ let cancelled = false;
+ // 能力表按 (设备, agent) 基本不变:缓存命中先画(选择器立即可用、不闪「正在读取
+ // 远程运行能力」),后台静默刷新覆盖;miss 才走 loading 态。
+ const capabilitiesCacheKey = buildAgentCapabilitiesCacheKey(deviceId, currentAgentKind);
+ const generation = getAgentCapabilitiesGeneration(deviceId);
+ const unsubscribe = subscribeAgentCapabilities(deviceId, currentAgentKind, (next) => {
+ if (cancelled) return;
+ setCapabilities(next);
+ setCapabilitiesLoading(false);
+ setCapabilitiesError(null);
+ });
+ const cachedCapabilities = getCachedAgentCapabilities(capabilitiesCacheKey);
+ if (cachedCapabilities) {
+ setCapabilities(cachedCapabilities);
+ setCapabilitiesLoading(false);
} else {
- setSlashPaletteLoading(true);
+ setCapabilitiesLoading(true);
}
- setSlashPaletteError(null);
- void withTransientRemoteRetry(async () => {
- await openLink(deviceId);
- const [builtins, skills, desktop] = await Promise.all([
- maker.listAgentCommands(agentKind, { sessionId: currentSession.id }),
- maker.listAgentSkills(agentKind, {
- ...(currentSession.workingDir ? { workingDir: currentSession.workingDir } : {}),
- forceReload: false,
- sessionId: currentSession.id,
- }),
- // desktop 命令是 additive 展示(白名单分流不依赖此清单,清单只参与同名 skill
- // 让行仲裁,见 desktopSlashCommands):拉取失败(含老被控端无此通道)静默降级
- // 为不展示,不能拖垮 builtin/skill 两路。
- maker.listDesktopCommands().catch(
- () => ({ success: false } satisfies MobileDesktopCommandListResult),
- ),
- ]);
- return { builtins, skills, desktop };
- })
- .then(({ builtins, skills, desktop }) => {
- if (slashLoadSeqRef.current !== seq) return;
- const builtinCommands = builtins.success && Array.isArray(builtins.commands)
- ? builtins.commands
- : [];
- const skillCommands = skills.success && Array.isArray(skills.skills)
- ? skills.skills
- : [];
- const desktopCommands = desktop.success && Array.isArray(desktop.commands)
- ? filterMobileDesktopCommands(desktop.commands)
- : [];
- const merged = mergeSlashCommands(builtinCommands, skillCommands, desktopCommands);
- // 刷新失败(整体或部分)且缓存已画:保留缓存行、不置 error——
- // ComposerPaletteFrame 的 errorText 渲染在 children 之前,会把刚画的缓存
- // 整体盖住,可用面板被错误文案顶掉正是本 PR 要消除的体验(codex review R18)。
- const partialError = !builtins.success ? (builtins.error ?? 'slash command list failed')
- : !skills.success ? (skills.error ?? 'skill list failed')
- : null;
- if (!partialError) {
- setSlashCommands(merged);
- // desktop 命令(kind === 'desktop')不写入共享缓存:缓存被 new.tsx 等
- // 没有 desktop 命令分流逻辑的页面共读,写入会导致它们展示 /learn 但发送
- // 时走普通文本透传给 agent(静默失效)。
- writeSlashCommandCache(paletteCacheKey, merged.filter((c) => c.kind !== 'desktop'));
- setSlashPaletteError(null);
- } else if (!cachedCommands) {
- setSlashCommands(merged);
- setSlashPaletteError(partialError);
- }
- })
- .catch((err) => {
- if (slashLoadSeqRef.current !== seq) return;
- // 同上:缓存已画时保留旧列表且不置 error;无缓存可画才显示错误。
- if (!cachedCommands) {
- setSlashCommands([]);
- setSlashPaletteError(formatRemoteError(err));
- }
- })
- .finally(() => {
- if (slashLoadSeqRef.current === seq) setSlashPaletteLoading(false);
- });
- }, [canUseRemoteSessionControls, composerTrigger.kind, currentSession, deviceId, maker, openLink]);
-
- useEffect(() => {
- if (!canUseRemoteSessionControls || composerTrigger.kind !== 'at' || !currentSession?.workingDir || !deviceId) {
- atLoadSeqRef.current += 1;
- setAtResources([]);
- setAtPaletteLoading(false);
- setAtPaletteError(null);
- setAtResourcesTruncated(false);
- return;
- }
- // 旧行为是把 query 透传远端逐键扫描(每键一次 device-link 往返)。本地渲染层已有
- // filterAtResources 打分过滤,远端逐键只在结果被 cap 截断时才有增量价值,所以:
- // - 打开面板拉一次全量并写缓存;全量未截断 → 逐键纯本地过滤,零远端流量;
- // - 截断仓库 → 先画缓存,query 变化 debounce 后带 query 补搜(不进缓存);
- // - TTL 内重开面板直接命中缓存不重拉。
- const agentKind = agentKindForSession(currentSession);
- const paletteCacheKey = buildComposerPaletteCacheKey(deviceId, agentKind, currentSession.workingDir);
- const query = composerTrigger.query.trim();
- const cachedScan = readAtResourceScanCache(paletteCacheKey);
- if (cachedScan) {
- setAtResources([...cachedScan.result.items]);
- setAtResourcesTruncated(cachedScan.result.truncated);
- setAtPaletteError(null);
- if (cachedScan.fresh && !cachedScan.result.truncated) {
- // 先作废在途请求再早退:切换会话 / workingDir 时上一个 scan 可能仍在天上,
- // 不递增 seq 它就仍匹配当前代,回来会用旧目录的结果覆盖刚画的缓存。
- atLoadSeqRef.current += 1;
- setAtPaletteLoading(false);
- return;
- }
- }
- const remoteQuery = cachedScan?.result.truncated ? (query || undefined) : undefined;
- const seq = ++atLoadSeqRef.current;
- // 缓存已画时 loading 置 false(而非跳过):ComposerPaletteFrame 的 spinner 会整体
- // 顶掉 children,置 true 会把刚画的缓存闪成「读取中」,而上一轮无缓存请求残留的
- // true 不清掉同样会盖住缓存行(与 slash 的缓存命中清 loading 同口径)。
- setAtPaletteLoading(!cachedScan);
- setAtPaletteError(null);
- const timer = setTimeout(() => {
- void withTransientRemoteRetry(async () => {
- await openLink(deviceId);
- return maker.scanAtResources(agentKind, {
- workingDir: currentSession.workingDir!,
- cap: 2000,
- query: remoteQuery,
- });
- })
- .then((result) => {
- if (atLoadSeqRef.current !== seq) return;
- if (!result.success) {
- // 缓存已画时保留旧列表且不置 error——ComposerPaletteFrame 的 errorText
- // 渲染在 children 之前,会把刚画的缓存整体盖住(codex review R18);
- // 无缓存可画才清空并显示错误。
- if (!cachedScan) {
- setAtResources([]);
- setAtResourcesTruncated(false);
- setAtPaletteError(result.error ?? 'resource scan failed');
- }
- return;
- }
- const items = Array.isArray(result.items) ? result.items : [];
- const truncated = result.truncated === true;
- setAtResources(items);
- setAtResourcesTruncated(truncated);
- setAtPaletteError(null);
- // 只缓存全量扫描;带 query 的截断补搜是局部结果,不能当全量复用。
- if (!remoteQuery) {
- writeAtResourceScanCache(paletteCacheKey, { items, truncated });
- // 首拉即截断且用户已在输入:全量结果对该 query 的本地过滤不完整,而
- // effect 依赖不含缓存写入、不会自动重跑,这里立即链式补搜一次(不进缓存)。
- if (truncated && query) {
- void withTransientRemoteRetry(async () => {
- await openLink(deviceId);
- return maker.scanAtResources(agentKind, {
- workingDir: currentSession.workingDir!,
- cap: 2000,
- query,
- });
- })
- .then((followup) => {
- if (atLoadSeqRef.current !== seq) return;
- if (!followup.success) return; // 补搜失败保留全量结果,不降级
- setAtResources(Array.isArray(followup.items) ? followup.items : []);
- setAtResourcesTruncated(followup.truncated === true);
- })
- .catch(() => undefined);
- }
- }
- })
- .catch((err) => {
- if (atLoadSeqRef.current !== seq) return;
- // 同上:缓存已画时不清列表、不置 error;无缓存可画才显示错误。
- if (!cachedScan) {
- setAtResources([]);
- setAtResourcesTruncated(false);
- setAtPaletteError(formatRemoteError(err));
- }
- })
- .finally(() => {
- if (atLoadSeqRef.current === seq) setAtPaletteLoading(false);
- });
- }, query === '' ? 0 : AT_RESOURCE_QUERY_DEBOUNCE_MS);
- return () => clearTimeout(timer);
- }, [canUseRemoteSessionControls, composerTrigger, currentSession, deviceId, maker, openLink]);
-
- useEffect(() => {
- if (!currentAgentKind || !deviceId) {
- capabilitiesLoadSeqRef.current += 1;
- setCapabilities(null);
- setCapabilitiesLoading(false);
- setCapabilitiesError(null);
- return;
- }
- const seq = ++capabilitiesLoadSeqRef.current;
- let cancelled = false;
- // 能力表按 (设备, agent) 基本不变:缓存命中先画(选择器立即可用、不闪「正在读取
- // 远程运行能力」),后台静默刷新覆盖;miss 才走 loading 态。
- const capabilitiesCacheKey = buildAgentCapabilitiesCacheKey(deviceId, currentAgentKind);
- const generation = getAgentCapabilitiesGeneration(deviceId);
- const unsubscribe = subscribeAgentCapabilities(deviceId, currentAgentKind, (next) => {
- if (cancelled) return;
- setCapabilities(next);
- setCapabilitiesLoading(false);
- setCapabilitiesError(null);
- });
- const cachedCapabilities = getCachedAgentCapabilities(capabilitiesCacheKey);
- if (cachedCapabilities) {
- setCapabilities(cachedCapabilities);
- setCapabilitiesLoading(false);
- } else {
- setCapabilitiesLoading(true);
- }
- setCapabilitiesError(null);
+ setCapabilitiesError(null);
void withTransientRemoteRetry(async () => {
await openLink(deviceId);
return maker.getCapabilities(currentAgentKind);
@@ -5365,11 +4746,11 @@ export default function SessionScreen() {
voiceContext.createRefinerTarget(providerId, options),
warmRefiner: (input: { system: string; user: unknown; promptCacheKey: string }) =>
voiceContext.warmRefiner(input),
- initialDraft: draft,
- refinementContext: buildMobileVoiceSessionRefinementContext(draft, renderItems),
+ initialDraft: draftRef.current,
+ refinementContext: buildMobileVoiceSessionRefinementContext(draftRef.current, renderItems),
localVoiceInputHistory,
readCurrentDraft: () => draftRef.current,
- onDraftChanged: setComposerDraft,
+ onDraftChanged: writeVoiceDraft,
onStateChanged: setVoiceState,
onError: (message) => {
setVoiceState('error');
@@ -5465,7 +4846,7 @@ export default function SessionScreen() {
setVoiceError(formatRemoteError(err));
await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}
- }, [deviceId, draft, openLink, renderItems, t, voiceIsProcessing, voiceState]);
+ }, [deviceId, openLink, renderItems, t, voiceIsProcessing, voiceState, writeVoiceDraft]);
const cancelVoiceForAppBackground = useCallback(() => {
const controller = voiceControllerSessionRef.current;
@@ -5654,83 +5035,6 @@ export default function SessionScreen() {
});
}, [deviceId, startVoiceRecording, voiceIsProcessing, voiceState]);
- const renderComposerVoiceButton = (buttonStyle?: StyleProp<ViewStyle>) => (
- <RouteActionButton
- accessibilityLabel={voiceIsListening ? t('session.common.voiceStopRecording') : t('session.screen.voiceStartInput')}
- accessibilityHint={composerLayout.voice.disabledReason ?? composerSendUnavailableReason ?? undefined}
- active={composerLayout.voice.active}
- busy={voiceIsProcessing}
- disabled={composerLayout.voice.disabled || (!canUseComposer && !voiceIsBusy)}
- delayLongPress={320}
- hitSlop={COMPOSER_CONTROL_HIT_SLOP}
- onPressIn={handleVoiceButtonPressIn}
- onLongPress={() => {
- voiceLongPressActiveRef.current = true;
- voiceSuppressNextPressRef.current = true;
- measureSendButtonTarget();
- // 录音已在 pressIn 起了;这里只兜 pressIn 守卫路径没起成的边缘
- // (startVoiceRecording 自带重入守卫,重复调用无害)。
- if (!voiceRecordingActiveRef.current) void startVoiceRecording();
- }}
- onPress={() => {
- if (voiceSuppressNextPressRef.current) {
- voiceSuppressNextPressRef.current = false;
- return;
- }
- if (voiceStartedOnPressInRef.current) {
- // 本次按下已在 pressIn 起录:这次松手属于同一手势,不再当作
- // 「再点一下停止」;下一次完整点击才会 toggle 停止。
- voiceStartedOnPressInRef.current = false;
- return;
- }
- toggleVoiceRecording();
- }}
- onPressOut={(event) => {
- if (!voiceLongPressActiveRef.current) return;
- // 长按路径在此收尾,本次按下的生命周期结束;标记同步清掉,
- // 手势取消(onTouchCancel)不再重复处理。
- voiceStartedOnPressInRef.current = false;
- const shouldSend = updateVoiceReleaseToSendTarget(event);
- voiceLongPressActiveRef.current = false;
- voiceSuppressNextPressRef.current = true;
- setVoiceReleaseToSendActive(false);
- if (!voiceRecordingActiveRef.current) {
- voiceStopAfterStartRef.current = true;
- return;
- }
- void finishVoiceRecording({ sendAfterTranscribe: shouldSend });
- }}
- onResponderMove={updateVoiceReleaseToSendTarget}
- onTouchCancel={() => {
- // 手势被系统/滚动打断(responder termination):撤销这次按下误触发的
- // 录音——用户本意是滚动列表,不能留下一个还在采集的麦克风(review P1)。
- // 正常松手(含拖出按钮后松开)不走这里,对齐桌面「pointercancel 才撤销」。
- if (!voiceStartedOnPressInRef.current) return;
- voiceStartedOnPressInRef.current = false;
- cancelVoiceForGestureTermination();
- }}
- style={[
- styles.composerInlineToolButton,
- buttonStyle,
- // 胶囊底色跟随计时内容(含 pressIn 乐观 pending 期),不只 listening——
- // 否则按下瞬间胶囊已展开、底色却要等 ASR 连上才变,闪一次半成品态。
- voiceRecordingTimer.label !== null && styles.composerToolButtonPrimary,
- voiceRecordingTimer.label !== null && { width: voiceRecordingTimer.pillWidth },
- ]}
- testID="session.voiceButton"
- >
- {voiceIsProcessing ? (
- <ActivityIndicator color={colors.textSecondary} size="small" />
- ) : voiceRecordingTimer.label !== null ? (
- // 录音中:胶囊展开为脉冲红点 + 计时(对齐桌面 activeRecording 形态),
- // 点胶囊任意位置停止录音;右缘锚定不动,只向左生长。
- <VoiceRecordingPillContent label={voiceRecordingTimer.label} testID="session.voiceRecordingPill" />
- ) : (
- <Mic color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- )}
- </RouteActionButton>
- );
-
const removeRemoteFileAttachment = useCallback((id: string) => {
// 已上传中转区的对象移除时 best-effort 回收,避免未发送附件在 OSS 留孤儿(codex review #504)。
const removed = attachments.find((item) => item.id === id);
@@ -5788,6 +5092,15 @@ export default function SessionScreen() {
));
}, []);
+ const handleComposerDragActiveChange = useCallback((active: boolean) => {
+ composerResizeDraggingRef.current = active;
+ if (active) return;
+ const pendingHeight = pendingBottomOverlayHeightRef.current;
+ if (pendingHeight === null) return;
+ pendingBottomOverlayHeightRef.current = null;
+ setBottomOverlayContentHeight((height) => Math.abs(height - pendingHeight) > 1 ? pendingHeight : height);
+ }, []);
+
// 顶部 chrome(半透明工具栏)是绝对定位浮层:量出实高喂给消息列表做顶部让位
// (滚到历史最顶端时第一条消息不被工具栏盖住),与 bottomOverlayHeight 同款模式。
const handleTopOverlayLayout = useCallback((event: LayoutChangeEvent) => {
@@ -5797,16 +5110,6 @@ export default function SessionScreen() {
));
}, []);
- useEffect(() => {
- if (composerResize.dragging) return;
- const pendingHeight = pendingBottomOverlayHeightRef.current;
- if (pendingHeight === null) return;
- pendingBottomOverlayHeightRef.current = null;
- setBottomOverlayContentHeight((currentHeight) => (
- Math.abs(currentHeight - pendingHeight) > 1 ? pendingHeight : currentHeight
- ));
- }, [composerResize.dragging]);
-
// ————— 本地待发队列(outbox):附件上传中消息先上屏 —————
// 状态机纯函数在 sessionOutbox.ts;这里只做 React 接线与 enqueue 派发。
// 所有更新经此单点:ref(同步真源)与 state(渲染)一起写。
@@ -6392,6 +5695,7 @@ export default function SessionScreen() {
await finishVoiceRecording({ sendAfterTranscribe: true });
return;
}
+ const commandsAtSend = slashCommandsRef.current;
const documentAtSend = options.documentOverride
?? (options.draftOverride === undefined
? composerDocumentRef.current
@@ -6443,7 +5747,7 @@ export default function SessionScreen() {
const pendingSkillAtSend = pendingSkillSelectionRef.current;
const parsedDesktopCommandAtSend = willHaveAttachments
? null
- : parseMobileDesktopCommand(body, slashCommands);
+ : parseMobileDesktopCommand(body, commandsAtSend);
const earlyDesktopCommand =
parsedDesktopCommandAtSend
&& pendingSkillAtSend?.sid === sessionId
@@ -6892,14 +6196,14 @@ export default function SessionScreen() {
data = buildMobileSystemCardData(localSystemCommand, {
contextUsage: usage,
projection: inputProjection,
- remoteCommands: slashCommands,
+ remoteCommands: commandsAtSend,
session: sessionAtSend,
});
} catch (err) {
data = buildMobileSystemCardData(localSystemCommand, {
contextError: formatRemoteError(err),
projection: inputProjection,
- remoteCommands: slashCommands,
+ remoteCommands: commandsAtSend,
session: sessionAtSend,
});
} finally {
@@ -6908,7 +6212,7 @@ export default function SessionScreen() {
} else {
data = buildMobileSystemCardData(localSystemCommand, {
projection: inputProjection,
- remoteCommands: slashCommands,
+ remoteCommands: commandsAtSend,
session: sessionAtSend,
});
}
@@ -7145,6 +6449,176 @@ export default function SessionScreen() {
.finally(() => setStopPending(false));
};
+ const renderComposerControls = ({ composerLayout, composerSendUnavailableReason, composerStopDisabledReason, composerStopDisabled, composerShowInlineStop, composerSendSlotIsStop, composerShowSendButton, composerSendDisabled, voiceIsListening, voiceIsProcessing, voiceIsBusy, voiceRecordingTimer, composerVoicePlacement }: SessionComposerControlState): SessionComposerControls => {
+ composerSendTargetEnabledRef.current = composerShowSendButton && !composerLayout.send.disabled;
+ if (!composerShowSendButton) sendButtonFrameRef.current = null;
+ // 聚焦卡片形态的底部工具排:[+][模型] …… [语音][停止/发送]。
+ // + 号打开 Context 面板(附件 / 计划模式 / 目标模式收在面板内);权限模式入口收进会话设置。
+ // 权限模式图标钮(2026-07-29 用户裁决,对齐 Codex,与新建页同位同款):
+ // 只显示档位图标,不带文字;危险档(auto / bypass)只染图标色。
+ const renderSessionPermissionButton = () => {
+ const presentation = permissionPresentation(displayPermissionMode, displayPermissionLabel);
+ const accent = presentation.accent !== 'neutral'
+ ? permissionAccentColor(presentation.accent, colors)
+ : null;
+ return (
+ <RouteActionButton
+ accessibilityLabel={t('models.picker.permissionModeAccessibility', { mode: presentation.label })}
+ active={permissionSheetOpen}
+ disabled={controlBusy || !canUseRemoteSessionControls}
+ hitSlop={COMPOSER_CONTROL_HIT_SLOP}
+ onPress={() => {
+ setModelSheetOpen(false);
+ setPermissionSheetSnap('half');
+ setPermissionSheetOpen(true);
+ }}
+ style={[
+ styles.composerInlineToolButton,
+ permissionSheetOpen && styles.composerToolButtonActive,
+ ]}
+ testID="session.permissionIndicator"
+ >
+ <presentation.Icon
+ color={accent ?? colors.textSecondary}
+ size={iconSize.sm}
+ strokeWidth={iconStroke.regular}
+ />
+ </RouteActionButton>
+ );
+ };
+
+ // 工具条布局:左 = [+][权限][计划 chip][模型];右 = [停止][语音][发送]。
+ // 模型放左侧组,不随发送/停止出现而横向跳动。
+ const renderComposerToolbar = () => (
+ <>
+ <ComposerToolbarLeftGroup testID="session.composerToolbarLeft">
+ {renderComposerAttachmentButton()}
+ {renderSessionPermissionButton()}
+ {planModeOn ? (
+ <PlanModeChip
+ disabled={controlBusy || !canUseRemoteSessionControls}
+ onExit={() => togglePlanMode(false)}
+ testID="session.planModeChip"
+ />
+ ) : null}
+ {composerRuntimeSummary ? (
+ <ComposerRuntimePill
+ disabled={controlBusy || !canUseRemoteSessionControls}
+ fastOn={composerPillFastOn}
+ label={composerRuntimeLabel}
+ leading={agentSwitchIntent ? (
+ <MobileAgentMark
+ agentKind={agentSwitchIntent.targetAgentKind}
+ color={colors.textSecondary}
+ size={iconSize.sm}
+ />
+ ) : composerPillSourceId ? (
+ // 正常态显示真正生效来源;断开态显示 DB 中的真实来源并使用状态色,
+ // 不静默换成 activeSourceId 的默认回退 Logo。
+ <MobileModelIconMark
+ color={composerSelectedSourceDisconnected ? colors.statusError : undefined}
+ icon={currentSession && composerPillSourceProvider
+ ? getModel(composerPillSourceProvider, currentSession.model, sessionAgentKind)?.icon
+ : undefined}
+ name={composerPillSourceProvider?.name ?? composerPillSourceId}
+ providerId={composerPillSourceId}
+ routing={composerPillSourceProvider?.routing}
+ logoKind={composerPillSourceProvider?.logoKind}
+ />
+ ) : null}
+ onPress={toggleComposerModelPicker}
+ testID="session.composerModelButton"
+ />
+ ) : null}
+ </ComposerToolbarLeftGroup>
+ <ComposerToolbarSpacer />
+ {/* 工具排右段顺序:[停止任务][语音占位][发送槽]。停止任务在语音左边(对齐桌面),
+ 语音占位宽度随录音胶囊(红点+计时)展开,把停止任务推开——语音右缘与发送槽
+ 的邻接关系全程不变。模型在 spacer 左侧,不随右段显隐横向跳动。 */}
+ {renderComposerInlineStop()}
+ {composerVoicePlacement?.inline || composerVoicePlacement?.floating
+ ? <ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />
+ : null}
+ {renderComposerSendSlot()}
+ </>
+ );
+ const renderComposerVoiceButton = (buttonStyle?: StyleProp<ViewStyle>) => (
+ <RouteActionButton
+ accessibilityLabel={voiceIsListening ? t('session.common.voiceStopRecording') : t('session.screen.voiceStartInput')}
+ accessibilityHint={composerLayout.voice.disabledReason ?? composerSendUnavailableReason ?? undefined}
+ active={composerLayout.voice.active}
+ busy={voiceIsProcessing}
+ disabled={composerLayout.voice.disabled || (!canUseComposer && !voiceIsBusy)}
+ delayLongPress={320}
+ hitSlop={COMPOSER_CONTROL_HIT_SLOP}
+ onPressIn={handleVoiceButtonPressIn}
+ onLongPress={() => {
+ voiceLongPressActiveRef.current = true;
+ voiceSuppressNextPressRef.current = true;
+ measureSendButtonTarget();
+ // 录音已在 pressIn 起了;这里只兜 pressIn 守卫路径没起成的边缘
+ // (startVoiceRecording 自带重入守卫,重复调用无害)。
+ if (!voiceRecordingActiveRef.current) void startVoiceRecording();
+ }}
+ onPress={() => {
+ if (voiceSuppressNextPressRef.current) {
+ voiceSuppressNextPressRef.current = false;
+ return;
+ }
+ if (voiceStartedOnPressInRef.current) {
+ // 本次按下已在 pressIn 起录:这次松手属于同一手势,不再当作
+ // 「再点一下停止」;下一次完整点击才会 toggle 停止。
+ voiceStartedOnPressInRef.current = false;
+ return;
+ }
+ toggleVoiceRecording();
+ }}
+ onPressOut={(event) => {
+ if (!voiceLongPressActiveRef.current) return;
+ // 长按路径在此收尾,本次按下的生命周期结束;标记同步清掉,
+ // 手势取消(onTouchCancel)不再重复处理。
+ voiceStartedOnPressInRef.current = false;
+ const shouldSend = updateVoiceReleaseToSendTarget(event);
+ voiceLongPressActiveRef.current = false;
+ voiceSuppressNextPressRef.current = true;
+ setVoiceReleaseToSendActive(false);
+ if (!voiceRecordingActiveRef.current) {
+ voiceStopAfterStartRef.current = true;
+ return;
+ }
+ void finishVoiceRecording({ sendAfterTranscribe: shouldSend });
+ }}
+ onResponderMove={updateVoiceReleaseToSendTarget}
+ onTouchCancel={() => {
+ // 手势被系统/滚动打断(responder termination):撤销这次按下误触发的
+ // 录音——用户本意是滚动列表,不能留下一个还在采集的麦克风(review P1)。
+ // 正常松手(含拖出按钮后松开)不走这里,对齐桌面「pointercancel 才撤销」。
+ if (!voiceStartedOnPressInRef.current) return;
+ voiceStartedOnPressInRef.current = false;
+ cancelVoiceForGestureTermination();
+ }}
+ style={[
+ styles.composerInlineToolButton,
+ buttonStyle,
+ // 胶囊底色跟随计时内容(含 pressIn 乐观 pending 期),不只 listening——
+ // 否则按下瞬间胶囊已展开、底色却要等 ASR 连上才变,闪一次半成品态。
+ voiceRecordingTimer.label !== null && styles.composerToolButtonPrimary,
+ voiceRecordingTimer.label !== null && { width: voiceRecordingTimer.pillWidth },
+ ]}
+ testID="session.voiceButton"
+ >
+ {voiceIsProcessing ? (
+ <ActivityIndicator color={colors.textSecondary} size="small" />
+ ) : voiceRecordingTimer.label !== null ? (
+ // 录音中:胶囊展开为脉冲红点 + 计时(对齐桌面 activeRecording 形态),
+ // 点胶囊任意位置停止录音;右缘锚定不动,只向左生长。
+ <VoiceRecordingPillContent label={voiceRecordingTimer.label} testID="session.voiceRecordingPill" />
+ ) : (
+ <Mic color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ )}
+ </RouteActionButton>
+ );
+
const renderComposerAttachmentButton = () => (
<RouteActionButton
accessibilityLabel={composerLayout.attachment.active ? composerLayout.attachment.label : t('session.common.openContextPanel')}
@@ -7318,6 +6792,16 @@ export default function SessionScreen() {
</>
);
+
+ return {
+ toolbar: renderComposerToolbar(),
+ leading: renderComposerCompactLeading(),
+ trailing: renderComposerTrailingActions(),
+ voiceButton: renderComposerVoiceButton,
+ attachmentTray: renderComposerAttachmentTray(),
+ };
+ };
+
const resumeQueue = () => {
void runQueueAction(() => maker.input.resume(sessionId));
};
@@ -9415,7 +8899,7 @@ export default function SessionScreen() {
error={goalError}
goal={goalStatus}
initial={goalRestoreForSession}
- initialObjective={goalRestoreForSession ? undefined : (draft.trim() || undefined)}
+ initialObjective={goalRestoreForSession ? undefined : (draftRef.current.trim() || undefined)}
onClearGoal={handleClearGoal}
onPauseGoal={handlePauseGoal}
onResumeGoal={handleResumeGoal}
@@ -9648,54 +9132,22 @@ export default function SessionScreen() {
]}
testID="session.bottomContent"
>
- {!shareSelectionActive && canUseComposer && composerTrigger.kind === 'slash' ? (
- <ComposerPaletteFrame
- emptyText={t('session.common.noMatchingCommands')}
- errorText={slashPaletteError}
- loading={slashPaletteLoading}
- maxHeight={nativeShellLayout.paletteMaxHeight}
- testID="session.slashPalette"
- >
- {visibleSlashCommands.map((command) => (
- <ComposerPaletteRow
- accessibilityLabel={t('session.common.insertCommand', { name: command.name })}
- key={`${command.kind}:${command.name}`}
- onPress={() => selectSlashCommand(command)}
- primary={`/${command.name}`}
- secondary={
- command.kind === 'agent-skill'
- ? command.source
- : command.kind === 'desktop'
- ? 'desktop'
- : 'agent-cmd'
- }
- testID="session.slashCommandRow"
- />
- ))}
- </ComposerPaletteFrame>
- ) : null}
-
- {!shareSelectionActive && canUseComposer && composerTrigger.kind === 'at' ? (
- <ComposerPaletteFrame
- emptyText={atResourcesTruncated ? t('session.common.keepTypingToNarrow') : t('session.common.noMatchingResources')}
- errorText={atPaletteError}
- loading={atPaletteLoading}
- maxHeight={nativeShellLayout.paletteMaxHeight}
- testID="session.atPalette"
- >
- {visibleAtResources.map((item) => (
- <ComposerPaletteRow
- accessibilityLabel={t('session.common.insertResource', { name: item.name })}
- key={`${item.type}:${item.relPath}`}
- onPress={() => selectAtResource(item)}
- primary={item.type === 'dir' ? `${item.name}/` : item.name}
- secondary={item.type === 'agent' ? 'Agent' : item.relPath}
- testID="session.atResourceRow"
- />
- ))}
- </ComposerPaletteFrame>
- ) : null}
-
+ <SessionComposerPalette
+ key={activeComposerDraftScopeKey}
+ source={composerDraftSource}
+ commandsRef={slashCommandsRef}
+ pendingSkillSelectionRef={pendingSkillSelectionRef}
+ canUseComposer={canUseComposer}
+ canUseRemoteSessionControls={canUseRemoteSessionControls}
+ currentSession={currentSession}
+ deviceId={deviceId}
+ maker={maker}
+ openLink={openLink}
+ shareSelectionActive={shareSelectionActive}
+ nativeShellLayout={nativeShellLayout}
+ selectSlashCommand={selectSlashCommand}
+ selectAtResource={selectAtResource}
+ />
{/*
手机端终结不了的请求(plugin_setup 等)只贴在输入框上方:能看清电脑端
在等什么、能取消,但不吃掉 composer —— 否则用户既处理不了这张卡又发不
@@ -9864,144 +9316,43 @@ export default function SessionScreen() {
<Text style={styles.queueEditBarText}>{composerAgentAuthHint}</Text>
</View>
) : null}
- <View
- style={[
- styles.composer,
- {
- // manual 拖高时容器上限放开到拖拽上限(bounds 已保证不顶穿屏幕),
- // 否则输入区超过 auto 上限后容器从底部裁剪掉发送按钮 trailing 行。
- maxHeight: composerResize.dragging || composerResize.mode === 'manual'
- ? composerResize.maxFrameHeight + composerChromeHeight
- : nativeShellLayout.composerMaxHeight,
- paddingHorizontal: composerTouchLayout.composerPaddingHorizontal,
- },
- ]}
- testID="session.composer"
- >
- {voiceStatusVisible ? (
- <View style={styles.voiceStatusRow}>
- <Text style={styles.voiceStatusText} testID="session.voiceStatus">
- {voiceError}
- </Text>
- {canOpenVoiceSettings ? (
- <RouteActionButton
- accessibilityLabel={t('session.common.openMicPermission')}
- hitSlop={COMPOSER_CONTROL_HIT_SLOP}
- onPress={openVoiceSettings}
- style={styles.voiceCancelButton}
- testID="session.voiceSettingsButton"
- >
- <Settings color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- </RouteActionButton>
- ) : null}
- </View>
- ) : null}
- <ScrollView
- ref={composerScrollViewRef}
- contentContainerStyle={styles.composerScrollContent}
- keyboardShouldPersistTaps="handled"
- scrollEnabled={composerScrollEnabled}
- showsVerticalScrollIndicator={composerScrollEnabled}
- style={styles.composerScroll}
- testID="session.composerScroll"
- >
-
- {attachmentError ? (
- <Text style={styles.attachmentErrorText} testID="session.attachmentStatus">
- {attachmentError}
- </Text>
- ) : null}
-
- <View style={[
- styles.composerSurface,
- compactComposer && !composerCardActive && styles.composerSurfaceCompact,
- ]}>
- <MobileComposerInputRow
- key={sessionId}
- accessibilityLabel={t('session.screen.composerPlaceholder')}
- accessibilityHint={composerLayout.input.disabledReason ?? undefined}
- accessoryAbove={attachments.length > 0 || pendingUploads.length > 0 || pastePlaceholderCount > 0 ? renderComposerAttachmentTray() : null}
- autoFocus={visualFocusComposer}
- cardActive={composerCardActive}
- caretHidden={voiceIsListening}
- compact={compactComposer && !composerCardActive}
- editable={!composerLayout.input.disabled}
- floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}
- cursorColor={colors.inputCaret}
- inputFrameHeight={composerResize.frameHeight}
- // 听写期间把输入区撑到 44pt 触控目标:命中层盖在 inputFrame 上,
- // hitSlop 越不过父边界(见常量注释)。
- inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}
- inputElement={(
- <ComposerRichInput
- ref={composerInputRef}
- accessibilityHint={composerLayout.input.disabledReason ?? undefined}
- accessibilityLabel={t('session.screen.composerPlaceholder')}
- document={composerDocument}
- editable={!composerLayout.input.disabled}
- height={composerInputVisibleHeight}
- hidden={voiceIsListening}
- maxHeight={composerResize.inputMaxHeight}
- opticalPadding={composerCardActive}
- onBlur={() => {
- setComposerFocused(false);
- setComposerVoiceHoldArmed(false);
- }}
- onChangeDocument={applyRichComposerChange}
- onFocus={() => setComposerFocused(true)}
- onHeightChange={handleComposerRichInputHeight}
- onPasteImages={(uris) => void addPastedImageAttachments(uris)}
- onPasteImagesLoading={beginPastePlaceholders}
- onPasteImagesLoadFailed={failPastePlaceholders}
- placeholder={voiceIsListening ? '' : composerLayout.input.placeholder}
- resolveSessionLinkLabel={resolvePastedSessionLinkLabel}
- testID="session.composerRichInput"
- theme={{
- background: colors.chatCodeSurface,
- border: colors.border,
- chip: colors.surfaceChip,
- focus: colors.inputCaret,
- placeholder: colors.textTertiary,
- text: colors.textPrimary,
- textSecondary: colors.textSecondary,
- }}
- />
- )}
- inputOverlay={renderComposerInputOverlay()}
- inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}
- inputTestID="session.composerInput"
- leading={renderComposerCompactLeading()}
- maxHeight={composerResize.inputMaxHeight}
- multilineShape={!composerCardActive && composerInputIsMultiline}
- onBlur={() => {
- setComposerFocused(false);
- // 失焦收起与「点别处收键盘」同语义:语音结束 hold 一并解除。
- setComposerVoiceHoldArmed(false);
- }}
- onChangeText={setComposerDraft}
- onContentSizeChange={handleComposerInputContentSizeChange}
- onFocus={() => {
- setComposerFocused(true);
- handleComposerInputPressIn();
- }}
- onPasteImages={(uris) => void addPastedImageAttachments(uris)}
- onPasteImagesLoading={beginPastePlaceholders}
- onPasteImagesLoadFailed={failPastePlaceholders}
- onPressIn={handleComposerInputPressIn}
- placeholder={voiceIsListening ? '' : composerLayout.input.placeholder}
- placeholderTextColor={colors.textTertiary}
- resizeHandle={composerCardActive ? renderComposerResizeHandle() : null}
- scrollEnabled={composerInputScrollEnabled}
- selectionColor={colors.inputCaret}
- testID="session.composerInputRow"
- toolbar={renderComposerToolbar()}
- trailing={composerCardActive ? null : renderComposerTrailingActions()}
- value={draft}
- voicePlacement={composerVoicePlacement}
- />
- </View>
- </ScrollView>
- </View>
+ <SessionComposerInput
+ key={activeComposerDraftScopeKey}
+ source={composerDraftSource}
+ sessionId={sessionId}
+ composerInputRef={composerInputRef}
+ canUseComposer={canUseComposer}
+ canStopComposer={canStopComposer}
+ canUseRemoteSessionControls={canUseRemoteSessionControls}
+ remoteUnavailableReason={remoteUnavailableReason}
+ voiceState={voiceState}
+ voiceStartPending={voiceStartPending}
+ voiceError={voiceError}
+ composerVoiceHoldArmed={composerVoiceHoldArmed}
+ setComposerVoiceHoldArmed={setComposerVoiceHoldArmed}
+ modelSheetOpen={modelSheetOpen}
+ permissionSheetOpen={permissionSheetOpen}
+ sending={sending}
+ queueBusy={queueBusy}
+ nativeShellLayout={nativeShellLayout}
+ composerTouchLayout={composerTouchLayout}
+ keyboardState={keyboardState}
+ attachmentError={attachmentError}
+ visualFocusComposer={visualFocusComposer}
+ applyRichComposerChange={applyRichComposerChange}
+ setComposerDraft={setComposerDraft}
+ handleComposerInputPressIn={handleComposerInputPressIn}
+ beginPastePlaceholders={beginPastePlaceholders}
+ failPastePlaceholders={failPastePlaceholders}
+ resolvePastedSessionLinkLabel={resolvePastedSessionLinkLabel}
+ openVoiceSettings={openVoiceSettings}
+ composerSendUnavailableReason={canUseComposer ? null : composerDisabledReason}
+ attachmentCount={attachments.length}
+ pendingUploadCount={pendingUploads.length}
+ onPasteImages={(uris) => void addPastedImageAttachments(uris)}
+ onDragActiveChange={handleComposerDragActiveChange}
+ renderControls={renderComposerControls}
+ />
</>
)}
{shareSelectionActive ? (
@@ -10309,6 +9660,834 @@ function compactSessionHeaderNotice({
return null;
}
+interface SessionComposerPaletteProps {
+ source: ComposerDraftSource;
+ commandsRef: RefObject<MobileSlashCommand[]>;
+ pendingSkillSelectionRef: RefObject<{ name: string; sid: string } | null>;
+ canUseComposer: boolean;
+ canUseRemoteSessionControls: boolean;
+ currentSession: RemoteSession | null | undefined;
+ deviceId: string;
+ maker: ReturnType<typeof useMobileMakerTransport>;
+ openLink: ReturnType<typeof useDeviceLink>['openLink'];
+ shareSelectionActive: boolean;
+ nativeShellLayout: ReturnType<typeof buildSessionNativeShellLayout>;
+ selectSlashCommand: (command: MobileSlashCommand) => void;
+ selectAtResource: (item: MobileAtResourceItem) => void;
+}
+
+/** Candidate filtering and remote query effects subscribe beside the editor. */
+function SessionComposerPalette({
+ source, commandsRef, pendingSkillSelectionRef, canUseComposer, canUseRemoteSessionControls,
+ currentSession, deviceId, maker, openLink, shareSelectionActive, nativeShellLayout,
+ selectSlashCommand, selectAtResource,
+}: SessionComposerPaletteProps) {
+ const { draft } = useSyncExternalStore(source.subscribe, source.getSnapshot);
+ const { t } = useTranslation();
+ const [slashCommands, setLocalSlashCommands] = useState<MobileSlashCommand[]>([]);
+ const [slashPaletteLoading, setSlashPaletteLoading] = useState(false);
+ const [slashPaletteError, setSlashPaletteError] = useState<string | null>(null);
+ const [atResources, setAtResources] = useState<MobileAtResourceItem[]>([]);
+ const [atPaletteLoading, setAtPaletteLoading] = useState(false);
+ const [atPaletteError, setAtPaletteError] = useState<string | null>(null);
+ const [atResourcesTruncated, setAtResourcesTruncated] = useState(false);
+
+ const slashLoadSeqRef = useRef(0);
+ const atLoadSeqRef = useRef(0);
+ const setSlashCommands = useCallback((commands: MobileSlashCommand[]) => {
+ commandsRef.current = commands;
+ setLocalSlashCommands(commands);
+ }, [commandsRef]);
+ useEffect(() => () => {
+ slashLoadSeqRef.current += 1;
+ atLoadSeqRef.current += 1;
+ }, []);
+ const composerTrigger = useMemo(() => detectComposerTrigger(draft), [draft]);
+ const visibleSlashCommands = useMemo(
+ () => canUseComposer && composerTrigger.kind === 'slash'
+ ? filterSlashCommands(mergeMobileLocalSlashCommands(slashCommands), composerTrigger.query, 5)
+ : [],
+ [canUseComposer, composerTrigger, slashCommands],
+ );
+ const visibleAtResources = useMemo(
+ () => canUseComposer && composerTrigger.kind === 'at'
+ ? filterAtResources(atResources, composerTrigger.query, 5)
+ : [],
+ [atResources, canUseComposer, composerTrigger],
+ );
+
+ useEffect(() => {
+ if (!canUseRemoteSessionControls || composerTrigger.kind !== 'slash' || !currentSession || !deviceId) {
+ slashLoadSeqRef.current += 1;
+ setSlashCommands([]);
+ setSlashPaletteLoading(false);
+ setSlashPaletteError(null);
+ return;
+ }
+ // palette 重新打开:之前的点选意图作废,以本次新选择为准。
+ pendingSkillSelectionRef.current = null;
+ const seq = ++slashLoadSeqRef.current;
+ const agentKind = agentKindForSession(currentSession);
+ const paletteCacheKey = buildComposerPaletteCacheKey(
+ deviceId,
+ agentKind,
+ currentSession.workingDir ?? '',
+ currentSession.id,
+ );
+ const cachedCommands = readSlashCommandCache(paletteCacheKey);
+ if (cachedCommands) {
+ // 任意年龄的缓存先画(重开面板不闪 spinner),后台静默刷新覆盖(规则 7)。
+ // loading 必须同时清掉:上一轮无缓存请求可能把它置了 true 还没回来(如切会话 /
+ // 切 workdir 时面板未关),不清的话 ComposerPaletteFrame 的 spinner 会盖住刚画的缓存行。
+ setSlashCommands([...cachedCommands]);
+ setSlashPaletteLoading(false);
+ } else {
+ setSlashPaletteLoading(true);
+ }
+ setSlashPaletteError(null);
+ void withTransientRemoteRetry(async () => {
+ await openLink(deviceId);
+ const [builtins, skills, desktop] = await Promise.all([
+ maker.listAgentCommands(agentKind, { sessionId: currentSession.id }),
+ maker.listAgentSkills(agentKind, {
+ ...(currentSession.workingDir ? { workingDir: currentSession.workingDir } : {}),
+ forceReload: false,
+ sessionId: currentSession.id,
+ }),
+ // desktop 命令是 additive 展示(白名单分流不依赖此清单,清单只参与同名 skill
+ // 让行仲裁,见 desktopSlashCommands):拉取失败(含老被控端无此通道)静默降级
+ // 为不展示,不能拖垮 builtin/skill 两路。
+ maker.listDesktopCommands().catch(
+ () => ({ success: false } satisfies MobileDesktopCommandListResult),
+ ),
+ ]);
+ return { builtins, skills, desktop };
+ })
+ .then(({ builtins, skills, desktop }) => {
+ if (slashLoadSeqRef.current !== seq) return;
+ const builtinCommands = builtins.success && Array.isArray(builtins.commands)
+ ? builtins.commands
+ : [];
+ const skillCommands = skills.success && Array.isArray(skills.skills)
+ ? skills.skills
+ : [];
+ const desktopCommands = desktop.success && Array.isArray(desktop.commands)
+ ? filterMobileDesktopCommands(desktop.commands)
+ : [];
+ const merged = mergeSlashCommands(builtinCommands, skillCommands, desktopCommands);
+ // 刷新失败(整体或部分)且缓存已画:保留缓存行、不置 error——
+ // ComposerPaletteFrame 的 errorText 渲染在 children 之前,会把刚画的缓存
+ // 整体盖住,可用面板被错误文案顶掉正是本 PR 要消除的体验(codex review R18)。
+ const partialError = !builtins.success ? (builtins.error ?? 'slash command list failed')
+ : !skills.success ? (skills.error ?? 'skill list failed')
+ : null;
+ if (!partialError) {
+ setSlashCommands(merged);
+ // desktop 命令(kind === 'desktop')不写入共享缓存:缓存被 new.tsx 等
+ // 没有 desktop 命令分流逻辑的页面共读,写入会导致它们展示 /learn 但发送
+ // 时走普通文本透传给 agent(静默失效)。
+ writeSlashCommandCache(paletteCacheKey, merged.filter((c) => c.kind !== 'desktop'));
+ setSlashPaletteError(null);
+ } else if (!cachedCommands) {
+ setSlashCommands(merged);
+ setSlashPaletteError(partialError);
+ }
+ })
+ .catch((err) => {
+ if (slashLoadSeqRef.current !== seq) return;
+ // 同上:缓存已画时保留旧列表且不置 error;无缓存可画才显示错误。
+ if (!cachedCommands) {
+ setSlashCommands([]);
+ setSlashPaletteError(formatRemoteError(err));
+ }
+ })
+ .finally(() => {
+ if (slashLoadSeqRef.current === seq) setSlashPaletteLoading(false);
+ });
+ return () => { slashLoadSeqRef.current += 1; };
+ }, [canUseRemoteSessionControls, composerTrigger.kind, currentSession, deviceId, maker, openLink, setSlashCommands, pendingSkillSelectionRef]);
+
+ useEffect(() => {
+ if (!canUseRemoteSessionControls || composerTrigger.kind !== 'at' || !currentSession?.workingDir || !deviceId) {
+ atLoadSeqRef.current += 1;
+ setAtResources([]);
+ setAtPaletteLoading(false);
+ setAtPaletteError(null);
+ setAtResourcesTruncated(false);
+ return;
+ }
+ // 旧行为是把 query 透传远端逐键扫描(每键一次 device-link 往返)。本地渲染层已有
+ // filterAtResources 打分过滤,远端逐键只在结果被 cap 截断时才有增量价值,所以:
+ // - 打开面板拉一次全量并写缓存;全量未截断 → 逐键纯本地过滤,零远端流量;
+ // - 截断仓库 → 先画缓存,query 变化 debounce 后带 query 补搜(不进缓存);
+ // - TTL 内重开面板直接命中缓存不重拉。
+ const agentKind = agentKindForSession(currentSession);
+ const paletteCacheKey = buildComposerPaletteCacheKey(deviceId, agentKind, currentSession.workingDir);
+ const query = composerTrigger.query.trim();
+ const cachedScan = readAtResourceScanCache(paletteCacheKey);
+ if (cachedScan) {
+ setAtResources([...cachedScan.result.items]);
+ setAtResourcesTruncated(cachedScan.result.truncated);
+ setAtPaletteError(null);
+ if (cachedScan.fresh && !cachedScan.result.truncated) {
+ // 先作废在途请求再早退:切换会话 / workingDir 时上一个 scan 可能仍在天上,
+ // 不递增 seq 它就仍匹配当前代,回来会用旧目录的结果覆盖刚画的缓存。
+ atLoadSeqRef.current += 1;
+ setAtPaletteLoading(false);
+ return;
+ }
+ }
+ const remoteQuery = cachedScan?.result.truncated ? (query || undefined) : undefined;
+ const seq = ++atLoadSeqRef.current;
+ // 缓存已画时 loading 置 false(而非跳过):ComposerPaletteFrame 的 spinner 会整体
+ // 顶掉 children,置 true 会把刚画的缓存闪成「读取中」,而上一轮无缓存请求残留的
+ // true 不清掉同样会盖住缓存行(与 slash 的缓存命中清 loading 同口径)。
+ setAtPaletteLoading(!cachedScan);
+ setAtPaletteError(null);
+ const timer = setTimeout(() => {
+ void withTransientRemoteRetry(async () => {
+ await openLink(deviceId);
+ return maker.scanAtResources(agentKind, {
+ workingDir: currentSession.workingDir!,
+ cap: 2000,
+ query: remoteQuery,
+ });
+ })
+ .then((result) => {
+ if (atLoadSeqRef.current !== seq) return;
+ if (!result.success) {
+ // 缓存已画时保留旧列表且不置 error——ComposerPaletteFrame 的 errorText
+ // 渲染在 children 之前,会把刚画的缓存整体盖住(codex review R18);
+ // 无缓存可画才清空并显示错误。
+ if (!cachedScan) {
+ setAtResources([]);
+ setAtResourcesTruncated(false);
+ setAtPaletteError(result.error ?? 'resource scan failed');
+ }
+ return;
+ }
+ const items = Array.isArray(result.items) ? result.items : [];
+ const truncated = result.truncated === true;
+ setAtResources(items);
+ setAtResourcesTruncated(truncated);
+ setAtPaletteError(null);
+ // 只缓存全量扫描;带 query 的截断补搜是局部结果,不能当全量复用。
+ if (!remoteQuery) {
+ writeAtResourceScanCache(paletteCacheKey, { items, truncated });
+ // 首拉即截断且用户已在输入:全量结果对该 query 的本地过滤不完整,而
+ // effect 依赖不含缓存写入、不会自动重跑,这里立即链式补搜一次(不进缓存)。
+ if (truncated && query) {
+ void withTransientRemoteRetry(async () => {
+ await openLink(deviceId);
+ return maker.scanAtResources(agentKind, {
+ workingDir: currentSession.workingDir!,
+ cap: 2000,
+ query,
+ });
+ })
+ .then((followup) => {
+ if (atLoadSeqRef.current !== seq) return;
+ if (!followup.success) return; // 补搜失败保留全量结果,不降级
+ setAtResources(Array.isArray(followup.items) ? followup.items : []);
+ setAtResourcesTruncated(followup.truncated === true);
+ })
+ .catch(() => undefined);
+ }
+ }
+ })
+ .catch((err) => {
+ if (atLoadSeqRef.current !== seq) return;
+ // 同上:缓存已画时不清列表、不置 error;无缓存可画才显示错误。
+ if (!cachedScan) {
+ setAtResources([]);
+ setAtResourcesTruncated(false);
+ setAtPaletteError(formatRemoteError(err));
+ }
+ })
+ .finally(() => {
+ if (atLoadSeqRef.current === seq) setAtPaletteLoading(false);
+ });
+ }, query === '' ? 0 : AT_RESOURCE_QUERY_DEBOUNCE_MS);
+ return () => { clearTimeout(timer); atLoadSeqRef.current += 1; };
+ }, [canUseRemoteSessionControls, composerTrigger, currentSession, deviceId, maker, openLink]);
+
+
+ return (
+ <>
+ {!shareSelectionActive && canUseComposer && composerTrigger.kind === 'slash' ? (
+ <ComposerPaletteFrame
+ emptyText={t('session.common.noMatchingCommands')}
+ errorText={slashPaletteError}
+ loading={slashPaletteLoading}
+ maxHeight={nativeShellLayout.paletteMaxHeight}
+ testID="session.slashPalette"
+ >
+ {visibleSlashCommands.map((command) => (
+ <ComposerPaletteRow
+ accessibilityLabel={t('session.common.insertCommand', { name: command.name })}
+ key={`${command.kind}:${command.name}`}
+ onPress={() => selectSlashCommand(command)}
+ primary={`/${command.name}`}
+ secondary={
+ command.kind === 'agent-skill'
+ ? command.source
+ : command.kind === 'desktop'
+ ? 'desktop'
+ : 'agent-cmd'
+ }
+ testID="session.slashCommandRow"
+ />
+ ))}
+ </ComposerPaletteFrame>
+ ) : null}
+
+ {!shareSelectionActive && canUseComposer && composerTrigger.kind === 'at' ? (
+ <ComposerPaletteFrame
+ emptyText={atResourcesTruncated ? t('session.common.keepTypingToNarrow') : t('session.common.noMatchingResources')}
+ errorText={atPaletteError}
+ loading={atPaletteLoading}
+ maxHeight={nativeShellLayout.paletteMaxHeight}
+ testID="session.atPalette"
+ >
+ {visibleAtResources.map((item) => (
+ <ComposerPaletteRow
+ accessibilityLabel={t('session.common.insertResource', { name: item.name })}
+ key={`${item.type}:${item.relPath}`}
+ onPress={() => selectAtResource(item)}
+ primary={item.type === 'dir' ? `${item.name}/` : item.name}
+ secondary={item.type === 'agent' ? 'Agent' : item.relPath}
+ testID="session.atResourceRow"
+ />
+ ))}
+ </ComposerPaletteFrame>
+ ) : null}
+
+
+ </>
+ );
+}
+
+interface SessionComposerControlState {
+ composerLayout: ReturnType<typeof buildSessionComposerLayout>;
+ composerSendUnavailableReason: string | null;
+ composerStopDisabledReason: string | null | undefined;
+ composerStopDisabled: boolean;
+ composerShowInlineStop: boolean;
+ composerSendSlotIsStop: boolean;
+ composerShowSendButton: boolean;
+ composerSendDisabled: boolean;
+ voiceIsListening: boolean;
+ voiceIsProcessing: boolean;
+ voiceIsBusy: boolean;
+ voiceRecordingTimer: ReturnType<typeof useMobileVoiceRecordingTimer>;
+ composerVoicePlacement: ReturnType<typeof resolveMobileComposerVoiceButtonPlacement> | undefined;
+}
+interface SessionComposerControls {
+ toolbar: ReactNode;
+ leading: ReactNode;
+ trailing: ReactNode;
+ attachmentTray: ReactNode;
+ voiceButton: (style?: StyleProp<ViewStyle>) => ReactNode;
+}
+interface SessionComposerInputProps {
+ source: ComposerDraftSource;
+ sessionId: string;
+ composerInputRef: RefObject<ComposerRichInputHandle | null>;
+ canUseComposer: boolean;
+ canStopComposer: boolean;
+ canUseRemoteSessionControls: boolean;
+ remoteUnavailableReason: string | null;
+ composerSendUnavailableReason: string | null;
+ voiceState: MobileVoiceState;
+ voiceStartPending: boolean;
+ voiceError: string | null;
+ composerVoiceHoldArmed: boolean;
+ setComposerVoiceHoldArmed: (value: boolean) => void;
+ modelSheetOpen: boolean;
+ permissionSheetOpen: boolean;
+ sending: boolean;
+ queueBusy: boolean;
+ nativeShellLayout: ReturnType<typeof buildSessionNativeShellLayout>;
+ composerTouchLayout: ReturnType<typeof buildComposerTouchLayout>;
+ keyboardState: ReturnType<typeof useMobileKeyboardState>;
+ attachmentError: string | null;
+ attachmentCount: number;
+ pendingUploadCount: number;
+ visualFocusComposer: boolean;
+ applyRichComposerChange: (value: ComposerDocument) => void;
+ setComposerDraft: (value: string) => void;
+ handleComposerInputPressIn: () => void;
+ onPasteImages: (uris: string[]) => void;
+ beginPastePlaceholders: (count: number) => void;
+ failPastePlaceholders: () => void;
+ resolvePastedSessionLinkLabel: NonNullable<React.ComponentProps<typeof ComposerRichInput>['resolveSessionLinkLabel']>;
+ openVoiceSettings: () => void;
+ onDragActiveChange: (active: boolean) => void;
+ renderControls: (state: SessionComposerControlState) => SessionComposerControls;
+}
+
+/** High-frequency editor, dictation, timer and resize state stops at this boundary. */
+function SessionComposerInput({
+ source, sessionId, composerInputRef, canUseComposer, canStopComposer, canUseRemoteSessionControls, remoteUnavailableReason, voiceState, voiceStartPending, voiceError, composerVoiceHoldArmed, setComposerVoiceHoldArmed, modelSheetOpen, permissionSheetOpen, sending, queueBusy, nativeShellLayout, composerTouchLayout, keyboardState, attachmentError, visualFocusComposer, applyRichComposerChange, setComposerDraft, handleComposerInputPressIn, beginPastePlaceholders, failPastePlaceholders, resolvePastedSessionLinkLabel, openVoiceSettings,
+ composerSendUnavailableReason, attachmentCount, pendingUploadCount,
+ onPasteImages, onDragActiveChange, renderControls,
+}: SessionComposerInputProps) {
+ const { document: composerDocument, draft } = useSyncExternalStore(source.subscribe, source.getSnapshot);
+ const { t, i18n: i18nInstance } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ const windowDimensions = useWindowDimensions();
+ const [composerFocused, setComposerFocused] = useState(false);
+ const [composerInputContentHeight, setComposerInputContentHeight] = useState(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT);
+ const [voiceDraftCaretFrame, setVoiceDraftCaretFrame] = useState({ left: 0, top: 0 });
+ const composerScrollViewRef = useRef<ScrollView>(null);
+ const composerScrollEnabledRef = useRef(false);
+ const voiceDraftScrollRef = useRef<ScrollView>(null);
+ const composerTrigger = useMemo(() => detectComposerTrigger(draft), [draft]);
+ const voiceUiAvailable = shouldShowMobileVoiceUi(Platform.OS);
+ const voiceIsListening = voiceState === 'listening';
+ const voiceIsProcessing = voiceState === 'submitting' || voiceState === 'refining';
+ const voiceIsBusy = voiceIsListening || voiceIsProcessing;
+ const canOpenVoiceSettings = isMobileVoiceMicPermissionError(voiceError);
+ // 引用已是 ComposerDocument 内的 atom;排队编辑同样可能只有引用而没有可见
+ // 文本,因此必须计入 payload,否则「保存修改」会被错误禁用。
+ const composerQuoteCount = composerDocumentQuotes(composerDocument).length;
+ // Context 面板是 Modal sheet,不再有内联附件面板 → attachmentPickerOpen 恒 false。
+ const composerLayout = useMemo(() => buildSessionComposerLayout({
+ attachmentBusy: false,
+ // pending(乐观上传中)计入:拍完照 / 选完文件立即可点发送,send() 内部会等落定。
+ attachmentCount: attachmentCount + pendingUploadCount,
+ attachmentPickerOpen: false,
+ // Stop 的可见性跟随真实运行 / 队列状态;断线时只单独禁用交互。
+ canStop: canStopComposer,
+ draftText: draft,
+ queueBusy,
+ quoteCount: composerQuoteCount,
+ sendUnavailableReason: composerSendUnavailableReason,
+ sending,
+ voiceState,
+ }), [
+ attachmentCount,
+ pendingUploadCount,
+ canStopComposer,
+ canUseComposer,
+ composerQuoteCount,
+ composerSendUnavailableReason,
+ draft,
+ i18nInstance.language,
+ queueBusy,
+ sending,
+ voiceState,
+ ]);
+ const compactComposer = composerLayout.density === 'compact';
+ // 发送槽双语义(对齐桌面 ChatInput 的主槽判定,voice busy = listening|submitting|refining):
+ // 任务执行中且发送不可用、又没有语音在进行时,停止任务顶替发送位;语音一旦开始,
+ // 发送键回到发送位(录音期=「结束并发送」,润色期=禁用态占位),停止任务退到
+ // 语音按钮**左边**的独立槽。语音按钮由此永远是发送槽的左邻,右缘位置与是否有
+ // 草稿/是否录音/任务是否执行全部无关——录音胶囊只向左生长,「原地再点一下」
+ // 永远是停止录音,不会误停任务。
+ const composerSendSlotIsStop = composerLayout.stop.visible
+ && composerLayout.send.disabled
+ && !sending
+ && !voiceIsBusy
+ && !voiceStartPending;
+ // 只有确定性不可用(撤权 / 关闭远控等)才禁发送;普通断线与自动恢复状态仍可发,
+ // 消息进入本地 outbox 等连接恢复。输入框在两类状态下都保持可编辑与持久化。
+ const composerSendDisabled = composerLayout.send.disabled;
+ const composerStopDisabled = composerLayout.stop.disabled || !canUseRemoteSessionControls;
+ const composerStopDisabledReason = !canUseRemoteSessionControls
+ ? remoteUnavailableReason ?? t('session.menu.aiRenameOffline')
+ : composerLayout.stop.disabledReason;
+ const composerShowInlineStop = composerLayout.stop.visible && !composerSendSlotIsStop && !sending;
+ // send.visible 在语音生命周期内恒 true(sessionOperation.ts),这里不再按
+ // voiceIsListening 二次过滤——那正是「首段转写落地瞬间发送键冒出来」的跳变源。
+ // 乐观 pending 期(state 还是 idle)同样要占住发送槽:否则空草稿按下语音时
+ // 胶囊先在 12pt 档展开,listening 一到发送键出现又整体跳到 52pt 档。
+ const composerShowSendButton = composerLayout.send.visible || voiceStartPending;
+ const composerVoicePlacement = voiceUiAvailable
+ ? resolveMobileComposerVoiceButtonPlacement({
+ // 行尾有发送或占发送位的停止按钮时让位;附件-only(无文字)同样命中。
+ hasTrailingAction: composerSendSlotIsStop || composerShowSendButton,
+ })
+ : undefined;
+ // 录音计时(红点+m:ss 胶囊);pillWidth 同时驱动语音按钮与工具排占位 slot,
+ // 胶囊展开时把左邻的停止任务按钮推开,而不是盖住它。expanded 含乐观 pending
+ // (按下即展开),counting 只认真实采集(listening)——启动链路(权限弹窗等)
+ // 不计入录音时长,pending 期显示静止的 0:00。
+ const voiceRecordingTimer = useMobileVoiceRecordingTimer({
+ expanded: voiceIsListening || voiceStartPending,
+ counting: voiceIsListening,
+ });
+ const composerEffectiveContentHeight = composerInputContentHeight;
+ const voiceDraftShowsListeningPrompt = voiceIsListening && draft.length === 0;
+ // 状态行只承载错误信息;「正在听 / 转写中」不再占一行,对齐桌面版——
+ // 录音状态由输入框内的语音按钮形态(Mic / 红点计时胶囊 / spinner)表达。
+ const voiceStatusVisible = voiceUiAvailable && Boolean(voiceError);
+
+ // 聚焦 / 面板打开 / 语音中呈现卡片形态(输入区全宽 + 底部工具排),其余保持单行简洁态。
+ // 注意不看 composerLayout.density:有草稿 / 会话运行中未聚焦时也应收回简洁态,
+ // 否则「拖回单行退出激活态」永远收不回去。
+ // 语音结束后草稿仍有内容时经 hold 保持展开(一行文字也不收),
+ // 不随 voiceIsBusy 归零塌回简洁态。
+ const composerVoiceHoldActive = resolveComposerVoiceHoldActive({
+ armed: composerVoiceHoldArmed,
+ draftText: draft,
+ });
+ const composerCardActive = (canUseComposer && composerFocused)
+ || modelSheetOpen
+ || permissionSheetOpen
+ || voiceIsBusy
+ || composerVoiceHoldActive;
+ useComposerCardTransition(composerCardActive, keyboardState);
+ const composerChromeHeight = useMemo(() => {
+ const statusReserve = voiceStatusVisible
+ ? COMPOSER_STATUS_ROW_RESERVED_HEIGHT + COMPOSER_STACK_GAP_HEIGHT
+ : 0;
+ const rowChrome = composerCardActive
+ ? COMPOSER_CARD_ROW_CHROME_HEIGHT
+ : COMPOSER_INPUT_ROW_CHROME_HEIGHT;
+ return COMPOSER_VERTICAL_PADDING_HEIGHT + statusReserve + rowChrome;
+ }, [composerCardActive, voiceStatusVisible]);
+ const composerInputMaxContentHeight = useMemo(() => {
+ const availableHeight = nativeShellLayout.composerMaxHeight - composerChromeHeight;
+ return Math.min(
+ COMPOSER_INPUT_MAX_CONTENT_HEIGHT,
+ Math.max(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT, availableHeight),
+ );
+ }, [composerChromeHeight, nativeShellLayout.composerMaxHeight]);
+ // 下拉收起 = 退出聚焦激活态(模型浮窗已是独立 Modal,拖拽手势够不到它,无需在此关闭)。
+ // 语音结束 hold 态未聚焦,blur 是 no-op,需显式解除 hold 才能收回简洁态。
+ const handleComposerSnapToAuto = useCallback(() => {
+ setComposerVoiceHoldArmed(false);
+ composerInputRef.current?.blur();
+ }, []);
+ // Installed apps arbitrate grabber/scroll ownership on UI via Gesture.Native.
+ // Retain the native scroll switch for Expo Go's PanResponder fallback.
+ const handleGrabberTouchActiveChange = useCallback((active: boolean) => {
+ onDragActiveChange(active);
+ composerScrollViewRef.current?.setNativeProps({
+ scrollEnabled: active ? false : composerScrollEnabledRef.current,
+ });
+ }, [onDragActiveChange]);
+ const composerResize = useComposerResize({
+ autoMaxContentHeight: composerInputMaxContentHeight,
+ // 简洁态一律收到单行(下拉收起和点别处收键盘的结果一致);
+ // auto / manual 记忆保留,重新聚焦后恢复。
+ collapsed: !composerCardActive,
+ minFrameHeight: voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined,
+ composerChromeHeight,
+ contentHeight: composerEffectiveContentHeight,
+ keyboardHeight: keyboardState.visible ? keyboardState.height : 0,
+ onGrabberTouchActiveChange: handleGrabberTouchActiveChange,
+ onSnapToAuto: handleComposerSnapToAuto,
+ singleLineContentHeight: COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT,
+ windowHeight: windowDimensions.height,
+ });
+ // manual 高度跨聚焦/失焦、键盘开合保留(用户拖出的高度是显式意图);
+ // 唯一自然失效点:草稿清空(发送成功/删光)回 auto,避免空输入框残留定高。
+ const composerResizeReset = composerResize.reset;
+ useEffect(() => {
+ if (draft.length === 0) {
+ composerResizeReset();
+ // 草稿清空(发送成功/删光)后语音结束 hold 也失去意义,一并解除。
+ setComposerVoiceHoldArmed(false);
+ }
+ }, [draft, composerResizeReset]);
+ const composerInputIsMultiline = composerResize.dragging
+ || composerResize.mode === 'manual'
+ || (draft.length > 0
+ && (draft.includes('\n') || composerEffectiveContentHeight > COMPOSER_INPUT_MULTILINE_CONTENT_THRESHOLD));
+ const composerInputVisibleHeight = composerResize.visibleContentHeight;
+ const composerInputScrollEnabled = composerResize.scrollEnabled;
+ const composerShellHasScrollableContent = attachmentCount > 0
+ || pendingUploadCount > 0
+ || attachmentError !== null
+ || composerTrigger.kind === 'slash'
+ || composerTrigger.kind === 'at';
+ // Only enable shell scrolling when attachments or palettes can overflow.
+ // Native gesture arbitration lets the grabber win without waiting for JS.
+ const composerScrollEnabled = (nativeShellLayout.composerScrollEnabled || composerTrigger.kind !== 'none')
+ && !composerResize.dragging
+ && composerShellHasScrollableContent;
+ composerScrollEnabledRef.current = composerScrollEnabled;
+ const resizeActive = composerResize.active;
+ const manualResize = composerResize.mode === 'manual';
+ const expandedMaxHeight = composerResize.maxFrameHeight + composerChromeHeight;
+ const autoMaxHeight = nativeShellLayout.composerMaxHeight;
+ const composerContainerStyle = useAnimatedStyle(() => ({
+ maxHeight: resizeActive.value || manualResize ? expandedMaxHeight : autoMaxHeight,
+ }));
+ const handleComposerInputContentSizeChange = useCallback((event: TextInputContentSizeChangeEvent) => {
+ const nextHeight = Math.max(
+ COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT,
+ Math.ceil(event.nativeEvent.contentSize.height),
+ );
+ setComposerInputContentHeight((currentHeight) => (
+ Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight
+ ));
+ }, []);
+ const handleComposerRichInputHeight = useCallback((height: number) => {
+ const nextHeight = Math.max(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT, Math.ceil(height));
+ setComposerInputContentHeight((currentHeight) => (
+ Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight
+ ));
+ }, []);
+ const handleVoiceDraftTextLayout = useCallback((event: TextLayoutEvent) => {
+ const lines = event.nativeEvent.lines;
+ const lastLine = lines[lines.length - 1];
+ if (!lastLine) return;
+ const nextFrame = {
+ left: Math.max(0, Math.round(lastLine.x + lastLine.width + COMPOSER_VOICE_CARET_GAP)),
+ top: Math.max(0, Math.round(lastLine.y + ((lastLine.height - COMPOSER_INPUT_LINE_HEIGHT) / 2))),
+ };
+ setVoiceDraftCaretFrame((currentFrame) => (
+ currentFrame.left === nextFrame.left && currentFrame.top === nextFrame.top
+ ? currentFrame
+ : nextFrame
+ ));
+ }, []);
+
+ const renderComposerResizeHandle = () => (
+ <ComposerResizeGrabber
+ onAdjust={composerResize.adjustByLine}
+ panHandlers={composerResize.panHandlers}
+ gesture={composerResize.gesture}
+ testID="session.composerResizeGrabber"
+ visible
+ />
+ );
+
+ const renderComposerInputOverlay = () => voiceIsListening ? (
+ // 「点输入区 = 想打字 → 停止听写」由这层 RN 覆盖层承接。听写期间真正盖在输入区上的
+ // 就是它;底下的富文本 WebView 此刻是 hidden(opacity 0),iOS hitTest 会跳过 alpha≈0
+ // 的 view,它根本收不到触摸——把停听写挂在 WebView 的 focus / touch 上都不成立
+ // (focus 还会被 WKWebView 自己恢复焦点误触发,掐断刚开始的听写)。
+ <Pressable
+ accessibilityLabel={t('session.common.voiceStopRecording')}
+ accessibilityRole="button"
+ // onPressIn 给手指「触摸即停」的即时手感;onPress 是无障碍激活(VoiceOver /
+ // TalkBack 的 activate 只走 onPress,不会派发 onPressIn)的唯一入口,两者都要挂。
+ // handler 幂等:finishVoiceRecording 有 voiceStopInFlight 门,重复调用是 no-op。
+ onPress={handleComposerInputPressIn}
+ onPressIn={handleComposerInputPressIn}
+ style={styles.voiceDraftOverlay}
+ testID="session.voiceDraftOverlay"
+ >
+ <ScrollView
+ ref={voiceDraftScrollRef}
+ contentContainerStyle={[
+ styles.voiceDraftOverlayContent,
+ !composerCardActive && styles.voiceDraftOverlayContentGeometric,
+ ]}
+ onContentSizeChange={() => {
+ requestAnimationFrame(() => {
+ voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
+ });
+ }}
+ onLayout={() => {
+ requestAnimationFrame(() => {
+ voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
+ });
+ }}
+ pointerEvents="none"
+ scrollEnabled={composerInputScrollEnabled}
+ showsVerticalScrollIndicator={false}
+ style={styles.voiceDraftScroll}
+ >
+ {voiceDraftShowsListeningPrompt ? (
+ <View style={styles.voiceDraftListeningPrompt}>
+ <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />
+ <Text style={styles.voiceDraftListeningText}>{composerLayout.input.placeholder}</Text>
+ </View>
+ ) : (
+ <View style={styles.voiceDraftMeasuredBlock}>
+ <Text
+ onTextLayout={handleVoiceDraftTextLayout}
+ style={styles.voiceDraftText}
+ >
+ {draft}
+ </Text>
+ <View
+ pointerEvents="none"
+ style={[
+ styles.voiceDraftCaretOverlay,
+ {
+ left: voiceDraftCaretFrame.left,
+ top: voiceDraftCaretFrame.top,
+ },
+ ]}
+ >
+ <VoiceMicWaveCaret color={colors.textPrimary} testID="session.voiceMicCaret" />
+ </View>
+ </View>
+ )}
+ </ScrollView>
+ </Pressable>
+ ) : null;
+
+ // 听写期间只滚动覆盖层跟随最新文字,**不碰隐藏编辑器的 caret**(2026-07-28):
+ // 旧实现每段转写都把选区挪到末尾,而富文本编辑器的选区操作底层是 WebView
+ // 程序化 focus,配合 keyboardDisplayRequiresUserAction={false} 会在点语音的
+ // 同时弹出软键盘。#551 之前这个 focus 表现为「听写刚开始就被掐断」(focus 即
+ // 停听写),#551 修掉掐断后它幸存为弹键盘。听写中输入框本就隐藏(覆盖层渲染
+ // 草稿),caret 无意义;落焦统一放在听写结束点(finishVoiceRecording)。
+ useEffect(() => {
+ if (!voiceIsListening) return undefined;
+ const frame = requestAnimationFrame(() => {
+ voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [composerInputContentHeight, composerInputVisibleHeight, draft, voiceIsListening]);
+
+ useEffect(() => {
+ if (voiceIsListening && draft.length > 0) return;
+ setVoiceDraftCaretFrame({ left: 0, top: 0 });
+ }, [draft.length, voiceIsListening]);
+
+
+ const controls = renderControls({ composerLayout, composerSendUnavailableReason, composerStopDisabledReason, composerStopDisabled, composerShowInlineStop, composerSendSlotIsStop, composerShowSendButton, composerSendDisabled, voiceIsListening, voiceIsProcessing, voiceIsBusy, voiceRecordingTimer, composerVoicePlacement });
+ return (
+ <Reanimated.View
+ style={[
+ styles.composer,
+ composerContainerStyle,
+ {
+ paddingHorizontal: composerTouchLayout.composerPaddingHorizontal,
+ },
+ ]}
+ testID="session.composer"
+ >
+ {voiceStatusVisible ? (
+ <View style={styles.voiceStatusRow}>
+ <Text style={styles.voiceStatusText} testID="session.voiceStatus">
+ {voiceError}
+ </Text>
+ {canOpenVoiceSettings ? (
+ <RouteActionButton
+ accessibilityLabel={t('session.common.openMicPermission')}
+ hitSlop={COMPOSER_CONTROL_HIT_SLOP}
+ onPress={openVoiceSettings}
+ style={styles.voiceCancelButton}
+ testID="session.voiceSettingsButton"
+ >
+ <Settings color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </RouteActionButton>
+ ) : null}
+ </View>
+ ) : null}
+ <GestureDetector gesture={composerResize.scrollGesture}>
+ <ScrollView
+ ref={composerScrollViewRef}
+ contentContainerStyle={styles.composerScrollContent}
+ keyboardShouldPersistTaps="handled"
+ scrollEnabled={composerScrollEnabled}
+ showsVerticalScrollIndicator={composerScrollEnabled}
+ style={styles.composerScroll}
+ testID="session.composerScroll"
+ >
+
+ {attachmentError ? (
+ <Text style={styles.attachmentErrorText} testID="session.attachmentStatus">
+ {attachmentError}
+ </Text>
+ ) : null}
+
+ <View style={[
+ styles.composerSurface,
+ compactComposer && !composerCardActive && styles.composerSurfaceCompact,
+ ]}>
+ <MobileComposerInputRow
+ key={sessionId}
+ accessibilityLabel={t('session.screen.composerPlaceholder')}
+ accessibilityHint={composerLayout.input.disabledReason ?? undefined}
+ accessoryAbove={controls.attachmentTray}
+ autoFocus={visualFocusComposer}
+ cardActive={composerCardActive}
+ caretHidden={voiceIsListening}
+ compact={compactComposer && !composerCardActive}
+ editable={!composerLayout.input.disabled}
+ floatingVoiceButton={voiceUiAvailable ? controls.voiceButton : undefined}
+ cursorColor={colors.inputCaret}
+ inputFrameAnimatedStyle={composerResize.frameStyle}
+ // 听写期间把输入区撑到 44pt 触控目标:命中层盖在 inputFrame 上,
+ // hitSlop 越不过父边界(见常量注释)。
+ inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}
+ inputElement={(
+ <ComposerRichInput
+ ref={composerInputRef}
+ accessibilityHint={composerLayout.input.disabledReason ?? undefined}
+ accessibilityLabel={t('session.screen.composerPlaceholder')}
+ document={composerDocument}
+ editable={!composerLayout.input.disabled}
+ height={composerInputVisibleHeight}
+ animatedHeight={composerResize.contentHeight}
+ hidden={voiceIsListening}
+ maxHeight={composerResize.inputMaxHeight}
+ opticalPadding={composerCardActive}
+ onBlur={() => {
+ setComposerFocused(false);
+ setComposerVoiceHoldArmed(false);
+ }}
+ onChangeDocument={applyRichComposerChange}
+ onFocus={() => setComposerFocused(true)}
+ onHeightChange={handleComposerRichInputHeight}
+ onPasteImages={onPasteImages}
+ onPasteImagesLoading={beginPastePlaceholders}
+ onPasteImagesLoadFailed={failPastePlaceholders}
+ placeholder={voiceIsListening ? '' : composerLayout.input.placeholder}
+ resolveSessionLinkLabel={resolvePastedSessionLinkLabel}
+ testID="session.composerRichInput"
+ theme={{
+ background: colors.chatCodeSurface,
+ border: colors.border,
+ chip: colors.surfaceChip,
+ focus: colors.inputCaret,
+ placeholder: colors.textTertiary,
+ text: colors.textPrimary,
+ textSecondary: colors.textSecondary,
+ }}
+ />
+ )}
+ inputOverlay={renderComposerInputOverlay()}
+ inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}
+ inputTestID="session.composerInput"
+ leading={controls.leading}
+ maxHeight={composerResize.inputMaxHeight}
+ multilineShape={!composerCardActive && composerInputIsMultiline}
+ onBlur={() => {
+ setComposerFocused(false);
+ // 失焦收起与「点别处收键盘」同语义:语音结束 hold 一并解除。
+ setComposerVoiceHoldArmed(false);
+ }}
+ onChangeText={setComposerDraft}
+ onContentSizeChange={handleComposerInputContentSizeChange}
+ onFocus={() => {
+ setComposerFocused(true);
+ handleComposerInputPressIn();
+ }}
+ onPasteImages={onPasteImages}
+ onPasteImagesLoading={beginPastePlaceholders}
+ onPasteImagesLoadFailed={failPastePlaceholders}
+ onPressIn={handleComposerInputPressIn}
+ placeholder={voiceIsListening ? '' : composerLayout.input.placeholder}
+ placeholderTextColor={colors.textTertiary}
+ resizeHandle={composerCardActive ? renderComposerResizeHandle() : null}
+ scrollEnabled={composerInputScrollEnabled}
+ selectionColor={colors.inputCaret}
+ testID="session.composerInputRow"
+ toolbar={controls.toolbar}
+ trailing={composerCardActive ? null : controls.trailing}
+ value={draft}
+ voicePlacement={composerVoicePlacement}
+ />
+ </View>
+ </ScrollView>
+ </GestureDetector>
+ </Reanimated.View>
+
+ );
+}
+
function SessionSearchSheet({
activeHit,
activeIndex,
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index e68ca4dd91..e4f06ca3e5 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -3351,6 +3351,7 @@ export default function NewRemoteSessionScreen() {
<ComposerResizeGrabber
onAdjust={composerResize.adjustByLine}
panHandlers={composerResize.panHandlers}
+ gesture={composerResize.gesture}
testID="newSession.composerResizeGrabber"
visible
/>
@@ -5788,7 +5789,7 @@ export default function NewRemoteSessionScreen() {
cursorColor={colors.inputCaret}
inputRef={firstMessageInputRef}
leading={renderComposerCompactLeading()}
- inputFrameHeight={composerResize.frameHeight}
+ inputFrameAnimatedStyle={composerResize.frameStyle}
// 听写期间把输入区撑到 44pt 触控目标:此时「点输入区停止听写」的命中层
// 是这层输入区自身(TextInput 的 onPressIn),单行时只有 28pt。
inputFrameMinHeight={voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}
diff --git a/apps/mobile/src/__tests__/composerDraftSource.test.tsx b/apps/mobile/src/__tests__/composerDraftSource.test.tsx
new file mode 100644
index 0000000000..c78cdf679d
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerDraftSource.test.tsx
@@ -0,0 +1,83 @@
+// @vitest-environment jsdom
+import { act, createElement, useSyncExternalStore } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, expect, it } from 'vitest';
+import { createComposerDraftSource, useComposerVoiceDraftWriter, type ComposerDraftSource } from '@/session/composerDraftSource';
+import { textComposerDocument } from '@/session/composerDocument';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; });
+
+it('typing and streamed dictation update subscribers without rendering the task or message list', () => {
+ const source = createComposerDraftSource(textComposerDocument(''));
+ const container = document.createElement('div');
+ const counts = { task: 0, messages: 0, input: 0 };
+ function Messages() { counts.messages++; return null; }
+ function Input() {
+ counts.input++;
+ const snapshot = useSyncExternalStore(source.subscribe, source.getSnapshot);
+ return createElement('span', null, snapshot.draft);
+ }
+ function Task() {
+ counts.task++;
+ return createElement('div', null, createElement(Messages), createElement(Input));
+ }
+ root = createRoot(container);
+ act(() => root!.render(createElement(Task)));
+ const before = { ...counts };
+ for (let index = 1; index <= 100; index++) {
+ act(() => source.setDocument(textComposerDocument('听写内容'.repeat(index))));
+ }
+ expect(counts.task).toBe(before.task);
+ expect(counts.messages).toBe(before.messages);
+ expect(counts.input).toBe(before.input + 100);
+ expect(container.textContent).toBe('听写内容'.repeat(100));
+});
+
+it('task switches detach old drafts and clearing the editor preserves the send snapshot', () => {
+ const first = createComposerDraftSource(textComposerDocument('first draft'));
+ const second = createComposerDraftSource(textComposerDocument('second draft'));
+ const container = document.createElement('div');
+ function Input({ source }: { source: ComposerDraftSource }) {
+ return createElement('span', null, useSyncExternalStore(source.subscribe, source.getSnapshot).draft);
+ }
+ root = createRoot(container);
+ act(() => root!.render(createElement(Input, { source: first })));
+ const atSend = first.getSnapshot();
+ act(() => first.setDocument(textComposerDocument('')));
+ expect(atSend.draft).toBe('first draft');
+ act(() => root!.render(createElement(Input, { source: second })));
+ act(() => first.setDocument(textComposerDocument('late old-task update')));
+ expect(container.textContent).toBe('second draft');
+ expect(first.getSnapshot()).toBe(first.getSnapshot());
+});
+
+it('a running voice writer follows replaced drafts but cannot write after leaving its task', () => {
+ const first = createComposerDraftSource(textComposerDocument('first'));
+ const replacement = createComposerDraftSource(textComposerDocument('file inserted'));
+ const other = createComposerDraftSource(textComposerDocument('other task'));
+ let writeVoice: (draft: string) => void;
+ function Controller({ sessionId, source }: { sessionId: string; source: ComposerDraftSource }) {
+ writeVoice = useComposerVoiceDraftWriter(sessionId, (draft) => source.setDocument(textComposerDocument(draft)));
+ return null;
+ }
+ root = createRoot(document.createElement('div'));
+ act(() => root!.render(createElement(Controller, { sessionId: 'a', source: first })));
+ const ongoingControllerWrite = writeVoice!;
+ act(() => root!.render(createElement(Controller, { sessionId: 'a', source: replacement })));
+ expect(writeVoice!).toBe(ongoingControllerWrite);
+ act(() => ongoingControllerWrite('file inserted plus dictation'));
+ expect(replacement.getSnapshot().draft).toBe('file inserted plus dictation');
+ expect(first.getSnapshot().draft).toBe('first');
+ act(() => root!.render(createElement(Controller, { sessionId: 'b', source: other })));
+ act(() => ongoingControllerWrite('late a'));
+ expect(other.getSnapshot().draft).toBe('other task');
+ act(() => root!.render(createElement(Controller, { sessionId: 'a', source: replacement })));
+ act(() => ongoingControllerWrite('late a after returning'));
+ expect(replacement.getSnapshot().draft).toBe('file inserted plus dictation');
+ const currentWrite = writeVoice!;
+ act(() => root!.render(null));
+ act(() => currentWrite('after unmount'));
+ expect(replacement.getSnapshot().draft).toBe('file inserted plus dictation');
+});
diff --git a/apps/mobile/src/__tests__/composerInteractionBoundary.test.tsx b/apps/mobile/src/__tests__/composerInteractionBoundary.test.tsx
new file mode 100644
index 0000000000..3675720792
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerInteractionBoundary.test.tsx
@@ -0,0 +1,400 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useComposerResize, type UseComposerResizeInput } from '@/session/useComposerResize';
+import { useContextSheetDrag, type UseContextSheetDragInput } from '@/session/useContextSheetDrag';
+
+const runtime = vi.hoisted(() => ({
+ js: [] as Array<() => void>,
+ ui: [] as Array<() => void>,
+ deferUI: false,
+ reduceMotion: false,
+ durations: [] as number[],
+ deferAnimations: false,
+ animationHeight: undefined as number | undefined,
+}));
+vi.mock('react-native', () => ({ PanResponder: { create: vi.fn(() => ({ panHandlers: {} })) } }));
+vi.mock('expo-constants', () => ({
+ default: { executionEnvironment: 'bare' }, ExecutionEnvironment: { StoreClient: 'storeClient' },
+}));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => runtime.reduceMotion }));
+vi.mock('@/theme', () => ({ motionDuration: { fast: 180 }, motionEasing: { move: [0, 0, 1, 1] } }));
+type Callback = (event: { translationY: number }, successful?: boolean) => void;
+interface TestGesture {
+ begin: Callback; update: Callback; finalize: Callback;
+}
+vi.mock('@/platform/gestureHandler', () => {
+ const make = () => {
+ const callbacks = {} as TestGesture;
+ return Object.assign(callbacks, {
+ minDistance() { return this; },
+ blocksExternalGesture() { return this; },
+ activeOffsetY() { return this; },
+ failOffsetX() { return this; },
+ onBegin(fn: Callback) { callbacks.begin = fn; return this; },
+ onUpdate(fn: Callback) { callbacks.update = fn; return this; },
+ onFinalize(fn: Callback) { callbacks.finalize = fn; return this; },
+ });
+ };
+ return { Gesture: { Pan: make, Native: make } };
+});
+// Run real hooks/React and geometry models. Model UI worklets as synchronous
+// callbacks, but hold runOnJS deliveries to exercise a busy JS thread explicitly.
+vi.mock('react-native-reanimated', async () => {
+ const { useRef } = await import('react');
+ return {
+ useSharedValue: (initial: unknown) => useRef({ value: initial }).current,
+ useDerivedValue: (calculate: () => unknown) => ({ get value() { return calculate(); } }),
+ useAnimatedStyle: (calculate: () => unknown) => ({ get current() { return calculate(); } }),
+ runOnJS: (fn: (...args: unknown[]) => void) => (...args: unknown[]) => {
+ runtime.js.push(() => fn(...args));
+ },
+ runOnUI: (fn: (...args: unknown[]) => void) => (...args: unknown[]) => {
+ if (runtime.deferUI) runtime.ui.push(() => fn(...args));
+ else fn(...args);
+ },
+ withTiming: (value: number, config: { duration: number }, done?: (finished: boolean) => void) => {
+ runtime.durations.push(config.duration);
+ if (!runtime.deferAnimations) done?.(true);
+ return runtime.animationHeight ?? value;
+ },
+ cancelAnimation: vi.fn(),
+ Easing: { bezier: vi.fn() },
+ };
+});
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root;
+const flushJS = () => act(() => { for (const job of runtime.js.splice(0)) job(); });
+const gestureOf = (value: unknown) => value as TestGesture;
+const styleOf = (value: unknown) => (value as { current: { height: number; maxHeight?: number } }).current;
+
+beforeEach(() => {
+ runtime.js = [];
+ runtime.ui = [];
+ runtime.deferUI = false;
+ runtime.durations = [];
+ runtime.reduceMotion = false;
+ runtime.deferAnimations = false;
+ runtime.animationHeight = undefined;
+ root = createRoot(document.createElement('div'));
+});
+afterEach(() => act(() => root.unmount()));
+
+const composerInput = (): UseComposerResizeInput => ({
+ contentHeight: 60, autoMaxContentHeight: 120, windowHeight: 900,
+ keyboardHeight: 250, singleLineContentHeight: 20, composerChromeHeight: 80,
+ onSnapToAuto: vi.fn(), onGrabberTouchActiveChange: vi.fn(),
+});
+function mountComposer(input: UseComposerResizeInput) {
+ let result: ReturnType<typeof useComposerResize>;
+ let renders = 0;
+ function Harness() { renders++; result = useComposerResize(input); return null; }
+ const rerender = () => act(() => root.render(createElement(Harness)));
+ rerender();
+ return { get result() { return result!; }, get renders() { return renders; }, rerender };
+}
+
+describe('composer resize interaction boundary', () => {
+ it('tracks 100 pointer moves with no JS deliveries or React renders, then commits once', () => {
+ const input = composerInput();
+ const harness = mountComposer(input);
+ const gesture = gestureOf(harness.result.gesture);
+ const innerLimit = harness.result.inputMaxHeight;
+ expect(innerLimit).toBeGreaterThan(input.autoMaxContentHeight);
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBe(input.autoMaxContentHeight);
+ gesture.begin({ translationY: 0 });
+ // Even touch-down can wait for JS while the native frame follows the finger.
+ const before = harness.renders;
+ for (let index = 1; index <= 100; index++) gesture.update({ translationY: -index });
+ expect(harness.result.contentHeight.value).toBe(160);
+ expect(styleOf(harness.result.frameStyle).height).toBeGreaterThan(160);
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBeUndefined();
+ expect(innerLimit).toBeGreaterThanOrEqual(styleOf(harness.result.frameStyle).height);
+ expect(harness.result.inputMaxHeight).toBe(innerLimit);
+ expect(harness.renders).toBe(before);
+ expect(runtime.js).toHaveLength(1); // only begin, never pointer moves
+ gesture.finalize({ translationY: -100 }, true);
+ flushJS();
+ expect(harness.result.visibleContentHeight).toBe(160);
+ expect(harness.result.mode).toBe('manual');
+ expect(harness.result.active.value).toBe(false);
+ expect(input.onGrabberTouchActiveChange).toHaveBeenNthCalledWith(1, true);
+ expect(input.onGrabberTouchActiveChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('cancellation restores the settled height without dismissing the keyboard', () => {
+ const input = composerInput();
+ const harness = mountComposer(input);
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 100 });
+ gesture.finalize({ translationY: 100 }, false);
+ expect(harness.result.active.value).toBe(false);
+ expect(harness.result.contentHeight.value).toBe(60);
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBe(input.autoMaxContentHeight);
+ flushJS();
+ expect(harness.result.contentHeight.value).toBe(60);
+ expect(harness.result.mode).toBe('auto');
+ expect(input.onSnapToAuto).not.toHaveBeenCalled();
+ });
+
+ it('keeps long drafts at the auto cap and restores that cap after cancel and reset', () => {
+ const input = { ...composerInput(), contentHeight: 500 };
+ const harness = mountComposer(input);
+ const gesture = gestureOf(harness.result.gesture);
+ expect(harness.result.visibleContentHeight).toBe(120);
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBe(120);
+ expect(harness.result.scrollEnabled).toBe(true);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -100 });
+ expect(harness.result.contentHeight.value).toBe(220);
+ expect(harness.result.inputMaxHeight).toBeGreaterThanOrEqual(220);
+ gesture.finalize({ translationY: -100 }, false);
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBe(120);
+ expect(harness.result.contentHeight.value).toBe(120);
+ flushJS();
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -100 });
+ gesture.finalize({ translationY: -100 }, true);
+ flushJS();
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBeUndefined();
+ act(() => harness.result.reset());
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBe(120);
+ expect(harness.result.visibleContentHeight).toBe(120);
+ input.autoMaxContentHeight = 100;
+ harness.rerender();
+ expect(styleOf(harness.result.frameStyle).maxHeight).toBe(100);
+ expect(harness.result.visibleContentHeight).toBe(100);
+ });
+
+ it('starts a new drag from the settled manual height before canceled JS callbacks arrive', () => {
+ const input = composerInput();
+ const harness = mountComposer(input);
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -100 });
+ gesture.finalize({ translationY: -100 }, true);
+ flushJS();
+ expect(harness.result.visibleContentHeight).toBe(160);
+
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 100 });
+ gesture.finalize({ translationY: 100 }, false);
+ expect(harness.result.active.value).toBe(false);
+ expect(harness.result.contentHeight.value).toBe(160);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -20 });
+ expect(harness.result.contentHeight.value).toBe(180);
+ flushJS();
+ expect(harness.result.active.value).toBe(true);
+ expect(harness.result.contentHeight.value).toBe(180);
+ gesture.finalize({ translationY: -20 }, true);
+ flushJS();
+ expect(harness.result.visibleContentHeight).toBe(180);
+ expect(input.onSnapToAuto).not.toHaveBeenCalled();
+ });
+
+ it('ignores an old release while a second drag is active and clamps to new keyboard bounds', () => {
+ const input = composerInput();
+ const harness = mountComposer(input);
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 100 });
+ gesture.finalize({ translationY: 100 }, true); // would dismiss if delivered
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -300 });
+ flushJS();
+ expect(input.onSnapToAuto).not.toHaveBeenCalled();
+ expect(harness.result.active.value).toBe(true);
+ input.keyboardHeight = 450;
+ harness.rerender();
+ expect(harness.result.contentHeight.value).toBe(150);
+ gesture.finalize({ translationY: -300 }, true);
+ flushJS();
+ expect(harness.result.visibleContentHeight).toBe(150);
+ expect(harness.result.contentHeight.value).toBe(150);
+ });
+
+ it('delayed release after unmount cannot dismiss a different task', () => {
+ const input = composerInput();
+ const harness = mountComposer(input);
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 100 });
+ gesture.finalize({ translationY: 100 }, true);
+ act(() => root.render(null));
+ flushJS();
+ expect(input.onSnapToAuto).not.toHaveBeenCalled();
+ });
+
+ it('a React height commit delivered after the next gesture cannot drop its UI override', () => {
+ const harness = mountComposer(composerInput());
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -100 });
+ gesture.finalize({ translationY: -100 }, true);
+ runtime.deferUI = true;
+ flushJS();
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -50 });
+ for (const job of runtime.ui.splice(0)) job();
+ expect(harness.result.active.value).toBe(true);
+ expect(harness.result.contentHeight.value).toBe(210);
+ });
+});
+
+function mountSheet() {
+ const input: UseContextSheetDragInput = {
+ heights: { half: 400, full: 700 }, snap: 'half',
+ onSnapChange: vi.fn(), onDismiss: vi.fn(),
+ };
+ let result: ReturnType<typeof useContextSheetDrag>;
+ let renders = 0;
+ function Harness() { renders++; result = useContextSheetDrag(input); return null; }
+ const rerender = () => act(() => root.render(createElement(Harness)));
+ rerender();
+ return { input, get result() { return result!; }, get renders() { return renders; }, rerender };
+}
+
+describe('sheet UI gesture lifecycle', () => {
+ it.each([0, 2])('retains the external snap when a drag returns to %ipx displacement', (distance) => {
+ const harness = mountSheet();
+ runtime.animationHeight = 450;
+ harness.input.snap = 'full';
+ harness.rerender();
+ runtime.animationHeight = undefined;
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -20 });
+ gesture.update({ translationY: distance });
+ gesture.finalize({ translationY: distance }, true);
+ flushJS();
+ expect(styleOf(harness.result.animatedStyle).height).toBe(700);
+ expect(harness.input.onSnapChange).toHaveBeenCalledExactlyOnceWith('full');
+ expect(harness.input.onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('moves without JS/React work and reports the full snap after release', () => {
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ for (let index = 1; index <= 250; index++) gesture.update({ translationY: -index });
+ expect(styleOf(harness.result.animatedStyle).height).toBe(650);
+ expect(harness.renders).toBe(1);
+ expect(runtime.js).toHaveLength(0);
+ gesture.finalize({ translationY: -250 }, true);
+ flushJS();
+ expect(harness.input.onSnapChange).toHaveBeenCalledExactlyOnceWith('full');
+ });
+
+ it('cancellation returns to the current snap, including reduced motion', () => {
+ runtime.reduceMotion = true;
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 350 });
+ gesture.finalize({ translationY: 350 }, false);
+ flushJS();
+ expect(styleOf(harness.result.animatedStyle).height).toBe(400);
+ expect(harness.input.onDismiss).not.toHaveBeenCalled();
+ expect(runtime.durations.every((duration) => duration === 0)).toBe(true);
+ });
+
+ it('rejects late dismissal from an earlier gesture or an unmounted sheet', () => {
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 350 });
+ gesture.finalize({ translationY: 350 }, true);
+ gesture.begin({ translationY: 0 });
+ flushJS();
+ expect(harness.input.onDismiss).not.toHaveBeenCalled();
+ gesture.finalize({ translationY: 0 }, true);
+ act(() => root.render(null));
+ flushJS();
+ expect(harness.input.onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('a header tap during snap animation preserves the last release destination', () => {
+ runtime.deferAnimations = true;
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -250 });
+ gesture.finalize({ translationY: -250 }, true);
+ expect(harness.input.onSnapChange).not.toHaveBeenCalled();
+ gesture.begin({ translationY: 0 });
+ gesture.finalize({ translationY: 0 }, false);
+ expect(styleOf(harness.result.animatedStyle).height).toBe(700);
+ expect(harness.input.onDismiss).not.toHaveBeenCalled();
+ });
+
+ it.each(['rotation', 'reduced motion'])('preserves and reports a release interrupted by %s', (change) => {
+ runtime.deferAnimations = true;
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -250 });
+ gesture.finalize({ translationY: -250 }, true);
+ if (change === 'rotation') harness.input.heights = { half: 300, full: 500 };
+ else runtime.reduceMotion = true;
+ harness.rerender();
+ expect(styleOf(harness.result.animatedStyle).height).toBe(harness.input.heights.full);
+ flushJS();
+ expect(harness.input.onSnapChange).toHaveBeenCalledExactlyOnceWith('full');
+ });
+
+ it('geometry queued on JS does not overwrite a newly started UI drag', () => {
+ const harness = mountSheet();
+ runtime.deferUI = true;
+ harness.input.heights = { half: 300, full: 500 };
+ harness.rerender();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -50 });
+ for (const job of runtime.ui.splice(0)) job();
+ expect(styleOf(harness.result.animatedStyle).height).toBe(450);
+ });
+
+ it.each(['UI delivery', 'React commit'])('ignores an old snap acknowledgement delayed until %s', (delay) => {
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -250 });
+ gesture.finalize({ translationY: -250 }, true);
+ flushJS();
+ runtime.deferUI = true;
+ if (delay === 'UI delivery') {
+ harness.input.snap = 'full';
+ harness.rerender();
+ }
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 300 });
+ gesture.finalize({ translationY: 300 }, true);
+ if (delay === 'React commit') {
+ harness.input.snap = 'full';
+ harness.rerender();
+ }
+ for (const job of runtime.ui.splice(0)) job();
+ expect(styleOf(harness.result.animatedStyle).height).toBe(400);
+ flushJS();
+ expect(harness.input.onSnapChange).toHaveBeenLastCalledWith('half');
+ });
+
+ it('reports a return to half even while the earlier full notification has not committed', () => {
+ const harness = mountSheet();
+ const gesture = gestureOf(harness.result.gesture);
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: -250 });
+ gesture.finalize({ translationY: -250 }, true);
+ flushJS();
+ gesture.begin({ translationY: 0 });
+ gesture.update({ translationY: 300 });
+ gesture.finalize({ translationY: 300 }, true);
+ flushJS();
+ expect(harness.input.onSnapChange).toHaveBeenNthCalledWith(1, 'full');
+ expect(harness.input.onSnapChange).toHaveBeenNthCalledWith(2, 'half');
+ });
+});
diff --git a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
index 194ab1f476..36dd67bf49 100644
--- a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
+++ b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
@@ -6,6 +6,16 @@ import { buildComposerRichInputHtml } from '@/session/composerRichInputHtml';
import { parseComposerWebMessage } from '@/session/composerRichInputProtocol';
describe('mobile composer rich input HTML', () => {
+ it('animates a native frame that fills the horizontal input row, preserving the WebView command ref', () => {
+ const source = readFileSync(resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'), 'utf8');
+ const frame = source.slice(source.indexOf('frame: {'), source.indexOf('webView: {'));
+ expect(frame).toContain('flex: 1');
+ expect(frame).toContain('minWidth: 0');
+ expect(source).toContain('<Animated.View style={[styles.frame, heightStyle');
+ expect(source).not.toContain('createAnimatedComponent(WebView)');
+ expect(source).toContain('containerStyle={styles.webView}');
+ });
+
const html = buildComposerRichInputHtml({
accessibilityLabel: '输入消息',
document: { version: 1, nodes: [{ type: 'quote', quote: { text: '<quoted>' } }] },
@@ -24,6 +34,12 @@ describe('mobile composer rich input HTML', () => {
});
it('ships an offline contenteditable protocol with atom deletion and caret placement', () => {
+ // The editor scrollport follows UI-driven WebView resizing without waiting
+ // for a setConfig message, while scrollHeight still reports natural content.
+ expect(html).toContain('max-height: min(var(--max-height), 100vh)');
+ expect(html).toContain('overflow-y: auto');
+ expect(html).toContain('root.scrollHeight');
+ expect(html).not.toContain('height: 100vh;');
expect(html).toContain('contentEditable');
expect(html).toContain("event.key === 'Backspace'");
expect(html).toContain('placeCaretAroundAtom(atom, event.clientX)');
@@ -269,6 +285,7 @@ describe('mobile composer rich input HTML', () => {
cindyComposer?: {
applyDocument(value: unknown, focusAfter?: boolean): void;
commitPaste(requestId: string, nodes: unknown[]): void;
+ setConfig(value: { maxHeight: number }): void;
};
getSelection(): typeof selection;
} = {
@@ -282,12 +299,14 @@ describe('mobile composer rich input HTML', () => {
},
};
+ let onResize = () => {};
runInNewContext(
`Array.prototype.flatMap = undefined;\n${script}`,
{
document: documentStub,
Node: { ELEMENT_NODE: 1, TEXT_NODE: 3 },
ResizeObserver: class {
+ constructor(callback: () => void) { onResize = callback; }
observe() {}
},
window: windowStub,
@@ -296,6 +315,19 @@ describe('mobile composer rich input HTML', () => {
expect(children).toHaveLength(1);
expect(children[0]).toMatchObject({ nodeType: 3, nodeValue: 'hello' });
expect(messages).toContainEqual({ type: 'ready' });
+ // A long draft's scrollport resizes on every drag frame; unchanged content
+ // measurements must not cross the WebView bridge again on those frames.
+ root.scrollHeight = 500;
+ const beforeResize = messages.length;
+ for (let frame = 0; frame < 100; frame += 1) onResize();
+ expect(messages.slice(beforeResize)).toEqual([{ type: 'height', height: 264 }]);
+ windowStub.cindyComposer?.setConfig({ maxHeight: 400 });
+ expect(messages.at(-1)).toEqual({ type: 'height', height: 400 });
+ root.scrollHeight = 80;
+ const beforeContentShrink = messages.length;
+ onResize();
+ onResize();
+ expect(messages.slice(beforeContentShrink)).toEqual([{ type: 'height', height: 80 }]);
children[0].nodeValue = 'hello world';
listeners.get('input')?.();
expect(messages).toContainEqual({
@@ -452,9 +484,10 @@ describe('mobile composer rich input HTML', () => {
'utf8',
).replace(/\r\n/g, '\n');
const overlayStart = screenSource.indexOf('const renderComposerInputOverlay = ');
+ expect(screenSource.indexOf('// 听写期间只滚动覆盖层', overlayStart)).toBeGreaterThan(overlayStart);
const overlaySource = screenSource.slice(
overlayStart,
- screenSource.indexOf('const measureSendButtonTarget', overlayStart),
+ screenSource.indexOf('// 听写期间只滚动覆盖层', overlayStart),
);
expect(overlaySource).toContain('onPressIn={handleComposerInputPressIn}');
diff --git a/apps/mobile/src/__tests__/contextSheetExpoGo.test.tsx b/apps/mobile/src/__tests__/contextSheetExpoGo.test.tsx
new file mode 100644
index 0000000000..ed03c409b7
--- /dev/null
+++ b/apps/mobile/src/__tests__/contextSheetExpoGo.test.tsx
@@ -0,0 +1,108 @@
+// @vitest-environment jsdom
+import { act, createElement, useRef } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useContextSheetDrag, type UseContextSheetDragInput } from '@/session/useContextSheetDrag';
+
+const runtime = vi.hoisted(() => ({ animationHeight: undefined as number | undefined, reduceMotion: false, durations: [] as number[] }));
+vi.mock('expo-constants', () => ({
+ default: { executionEnvironment: 'storeClient' }, ExecutionEnvironment: { StoreClient: 'storeClient' },
+}));
+vi.mock('react-native', () => ({ PanResponder: { create: (handlers: unknown) => ({ panHandlers: handlers }) } }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => runtime.reduceMotion }));
+vi.mock('@/theme', () => ({ motionDuration: { fast: 180 }, motionEasing: { move: [0, 0, 1, 1] } }));
+vi.mock('@/platform/gestureHandler', () => ({ Gesture: { Pan: () => {
+ const gesture = { activeOffsetY: () => gesture, failOffsetX: () => gesture, onBegin: () => gesture, onUpdate: () => gesture, onFinalize: () => gesture };
+ return gesture;
+} } }));
+vi.mock('react-native-reanimated', () => ({
+ useSharedValue: (value: unknown) => useRef({ value }).current,
+ useAnimatedStyle: (calculate: () => unknown) => ({ get current() { return calculate(); } }),
+ runOnJS: (fn: unknown) => fn,
+ runOnUI: (fn: unknown) => fn,
+ cancelAnimation: vi.fn(),
+ withTiming: (value: number, config: { duration: number }) => {
+ runtime.durations.push(config.duration);
+ return runtime.animationHeight ?? value;
+ },
+ Easing: { bezier: vi.fn() },
+}));
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root;
+beforeEach(() => {
+ runtime.animationHeight = undefined;
+ runtime.reduceMotion = false;
+ runtime.durations = [];
+ root = createRoot(document.createElement('div'));
+});
+afterEach(() => act(() => root.unmount()));
+
+function mountSheet() {
+ const input: UseContextSheetDragInput = {
+ heights: { half: 400, full: 700 }, snap: 'half', onSnapChange: vi.fn(), onDismiss: vi.fn(),
+ };
+ let result: ReturnType<typeof useContextSheetDrag>;
+ function Harness() { result = useContextSheetDrag(input); return null; }
+ const rerender = () => act(() => root.render(createElement(Harness)));
+ rerender();
+ const handlers = () => result!.panHandlers as unknown as {
+ onPanResponderGrant(): void;
+ onPanResponderMove(event: unknown, gesture: { dy: number }): void;
+ onPanResponderRelease(): void;
+ onPanResponderTerminate(): void;
+ };
+ return {
+ input, rerender,
+ get height() { return (result!.animatedStyle as unknown as { current: { height: number } }).current.height; },
+ begin: () => handlers().onPanResponderGrant(),
+ move: (dy: number) => handlers().onPanResponderMove({}, { dy }),
+ release: () => handlers().onPanResponderRelease(),
+ cancel: () => handlers().onPanResponderTerminate(),
+ };
+}
+
+describe('Expo Go sheet release boundary', () => {
+ it.each(['tap', 'micro move', 'return to start', 'cancel'])('preserves an external expansion during %s', (event) => {
+ const sheet = mountSheet();
+ runtime.animationHeight = 450; // External half -> full animation has not reached its destination.
+ sheet.input.snap = 'full';
+ sheet.rerender();
+ runtime.animationHeight = undefined;
+ expect(sheet.height).toBe(450);
+ sheet.begin();
+ if (event === 'micro move') sheet.move(2);
+ if (event === 'return to start') { sheet.move(-20); sheet.move(0); }
+ if (event === 'cancel') { sheet.move(300); sheet.cancel(); }
+ else sheet.release();
+ expect(sheet.height).toBe(700);
+ expect(sheet.input.onSnapChange).not.toHaveBeenCalled();
+ expect(sheet.input.onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('retains a release before React commits it, then still supports half and dismiss', () => {
+ const sheet = mountSheet();
+ sheet.begin(); sheet.move(-250); sheet.release();
+ expect(sheet.input.onSnapChange).toHaveBeenCalledExactlyOnceWith('full');
+ expect(sheet.input.snap).toBe('half'); // Parent acknowledgement is pending.
+ sheet.begin(); sheet.move(300); sheet.cancel();
+ expect(sheet.height).toBe(700);
+ expect(sheet.input.onSnapChange).toHaveBeenCalledTimes(1);
+ sheet.begin(); sheet.move(300); sheet.release();
+ expect(sheet.input.onSnapChange).toHaveBeenLastCalledWith('half');
+ sheet.begin(); sheet.move(350); sheet.release();
+ expect(sheet.input.onDismiss).toHaveBeenCalledOnce();
+ });
+
+ it('restores the release target with new geometry and reduced motion', () => {
+ runtime.reduceMotion = true;
+ const sheet = mountSheet();
+ sheet.begin(); sheet.move(-250); sheet.release();
+ sheet.begin(); sheet.move(100);
+ sheet.input.heights = { half: 300, full: 500 };
+ sheet.rerender();
+ sheet.cancel();
+ expect(sheet.height).toBe(500);
+ expect(runtime.durations.every(duration => duration === 0)).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
index c5432f7563..5cacc06924 100644
--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
@@ -304,7 +304,8 @@ describe('native e2e environment', () => {
);
expect(sessionScreen).toContain('const latestDocument = latestDraft.trim()');
expect(sessionScreen).toContain('readCurrentDraft: () => draftRef.current');
- expect(sessionScreen).toContain('onDraftChanged: setComposerDraft');
+ expect(sessionScreen).toContain('onDraftChanged: writeVoiceDraft');
+ expect(sessionScreen).toContain('useComposerVoiceDraftWriter(sessionId, setComposerDraft)');
expect(sessionScreen).toContain('createMobileVoiceControllerSession({');
expect(sessionScreen).not.toContain('await sendLatest({ draftOverride: latestDraft });');
});
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 223f29cfd3..48dfee5969 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -1588,7 +1588,8 @@ describe('new session composer surface', () => {
expect(newComposerSource).toContain('inputTestID="newSession.firstMessageInput"');
expect(newComposerSource).toContain('autoFocus={visualFocusComposer}');
expect(newComposerSource).toContain('maxHeight={composerResize.inputMaxHeight}');
- expect(newComposerSource).toContain('inputFrameHeight={composerResize.frameHeight}');
+ expect(newComposerSource).toContain('inputFrameAnimatedStyle={composerResize.frameStyle}');
+ expect(newSource).toContain('gesture={composerResize.gesture}');
expect(newComposerSource).toContain('resizeHandle={composerCardActive ? renderComposerResizeHandle() : null}');
expect(newComposerSource).toContain('cardActive={composerCardActive}');
expect(newComposerSource).toContain('toolbar={renderComposerToolbar()}');
@@ -2254,7 +2255,7 @@ describe('submit guard catalog wiring (source locks)', () => {
sessionSource.indexOf('initial={goalRestoreForSession}') + 300,
);
expect(viewCall).toContain('initial={goalRestoreForSession}');
- expect(viewCall).toContain('initialObjective={goalRestoreForSession ? undefined : (draft.trim() || undefined)}');
+ expect(viewCall).toContain('initialObjective={goalRestoreForSession ? undefined : (draftRef.current.trim() || undefined)}');
});
it('goal 接回载荷按 sessionId 换代清理:切任务不残留旧 objective/limits(codex P2)', () => {
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 79e5ff1261..bb5ec9eca1 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -7,6 +7,36 @@ const readTextLf = (...args: Parameters<typeof readFileSync>): string =>
String(readFileSync(...args)).replace(/\r\n/g, '\n');
describe('mobile session composer desktop-first surface', () => {
+ it('keeps draft subscriptions and the recording timer outside the task render boundary', () => {
+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+ const paletteStart = source.indexOf('function SessionComposerPalette(');
+ const inputStart = source.indexOf('function SessionComposerInput(');
+ const inputEnd = source.indexOf('function SessionSearchSheet(', inputStart);
+ expect(paletteStart).toBeGreaterThan(source.indexOf('export default function SessionScreen()'));
+ const task = source.slice(source.indexOf('export default function SessionScreen()'), paletteStart);
+ const input = source.slice(inputStart, inputEnd);
+ expect(task).not.toContain('useSyncExternalStore(source.subscribe');
+ expect(task).not.toContain('composerDraftSource.subscribe');
+ expect(task).not.toContain('useMobileVoiceRecordingTimer(');
+ expect(task).toContain('<SessionComposerInput');
+ expect(task).toContain('<SessionComposerPalette');
+ expect(task).toContain('source={composerDraftSource}');
+ expect(input).toContain('useSyncExternalStore(source.subscribe, source.getSnapshot)');
+ expect(input).toContain('useMobileVoiceRecordingTimer(');
+ expect(task).toContain('const commandsAtSend = slashCommandsRef.current;');
+ expect(task).toContain('remoteCommands: commandsAtSend,');
+ // Dispatch and the keyed palette must receive a fresh ref synchronously;
+ // passive unmount cleanup leaves a window for the old command list to leak.
+ expect(task).toContain('const slashCommandsRef = useMemo<RefObject<MobileSlashCommand[]>>(\n'
+ + ' () => ({ current: [] }),\n'
+ + ' [activeComposerDraftScopeKey],\n'
+ + ' );');
+ expect(task).toContain('<SessionComposerPalette\n'
+ + ' key={activeComposerDraftScopeKey}\n'
+ + ' source={composerDraftSource}\n'
+ + ' commandsRef={slashCommandsRef}');
+ });
+
it('keeps local send and queue activity out of message grouping', () => {
const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
expect(source).toContain('const isMessageListStreaming = remoteSessionRunning || currentTurnStreaming;');
@@ -51,10 +81,10 @@ describe('mobile session composer desktop-first surface', () => {
const trailingActionsEnd = source.indexOf('const resumeQueue = () => {', trailingActionsStart);
const trailingActionsSource = source.slice(trailingActionsStart, trailingActionsEnd);
const voiceButtonStart = source.indexOf('const renderComposerVoiceButton = (buttonStyle?: StyleProp<ViewStyle>) => (');
- const voiceButtonEnd = source.indexOf('const removeRemoteFileAttachment = useCallback', voiceButtonStart);
+ const voiceButtonEnd = source.indexOf('const renderComposerAttachmentButton = () => (', voiceButtonStart);
const voiceButtonSource = source.slice(voiceButtonStart, voiceButtonEnd);
- const floatingVoiceIndex = composerInputSource.indexOf('floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}');
- const sendIndex = composerInputSource.indexOf('trailing={composerCardActive ? null : renderComposerTrailingActions()}');
+ const floatingVoiceIndex = composerInputSource.indexOf('floatingVoiceButton={voiceUiAvailable ? controls.voiceButton : undefined}');
+ const sendIndex = composerInputSource.indexOf('trailing={composerCardActive ? null : controls.trailing}');
const composerSurfaceStart = source.indexOf('composerSurface: {');
// composerOverlayPanel 已随「模型下拉改 ModelPickerSheet 浮窗」删除,锚到下一个样式键。
const composerSurfaceEnd = source.indexOf('composerSurfaceCompact:', composerSurfaceStart);
@@ -124,8 +154,13 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('<Scan color={colors.textPrimary}');
expect(source).toContain('<Folder color={colors.textPrimary}');
expect(composerInputSource).toContain('cardActive={composerCardActive}');
- expect(composerInputSource).toContain('leading={renderComposerCompactLeading()}');
+ expect(composerInputSource).toContain('leading={controls.leading}');
expect(source).toContain('const renderComposerCompactLeading = () => (');
+ expect(source).toContain('leading: renderComposerCompactLeading()');
+ expect(source).toContain('toolbar: renderComposerToolbar()');
+ expect(source).toContain('trailing: renderComposerTrailingActions()');
+ expect(source).toContain('gesture={composerResize.gesture}');
+ expect(source).toContain('<GestureDetector gesture={composerResize.scrollGesture}>');
expect(source).not.toContain('styles.composerCompactAttachmentSlot');
expect(source).toContain('styles.composerCompactAttachmentHit');
expect(source).not.toContain('styles.composerCompactAttachmentHitArea');
@@ -137,11 +172,11 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).not.toContain('marginVertical: (MOBILE_COMPOSER_CONTROL_SIZE - MOBILE_COMPOSER_MIN_TOUCH_TARGET) / 2');
expect(source).not.toContain('marginHorizontal: (MOBILE_COMPOSER_CONTROL_SIZE - MOBILE_COMPOSER_MIN_TOUCH_TARGET) / 2');
expect(source).not.toContain('left: (MOBILE_COMPOSER_CONTROL_SIZE - MOBILE_COMPOSER_MIN_TOUCH_TARGET) / 2');
- expect(composerInputSource).toContain('toolbar={renderComposerToolbar()}');
+ expect(composerInputSource).toContain('toolbar={controls.toolbar}');
expect(source).toContain('const renderComposerToolbar = () => (');
expect(attachmentButtonSource).toContain('<Plus');
expect(source).toContain('<Mic color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />');
- expect(composerInputSource).toContain('trailing={composerCardActive ? null : renderComposerTrailingActions()}');
+ expect(composerInputSource).toContain('trailing={composerCardActive ? null : controls.trailing}');
expect(trailingActionsSource).toContain('<PaperPlaneIcon');
expect(trailingActionsSource).toContain('color={composerSendDisabled ? colors.textSecondary : colors.ctaText}');
expect(source).toContain('const composerCardActive = (canUseComposer && composerFocused)');
@@ -316,11 +351,9 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('const composerResize = useComposerResize({');
expect(source).toContain('const composerInputVisibleHeight = composerResize.visibleContentHeight;');
expect(source).toContain('const composerInputScrollEnabled = composerResize.scrollEnabled;');
- expect(source).toContain('const composerShellHasScrollableContent = attachments.length > 0');
- expect(source).toContain('const composerScrollEnabled = nativeShellLayout.composerScrollEnabled');
- // 外壳滚动必须仅在真有可滚内容时启用,且 grabber touch-down 通过
- // setNativeProps 同步关闸(绝不能 setState——重页面 re-render 会阻塞
- // JS 线程,拖拽 move 事件被合并延后,位移在 grant 重置前全部丢失)。
+ expect(source).toContain('const composerShellHasScrollableContent = attachmentCount > 0');
+ expect(source).toContain('const composerScrollEnabled = (nativeShellLayout.composerScrollEnabled');
+ // Scroll ownership is native in installed apps; retain Expo Go's JS fallback.
expect(source).toContain('&& composerShellHasScrollableContent;');
expect(source).not.toContain('&& (!composerInputScrollEnabled || composerShellHasScrollableContent);');
expect(source).toContain('const handleGrabberTouchActiveChange = useCallback((active: boolean) => {');
@@ -336,7 +369,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('scrollEnabled={composerInputScrollEnabled}');
expect(source.match(/scrollEnabled={composerInputScrollEnabled}/g)?.length ?? 0).toBeGreaterThanOrEqual(2);
expect(composerInputSource).toContain('maxHeight={composerResize.inputMaxHeight}');
- expect(composerInputSource).toContain('inputFrameHeight={composerResize.frameHeight}');
+ expect(composerInputSource).toContain('inputFrameAnimatedStyle={composerResize.frameStyle}');
expect(composerInputSource).toContain('resizeHandle={composerCardActive ? renderComposerResizeHandle() : null}');
expect(sharedSource).toContain('{ maxHeight },');
expect(source).not.toContain('{ height: composerInputVisibleHeight');
@@ -360,9 +393,10 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('modelSummary: [modelLabel, effortLabel].filter(Boolean).join');
expect(source).toContain('const COMPOSER_CONTROL_HIT_SLOP = { bottom: 8, left: 8, right: 8, top: 8 };');
expect(source.match(/hitSlop={COMPOSER_CONTROL_HIT_SLOP}/g)?.length ?? 0).toBeGreaterThanOrEqual(3);
- expect(source).toContain('const composerHasText = draft.trim().length > 0;');
expect(source).toContain('const composerQuoteCount = composerDocumentQuotes(composerDocument).length;');
- expect(source).toContain('const composerHasPayload = composerHasText || attachments.length > 0 || pendingUploads.length > 0 || composerQuoteCount > 0;');
+ expect(source).toContain('attachmentCount: attachmentCount + pendingUploadCount,');
+ expect(source).toContain('quoteCount: composerQuoteCount,');
+ expect(source).toContain('draftText: draft,');
expect(source).toContain('const composerShowSendButton = composerLayout.send.visible || voiceStartPending;');
expect(source).not.toContain('composerLayout.send.visible && (!voiceIsListening || composerHasPayload)');
expect(source).toContain('const latestDocument = latestDraft.trim()');
@@ -494,7 +528,7 @@ describe('mobile session composer desktop-first surface', () => {
finishVoiceSource.indexOf('const latestDraft = await controller.stop();'),
);
expect(finishVoiceSource).toContain('voiceStopInFlightRef.current = false;');
- expect(composerInputSource).toContain('floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}');
+ expect(composerInputSource).toContain('floatingVoiceButton={voiceUiAvailable ? controls.voiceButton : undefined}');
expect(composerInputSource).not.toContain('floatingVoiceButtonStyle=');
expect(composerInputSource).toContain('voicePlacement={composerVoicePlacement}');
expect(sharedSource).toContain('voicePlacement?.inline || voicePlacement?.floating');
@@ -702,7 +736,8 @@ describe('mobile session composer desktop-first surface', () => {
+ " startupSeq = voiceStartupSeqRef.current + 1;",
);
expect(voiceSource).toContain('voiceStartupInFlightRef.current = false;');
- expect(voiceSource).toContain('onDraftChanged: setComposerDraft');
+ expect(voiceSource).toContain('onDraftChanged: writeVoiceDraft');
+ expect(source).toContain('useComposerVoiceDraftWriter(sessionId, setComposerDraft)');
expect(voiceSource).toContain('isMobileRealtimeAudioAvailable()');
expect(voiceSource.indexOf('isMobileRealtimeAudioAvailable()')).toBeLessThan(
voiceSource.indexOf('resolveMobileVoiceRecordingPermission({'),
diff --git a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
index 080fa1d73c..1387b9eb11 100644
--- a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
@@ -188,8 +188,8 @@ describe('mobile session header desktop-first surface', () => {
expect(draftScopeEnd).toBeGreaterThan(draftScopeStart);
expect(draftScope).toContain('if (composerDraftStateKey !== activeComposerDraftScopeKey) {');
expect(draftScope).toContain('const nextScope = readImmediateComposerDraftScope(sessionId, routeDraft);');
- expect(draftScope).toContain('setComposerDocumentState(nextScope.document);');
- expect(draftScope).toContain('setDraft(nextDraft);');
+ expect(draftScope).toContain('setComposerDraftSource(createComposerDraftSource(nextScope.document));');
+ expect(draftScope).toContain('draftRef.current = nextDraft;');
expect(draftScope).toContain('setComposerDraftHydrated(false);');
expect(draftScope).toContain('appliedRouteDraftRef.current = null;');
expect(draftScope).toContain('composerDocumentRef.current = nextScope.document;');
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
index af83d01261..3c3153641c 100644
--- a/apps/mobile/src/session/ComposerRichInput.tsx
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -1,6 +1,7 @@
import { forwardRef, useCallback, useEffect, useMemo, useRef } from 'react';
import { Platform, StyleSheet } from 'react-native';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
+import Animated, { useAnimatedStyle, type SharedValue } from 'react-native-reanimated';
import { File, Paths } from 'expo-file-system';
import * as Clipboard from 'expo-clipboard';
import {
@@ -33,6 +34,8 @@ export interface ComposerRichInputProps {
document: ComposerDocument;
editable?: boolean;
height: number;
+ /** Resize follows the UI thread without an RN render or WebView reload. */
+ animatedHeight?: SharedValue<number>;
hidden?: boolean;
maxHeight: number;
onBlur?: () => void;
@@ -60,6 +63,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
function ComposerRichInput({
accessibilityHint,
accessibilityLabel,
+ animatedHeight,
document,
editable = true,
height,
@@ -376,7 +380,11 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
}
}, [applyDocument, commitPlainTextPaste, focusEditor, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage]);
+ const heightStyle = useAnimatedStyle(() => ({ height: animatedHeight?.value ?? height }));
return (
+ // WebView's imperative ref is a command handle, not a Fabric host ref.
+ // Animate its native View container and let the WebView fill that frame.
+ <Animated.View style={[styles.frame, heightStyle, { opacity: hidden ? 0 : 1 }]}>
<WebView
ref={webViewRef}
accessibilityHint={accessibilityHint}
@@ -404,10 +412,12 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
scrollEnabled={false}
setSupportMultipleWindows={false}
source={{ html }}
- style={[styles.webView, { height, opacity: hidden ? 0 : 1 }]}
+ containerStyle={styles.webView}
+ style={styles.webView}
testID={testID}
textInteractionEnabled
/>
+ </Animated.View>
);
},
);
@@ -428,11 +438,13 @@ async function deleteComposerPastedImageUris(uris: readonly string[]): Promise<v
}
const styles = StyleSheet.create({
+ frame: {
+ flex: 1,
+ minWidth: 0,
+ minHeight: COMPOSER_SINGLE_LINE_HEIGHT,
+ },
webView: {
backgroundColor: 'transparent',
- // react-native-webview defaults the native child to flex: 1. Override it
- // because this composer drives the child with an explicit measured height.
- flex: 0,
- minHeight: COMPOSER_SINGLE_LINE_HEIGHT,
+ flex: 1,
},
});
diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsx
index 4fb72bebff..51a5f1f6b0 100644
--- a/apps/mobile/src/session/MobileComposerInputRow.tsx
+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx
@@ -11,6 +11,9 @@ import {
type ViewStyle,
} from 'react-native';
import { TextInput } from '@/components/AppText';
+import Reanimated, { type useAnimatedStyle } from 'react-native-reanimated';
+import { GestureDetector } from '@/platform/gestureHandler';
+import type { PanGesture } from 'react-native-gesture-handler';
import Constants, { ExecutionEnvironment } from 'expo-constants';
import { TextInputWrapper, type PasteEventPayload } from 'expo-paste-input';
import { Mic } from 'lucide-react-native';
@@ -109,6 +112,7 @@ export interface MobileComposerInputRowProps {
* null / undefined 走内容自动增长(现状行为)。
*/
inputFrameHeight?: number | Animated.Value | null;
+ inputFrameAnimatedStyle?: ReturnType<typeof useAnimatedStyle>;
/**
* 输入区(inputFrame)的最小高度。给语音听写用:听写期间「点输入区停止听写」的命中层
* 盖在 inputFrame 上,而单行听写时 inputFrame 只有 28pt,不满足触控目标 44pt;
@@ -188,6 +192,7 @@ export function MobileComposerInputRow({
floatingVoiceButton,
floatingVoiceButtonStyle,
inputFrameHeight,
+ inputFrameAnimatedStyle,
inputFrameMinHeight,
inputElement,
inputOverlay,
@@ -297,13 +302,14 @@ export function MobileComposerInputRow({
]}
>
{cardLayout ? null : leading}
- <Animated.View
+ <Reanimated.View
style={[
styles.inputFrame,
// 收起单行与 34pt + 并排:输入盒在行内居中。
geometricSingleLine && inputFrameMinHeight == null && styles.inputFrameSingleLine,
inputFrameMinHeight != null && { minHeight: inputFrameMinHeight },
resolvedInputFrameHeight != null && { height: resolvedInputFrameHeight },
+ inputFrameAnimatedStyle,
]}
>
{inputElement ?? (onPasteImages && !isExpoGo ? (
@@ -312,7 +318,7 @@ export function MobileComposerInputRow({
</TextInputWrapper>
) : textInputElement)}
{inputOverlay}
- </Animated.View>
+ </Reanimated.View>
{cardLayout ? null : trailing}
</View>
{cardLayout && toolbar != null ? (
@@ -384,6 +390,7 @@ export interface ComposerResizeGrabberProps {
* ScrollView 滚动,防止原生滚动抢走拖拽手势)。
*/
panHandlers: GestureResponderHandlers & Pick<ViewProps, 'onTouchStart' | 'onTouchEnd' | 'onTouchCancel'>;
+ gesture: PanGesture;
/** 不可见时淡出且不响应触摸,布局位置保持不变(避免出现/消失跳变)。 */
visible: boolean;
testID?: string;
@@ -396,7 +403,7 @@ export interface ComposerResizeGrabberProps {
* 不会引起输入行高度跳变。触摸命中区是顶部居中的一段窄条,比可见的横条大得多,
* 行两端保持穿透,不与左右按钮抢触摸。
*/
-export function ComposerResizeGrabber({ onAdjust, panHandlers, visible, testID }: ComposerResizeGrabberProps) {
+export function ComposerResizeGrabber({ onAdjust, panHandlers, gesture, visible, testID }: ComposerResizeGrabberProps) {
const { t } = useTranslation();
const styles = useThemedStyles(makeMobileComposerInputRowStyles);
const opacity = useRef(new Animated.Value(visible ? 1 : 0)).current;
@@ -417,7 +424,9 @@ export function ComposerResizeGrabber({ onAdjust, panHandlers, visible, testID }
pointerEvents={visible ? 'box-none' : 'none'}
style={[styles.resizeGrabberTouch, { opacity }]}
>
+ <GestureDetector gesture={gesture}>
<View
+ collapsable={false}
accessibilityActions={[
{ label: t('composer.input.resize.increaseHeight'), name: 'increment' },
{ label: t('composer.input.resize.decreaseHeight'), name: 'decrement' },
@@ -434,6 +443,7 @@ export function ComposerResizeGrabber({ onAdjust, panHandlers, visible, testID }
>
<View style={styles.resizeGrabberBar} />
</View>
+ </GestureDetector>
</Animated.View>
);
}
diff --git a/apps/mobile/src/session/SheetModal.tsx b/apps/mobile/src/session/SheetModal.tsx
index b083dd599d..e995c56ff9 100644
--- a/apps/mobile/src/session/SheetModal.tsx
+++ b/apps/mobile/src/session/SheetModal.tsx
@@ -25,6 +25,7 @@ import {
} from 'react-native';
import { useTranslation } from 'react-i18next';
import { BlurBackdrop } from '@/session/BlurBackdrop';
+import { GestureHandlerRootView } from '@/platform/gestureHandler';
import { useModalFadeLifecycle } from '@/session/useModalFadeLifecycle';
import { useThemedStyles, type ThemeColors } from '@/theme';
@@ -118,6 +119,7 @@ export function SheetModal({
transparent
visible={mounted}
>
+ <GestureHandlerRootView style={styles.gestureRoot}>
<Animated.View style={backdropStyle}>
<BlurBackdrop />
<Pressable
@@ -145,12 +147,14 @@ export function SheetModal({
) : (
content
)}
+ </GestureHandlerRootView>
</Modal>
);
}
function makeStyles(colors: ThemeColors) {
return {
+ gestureRoot: { flex: 1 },
backdrop: {
...StyleSheet.absoluteFill,
},
diff --git a/apps/mobile/src/session/SheetSurface.tsx b/apps/mobile/src/session/SheetSurface.tsx
index 9f1847a704..7b8790f6e1 100644
--- a/apps/mobile/src/session/SheetSurface.tsx
+++ b/apps/mobile/src/session/SheetSurface.tsx
@@ -15,7 +15,9 @@
import type { ReactNode, RefObject } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronLeft } from 'lucide-react-native';
-import { Animated, Pressable, ScrollView, View, type StyleProp, type ViewStyle } from 'react-native';
+import { Pressable, ScrollView, View, type StyleProp, type ViewStyle } from 'react-native';
+import Animated from 'react-native-reanimated';
+import { GestureDetector } from '@/platform/gestureHandler';
import { Text } from '@/components/AppText';
import { BlurBackdrop } from '@/session/BlurBackdrop';
import type { ContextSheetSnap, ContextSheetSnapHeights } from '@/session/contextSheetModel';
@@ -85,7 +87,8 @@ export function SheetSurface({
style={[
styles.sheet,
variant === 'tasksheet' && styles.sheetTasksheet,
- { height: drag.animatedHeight, paddingBottom: bottomInset },
+ { paddingBottom: bottomInset },
+ drag.animatedStyle,
]}
testID={testID}
>
@@ -93,7 +96,8 @@ export function SheetSurface({
intensity={32}
overlayColor={variant === 'tasksheet' ? colors.sheetSurface : colors.surfaceGlassPanel}
/>
- <View style={styles.dragZone} {...drag.panHandlers}>
+ <GestureDetector gesture={drag.gesture}>
+ <View collapsable={false} style={styles.dragZone} {...drag.panHandlers}>
<SheetGrabber variant={variant} />
<View style={styles.header}>
{onBack ? (
@@ -116,12 +120,12 @@ export function SheetSurface({
{headerTrailing ?? <View style={styles.headerSpacer} />}
</View>
</View>
+ </GestureDetector>
{pinnedTop ? <View style={styles.pinnedTop}>{pinnedTop}</View> : null}
<ScrollView
contentContainerStyle={styles.contentScrollContent}
keyboardShouldPersistTaps="handled"
ref={scrollRef}
- scrollEnabled={!drag.dragging}
style={styles.contentScroll}
testID={testID ? `${testID}.scroll` : undefined}
>
diff --git a/apps/mobile/src/session/composerDraftSource.ts b/apps/mobile/src/session/composerDraftSource.ts
new file mode 100644
index 0000000000..d39bcbf839
--- /dev/null
+++ b/apps/mobile/src/session/composerDraftSource.ts
@@ -0,0 +1,48 @@
+import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';
+import { composerDocumentProjectedText, type ComposerDocument } from '@/session/composerDocument';
+
+export interface ComposerDraftSnapshot {
+ document: ComposerDocument;
+ draft: string;
+}
+
+/**
+ * One mounted task's editor value. Only input/palette components subscribe.
+ * Persistence, queue-edit exceptions and send snapshots remain with their
+ * existing owner; this source adds no disk cache or cross-task lifetime.
+ */
+export function createComposerDraftSource(document: ComposerDocument) {
+ let snapshot: ComposerDraftSnapshot = { document, draft: composerDocumentProjectedText(document) };
+ const listeners = new Set<() => void>();
+ return {
+ getSnapshot: () => snapshot,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ },
+ setDocument: (next: ComposerDocument) => {
+ if (snapshot.document === next) return;
+ snapshot = { document: next, draft: composerDocumentProjectedText(next) };
+ for (const listener of listeners) listener();
+ },
+ };
+}
+
+export type ComposerDraftSource = ReturnType<typeof createComposerDraftSource>;
+
+/** A running voice controller follows source replacement within its task only. */
+export function useComposerVoiceDraftWriter(sessionId: string, writeDraft: (draft: string) => void) {
+ const owner = useMemo(() => ({ sessionId }), [sessionId]);
+ const latest = useRef<{ owner: typeof owner; writeDraft: typeof writeDraft } | null>(null);
+ latest.current = { owner, writeDraft };
+ useLayoutEffect(() => {
+ latest.current = { owner, writeDraft };
+ return () => {
+ if (latest.current?.owner === owner) latest.current = null;
+ };
+ }, [owner]);
+ return useCallback((draft: string) => {
+ const current = latest.current;
+ if (current?.owner === owner) current.writeDraft(draft);
+ }, [owner]);
+}
diff --git a/apps/mobile/src/session/composerResize.ts b/apps/mobile/src/session/composerResize.ts
index 736051845f..92e78630e3 100644
--- a/apps/mobile/src/session/composerResize.ts
+++ b/apps/mobile/src/session/composerResize.ts
@@ -108,6 +108,7 @@ export interface ApplyComposerResizeDragInput {
}
export function applyComposerResizeDrag(input: ApplyComposerResizeDragInput): number {
+ 'worklet';
const bounds = normalizeBounds(input.bounds);
return clamp(
Math.round(input.startContentHeight - input.translationY),
@@ -295,6 +296,7 @@ export function computeComposerResizeBounds(
}
function normalizeBounds(bounds: ComposerResizeBounds): ComposerResizeBounds {
+ 'worklet';
const minContentHeight = Math.max(1, Math.round(bounds.minContentHeight));
return {
minContentHeight,
@@ -311,5 +313,6 @@ function normalizeNonNegativeDimension(value: number, fallback: number): number
}
function clamp(value: number, min: number, max: number): number {
+ 'worklet';
return Math.min(Math.max(value, min), max);
}
diff --git a/apps/mobile/src/session/composerRichInputHtml.ts b/apps/mobile/src/session/composerRichInputHtml.ts
index dcc96e5149..67d7c8495e 100644
--- a/apps/mobile/src/session/composerRichInputHtml.ts
+++ b/apps/mobile/src/session/composerRichInputHtml.ts
@@ -58,7 +58,9 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str
#editor {
color: var(--text); caret-color: var(--focus);
font-size: ${COMPOSER_TEXT_FONT_SIZE}px; line-height: ${COMPOSER_TEXT_LINE_HEIGHT}px;
- min-height: ${COMPOSER_SINGLE_LINE_HEIGHT}px; max-height: var(--max-height);
+ /* The native frame sets the viewport on UI, without a JS config roundtrip.
+ Keep natural content height so scrollHeight still measures short drafts. */
+ min-height: ${COMPOSER_SINGLE_LINE_HEIGHT}px; max-height: min(var(--max-height), 100vh);
overflow-y: auto; outline: none;
padding: ${composerTextPadding.top}px ${COMPOSER_TEXT_HORIZONTAL_PADDING}px ${composerTextPadding.bottom}px;
white-space: pre-wrap; overflow-wrap: anywhere; -webkit-user-select: text;
@@ -239,7 +241,14 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str
walk(root, nodes);
return { version: 1, nodes };
};
- const reportHeight = () => post({ type: 'height', height: Math.min(config.maxHeight, Math.max(${COMPOSER_SINGLE_LINE_HEIGHT}, root.scrollHeight)) });
+ let lastReportedHeight = null;
+ const reportHeight = () => {
+ const height = Math.min(config.maxHeight, Math.max(${COMPOSER_SINGLE_LINE_HEIGHT}, root.scrollHeight));
+ // Viewport resizing can notify every frame without changing content height.
+ if (height === lastReportedHeight) return;
+ lastReportedHeight = height;
+ post({ type: 'height', height });
+ };
const notify = () => {
if (applying || composing) return;
const value = readDocument();
diff --git a/apps/mobile/src/session/contextSheetModel.ts b/apps/mobile/src/session/contextSheetModel.ts
index 780e442bd6..3e14abdcd5 100644
--- a/apps/mobile/src/session/contextSheetModel.ts
+++ b/apps/mobile/src/session/contextSheetModel.ts
@@ -57,6 +57,7 @@ export interface ApplyContextSheetDragInput {
/** 拖动跟手:位移换算成面板高度,上限 full;向下允许拖过 half(用于 dismiss 判定)。 */
export function applyContextSheetDrag(input: ApplyContextSheetDragInput): number {
+ 'worklet';
const heights = normalizeHeights(input.heights);
return clamp(Math.round(input.startHeight - input.translationY), 0, heights.full);
}
@@ -74,6 +75,7 @@ export interface SettleContextSheetDragInput {
* 其余情况回 half。half === full(小屏钳住)时只在 full 与 dismiss 之间二选一。
*/
export function settleContextSheetDrag(input: SettleContextSheetDragInput): ContextSheetSettle {
+ 'worklet';
const heights = normalizeHeights(input.heights);
if (input.draggedHeight < heights.half * CONTEXT_SHEET_DISMISS_RATIO) return 'dismiss';
if (heights.full <= heights.half) return 'full';
@@ -82,6 +84,7 @@ export function settleContextSheetDrag(input: SettleContextSheetDragInput): Cont
}
function normalizeHeights(heights: ContextSheetSnapHeights): ContextSheetSnapHeights {
+ 'worklet';
const half = Math.max(1, Math.round(heights.half));
return { half, full: Math.max(half, Math.round(heights.full)) };
}
@@ -95,5 +98,6 @@ function normalizeNonNegativeDimension(value: number | undefined, fallback: numb
}
function clamp(value: number, min: number, max: number): number {
+ 'worklet';
return Math.min(Math.max(value, min), max);
}
diff --git a/apps/mobile/src/session/useComposerResize.ts b/apps/mobile/src/session/useComposerResize.ts
index 9bee2bd881..b1e91d23b4 100644
--- a/apps/mobile/src/session/useComposerResize.ts
+++ b/apps/mobile/src/session/useComposerResize.ts
@@ -1,9 +1,9 @@
-import { useCallback, useMemo, useRef, useState } from 'react';
-import { Animated, PanResponder, type GestureResponderHandlers } from 'react-native';
-import {
- MOBILE_COMPOSER_INPUT_LINE_HEIGHT,
- MOBILE_COMPOSER_INPUT_VERTICAL_PADDING,
-} from '@/session/MobileComposerInputRow';
+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { PanResponder } from 'react-native';
+import Constants, { ExecutionEnvironment } from 'expo-constants';
+import { runOnJS, runOnUI, useAnimatedStyle, useDerivedValue, useSharedValue } from 'react-native-reanimated';
+import { Gesture } from '@/platform/gestureHandler';
+import { COMPOSER_TEXT_LINE_HEIGHT, COMPOSER_TEXT_VERTICAL_PADDING } from '@/session/composerTextMetrics';
import {
COMPOSER_RESIZE_DRAG_ACTIVATION_THRESHOLD,
applyComposerResizeDrag,
@@ -13,226 +13,174 @@ import {
resolveComposerInputHeight,
settleComposerResizeDrag,
shouldDismissComposerOnRelease,
- type ComposerResizeMode,
} from '@/session/composerResize';
-/** grabber 需要挂载的全部触摸 props:PanResponder handlers + 原生触摸监听。 */
-export type ComposerResizeGrabberHandlers = GestureResponderHandlers & {
- onTouchCancel: () => void;
- onTouchEnd: () => void;
- onTouchStart: () => void;
-};
+const isStoreClient = Constants.executionEnvironment === ExecutionEnvironment.StoreClient;
export interface UseComposerResizeInput {
- /** TextInput 上报的内容高度(页面既有 state)。 */
contentHeight: number;
- /** auto 模式的内容高度上限(页面既有 max 计算结果)。 */
autoMaxContentHeight: number;
- /** 窗口高度(useWindowDimensions().height)。 */
windowHeight: number;
- /** 键盘可见高度;收起时传 0。 */
keyboardHeight: number;
- /** 单行内容高度。 */
singleLineContentHeight: number;
- /** composer 除输入区之外占用的高度(状态行、工具行等)。 */
composerChromeHeight: number;
- /**
- * 简洁态(非激活卡片态)时置 true:输入框一律收到单行(下拉收起和点别处
- * 收键盘的结果一致);auto / manual 记忆保留,重新激活后恢复。
- */
collapsed?: boolean;
- /**
- * 松手结算吸附回 auto(把 grabber 拖回单行高度附近)时回调。
- * 页面可借此让输入框 blur、退出聚焦卡片态——「拖到底 = 想收起」。
- */
+ minFrameHeight?: number;
onSnapToAuto?: () => void;
- /**
- * grabber 触摸按下 / 抬手(touch-down 即回调,早于手势认领与 dragging)。
- * 页面用它同步关闭外壳 ScrollView 的原生滚动(setNativeProps 直改原生属性,
- * 不能走 setState——touch-down 触发整页 re-render 会阻塞 JS 线程,move
- * 事件被合并延后,位移在 grant 重置 dx/dy 前就被烧光,拖拽变成「没反应」)。
- */
+ /** Only gesture boundaries cross to JS; never publish per-frame heights. */
onGrabberTouchActiveChange?: (active: boolean) => void;
}
-export interface UseComposerResizeResult {
- /** 拖动进行中(页面可据此暂停外层 ScrollView 滚动)。 */
- dragging: boolean;
- mode: ComposerResizeMode;
- /** 输入区当前应呈现的内容高度(非拖动时的解析结果)。 */
- visibleContentHeight: number;
- /** TextInput 内部滚动开关(激活态恒 true,语义见 ComposerInputHeightModel.scrollEnabled)。 */
- scrollEnabled: boolean;
- /**
- * 传给 MobileComposerInputRow 的 inputFrameHeight:
- * 拖动中是 Animated 值(跟手、不触发 re-render);manual 定高时是数值;auto 时为 null。
- */
- frameHeight: Animated.Value | number | null;
- /** manual / 拖动时传给 TextInput 的 maxHeight,放开到拖拽上限。 */
- inputMaxHeight: number;
- /**
- * 拖拽上限对应的 inputFrame 高度。manual / 拖动时 composer 外层容器的
- * maxHeight 需要放开到「该值 + chrome」,否则输入区拖高后容器被原有
- * 上限钳住、从底部裁剪掉发送按钮等 trailing 行。
- */
- maxFrameHeight: number;
- /** 传给 ComposerResizeGrabber 的手势 handlers(含 grabberTouchActive 触摸监听)。 */
- panHandlers: ComposerResizeGrabberHandlers;
- /** 恢复 auto 自动增长模式。 */
- reset: () => void;
- /**
- * 无障碍步进调高:按一行行高增减输入区高度(VoiceOver / TalkBack 的
- * increment / decrement 动作),语义与拖拽一致(clamp 边界、调到底吸附回 auto)。
- */
- adjustByLine: (direction: 1 | -1) => void;
-}
-
-/**
- * Composer 输入区拖拽调高的手势与状态编排。
- *
- * 拖动期间只更新 Animated.Value(JS 驱动布局高度),不做 per-frame setState,
- * 避免整页 re-render;松手时一次性把结算高度落进 state。高度决策全部走
- * composerResize 纯函数模型。
- */
-export function useComposerResize(input: UseComposerResizeInput): UseComposerResizeResult {
+/** UI-thread resize. React remembers the settled height, not the pointer stream. */
+export function useComposerResize(input: UseComposerResizeInput) {
const [userContentHeight, setUserContentHeight] = useState<number | null>(null);
const [dragging, setDragging] = useState(false);
+ const [completedGesture, setCompletedGesture] = useState(0);
+ const mounted = useRef(true);
+ const latest = useRef(input);
+ latest.current = input;
+ const bounds = computeComposerResizeBounds(input);
+ const model = resolveComposerInputHeight({ ...input, bounds, userContentHeight });
+ const geometry = useSharedValue({ bounds, visibleHeight: model.visibleContentHeight, explicit: input.collapsed === true || model.mode === 'manual', minFrameHeight: input.minFrameHeight ?? 0, autoMaxHeight: input.autoMaxContentHeight });
+ const active = useSharedValue(false);
+ const gestureId = useSharedValue(0);
+ const startHeight = useSharedValue(model.visibleContentHeight);
+ const dragHeight = useSharedValue(model.visibleContentHeight);
+ useLayoutEffect(() => {
+ const nextGeometry = { bounds, visibleHeight: model.visibleContentHeight, explicit: input.collapsed === true || model.mode === 'manual', minFrameHeight: input.minFrameHeight ?? 0, autoMaxHeight: input.autoMaxContentHeight };
+ // Check the generation and publish together on UI: another gesture may
+ // begin between React's commit and delivery of this geometry update.
+ runOnUI((next: typeof nextGeometry, completed: number) => {
+ 'worklet';
+ geometry.value = next;
+ if (completed === gestureId.value) active.value = false;
+ })(nextGeometry, completedGesture);
+ }, [active, bounds.minContentHeight, bounds.maxContentHeight, completedGesture, gestureId, input.autoMaxContentHeight, input.collapsed, input.minFrameHeight, model.mode, model.visibleContentHeight, geometry]);
- const bounds = useMemo(() => computeComposerResizeBounds({
- autoMaxContentHeight: input.autoMaxContentHeight,
- composerChromeHeight: input.composerChromeHeight,
- keyboardHeight: input.keyboardHeight,
- singleLineContentHeight: input.singleLineContentHeight,
- windowHeight: input.windowHeight,
- }), [
- input.autoMaxContentHeight,
- input.composerChromeHeight,
- input.keyboardHeight,
- input.singleLineContentHeight,
- input.windowHeight,
- ]);
-
- const model = resolveComposerInputHeight({
- autoMaxContentHeight: input.autoMaxContentHeight,
- bounds,
- collapsed: input.collapsed,
- contentHeight: input.contentHeight,
- userContentHeight,
- });
-
- // PanResponder 回调生命周期长于 render,经 ref 读取最新值。
- const boundsRef = useRef(bounds);
- boundsRef.current = bounds;
- const visibleContentHeightRef = useRef(model.visibleContentHeight);
- visibleContentHeightRef.current = model.visibleContentHeight;
- const onSnapToAutoRef = useRef(input.onSnapToAuto);
- onSnapToAutoRef.current = input.onSnapToAuto;
- const onGrabberTouchActiveChangeRef = useRef(input.onGrabberTouchActiveChange);
- onGrabberTouchActiveChangeRef.current = input.onGrabberTouchActiveChange;
- const contentHeightRef = useRef(input.contentHeight);
- contentHeightRef.current = input.contentHeight;
-
- const dragAnim = useRef(new Animated.Value(0)).current;
- const dragStartRef = useRef(0);
- const dragLastRef = useRef(0);
-
- // 手势认领 / 让出策略集中在 buildComposerResizeGestureConfig(纯函数,单测
- // 锁行为):capture 认领竖直拖动 + 拒绝 termination request,保证 grabber 在
- // ScrollView 内(会话页 composer 外壳)拖动时不被原生滚动抢走手势。
- const panResponder = useMemo(() => {
- const settle = (translationY: number) => {
- const moved = Math.abs(dragLastRef.current - dragStartRef.current)
- >= COMPOSER_RESIZE_DRAG_ACTIVATION_THRESHOLD;
- if (moved) {
- setUserContentHeight(settleComposerResizeDrag({
- bounds: boundsRef.current,
- contentHeight: contentHeightRef.current,
- draggedContentHeight: dragLastRef.current,
- }));
+ const begin = useCallback((id: number) => {
+ if (!mounted.current || id !== gestureId.value) return;
+ latest.current.onGrabberTouchActiveChange?.(true);
+ setDragging(true);
+ }, [gestureId]);
+ const finish = useCallback((height: number, initialHeight: number, translationY: number, successful: boolean, id: number) => {
+ if (!mounted.current || id !== gestureId.value) return;
+ const current = latest.current;
+ const currentBounds = computeComposerResizeBounds(current);
+ if (successful) {
+ if (Math.abs(height - initialHeight) >= COMPOSER_RESIZE_DRAG_ACTIVATION_THRESHOLD) {
+ setUserContentHeight(settleComposerResizeDrag({ bounds: currentBounds, contentHeight: current.contentHeight, draggedContentHeight: height }));
}
- // 下拉收起判定独立于高度变化量:输入框本来就一行时向下拖,高度被 clamp
- // 纹丝不动(moved 恒 false),但手势位移真实存在,同样应该退出激活态。
- if (shouldDismissComposerOnRelease({
- bounds: boundsRef.current,
- draggedContentHeight: dragLastRef.current,
- translationY,
- })) {
- onSnapToAutoRef.current?.();
+ if (shouldDismissComposerOnRelease({ bounds: currentBounds, draggedContentHeight: height, translationY })) {
+ current.onSnapToAuto?.();
}
- setDragging(false);
+ }
+ setDragging(false);
+ setCompletedGesture(id);
+ current.onGrabberTouchActiveChange?.(false);
+ }, [gestureId]);
+
+ const scrollGesture = useMemo(() => Gesture.Native(), []);
+ const gesture = useMemo(() => Gesture.Pan()
+ // Dedicated grabber: own the touch before the keyboard's ancestor ScrollView.
+ .minDistance(0)
+ .blocksExternalGesture(scrollGesture)
+ .onBegin(() => {
+ 'worklet';
+ gestureId.value += 1;
+ // A second drag can begin before the first JS completion is delivered.
+ startHeight.value = active.value ? dragHeight.value : geometry.value.visibleHeight;
+ active.value = true;
+ dragHeight.value = startHeight.value;
+ runOnJS(begin)(gestureId.value);
+ })
+ .onUpdate((event) => {
+ 'worklet';
+ dragHeight.value = applyComposerResizeDrag({ bounds: geometry.value.bounds, startContentHeight: startHeight.value, translationY: event.translationY });
+ })
+ .onFinalize((event, successful) => {
+ 'worklet';
+ if (!successful) {
+ // Cancellation must restore the settled frame even while JS is busy,
+ // so a new gesture cannot inherit the canceled temporary height.
+ dragHeight.value = geometry.value.visibleHeight;
+ active.value = false;
+ }
+ runOnJS(finish)(dragHeight.value, startHeight.value, event.translationY, successful, gestureId.value);
+ }), [active, begin, dragHeight, finish, geometry, gestureId, scrollGesture, startHeight]);
+
+ useLayoutEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ latest.current.onGrabberTouchActiveChange?.(false);
};
- const config = buildComposerResizeGestureConfig({
- onEnd: settle,
+ }, []);
+
+ // Expo Go deliberately disables RNGH in the platform adapter. Keep its
+ // existing JS fallback; installed apps never attach a PanResponder.
+ const panHandlers = useMemo(() => {
+ if (!isStoreClient) return {};
+ let initial = 0;
+ let height = 0;
+ let id = 0;
+ const responder = PanResponder.create(buildComposerResizeGestureConfig({
onGrant: () => {
- dragStartRef.current = visibleContentHeightRef.current;
- dragLastRef.current = dragStartRef.current;
- dragAnim.setValue(toFrameHeight(dragStartRef.current));
- setDragging(true);
+ initial = geometry.value.visibleHeight;
+ height = initial;
+ dragHeight.value = height;
+ active.value = true;
+ id = ++gestureId.value;
+ begin(id);
},
onMove: (translationY) => {
- const next = applyComposerResizeDrag({
- bounds: boundsRef.current,
- startContentHeight: dragStartRef.current,
- translationY,
- });
- dragLastRef.current = next;
- dragAnim.setValue(toFrameHeight(next));
+ height = applyComposerResizeDrag({ bounds: geometry.value.bounds, startContentHeight: initial, translationY });
+ dragHeight.value = height;
},
- });
- return {
- responder: PanResponder.create(config),
- touchHandlers: buildComposerResizeTouchHandlers((active) => {
- onGrabberTouchActiveChangeRef.current?.(active);
- }),
+ onEnd: (translationY) => finish(height, initial, translationY, true, id),
+ }));
+ responder.panHandlers.onResponderTerminate = () => {
+ dragHeight.value = geometry.value.visibleHeight;
+ active.value = false;
+ finish(height, initial, 0, false, id);
};
- }, [dragAnim]);
+ return { ...responder.panHandlers, ...buildComposerResizeTouchHandlers((value) => latest.current.onGrabberTouchActiveChange?.(value)) };
+ }, [active, begin, dragHeight, finish, geometry, gestureId]);
+ const contentHeight = useDerivedValue(() => active.value
+ ? Math.max(geometry.value.bounds.minContentHeight, Math.min(dragHeight.value, geometry.value.bounds.maxContentHeight))
+ : geometry.value.visibleHeight);
+ const frameStyle = useAnimatedStyle(() => ({
+ // Auto growth stays capped, but the grabber removes that cap on UI before
+ // begin can reach JS. Explicit heights are already bounded by the model.
+ maxHeight: active.value || geometry.value.explicit ? undefined : geometry.value.autoMaxHeight,
+ height: active.value || geometry.value.explicit
+ ? Math.max(geometry.value.minFrameHeight, contentHeight.value + COMPOSER_TEXT_VERTICAL_PADDING * 2)
+ : undefined,
+ }));
const reset = useCallback(() => setUserContentHeight(null), []);
-
const adjustByLine = useCallback((direction: 1 | -1) => {
- const next = applyComposerResizeDrag({
- bounds: boundsRef.current,
- startContentHeight: visibleContentHeightRef.current,
- // 向上(增高)为负位移,与 grabber 拖拽同一坐标系。
- translationY: -direction * MOBILE_COMPOSER_INPUT_LINE_HEIGHT,
- });
- setUserContentHeight(settleComposerResizeDrag({
- bounds: boundsRef.current,
- contentHeight: contentHeightRef.current,
- draggedContentHeight: next,
- }));
- }, []);
-
- // 简洁态(collapsed)必须显式定高:auto 模式下 TextInput 是内容自增长的,
- // 不给 frame 定高的话多行草稿的简洁态仍会撑到内容高度。
- const frameHeight = dragging
- ? dragAnim
- : input.collapsed === true || model.mode === 'manual'
- ? toFrameHeight(model.visibleContentHeight)
- : null;
-
- // auto 分支保持页面原有 maxHeight 语义(不加 padding 补偿),避免行为漂移;
- // manual / 拖动时必须放开到拖拽上限对应的 frame 高度,否则 TextInput 的
- // maxHeight 会顶住 stretch,输入区撑不满定高的 frame。
- const inputMaxHeight = dragging || model.mode === 'manual'
- ? toFrameHeight(bounds.maxContentHeight)
- : input.autoMaxContentHeight;
+ const current = latest.current;
+ const currentBounds = computeComposerResizeBounds(current);
+ const height = applyComposerResizeDrag({ bounds: currentBounds, startContentHeight: geometry.value.visibleHeight, translationY: -direction * COMPOSER_TEXT_LINE_HEIGHT });
+ setUserContentHeight(settleComposerResizeDrag({ bounds: currentBounds, contentHeight: current.contentHeight, draggedContentHeight: height }));
+ }, [geometry]);
return {
adjustByLine,
+ active,
+ contentHeight,
dragging,
- frameHeight,
- inputMaxHeight,
- maxFrameHeight: toFrameHeight(bounds.maxContentHeight),
+ frameStyle,
+ gesture,
+ // The inner TextInput/WebView must be ready to fill any UI-driven frame;
+ // waiting for React dragging here would clip it during a busy JS thread.
+ inputMaxHeight: Math.max(input.autoMaxContentHeight, bounds.maxContentHeight + COMPOSER_TEXT_VERTICAL_PADDING * 2),
+ maxFrameHeight: bounds.maxContentHeight + COMPOSER_TEXT_VERTICAL_PADDING * 2,
mode: model.mode,
- panHandlers: { ...panResponder.responder.panHandlers, ...panResponder.touchHandlers },
+ panHandlers,
reset,
scrollEnabled: model.scrollEnabled,
+ scrollGesture,
visibleContentHeight: model.visibleContentHeight,
};
}
-
-/** 内容高度 → inputFrame 高度(补上输入框上下 padding)。 */
-function toFrameHeight(contentHeight: number): number {
- return contentHeight + MOBILE_COMPOSER_INPUT_VERTICAL_PADDING * 2;
-}
diff --git a/apps/mobile/src/session/useContextSheetDrag.ts b/apps/mobile/src/session/useContextSheetDrag.ts
index 65b9ea2b5b..6df588346e 100644
--- a/apps/mobile/src/session/useContextSheetDrag.ts
+++ b/apps/mobile/src/session/useContextSheetDrag.ts
@@ -1,16 +1,11 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { Animated, PanResponder, type GestureResponderHandlers } from 'react-native';
-import {
- applyContextSheetDrag,
- settleContextSheetDrag,
- type ContextSheetSnap,
- type ContextSheetSnapHeights,
-} from '@/session/contextSheetModel';
-
-/** 松手时位移小于该值视为轻点而非拖动,不触发档位结算。 */
-const DRAG_ACTIVATION_THRESHOLD = 3;
-/** 档位吸附动画时长;与 Modal slide 的节奏保持接近。 */
-const SNAP_ANIMATION_DURATION_MS = 180;
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { PanResponder } from 'react-native';
+import Constants, { ExecutionEnvironment } from 'expo-constants';
+import { cancelAnimation, Easing, runOnJS, runOnUI, useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';
+import { Gesture } from '@/platform/gestureHandler';
+import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { motionDuration, motionEasing } from '@/theme';
+import { applyContextSheetDrag, settleContextSheetDrag, type ContextSheetSnap, type ContextSheetSnapHeights } from '@/session/contextSheetModel';
export interface UseContextSheetDragInput {
heights: ContextSheetSnapHeights;
@@ -19,113 +14,140 @@ export interface UseContextSheetDragInput {
onDismiss: () => void;
}
-export interface UseContextSheetDragResult {
- /** 面板当前呈现高度;拖动 / 吸附动画期间由 Animated 驱动,不触发整页 re-render。 */
- animatedHeight: Animated.Value;
- /** 拖动进行中(内容区可据此暂停滚动等)。 */
- dragging: boolean;
- /** 传给 grabber / header 拖动区的手势 handlers。 */
- panHandlers: GestureResponderHandlers;
-}
-
-/**
- * Context 面板拖动换档的手势与动画编排。
- *
- * 沿用 useComposerResize 的模式:拖动期间只 setValue(JS 驱动布局高度),
- * 松手按 contextSheet 纯函数结算——吸附到 half / full 时先动画到目标高度再落 state,
- * 判定 dismiss 时直接回调关闭(Modal 自带滑出动画)。
- */
-export function useContextSheetDrag(input: UseContextSheetDragInput): UseContextSheetDragResult {
- const [dragging, setDragging] = useState(false);
-
- const heightAnim = useRef(new Animated.Value(input.heights[input.snap])).current;
+const isStoreClient = Constants.executionEnvironment === ExecutionEnvironment.StoreClient;
- // PanResponder 回调生命周期长于 render,经 ref 读取最新值。
- const heightsRef = useRef(input.heights);
- heightsRef.current = input.heights;
- const snapRef = useRef(input.snap);
- snapRef.current = input.snap;
- const onSnapChangeRef = useRef(input.onSnapChange);
- onSnapChangeRef.current = input.onSnapChange;
- const onDismissRef = useRef(input.onDismiss);
- onDismissRef.current = input.onDismiss;
- const draggingRef = useRef(false);
- const dragStartRef = useRef(0);
- const dragLastRef = useRef(0);
+function hasDragMoved(start: number, current: number): boolean {
+ 'worklet';
+ return Math.abs(current - start) >= 3;
+}
- // 非拖动期间,snap / 屏幕尺寸变化时把高度动画到当前档位。
+/** Pointer updates and snap animations stay on UI; JS only receives the result. */
+export function useContextSheetDrag(input: UseContextSheetDragInput) {
+ const latest = useRef(input);
+ latest.current = input;
+ const reduceMotion = useReduceMotionEnabled();
+ const height = useSharedValue(input.heights[input.snap]);
+ const startHeight = useSharedValue(height.value);
+ const active = useSharedValue(false);
+ // Keep the release destination even before JS acknowledges the snap.
+ // A tap that interrupts an in-flight snap animation must return here.
+ const settledSnap = useSharedValue(input.snap);
+ const gestureId = useSharedValue(0);
+ const mounted = useRef(true);
+ const lastNotification = useRef<{ snap: ContextSheetSnap; id: number } | null>(null);
+ const geometry = useSharedValue({ heights: input.heights, snap: input.snap });
+ const notify = useCallback((target: ContextSheetSnap | 'dismiss', id: number) => {
+ if (!mounted.current || id !== gestureId.value) return;
+ if (target === 'dismiss') latest.current.onDismiss();
+ else {
+ lastNotification.current = { snap: target, id };
+ // Do not compare with props: an earlier notification can still be waiting
+ // for React to commit, including a full -> half return to the old value.
+ latest.current.onSnapChange(target);
+ }
+ }, [gestureId]);
useEffect(() => {
- if (draggingRef.current) return;
- Animated.timing(heightAnim, {
- duration: SNAP_ANIMATION_DURATION_MS,
- toValue: input.heights[input.snap],
- useNativeDriver: false,
- }).start();
- }, [heightAnim, input.heights, input.snap]);
-
- const panResponder = useMemo(() => {
- const settle = () => {
- draggingRef.current = false;
- setDragging(false);
- const moved = Math.abs(dragLastRef.current - dragStartRef.current) >= DRAG_ACTIVATION_THRESHOLD;
- if (!moved) {
- heightAnim.setValue(heightsRef.current[snapRef.current]);
+ const nextGeometry = { heights: input.heights, snap: input.snap };
+ const duration = reduceMotion === false ? motionDuration.fast : 0;
+ const notification = lastNotification.current;
+ const observedGesture = notification?.snap === input.snap ? notification.id : gestureId.value;
+ runOnUI((next: typeof nextGeometry, durationMs: number, observed: number) => {
+ 'worklet';
+ if (next.snap !== geometry.value.snap && observed === gestureId.value) settledSnap.value = next.snap;
+ geometry.value = next;
+ // Rotation/reduced-motion changes retain the user's release destination.
+ // Only an explicit external snap change replaces it.
+ if (active.value) {
+ height.value = Math.min(height.value, next.heights.full);
return;
}
- const target = settleContextSheetDrag({
- draggedHeight: dragLastRef.current,
- heights: heightsRef.current,
+ height.value = withTiming(next.heights[settledSnap.value], {
+ duration: durationMs,
+ easing: Easing.bezier(...motionEasing.move),
});
+ })(nextGeometry, duration, observedGesture);
+ }, [active, geometry, gestureId, height, input.heights.half, input.heights.full, input.snap, reduceMotion, settledSnap]);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ cancelAnimation(height);
+ };
+ }, [height]);
+
+ const gesture = useMemo(() => Gesture.Pan()
+ // Header buttons remain tappable; only a vertical drag claims the header.
+ .activeOffsetY([-3, 3])
+ .failOffsetX([-12, 12])
+ .onBegin(() => {
+ 'worklet';
+ cancelAnimation(height);
+ gestureId.value += 1;
+ active.value = true;
+ startHeight.value = height.value;
+ })
+ .onUpdate((event) => {
+ 'worklet';
+ height.value = applyContextSheetDrag({ heights: geometry.value.heights, startHeight: startHeight.value, translationY: event.translationY });
+ })
+ .onFinalize((_event, successful) => {
+ 'worklet';
+ active.value = false;
+ const current = geometry.value;
+ const id = gestureId.value;
+ const target = successful && hasDragMoved(startHeight.value, height.value)
+ ? settleContextSheetDrag({ draggedHeight: height.value, heights: current.heights })
+ : settledSnap.value;
if (target === 'dismiss') {
- onDismissRef.current();
+ runOnJS(notify)(target, id);
return;
}
- Animated.timing(heightAnim, {
- duration: SNAP_ANIMATION_DURATION_MS,
- toValue: heightsRef.current[target],
- useNativeDriver: false,
- }).start(() => {
- if (target !== snapRef.current) onSnapChangeRef.current(target);
+ settledSnap.value = target;
+ // The semantic result survives animation cancellation (rotation, a new
+ // touch, reduced motion); animation completion is presentation only.
+ runOnJS(notify)(target, id);
+ height.value = withTiming(current.heights[target], {
+ duration: reduceMotion === false ? motionDuration.fast : 0,
+ easing: Easing.bezier(...motionEasing.move),
});
+ }), [active, geometry, gestureId, height, notify, reduceMotion, settledSnap, startHeight]);
+
+ // Preserve Expo Go's adapter fallback. Installed apps attach only the UI gesture.
+ const panHandlers = useMemo(() => {
+ if (!isStoreClient) return {};
+ const settle = (successful: boolean) => {
+ active.value = false;
+ // A tap or cancellation resumes the release destination, even while its
+ // animation or React acknowledgement is still pending.
+ if (!successful || !hasDragMoved(startHeight.value, height.value)) {
+ height.value = withTiming(latest.current.heights[settledSnap.value], { duration: reduceMotion === false ? motionDuration.fast : 0 });
+ return;
+ }
+ const target = settleContextSheetDrag({ draggedHeight: height.value, heights: latest.current.heights });
+ if (target === 'dismiss') notify(target, gestureId.value);
+ else {
+ settledSnap.value = target;
+ height.value = withTiming(latest.current.heights[target], { duration: reduceMotion === false ? motionDuration.fast : 0 });
+ notify(target, gestureId.value);
+ }
};
return PanResponder.create({
- // 兜底保留 move 阶段协商;但在 Fabric 新架构下 Modal 内 move 阶段的 responder
- // 协商不会被触发(start 阶段与已授权 responder 的 move 事件均正常——面板内
- // Pressable 可点、backdrop 能跨 move 收到 release),所以真正生效的是下面的
- // touch-down 认领。
- onMoveShouldSetPanResponder: (_event, gestureState) =>
- Math.abs(gestureState.dy) > DRAG_ACTIVATION_THRESHOLD
- && Math.abs(gestureState.dy) > Math.abs(gestureState.dx),
+ onStartShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
- dragStartRef.current = heightsRef.current[snapRef.current];
- dragLastRef.current = dragStartRef.current;
- heightAnim.setValue(dragStartRef.current);
- draggingRef.current = true;
- setDragging(true);
+ cancelAnimation(height);
+ gestureId.value += 1;
+ startHeight.value = height.value;
+ active.value = true;
},
- onPanResponderMove: (_event, gestureState) => {
- const next = applyContextSheetDrag({
- heights: heightsRef.current,
- startHeight: dragStartRef.current,
- translationY: gestureState.dy,
- });
- dragLastRef.current = next;
- heightAnim.setValue(next);
+ onPanResponderMove: (_event, event) => {
+ height.value = applyContextSheetDrag({ heights: latest.current.heights, startHeight: startHeight.value, translationY: event.dy });
},
- onPanResponderRelease: settle,
- onPanResponderTerminate: settle,
- // touch-down 即认领:拖动区(grabber + header 底)没有可点内容,header 里的
- // 关闭 / 返回按钮是更深层的 Pressable、协商时优先于本区,不受影响;轻点无位移
- // 时 settle 的 moved 阈值会直接复位,不产生档位变化。
- onStartShouldSetPanResponder: () => true,
- // 已接管的拖动不许被父级(ScrollView 等)中途抢走,避免拖到一半面板卡在中间。
+ onPanResponderRelease: () => settle(true),
+ onPanResponderTerminate: () => settle(false),
onPanResponderTerminationRequest: () => false,
- });
- }, [heightAnim]);
+ }).panHandlers;
+ }, [active, gestureId, height, notify, reduceMotion, settledSnap, startHeight]);
- return {
- animatedHeight: heightAnim,
- dragging,
- panHandlers: panResponder.panHandlers,
- };
+ const animatedStyle = useAnimatedStyle(() => ({ height: height.value }));
+ return { animatedStyle, gesture, panHandlers };
}