diff --git a/apps/android/src/screens/bot/shared-panels.tsx b/apps/android/src/screens/bot/shared-panels.tsx new file mode 100644 index 0000000..632d827 --- /dev/null +++ b/apps/android/src/screens/bot/shared-panels.tsx @@ -0,0 +1,1650 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + ActivityIndicator, + Modal, + Pressable, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native' +import { WebView } from 'react-native-webview' +import { + ArrowUp, + CalendarClock, + Check, + ChevronLeft, + ChevronRight, + Download, + FileText, + Folder, + Globe, + Lock, + Plus, + RotateCw, + Shield, + Trash2, + X, +} from 'lucide-react-native' +import { strings as s } from '../../locales/i18n' +import { + object, + objects, + text, + type BotEntry, + type BotObject, + type BotOperation, + type BotRemoteClient, + type BotState, +} from '../../services/bot-catalog' +import { useAppStore } from '../../state/store' +import type { ScheduleCreateRequest } from '../../types' +import { Button } from '../../ui/components' +import { radius } from '../../ui/theme' +import { useTheme, type ThemeColors } from '../../ui/theme-context' +import { useThemedStyles } from '../../ui/use-themed-styles' +import { ModalSurface } from '../chat/modal' +import { BotAvatar } from './avatar' + +export type BotPerformFn = ( + operation: BotOperation, + payload?: BotObject, +) => Promise<{ ok: boolean; value?: unknown }> + +export function folderBasename(path?: string): string { + const clean = String(path ?? '').replace(/[\\/]+$/, '') + if (!clean) return '' + return clean.split(/[\\/]/).pop() || clean +} + +export function formatCompactTokens(total: number): string { + if (!Number.isFinite(total) || total <= 0) return '0' + if (total >= 1_000_000) return `${(total / 1_000_000).toFixed(1)}M` + if (total >= 1_000) return `${(total / 1_000).toFixed(1)}K` + return String(Math.round(total)) +} + +export function formatScheduleSummary(task: BotObject): string { + const kind = text(task.kind) || text(object(task.schedule).kind) + const time = (text(task.time) || text(object(task.schedule).time)).replace(/:00$/, '') + if (kind === 'daily') return time ? `${s.bots.scheduleDaily} ${time}` : s.bots.scheduleDaily + if (kind === 'weekly') return time ? `${s.bots.scheduleWeekly} ${time}` : s.bots.scheduleWeekly + if (kind === 'every' || kind === 'interval') { + const everySec = Number(task.everySeconds ?? Number(object(task.schedule).everyMs ?? 0) / 1000) + if (everySec >= 86_400) return `${Math.round(everySec / 86_400)}d` + if (everySec >= 3_600) return `${Math.round(everySec / 3_600)}h` + if (everySec >= 60) return `${Math.max(1, Math.round(everySec / 60))}m` + return s.bots.scheduleInterval + } + if (kind === 'at' || kind === 'once' || kind === 'after') { + const scheduled = text(task.scheduledAt) + if (scheduled) { + const d = new Date(scheduled) + if (!Number.isNaN(d.getTime())) { + return `${s.bots.scheduleOnce} · ${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}` + } + } + return s.bots.scheduleOnce + } + return text(task.cadence) || text(task.expression) || s.bots.scheduledTasks +} + +interface BrowserTabItem { + id: string + url: string + title: string + loading: boolean + canGoBack: boolean + canGoForward: boolean +} + +function normalizeBrowserInput(raw: string): string { + const trimmed = raw.trim() + if (!trimmed || trimmed === 'about:blank') return 'about:blank' + if (/^https?:\/\//i.test(trimmed)) return trimmed + if (/^[a-z0-9-]+(\.[a-z0-9-]+)+(\/.*)?$/i.test(trimmed)) return `https://${trimmed}` + return `https://www.bing.com/search?q=${encodeURIComponent(trimmed)}` +} + +function shortBrowserLabel(tab: BrowserTabItem): string { + if (tab.title && tab.title !== 'about:blank') return tab.title + if (!tab.url || tab.url === 'about:blank') return 'about:blank' + return tab.url.replace(/^https?:\/\//i, '').replace(/^www\./i, '').replace(/\/$/, '') +} + +/** + * Per-Bot embedded Browser pane modeled directly on DS-Bot's `browser-pane.js` (Figure 2): + * - Top tab strip (`about:blank ×`) + * - Bot automation banner (`Bot 正在控制此浏览器` · `接管` · `停止` / `你在控制此浏览器` · `交还`) + * - Navigation bar (`<` `>` `↻` `[🌐 搜索或输入网址]` `+` `⤓/🛡`) + * - Interactive WebView viewport (blank canvas on `about:blank`, live webview on http/https) + */ +export function BotBrowserPane({ + bot, + perform, +}: { + bot: BotEntry + perform: BotPerformFn +}) { + const { colors } = useTheme() + const styles = useThemedStyles(createSharedStyles) + const webViewRef = useRef(null) + + const [tabs, setTabs] = useState([ + { id: 'tab-1', url: 'about:blank', title: 'about:blank', loading: false, canGoBack: false, canGoForward: false }, + ]) + const [activeTabId, setActiveTabId] = useState('tab-1') + const [addressDraft, setAddressDraft] = useState('') + const [editingAddress, setEditingAddress] = useState(false) + const [userHeld, setUserHeld] = useState(false) + const [grantsOpen, setGrantsOpen] = useState(false) + + const activeTab = useMemo( + () => tabs.find(t => t.id === activeTabId) ?? tabs[0]!, + [tabs, activeTabId], + ) + + const updateActiveTab = useCallback( + (patch: Partial) => { + setTabs(prev => prev.map(item => (item.id === activeTab.id ? { ...item, ...patch } : item))) + }, + [activeTab.id], + ) + + const addNewTab = () => { + const id = `tab-${Date.now()}` + setTabs(prev => [ + ...prev, + { id, url: 'about:blank', title: 'about:blank', loading: false, canGoBack: false, canGoForward: false }, + ]) + setActiveTabId(id) + setAddressDraft('') + setEditingAddress(false) + } + + const closeTab = (id: string) => { + setTabs(prev => { + if (prev.length <= 1) { + return [{ id: 'tab-1', url: 'about:blank', title: 'about:blank', loading: false, canGoBack: false, canGoForward: false }] + } + const next = prev.filter(t => t.id !== id) + if (activeTabId === id && next[0]) setActiveTabId(next[0].id) + return next + }) + } + + const submitAddress = () => { + const nextUrl = normalizeBrowserInput(addressDraft) + setEditingAddress(false) + updateActiveTab({ url: nextUrl, title: nextUrl === 'about:blank' ? 'about:blank' : nextUrl }) + } + + const handleTakeover = async () => { + setUserHeld(true) + await perform('browser-takeover', { botId: bot.id }).catch(() => undefined) + } + + const handleGiveBack = async () => { + setUserHeld(false) + await perform('browser-give-back', { botId: bot.id }).catch(() => undefined) + } + + const handleStop = async () => { + setUserHeld(true) + webViewRef.current?.stopLoading() + await perform('browser-stop', { botId: bot.id }).catch(() => undefined) + } + + const isBlank = !activeTab.url || activeTab.url === 'about:blank' + const isSecure = /^https:/i.test(activeTab.url) + const grantCount = (bot.browserGrants ?? []).length + + return ( + + {/* Browser Tab Strip */} + + + {tabs.map(tab => { + const active = tab.id === activeTab.id + return ( + { + setActiveTabId(tab.id) + setEditingAddress(false) + }} + style={[styles.browserTabChip, active && styles.browserTabChipActive]} + > + + + {shortBrowserLabel(tab)} + + closeTab(tab.id)} + style={styles.browserTabClose} + > + + + + ) + })} + + + + {/* Bot Automation Control Banner (matches Figure 2) */} + + + {userHeld ? s.bots.browserUserControls : s.bots.browserBotControls} + + + {userHeld ? ( + void handleGiveBack()} + style={({ pressed }) => [styles.browserBannerBtn, pressed && { opacity: 0.75 }]} + > + {s.bots.browserGiveBack} + + ) : ( + <> + void handleTakeover()} + style={({ pressed }) => [styles.browserBannerBtn, pressed && { opacity: 0.75 }]} + > + {s.bots.browserTakeover} + + void handleStop()} + style={({ pressed }) => [styles.browserBannerBtn, pressed && { opacity: 0.75 }]} + > + {s.bots.stop} + + + )} + + + + {/* Navigation & Address Bar (matches Figure 2) */} + + webViewRef.current?.goBack()} + style={[styles.browserNavIconBtn, (!activeTab.canGoBack || isBlank) && { opacity: 0.35 }]} + > + + + webViewRef.current?.goForward()} + style={[styles.browserNavIconBtn, (!activeTab.canGoForward || isBlank) && { opacity: 0.35 }]} + > + + + (activeTab.loading ? webViewRef.current?.stopLoading() : webViewRef.current?.reload())} + style={[styles.browserNavIconBtn, isBlank && { opacity: 0.45 }]} + > + {activeTab.loading ? : } + + + + {isSecure ? : } + { + setAddressDraft(isBlank ? '' : activeTab.url) + setEditingAddress(true) + }} + onBlur={() => setEditingAddress(false)} + onChangeText={setAddressDraft} + onSubmitEditing={submitAddress} + placeholder={s.bots.browserAddressPlaceholder} + placeholderTextColor={colors.muted} + autoCapitalize="none" + autoCorrect={false} + returnKeyType="go" + style={styles.browserAddressInput} + /> + + + + + + setGrantsOpen(true)} + style={styles.browserNavIconBtn} + > + 0 ? colors.primary : colors.ink} /> + + + + {/* Viewport Area */} + + {isBlank ? ( + + ) : ( + { + updateActiveTab({ + url: navState.url || activeTab.url, + title: navState.title || navState.url || 'about:blank', + loading: Boolean(navState.loading), + canGoBack: Boolean(navState.canGoBack), + canGoForward: Boolean(navState.canGoForward), + }) + }} + /> + )} + + + {/* Per-Bot Browser Site Permissions Sheet */} + {grantsOpen && ( + setGrantsOpen(false)}> + setGrantsOpen(false)}> + + + + + {s.bots.browserGrants} + + setGrantsOpen(false)} hitSlop={8}> + + + + + + + + + + )} + + ) +} + +/** + * Browser site permissions editor modeled on `browser-settings.js`. + */ +export function BotBrowserGrantsSection({ + bots, + fixedBot, + perform, +}: { + bots: BotEntry[] + fixedBot?: BotEntry + perform: BotPerformFn +}) { + const { colors } = useTheme() + const styles = useThemedStyles(createSharedStyles) + const [pickedBotId, setPickedBotId] = useState(fixedBot?.id ?? bots[0]?.id ?? '') + const [botPickerOpen, setBotPickerOpen] = useState(false) + const [site, setSite] = useState('') + const [actions, setActions] = useState(['post']) + const [duration, setDuration] = useState<'hour' | 'today' | 'week' | 'always'>('hour') + + useEffect(() => { + if (fixedBot) { + setPickedBotId(fixedBot.id) + return + } + if (!bots.some(b => b.id === pickedBotId) && bots[0]) { + setPickedBotId(bots[0].id) + } + }, [bots, fixedBot, pickedBotId]) + + const rows = useMemo( + () => + bots.flatMap(bot => + (bot.browserGrants ?? []).map((grant, idx) => ({ + key: `${bot.id}-${idx}-${text(grant.site)}`, + bot, + grant, + })), + ), + [bots], + ) + + const toggleAction = (act: string) => { + setActions(prev => (prev.includes(act) ? prev.filter(x => x !== act) : [...prev, act])) + } + + const computeUntil = (): number | null => { + const now = Date.now() + if (duration === 'hour') return now + 3_600_000 + if (duration === 'today') { + const end = new Date() + end.setHours(23, 59, 59, 999) + return end.getTime() + } + if (duration === 'week') return now + 7 * 86_400_000 + return null + } + + const targetBot = fixedBot ?? bots.find(b => b.id === pickedBotId) ?? bots[0] + + const saveGrant = async () => { + if (!targetBot || !site.trim() || actions.length === 0) return + const normalizedSite = site.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '') + if (!normalizedSite) return + const existing = (targetBot.browserGrants ?? []).filter(g => text(g.site) !== normalizedSite) + const nextGrants = [...existing, { site: normalizedSite, actions, until: computeUntil() }] + const res = await perform('update-bot', { id: targetBot.id, browserGrants: nextGrants }) + if (res.ok) { + setSite('') + } + } + + const removeGrant = async (bot: BotEntry, grantSite: string) => { + const nextGrants = (bot.browserGrants ?? []).filter(g => text(g.site) !== grantSite) + await perform('update-bot', { id: bot.id, browserGrants: nextGrants }) + } + + const actionLabels: Record = { + post: s.bots.browserActPost, + upload: s.bots.browserActUpload, + download: s.bots.browserActDownload, + delete: s.bots.browserActDelete, + } + + const formatUntilLabel = (untilVal: unknown): string => { + if (untilVal === null || untilVal === undefined) return s.bots.browserDurAlways + const ts = Number(untilVal) + if (!Number.isFinite(ts) || ts <= 0) return s.bots.browserDurAlways + const diff = ts - Date.now() + if (diff <= 0) return '已过期' + if (diff <= 3_700_000) return s.bots.browserDurHour + if (diff <= 86_400_000) return s.bots.browserDurToday + return s.bots.browserDurWeek + } + + return ( + + + Bot 可以自行打开网页、阅读内容和填写表单。发布、上传、下载和删除需要你事先允许;涉及付款的操作始终交给你本人处理。 + + + + {rows.length === 0 ? ( + + 还没有预授权的操作。 + + ) : ( + rows.map((row, idx) => { + const siteText = text(row.grant.site) + const acts = Array.isArray(row.grant.actions) ? row.grant.actions.map(a => actionLabels[String(a)] ?? String(a)) : [] + const untilText = formatUntilLabel(row.grant.until) + return ( + + {idx > 0 && } + + {!fixedBot && } + + + {!fixedBot ? `${row.bot.name} · ` : ''} + {siteText === '*' || !siteText ? s.bots.browserAllSites : siteText} + + + {[acts.join('、'), untilText].filter(Boolean).join(' · ')} + + + void removeGrant(row.bot, siteText)} hitSlop={8} style={styles.iconHit}> + + + + + ) + }) + )} + + + + 允许操作 + + {!fixedBot && targetBot && ( + + + Bot + setBotPickerOpen((v: boolean) => !v)} + style={[ + styles.input, + { + flex: 1, + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingVertical: 8, + }, + ]} + > + + + {targetBot.name} + + + + + {botPickerOpen && bots.length > 1 && ( + + {bots.map(b => { + const on = b.id === targetBot.id + return ( + { + setPickedBotId(b.id) + setBotPickerOpen(false) + }} + style={[styles.choicePill, on && styles.choicePillActive]} + > + {b.name} + + ) + })} + + )} + + )} + + + 网站 + + + + + 动作 + + {(['post', 'upload', 'download', 'delete'] as const).map(act => { + const on = actions.includes(act) + return ( + toggleAction(act)} + style={[styles.choicePill, on && styles.choicePillActive]} + > + {actionLabels[act]} + + ) + })} + + + + + 时限 + + {([ + ['hour', s.bots.browserDurHour], + ['today', s.bots.browserDurToday], + ['week', s.bots.browserDurWeek], + ['always', s.bots.browserDurAlways], + ] as const).map(([id, label]) => { + const on = duration === id + return ( + setDuration(id)} + style={[styles.choicePill, on && styles.choicePillActive]} + > + {label} + + ) + })} + + + + +