import * as Haptics from 'expo-haptics' import { ArrowDown, ArrowLeft, FileText, Film, ListTree, Menu, MessageSquare, RefreshCw, X } from 'lucide-react-native' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { AccessibilityInfo, ActivityIndicator, Animated, DeviceEventEmitter, Easing, FlatList, Image, Keyboard, Modal, NativeModules, PanResponder, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' import { Alert } from '../ui/alert' import { shouldConfirmSwipeRightOpen, shouldStartSwipeRightToOpen } from '../lib/gesture-swipe-rules' import { isSubagentSession } from '../lib/session-kind' import { workspaceStableKey } from '../lib/workspace-key' import { strings } from '../locales/i18n' import { sessionPermissions } from '../services/session-permissions' import type { CustomPrompt } from '../services/storage' import { BUILT_IN_PROMPTS } from '../services/storage' import type { ChatSection } from '../state/message-helpers' import { isKnownBotSessionId, useBotTeamStore } from '../state/bot-store' import { chatImageConnectionGeneration, requireConnectionRpc, requireSessionTools, sessionChatImageLoader, useAppStore } from '../state/store' import { type UiArtifact } from '../state/ui-artifacts' import type { ChatItem, ModelCatalogModel, ModelProviderGroup, PermissionSelect, PromptImage, WorkspaceView } from '../types' import { AnimatedEllipsis } from '../ui/animated-ellipsis' import { ChatImageProvider } from '../ui/chat-image' import { BlurHeaderFrame, IconButton, TopBar } from '../ui/components' import { KeyboardInset } from '../ui/keyboard-inset' import { decodeSessionMentionUri, markdownFilePath, MarkdownLinkProvider, openSafeExternalUrl } from '../ui/markdown' import { NavigationFocusProvider } from '../ui/mention-popover' import { OfficialMenuIcons } from '../ui/official-menu-icons' import { useResponsiveLayout } from '../ui/responsive' import { spacing } from '../ui/theme' import { useTheme } from '../ui/theme-context' import { useThemedStyles } from '../ui/use-themed-styles' import { easingCurve, resolveMotion, type Rect } from '../ui/motion' import { triggerLightHaptic } from '../ui/haptics' import { useReduceMotion } from '../ui/use-reduce-motion' import { AutomationTasksModal } from './automation-tasks-modal' import { ChatErrorBoundary } from './chat-error-boundary' import { formatDurationMs, formatFileBytes, formatUploadedFilesPrompt, formatUploadedFilesReferencePrompt, isDirectTransportMode, isVideoFile, uploadStagedFilesToWorkspace, workspaceUploadMaxBytes, type StagedFile, type UploadProgress } from './chat-files' import { ChatTrajectory } from './chat-trajectory' import { ChatActionMenu } from './chat/action-menu' import { BACKEND_CHAT_TEXT_KEYS, ChatComposer } from './chat/composer' import { applyQuickPromptDraft, composerEditable, submitIntent } from './chat/composer-gate' import { ExpandedComposer } from './chat/expanded-composer' import { ChatImages, ChatItemView, ChatProcessGroup, isActiveChatItem, QueueDock, ReplyStatusBanner, WelcomeMessage } from './chat/messages' import { agentPresetName, builtinPresetName, ModelPicker, ModePicker, permissionDisplayName, PermissionPicker, PromptEditor, PromptsManager, PromptsPicker, ToolAccessPicker, WorkspacePicker, } from './chat/pickers' import { sessionTitle } from './chat/presentation' import { SessionActivityDock } from './chat/session-activity' import { SessionInfo } from './chat/session-info' import { createStyles } from './chat/styles' import { useChatAttachments } from './chat/use-chat-attachments' import { useChatBackHandler } from './chat/use-chat-back-handler' import { useChatMentions } from './chat/use-chat-mentions' import { useChatPrompts } from './chat/use-chat-prompts' import { useChatScroll } from './chat/use-chat-scroll' import { useChatTranscript } from './chat/use-chat-transcript' import { BotModeScreen } from './bot-mode-screen' import { useLiveSessionStatus } from './device-screens' import { HostSessionsDrawer } from './host-sessions-drawer' import { PluginsModal } from './plugins-modal' import { ReferenceChatModal, ReferencedChatPills } from './bot/reference-chat-modal' import type { ReferenceChatCandidate } from './bot/at-menu' import { SessionToolsPanel } from './session-tools-panel' import { browseKey, browseScope, updateBrowseEntry, useBrowseMemory } from '../services/browse-memory' import { formatQuoteText, QuotePreview } from '../ui/quote-preview' const EMPTY_QUOTES: string[] = [] const EMPTY_IMAGES: PromptImage[] = [] const EMPTY_CHAT_ITEMS: ChatItem[] = [] const EMPTY_UI_ARTIFACTS: UiArtifact[] = [] /** Hard cap mirroring the largest backend prompt budget (ACP/CodeX 256 KiB). */ const LONG_DRAFT_MAX = 256_000 export function ChatScreen({ active = true, suppressAutoSelect = false, onBack = () => {}, onOpenDevices: _onOpenDevices, onNewSession, onOpenWorkspaces, onOpenDeviceInfo, onOpenHostSwitcher, onOpenSettings, onOpenAbout, botMode = false, externalOpenRevision, botConversationId, onBotModeChange, onSelectBot, }: { active?: boolean suppressAutoSelect?: boolean onBack?: () => void onOpenDevices?: () => void onNewSession?: () => void onOpenWorkspaces?: (focusWorkspaceKey?: string) => void onOpenDeviceInfo?: () => void onOpenHostSwitcher?: () => void onOpenSettings?: () => void onOpenAbout?: () => void botMode?: boolean externalOpenRevision?: number botConversationId?: string onBotModeChange?: (botMode: boolean) => void onSelectBot?: (id?: string) => void }) { const reduceMotion = useReduceMotion() const session = useAppStore(state => state.selectedSession) const archivedSessionIds = useAppStore(state => state.archivedSessionIds) // Legacy Hosts keep the 8s poll; event-capable Hosts use `$events` + `session/control`. // Keep this mounted in chat so subagent/running updates still arrive when list screens unmount. useLiveSessionStatus(!botMode && session !== undefined && (session.backend ?? 'harness') === 'harness') const hostId = useAppStore(state => state.selectedDevice?.deviceId) const hostPlatform = useAppStore(state => state.selectedDevice?.platform) const messages = useAppStore(state => session === undefined ? EMPTY_CHAT_ITEMS : state.messages[session.sessionId] ?? EMPTY_CHAT_ITEMS) const busy = useAppStore(state => state.busyAction) const codexReadySessionId = useAppStore(state => state.codexReadySessionId) const connection = useAppStore(state => state.connection) const imageGeneration = chatImageConnectionGeneration() const imageLoader = useMemo(() => session === undefined || connection.phase !== 'connected' ? undefined : sessionChatImageLoader(session), [session?.sessionId, session?.backend, hostId, imageGeneration, connection.phase]) const historyHasMore = useAppStore(state => state.historyHasMore) const historyLoadingOlder = useAppStore(state => state.historyLoadingOlder) const sessionModels = useAppStore(state => state.sessionModels) const modelSelecting = useAppStore(state => state.modelSelecting) const permissionSelecting = useAppStore(state => state.permissionSelecting) const sendMessage = useAppStore(state => state.sendMessage) const stopSession = useAppStore(state => state.stopSession) const cancelCompaction = useAppStore(state => state.cancelCompaction) const reconnect = useAppStore(state => state.reconnect) const openSession = useAppStore(state => state.openSession) const respondApproval = useAppStore(state => state.respondApproval) const respondQuestion = useAppStore(state => state.respondQuestion) const loadOlderHistory = useAppStore(state => state.loadOlderHistory) const selectModel = useAppStore(state => state.selectModel) const selectPermission = useAppStore(state => state.selectPermission) const loadAgentPresets = useAppStore(state => state.loadAgentPresets) const selectAgentPreset = useAppStore(state => state.selectAgentPreset) const createSession = useAppStore(state => state.createSession) const archiveSession = useAppStore(state => state.archiveSession) const workspaces = useAppStore(state => state.workspaces) const sessions = useAppStore(state => state.sessions) const agentPresetOptions = useAppStore(state => state.agentPresetOptions) const agentPresetLoading = useAppStore(state => state.agentPresetLoading) const agentPresetSelecting = useAppStore(state => state.agentPresetSelecting) const quickPromptActionMode = useAppStore(state => state.quickPromptActionMode) const setQuickPromptActionMode = useAppStore(state => state.setQuickPromptActionMode) const previewImageUri = useAppStore(state => state.previewImageUri) const setPreviewImageUri = useAppStore(state => state.setPreviewImageUri) // Lightbox grows from the tap instead of a whole-screen cross fade. const lightboxMotion = useRef(new Animated.Value(0)).current useEffect(() => { if (previewImageUri === undefined) return lightboxMotion.setValue(0) const animation = Animated.timing(lightboxMotion, { toValue: 1, duration: resolveMotion('fullscreen', reduceMotion).duration, easing: Easing.bezier(...easingCurve('expand')), useNativeDriver: true, }) animation.start() return () => animation.stop() }, [previewImageUri, lightboxMotion, reduceMotion]) const memoryScope = browseScope(useAppStore.getState()) const memoryKey = browseKey(memoryScope, session?.sessionId ?? '') const draft = useBrowseMemory(state => state.entries[memoryKey]?.draft ?? '') const memoryError = useBrowseMemory(state => state.error) const setDraft = (value: string) => updateBrowseEntry(memoryScope, session?.sessionId ?? '', {draft: value}) const [trajectory, setTrajectory] = useState(false) // Enter-only motion for the transcript <-> trajectory swap. Both views keep // their own scroll state; only the incoming view moves. const trajectoryMotion = useRef(new Animated.Value(1)).current const trajectoryMountedRef = useRef(false) useEffect(() => { if (!trajectoryMountedRef.current) { trajectoryMountedRef.current = true return } trajectoryMotion.setValue(0) const animation = Animated.timing(trajectoryMotion, { toValue: 1, duration: resolveMotion('fullscreen', reduceMotion).duration, easing: Easing.bezier(...easingCurve('expand')), useNativeDriver: true, }) animation.start() return () => animation.stop() }, [trajectory, trajectoryMotion, reduceMotion]) const [sessionsOpen, setSessionsOpen] = useState(true) const [drawerEntrance, setDrawerEntrance] = useState<'immediate' | 'slide'>('immediate') const drawerBackRef = useRef<(() => boolean) | undefined>(undefined) // Cold start parks the sidebar full-screen before any page is chosen; swiping // or pressing back must not drop the user into an arbitrary conversation. const [drawerSwipeUnlocked, setDrawerSwipeUnlocked] = useState(false) const markConversationChosen = () => setDrawerSwipeUnlocked(true) const lastHostIdRef = useRef(hostId) useEffect(() => { if (hostId === lastHostIdRef.current) return lastHostIdRef.current = hostId setDrawerSwipeUnlocked(false) setDrawerEntrance('immediate') setSessionsOpen(true) }, [hostId]) // Explicit navigation must also reveal an already selected conversation. // A revision (rather than session identity) handles repeated notification taps. useEffect(() => { if (externalOpenRevision === undefined) return setDrawerSwipeUnlocked(true) setSessionsOpen(false) }, [externalOpenRevision]) const [automationTasksOpen, setAutomationTasksOpen] = useState(false) const [pluginsOpen, setPluginsOpen] = useState(false) const pluginsAvailable = useAppStore(state => state.connection.phase === 'connected') const [sessionInfoOpen, setSessionInfoOpen] = useState(false) // Web-style blue marks: `/` commands and `@` references render in accent blue. const images = useBrowseMemory(state => state.entries[memoryKey]?.images ?? EMPTY_IMAGES) const setImages = (value: PromptImage[] | ((previous: PromptImage[]) => PromptImage[])) => { const previous = useBrowseMemory.getState().entries[memoryKey]?.images ?? EMPTY_IMAGES updateBrowseEntry(memoryScope, session?.sessionId ?? '', {images: typeof value === 'function' ? value(previous) : value}) } const quotes = useBrowseMemory(state => state.entries[memoryKey]?.quotes ?? EMPTY_QUOTES) const setQuotes = (value: string[] | ((previous: string[]) => string[])) => { const previous = useBrowseMemory.getState().entries[memoryKey]?.quotes ?? EMPTY_QUOTES updateBrowseEntry(memoryScope, session?.sessionId ?? '', {quotes: typeof value === 'function' ? value(previous) : value}) } const [modelPickerOpen, setModelPickerOpen] = useState(false) const [permissionPickerOpen, setPermissionPickerOpen] = useState(false) const mentionInput = useChatMentions({ session, sessions, workspaces, connectionPhase: connection.phase, draft, setDraft, setPermissionPickerOpen, setModelPickerOpen, }) const { composerInputRef, draftRef, mentionType, setMentionType, applyDraft, closeMention, resetSelection } = mentionInput const lastQuoteCountRef = useRef(quotes.length) useEffect(() => { if (quotes.length > lastQuoteCountRef.current) { composerInputRef.current?.focus() } lastQuoteCountRef.current = quotes.length }, [quotes.length, composerInputRef]) useEffect(() => { if (NativeModules.DshProcessText?.getInitialText) { NativeModules.DshProcessText.getInitialText().then((text: string | null) => { if (text && text.trim().length > 0) { setQuotes(current => [...current, text.trim()]) composerInputRef.current?.focus() } }).catch(() => {}) } const sub = DeviceEventEmitter.addListener('onProcessText', (text: string) => { if (text && text.trim().length > 0) { setQuotes(current => [...current, text.trim()]) composerInputRef.current?.focus() } }) return () => { sub.remove() } }, [setQuotes, composerInputRef]) const [stagedFiles, setStagedFiles] = useState([]) const [uploadingFiles, setUploadingFiles] = useState(false) const [uploadProgress, setUploadProgress] = useState() const uploadingRef = useRef(false) const uploadControllerRef = useRef(undefined) const sessionGenerationRef = useRef(0) useLayoutEffect(() => { let lastSessionId = useAppStore.getState().selectedSession?.sessionId return useAppStore.subscribe((state) => { const currentId = state.selectedSession?.sessionId if (currentId !== lastSessionId) { lastSessionId = currentId sessionGenerationRef.current += 1 uploadControllerRef.current?.abort() setUploadProgress(undefined) setStagedFiles([]) } }) }, []) useEffect(() => () => { uploadControllerRef.current?.abort() }, []) useEffect(() => { if (connection.phase !== 'connected') uploadControllerRef.current?.abort() }, [connection.phase]) const { attachmentPicking, pickImages, takePhoto, pickFiles } = useChatAttachments({ session, memoryKey, images, setImages, stagedFiles, setStagedFiles, sessionGenerationRef, }) const [plusMenuOpen, setPlusMenuOpen] = useState(false) const [sheetAnchor, setSheetAnchor] = useState() const composerAnchorRef = useRef(null) const [referenceChatOpen, setReferenceChatOpen] = useState(false) const [stagedReferences, setStagedReferences] = useState([]) const [modePickerOpen, setModePickerOpen] = useState(false) const [workspacePickerOpen, setWorkspacePickerOpen] = useState(false) const [toolPickerOpen, setToolPickerOpen] = useState(false) const [toolsMode, setToolsMode] = useState<'files' | 'terminal'>() const [fileLinkPath, setFileLinkPath] = useState() const { promptsPickerOpen, setPromptsPickerOpen, customPrompts, promptEditing, setPromptEditing, promptsManagerOpen, setPromptsManagerOpen, promptsLoading, savePromptEdit, deletePrompt } = useChatPrompts(connection.phase) const [permissionOptions, setPermissionOptions] = useState() const [permissionError, setPermissionError] = useState() const [permissionRevision, setPermissionRevision] = useState(0) const [permissionLoading, setPermissionLoading] = useState(false) const inlinePermissionOptions = session?.projections?.values?.permissions useEffect(() => { setPermissionOptions(undefined) setPermissionError(undefined) setPermissionLoading(false) if (session === undefined || session.backend === 'codex' || connection.phase !== 'connected') return const projected = sessionPermissions(session) if (projected === undefined || projected.options.length > 0) return const controller = new AbortController() setPermissionLoading(true) void Promise.resolve().then(() => requireSessionTools().permissionOptions(controller.signal)) .then(options => { if (!controller.signal.aborted) setPermissionOptions(options) }) .catch(() => { if (!controller.signal.aborted) setPermissionError(strings.tools.permissionUnavailable) }) .finally(() => { if (!controller.signal.aborted) setPermissionLoading(false) }) return () => controller.abort() }, [session?.sessionId, session?.backend, inlinePermissionOptions, connection.phase, permissionPickerOpen, permissionRevision]) // A carrier drop must not close the full-screen editor: the draft stays // editable offline, so only a conversation change collapses it. useEffect(() => { setToolsMode(undefined) }, [session?.sessionId, connection.phase]) useEffect(() => { setComposerExpanded(false) }, [session?.sessionId]) // The mode (agent-preset) roster is deployment-level; fetch it once per connection. useEffect(() => { if (connection.phase !== 'connected' || session?.backend === 'codex') return if (useAppStore.getState().agentPresetOptions !== undefined) return void loadAgentPresets() }, [connection.phase, session?.sessionId, session?.backend, loadAgentPresets]) const [composerExpanded, setComposerExpanded] = useState(false) const [reconnectingSession, setReconnectingSession] = useState(false) const [newSessionPending, setNewSessionPending] = useState(false) const creatingSessionRef = useRef(false) const lastNewSessionTimeRef = useRef(0) const { visibleMessages, visibleSections, uiBySection, visibleUiIds, queueItems, childSessions, teamState } = useChatTranscript({ session, sessions, messages, hostId }) const panelOpen = composerExpanded || plusMenuOpen || modelPickerOpen || modePickerOpen || permissionPickerOpen || workspacePickerOpen || toolPickerOpen || toolsMode !== undefined || trajectory || mentionType !== null || promptsPickerOpen || promptsManagerOpen || promptEditing !== null || sessionInfoOpen const { listRef, viewability, awayFromLatest, newContent, jumpToLatest, beginSendScroll, onListLayout, onListContentSizeChange, onListScroll, onListDragEnd, onListMomentumEnd, onScrollBeginDrag, onMomentumScrollBegin } = useChatScroll({ session, messages, visibleMessages, visibleSections, memoryScope, memoryKey, panelOpen, historyLoadingOlder, busy, setTrajectory, }) const { colors } = useTheme() const styles = useThemedStyles(createStyles) // Landscape phones are short: keep the composer compact when the IME is up // and let the list use a readable centred column on wide windows. const { landscape, compactHeight, height, width, contentMaxWidth } = useResponsiveLayout() const compactComposer = landscape || compactHeight const composerInputMaxHeight = compactComposer ? Math.max(48, Math.min(96, Math.round(height * 0.22))) : 126 // Tablets keep the session list visible beside the conversation. Short // landscape phone windows stay single-pane; a wide tablet keeps the split // even while the IME reduces the window height. const tabletSplit = width >= 760 && (height >= 520 || width >= 1000) useEffect(() => { if (tabletSplit) setSessionsOpen(false) }, [tabletSplit]) const readableColumn = { width: '100%' as const, maxWidth: contentMaxWidth, alignSelf: 'center' as const } const openSessionsDrawer = useCallback(() => { Keyboard.dismiss() setMentionType(null) void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light).catch(() => undefined) // Reached from a conversation, so the sidebar may be swiped away again. setDrawerSwipeUnlocked(true) setDrawerEntrance('slide') setSessionsOpen(true) }, [setMentionType]) // Swipe right gesture to open sessions drawer with haptic feedback const edgeSwipeResponder = useMemo( () => PanResponder.create({ onStartShouldSetPanResponder: () => false, onStartShouldSetPanResponderCapture: () => false, onMoveShouldSetPanResponder: (_evt, g) => { if (tabletSplit || sessionsOpen) return false return shouldStartSwipeRightToOpen({ dx: g.dx, dy: g.dy, x0: g.x0 }, trajectory) }, onMoveShouldSetPanResponderCapture: (_evt, g) => { if (tabletSplit || sessionsOpen) return false return shouldStartSwipeRightToOpen({ dx: g.dx, dy: g.dy, x0: g.x0 }, trajectory) }, onPanResponderTerminationRequest: () => false, onPanResponderRelease: (_evt, g) => { if (tabletSplit || sessionsOpen) return if (shouldConfirmSwipeRightOpen({ dx: g.dx, dy: g.dy, x0: g.x0, vx: g.vx })) { openSessionsDrawer() } }, }), [sessionsOpen, tabletSplit, trajectory, openSessionsDrawer] ) const swipeStartRef = useRef<{ x0: number; y0: number; t0: number } | undefined>(undefined) const swipeRightTouchProps = useMemo( () => ({ ...edgeSwipeResponder.panHandlers, onTouchStart: (e: { nativeEvent: { pageX: number; pageY: number } }) => { swipeStartRef.current = { x0: e.nativeEvent.pageX, y0: e.nativeEvent.pageY, t0: Date.now() } }, onTouchEnd: (e: { nativeEvent: { pageX: number; pageY: number } }) => { const start = swipeStartRef.current swipeStartRef.current = undefined if (start === undefined || tabletSplit || sessionsOpen) return const dx = e.nativeEvent.pageX - start.x0 const dy = e.nativeEvent.pageY - start.y0 const dt = Math.max(16, Date.now() - start.t0) const vx = dx / dt if ( shouldStartSwipeRightToOpen({ dx, dy, x0: start.x0 }, trajectory) && shouldConfirmSwipeRightOpen({ dx, dy, x0: start.x0, vx }) ) { openSessionsDrawer() } }, }), [edgeSwipeResponder, tabletSplit, sessionsOpen, trajectory, openSessionsDrawer], ) // Artifact changes must invalidate FlatList cells even when their section is // reused (a later turn can patch a card owned by an earlier turn). const renderChatItem = useCallback(({ item }: { item: ChatSection }) => item.kind === 'process' ? : , [busy, respondApproval, respondQuestion, uiBySection, visibleUiIds]) // Keep chat's back action at the top of the Android responder stack. The // navigator also handles back globally, but a freshly mounted FlatList can // otherwise win the first dispatch while its cells are being measured. // Back inside a subagent child returns to its parent conversation (the // official subagent UI's navigation), instead of leaving the chat entirely. const backFromChat = () => { if (!tabletSplit && sessionsOpen) { return drawerBackRef.current?.() ?? false } const parent = session !== undefined && isSubagentSession(session) ? sessions.find(item => item.sessionId === session.parentSessionId) : undefined if (parent !== undefined) { Keyboard.dismiss() void openSession(parent) return true } if (!tabletSplit && !sessionsOpen) { openSessionsDrawer() return true } Keyboard.dismiss() onBack() return true } const onBackRef = useRef(backFromChat) onBackRef.current = backFromChat useChatBackHandler(composerInputRef, () => onBackRef.current(), [ { open: composerExpanded, close: () => setComposerExpanded(false) }, { open: plusMenuOpen, close: () => { Keyboard.dismiss(); setPlusMenuOpen(false) } }, { open: referenceChatOpen, close: () => setReferenceChatOpen(false) }, { open: modelPickerOpen, close: () => setModelPickerOpen(false) }, { open: modePickerOpen, close: () => setModePickerOpen(false) }, { open: permissionPickerOpen, close: () => setPermissionPickerOpen(false) }, { open: workspacePickerOpen, close: () => setWorkspacePickerOpen(false) }, { open: toolPickerOpen, close: () => setToolPickerOpen(false) }, { open: promptEditing !== null, close: () => { setPromptEditing(null); setPromptsManagerOpen(true) } }, { open: promptsManagerOpen, close: () => { setPromptsManagerOpen(false); setPromptsPickerOpen(true) } }, { open: promptsPickerOpen, close: () => setPromptsPickerOpen(false) }, { open: toolsMode !== undefined, close: () => { setToolsMode(undefined); setFileLinkPath(undefined) } }, { open: trajectory, close: () => setTrajectory(false) }, ], active) const botTeamState = useBotTeamStore(state => state.state) const openLink = useCallback((href: string) => { // 1. Session reference navigation: dsh-session: const targetSessionId = decodeSessionMentionUri(href) if (targetSessionId !== undefined) { const matchedBot = botTeamState?.bots.find(entry => entry.sessionId === targetSessionId) if (matchedBot !== undefined) { onBotModeChange?.(true) onSelectBot?.(matchedBot.id) return } const targetSession = sessions.find(candidate => candidate.sessionId === targetSessionId) if (targetSession !== undefined) { void openSession(targetSession) } return } // 2. Safe external web URLs (http, https, mailto, www.*) if (openSafeExternalUrl(href)) return // 3. Workspace file link const path = markdownFilePath(href) if (path === undefined) return setFileLinkPath(path) setToolsMode('files') }, [openSession, session?.backend, sessions, botTeamState?.bots, onBotModeChange, onSelectBot]) const connected = connection.phase === 'connected' && !reconnectingSession const hasActiveChatItem = visibleMessages.some(isActiveChatItem) const replyActive = connected && (busy === 'send-message' || busy === 'stop-session' || (session?.running ?? false) || hasActiveChatItem) const lastAgentSessionByScopeRef = useRef>({}) useEffect(() => { if (!botMode && session !== undefined && !isKnownBotSessionId(session.sessionId, botTeamState, memoryScope)) { lastAgentSessionByScopeRef.current[memoryScope] = session } }, [botMode, session, botTeamState, memoryScope]) const findPreferredAgentSession = () => { const candidates = sessions.filter( item => !archivedSessionIds.includes(item.sessionId) && !isKnownBotSessionId(item.sessionId, botTeamState, memoryScope), ) const remembered = lastAgentSessionByScopeRef.current[memoryScope] const preferred = remembered ? candidates.find(item => item.sessionId === remembered.sessionId && (item.backend ?? 'harness') === (remembered.backend ?? 'harness')) : undefined return preferred ?? [...candidates].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))[0] } const switchToAgentMode = () => { const target = findPreferredAgentSession() if (target !== undefined) { void openSession(target) } else if (session !== undefined && isKnownBotSessionId(session.sessionId, botTeamState, memoryScope)) { useAppStore.setState({ selectedSession: undefined }) } onBotModeChange?.(false) } const autoSelectingRef = useRef(false) useEffect(() => { if (botMode || suppressAutoSelect) return const sessionIsBot = session !== undefined && isKnownBotSessionId(session.sessionId, botTeamState, memoryScope) if (sessionIsBot) { useAppStore.setState({ selectedSession: undefined }) } if ((session !== undefined && !sessionIsBot) || busy !== undefined || autoSelectingRef.current) return const target = findPreferredAgentSession() if (target) { autoSelectingRef.current = true void openSession(target).finally(() => { autoSelectingRef.current = false }) } }, [botMode, suppressAutoSelect, session, connected, busy, sessions, archivedSessionIds, openSession, botTeamState, memoryScope]) const drawerElement = (inlineMode: boolean) => ( { markConversationChosen() onSelectBot?.(id) }} onOpenDeviceInfo={() => { Keyboard.dismiss() onOpenDeviceInfo?.() }} onOpenWorkspaces={() => { Keyboard.dismiss() if (onOpenWorkspaces) onOpenWorkspaces() }} onBack={inlineMode ? undefined : () => { Keyboard.dismiss() setSessionsOpen(false) }} backLabel={strings.chat.backToChat} onClose={() => { if (inlineMode) Keyboard.dismiss() else setSessionsOpen(false) }} onOpenAutomationTasks={() => { Keyboard.dismiss() setAutomationTasksOpen(true) }} onOpenPlugins={pluginsAvailable ? () => { Keyboard.dismiss() setPluginsOpen(true) } : undefined} onOpenHostSwitcher={onOpenHostSwitcher ? () => { Keyboard.dismiss() onOpenHostSwitcher() } : undefined} onOpenAbout={onOpenAbout} onOpenSettings={() => { Keyboard.dismiss() onOpenSettings?.() }} onSelect={async next => { markConversationChosen() const pending = openSession(next) onBotModeChange?.(false) const visible = useAppStore.getState().selectedSession?.sessionId === next.sessionId if (!inlineMode && visible) { setSessionsOpen(false) } if (await pending && !inlineMode && !visible) { setSessionsOpen(false) } }} /> ) const defaultTaskWorkspaceId = (session === undefined ? undefined : workspaces.find(w => w.sessionIds.includes(session.sessionId))?.workspaceId) ?? workspaces[0]?.workspaceId const wrapChatShell = (mainPane: ReactNode, extraOverlays?: ReactNode) => ( {tabletSplit && {drawerElement(true)}} {mainPane} {extraOverlays} {sessionsOpen && !tabletSplit && drawerElement(false)} setPluginsOpen(false)} /> setAutomationTasksOpen(false)} onOpenSession={async targetSession => { markConversationChosen() const opened = await openSession(targetSession) onBotModeChange?.(false) if (opened && !tabletSplit) setSessionsOpen(false) setAutomationTasksOpen(false) }} onNewTask={async () => { markConversationChosen() const created = await createSession(defaultTaskWorkspaceId) onBotModeChange?.(false) if (created && !tabletSplit) setSessionsOpen(false) setAutomationTasksOpen(false) }} /> ) if (botMode) { return wrapChatShell( onSelectBot?.(id)} onAgentMode={switchToAgentMode} onOpenDrawer={openSessionsDrawer} onDeviceInfo={() => onOpenDeviceInfo?.()} onMore={() => onOpenSettings?.()} splitView={tabletSplit} drawerOpen={sessionsOpen || tabletSplit} screenActive={active && (!sessionsOpen || tabletSplit)} /> , ) } const sessionIsBot = session !== undefined && isKnownBotSessionId(session.sessionId, botTeamState, memoryScope) if (session === undefined || sessionIsBot) { const emptyHeader = ( void createSession(workspaces[0]?.workspaceId)} disabled={!connected || busy !== undefined} /> {!connected && ( { if (onOpenHostSwitcher) onOpenHostSwitcher() else void reconnect() }} /> )} } /> ) return wrapChatShell( {headerHeight => ( {busy !== undefined ? ( ) : ( )} )} , ) } const submit = async () => { if (session === undefined) return // Read the live ref: the render-closure `draft` can lag the last keystrokes // typed right before the tap, silently dropping the tail of the message. const submittedDraft = draftRef.current const rawText = submittedDraft.trim() const submittedReferences = stagedReferences const refPrefix = submittedReferences.map(item => item.mentionText.trim()).join(' ') const text = [refPrefix, rawText].filter(Boolean).join(' ') const submittedQuotes = quotes const submittedImages = images const submittedFiles = stagedFiles // Everything below this gate clears the composer, so an offline tap has to // stop here: the draft stays, no optimistic row is created and the manual // send after reconnection is the only submission path. const intent = submitIntent({ connected, sendReady, permissionSelecting, uploading: uploadingRef.current, hasContent: text.length > 0 || submittedQuotes.length > 0 || images.length > 0 || stagedFiles.length > 0, }) if (intent !== 'submit') return let promptWithQuotes = text if (submittedQuotes.length > 0) { const formattedQuotes = submittedQuotes.map(formatQuoteText).join('\n\n') promptWithQuotes = text.length > 0 ? `${formattedQuotes}\n\n${text}` : formattedQuotes } let promptText = promptWithQuotes const targetSessionId = session.sessionId const sendSessionGen = sessionGenerationRef.current if (submittedFiles.length > 0) { const transportModeAtStart = useAppStore.getState().connection.stats.mode const maxBytesAtStart = workspaceUploadMaxBytes(transportModeAtStart) const oversizedFile = submittedFiles.find( file => !(typeof file.remotePath === 'string' && file.remotePath.trim().length > 0) && typeof file.content !== 'string' && file.size > maxBytesAtStart, ) if (oversizedFile) { Alert.alert( strings.messageActions.failed, strings.chat.fileTooLargeForTransport( oversizedFile.name, formatFileBytes(maxBytesAtStart), isDirectTransportMode(transportModeAtStart), ), ) return } let failingFile: StagedFile | undefined = submittedFiles[0] const controller = new AbortController() uploadControllerRef.current?.abort() uploadControllerRef.current = controller uploadingRef.current = true setUploadingFiles(true) setUploadProgress({ fileIndex: 0, fileCount: submittedFiles.length, fileName: submittedFiles[0]?.name ?? '', bytesSent: 0, totalBytes: submittedFiles[0]?.size ?? 0, }) try { const rpc = requireConnectionRpc() const uploaded = await uploadStagedFilesToWorkspace( rpc, session.sessionId, submittedFiles, controller.signal, progress => { failingFile = submittedFiles[progress.fileIndex] ?? failingFile if (!controller.signal.aborted && uploadControllerRef.current === controller) { setUploadProgress(progress) } }, ) // A navigation, session switch, reconnection or unmount during a long // upload must never leak the prompt into another conversation. if (controller.signal.aborted) return if (sessionGenerationRef.current !== sendSessionGen || useAppStore.getState().selectedSession?.sessionId !== targetSessionId) return if (useAppStore.getState().connection.phase !== 'connected') { Alert.alert(strings.messageActions.failed, strings.messageActions.unavailable) return } promptText = formatUploadedFilesReferencePrompt(promptWithQuotes, uploaded) } catch (uploadError) { // Aborted uploads already restored (or discarded) their composer state; // do not surface a cancellation as a failure. if (controller.signal.aborted || (uploadError as Error | undefined)?.name === 'AbortError') return const code = (uploadError as { code?: string })?.code const activeFile = failingFile ?? submittedFiles[0] const activeName = activeFile?.name ?? '' const transportMode = useAppStore.getState().connection.stats.mode const maxTransportBytes = workspaceUploadMaxBytes(transportMode) let errorMsg: string if (code === 'FEATURE_NOT_SUPPORTED' || code === 'UPLOAD_WORKSPACE_UNAVAILABLE') { errorMsg = strings.chat.uploadUnavailable } else if (code === 'UPLOAD_LIMIT' && (activeFile?.size ?? 0) > maxTransportBytes) { errorMsg = strings.chat.fileTooLargeForTransport( activeName, formatFileBytes(maxTransportBytes), isDirectTransportMode(transportMode), ) } else { errorMsg = strings.chat.uploadFileFailed(activeName, (uploadError as Error).message) } Alert.alert(strings.messageActions.failed, errorMsg) return } finally { if (uploadControllerRef.current === controller) { uploadControllerRef.current = undefined uploadingRef.current = false setUploadingFiles(false) setUploadProgress(undefined) } } } if (promptText.length > LONG_DRAFT_MAX) { Alert.alert(strings.chat.draftTooLongTitle, strings.chat.draftTooLong(LONG_DRAFT_MAX)) return } applyDraft('') setQuotes([]) setImages([]) setStagedFiles([]) setStagedReferences([]) setMentionType(null) resetSelection() const restoreScrollAfterRejectedSend = beginSendScroll() const outcome = await sendMessage(promptText, submittedImages) if (outcome === 'rejected') { restoreScrollAfterRejectedSend() // Nothing was persisted (command failure): restore the draft without // clobbering input typed while the send was in flight. if (sessionGenerationRef.current === sendSessionGen && useAppStore.getState().selectedSession?.sessionId === targetSessionId) { const inFlight = useBrowseMemory.getState().entries[memoryKey]?.draft ?? '' setDraft(inFlight.length === 0 ? submittedDraft : `${submittedDraft}\n${inFlight}`) setQuotes(previous => previous.length === 0 ? submittedQuotes : [...submittedQuotes, ...previous]) setImages(previous => previous.length === 0 ? submittedImages : [...submittedImages, ...previous]) setStagedReferences(previous => previous.length === 0 ? submittedReferences : [...submittedReferences, ...previous]) setStagedFiles(current => { const seen = new Set() const restored: StagedFile[] = [] for (const f of [...submittedFiles, ...current]) { if (seen.has(f.id)) continue seen.add(f.id) restored.push(f) } return restored }) } Alert.alert(strings.messageActions.failed, useAppStore.getState().error ?? strings.messageActions.unavailable) } else if (outcome === 'sent') { const result = useAppStore.getState().commandResult if (result?.sessionId === session.sessionId && useAppStore.getState().selectedSession?.sessionId === session.sessionId) { Alert.alert(strings.mention.commandSection, result.text) useAppStore.setState({ commandResult: undefined }) } } // 'kept': the row stays in the timeline with an inline failed/unconfirmed // state and a retry affordance — no Alert and no draft restore. } const openPlusMenu = () => { // When the IME is currently open, measuring composerAnchorRef before the // keyboard settles yields a mid-screen y coordinate that would launch the // bottom sheet from an elevated anchor. const imeOpen = typeof Keyboard.isVisible === 'function' && Keyboard.isVisible() Keyboard.dismiss() const node = composerAnchorRef.current if (node === null || imeOpen) { setSheetAnchor(undefined) setPlusMenuOpen(true) return } // One frame of measurement so the sheet can grow out of the composer // instead of the screen edge; a missing measurement falls back to a // bottom rise inside SheetModal. node.measureInWindow((x, y, width, height) => { setSheetAnchor(width > 0 && height > 0 ? { x, y, width, height } : undefined) setPlusMenuOpen(true) }) } const closePlusMenu = () => { Keyboard.dismiss() setPlusMenuOpen(false) } const openPromptsPicker = () => { Keyboard.dismiss() setMentionType(null) setPromptsPickerOpen(true) } const handleBack = () => { Keyboard.dismiss() if (trajectory) { setTrajectory(false) return } onBackRef.current() } const pickModel = async (group: ModelProviderGroup, model: ModelCatalogModel, reasoningEffort?: string) => { setModelPickerOpen(false) await selectModel({ provider: group.id, model: model.id, ...(reasoningEffort === undefined ? {} : { reasoningEffort }), }) } const reconnectCurrentSession = async () => { if (reconnectingSession) return setReconnectingSession(true) try { await reconnect() } finally { setReconnectingSession(false) } } const supportsModeSelection = !['codex', 'cursor', 'antigravity', 'pi', 'opencode', 'claude', 'hermes'].includes(session.backend ?? 'harness') const currentAgentPresetId = session.agentPreset ?? agentPresetOptions?.find(option => option.isDefault)?.id const currentWorkspace = workspaces.find(workspace => workspace.sessionIds.includes(session.sessionId)) const workspaceLabel = currentWorkspace?.title ?? strings.chat.workspaceNone const currentPresetRow = agentPresetOptions?.find(option => option.id === currentAgentPresetId) const modeLabel = currentAgentPresetId === undefined ? strings.chat.modeDefault : currentPresetRow === undefined ? builtinPresetName(currentAgentPresetId) ?? currentAgentPresetId : agentPresetName(currentPresetRow) const connectionRetrying = reconnectingSession || connection.phase === 'connecting' || connection.phase === 'reconnecting' const sendReady = connected && !busy?.startsWith('session:') && (session.backend !== 'codex' || codexReadySessionId === session.sessionId) const hasComposerContent = draft.trim().length > 0 || quotes.length > 0 || images.length > 0 || stagedFiles.length > 0 || stagedReferences.length > 0 const stopping = busy === 'stop-session' const commandRunning = busy === 'command' const stopOrCancel = () => { if (!commandRunning) { void stopSession(); return } // A tracked /compact can run for minutes; the stop control asks the Host to // cancel it and keeps observing the confirmed terminal state. void cancelCompaction().then(cancelled => { if (!cancelled) void stopSession() }) } // Action entries (attachments, tools, prompts) still need the channel, but the // text field itself only blocks on composer-local states so an offline draft // can be typed, edited and kept for the manual send after reconnection. const inputEditable = composerEditable({ permissionSelecting, uploading: uploadingFiles }) const composerDisabled = !connected || permissionSelecting || uploadingFiles const sendDisabled = !sendReady || permissionSelecting || !hasComposerContent || uploadingFiles const projectedPermissions = sessionPermissions(session) const permissions = projectedPermissions === undefined ? undefined : { ...projectedPermissions, options: permissionOptions ?? projectedPermissions.options } const currentPermission = permissions?.options.find(option => option.value === permissions.currentValue) const currentModel = sessionModels?.groups .find(group => group.id === sessionModels.current.provider) ?.models.find(model => model.id === sessionModels.current.model) const currentEffortId = sessionModels?.current.reasoningEffort ?? currentModel?.reasoning?.defaultEffort const currentEffortName = currentModel?.reasoning?.efforts.find(effort => effort.id === currentEffortId)?.name ?? currentEffortId const currentModelName = currentModel?.name ?? sessionModels?.current.model const currentModelLabel = currentEffortName === undefined ? currentModelName : `${currentModelName} · ${currentEffortName}` const pickMode = async (preset: string) => { setModePickerOpen(false) if (!connected || preset === session.agentPreset) return const applied = await selectAgentPreset(preset) if (!applied) { Alert.alert( strings.chat.modeLockedTitle, session.blank ? strings.chat.modeSelectFailedBody : strings.chat.modeLockedBody, ) } } const pickToolMode = (mode: 'files' | 'terminal') => { setToolPickerOpen(false) setFileLinkPath(undefined) setToolsMode(mode) } const sessionBlank = visibleMessages.length === 0 && session.blank !== false const startNewSession = async () => { if (!connected) { Alert.alert(strings.chat.newChatFailedTitle, strings.chat.offlineNotice) return } const now = Date.now() if (now - lastNewSessionTimeRef.current < 800) return if (creatingSessionRef.current || newSessionPending || busy !== undefined) return if (sessionBlank) { Keyboard.dismiss() setMentionType(null) applyDraft('') setImages([]) return } creatingSessionRef.current = true lastNewSessionTimeRef.current = now setNewSessionPending(true) try { const created = await createSession(currentWorkspace?.workspaceId) if (created) { onNewSession?.() } else { Alert.alert(strings.chat.newChatFailedTitle, strings.chat.newChatFailedBody) } } finally { creatingSessionRef.current = false setNewSessionPending(false) } } const pickQuickPrompt = async (prompt: CustomPrompt) => { setPromptsPickerOpen(false) if (quickPromptActionMode === 'fill') { const { draft: nextDraft, cursor } = applyQuickPromptDraft(draftRef.current, prompt.text) applyDraft(nextDraft) mentionInput.setCursor(cursor) setMentionType(null) requestAnimationFrame(() => composerInputRef.current?.focus()) return } if (!connected) { Alert.alert(strings.chat.toolPromptSendFailed, strings.chat.offlineNotice) return } const outcome = await sendMessage(prompt.text) if (outcome === 'sent') AccessibilityInfo.announceForAccessibility(strings.chat.toolPromptSent(prompt.title)) else if (outcome === 'rejected') Alert.alert(strings.chat.toolPromptSendFailed, strings.chat.toolPromptSendFailed) } const moveSessionToWorkspace = async (workspace: WorkspaceView) => { if (!connected) { Alert.alert(strings.chat.moveFailedTitle, strings.chat.offlineNotice) return } const previousId = session.sessionId const opened = await createSession(workspace.workspaceId) if (!opened) { Alert.alert(strings.chat.moveFailedTitle, strings.chat.moveFailedBody) return } // A blank conversation carries nothing to lose: recreate it inside the // chosen workspace and archive the old placeholder so it reads as a move. if (sessionBlank && useAppStore.getState().selectedSession?.sessionId !== previousId) await archiveSession(previousId) } const pickWorkspace = (workspace: WorkspaceView) => { setWorkspacePickerOpen(false) if (!connected) { Alert.alert(strings.chat.moveFailedTitle, strings.chat.offlineNotice) return } if (workspace.sessionIds.includes(session.sessionId)) return if (sessionBlank) { void moveSessionToWorkspace(workspace) return } Alert.alert( strings.chat.moveStartedTitle, strings.chat.moveStartedBody(workspace.title), [ { text: strings.common.cancel, style: 'cancel' }, { text: strings.chat.moveStartedConfirm, onPress: () => void moveSessionToWorkspace(workspace) }, ], ) } const pickPermission = (preset: string) => { setPermissionPickerOpen(false) const apply = () => void selectPermission(preset) if (preset === 'danger-full-access') { Alert.alert( session.backend === 'codex' ? strings.chat.codexFullAccessTitle : strings.chat.fullAccessTitle, session.backend === 'codex' ? strings.chat.codexFullAccessBody : strings.chat.fullAccessBody, [ { text: strings.common.cancel, style: 'cancel' }, { text: strings.chat.enable, style: 'destructive', onPress: apply }, ], ) } else apply() } const header = <> : undefined} onSubtitlePress={sessionModels !== undefined ? () => { Keyboard.dismiss(); setMentionType(null); setModelPickerOpen(true) } : undefined} onTitlePress={() => { Keyboard.dismiss(); setMentionType(null); setSessionInfoOpen(true) }} titleLines={1} titleAlign="between" onBack={tabletSplit ? undefined : trajectory ? handleBack : openSessionsDrawer} backIcon={trajectory ? ArrowLeft : Menu} backLabel={trajectory ? strings.common.back : strings.chat.openHostSessions} action={<> { Keyboard.dismiss(); setMentionType(null); setTrajectory(value => !value) }} /> void startNewSession()} disabled={(sessionBlank && !hasComposerContent) || newSessionPending || busy !== undefined} /> } /> {!connected && ( void reconnectCurrentSession()}> {connectionRetrying ? <>{strings.chat.reconnecting.replace(/…$/, '')} : strings.chat.offline} )} {connected && busy === `session:${session.sessionId}` && ( {strings.chat.syncingHistory} )} return wrapChatShell( {memoryError !== undefined && {memoryError}} {/* Messages scroll beneath the frosted header; the trajectory view keeps its own fixed search bar below it. */} {headerHeight => {trajectory ? } hasMore={historyHasMore} loading={historyLoadingOlder} loadOlder={() => void loadOlderHistory()} renderItem={item => } /> : <> item.key} renderItem={renderChatItem} initialNumToRender={6} maxToRenderPerBatch={6} updateCellsBatchingPeriod={16} windowSize={7} removeClippedSubviews keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" onLayout={onListLayout} onContentSizeChange={onListContentSizeChange} onScroll={onListScroll} onViewableItemsChanged={viewability} onScrollToIndexFailed={info => { listRef.current?.scrollToOffset({offset: Math.max(0, info.averageItemLength * info.index), animated: false}) }} maintainVisibleContentPosition={{minIndexForVisible: 0}} scrollEventThrottle={16} onScrollBeginDrag={onScrollBeginDrag} onScrollEndDrag={onListDragEnd} onMomentumScrollBegin={onMomentumScrollBegin} onMomentumScrollEnd={onListMomentumEnd} ListEmptyComponent={busy === `session:${session.sessionId}` ? : } ListFooterComponent={replyActive ? ( ) : undefined} ListHeaderComponent={historyHasMore ? ( void loadOlderHistory()} style={styles.olderButton} > {historyLoadingOlder ? : {strings.chat.older}} ) : undefined} /> {/* Floats over the last row only while an older turn owns the viewport. */} {awayFromLatest && ( [styles.latestTurnButton, pressed && styles.latestTurnButtonPressed]} > )} }} {mentionType !== null && ( { closeMention(); Keyboard.dismiss() }} accessibilityRole="button" accessibilityLabel={strings.common.close} /> )} {connected && (session.backend === undefined || session.backend === 'harness' || Boolean(session.projections?.values?.todos) || Boolean(session.projections?.values?.goal) || childSessions.length > 0 || (teamState !== undefined && teamState.members.length > 0)) && ( void openSession(targetSession)} /> )} {queueItems.length > 0 && } {images.length > 0 && ( {images.map((image, index) => ( setImages(current => current.filter((_, imageIndex) => imageIndex !== index))} style={styles.removeImageButton} > ))} )} {stagedFiles.length > 0 && ( {stagedFiles.map((file, index) => { const video = isVideoFile(file.name, file.mimeType) const sizeLine = file.durationMs !== undefined ? `${formatFileBytes(file.size)} · ${formatDurationMs(file.durationMs)}` : formatFileBytes(file.size) return ( {video ? : } {file.name} {sizeLine} setStagedFiles(current => current.filter((_, fileIndex) => fileIndex !== index))} style={styles.removeFileButton} > ) })} )} {uploadingFiles && ( {uploadProgress && uploadProgress.totalBytes > 0 ? strings.chat.uploadingFileProgress( uploadProgress.fileCount > 1 ? `(${uploadProgress.fileIndex + 1}/${uploadProgress.fileCount}) ${uploadProgress.fileName}` : uploadProgress.fileName, Math.min(100, Math.round((uploadProgress.bytesSent / uploadProgress.totalBytes) * 100)), ) : strings.chat.uploadingFile(uploadProgress?.fileName ?? stagedFiles[0]?.name ?? '')} { triggerLightHaptic() uploadControllerRef.current?.abort() }} > {strings.chat.cancelUpload} )} setStagedReferences(current => current.filter(item => item.sessionId !== sid))} /> setQuotes(current => current.filter((_, i) => i !== index))} replyActive={replyActive} stopping={stopping} commandRunning={commandRunning} hasComposerContent={hasComposerContent} connected={connected} editable={inputEditable} composerDisabled={composerDisabled} sendDisabled={sendDisabled} compactComposer={compactComposer} composerInputMaxHeight={composerInputMaxHeight} onOpenExpand={() => setComposerExpanded(true)} onOpenActions={openPlusMenu} onOpenPrompts={openPromptsPicker} onSubmit={() => void submit()} onStop={stopOrCancel} /> setComposerExpanded(false)} backend={session.backend} draft={draft} quotes={quotes} onRemoveQuote={index => setQuotes(current => current.filter((_, i) => i !== index))} input={mentionInput} replyActive={replyActive} stopping={stopping} sendDisabled={sendDisabled} onSubmit={() => void submit()} onStop={stopOrCancel} /> , <> setReferenceChatOpen(true) : undefined} onOpenPrompts={openPromptsPicker} onOpenWorkspace={() => setWorkspacePickerOpen(true)} onOpenMode={() => setModePickerOpen(true)} onOpenTools={() => setToolPickerOpen(true)} onOpenPermissions={() => setPermissionPickerOpen(true)} /> setReferenceChatOpen(false)} onPick={(_mentionText, candidate) => { setStagedReferences(current => current.some(item => item.sessionId === candidate.sessionId) ? current : [...current, candidate], ) }} /> setModelPickerOpen(false)} onPick={pickModel} /> {toolsMode !== undefined && connected && ( { setToolsMode(undefined); setFileLinkPath(undefined) }} /> )} setPermissionRevision(v => v + 1)} visible={permissionPickerOpen} permissions={permissions} onClose={() => setPermissionPickerOpen(false)} onPick={pickPermission} /> setModePickerOpen(false)} onPick={pickMode} /> setSessionInfoOpen(false)} onOpenWorkspace={() => { setSessionInfoOpen(false) if (onOpenWorkspaces !== undefined) onOpenWorkspaces(currentWorkspace === undefined ? undefined : workspaceStableKey(currentWorkspace, hostPlatform)) else openSessionsDrawer() }} /> setWorkspacePickerOpen(false)} onPick={pickWorkspace} onManage={() => { setWorkspacePickerOpen(false); openSessionsDrawer() }} /> setToolPickerOpen(false)} onPick={pickToolMode} /> { void setQuickPromptActionMode(mode).catch(() => { Alert.alert(strings.settings.quickPromptActionMode, strings.settings.quickPromptActionSaveFailed) }) }} onClose={() => setPromptsPickerOpen(false)} onPick={prompt => void pickQuickPrompt(prompt)} onManage={() => { setPromptsPickerOpen(false); setPromptsManagerOpen(true) }} /> { setPromptsManagerOpen(false); setPromptsPickerOpen(true) }} onClose={() => setPromptsManagerOpen(false)} onAdd={() => { setPromptsManagerOpen(false); setPromptEditing('new') }} onEdit={prompt => { setPromptsManagerOpen(false); setPromptEditing(prompt) }} onDelete={prompt => { Alert.alert(strings.chat.toolPromptDeleteTitle(prompt.title), strings.chat.toolPromptDeleteBody, [ { text: strings.common.cancel, style: 'cancel' }, { text: strings.common.delete, style: 'destructive', onPress: () => void deletePrompt(prompt) }, ]) }} /> { setPromptEditing(null); setPromptsManagerOpen(true) }} onClose={() => setPromptEditing(null)} onSave={(title, text) => void savePromptEdit(title, text)} /> setPreviewImageUri(undefined)} statusBarTranslucent > setPreviewImageUri(undefined)} /> {previewImageUri !== undefined && ( )} setPreviewImageUri(undefined)} accessibilityRole="button" accessibilityLabel={strings.common.close} hitSlop={12} > , ) } export { ModalSurface,usePickerListMaxHeight } from './chat/modal'