import { useEffect, useRef, useState, type ReactNode } from 'react'
import {
Keyboard,
Modal,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from 'react-native'
import {
ArrowDown,
ArrowUp,
Check,
CirclePlus,
Code2,
Eye,
EyeOff,
Folder,
FolderOpen,
Pencil,
Plus,
Sparkles,
Star,
Trash2,
X,
type LucideIcon,
} from 'lucide-react-native'
import { deviceVersionSubtitle, platformIcon } from '../lib/device-display'
import { useAppStore } from '../state/store'
import type { AgentBackend, DirectoryListing, WorkspaceView } from '../types'
import { BlurHeaderFrame, Button, GroupCard, GroupRow, IconButton, Screen, SectionTitle, TopBar } from '../ui/components'
import { radius, spacing, type } from '../ui/theme'
import { useTheme, type ThemeColors } from '../ui/theme-context'
import { useResponsiveLayout } from '../ui/responsive'
import { useThemedStyles } from '../ui/use-themed-styles'
import { SheetModal } from '../ui/sheet'
import { strings } from '../locales/i18n'
const DIRECTORY_SHEET_COMPACT_RATIO = 0.92
const DIRECTORY_SHEET_RATIO = 0.75
export function WorkspaceActionsModal({
target,
favorited = false,
canMoveUp,
canMoveDown,
busy,
onClose,
onNewSession,
onToggleFavorite,
onRename,
onMoveUp,
onMoveDown,
onDelete,
}: {
target?: WorkspaceView
favorited?: boolean
canMoveUp: boolean
canMoveDown: boolean
busy: boolean
onClose: () => void
onNewSession?: () => void
onToggleFavorite?: () => void
onRename: () => void
onMoveUp: () => void
onMoveDown: () => void
onDelete: () => void
}) {
const styles = useThemedStyles(createStyles)
const { sheetMaxHeight } = useResponsiveLayout()
const canManage = target !== undefined && (target.backend === undefined || target.backend === 'harness')
return (
{strings.workspaces.options}
{target !== undefined && {target.title}}
{target !== undefined && Boolean(target.path) && (
{target.path}
)}
{target !== undefined && (
{onNewSession !== undefined && (
)}
{onToggleFavorite !== undefined && (
)}
{canManage && (
)}
{canManage && (
)}
{canManage && (
)}
)}
{canManage && (
)}
)
}
export function CreateWorkspaceModal({
visible,
codexAvailable,
cursorAvailable,
antigravityAvailable,
piAvailable,
opencodeAvailable,
claudeAvailable,
hermesAvailable,
initialBackend,
busy,
onClose,
onCreate,
onCreated,
}: {
visible: boolean
codexAvailable: boolean
cursorAvailable: boolean
antigravityAvailable: boolean
piAvailable: boolean
opencodeAvailable: boolean
claudeAvailable: boolean
hermesAvailable: boolean
initialBackend: AgentBackend
busy: boolean
onClose: () => void
onCreate: (path: string, backend: AgentBackend) => Promise
onCreated: (workspace: WorkspaceView) => void
}) {
useAppStore(state => state.language)
const selectedDevice = useAppStore(state => state.selectedDevice)
const connectionPhase = useAppStore(state => state.connection.phase)
const [backend, setBackend] = useState('harness')
const [path, setPath] = useState('')
const [browseOpen, setBrowseOpen] = useState(false)
const { colors } = useTheme()
const styles = useThemedStyles(createStyles)
const { contentMaxWidth, landscape } = useResponsiveLayout()
const sheetScrollRef = useRef(null)
const requestEpochRef = useRef(0)
useEffect(() => {
requestEpochRef.current += 1
if (visible) sheetScrollRef.current?.scrollTo({ y: 0, animated: false })
}, [visible, selectedDevice?.deviceId])
useEffect(() => {
if (!visible) return
if (initialBackend === 'codex' && codexAvailable) setBackend('codex')
else if (initialBackend === 'cursor' && cursorAvailable) setBackend('cursor')
else if (initialBackend === 'pi' && piAvailable) setBackend('pi')
else if (initialBackend === 'antigravity' && antigravityAvailable) setBackend('antigravity')
else if (initialBackend === 'opencode' && opencodeAvailable) setBackend('opencode')
else if (initialBackend === 'claude' && claudeAvailable) setBackend('claude')
else if (initialBackend === 'hermes' && hermesAvailable) setBackend('hermes')
else setBackend('harness')
}, [codexAvailable, cursorAvailable, antigravityAvailable, piAvailable, opencodeAvailable, claudeAvailable, hermesAvailable, initialBackend, visible])
const dismissModal = () => {
requestEpochRef.current += 1
setBrowseOpen(false)
onClose()
}
const create = async () => {
const trimmed = path.trim()
if (trimmed.length === 0) return
const epoch = requestEpochRef.current
const targetDeviceId = selectedDevice?.deviceId
const workspace = await onCreate(trimmed, backend)
if (
workspace === undefined
|| requestEpochRef.current !== epoch
|| useAppStore.getState().selectedDevice?.deviceId !== targetDeviceId
) {
return
}
setPath('')
dismissModal()
onCreated(workspace)
}
const openBrowser = () => {
Keyboard.dismiss()
setBrowseOpen(true)
}
const backendItems: Array<{ value: AgentBackend; label: string; detail: string; icon: LucideIcon }> = [
{ value: 'harness', label: strings.workspaces.dsh, detail: strings.devices.harness, icon: FolderOpen },
...(codexAvailable ? [{ value: 'codex' as const, label: strings.workspaces.codex, detail: 'OpenAI Codex', icon: Code2 }] : []),
...(claudeAvailable ? [{ value: 'claude' as const, label: strings.workspaces.claude, detail: 'Anthropic Claude', icon: Sparkles }] : []),
...(hermesAvailable ? [{ value: 'hermes' as const, label: strings.workspaces.hermes, detail: 'Nous Research Hermes', icon: Sparkles }] : []),
...(cursorAvailable ? [{ value: 'cursor' as const, label: strings.workspaces.cursor, detail: 'Cursor ACP', icon: Sparkles }] : []),
...(antigravityAvailable ? [{ value: 'antigravity' as const, label: strings.workspaces.antigravity, detail: 'Antigravity ACP', icon: Sparkles }] : []),
...(opencodeAvailable ? [{ value: 'opencode' as const, label: strings.workspaces.opencode, detail: 'OpenCode ACP', icon: Sparkles }] : []),
...(piAvailable ? [{ value: 'pi' as const, label: strings.workspaces.pi, detail: 'Pi ACP', icon: Sparkles }] : []),
]
const directoryHint = backend === 'codex'
? strings.workspaces.codexDirectoryHint
: backend === 'cursor'
? strings.workspaces.cursorDirectoryHint
: backend === 'pi'
? strings.workspaces.piDirectoryHint
: backend === 'antigravity'
? strings.workspaces.antigravityDirectoryHint
: backend === 'opencode'
? strings.workspaces.opencodeDirectoryHint
: backend === 'claude'
? strings.workspaces.claudeDirectoryHint
: backend === 'hermes'
? strings.workspaces.hermesDirectoryHint
: strings.workspaces.directoryHint
const HostIcon = selectedDevice ? platformIcon(selectedDevice.platform) : FolderOpen
const hostOnline = connectionPhase === 'connected'
const hostConnecting = connectionPhase === 'connecting' || connectionPhase === 'reconnecting'
const hostStatusDot = hostOnline ? colors.success : hostConnecting ? colors.warning : colors.disabled
const hostStatusLabel = hostOnline ? strings.status.online : hostConnecting ? strings.status.waiting : strings.status.offline
return (
}
>
{selectedDevice !== undefined && (
<>
{strings.sessionInfo.host}
{hostStatusLabel}
}
/>
>
)}
{strings.workspaces.deviceDirectory}
{path.length > 0 && !busy && (
setPath('')}
style={({ pressed }) => [styles.clearSearch, pressed && styles.workspaceRowPressed]}
>
)}
{directoryHint}
{strings.workspaces.type}
{backendItems.map((option, index) => {
const chosen = backend === option.value
return (
setBackend(option.value)}
accessory={
{chosen ? : null}
}
/>
)
})}
setBrowseOpen(false)}
onChoose={picked => { setPath(picked); setBrowseOpen(false) }}
/>
)
}
export function RenameWorkspaceModal({
target,
busy,
onClose,
onRename,
}: {
target?: WorkspaceView
busy: boolean
onClose: () => void
onRename: (workspaceId: string, title: string) => Promise
}) {
const [title, setTitle] = useState('')
const { colors } = useTheme()
const styles = useThemedStyles(createStyles)
const { sheetMaxHeight } = useResponsiveLayout()
useEffect(() => {
if (target !== undefined) setTitle(target.title)
}, [target])
const rename = async () => {
const trimmed = title.trim()
if (target === undefined || trimmed.length === 0) return
if (await onRename(target.workspaceId, trimmed)) onClose()
}
return (
{strings.workspaces.renameTitle}
)
}
export function DirectoryBrowserModal({
visible,
onClose,
onChoose,
}: {
visible: boolean
onClose: () => void
onChoose: (path: string) => void
}) {
const listDirectory = useAppStore(state => state.hostListDirectory)
const [listing, setListing] = useState(undefined)
const [showHidden, setShowHidden] = useState(false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(undefined)
const { colors } = useTheme()
const styles = useThemedStyles(createStyles)
const { height: windowHeight, landscape, compactHeight } = useResponsiveLayout()
const browserSheetHeight = Math.round(windowHeight * (landscape || compactHeight ? DIRECTORY_SHEET_COMPACT_RATIO : DIRECTORY_SHEET_RATIO))
useEffect(() => {
if (!visible) return
let cancelled = false
setLoading(true)
setError(undefined)
void listDirectory(undefined).then(result => {
if (cancelled) return
if (result === undefined) { setLoading(false); return }
setListing(result)
setLoading(false)
})
return () => { cancelled = true }
}, [visible, listDirectory])
const open = async (path: string) => {
setLoading(true)
setError(undefined)
const result = await listDirectory(path)
if (result !== undefined) setListing(result)
setLoading(false)
}
const entries = listing === undefined ? [] : listing.entries.filter(entry => showHidden || !entry.hidden)
return (
{strings.workspaces.chooseFolder}
{listing?.path ?? strings.workspaces.loading}
{(listing?.crumbs ?? []).map((crumb, index, all) => (
void open(crumb.path)}>
{crumb.name}{index < all.length - 1 ? ' / ' : ''}
))}
{error !== undefined && {error}}
{loading
? {strings.workspaces.loadingDirectory}
: entries.length === 0
? {strings.workspaces.noFolders}
: (
{entries.map((entry, index) => (
void open(entry.path)}
/>
))}
)}
)
}
function createStyles(colors: ThemeColors) {
return StyleSheet.create({
flex: { flex: 1, backgroundColor: colors.background },
backdrop: { flex: 1, backgroundColor: colors.modalBackdrop, justifyContent: 'flex-end' },
grabber: { width: 36, height: 4, borderRadius: 2, backgroundColor: colors.subtle, opacity: 0.45, alignSelf: 'center', marginBottom: spacing.xxs },
createContentColumn: { width: '100%', alignSelf: 'center' },
createStatusInline: { flexDirection: 'row', alignItems: 'center', gap: 5 },
createStatusDot: { width: 7, height: 7, borderRadius: 4 },
createStatusText: { ...type.caption, color: colors.muted },
createPathRow: { minHeight: 58, paddingLeft: spacing.md, flexDirection: 'row', alignItems: 'center' },
createPathIcon: { width: 28, marginRight: spacing.sm, alignItems: 'center', justifyContent: 'center' },
createPathBody: { flex: 1, minWidth: 0, minHeight: 58, paddingRight: spacing.sm, flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
createPathInput: { flex: 1, ...type.body, fontSize: 16, color: colors.ink, paddingVertical: spacing.sm },
clearSearch: { padding: spacing.xxs, alignItems: 'center', justifyContent: 'center' },
createSectionNote: { ...type.caption, fontSize: 13, lineHeight: 18, color: colors.muted, marginTop: spacing.xs, paddingHorizontal: spacing.md },
createCheckSlot: { width: 20, alignItems: 'center', justifyContent: 'center' },
createPrimaryArea: { marginTop: spacing.xl },
sheet: {
backgroundColor: colors.background,
borderTopLeftRadius: radius.xxl,
borderTopRightRadius: radius.xxl,
paddingHorizontal: spacing.lg,
paddingTop: spacing.sm,
paddingBottom: spacing.xxl,
gap: spacing.md,
},
sheetScroll: { flexGrow: 0, flexShrink: 1 },
sheetScrollContent: { gap: spacing.md },
browserSheet: {
backgroundColor: colors.background,
borderTopLeftRadius: radius.xxl,
borderTopRightRadius: radius.xxl,
paddingHorizontal: spacing.lg,
paddingTop: spacing.sm,
paddingBottom: spacing.lg,
},
sheetHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
sheetTitle: { ...type.heading, fontSize: 18, fontWeight: '700', color: colors.ink },
workspaceActionHeading: { flex: 1, minWidth: 0 },
workspaceActionName: { ...type.smallStrong, color: colors.muted, marginTop: 2 },
workspaceActionPath: { ...type.caption, color: colors.muted, fontFamily: 'monospace', paddingHorizontal: spacing.xxs },
workspaceRowPressed: { opacity: 0.7 },
disabled: { opacity: 0.55 },
titleInput: {
...type.body,
color: colors.ink,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.border,
borderRadius: radius.lg,
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
},
browserPathCard: { marginTop: spacing.xs },
browserPath: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },
browserPathText: { flex: 1, ...type.small, color: colors.ink, fontFamily: 'monospace' },
crumbRow: { flexDirection: 'row', flexWrap: 'wrap', paddingVertical: spacing.xs, paddingHorizontal: spacing.xxs },
crumbText: { ...type.small, color: colors.primary },
browserList: { flex: 1, marginTop: spacing.xs },
loadingText: { ...type.small, color: colors.muted, textAlign: 'center', marginTop: spacing.lg },
emptyText: { ...type.small, color: colors.muted, textAlign: 'center', marginTop: spacing.lg },
errorText: { ...type.small, color: colors.danger },
browserFooter: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing.sm, marginTop: spacing.md },
})
}