From 5fb612cc601b6ee3c3091cc7e1fad03756e853e6 Mon Sep 17 00:00:00 2001 From: QQ Date: Tue, 17 Nov 2026 08:27:40 +0800 Subject: [PATCH] Import apps/android/src/screens/bot/conversation.tsx --- apps/android/src/screens/bot/conversation.tsx | 510 +++++++++++++----- 1 file changed, 378 insertions(+), 132 deletions(-) diff --git a/apps/android/src/screens/bot/conversation.tsx b/apps/android/src/screens/bot/conversation.tsx index bfd6944..e70c462 100644 --- a/apps/android/src/screens/bot/conversation.tsx +++ b/apps/android/src/screens/bot/conversation.tsx @@ -1,17 +1,27 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { ActivityIndicator, FlatList, Pressable, Text, TextInput, View } from 'react-native' -import { ArrowUp, Plus, Square, Users } from 'lucide-react-native' +import { AccessibilityInfo, ActivityIndicator, FlatList, Keyboard, Pressable, Text, TextInput, View } from 'react-native' +import { Users } from 'lucide-react-native' import { strings as s } from '../../locales/i18n' -import { botMessageRequest, object, objects, text, type BotEntry, type BotRoom, type BotState, type BotRemoteClient, type BotObject, type BotOperation } from '../../services/bot-catalog' +import { BUILT_IN_PROMPTS, type CustomPrompt } from '../../services/storage' +import { botMessageRequest, formatBotSubmission, object, objects, text, type BotEntry, type BotRoom, type BotState, type BotRemoteClient, type BotObject, type BotOperation } from '../../services/bot-catalog' import { pollRoomRows, preferredRoomRows, ROOM_ROWS_INTERVAL_MS, ROOM_ROWS_LEGACY_INTERVAL_MS, ROOM_ROWS_LEGACY_MISSES, type RoomRowsPoll } from '../../services/bot-room-rows' import { useAppStore } from '../../state/store' +import { useBotTeamStore } from '../../state/bot-store' import type { ChatItem, RemoteSession } from '../../types' -import { Button, IconButton } from '../../ui/components' +import { Alert } from '../../ui/alert' +import { Button } from '../../ui/components' import { decodeSessionMentionUri, markdownFilePath, MarkdownLinkProvider, NativeMarkdown, openSafeExternalUrl } from '../../ui/markdown' -import { detectMention, MentionPopover, type MentionGroup } from '../../ui/mention-popover' +import { detectMention, type MentionGroup } from '../../ui/mention-popover' +import { useResponsiveLayout } from '../../ui/responsive' import { useTheme } from '../../ui/theme-context' import { useThemedStyles } from '../../ui/use-themed-styles' +import { ChatComposer, type ComposerInputBridge } from '../chat/composer' +import { applyQuickPromptDraft } from '../chat/composer-gate' +import { type ExpandedComposerProps } from '../chat/expanded-composer' import { ChatActivityGroup, ChatItemView, QueueDock } from '../chat/messages' +import { PromptEditor, PromptsManager, PromptsPicker } from '../chat/pickers' +import { createStyles as createChatStyles } from '../chat/styles' +import { useChatPrompts } from '../chat/use-chat-prompts' import { chatSections, inboxQueuedItems, inboxRpcIds, type ChatSection } from '../../state/message-helpers' import { processSegments } from '../chat-process' import { useSessionUiArtifacts } from '../chat/use-session-ui-artifacts' @@ -31,7 +41,7 @@ import { linkBotMentions, botMentionTarget } from './mentions' import { BotMessageActionsContext } from '../message-actions' import { SessionToolsPanel } from '../session-tools-panel' -import { browseScope, browseKey, useBrowseMemory, getCachedGroupRound, saveGroupRound } from '../../services/browse-memory' +import { browseScope, browseKey, updateBrowseEntry, useBrowseMemory, saveGroupRound } from '../../services/browse-memory' const EMPTY: ChatItem[] = [] type BotChatRow = @@ -40,43 +50,60 @@ type BotChatRow = | { kind: 'ui'; key: string; artifact: UiArtifact } | { kind: 'ui-pointer'; key: string; artifact: UiArtifact } | { kind: 'ui-unavailable'; key: string; item: ToolActivity } -export function BotConversation({ bot, room, state, client, session, busy, active, perform, onSelectBot }: { - bot?: BotEntry; room?: BotRoom; state: BotState; client: BotRemoteClient; session: RemoteSession +export function BotConversation({ bot, room, state, client, session, busy, active, perform, onSelectBot, onExpandedComposerChange }: { + bot?: BotEntry; room?: BotRoom; state: BotState; client?: BotRemoteClient; session: RemoteSession busy: boolean; active: boolean; perform: BotPerform; onSelectBot: (id: string) => void + onExpandedComposerChange?: (props: ExpandedComposerProps | null) => void }) { const transformText = useCallback((value: string) => linkBotMentions(value, state.bots, bot?.id), [state.bots, bot?.id]) const botById = useCallback((id: string) => state.bots.find(entry => entry.id === id), [state.bots]) const mentions = useMemo(() => ({ bots: state.bots, selfId: bot?.id, onPress: (id: string) => onSelectBot(id) }), [state.bots, bot?.id, onSelectBot]) const styles = useThemedStyles(createBotStyles) + const chatStyles = useThemedStyles(createChatStyles) const { colors } = useTheme() + const { compactHeight, height, landscape, contentMaxWidth } = useResponsiveLayout() + const compactComposer = landscape || compactHeight + const composerInputMaxHeight = compactComposer ? Math.max(48, Math.min(96, Math.round(height * 0.22))) : 126 + const readableColumn = { width: '100%' as const, maxWidth: contentMaxWidth, alignSelf: 'center' as const } const messages = useAppStore(store => store.messages[session.sessionId] ?? EMPTY) const selected = useAppStore(store => store.selectedSession) const storeBusy = useAppStore(store => store.busyAction) + const quickPromptActionMode = useAppStore(store => store.quickPromptActionMode) + const setQuickPromptActionMode = useAppStore(store => store.setQuickPromptActionMode) const hasMore = useAppStore(store => store.historyHasMore) const olderLoading = useAppStore(store => store.historyLoadingOlder) const loadOlder = useAppStore(store => store.loadOlderHistory) const respondApproval = useAppStore(store => store.respondApproval) const respondQuestion = useAppStore(store => store.respondQuestion) const stopSession = useAppStore(store => store.stopSession) - const [draft, setDraft] = useState('') + const refreshLive = useBotTeamStore(store => store.refreshLive) + const memoryScope = useAppStore(browseScope) + const savedDraft = useBrowseMemory(store => store.entries[browseKey(memoryScope, session.sessionId)]?.draft ?? '') + const [draft, setDraft] = useState(savedDraft) const draftRef = useRef(draft) draftRef.current = draft const selectionRef = useRef({ start: 0, end: 0 }) const inputRef = useRef(null) + const sendingRef = useRef(false) const [atQuery, setAtQuery] = useState(null) const atSpanStartRef = useRef(0) const [plusMenuOpen, setPlusMenuOpen] = useState(false) + const [composerExpanded, setComposerExpanded] = useState(false) + const expandedActivatedRef = useRef(false) const [referenceChatOpen, setReferenceChatOpen] = useState(false) const [stagedReferences, setStagedReferences] = useState([]) const [fileLinkPath, setFileLinkPath] = useState() const sessions = useAppStore(store => store.sessions) const openSession = useAppStore(store => store.openSession) const connected = useAppStore(store => store.connection.phase === 'connected') + const { promptsPickerOpen, setPromptsPickerOpen, customPrompts, promptEditing, + setPromptEditing, promptsManagerOpen, setPromptsManagerOpen, promptsLoading, savePromptEdit, deletePrompt } = useChatPrompts(connected ? 'connected' : 'disconnected') const [progress, setProgress] = useState([]) const [speaking, setSpeaking] = useState([]) const [earlier, setEarlier] = useState([]) const [cursor, setCursor] = useState(undefined) const [olderBusy, setOlderBusy] = useState(false) + const olderBusyRef = useRef(false) const [error, setError] = useState() const mounted = useRef(true) const request = useRef(new AbortController()) @@ -84,10 +111,19 @@ export function BotConversation({ bot, room, state, client, session, busy, activ const atEnd = useRef(true) const scrolling = useRef(false) const scrollFrame = useRef(undefined) + const cancelFollowEnd = () => { + if (scrollFrame.current !== undefined) { + cancelAnimationFrame(scrollFrame.current) + scrollFrame.current = undefined + } + } const followEnd = () => { - if (!atEnd.current) return - if (scrollFrame.current !== undefined) cancelAnimationFrame(scrollFrame.current) - scrollFrame.current = requestAnimationFrame(() => { if (atEnd.current) list.current?.scrollToEnd({ animated: false }) }) + if (!atEnd.current || scrolling.current) return + cancelFollowEnd() + scrollFrame.current = requestAnimationFrame(() => { + scrollFrame.current = undefined + if (atEnd.current && !scrolling.current) list.current?.scrollToEnd({ animated: false }) + }) } useEffect(() => () => { if (scrollFrame.current !== undefined) cancelAnimationFrame(scrollFrame.current) }, []) const ready = selected?.sessionId === session.sessionId @@ -122,16 +158,24 @@ export function BotConversation({ bot, room, state, client, session, busy, activ const path = markdownFilePath(href) if (path !== undefined) setFileLinkPath(path) }, [state.bots, bot?.id, onSelectBot, ready, connected, sessions, openSession]) + const applyDraft = useCallback((nextText: string) => { + draftRef.current = nextText + setDraft(nextText) + updateBrowseEntry(memoryScope, session.sessionId, { draft: nextText }) + }, [memoryScope, session.sessionId]) useEffect(() => { - draftRef.current = '' - selectionRef.current = { start: 0, end: 0 } - setDraft('') + const initialDraft = useBrowseMemory.getState().entries[browseKey(memoryScope, session.sessionId)]?.draft ?? '' + draftRef.current = initialDraft + selectionRef.current = { start: initialDraft.length, end: initialDraft.length } + setDraft(initialDraft) setFileLinkPath(undefined) setAtQuery(null) setPlusMenuOpen(false) + setComposerExpanded(false) + setPromptsPickerOpen(false) setReferenceChatOpen(false) setStagedReferences([]) - }, [session.sessionId]) + }, [memoryScope, session.sessionId]) const updateAtMention = (nextText: string, cursor: number) => { const detected = detectMention(nextText, cursor) @@ -145,8 +189,7 @@ export function BotConversation({ bot, room, state, client, session, busy, activ const handleDraftChange = (nextText: string) => { if (nextText === draftRef.current) return const delta = nextText.length - draftRef.current.length - draftRef.current = nextText - setDraft(nextText) + applyDraft(nextText) const cursor = Math.max(0, Math.min(nextText.length, selectionRef.current.end + delta)) selectionRef.current = { start: cursor, end: cursor } updateAtMention(nextText, cursor) @@ -163,8 +206,7 @@ export function BotConversation({ bot, room, state, client, session, busy, activ const current = draftRef.current const nextText = current.slice(0, start) + mentionText + current.slice(end) const nextCursor = start + mentionText.length - draftRef.current = nextText - setDraft(nextText) + applyDraft(nextText) selectionRef.current = { start: nextCursor, end: nextCursor } setAtQuery(null) inputRef.current?.focus() @@ -205,11 +247,15 @@ export function BotConversation({ bot, room, state, client, session, busy, activ || (bot !== undefined && bot.sessionId !== session.sessionId) || (room !== undefined && (room.sessionId || room.id) !== session.sessionId) || state.readOnly !== undefined - const disabled = busy || inputDisabled - useEffect(() => { setEarlier([]); setCursor(undefined); setProgress([]); setSpeaking([]); setOlderBusy(false); setError(undefined); atEnd.current = true; scrolling.current = false; followEnd() }, [session.sessionId]) + const disabled = busy || inputDisabled || !connected || client === undefined + useEffect(() => { olderBusyRef.current = false; setEarlier([]); setCursor(undefined); setProgress([]); setSpeaking([]); setOlderBusy(false); setError(undefined); atEnd.current = true; scrolling.current = false; followEnd() }, [session.sessionId]) useEffect(() => { mounted.current = true; request.current = new AbortController(); return () => { mounted.current = false; request.current.abort() } }, [session.sessionId]) useEffect(() => { - if (room === undefined || !active) return + if (room === undefined || !active || !connected || client === undefined) { + setSpeaking([]) + if (!connected) setProgress([]) + return + } const control = new AbortController() let timer: ReturnType | undefined const tick = async () => { @@ -226,20 +272,21 @@ export function BotConversation({ bot, room, state, client, session, busy, activ } if (!control.signal.aborted) setProgress(objects(value).filter(entry => { const call = (useAppStore.getState().messages[session.sessionId] ?? []).find(item => item.id === entry.callId) - return call?.kind !== 'tool' || call.state !== 'finished' + return call?.kind !== 'tool' || (call.state !== 'finished' && call.state !== 'failed') }).flatMap(entry => objects(entry.replies))) } catch { /* The parent state refresh reports connection and Host errors. */ } if (!control.signal.aborted) timer = setTimeout(() => void tick(), 2000) } void tick() return () => { control.abort(); clearTimeout(timer) } - }, [client, room?.id, session.sessionId, active]) - const send = async () => { - const rawDraft = draftRef.current.trim() + }, [client, room?.id, session.sessionId, active, connected]) + const sendSubmission = async (rawText: string, clearDraft: boolean): Promise => { + if (sendingRef.current || disabled) return false + const rawDraft = rawText.trim() const submittedRefs = stagedReferences - const prefix = submittedRefs.map(item => item.mentionText.trim()).join(' ') - const submitted = [prefix, rawDraft].filter(Boolean).join(' ') - if (!submitted || disabled) return + const submitted = formatBotSubmission(rawDraft, submittedRefs.map(item => item.mentionText)) + if (!submitted) return false + sendingRef.current = true atEnd.current = true followEnd() setError(undefined) @@ -247,25 +294,28 @@ export function BotConversation({ bot, room, state, client, session, busy, activ try { message = botMessageRequest(state, bot?.id ?? room?.id ?? session.sessionId, submitted) } catch (reason) { + sendingRef.current = false setError(reason instanceof Error ? reason.message : s.bots.unavailable) - return + return false } const sendSessionId = session.sessionId const activeRequest = request.current - draftRef.current = '' - selectionRef.current = { start: 0, end: 0 } - setDraft('') - setAtQuery(null) + if (clearDraft) { + applyDraft('') + selectionRef.current = { start: 0, end: 0 } + setAtQuery(null) + } setStagedReferences([]) const restoreFailedDraft = () => { if (!mounted.current || activeRequest.signal.aborted || session.sessionId !== sendSessionId) return - const typedWhileInFlight = draftRef.current.trim() - const restoredDraft = typedWhileInFlight - ? (rawDraft ? `${rawDraft}\n${typedWhileInFlight}` : typedWhileInFlight) - : rawDraft - draftRef.current = restoredDraft - selectionRef.current = { start: restoredDraft.length, end: restoredDraft.length } - setDraft(restoredDraft) + if (clearDraft) { + const typedWhileInFlight = draftRef.current.trim() + const restoredDraft = typedWhileInFlight + ? (rawDraft ? `${rawDraft}\n${typedWhileInFlight}` : typedWhileInFlight) + : rawDraft + applyDraft(restoredDraft) + selectionRef.current = { start: restoredDraft.length, end: restoredDraft.length } + } if (submittedRefs.length > 0) { setStagedReferences(current => { const existing = new Set(current.map(item => item.sessionId)) @@ -277,16 +327,45 @@ export function BotConversation({ bot, room, state, client, session, busy, activ const result = await perform(message.endpoint, message.payload) if (!result.ok) { restoreFailedDraft() + return false } + return true } catch (reason) { if (mounted.current && !activeRequest.signal.aborted && session.sessionId === sendSessionId) { restoreFailedDraft() setError(reason instanceof Error ? reason.message : s.bots.unavailable) } + return false + } finally { + sendingRef.current = false } } + const send = () => sendSubmission(draftRef.current, true) + const pickQuickPrompt = async (prompt: CustomPrompt) => { + setPromptsPickerOpen(false) + if (quickPromptActionMode === 'fill') { + const { draft: nextDraft, cursor } = applyQuickPromptDraft(draftRef.current, prompt.text) + applyDraft(nextDraft) + selectionRef.current = { start: cursor, end: cursor } + updateAtMention(nextDraft, cursor) + requestAnimationFrame(() => inputRef.current?.focus()) + return + } + if (!connected) { + Alert.alert(s.chat.toolPromptSendFailed, s.chat.offlineNotice) + return + } + if (disabled) { + Alert.alert(s.chat.toolPromptSendFailed, s.chat.toolPromptSendFailed) + return + } + const sent = await sendSubmission(prompt.text, false) + if (sent) AccessibilityInfo.announceForAccessibility(s.chat.toolPromptSent(prompt.title)) + else Alert.alert(s.chat.toolPromptSendFailed, s.chat.toolPromptSendFailed) + } const earlierPage = async () => { - if (olderBusy || bot === undefined || cursor === null) return + if (olderBusyRef.current || bot === undefined || !client || cursor === null) return + olderBusyRef.current = true atEnd.current = false setOlderBusy(true) setError(undefined) @@ -295,19 +374,24 @@ export function BotConversation({ bot, room, state, client, session, busy, activ const value = object(await client.call('earlier', { sessionId: session.sessionId, ...(cursor === undefined ? {} : { cursor }) }, signal)) if (!mounted.current || signal.aborted) return setEarlier(current => { - const known = new Set(current.filter(entry => entry.kind === 'btw').map(entry => entry.id)) - const cards = objects(value.btw).filter(entry => entry.botId === bot.id && !known.has(entry.id)).map(entry => ({ ...entry, kind: 'btw', pageCursor: cursor })) - return [...objects(value.items), ...cards.reverse(), ...current] + const knownBtw = new Set(current.filter(entry => entry.kind === 'btw').map(entry => entry.id)) + const cards = objects(value.btw).filter(entry => entry.botId === bot.id && !knownBtw.has(entry.id)).map(entry => ({ ...entry, kind: 'btw', pageCursor: cursor })) + const knownItems = new Set(current.filter(entry => typeof entry.id === 'string').map(entry => `${text(entry.kind)}:${text(entry.id)}`)) + const items = objects(value.items).filter(entry => typeof entry.id !== 'string' || !knownItems.has(`${text(entry.kind)}:${text(entry.id)}`)) + return [...items, ...cards.reverse(), ...current] }) setCursor(value.cursor ?? null) } catch { if (mounted.current && !signal.aborted) setError(s.bots.earlierUnavailable) } - finally { if (mounted.current && !signal.aborted) setOlderBusy(false) } + finally { + olderBusyRef.current = false + if (mounted.current && !signal.aborted) setOlderBusy(false) + } } // A part can roll over while its aside is still answering. Current roster polls // no longer include it, so refresh only historical pages with a pending aside. const pendingAsidePages = JSON.stringify([...new Map(earlier.filter(entry => entry.kind === 'btw' && entry.status === 'answering').map(entry => [JSON.stringify(entry.pageCursor ?? null), entry.pageCursor ?? null])).values()]) useEffect(() => { - if (!active || !bot || pendingAsidePages === '[]') return + if (!active || !connected || !client || !bot || pendingAsidePages === '[]') return const control = new AbortController() let timer: ReturnType | undefined const tick = async () => { @@ -323,7 +407,7 @@ export function BotConversation({ bot, room, state, client, session, busy, activ } void tick() return () => { control.abort(); clearTimeout(timer) } - }, [active, bot?.id, client, session.sessionId, pendingAsidePages]) + }, [active, connected, bot?.id, client, session.sessionId, pendingAsidePages]) const question = object(state.questions[session.sessionId]) const view = object(state.views[session.sessionId]) const closedCards = object(state.closedCards[session.sessionId]) @@ -338,6 +422,75 @@ export function BotConversation({ bot, room, state, client, session, busy, activ ) return hasConnector || hasMail || hasComputer }, [state.connectorRequests, state.mailRequests, state.computerLive, session.sessionId, bot]) + const activeBtwCards = useMemo( + () => (bot ? objects(state.btwCards[bot.id]).filter(card => card.botId === bot.id && card.partId === session.sessionId) : []), + [bot, state.btwCards, session.sessionId], + ) + const hasPendingBtw = activeBtwCards.some(card => card.status === 'answering') + const interactiveSignal = useMemo(() => { + const parts = [selected?.running === true ? '1' : '0'] + for (const item of messages) { + if (item.kind === 'approval') { + parts.push(`a:${item.id}:${item.outcome ?? 'open'}`) + } else if ( + item.kind === 'tool' + && ( + item.toolKey === 'ask_user' + || item.toolKey === 'show_view' + || item.toolKey === 'request_connector' + || item.toolKey === 'mail_send' + || item.toolKey?.startsWith('computer_') + ) + ) { + parts.push(`t:${item.id}:${item.state}`) + } + } + return parts.join('|') + }, [messages, selected?.running]) + const prevInteractiveSignalRef = useRef(undefined) + useEffect(() => { + prevInteractiveSignalRef.current = undefined + }, [session.sessionId]) + useEffect(() => { + if (!active || !connected || !ready) return + const prev = prevInteractiveSignalRef.current + prevInteractiveSignalRef.current = interactiveSignal + if (prev === undefined || prev === interactiveSignal) return + void refreshLive({ forceFull: true }) + }, [active, connected, ready, interactiveSignal, refreshLive]) + const hasLiveFooterWork = Boolean( + selected?.running + || hasPendingBtw + || text(question.id) !== '' + || text(view.id) !== '' + || approvals.length > 0 + || hasDesktopPendingRequest + || room !== undefined, + ) + useEffect(() => { + if (!active || !connected || !ready) return + const control = new AbortController() + let timer: ReturnType | undefined + const intervalMs = hasLiveFooterWork ? 1500 : 3000 + const tick = async () => { + await refreshLive({ forceFull: hasPendingBtw }) + if (!control.signal.aborted) { + timer = setTimeout(() => void tick(), intervalMs) + } + } + timer = setTimeout(() => void tick(), intervalMs) + return () => { + control.abort() + clearTimeout(timer) + } + }, [active, connected, ready, session.sessionId, hasLiveFooterWork, hasPendingBtw, refreshLive]) + const questionId = text(question.id) + const viewId = text(view.id) + const approvalsKey = approvals.map(entry => text(entry.id)).join(',') + const btwKey = activeBtwCards.map(card => `${text(card.id)}:${text(card.status)}`).join(',') + useEffect(() => { + if (atEnd.current) followEnd() + }, [questionId, viewId, approvalsKey, btwKey, room?.paused, hasDesktopPendingRequest]) const inboxProjection = (session.projections?.values as Record | undefined)?.inbox const queueItems = useMemo(() => { const inboxItems = inboxProjection === undefined ? [] : inboxQueuedItems(inboxProjection) @@ -465,8 +618,26 @@ export function BotConversation({ bot, room, state, client, session, busy, activ return sectionRows }) - const onApproval: Parameters[0]['onApproval'] = async (...args) => { if (!disabled) await respondApproval(...args) } - const onQuestion: Parameters[0]['onQuestion'] = async (...args) => { if (!disabled) await respondQuestion(...args) } + const onApproval: Parameters[0]['onApproval'] = async (...args) => { + if (disabled) return + await respondApproval(...args) + void refreshLive({ forceFull: true }) + } + const onQuestion: Parameters[0]['onQuestion'] = async (...args) => { + if (disabled) return + await respondQuestion(...args) + void refreshLive({ forceFull: true }) + } + const hasEarlierParts = Boolean( + bot + && (bot.parts ?? []).some(id => id !== session.sessionId) + && bot.parts?.[0] !== session.sessionId, + ) + const showLoadOlder = hasMore || (hasEarlierParts && cursor !== null && client !== undefined) + const updateAtEnd = (nativeEvent: { contentOffset: { y: number }; contentSize: { height: number }; layoutMeasurement: { height: number } }) => { + const { contentOffset, contentSize, layoutMeasurement } = nativeEvent + atEnd.current = contentSize.height - contentOffset.y - layoutMeasurement.height < 90 + } const render = (item: ChatItem, artifacts?: UiArtifact[]) => { if (item.kind === 'tool' && item.toolKey === 'ask_user') { const closedStatus = text(closedCards[item.id]) @@ -508,6 +679,67 @@ export function BotConversation({ bot, room, state, client, session, busy, activ if (item.kind === 'tool') return null return } + const composerLabel = bot ? s.bots.askBot(bot.name) : room ? s.bots.askBot(room.name) : s.bots.message + const hasComposerContent = draft.trim().length > 0 || stagedReferences.length > 0 + const replyActive = Boolean(selected?.running) + const stopping = storeBusy === 'stop-session' + const composerSendDisabled = disabled || !hasComposerContent + + const draftChangeRef = useRef(handleDraftChange) + draftChangeRef.current = handleDraftChange + const selectionChangeRef = useRef(handleSelectionChange) + selectionChangeRef.current = handleSelectionChange + const sendRef = useRef(send) + sendRef.current = send + const stopRef = useRef(stopSession) + stopRef.current = stopSession + + const composerInputBridge = useMemo(() => ({ + composerInputRef: inputRef, + mentionType: atQuery !== null && botAtMentionGroups.length > 0 ? 'context' : null, + mentionGroups: botAtMentionGroups, + closeMention: () => setAtQuery(null), + onChangeText: next => draftChangeRef.current(next), + onSelectionChange: event => selectionChangeRef.current(event), + }), [atQuery, botAtMentionGroups]) + + useEffect(() => { + if (composerExpanded) expandedActivatedRef.current = true + if (!expandedActivatedRef.current) return + onExpandedComposerChange?.({ + visible: composerExpanded, + onClose: () => setComposerExpanded(false), + draft, + input: { + onChangeText: next => draftChangeRef.current(next), + onSelectionChange: event => selectionChangeRef.current(event), + }, + accessibilityLabel: composerLabel, + placeholder: composerLabel, + highlightMentionTokens: false, + replyActive, + stopping, + sending: busy, + sendDisabled: composerSendDisabled, + onSubmit: () => void sendRef.current(), + onStop: () => void stopRef.current(), + }) + }, [ + onExpandedComposerChange, + composerExpanded, + draft, + composerLabel, + replyActive, + stopping, + busy, + composerSendDisabled, + ]) + + useEffect(() => () => { + expandedActivatedRef.current = false + onExpandedComposerChange?.(null) + }, [onExpandedComposerChange]) + return item.key} renderItem={({ item, index }) => ( 0 && rows[index - 1]?.kind !== 'activity' ? 8 : 0 }}> @@ -530,34 +762,43 @@ export function BotConversation({ bot, room, state, client, session, busy, activ )} contentContainerStyle={styles.conversation} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" onLayout={followEnd} - onScrollBeginDrag={() => { scrolling.current = true; atEnd.current = false }} - onScrollEndDrag={() => { scrolling.current = false }} - onMomentumScrollBegin={() => { scrolling.current = true }} - onMomentumScrollEnd={() => { scrolling.current = false }} - onScroll={event => { if (!scrolling.current) return; const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent; atEnd.current = contentSize.height - contentOffset.y - layoutMeasurement.height < 90 }} + onScrollBeginDrag={() => { scrolling.current = true; cancelFollowEnd() }} + onScrollEndDrag={event => { + updateAtEnd(event.nativeEvent) + if (Math.abs(event.nativeEvent.velocity?.y ?? 0) <= 0.05) { + scrolling.current = false + } + }} + onMomentumScrollBegin={() => { scrolling.current = true; cancelFollowEnd() }} + onMomentumScrollEnd={event => { scrolling.current = false; updateAtEnd(event.nativeEvent) }} + onScroll={event => { if (!scrolling.current) return; updateAtEnd(event.nativeEvent) }} scrollEventThrottle={32} onContentSizeChange={followEnd} ListEmptyComponent={null} ListHeaderComponent={ - {earlier.map((entry, i) => entry.kind === 'btw' ? void perform('btw-cancel', { sessionId: bot!.id, id: entry.id })} onDelete={() => void perform('btw-delete', { sessionId: bot!.id, id: entry.id })} /> : entry.kind === 'closed' ? : entry.kind === 'view' ? {}} /> : {entry.kind === 'user' ? s.bots.yourAnswer : bot?.name}{text(entry.via) !== '' && })} - {hasMore && ( + {showLoadOlder && ( { atEnd.current = false; void loadOlder() }} + disabled={olderLoading || olderBusy || !ready || !connected} + onPress={() => { + atEnd.current = false + if (hasMore) void loadOlder() + else void earlierPage() + }} style={({ pressed }) => [styles.earlierPill, pressed && { opacity: 0.72 }]} > {s.bots.loadOlder} )} + {earlier.map((entry, i) => entry.kind === 'btw' ? void perform('btw-cancel', { sessionId: bot!.id, id: entry.id })} onDelete={() => void perform('btw-delete', { sessionId: bot!.id, cardId: entry.id })} /> : entry.kind === 'closed' ? : entry.kind === 'view' ? {}} /> : {entry.kind === 'user' ? s.bots.yourAnswer : bot?.name}{text(entry.via) !== '' && })} } ListFooterComponent={ {room && progress.length > 0 && } {room && speaking.map(id => {state.bots.find(bot => bot.id === id)?.name ?? id} · {s.bots.relayTyping})} {room?.paused && {s.bots.roomPaused}