Import apps/android/src/screens/chat-screen.tsx
This commit is contained in:
parent
0eb7be8130
commit
85ec7d27a6
|
|
@ -1,10 +1,9 @@
|
||||||
import * as Haptics from 'expo-haptics'
|
import * as Haptics from 'expo-haptics'
|
||||||
import { ArrowDown, ArrowLeft, FileText, ListTree, Menu, MessageSquare, RefreshCw, X } from 'lucide-react-native'
|
import { ArrowDown, ArrowLeft, FileText, Film, ListTree, Menu, MessageSquare, RefreshCw, X } from 'lucide-react-native'
|
||||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||||
import {
|
import {
|
||||||
AccessibilityInfo,
|
AccessibilityInfo,
|
||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
Alert,
|
|
||||||
Animated,
|
Animated,
|
||||||
DeviceEventEmitter,
|
DeviceEventEmitter,
|
||||||
Easing,
|
Easing,
|
||||||
|
|
@ -20,6 +19,7 @@ import {
|
||||||
Text,
|
Text,
|
||||||
View
|
View
|
||||||
} from 'react-native'
|
} from 'react-native'
|
||||||
|
import { Alert } from '../ui/alert'
|
||||||
import { shouldConfirmSwipeRightOpen, shouldStartSwipeRightToOpen } from '../lib/gesture-swipe-rules'
|
import { shouldConfirmSwipeRightOpen, shouldStartSwipeRightToOpen } from '../lib/gesture-swipe-rules'
|
||||||
import { isSubagentSession } from '../lib/session-kind'
|
import { isSubagentSession } from '../lib/session-kind'
|
||||||
import { workspaceStableKey } from '../lib/workspace-key'
|
import { workspaceStableKey } from '../lib/workspace-key'
|
||||||
|
|
@ -44,27 +44,33 @@ import { ChatImageProvider } from '../ui/chat-image'
|
||||||
import { BlurHeaderFrame, IconButton, TopBar } from '../ui/components'
|
import { BlurHeaderFrame, IconButton, TopBar } from '../ui/components'
|
||||||
import { KeyboardInset } from '../ui/keyboard-inset'
|
import { KeyboardInset } from '../ui/keyboard-inset'
|
||||||
import { decodeSessionMentionUri, markdownFilePath, MarkdownLinkProvider, openSafeExternalUrl } from '../ui/markdown'
|
import { decodeSessionMentionUri, markdownFilePath, MarkdownLinkProvider, openSafeExternalUrl } from '../ui/markdown'
|
||||||
|
import { NavigationFocusProvider } from '../ui/mention-popover'
|
||||||
import { OfficialMenuIcons } from '../ui/official-menu-icons'
|
import { OfficialMenuIcons } from '../ui/official-menu-icons'
|
||||||
import { useResponsiveLayout } from '../ui/responsive'
|
import { useResponsiveLayout } from '../ui/responsive'
|
||||||
import { spacing } from '../ui/theme'
|
import { spacing } from '../ui/theme'
|
||||||
import { useTheme } from '../ui/theme-context'
|
import { useTheme } from '../ui/theme-context'
|
||||||
import { useThemedStyles } from '../ui/use-themed-styles'
|
import { useThemedStyles } from '../ui/use-themed-styles'
|
||||||
import { easingCurve, resolveMotion, type Rect } from '../ui/motion'
|
import { easingCurve, resolveMotion, type Rect } from '../ui/motion'
|
||||||
|
import { triggerLightHaptic } from '../ui/haptics'
|
||||||
import { useReduceMotion } from '../ui/use-reduce-motion'
|
import { useReduceMotion } from '../ui/use-reduce-motion'
|
||||||
import { AutomationTasksModal } from './automation-tasks-modal'
|
import { AutomationTasksModal } from './automation-tasks-modal'
|
||||||
import { ChatErrorBoundary } from './chat-error-boundary'
|
import { ChatErrorBoundary } from './chat-error-boundary'
|
||||||
import {
|
import {
|
||||||
|
formatDurationMs,
|
||||||
formatFileBytes,
|
formatFileBytes,
|
||||||
formatUploadedFilesPrompt,
|
formatUploadedFilesPrompt,
|
||||||
formatUploadedFilesReferencePrompt,
|
formatUploadedFilesReferencePrompt,
|
||||||
MAX_TOTAL_FILES_BYTES,
|
isDirectTransportMode,
|
||||||
|
isVideoFile,
|
||||||
uploadStagedFilesToWorkspace,
|
uploadStagedFilesToWorkspace,
|
||||||
type StagedFile
|
workspaceUploadMaxBytes,
|
||||||
|
type StagedFile,
|
||||||
|
type UploadProgress
|
||||||
} from './chat-files'
|
} from './chat-files'
|
||||||
import { ChatTrajectory } from './chat-trajectory'
|
import { ChatTrajectory } from './chat-trajectory'
|
||||||
import { ChatActionMenu } from './chat/action-menu'
|
import { ChatActionMenu } from './chat/action-menu'
|
||||||
import { ChatComposer } from './chat/composer'
|
import { BACKEND_CHAT_TEXT_KEYS, ChatComposer } from './chat/composer'
|
||||||
import { composerEditable, submitIntent } from './chat/composer-gate'
|
import { applyQuickPromptDraft, composerEditable, submitIntent } from './chat/composer-gate'
|
||||||
import { ExpandedComposer } from './chat/expanded-composer'
|
import { ExpandedComposer } from './chat/expanded-composer'
|
||||||
import {
|
import {
|
||||||
ChatImages,
|
ChatImages,
|
||||||
|
|
@ -72,6 +78,7 @@ import {
|
||||||
ChatProcessGroup,
|
ChatProcessGroup,
|
||||||
isActiveChatItem,
|
isActiveChatItem,
|
||||||
QueueDock,
|
QueueDock,
|
||||||
|
ReplyStatusBanner,
|
||||||
WelcomeMessage
|
WelcomeMessage
|
||||||
} from './chat/messages'
|
} from './chat/messages'
|
||||||
import {
|
import {
|
||||||
|
|
@ -97,8 +104,8 @@ import { useChatMentions } from './chat/use-chat-mentions'
|
||||||
import { useChatPrompts } from './chat/use-chat-prompts'
|
import { useChatPrompts } from './chat/use-chat-prompts'
|
||||||
import { useChatScroll } from './chat/use-chat-scroll'
|
import { useChatScroll } from './chat/use-chat-scroll'
|
||||||
import { useChatTranscript } from './chat/use-chat-transcript'
|
import { useChatTranscript } from './chat/use-chat-transcript'
|
||||||
import { useLiveSessionStatus } from './device-screens'
|
|
||||||
import { BotModeScreen } from './bot-mode-screen'
|
import { BotModeScreen } from './bot-mode-screen'
|
||||||
|
import { useLiveSessionStatus } from './device-screens'
|
||||||
import { HostSessionsDrawer } from './host-sessions-drawer'
|
import { HostSessionsDrawer } from './host-sessions-drawer'
|
||||||
import { PluginsModal } from './plugins-modal'
|
import { PluginsModal } from './plugins-modal'
|
||||||
import { ReferenceChatModal, ReferencedChatPills } from './bot/reference-chat-modal'
|
import { ReferenceChatModal, ReferencedChatPills } from './bot/reference-chat-modal'
|
||||||
|
|
@ -116,6 +123,8 @@ const EMPTY_UI_ARTIFACTS: UiArtifact[] = []
|
||||||
const LONG_DRAFT_MAX = 256_000
|
const LONG_DRAFT_MAX = 256_000
|
||||||
|
|
||||||
export function ChatScreen({
|
export function ChatScreen({
|
||||||
|
active = true,
|
||||||
|
suppressAutoSelect = false,
|
||||||
onBack = () => {},
|
onBack = () => {},
|
||||||
onOpenDevices: _onOpenDevices,
|
onOpenDevices: _onOpenDevices,
|
||||||
onNewSession,
|
onNewSession,
|
||||||
|
|
@ -130,6 +139,8 @@ export function ChatScreen({
|
||||||
onBotModeChange,
|
onBotModeChange,
|
||||||
onSelectBot,
|
onSelectBot,
|
||||||
}: {
|
}: {
|
||||||
|
active?: boolean
|
||||||
|
suppressAutoSelect?: boolean
|
||||||
onBack?: () => void
|
onBack?: () => void
|
||||||
onOpenDevices?: () => void
|
onOpenDevices?: () => void
|
||||||
onNewSession?: () => void
|
onNewSession?: () => void
|
||||||
|
|
@ -145,10 +156,10 @@ export function ChatScreen({
|
||||||
onSelectBot?: (id?: string) => void
|
onSelectBot?: (id?: string) => void
|
||||||
}) {
|
}) {
|
||||||
const reduceMotion = useReduceMotion()
|
const reduceMotion = useReduceMotion()
|
||||||
// New subagent children and running-state changes must reach `sessions`
|
|
||||||
// without leaving the chat (the list screens unmount here).
|
|
||||||
const session = useAppStore(state => state.selectedSession)
|
const session = useAppStore(state => state.selectedSession)
|
||||||
const archivedSessionIds = useAppStore(state => state.archivedSessionIds)
|
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')
|
useLiveSessionStatus(!botMode && session !== undefined && (session.backend ?? 'harness') === 'harness')
|
||||||
const hostId = useAppStore(state => state.selectedDevice?.deviceId)
|
const hostId = useAppStore(state => state.selectedDevice?.deviceId)
|
||||||
const hostPlatform = useAppStore(state => state.selectedDevice?.platform)
|
const hostPlatform = useAppStore(state => state.selectedDevice?.platform)
|
||||||
|
|
@ -166,6 +177,7 @@ export function ChatScreen({
|
||||||
const permissionSelecting = useAppStore(state => state.permissionSelecting)
|
const permissionSelecting = useAppStore(state => state.permissionSelecting)
|
||||||
const sendMessage = useAppStore(state => state.sendMessage)
|
const sendMessage = useAppStore(state => state.sendMessage)
|
||||||
const stopSession = useAppStore(state => state.stopSession)
|
const stopSession = useAppStore(state => state.stopSession)
|
||||||
|
const cancelCompaction = useAppStore(state => state.cancelCompaction)
|
||||||
const reconnect = useAppStore(state => state.reconnect)
|
const reconnect = useAppStore(state => state.reconnect)
|
||||||
const openSession = useAppStore(state => state.openSession)
|
const openSession = useAppStore(state => state.openSession)
|
||||||
const respondApproval = useAppStore(state => state.respondApproval)
|
const respondApproval = useAppStore(state => state.respondApproval)
|
||||||
|
|
@ -182,6 +194,8 @@ export function ChatScreen({
|
||||||
const agentPresetOptions = useAppStore(state => state.agentPresetOptions)
|
const agentPresetOptions = useAppStore(state => state.agentPresetOptions)
|
||||||
const agentPresetLoading = useAppStore(state => state.agentPresetLoading)
|
const agentPresetLoading = useAppStore(state => state.agentPresetLoading)
|
||||||
const agentPresetSelecting = useAppStore(state => state.agentPresetSelecting)
|
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 previewImageUri = useAppStore(state => state.previewImageUri)
|
||||||
const setPreviewImageUri = useAppStore(state => state.setPreviewImageUri)
|
const setPreviewImageUri = useAppStore(state => state.setPreviewImageUri)
|
||||||
// Lightbox grows from the tap instead of a whole-screen cross fade.
|
// Lightbox grows from the tap instead of a whole-screen cross fade.
|
||||||
|
|
@ -207,7 +221,12 @@ export function ChatScreen({
|
||||||
// Enter-only motion for the transcript <-> trajectory swap. Both views keep
|
// Enter-only motion for the transcript <-> trajectory swap. Both views keep
|
||||||
// their own scroll state; only the incoming view moves.
|
// their own scroll state; only the incoming view moves.
|
||||||
const trajectoryMotion = useRef(new Animated.Value(1)).current
|
const trajectoryMotion = useRef(new Animated.Value(1)).current
|
||||||
|
const trajectoryMountedRef = useRef(false)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!trajectoryMountedRef.current) {
|
||||||
|
trajectoryMountedRef.current = true
|
||||||
|
return
|
||||||
|
}
|
||||||
trajectoryMotion.setValue(0)
|
trajectoryMotion.setValue(0)
|
||||||
const animation = Animated.timing(trajectoryMotion, {
|
const animation = Animated.timing(trajectoryMotion, {
|
||||||
toValue: 1,
|
toValue: 1,
|
||||||
|
|
@ -218,9 +237,10 @@ export function ChatScreen({
|
||||||
animation.start()
|
animation.start()
|
||||||
return () => animation.stop()
|
return () => animation.stop()
|
||||||
}, [trajectory, trajectoryMotion, reduceMotion])
|
}, [trajectory, trajectoryMotion, reduceMotion])
|
||||||
const [composingDuringRun, setComposingDuringRun] = useState(false)
|
|
||||||
|
|
||||||
const [sessionsOpen, setSessionsOpen] = useState(true)
|
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
|
// 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.
|
// or pressing back must not drop the user into an arbitrary conversation.
|
||||||
const [drawerSwipeUnlocked, setDrawerSwipeUnlocked] = useState(false)
|
const [drawerSwipeUnlocked, setDrawerSwipeUnlocked] = useState(false)
|
||||||
|
|
@ -230,6 +250,7 @@ export function ChatScreen({
|
||||||
if (hostId === lastHostIdRef.current) return
|
if (hostId === lastHostIdRef.current) return
|
||||||
lastHostIdRef.current = hostId
|
lastHostIdRef.current = hostId
|
||||||
setDrawerSwipeUnlocked(false)
|
setDrawerSwipeUnlocked(false)
|
||||||
|
setDrawerEntrance('immediate')
|
||||||
setSessionsOpen(true)
|
setSessionsOpen(true)
|
||||||
}, [hostId])
|
}, [hostId])
|
||||||
// Explicit navigation must also reveal an already selected conversation.
|
// Explicit navigation must also reveal an already selected conversation.
|
||||||
|
|
@ -293,6 +314,7 @@ export function ChatScreen({
|
||||||
}, [setQuotes, composerInputRef])
|
}, [setQuotes, composerInputRef])
|
||||||
const [stagedFiles, setStagedFiles] = useState<StagedFile[]>([])
|
const [stagedFiles, setStagedFiles] = useState<StagedFile[]>([])
|
||||||
const [uploadingFiles, setUploadingFiles] = useState(false)
|
const [uploadingFiles, setUploadingFiles] = useState(false)
|
||||||
|
const [uploadProgress, setUploadProgress] = useState<UploadProgress>()
|
||||||
const uploadingRef = useRef(false)
|
const uploadingRef = useRef(false)
|
||||||
const uploadControllerRef = useRef<AbortController | undefined>(undefined)
|
const uploadControllerRef = useRef<AbortController | undefined>(undefined)
|
||||||
const sessionGenerationRef = useRef(0)
|
const sessionGenerationRef = useRef(0)
|
||||||
|
|
@ -304,6 +326,7 @@ export function ChatScreen({
|
||||||
lastSessionId = currentId
|
lastSessionId = currentId
|
||||||
sessionGenerationRef.current += 1
|
sessionGenerationRef.current += 1
|
||||||
uploadControllerRef.current?.abort()
|
uploadControllerRef.current?.abort()
|
||||||
|
setUploadProgress(undefined)
|
||||||
setStagedFiles([])
|
setStagedFiles([])
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
@ -312,7 +335,7 @@ export function ChatScreen({
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (connection.phase !== 'connected') uploadControllerRef.current?.abort()
|
if (connection.phase !== 'connected') uploadControllerRef.current?.abort()
|
||||||
}, [connection.phase])
|
}, [connection.phase])
|
||||||
const { canAttachImages, attachmentPicking, pickImages, takePhoto, pickFiles } = useChatAttachments({
|
const { attachmentPicking, pickImages, takePhoto, pickFiles } = useChatAttachments({
|
||||||
session, memoryKey, images, setImages, stagedFiles, setStagedFiles, sessionGenerationRef,
|
session, memoryKey, images, setImages, stagedFiles, setStagedFiles, sessionGenerationRef,
|
||||||
})
|
})
|
||||||
const [plusMenuOpen, setPlusMenuOpen] = useState(false)
|
const [plusMenuOpen, setPlusMenuOpen] = useState(false)
|
||||||
|
|
@ -395,6 +418,7 @@ export function ChatScreen({
|
||||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light).catch(() => undefined)
|
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light).catch(() => undefined)
|
||||||
// Reached from a conversation, so the sidebar may be swiped away again.
|
// Reached from a conversation, so the sidebar may be swiped away again.
|
||||||
setDrawerSwipeUnlocked(true)
|
setDrawerSwipeUnlocked(true)
|
||||||
|
setDrawerEntrance('slide')
|
||||||
setSessionsOpen(true)
|
setSessionsOpen(true)
|
||||||
}, [setMentionType])
|
}, [setMentionType])
|
||||||
|
|
||||||
|
|
@ -461,20 +485,24 @@ export function ChatScreen({
|
||||||
// Back inside a subagent child returns to its parent conversation (the
|
// Back inside a subagent child returns to its parent conversation (the
|
||||||
// official subagent UI's navigation), instead of leaving the chat entirely.
|
// official subagent UI's navigation), instead of leaving the chat entirely.
|
||||||
const backFromChat = () => {
|
const backFromChat = () => {
|
||||||
|
if (!tabletSplit && sessionsOpen) {
|
||||||
|
return drawerBackRef.current?.() ?? false
|
||||||
|
}
|
||||||
const parent = session !== undefined && isSubagentSession(session)
|
const parent = session !== undefined && isSubagentSession(session)
|
||||||
? sessions.find(item => item.sessionId === session.parentSessionId)
|
? sessions.find(item => item.sessionId === session.parentSessionId)
|
||||||
: undefined
|
: undefined
|
||||||
if (parent !== undefined) {
|
if (parent !== undefined) {
|
||||||
Keyboard.dismiss()
|
Keyboard.dismiss()
|
||||||
void openSession(parent)
|
void openSession(parent)
|
||||||
return
|
return true
|
||||||
}
|
}
|
||||||
if (!tabletSplit && !sessionsOpen) {
|
if (!tabletSplit && !sessionsOpen) {
|
||||||
openSessionsDrawer()
|
openSessionsDrawer()
|
||||||
return
|
return true
|
||||||
}
|
}
|
||||||
Keyboard.dismiss()
|
Keyboard.dismiss()
|
||||||
onBack()
|
onBack()
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
const onBackRef = useRef(backFromChat)
|
const onBackRef = useRef(backFromChat)
|
||||||
onBackRef.current = backFromChat
|
onBackRef.current = backFromChat
|
||||||
|
|
@ -492,7 +520,7 @@ export function ChatScreen({
|
||||||
{ open: promptsPickerOpen, close: () => setPromptsPickerOpen(false) },
|
{ open: promptsPickerOpen, close: () => setPromptsPickerOpen(false) },
|
||||||
{ open: toolsMode !== undefined, close: () => { setToolsMode(undefined); setFileLinkPath(undefined) } },
|
{ open: toolsMode !== undefined, close: () => { setToolsMode(undefined); setFileLinkPath(undefined) } },
|
||||||
{ open: trajectory, close: () => setTrajectory(false) },
|
{ open: trajectory, close: () => setTrajectory(false) },
|
||||||
])
|
], active)
|
||||||
|
|
||||||
const botTeamState = useBotTeamStore(state => state.state)
|
const botTeamState = useBotTeamStore(state => state.state)
|
||||||
|
|
||||||
|
|
@ -534,14 +562,7 @@ export function ChatScreen({
|
||||||
}
|
}
|
||||||
}, [botMode, session, botTeamState, memoryScope])
|
}, [botMode, session, botTeamState, memoryScope])
|
||||||
|
|
||||||
const autoSelectingRef = useRef(false)
|
const findPreferredAgentSession = () => {
|
||||||
useEffect(() => {
|
|
||||||
if (botMode) 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 candidates = sessions.filter(
|
const candidates = sessions.filter(
|
||||||
item => !archivedSessionIds.includes(item.sessionId) && !isKnownBotSessionId(item.sessionId, botTeamState, memoryScope),
|
item => !archivedSessionIds.includes(item.sessionId) && !isKnownBotSessionId(item.sessionId, botTeamState, memoryScope),
|
||||||
)
|
)
|
||||||
|
|
@ -549,29 +570,42 @@ export function ChatScreen({
|
||||||
const preferred = remembered
|
const preferred = remembered
|
||||||
? candidates.find(item => item.sessionId === remembered.sessionId && (item.backend ?? 'harness') === (remembered.backend ?? 'harness'))
|
? candidates.find(item => item.sessionId === remembered.sessionId && (item.backend ?? 'harness') === (remembered.backend ?? 'harness'))
|
||||||
: undefined
|
: undefined
|
||||||
const target = preferred ?? [...candidates].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))[0]
|
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) {
|
if (target) {
|
||||||
const capturedScope = memoryScope
|
|
||||||
autoSelectingRef.current = true
|
autoSelectingRef.current = true
|
||||||
void openSession(target).finally(() => {
|
void openSession(target).finally(() => {
|
||||||
if (browseScope(useAppStore.getState()) === capturedScope) {
|
autoSelectingRef.current = false
|
||||||
autoSelectingRef.current = false
|
|
||||||
} else {
|
|
||||||
autoSelectingRef.current = false
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [botMode, session, connected, busy, sessions, archivedSessionIds, openSession, botTeamState, memoryScope])
|
}, [botMode, suppressAutoSelect, session, connected, busy, sessions, archivedSessionIds, openSession, botTeamState, memoryScope])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!replyActive) setComposingDuringRun(false)
|
|
||||||
else if (composingDuringRun) composerInputRef.current?.focus()
|
|
||||||
}, [replyActive, composingDuringRun])
|
|
||||||
|
|
||||||
const drawerElement = (inlineMode: boolean) => (
|
const drawerElement = (inlineMode: boolean) => (
|
||||||
<HostSessionsDrawer
|
<HostSessionsDrawer
|
||||||
key={inlineMode ? 'inline-navigation' : 'navigation-drawer'}
|
key={inlineMode ? 'inline-navigation' : 'navigation-drawer'}
|
||||||
inline={inlineMode}
|
inline={inlineMode}
|
||||||
|
entrance={inlineMode ? 'immediate' : drawerEntrance}
|
||||||
|
backRef={inlineMode ? undefined : drawerBackRef}
|
||||||
botMode={botMode}
|
botMode={botMode}
|
||||||
onBotModeChange={onBotModeChange}
|
onBotModeChange={onBotModeChange}
|
||||||
dismissible={inlineMode || drawerSwipeUnlocked}
|
dismissible={inlineMode || drawerSwipeUnlocked}
|
||||||
|
|
@ -615,8 +649,8 @@ export function ChatScreen({
|
||||||
}}
|
}}
|
||||||
onSelect={async next => {
|
onSelect={async next => {
|
||||||
markConversationChosen()
|
markConversationChosen()
|
||||||
onBotModeChange?.(false)
|
|
||||||
const pending = openSession(next)
|
const pending = openSession(next)
|
||||||
|
onBotModeChange?.(false)
|
||||||
const visible = useAppStore.getState().selectedSession?.sessionId === next.sessionId
|
const visible = useAppStore.getState().selectedSession?.sessionId === next.sessionId
|
||||||
if (!inlineMode && visible) {
|
if (!inlineMode && visible) {
|
||||||
setSessionsOpen(false)
|
setSessionsOpen(false)
|
||||||
|
|
@ -628,53 +662,79 @@ export function ChatScreen({
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|
||||||
if (botMode) {
|
const defaultTaskWorkspaceId =
|
||||||
return (
|
(session === undefined ? undefined : workspaces.find(w => w.sessionIds.includes(session.sessionId))?.workspaceId)
|
||||||
<ChatImageProvider value={imageLoader}><MarkdownLinkProvider onLinkPress={openLink}><KeyboardInset>
|
?? workspaces[0]?.workspaceId
|
||||||
<View key="chat-layout" style={[styles.splitRoot, tabletSplit && styles.splitRootWide]}>
|
|
||||||
{tabletSplit && <View style={styles.splitSidebar}>{drawerElement(true)}</View>}
|
const wrapChatShell = (mainPane: ReactNode, extraOverlays?: ReactNode) => (
|
||||||
<View style={styles.splitMain} {...swipeRightTouchProps}>
|
<ChatImageProvider value={imageLoader}>
|
||||||
<BotModeScreen
|
<MarkdownLinkProvider onLinkPress={openLink}>
|
||||||
selectedId={botConversationId}
|
<View style={styles.flex}>
|
||||||
onSelect={id => onSelectBot?.(id)}
|
<NavigationFocusProvider value={active && (!sessionsOpen || tabletSplit) && !composerExpanded}>
|
||||||
onAgentMode={() => onBotModeChange?.(false)}
|
<KeyboardInset>
|
||||||
onOpenDrawer={openSessionsDrawer}
|
<View
|
||||||
onDeviceInfo={() => onOpenDeviceInfo?.()}
|
key="chat-layout"
|
||||||
onMore={() => onOpenSettings?.()}
|
style={[styles.splitRoot, tabletSplit && styles.splitRootWide]}
|
||||||
splitView={tabletSplit}
|
pointerEvents={sessionsOpen && !tabletSplit ? 'none' : 'auto'}
|
||||||
drawerOpen={sessionsOpen || tabletSplit}
|
accessibilityElementsHidden={sessionsOpen && !tabletSplit}
|
||||||
/>
|
importantForAccessibility={sessionsOpen && !tabletSplit ? 'no-hide-descendants' : 'auto'}
|
||||||
</View>
|
>
|
||||||
|
{tabletSplit && <View style={styles.splitSidebar}>{drawerElement(true)}</View>}
|
||||||
|
{mainPane}
|
||||||
|
</View>
|
||||||
|
{extraOverlays}
|
||||||
|
</KeyboardInset>
|
||||||
|
</NavigationFocusProvider>
|
||||||
|
{sessionsOpen && !tabletSplit && drawerElement(false)}
|
||||||
|
<PluginsModal visible={pluginsOpen} onClose={() => setPluginsOpen(false)} />
|
||||||
|
<AutomationTasksModal
|
||||||
|
visible={automationTasksOpen}
|
||||||
|
onClose={() => 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)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</View>
|
</View>
|
||||||
{sessionsOpen && !tabletSplit && drawerElement(false)}
|
</MarkdownLinkProvider>
|
||||||
<PluginsModal visible={pluginsOpen} onClose={() => setPluginsOpen(false)} />
|
</ChatImageProvider>
|
||||||
<AutomationTasksModal
|
)
|
||||||
visible={automationTasksOpen}
|
|
||||||
onClose={() => setAutomationTasksOpen(false)}
|
if (botMode) {
|
||||||
onOpenSession={async targetSession => {
|
return wrapChatShell(
|
||||||
setAutomationTasksOpen(false)
|
<View style={styles.splitMain} {...swipeRightTouchProps}>
|
||||||
markConversationChosen()
|
<BotModeScreen
|
||||||
setSessionsOpen(false)
|
selectedId={botConversationId}
|
||||||
onBotModeChange?.(false)
|
onSelect={id => onSelectBot?.(id)}
|
||||||
await openSession(targetSession)
|
onAgentMode={switchToAgentMode}
|
||||||
}}
|
onOpenDrawer={openSessionsDrawer}
|
||||||
onNewTask={async () => {
|
onDeviceInfo={() => onOpenDeviceInfo?.()}
|
||||||
setAutomationTasksOpen(false)
|
onMore={() => onOpenSettings?.()}
|
||||||
markConversationChosen()
|
splitView={tabletSplit}
|
||||||
setSessionsOpen(false)
|
drawerOpen={sessionsOpen || tabletSplit}
|
||||||
onBotModeChange?.(false)
|
screenActive={active && (!sessionsOpen || tabletSplit)}
|
||||||
await createSession(workspaces[0]?.workspaceId)
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</KeyboardInset></MarkdownLinkProvider></ChatImageProvider>
|
</View>,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session === undefined) {
|
const sessionIsBot = session !== undefined && isKnownBotSessionId(session.sessionId, botTeamState, memoryScope)
|
||||||
|
if (session === undefined || sessionIsBot) {
|
||||||
const emptyHeader = (
|
const emptyHeader = (
|
||||||
<TopBar
|
<TopBar
|
||||||
title={strings.chat.newChat}
|
title={strings.chat.newChat}
|
||||||
titleLines={1}
|
titleLines={1}
|
||||||
|
titleAlign="between"
|
||||||
onBack={tabletSplit ? undefined : openSessionsDrawer}
|
onBack={tabletSplit ? undefined : openSessionsDrawer}
|
||||||
backIcon={Menu}
|
backIcon={Menu}
|
||||||
backLabel={strings.chat.openHostSessions}
|
backLabel={strings.chat.openHostSessions}
|
||||||
|
|
@ -702,45 +762,22 @@ export function ChatScreen({
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
return (
|
return wrapChatShell(
|
||||||
<ChatImageProvider value={imageLoader}><MarkdownLinkProvider onLinkPress={openLink}><KeyboardInset>
|
<View style={styles.splitMain} {...swipeRightTouchProps}>
|
||||||
<View key="chat-layout" style={[styles.splitRoot, tabletSplit && styles.splitRootWide]}>
|
<BlurHeaderFrame header={emptyHeader}>
|
||||||
{tabletSplit && <View style={styles.splitSidebar}>{drawerElement(true)}</View>}
|
{headerHeight => (
|
||||||
<View style={styles.splitMain} {...swipeRightTouchProps}>
|
<View style={[styles.list, readableColumn, styles.emptyList, { paddingTop: headerHeight + spacing.xl }]}>
|
||||||
<BlurHeaderFrame header={emptyHeader}>
|
{busy !== undefined ? (
|
||||||
{headerHeight => (
|
<View style={{ padding: spacing.xl, alignItems: 'center' }}>
|
||||||
<View style={[styles.list, readableColumn, styles.emptyList, { paddingTop: headerHeight + spacing.xl }]}>
|
<ActivityIndicator size="large" color={colors.primary} />
|
||||||
{busy !== undefined ? (
|
|
||||||
<View style={{ padding: spacing.xl, alignItems: 'center' }}>
|
|
||||||
<ActivityIndicator size="large" color={colors.primary} />
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
<WelcomeMessage />
|
|
||||||
)}
|
|
||||||
</View>
|
</View>
|
||||||
|
) : (
|
||||||
|
<WelcomeMessage />
|
||||||
)}
|
)}
|
||||||
</BlurHeaderFrame>
|
</View>
|
||||||
</View>
|
)}
|
||||||
</View>
|
</BlurHeaderFrame>
|
||||||
{sessionsOpen && !tabletSplit && drawerElement(false)}
|
</View>,
|
||||||
<PluginsModal visible={pluginsOpen} onClose={() => setPluginsOpen(false)} />
|
|
||||||
<AutomationTasksModal
|
|
||||||
visible={automationTasksOpen}
|
|
||||||
onClose={() => setAutomationTasksOpen(false)}
|
|
||||||
onOpenSession={async targetSession => {
|
|
||||||
setAutomationTasksOpen(false)
|
|
||||||
markConversationChosen()
|
|
||||||
setSessionsOpen(false)
|
|
||||||
await openSession(targetSession)
|
|
||||||
}}
|
|
||||||
onNewTask={async () => {
|
|
||||||
setAutomationTasksOpen(false)
|
|
||||||
markConversationChosen()
|
|
||||||
setSessionsOpen(false)
|
|
||||||
await createSession(workspaces[0]?.workspaceId)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</KeyboardInset></MarkdownLinkProvider></ChatImageProvider>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -773,14 +810,51 @@ export function ChatScreen({
|
||||||
const targetSessionId = session.sessionId
|
const targetSessionId = session.sessionId
|
||||||
const sendSessionGen = sessionGenerationRef.current
|
const sendSessionGen = sessionGenerationRef.current
|
||||||
if (submittedFiles.length > 0) {
|
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()
|
const controller = new AbortController()
|
||||||
uploadControllerRef.current?.abort()
|
uploadControllerRef.current?.abort()
|
||||||
uploadControllerRef.current = controller
|
uploadControllerRef.current = controller
|
||||||
uploadingRef.current = true
|
uploadingRef.current = true
|
||||||
setUploadingFiles(true)
|
setUploadingFiles(true)
|
||||||
|
setUploadProgress({
|
||||||
|
fileIndex: 0,
|
||||||
|
fileCount: submittedFiles.length,
|
||||||
|
fileName: submittedFiles[0]?.name ?? '',
|
||||||
|
bytesSent: 0,
|
||||||
|
totalBytes: submittedFiles[0]?.size ?? 0,
|
||||||
|
})
|
||||||
try {
|
try {
|
||||||
const rpc = requireConnectionRpc()
|
const rpc = requireConnectionRpc()
|
||||||
const uploaded = await uploadStagedFilesToWorkspace(rpc, session.sessionId, submittedFiles, controller.signal)
|
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
|
// A navigation, session switch, reconnection or unmount during a long
|
||||||
// upload must never leak the prompt into another conversation.
|
// upload must never leak the prompt into another conversation.
|
||||||
if (controller.signal.aborted) return
|
if (controller.signal.aborted) return
|
||||||
|
|
@ -795,10 +869,23 @@ export function ChatScreen({
|
||||||
// Aborted uploads already restored (or discarded) their composer state;
|
// Aborted uploads already restored (or discarded) their composer state;
|
||||||
// do not surface a cancellation as a failure.
|
// do not surface a cancellation as a failure.
|
||||||
if (controller.signal.aborted || (uploadError as Error | undefined)?.name === 'AbortError') return
|
if (controller.signal.aborted || (uploadError as Error | undefined)?.name === 'AbortError') return
|
||||||
const isUnsupported = (uploadError as { code?: string })?.code === 'FEATURE_NOT_SUPPORTED'
|
const code = (uploadError as { code?: string })?.code
|
||||||
const errorMsg = isUnsupported
|
const activeFile = failingFile ?? submittedFiles[0]
|
||||||
? strings.chat.uploadUnavailable
|
const activeName = activeFile?.name ?? ''
|
||||||
: strings.chat.uploadFileFailed(submittedFiles[0]?.name ?? '', (uploadError as Error).message)
|
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)
|
Alert.alert(strings.messageActions.failed, errorMsg)
|
||||||
return
|
return
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -806,6 +893,7 @@ export function ChatScreen({
|
||||||
uploadControllerRef.current = undefined
|
uploadControllerRef.current = undefined
|
||||||
uploadingRef.current = false
|
uploadingRef.current = false
|
||||||
setUploadingFiles(false)
|
setUploadingFiles(false)
|
||||||
|
setUploadProgress(undefined)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -833,15 +921,14 @@ export function ChatScreen({
|
||||||
setImages(previous => previous.length === 0 ? submittedImages : [...submittedImages, ...previous])
|
setImages(previous => previous.length === 0 ? submittedImages : [...submittedImages, ...previous])
|
||||||
setStagedReferences(previous => previous.length === 0 ? submittedReferences : [...submittedReferences, ...previous])
|
setStagedReferences(previous => previous.length === 0 ? submittedReferences : [...submittedReferences, ...previous])
|
||||||
setStagedFiles(current => {
|
setStagedFiles(current => {
|
||||||
const combined = [...submittedFiles, ...current]
|
const seen = new Set<string>()
|
||||||
let acc = 0
|
const restored: StagedFile[] = []
|
||||||
return combined.filter(f => {
|
for (const f of [...submittedFiles, ...current]) {
|
||||||
if (acc + f.size <= MAX_TOTAL_FILES_BYTES) {
|
if (seen.has(f.id)) continue
|
||||||
acc += f.size
|
seen.add(f.id)
|
||||||
return true
|
restored.push(f)
|
||||||
}
|
}
|
||||||
return false
|
return restored
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Alert.alert(strings.messageActions.failed, useAppStore.getState().error ?? strings.messageActions.unavailable)
|
Alert.alert(strings.messageActions.failed, useAppStore.getState().error ?? strings.messageActions.unavailable)
|
||||||
|
|
@ -857,13 +944,13 @@ export function ChatScreen({
|
||||||
}
|
}
|
||||||
|
|
||||||
const openPlusMenu = () => {
|
const openPlusMenu = () => {
|
||||||
// The composer TextInput often still owns focus when the user taps +.
|
// When the IME is currently open, measuring composerAnchorRef before the
|
||||||
// Dismissing the IME first gives the transparent Modal the full window and
|
// keyboard settles yields a mid-screen y coordinate that would launch the
|
||||||
// keeps its sheet (including the close target) out of the keyboard's touch
|
// bottom sheet from an elevated anchor.
|
||||||
// region on Android.
|
const imeOpen = typeof Keyboard.isVisible === 'function' && Keyboard.isVisible()
|
||||||
Keyboard.dismiss()
|
Keyboard.dismiss()
|
||||||
const node = composerAnchorRef.current
|
const node = composerAnchorRef.current
|
||||||
if (node === null) {
|
if (node === null || imeOpen) {
|
||||||
setSheetAnchor(undefined)
|
setSheetAnchor(undefined)
|
||||||
setPlusMenuOpen(true)
|
setPlusMenuOpen(true)
|
||||||
return
|
return
|
||||||
|
|
@ -931,8 +1018,14 @@ export function ChatScreen({
|
||||||
const sendReady = connected && !busy?.startsWith('session:')
|
const sendReady = connected && !busy?.startsWith('session:')
|
||||||
&& (session.backend !== 'codex' || codexReadySessionId === session.sessionId)
|
&& (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 hasComposerContent = draft.trim().length > 0 || quotes.length > 0 || images.length > 0 || stagedFiles.length > 0 || stagedReferences.length > 0
|
||||||
const compactRunning = replyActive && !hasComposerContent && !composingDuringRun
|
|
||||||
const stopping = busy === 'stop-session'
|
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
|
// Action entries (attachments, tools, prompts) still need the channel, but the
|
||||||
// text field itself only blocks on composer-local states so an offline draft
|
// 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.
|
// can be typed, edited and kept for the manual send after reconnection.
|
||||||
|
|
@ -1006,8 +1099,16 @@ export function ChatScreen({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const sendPrompt = async (prompt: CustomPrompt) => {
|
const pickQuickPrompt = async (prompt: CustomPrompt) => {
|
||||||
setPromptsPickerOpen(false)
|
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) {
|
if (!connected) {
|
||||||
Alert.alert(strings.chat.toolPromptSendFailed, strings.chat.offlineNotice)
|
Alert.alert(strings.chat.toolPromptSendFailed, strings.chat.offlineNotice)
|
||||||
return
|
return
|
||||||
|
|
@ -1030,7 +1131,7 @@ export function ChatScreen({
|
||||||
}
|
}
|
||||||
// A blank conversation carries nothing to lose: recreate it inside the
|
// A blank conversation carries nothing to lose: recreate it inside the
|
||||||
// chosen workspace and archive the old placeholder so it reads as a move.
|
// chosen workspace and archive the old placeholder so it reads as a move.
|
||||||
if (sessionBlank) await archiveSession(previousId)
|
if (sessionBlank && useAppStore.getState().selectedSession?.sessionId !== previousId) await archiveSession(previousId)
|
||||||
}
|
}
|
||||||
|
|
||||||
const pickWorkspace = (workspace: WorkspaceView) => {
|
const pickWorkspace = (workspace: WorkspaceView) => {
|
||||||
|
|
@ -1072,8 +1173,15 @@ export function ChatScreen({
|
||||||
const header = <>
|
const header = <>
|
||||||
<TopBar
|
<TopBar
|
||||||
title={sessionTitle(session)}
|
title={sessionTitle(session)}
|
||||||
|
subtitle={sessionModels !== undefined ? (currentModelLabel || strings.chat.selectModel) : undefined}
|
||||||
|
subtitleLabel={strings.chat.selectModel}
|
||||||
|
subtitleAccessory={modelSelecting
|
||||||
|
? <View style={{ width: 13, height: 13, alignItems: 'center', justifyContent: 'center' }}><ActivityIndicator size="small" color={colors.muted} style={{ transform: [{ scale: 0.65 }] }} /></View>
|
||||||
|
: undefined}
|
||||||
|
onSubtitlePress={sessionModels !== undefined ? () => { Keyboard.dismiss(); setMentionType(null); setModelPickerOpen(true) } : undefined}
|
||||||
onTitlePress={() => { Keyboard.dismiss(); setMentionType(null); setSessionInfoOpen(true) }}
|
onTitlePress={() => { Keyboard.dismiss(); setMentionType(null); setSessionInfoOpen(true) }}
|
||||||
titleLines={1}
|
titleLines={1}
|
||||||
|
titleAlign="between"
|
||||||
onBack={tabletSplit ? undefined : trajectory ? handleBack : openSessionsDrawer}
|
onBack={tabletSplit ? undefined : trajectory ? handleBack : openSessionsDrawer}
|
||||||
backIcon={trajectory ? ArrowLeft : Menu}
|
backIcon={trajectory ? ArrowLeft : Menu}
|
||||||
backLabel={trajectory ? strings.common.back : strings.chat.openHostSessions}
|
backLabel={trajectory ? strings.common.back : strings.chat.openHostSessions}
|
||||||
|
|
@ -1081,7 +1189,7 @@ export function ChatScreen({
|
||||||
<IconButton label={trajectory ? strings.trajectory.close : strings.trajectory.open}
|
<IconButton label={trajectory ? strings.trajectory.close : strings.trajectory.open}
|
||||||
icon={trajectory ? MessageSquare : ListTree} dense tint={trajectory ? colors.primary : undefined}
|
icon={trajectory ? MessageSquare : ListTree} dense tint={trajectory ? colors.primary : undefined}
|
||||||
onPress={() => { Keyboard.dismiss(); setMentionType(null); setTrajectory(value => !value) }} />
|
onPress={() => { Keyboard.dismiss(); setMentionType(null); setTrajectory(value => !value) }} />
|
||||||
<IconButton label={strings.chat.newChat} icon={OfficialMenuIcons.newChat} dense onPress={() => void startNewSession()} disabled={newSessionPending || busy !== undefined} />
|
<IconButton label={strings.chat.newChat} icon={OfficialMenuIcons.newChat} dense onPress={() => void startNewSession()} disabled={(sessionBlank && !hasComposerContent) || newSessionPending || busy !== undefined} />
|
||||||
</>}
|
</>}
|
||||||
/>
|
/>
|
||||||
{!connected && (
|
{!connected && (
|
||||||
|
|
@ -1091,30 +1199,23 @@ export function ChatScreen({
|
||||||
accessibilityLiveRegion="polite" disabled={connectionRetrying}
|
accessibilityLiveRegion="polite" disabled={connectionRetrying}
|
||||||
onPress={() => void reconnectCurrentSession()}>
|
onPress={() => void reconnectCurrentSession()}>
|
||||||
<View style={styles.connectionDot} />
|
<View style={styles.connectionDot} />
|
||||||
<Text style={styles.connectionBannerText}>
|
<Text style={styles.connectionBannerText} numberOfLines={1}>
|
||||||
{connectionRetrying ? <>{strings.chat.reconnecting.replace(/…$/, '')}<AnimatedEllipsis /></> : strings.chat.offline}
|
{connectionRetrying ? <>{strings.chat.reconnecting.replace(/…$/, '')}<AnimatedEllipsis /></> : strings.chat.offline}
|
||||||
</Text>
|
</Text>
|
||||||
</Pressable>
|
</Pressable>
|
||||||
)}
|
)}
|
||||||
{connected && busy === `session:${session.sessionId}` && (
|
{connected && busy === `session:${session.sessionId}` && (
|
||||||
<View style={styles.connectionBanner} accessibilityRole="summary">
|
<View style={styles.syncBanner} accessibilityRole="summary">
|
||||||
<View style={[styles.connectionDot, { backgroundColor: colors.primary }]} />
|
<ActivityIndicator size="small" color={colors.primary} style={{ transform: [{ scale: 0.7 }] }} />
|
||||||
<Text style={styles.connectionBannerText}>
|
<Text style={styles.connectionBannerText} numberOfLines={1}>
|
||||||
{strings.chat.syncingHistory}
|
{strings.chat.syncingHistory}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
return (
|
return wrapChatShell(
|
||||||
<ChatImageProvider value={imageLoader}><MarkdownLinkProvider onLinkPress={openLink}><KeyboardInset>
|
<View style={styles.splitMain} {...swipeRightTouchProps}>
|
||||||
{memoryError !== undefined && <Text accessibilityRole="alert" style={{color: colors.danger, padding: 8}}>{memoryError}</Text>}
|
{memoryError !== undefined && <Text accessibilityRole="alert" style={{color: colors.danger, padding: 8}}>{memoryError}</Text>}
|
||||||
<View key="chat-layout" style={[styles.splitRoot, tabletSplit && styles.splitRootWide]}>
|
|
||||||
{tabletSplit && (
|
|
||||||
<View style={styles.splitSidebar}>
|
|
||||||
{drawerElement(true)}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
<View style={styles.splitMain} {...swipeRightTouchProps}>
|
|
||||||
{/* Messages scroll beneath the frosted header; the trajectory view keeps its own fixed search bar below it. */}
|
{/* Messages scroll beneath the frosted header; the trajectory view keeps its own fixed search bar below it. */}
|
||||||
<BlurHeaderFrame header={header} inset={trajectory}>{headerHeight => <ChatErrorBoundary key={session.sessionId} resetKey={session.sessionId}><Animated.View style={[{ flex: 1 }, { opacity: trajectoryMotion, transform: [{ translateY: trajectoryMotion.interpolate({ inputRange: [0, 1], outputRange: [resolveMotion('fullscreen', reduceMotion).translate, 0] }) }] }]}>{trajectory ? <ChatTrajectory key={session.sessionId} items={messages} renderImages={images => <ChatImages images={images} />} hasMore={historyHasMore} loading={historyLoadingOlder} loadOlder={() => void loadOlderHistory()} renderItem={item => <ChatItemView item={item} compact={false} busyAction={busy} onApproval={respondApproval} onQuestion={respondQuestion} />} /> : <>
|
<BlurHeaderFrame header={header} inset={trajectory}>{headerHeight => <ChatErrorBoundary key={session.sessionId} resetKey={session.sessionId}><Animated.View style={[{ flex: 1 }, { opacity: trajectoryMotion, transform: [{ translateY: trajectoryMotion.interpolate({ inputRange: [0, 1], outputRange: [resolveMotion('fullscreen', reduceMotion).translate, 0] }) }] }]}>{trajectory ? <ChatTrajectory key={session.sessionId} items={messages} renderImages={images => <ChatImages images={images} />} hasMore={historyHasMore} loading={historyLoadingOlder} loadOlder={() => void loadOlderHistory()} renderItem={item => <ChatItemView item={item} compact={false} busyAction={busy} onApproval={respondApproval} onQuestion={respondQuestion} />} /> : <>
|
||||||
<FlatList
|
<FlatList
|
||||||
|
|
@ -1147,7 +1248,15 @@ export function ChatScreen({
|
||||||
onMomentumScrollEnd={onListMomentumEnd}
|
onMomentumScrollEnd={onListMomentumEnd}
|
||||||
ListEmptyComponent={busy === `session:${session.sessionId}`
|
ListEmptyComponent={busy === `session:${session.sessionId}`
|
||||||
? <View style={{ padding: spacing.xl }}><ActivityIndicator size="large" color={colors.primary} /></View>
|
? <View style={{ padding: spacing.xl }}><ActivityIndicator size="large" color={colors.primary} /></View>
|
||||||
: <WelcomeMessage />}
|
: <WelcomeMessage policyHint={strings.chat[(BACKEND_CHAT_TEXT_KEYS[session.backend ?? 'harness'] ?? BACKEND_CHAT_TEXT_KEYS.harness).policyHint]} />}
|
||||||
|
ListFooterComponent={replyActive ? (
|
||||||
|
<ReplyStatusBanner
|
||||||
|
label={stopping
|
||||||
|
? strings.chat.stopping
|
||||||
|
: strings.chat[(BACKEND_CHAT_TEXT_KEYS[session.backend ?? 'harness'] ?? BACKEND_CHAT_TEXT_KEYS.harness).generating]}
|
||||||
|
stopping={stopping}
|
||||||
|
/>
|
||||||
|
) : undefined}
|
||||||
ListHeaderComponent={historyHasMore ? (
|
ListHeaderComponent={historyHasMore ? (
|
||||||
<Pressable
|
<Pressable
|
||||||
accessibilityRole="button"
|
accessibilityRole="button"
|
||||||
|
|
@ -1222,30 +1331,56 @@ export function ChatScreen({
|
||||||
)}
|
)}
|
||||||
{stagedFiles.length > 0 && (
|
{stagedFiles.length > 0 && (
|
||||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} keyboardShouldPersistTaps="always" contentContainerStyle={styles.fileTray}>
|
<ScrollView horizontal showsHorizontalScrollIndicator={false} keyboardShouldPersistTaps="always" contentContainerStyle={styles.fileTray}>
|
||||||
{stagedFiles.map((file, index) => (
|
{stagedFiles.map((file, index) => {
|
||||||
<View key={`${file.id}:${index}`} style={styles.fileCard}>
|
const video = isVideoFile(file.name, file.mimeType)
|
||||||
<FileText size={16} color={colors.primary} />
|
const sizeLine = file.durationMs !== undefined
|
||||||
<View style={styles.fileCardMeta}>
|
? `${formatFileBytes(file.size)} · ${formatDurationMs(file.durationMs)}`
|
||||||
<Text style={styles.fileCardName} numberOfLines={1}>{file.name}</Text>
|
: formatFileBytes(file.size)
|
||||||
<Text style={styles.fileCardSize}>{formatFileBytes(file.size)}</Text>
|
return (
|
||||||
|
<View key={`${file.id}:${index}`} style={styles.fileCard}>
|
||||||
|
{video ? <Film size={16} color={colors.primary} /> : <FileText size={16} color={colors.primary} />}
|
||||||
|
<View style={styles.fileCardMeta}>
|
||||||
|
<Text style={styles.fileCardName} numberOfLines={1}>{file.name}</Text>
|
||||||
|
<Text style={styles.fileCardSize}>{sizeLine}</Text>
|
||||||
|
</View>
|
||||||
|
<Pressable
|
||||||
|
accessibilityRole="button"
|
||||||
|
accessibilityLabel={file.name ? strings.chat.removeFile(file.name) : strings.chat.unnamedFile}
|
||||||
|
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
|
||||||
|
onPress={() => setStagedFiles(current => current.filter((_, fileIndex) => fileIndex !== index))}
|
||||||
|
style={styles.removeFileButton}
|
||||||
|
>
|
||||||
|
<X size={13} color={colors.muted} />
|
||||||
|
</Pressable>
|
||||||
</View>
|
</View>
|
||||||
<Pressable
|
)
|
||||||
accessibilityRole="button"
|
})}
|
||||||
accessibilityLabel={file.name ? `移除文件“${file.name}”` : '移除文件'}
|
|
||||||
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
|
|
||||||
onPress={() => setStagedFiles(current => current.filter((_, fileIndex) => fileIndex !== index))}
|
|
||||||
style={styles.removeFileButton}
|
|
||||||
>
|
|
||||||
<X size={13} color={colors.muted} />
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
)}
|
)}
|
||||||
{uploadingFiles && (
|
{uploadingFiles && (
|
||||||
<Text style={[styles.fileCardSize, { paddingHorizontal: spacing.md, paddingBottom: spacing.xs }]}>
|
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: spacing.md, paddingBottom: spacing.xs, gap: spacing.sm }}>
|
||||||
{strings.chat.uploadingFile(stagedFiles[0]?.name ?? '')}
|
<Text style={[styles.fileCardSize, { flexShrink: 1 }]} numberOfLines={1}>
|
||||||
</Text>
|
{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 ?? '')}
|
||||||
|
</Text>
|
||||||
|
<Pressable
|
||||||
|
accessibilityRole="button"
|
||||||
|
accessibilityLabel={strings.chat.cancelUpload}
|
||||||
|
hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
|
||||||
|
onPress={() => {
|
||||||
|
triggerLightHaptic()
|
||||||
|
uploadControllerRef.current?.abort()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text style={[styles.fileCardSize, { color: colors.primary, fontWeight: '600' }]}>{strings.chat.cancelUpload}</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
)}
|
)}
|
||||||
<ReferencedChatPills
|
<ReferencedChatPills
|
||||||
items={stagedReferences}
|
items={stagedReferences}
|
||||||
|
|
@ -1254,15 +1389,14 @@ export function ChatScreen({
|
||||||
<ChatComposer
|
<ChatComposer
|
||||||
backend={session.backend} draft={draft} input={mentionInput}
|
backend={session.backend} draft={draft} input={mentionInput}
|
||||||
quotes={quotes} onRemoveQuote={index => setQuotes(current => current.filter((_, i) => i !== index))}
|
quotes={quotes} onRemoveQuote={index => setQuotes(current => current.filter((_, i) => i !== index))}
|
||||||
replyActive={replyActive} stopping={stopping} compactRunning={compactRunning}
|
replyActive={replyActive} stopping={stopping} commandRunning={commandRunning}
|
||||||
hasComposerContent={hasComposerContent} connected={connected} editable={inputEditable}
|
hasComposerContent={hasComposerContent} connected={connected} editable={inputEditable}
|
||||||
composerDisabled={composerDisabled} sendDisabled={sendDisabled}
|
composerDisabled={composerDisabled} sendDisabled={sendDisabled}
|
||||||
compactComposer={compactComposer} composerInputMaxHeight={composerInputMaxHeight}
|
compactComposer={compactComposer} composerInputMaxHeight={composerInputMaxHeight}
|
||||||
model={{ available: sessionModels !== undefined, label: currentModelLabel, selecting: modelSelecting, onOpen: () => setModelPickerOpen(true) }}
|
|
||||||
promptsPickerOpen={promptsPickerOpen} onExpand={() => setComposingDuringRun(true)}
|
|
||||||
onOpenExpand={() => setComposerExpanded(true)}
|
onOpenExpand={() => setComposerExpanded(true)}
|
||||||
onOpenActions={openPlusMenu} onOpenPrompts={openPromptsPicker}
|
onOpenActions={openPlusMenu}
|
||||||
onSubmit={() => void submit()} onStop={() => void stopSession()}
|
onOpenPrompts={openPromptsPicker}
|
||||||
|
onSubmit={() => void submit()} onStop={stopOrCancel}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
@ -1278,14 +1412,14 @@ export function ChatScreen({
|
||||||
stopping={stopping}
|
stopping={stopping}
|
||||||
sendDisabled={sendDisabled}
|
sendDisabled={sendDisabled}
|
||||||
onSubmit={() => void submit()}
|
onSubmit={() => void submit()}
|
||||||
onStop={() => void stopSession()}
|
onStop={stopOrCancel}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>,
|
||||||
</View>
|
<>
|
||||||
|
|
||||||
<ChatActionMenu
|
<ChatActionMenu
|
||||||
visible={plusMenuOpen} onClose={closePlusMenu} anchor={sheetAnchor}
|
visible={plusMenuOpen} onClose={closePlusMenu} anchor={sheetAnchor}
|
||||||
canAttachImages={canAttachImages} attachmentPicking={attachmentPicking}
|
attachmentPicking={attachmentPicking}
|
||||||
takePhoto={takePhoto} pickImages={pickImages} pickFiles={pickFiles}
|
takePhoto={takePhoto} pickImages={pickImages} pickFiles={pickFiles}
|
||||||
workspaceLabel={workspaceLabel} modeLabel={modeLabel}
|
workspaceLabel={workspaceLabel} modeLabel={modeLabel}
|
||||||
supportsModeSelection={supportsModeSelection} agentPresetSelecting={agentPresetSelecting}
|
supportsModeSelection={supportsModeSelection} agentPresetSelecting={agentPresetSelecting}
|
||||||
|
|
@ -1294,6 +1428,7 @@ export function ChatScreen({
|
||||||
permissionDisabled={permissionSelecting || (replyActive && !hasComposerContent)}
|
permissionDisabled={permissionSelecting || (replyActive && !hasComposerContent)}
|
||||||
permissionLabel={permissions === undefined ? undefined : permissionDisplayName(permissions.currentValue, currentPermission?.name)}
|
permissionLabel={permissions === undefined ? undefined : permissionDisplayName(permissions.currentValue, currentPermission?.name)}
|
||||||
onReferenceChat={(session.backend ?? 'harness') === 'harness' ? () => setReferenceChatOpen(true) : undefined}
|
onReferenceChat={(session.backend ?? 'harness') === 'harness' ? () => setReferenceChatOpen(true) : undefined}
|
||||||
|
onOpenPrompts={openPromptsPicker}
|
||||||
onOpenWorkspace={() => setWorkspacePickerOpen(true)} onOpenMode={() => setModePickerOpen(true)}
|
onOpenWorkspace={() => setWorkspacePickerOpen(true)} onOpenMode={() => setModePickerOpen(true)}
|
||||||
onOpenTools={() => setToolPickerOpen(true)} onOpenPermissions={() => setPermissionPickerOpen(true)}
|
onOpenTools={() => setToolPickerOpen(true)} onOpenPermissions={() => setPermissionPickerOpen(true)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -1341,14 +1476,19 @@ export function ChatScreen({
|
||||||
else openSessionsDrawer()
|
else openSessionsDrawer()
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{sessionsOpen && !tabletSplit && drawerElement(false)}
|
|
||||||
<WorkspacePicker visible={workspacePickerOpen} workspaces={workspaces} currentSessionId={session.sessionId} sessionBackend={session.backend} busy={busy} onClose={() => setWorkspacePickerOpen(false)} onPick={pickWorkspace} onManage={() => { setWorkspacePickerOpen(false); openSessionsDrawer() }} />
|
<WorkspacePicker visible={workspacePickerOpen} workspaces={workspaces} currentSessionId={session.sessionId} sessionBackend={session.backend} busy={busy} onClose={() => setWorkspacePickerOpen(false)} onPick={pickWorkspace} onManage={() => { setWorkspacePickerOpen(false); openSessionsDrawer() }} />
|
||||||
<ToolAccessPicker visible={toolPickerOpen} onClose={() => setToolPickerOpen(false)} onPick={pickToolMode} />
|
<ToolAccessPicker visible={toolPickerOpen} onClose={() => setToolPickerOpen(false)} onPick={pickToolMode} />
|
||||||
<PromptsPicker
|
<PromptsPicker
|
||||||
visible={promptsPickerOpen}
|
visible={promptsPickerOpen}
|
||||||
prompts={customPrompts ?? BUILT_IN_PROMPTS}
|
prompts={customPrompts ?? BUILT_IN_PROMPTS}
|
||||||
|
actionMode={quickPromptActionMode}
|
||||||
|
onToggleActionMode={mode => {
|
||||||
|
void setQuickPromptActionMode(mode).catch(() => {
|
||||||
|
Alert.alert(strings.settings.quickPromptActionMode, strings.settings.quickPromptActionSaveFailed)
|
||||||
|
})
|
||||||
|
}}
|
||||||
onClose={() => setPromptsPickerOpen(false)}
|
onClose={() => setPromptsPickerOpen(false)}
|
||||||
onPick={prompt => void sendPrompt(prompt)}
|
onPick={prompt => void pickQuickPrompt(prompt)}
|
||||||
onManage={() => { setPromptsPickerOpen(false); setPromptsManagerOpen(true) }}
|
onManage={() => { setPromptsPickerOpen(false); setPromptsManagerOpen(true) }}
|
||||||
/>
|
/>
|
||||||
<PromptsManager
|
<PromptsManager
|
||||||
|
|
@ -1404,20 +1544,7 @@ export function ChatScreen({
|
||||||
</Pressable>
|
</Pressable>
|
||||||
</View>
|
</View>
|
||||||
</Modal>
|
</Modal>
|
||||||
<PluginsModal visible={pluginsOpen} onClose={() => setPluginsOpen(false)} />
|
</>,
|
||||||
<AutomationTasksModal
|
|
||||||
visible={automationTasksOpen}
|
|
||||||
onClose={() => setAutomationTasksOpen(false)}
|
|
||||||
onOpenSession={async targetSession => {
|
|
||||||
setAutomationTasksOpen(false)
|
|
||||||
await openSession(targetSession)
|
|
||||||
}}
|
|
||||||
onNewTask={async () => {
|
|
||||||
setAutomationTasksOpen(false)
|
|
||||||
await createSession(currentWorkspace?.workspaceId)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</KeyboardInset></MarkdownLinkProvider></ChatImageProvider>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue