From 54b5c8e57ad3a1c909d643b81f2e7edf46cdf9b3 Mon Sep 17 00:00:00 2001 From: QQ Date: Sat, 14 Nov 2026 14:13:17 +0800 Subject: [PATCH] Import apps/android/src/screens/bot/profile-page.tsx --- apps/android/src/screens/bot/profile-page.tsx | 1563 +++++++++++++++++ 1 file changed, 1563 insertions(+) create mode 100644 apps/android/src/screens/bot/profile-page.tsx diff --git a/apps/android/src/screens/bot/profile-page.tsx b/apps/android/src/screens/bot/profile-page.tsx new file mode 100644 index 0000000..770bc70 --- /dev/null +++ b/apps/android/src/screens/bot/profile-page.tsx @@ -0,0 +1,1563 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + ActivityIndicator, + Alert, + Animated, + BackHandler, + Dimensions, + Easing, + Modal, + Pressable, + ScrollView, + StyleSheet, + Text, + View, +} from 'react-native' +import * as Clipboard from 'expo-clipboard' +import { + ArrowLeftRight, + Check, + ChevronDown, + ChevronLeft, + ChevronRight, + Copy, + CopyPlus, + FileText, + FolderOpen, + Globe, + MoreHorizontal, + Pause, + Play, + Plus, + Settings, + Square, + Trash2, + Users, + X, +} from 'lucide-react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { strings as s } from '../../locales/i18n' +import { + canDeleteBot, + object, + objects, + text, + type BotEntry, + type BotObject, + type BotOperation, + type BotRemoteClient, + type BotRoom, + type BotState, +} from '../../services/bot-catalog' +import { useAppStore } from '../../state/store' +import { Button, IconButton } from '../../ui/components' +import { useTheme, type ThemeColors } from '../../ui/theme-context' +import { Toggle } from '../../ui/toggle' +import { useThemedStyles } from '../../ui/use-themed-styles' +import { ModalSurface } from '../chat/modal' +import { BotAgentBadge, engineOfModel } from './agent-badge' +import { BotAvatar, BotAvatarWithBadge } from './avatar' +import { BotFloatingPopover, type BotPopoverAction } from './popover-menu' +import { + BotBrowserPane, + BotFolderPickerModal, + BotMemoryPanel, + BotSchedulesPanel, + folderBasename, + formatCompactTokens, + formatScheduleSummary, +} from './shared-panels' + +type ProfileTopTab = 'details' | 'browser' +type ProfileSubPage = 'sessions' | 'memory' | 'usage' | 'schedules' | null + +function isNonEmptyObject(value: BotObject | undefined): boolean { + return value !== undefined && Object.keys(value).length > 0 +} + +function groupBotModels(models: BotObject[]): { provider: string; label: string; items: BotObject[] }[] { + const groups = new Map() + for (const model of models) { + const ref = text(model.ref) + const provider = text(model.provider) || text(model.providerName) || ref.split('/')[0] || 'default' + const existing = groups.get(provider) + if (existing) existing.push(model) + else groups.set(provider, [model]) + } + return [...groups].map(([provider, items]) => ({ + provider, + label: text(items[0]?.providerName) || provider, + items, + })) +} + +export function BotProfilePage({ + visible, + bot, + room, + state, + client, + busy, + error, + runStats, + onClose, + onEdit, + perform, +}: { + visible: boolean + bot?: BotEntry + room?: BotRoom + state: BotState + client?: BotRemoteClient + busy: boolean + error?: string + runStats?: BotObject | null + onClose: () => void + onEdit: () => void + perform: (operation: BotOperation, payload?: BotObject) => Promise<{ ok: boolean; value?: unknown }> +}) { + const insets = useSafeAreaInsets() + const { colors, scheme } = useTheme() + const styles = useThemedStyles(createProfileStyles) + const appSessions = useAppStore(store => store.sessions) + + const [mounted, setMounted] = useState(visible) + const [topTab, setTopTab] = useState('details') + const [subPage, setSubPage] = useState(null) + const [mountedSubPage, setMountedSubPage] = useState(null) + const [schedulesStartCreating, setSchedulesStartCreating] = useState(false) + const [moreOpen, setMoreOpen] = useState(false) + const [modelPickerOpen, setModelPickerOpen] = useState(false) + const [folderPickerOpen, setFolderPickerOpen] = useState(false) + + const [schedulesData, setSchedulesData] = useState(null) + const [schedulesLoading, setSchedulesLoading] = useState(false) + const [memoryCount, setMemoryCount] = useState(null) + const [usageData, setUsageData] = useState(null) + const [usageLoading, setUsageLoading] = useState(false) + + const screenWidth = Dimensions.get('window').width || 390 + const slideAnim = useRef(new Animated.Value(screenWidth)).current + const subSlideAnim = useRef(new Animated.Value(screenWidth)).current + + useEffect(() => { + if (visible) { + setMounted(true) + setTopTab('details') + setSubPage(null) + setMountedSubPage(null) + setMoreOpen(false) + slideAnim.setValue(screenWidth) + Animated.timing(slideAnim, { + toValue: 0, + duration: 250, + easing: Easing.out(Easing.cubic), + useNativeDriver: true, + }).start() + } else if (mounted) { + setMoreOpen(false) + Animated.timing(slideAnim, { + toValue: screenWidth, + duration: 210, + easing: Easing.in(Easing.cubic), + useNativeDriver: true, + }).start(({ finished }) => { + if (finished) { + setMounted(false) + setSubPage(null) + setMountedSubPage(null) + } + }) + } + }, [visible, screenWidth, slideAnim, mounted]) + + const openSubPage = useCallback( + (target: Exclude, createScheduleNow = false) => { + setSchedulesStartCreating(createScheduleNow) + setSubPage(target) + setMountedSubPage(target) + subSlideAnim.setValue(screenWidth) + Animated.timing(subSlideAnim, { + toValue: 0, + duration: 240, + easing: Easing.out(Easing.cubic), + useNativeDriver: true, + }).start() + }, + [screenWidth, subSlideAnim], + ) + + const closeSubPage = useCallback(() => { + setSubPage(null) + Animated.timing(subSlideAnim, { + toValue: screenWidth, + duration: 200, + easing: Easing.in(Easing.cubic), + useNativeDriver: true, + }).start(({ finished }) => { + if (finished) setMountedSubPage(null) + }) + }, [screenWidth, subSlideAnim]) + + const handleBack = useCallback(() => { + if (moreOpen) { + setMoreOpen(false) + return true + } + if (subPage !== null) { + closeSubPage() + return true + } + onClose() + return true + }, [moreOpen, subPage, closeSubPage, onClose]) + + useEffect(() => { + if (!visible) return + const sub = BackHandler.addEventListener('hardwareBackPress', handleBack) + return () => sub.remove() + }, [visible, handleBack]) + + const reloadSchedules = useCallback(() => { + if (!visible || !client) return + setSchedulesLoading(true) + void client + .call('schedules') + .then(val => { + setSchedulesData(objects(object(val).tasks)) + }) + .catch(() => setSchedulesData([])) + .finally(() => setSchedulesLoading(false)) + }, [visible, client]) + + useEffect(() => { + reloadSchedules() + }, [reloadSchedules, bot?.id, room?.id]) + + useEffect(() => { + const ownerId = bot?.id ?? room?.id + if (!visible || !client || !ownerId || state.memory === false) { + setMemoryCount(0) + return + } + let cancelled = false + setMemoryCount(null) + void client + .call('memory-view', { id: ownerId }) + .then(res => { + if (!cancelled) setMemoryCount(objects(object(res).entries).length) + }) + .catch(() => { + if (!cancelled) setMemoryCount(0) + }) + return () => { + cancelled = true + } + }, [visible, client, bot?.id, room?.id, state.memory]) + + const loadFullUsage = useCallback(() => { + if (!client) return + setUsageLoading(true) + void client + .call('usage', { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone }) + .then(val => setUsageData(object(val))) + .catch(() => setUsageData(null)) + .finally(() => setUsageLoading(false)) + }, [client]) + + useEffect(() => { + if (visible && client) loadFullUsage() + }, [visible, client, loadFullUsage, bot?.id, room?.id]) + + const botSchedules = useMemo(() => { + if (!schedulesData) return [] + if (bot) { + return schedulesData.filter( + t => text(t.botId) === bot.id || text(t.sessionId) === bot.sessionId || (bot.parts ?? []).includes(text(t.sessionId)), + ) + } + if (room) { + return schedulesData.filter( + t => text(t.roomId) === room.id || text(t.sessionId) === room.sessionId || (room.ownParts ?? []).includes(text(t.sessionId)), + ) + } + return [] + }, [schedulesData, bot, room]) + + if (!mounted || (!bot && !room)) return null + + const mainCount = state.bots.filter(b => b.main).length + const allParts = bot + ? [bot.sessionId, ...(bot.parts ?? []).filter(id => id !== bot.sessionId).slice().reverse()] + : [] + + const confirmDelete = () => { + const targetId = bot?.id ?? room?.id + if (!targetId) return + Alert.alert(s.bots.delete, s.bots.deleteHint, [ + { text: s.bots.cancel, style: 'cancel' }, + { + text: s.bots.delete, + style: 'destructive', + onPress: () => { + onClose() + void perform(bot ? 'delete-bot' : 'delete-room', { id: targetId }) + }, + }, + ]) + } + + const popoverActions: BotPopoverAction[] = [] + if (bot) { + popoverActions.push({ + key: 'browser', + icon: Globe, + label: s.bots.browser, + onPress: () => setTopTab('browser'), + }) + popoverActions.push({ + key: 'sessions', + icon: FolderOpen, + label: `${s.bots.sessions} (${allParts.length})`, + onPress: () => openSubPage('sessions'), + }) + popoverActions.push({ + key: 'new-part', + icon: Plus, + label: s.bots.newSession, + disabled: busy || Boolean(state.readOnly), + onPress: () => { + onClose() + void perform('bot-new-part', { botId: bot.id }) + }, + }) + if (!bot.main || mainCount > 1) { + popoverActions.push({ + key: 'main', + icon: ArrowLeftRight, + label: bot.main ? s.bots.removeMain : s.bots.replaceMain, + disabled: busy || Boolean(state.readOnly), + onPress: () => void perform('set-main', { id: bot.id, main: !bot.main }), + }) + } + if (!bot.private) { + popoverActions.push({ + key: 'duplicate', + icon: CopyPlus, + label: s.bots.duplicate, + disabled: busy || Boolean(state.readOnly), + onPress: () => { + onClose() + void perform('duplicate-bot', { id: bot.id }) + }, + }) + } + popoverActions.push({ + key: 'copy-id', + icon: Copy, + label: s.bots.copyId, + onPress: () => void Clipboard.setStringAsync(bot.id), + }) + if (canDeleteBot(state, bot)) { + popoverActions.push({ + key: 'delete', + icon: Trash2, + label: s.bots.delete, + danger: true, + disabled: busy || Boolean(state.readOnly), + onPress: confirmDelete, + }) + } + } else if (room) { + popoverActions.push({ + key: 'stop-room', + icon: Square, + label: s.bots.stop, + disabled: busy || Boolean(state.readOnly), + onPress: () => void perform('stop-room-work', { roomId: room.id }), + }) + popoverActions.push({ + key: 'copy-id', + icon: Copy, + label: s.bots.copyId, + onPress: () => void Clipboard.setStringAsync(room.id), + }) + popoverActions.push({ + key: 'delete', + icon: Trash2, + label: s.bots.delete, + danger: true, + disabled: busy || Boolean(state.readOnly), + onPress: confirmDelete, + }) + } + + // Model & availability (Figure 1: `group/duty` + `magpie · 不可用`) + const activeModelRef = bot ? bot.model || bot.appliedModel || state.defaultModel || '' : '' + const matchedModel = activeModelRef ? state.models.find(m => text(m.ref) === activeModelRef) : undefined + const modelAvailable = !activeModelRef || state.models.length === 0 || Boolean(matchedModel && !matchedModel.needsKey) + const modelTitle = activeModelRef + ? text(matchedModel?.name) || text(matchedModel?.label) || activeModelRef + : s.bots.defaultModel + const modelProvider = activeModelRef + ? text(matchedModel?.providerName) || text(matchedModel?.provider) || activeModelRef.split('/')[0] || '' + : '' + + // Permission preset (`read-only` | `workspace-write` | `danger-full-access`) + const defaultPerm = text(state.permissions?.defaultPreset) || 'workspace-write' + const currentPerm = bot?.permission || defaultPerm + + // Usage summary (`600.9K tok · 缓存命中 74%`) + const usageInlineText = (() => { + const tu = runStats ? object(runStats.tokenUsage) : {} + let input = Number(tu.inputTokens ?? 0) + let output = Number(tu.outputTokens ?? 0) + let cacheRead = Number(tu.cacheReadTokens ?? tu.cachedInputTokens ?? 0) + + if (input + output <= 0 && Array.isArray(usageData?.rows)) { + const targetName = bot?.name ?? room?.name ?? '' + for (const r of usageData!.rows) { + if (!Array.isArray(r)) continue + const rowOwner = text(r[0]) + if (!targetName || rowOwner === targetName || rowOwner === (bot?.id ?? room?.id)) { + input += Number(r[3] ?? 0) + output += Number(r[4] ?? 0) + cacheRead += Number(r[5] ?? 0) + } + } + } + const total = input + output + cacheRead + if (total <= 0) return '0 tok' + const hit = input + cacheRead > 0 ? Math.round((cacheRead / (input + cacheRead)) * 100) : 0 + return s.bots.usageSummary(formatCompactTokens(total), hit) + })() + + const canvasBg = scheme === 'light' ? '#F6F7F9' : colors.background + const cardBg = scheme === 'light' ? '#FFFFFF' : colors.cardOpaque + + const memoryCountLabel = + memoryCount === null ? '…' : memoryCount === 0 ? s.bots.memoryEmpty : s.bots.memoryCount(memoryCount) + + return ( + + + + {/* Top Action Bar (`<` on left, `⚙` Settings + `•••` More on right, matching Figure 1) */} + + [styles.circleBtn, { backgroundColor: cardBg }, pressed && styles.btnPressed]} + > + + + + + { + onClose() + onEdit() + }} + hitSlop={8} + style={({ pressed }) => [ + styles.circleBtn, + { backgroundColor: cardBg }, + pressed && styles.btnPressed, + (busy || Boolean(state.readOnly)) && { opacity: 0.45 }, + ]} + > + + + + setMoreOpen(true)} + hitSlop={8} + style={({ pressed }) => [styles.circleBtn, { backgroundColor: cardBg }, pressed && styles.btnPressed]} + > + + + + + + {/* Compact Header + `详情 | 浏览器` Segmented Tabs */} + + {bot ? ( + + ) : room ? ( + + {room.members.slice(0, 3).map((id, idx) => { + const member = state.bots.find(b => b.id === id) + return member ? ( + + + + ) : null + })} + {room.members.length === 0 && } + + ) : null} + + + + {bot?.name ?? room?.name} + + {bot && ( + + )} + + + {topTab === 'details' && Boolean(bot?.role || room?.notice) && ( + + {bot?.role ?? room?.notice} + + )} + + {/* Figure 1 Segmented Tabs: `详情 | 浏览器` */} + {bot && ( + + {([ + ['details', s.bots.details], + ['browser', s.bots.browser], + ] as const).map(([key, label]) => { + const active = topTab === key + return ( + setTopTab(key)} + style={[ + styles.segmentedTab, + active && [ + styles.segmentedTabActive, + { backgroundColor: scheme === 'light' ? '#FFFFFF' : colors.surfaceStrong }, + ], + ]} + > + + {label} + + + ) + })} + + )} + + + {Boolean(error) && ( + + {error} + + )} + + {/* Browser Tab Content (Figure 2) */} + {bot && topTab === 'browser' ? ( + + + + ) : ( + + {bot ? ( + + {/* 1. 模型 (Model Selector Box, matching Figure 1) */} + + {s.bots.model} + setModelPickerOpen(true)} + style={({ pressed }) => [ + styles.selectorBox, + { backgroundColor: cardBg }, + pressed && styles.cardRowPressed, + ]} + > + + + {modelTitle} + + {(modelProvider || !modelAvailable || bot.effort) && ( + + {[ + modelProvider, + !modelAvailable ? s.bots.modelUnavailable : bot.effort ? `${s.bots.effort}: ${bot.effort}` : '', + ] + .filter(Boolean) + .join(' · ')} + + )} + + + + + + {/* 2. 权限 (3-Segment Pill: 仅可查看 | 工作区内修改 | 完全权限, matching Figure 1) */} + + {s.bots.permissions} + + {( + [ + ['read-only', s.bots.permReadOnly, false], + ['workspace-write', s.bots.permWorkspace, false], + ['danger-full-access', s.bots.permFullAccess, true], + ] as const + ).map(([val, label, danger]) => { + const active = currentPerm === val + return ( + { + if (val !== currentPerm) { + void perform('update-bot', { id: bot.id, permission: val }) + } + }} + style={[ + styles.permOption, + active && [ + styles.permOptionActive, + { backgroundColor: scheme === 'light' ? '#FFFFFF' : colors.surfaceStrong }, + ], + ]} + > + + {label} + + + ) + })} + + + + {/* 3. 工作文件夹 (Working Folder Selector Box: `总工作区 ∨`, matching Figure 1) */} + + {s.bots.workingFolder} + setFolderPickerOpen(true)} + style={({ pressed }) => [ + styles.selectorBox, + { backgroundColor: cardBg }, + pressed && styles.cardRowPressed, + ]} + > + + + {bot.workDir ? folderBasename(bot.workDir) : s.bots.teamWorkspace} + + {Boolean(bot.workDir) && ( + + {bot.workDir} + + )} + + + + + + {/* 4. Instructions / `在 Bot 设置里添加说明` (matching Figure 1) */} + {bot.instructions.trim() ? ( + { + onClose() + onEdit() + }} + style={[styles.selectorBox, { backgroundColor: cardBg }]} + > + + {bot.instructions.trim()} + + + ) : ( + { + onClose() + onEdit() + }} + style={styles.centeredHintBtn} + > + {s.bots.addInstructionsHint} + + )} + + {/* 5. 记忆 (Memory: `📄 3 条 管理 >`, matching Figure 1) */} + {state.memory !== false && ( + + {s.bots.memory} + openSubPage('memory')} + style={({ pressed }) => [ + styles.selectorBox, + { backgroundColor: cardBg }, + pressed && styles.cardRowPressed, + ]} + > + + + {memoryCountLabel} + + + {s.bots.memoryManage} + + + + + )} + + {/* 6. 用量 (Usage: `Chief 600.9K tok · 缓存命中 74%`, matching Figure 1) */} + + {s.bots.usage} + { + loadFullUsage() + openSubPage('usage') + }} + style={({ pressed }) => [ + styles.selectorBox, + { backgroundColor: cardBg }, + pressed && styles.cardRowPressed, + ]} + > + + {bot.name} + + + {usageInlineText} + + + + + + {/* 7. 定时任务 (Scheduled Tasks: `还没有定时任务,去添加` or task rows, matching Figure 1) */} + + + + {botSchedules.length > 0 + ? `${s.bots.scheduledTasks} · ${botSchedules.length}` + : s.bots.scheduledTasks} + + {botSchedules.length > 0 && ( + openSubPage('schedules', false)} hitSlop={8}> + {s.bots.memoryManage} + + )} + + + {schedulesLoading ? ( + + + + ) : botSchedules.length === 0 ? ( + openSubPage('schedules', true)} + style={({ pressed }) => [ + styles.selectorBox, + { backgroundColor: cardBg }, + pressed && styles.cardRowPressed, + ]} + > + {s.bots.schedulesNoneAdd} + + + ) : ( + openSubPage('schedules', false)} + style={({ pressed }) => [ + styles.groupCard, + { backgroundColor: cardBg }, + pressed && styles.cardRowPressed, + ]} + > + {botSchedules.slice(0, 3).map((task, idx) => ( + 0 && styles.cardRowDivider]}> + + + {text(task.title) || s.bots.scheduledTasks} + + + {formatScheduleSummary(task)} + + + + + ))} + + )} + + + {/* 会话分段快捷入口 + 置顶开关 */} + + openSubPage('sessions')} + style={({ pressed }) => [styles.cardRow, pressed && styles.cardRowPressed]} + > + + {s.bots.sessions} + {s.bots.sessionsCount(allParts.length)} + + + {!bot.tile && ( + + {s.bots.pinChat} + void perform('set-flags', { id: bot.id, pinned: !bot.pinned })} + /> + + )} + + + {canDeleteBot(state, bot) && ( + + [ + styles.cardRow, + pressed && styles.cardRowPressed, + (busy || Boolean(state.readOnly)) && { opacity: 0.45 }, + ]} + > + + {s.bots.delete} + + + )} + + ) : room ? ( + + {room.goal && isNonEmptyObject(room.goal) && ( + + + {s.sessionActivity.goal}: {text(room.goal.title) || text(room.goal.status)} + + + {text(room.goal.status) === 'running' ? ( +