Import apps/android/src/screens/bot/conversation.tsx
This commit is contained in:
parent
bc01a1eec3
commit
5fb612cc60
|
|
@ -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<TextInput>(null)
|
||||
const sendingRef = useRef(false)
|
||||
const [atQuery, setAtQuery] = useState<string | null>(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<ReferenceChatCandidate[]>([])
|
||||
const [fileLinkPath, setFileLinkPath] = useState<string>()
|
||||
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<BotObject[]>([])
|
||||
const [speaking, setSpeaking] = useState<string[]>([])
|
||||
const [earlier, setEarlier] = useState<BotObject[]>([])
|
||||
const [cursor, setCursor] = useState<unknown>(undefined)
|
||||
const [olderBusy, setOlderBusy] = useState(false)
|
||||
const olderBusyRef = useRef(false)
|
||||
const [error, setError] = useState<string>()
|
||||
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<number | undefined>(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<typeof setTimeout> | 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<boolean> => {
|
||||
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<typeof setTimeout> | 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<string | undefined>(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<typeof setTimeout> | 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<string, unknown> | 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<typeof ChatItemView>[0]['onApproval'] = async (...args) => { if (!disabled) await respondApproval(...args) }
|
||||
const onQuestion: Parameters<typeof ChatItemView>[0]['onQuestion'] = async (...args) => { if (!disabled) await respondQuestion(...args) }
|
||||
const onApproval: Parameters<typeof ChatItemView>[0]['onApproval'] = async (...args) => {
|
||||
if (disabled) return
|
||||
await respondApproval(...args)
|
||||
void refreshLive({ forceFull: true })
|
||||
}
|
||||
const onQuestion: Parameters<typeof ChatItemView>[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 <ChatItemView item={item} compact={false} artifacts={artifacts} onSendPrompt={onSendPrompt} busyAction={storeBusy} onApproval={onApproval} onQuestion={onQuestion} userBubble={room !== undefined} />
|
||||
}
|
||||
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<ComposerInputBridge>(() => ({
|
||||
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 <BotMessageActionsContext.Provider value={true}><MarkdownLinkProvider onLinkPress={onLinkPress} transformText={transformText}><View style={styles.flex}>
|
||||
<FlatList ref={list} data={ready ? rows : []} keyExtractor={item => item.key} renderItem={({ item, index }) => (
|
||||
<View style={{ paddingTop: 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={<View style={styles.section}>
|
||||
{earlier.map((entry, i) => entry.kind === 'btw' ? <BotAsideCard key={`btw:${text(entry.id)}`} card={entry} busy={disabled} cancel={() => void perform('btw-cancel', { sessionId: bot!.id, id: entry.id })} onDelete={() => void perform('btw-delete', { sessionId: bot!.id, id: entry.id })} /> : entry.kind === 'closed' ? <BotSettledCard key={i} title={text(entry.title) || text(object(entry.question).question) || s.bots.question} closed={text(entry.closed) || 'dismissed'} /> : entry.kind === 'view' ? <BotViewCard key={i} pending={entry} busy reply={() => {}} /> : <View key={i} style={styles.card}><View style={styles.row}><Text style={[styles.muted, styles.grow]}>{entry.kind === 'user' ? s.bots.yourAnswer : bot?.name}</Text>{text(entry.via) !== '' && <BotViaPill platform={text(entry.via)} />}</View><NativeMarkdown text={text(entry.text)} /></View>)}
|
||||
{hasMore && (
|
||||
{showLoadOlder && (
|
||||
<View style={styles.earlierTop}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={s.bots.loadOlder}
|
||||
disabled={olderLoading || !ready}
|
||||
onPress={() => { 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 }]}
|
||||
>
|
||||
<Text style={styles.earlierPillText}>{s.bots.loadOlder}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)}
|
||||
{earlier.map((entry, i) => entry.kind === 'btw' ? <BotAsideCard key={`btw:${text(entry.id)}`} card={entry} busy={disabled} cancel={() => void perform('btw-cancel', { sessionId: bot!.id, id: entry.id })} onDelete={() => void perform('btw-delete', { sessionId: bot!.id, cardId: entry.id })} /> : entry.kind === 'closed' ? <BotSettledCard key={i} title={text(entry.title) || text(object(entry.question).question) || s.bots.question} closed={text(entry.closed) || 'dismissed'} /> : entry.kind === 'view' ? <BotViewCard key={i} pending={entry} busy reply={() => {}} /> : <View key={i} style={styles.card}><View style={styles.row}><Text style={[styles.muted, styles.grow]}>{entry.kind === 'user' ? s.bots.yourAnswer : bot?.name}</Text>{text(entry.via) !== '' && <BotViaPill platform={text(entry.via)} />}</View><NativeMarkdown text={text(entry.text)} /></View>)}
|
||||
</View>}
|
||||
ListFooterComponent={<View style={styles.section}>
|
||||
{room && progress.length > 0 && <BotReplies rows={progress} botOf={botById} mentions={mentions} adminId={text(room?.admin)} />}
|
||||
{room && speaking.map(id => <View key={id} style={styles.row}><ActivityIndicator size="small" /><Text style={styles.muted}>{state.bots.find(bot => bot.id === id)?.name ?? id} · {s.bots.relayTyping}</Text></View>)}
|
||||
{room?.paused && <View style={styles.section}><Text style={styles.body}>{s.bots.roomPaused}</Text><Button label={s.bots.roomContinue} disabled={disabled} onPress={() => void perform('room-continue', { roomId: room.id })} /></View>}
|
||||
{bot && objects(state.btwCards[bot.id]).filter(card => card.botId === bot.id && card.partId === session.sessionId).slice().reverse().map(card => <BotAsideCard key={text(card.id)} card={card} busy={disabled} cancel={() => void perform('btw-cancel', { sessionId: bot.id, id: card.id })} onDelete={() => void perform('btw-delete', { sessionId: bot.id, id: card.id })} />)}
|
||||
{bot && objects(state.btwCards[bot.id]).filter(card => card.botId === bot.id && card.partId === session.sessionId).slice().reverse().map(card => <BotAsideCard key={text(card.id)} card={card} busy={disabled} cancel={() => void perform('btw-cancel', { sessionId: bot.id, id: card.id })} onDelete={() => void perform('btw-delete', { sessionId: bot.id, cardId: card.id })} />)}
|
||||
{approvals.map(approval => <View key={text(approval.id)} style={styles.card}><Text style={styles.heading}>{state.bots.find(entry => entry.id === approval.botId)?.name} · {text(approval.tool)}</Text><Text style={styles.body}>{text(approval.reason)}</Text><View style={styles.actions}><Button variant="secondary" label={s.bots.reject} disabled={disabled} onPress={() => void perform('approval-answer', { id: approval.id, choice: 'reject' })} /><Button label={s.bots.allow} disabled={disabled} onPress={() => void perform('approval-answer', { id: approval.id, choice: 'allow' })} /></View></View>)}
|
||||
{text(question.id) !== '' && <BotQuestion key={text(question.id)} question={question} busy={disabled} answer={answer => void perform('answer-question', { sessionId: session.sessionId, questionId: question.id, answer })} dismiss={() => void perform('dismiss-question', { sessionId: session.sessionId })} />}
|
||||
{text(view.id) !== '' && <BotViewCard key={text(view.id)} pending={view} busy={disabled} reply={(action, values) => void perform('view-reply', { sessionId: session.sessionId, viewId: view.id, action, values })} />}
|
||||
|
|
@ -569,82 +810,49 @@ export function BotConversation({ bot, room, state, client, session, busy, activ
|
|||
<QueueDock items={queueItems} />
|
||||
</View>
|
||||
)}
|
||||
{atQuery !== null && botAtMentionGroups.length > 0 && (
|
||||
<View style={{ paddingHorizontal: 14 }}>
|
||||
<MentionPopover
|
||||
groups={botAtMentionGroups}
|
||||
onDismiss={() => setAtQuery(null)}
|
||||
emptyText={s.mention.noMatches}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
<View style={styles.composerOuter}>
|
||||
<View style={[styles.composerCard, stagedReferences.length > 0 && styles.composerCardWithPills]}>
|
||||
<View style={chatStyles.composerWrap}>
|
||||
<View style={[chatStyles.composerInner, readableColumn]}>
|
||||
<ReferencedChatPills
|
||||
items={stagedReferences}
|
||||
onRemove={sid => setStagedReferences(current => current.filter(item => item.sessionId !== sid))}
|
||||
/>
|
||||
<View style={styles.composerRow}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={s.chat.moreActions}
|
||||
disabled={disabled}
|
||||
onPress={() => setPlusMenuOpen(true)}
|
||||
style={({ pressed }) => [styles.plusCircle, pressed && { opacity: 0.72 }, disabled && { opacity: 0.4 }]}
|
||||
>
|
||||
<Plus size={18} color={colors.ink} strokeWidth={2.1} />
|
||||
</Pressable>
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
accessibilityLabel={bot ? s.bots.askBot(bot.name) : room ? s.bots.askBot(room.name) : s.bots.message}
|
||||
placeholder={bot ? s.bots.askBot(bot.name) : room ? s.bots.askBot(room.name) : s.bots.message}
|
||||
placeholderTextColor={colors.muted}
|
||||
style={styles.composerInput}
|
||||
multiline
|
||||
editable={!inputDisabled}
|
||||
value={draft}
|
||||
onChangeText={handleDraftChange}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
selectionColor={colors.accent}
|
||||
cursorColor={colors.accent}
|
||||
/>
|
||||
{selected?.running && (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={s.bots.stop}
|
||||
disabled={disabled}
|
||||
onPress={() => void stopSession()}
|
||||
style={({ pressed }) => [styles.stopCircle, pressed && { opacity: 0.78 }]}
|
||||
>
|
||||
<Square size={12} color={colors.surface} fill={colors.surface} />
|
||||
</Pressable>
|
||||
)}
|
||||
{busy ? (
|
||||
<View style={styles.sendCircle}>
|
||||
<ActivityIndicator size="small" color={colors.surface} />
|
||||
</View>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={s.bots.send}
|
||||
disabled={disabled || (!draft.trim() && stagedReferences.length === 0)}
|
||||
onPress={() => void send()}
|
||||
style={({ pressed }) => [
|
||||
styles.sendCircle,
|
||||
(disabled || (!draft.trim() && stagedReferences.length === 0)) && styles.sendCircleDisabled,
|
||||
pressed && { opacity: 0.82 },
|
||||
]}
|
||||
>
|
||||
<ArrowUp size={18} color={colors.surface} strokeWidth={2.4} />
|
||||
</Pressable>
|
||||
)}
|
||||
</View>
|
||||
<ChatComposer
|
||||
draft={draft}
|
||||
input={composerInputBridge}
|
||||
accessibilityLabel={composerLabel}
|
||||
placeholder={composerLabel}
|
||||
highlightMentionTokens={false}
|
||||
replyActive={replyActive}
|
||||
stopping={stopping}
|
||||
sending={busy}
|
||||
hasComposerContent={hasComposerContent}
|
||||
connected={connected}
|
||||
editable={!inputDisabled}
|
||||
composerDisabled={disabled}
|
||||
sendDisabled={composerSendDisabled}
|
||||
compactComposer={compactComposer}
|
||||
composerInputMaxHeight={composerInputMaxHeight}
|
||||
onOpenExpand={() => setComposerExpanded(true)}
|
||||
onOpenActions={() => {
|
||||
Keyboard.dismiss()
|
||||
setAtQuery(null)
|
||||
setPlusMenuOpen(true)
|
||||
}}
|
||||
onOpenPrompts={() => {
|
||||
Keyboard.dismiss()
|
||||
setAtQuery(null)
|
||||
setPromptsPickerOpen(true)
|
||||
}}
|
||||
onSubmit={() => void send()}
|
||||
onStop={() => void stopSession()}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
<BotPlusMenuModal
|
||||
visible={plusMenuOpen}
|
||||
onClose={() => setPlusMenuOpen(false)}
|
||||
onReferenceChat={() => setReferenceChatOpen(true)}
|
||||
onOpenPrompts={() => setPromptsPickerOpen(true)}
|
||||
onOpenSchedules={() => void perform('schedules')}
|
||||
/>
|
||||
<ReferenceChatModal
|
||||
|
|
@ -655,6 +863,42 @@ export function BotConversation({ bot, room, state, client, session, busy, activ
|
|||
onClose={() => setReferenceChatOpen(false)}
|
||||
onPick={(_mentionText, candidate) => handlePickReferencedChat(_mentionText, candidate)}
|
||||
/>
|
||||
<PromptsPicker
|
||||
visible={promptsPickerOpen}
|
||||
prompts={customPrompts ?? BUILT_IN_PROMPTS}
|
||||
actionMode={quickPromptActionMode}
|
||||
onToggleActionMode={mode => {
|
||||
void setQuickPromptActionMode(mode).catch(() => {
|
||||
Alert.alert(s.settings.quickPromptActionMode, s.settings.quickPromptActionSaveFailed)
|
||||
})
|
||||
}}
|
||||
onClose={() => setPromptsPickerOpen(false)}
|
||||
onPick={prompt => void pickQuickPrompt(prompt)}
|
||||
onManage={() => { setPromptsPickerOpen(false); setPromptsManagerOpen(true) }}
|
||||
/>
|
||||
<PromptsManager
|
||||
visible={promptsManagerOpen}
|
||||
prompts={customPrompts ?? BUILT_IN_PROMPTS}
|
||||
promptsLoading={promptsLoading}
|
||||
onBack={() => { setPromptsManagerOpen(false); setPromptsPickerOpen(true) }}
|
||||
onClose={() => setPromptsManagerOpen(false)}
|
||||
onAdd={() => { setPromptsManagerOpen(false); setPromptEditing('new') }}
|
||||
onEdit={prompt => { setPromptsManagerOpen(false); setPromptEditing(prompt) }}
|
||||
onDelete={prompt => {
|
||||
Alert.alert(s.chat.toolPromptDeleteTitle(prompt.title), s.chat.toolPromptDeleteBody, [
|
||||
{ text: s.common.cancel, style: 'cancel' },
|
||||
{ text: s.common.delete, style: 'destructive', onPress: () => void deletePrompt(prompt) },
|
||||
])
|
||||
}}
|
||||
/>
|
||||
<PromptEditor
|
||||
visible={promptEditing !== null}
|
||||
prompt={promptEditing === 'new' || promptEditing === null ? undefined : promptEditing}
|
||||
promptsLoading={promptsLoading}
|
||||
onBack={() => { setPromptEditing(null); setPromptsManagerOpen(true) }}
|
||||
onClose={() => setPromptEditing(null)}
|
||||
onSave={(title, text) => void savePromptEdit(title, text)}
|
||||
/>
|
||||
{fileLinkPath !== undefined && connected && ready && <SessionToolsPanel
|
||||
key={`${session.sessionId}:${fileLinkPath}`} mode="files" sessionId={session.sessionId}
|
||||
initialFile={fileLinkPath} onClose={() => setFileLinkPath(undefined)} />}
|
||||
|
|
@ -662,22 +906,24 @@ export function BotConversation({ bot, room, state, client, session, busy, activ
|
|||
}
|
||||
|
||||
function BotLedgerReplies({ client, sessionId, callId, range, botOf, mentions, adminId, fallback }: {
|
||||
client: BotRemoteClient; sessionId: string; callId: string; range: { from: number; to?: number; anchor?: string }
|
||||
client?: BotRemoteClient; sessionId: string; callId: string; range: { from: number; to?: number; anchor?: string }
|
||||
botOf?: (botId: string) => BotEntry | undefined; mentions?: BotMentionContext; adminId?: string; fallback: React.ReactNode
|
||||
}) {
|
||||
const scope = useAppStore(browseScope)
|
||||
const canCache = useAppStore(state => Boolean(state.config?.baseUrl && state.selectedDevice?.identityKey))
|
||||
const round = JSON.stringify([range.from, range.to, range.anchor])
|
||||
const liveRows = useBrowseMemory(state => canCache ? state.entries[browseKey(scope, sessionId)]?.groupRounds?.[`call:${callId}`] : undefined)
|
||||
const cachedRows = useBrowseMemory(state => canCache ? state.entries[browseKey(scope, sessionId)]?.groupRounds?.[round] : undefined)
|
||||
const [loadError, setLoadError] = useState<string>()
|
||||
const [rows, setRows] = useState<BotObject[]>(() => canCache ? getCachedGroupRound(scope, sessionId, round) ?? [] : [])
|
||||
const shown = preferredRoomRows(liveRows, rows)
|
||||
const [rows, setRows] = useState<BotObject[]>()
|
||||
const shown = preferredRoomRows(liveRows ?? cachedRows, rows)
|
||||
useEffect(() => {
|
||||
const control = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let misses = 0
|
||||
setLoadError(undefined)
|
||||
setRows(canCache ? getCachedGroupRound(scope, sessionId, round) ?? getCachedGroupRound(scope, sessionId, `call:${callId}`) ?? [] : [])
|
||||
setRows(undefined)
|
||||
if (!client) return
|
||||
let misses = 0
|
||||
const tick = async () => {
|
||||
let poll: RoomRowsPoll
|
||||
try {
|
||||
|
|
|
|||
Loading…
Reference in New Issue