Feat/mobile session actions (#206)

* feat: improve mobile session actions

* feat(frontend): improve mobile session actions

Replace inline file search in MoreDrawer with FileBrowserSheet for
mention-file interactions. Add activePromptFileBasePath state to track
workspace context, normalize file paths on selection, and improve
command sorting with relevance ranking (exact > prefix > partial match).

* refactor(frontend): remove dead state and deduplicate event reconciliation

Remove unused activePromptDirectory from uiStateStore and its writers in
SessionDetail and PromptInput. Consolidate duplicated permission and
question reconciliation helpers in EventContext behind a generic
session-scoped helper.

---------

Co-authored-by: Chris Scott <>
This commit is contained in:
Chris ScottandChris Scott authored and GitHub committed 2026-04-28 16:20:54 -04:00
1 parent 389120559f
commit 04400c91cc
17 files changed
+709 -132

No files matched your search

+23 -1
View File
@@ -20,7 +20,8 @@ import { MobileTabBar } from '@/components/navigation/MobileTabBar'
import { MobileSheetHost } from '@/components/navigation/MobileSheetHost'
import { DesktopSidebar } from '@/components/navigation/DesktopSidebar'
import { useTheme } from './hooks/useTheme'
import { useSwipeBack } from './hooks/useMobile'
import { useRightEdgeSwipe, useSwipeBack } from './hooks/useMobile'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { TTSProvider } from './contexts/TTSContext'
import { AuthProvider } from './contexts/AuthContext'
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
@@ -76,6 +77,7 @@ function AppShell() {
const navigate = useNavigate()
const location = useLocation()
const rootRef = useRef<HTMLDivElement>(null)
const { open: openMobileSheet, openSheet } = useMobileTabBar()
useTheme()
const getSwipeBackTarget = () => {
@@ -123,6 +125,19 @@ function AppShell() {
}
)
const canOpenMoreWithSwipe = () => {
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(location.pathname) && !openSheet
}
const { bind: bindMoreSwipe } = useRightEdgeSwipe(
() => openMobileSheet('more'),
{
enabled: canOpenMoreWithSwipe(),
edgeWidth: 32,
threshold: 72,
}
)
useEffect(() => {
const cleanup = bindRouteSwipe(rootRef.current)
return () => {
@@ -130,6 +145,13 @@ function AppShell() {
}
}, [bindRouteSwipe])
useEffect(() => {
const cleanup = bindMoreSwipe(rootRef.current)
return () => {
cleanup?.()
}
}, [bindMoreSwipe])
useEffect(() => {
const channel = new BroadcastChannel('notification-click')
channel.onmessage = (event: MessageEvent) => {
@@ -9,6 +9,7 @@ import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from '@/lib/utils'
import { useSwipeBack } from '@/hooks/useMobile'
import { downloadDirectoryAsZip } from '@/api/files'
import { downloadRepo } from '@/api/repos'
import type { FileInfo } from '@/types/files'
import {
DropdownMenu,
DropdownMenuContent,
@@ -24,9 +25,10 @@ interface FileBrowserSheetProps {
repoId?: number
initialSelectedFile?: string
allowNavigateAboveBase?: boolean
onFileSelect?: (file: FileInfo) => void
}
export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, repoId, initialSelectedFile, allowNavigateAboveBase = false }: FileBrowserSheetProps) {
export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, repoId, initialSelectedFile, allowNavigateAboveBase = false, onFileSelect }: FileBrowserSheetProps) {
const normalizedBasePath = basePath || '.'
const [isEditing, setIsEditing] = useState(false)
const [displayPath, setDisplayPath] = useState<string>('/')
@@ -197,6 +199,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
basePath={normalizedBasePath}
embedded={true}
initialSelectedFile={initialSelectedFile}
onFileSelect={onFileSelect}
onDirectoryLoad={handleDirectoryLoad}
onPreviewStateChange={setIsPreviewOpen}
allowNavigateAboveBase={allowNavigateAboveBase}
@@ -676,4 +676,39 @@ describe('MessagePart', () => {
expect(screen.getByText('Reasoning')).toBeInTheDocument()
})
})
describe('synthetic text parts', () => {
const createTextPart = (overrides: Partial<MessagePartType>): MessagePartType => ({
type: 'text',
text: 'hello',
sessionID: 'test-session',
messageID: 'm1',
...overrides,
} as MessagePartType)
it('does not render synthetic text parts', () => {
setup()
const part = createTextPart({
text: 'Called the Read tool with the following input: {"filePath":"/x/README.md"}',
synthetic: true,
} as Partial<MessagePartType>)
const { container } = render(
<MessagePart part={part} role="user" allParts={[part]} partIndex={0} />,
)
expect(container.firstChild).toBeNull()
})
it('renders non-synthetic text parts normally', () => {
setup()
const part = createTextPart({ text: 'Just a normal user message' })
render(
<MessagePart part={part} role="user" allParts={[part]} partIndex={0} />,
)
expect(screen.getByText('Just a normal user message')).toBeInTheDocument()
})
})
})
@@ -111,6 +111,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
switch (part.type) {
case 'text':
if (part.synthetic) return null
if (role === 'user' && allParts && partIndex !== undefined) {
const nextPart = allParts[partIndex + 1]
if (nextPart && nextPart.type === 'file') {
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
@@ -189,6 +190,8 @@ describe('PromptInput STT Gesture Tests', () => {
mocks.useAgents.mockReturnValue({ data: [] })
mocks.useUserBash.mockReturnValue({ addUserBashCommand: vi.fn() })
mocks.useSessionAgentStore.mockReturnValue({ setAgent: mockSetAgent })
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
const renderComponent = (sttOverrides: Partial<MockSTTReturn> = {}) => {
@@ -228,6 +231,37 @@ describe('PromptInput STT Gesture Tests', () => {
}
describe('quick tap behavior', () => {
it('inserts a command selected from the mobile drawer', async () => {
renderComponent()
act(() => {
useUIState.getState().selectPromptCommand({
name: 'help',
description: 'Show help',
template: '',
agent: '',
model: '',
hints: [],
})
})
await waitFor(() => {
expect(screen.getByPlaceholderText('Send a message...')).toHaveValue('/help ')
})
})
it('inserts a file selected from the mobile drawer', async () => {
renderComponent()
act(() => {
useUIState.getState().selectPromptFile('src/App.tsx')
})
await waitFor(() => {
expect(screen.getByPlaceholderText('Send a message...')).toHaveValue('@App.tsx ')
})
})
it('quick tap starts recording through click only', async () => {
mockStartRecording.mockResolvedValue(true)
+68 -46
View File
@@ -11,6 +11,7 @@ import { useSTT } from '@/hooks/useSTT'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useUIState } from '@/stores/uiStateStore'
import { useMobile } from '@/hooks/useMobile'
import { usePermissions } from '@/contexts/EventContext'
@@ -122,6 +123,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const voiceHoldActivatedRef = useRef(false)
const voiceStartRequestRef = useRef(0)
const handleSubmitRef = useRef<() => void>(() => {})
const pendingPromptCommand = useUIState((state) => state.pendingPromptCommand)
const pendingPromptFile = useUIState((state) => state.pendingPromptFile)
const clearPendingPromptCommand = useUIState((state) => state.clearPendingPromptCommand)
const clearPendingPromptFile = useUIState((state) => state.clearPendingPromptFile)
const {
isRecording,
@@ -323,7 +328,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
abortSession.mutate(sessionID)
}
const handleCommandSelect = async (command: CommandType) => {
const handleCommandSelect = useCallback(async (command: CommandType) => {
if (!textareaRef.current) return
setShowSuggestions(false)
@@ -348,25 +353,68 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const beforeCommand = prompt.slice(0, commandMatch.index)
const afterCommand = prompt.slice(cursorPosition)
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
}
const beforeCommand = commandMatch ? prompt.slice(0, commandMatch.index) : ''
const afterCommand = commandMatch ? prompt.slice(cursorPosition) : ''
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
}
}
}, [prompt])
useEffect(() => {
if (!pendingPromptCommand) return
handleCommandSelect(pendingPromptCommand.command)
clearPendingPromptCommand()
}, [pendingPromptCommand, handleCommandSelect, clearPendingPromptCommand])
const insertFileMention = useCallback((filePath: string, range: { start: number, end: number } | null = mentionRange) => {
const filename = getFilename(filePath)
const beforeMention = range ? prompt.slice(0, range.start) : `${prompt}${prompt.trim() ? ' ' : ''}`
const afterMention = range ? prompt.slice(range.end) : ''
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = filePath.startsWith('/')
? filePath
: directory
? `${directory}/${filePath}`
: filePath
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
})
return next
})
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
}, [directory, mentionRange, prompt])
useEffect(() => {
if (!pendingPromptFile) return
insertFileMention(pendingPromptFile.path, null)
clearPendingPromptFile()
}, [pendingPromptFile, insertFileMention, clearPendingPromptFile])
const handleMentionSelect = (item: MentionItem) => {
if (!mentionRange || !textareaRef.current) return
@@ -387,33 +435,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
}, 0)
} else {
const filename = getFilename(item.value)
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = item.value.startsWith('/')
? item.value
: directory
? `${directory}/${item.value}`
: item.value
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
})
return next
})
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
insertFileMention(item.value, mentionRange)
}
setShowMentionSuggestions(false)
@@ -1,15 +1,27 @@
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { beforeEach, describe, it, expect, vi } from 'vitest'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { MoreDrawer } from './MoreDrawer'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useCommands } from '@/hooks/useCommands'
import { useUIState } from '@/stores/uiStateStore'
vi.mock('@/hooks/useAuth')
vi.mock('@/hooks/useServerHealth')
vi.mock('@/hooks/useCommands')
vi.mock('@/hooks/useMemoryPluginStatus', () => ({
useMemoryPluginStatus: () => ({ memoryPluginEnabled: false }),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: ({ isOpen, basePath, onFileSelect }: { isOpen: boolean; basePath: string; onFileSelect: (file: { path: string }) => void }) => (
isOpen ? (
<div data-testid="mention-file-browser" data-base-path={basePath}>
<button type="button" onClick={() => onFileSelect({ path: 'repo/src/App.tsx' })}>App.tsx</button>
</div>
) : null
),
}))
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom')
return {
@@ -64,6 +76,24 @@ describe('MoreDrawer', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(useNavigate).mockReturnValue(vi.fn())
vi.mocked(useCommands).mockReturnValue({
commands: [],
loading: false,
error: null,
filterCommands: vi.fn().mockReturnValue([
{
name: 'help',
description: 'Show help',
template: '',
agent: '',
model: '',
hints: [],
},
]),
})
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
useUIState.getState().setActivePromptFileBasePath(null)
})
it('renders Settings and Logout menu items', () => {
@@ -74,7 +104,6 @@ describe('MoreDrawer', () => {
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
expect(screen.getByText('OpenCode')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
})
@@ -131,8 +160,7 @@ describe('MoreDrawer', () => {
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
expect(screen.getByText('OpenCode v1.4.11')).toBeInTheDocument()
expect(screen.getByText('Manager v0.9.16')).toBeInTheDocument()
expect(screen.getByText('v1.4.11 · Manager v0.9.16')).toBeInTheDocument()
})
it('shows unhealthy server status when server is unhealthy', () => {
@@ -143,7 +171,7 @@ describe('MoreDrawer', () => {
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
expect(screen.getByText('OpenCode v1.4.11')).toBeInTheDocument()
expect(screen.getByText('v1.4.11')).toBeInTheDocument()
})
it('shows fallback text when version is not available', () => {
@@ -154,7 +182,42 @@ describe('MoreDrawer', () => {
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
expect(screen.getByText('OpenCode')).toBeInTheDocument()
expect(screen.queryByText('OpenCode')).not.toBeInTheDocument()
})
it('shows session commands and selects a command', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter initialEntries={['/repos/1/sessions/session-1']}>{children}</MemoryRouter> },
)
fireEvent.click(screen.getByText('Commands'))
expect(screen.queryByText('/help')).not.toBeInTheDocument()
fireEvent.click(screen.getByText('help'))
expect(useUIState.getState().pendingPromptCommand?.command.name).toBe('help')
expect(handleClose).toHaveBeenCalled()
})
it('opens file browser and selects a file mention', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
useUIState.getState().setActivePromptFileBasePath('repo')
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter initialEntries={['/repos/1/sessions/session-1']}>{children}</MemoryRouter> },
)
fireEvent.click(screen.getByText('Mention File'))
expect(screen.getByTestId('mention-file-browser')).toHaveAttribute('data-base-path', 'repo')
fireEvent.click(screen.getByText('App.tsx'))
expect(useUIState.getState().pendingPromptFile?.path).toBe('src/App.tsx')
expect(handleClose).toHaveBeenCalled()
})
})
+109 -11
View File
@@ -1,9 +1,18 @@
import { useNavigate, useLocation } from 'react-router-dom'
import { useState } from 'react'
import { ChevronDown, ChevronRight, Command as CommandIcon, FileText, X } from 'lucide-react'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useMemoryPluginStatus } from '@/hooks/useMemoryPluginStatus'
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from '@/components/ui/side-drawer'
import { useCommands } from '@/hooks/useCommands'
import { useUIState } from '@/stores/uiStateStore'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { buildMoreItems } from './moreDrawerItems'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
interface MoreDrawerProps {
isOpen: boolean
@@ -13,9 +22,16 @@ interface MoreDrawerProps {
export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const navigate = useNavigate()
const location = useLocation()
const [commandsOpen, setCommandsOpen] = useState(false)
const [mentionFileBrowserOpen, setMentionFileBrowserOpen] = useState(false)
const { logout } = useAuth()
const { data: health } = useServerHealth()
const { memoryPluginEnabled } = useMemoryPluginStatus()
const isSessionDetail = /^\/repos\/\d+\/sessions\/[^/]+$/.test(location.pathname)
const { filterCommands } = useCommands(isSessionDetail ? OPENCODE_API_ENDPOINT : null)
const activePromptFileBasePath = useUIState((state) => state.activePromptFileBasePath)
const selectPromptCommand = useUIState((state) => state.selectPromptCommand)
const selectPromptFile = useUIState((state) => state.selectPromptFile)
const handleSettingsClick = () => {
const newParams = new URLSearchParams(location.search)
@@ -44,23 +60,99 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
}
}
const handleCommandClick = (command: CommandType) => {
selectPromptCommand(command)
onClose()
}
const getPromptFilePath = (path: string) => {
if (!activePromptFileBasePath) return path
const normalizedPath = path.replace(/^\.\//, '')
const normalizedBasePath = activePromptFileBasePath.replace(/^\.\//, '').replace(/\/+$/, '')
const basePrefix = `${normalizedBasePath}/`
return normalizedPath.startsWith(basePrefix)
? normalizedPath.slice(basePrefix.length)
: normalizedPath
}
const handleFileClick = (path: string) => {
selectPromptFile(getPromptFilePath(path))
setMentionFileBrowserOpen(false)
onClose()
}
const items = buildMoreItems(location.pathname, { memoryPluginEnabled })
const commands = filterCommands('')
const opencodeVersion = health?.opencodeVersion
const managerVersion = health?.opencodeManagerVersion
const versionLabel = [
opencodeVersion ? `v${opencodeVersion}` : null,
managerVersion ? `Manager v${managerVersion}` : null,
].filter(Boolean).join(' · ')
return (
<SideDrawer isOpen={isOpen} onClose={onClose} side="right" ariaLabel="More">
<SideDrawerHeader
title={opencodeVersion ? `OpenCode v${opencodeVersion}` : 'OpenCode'}
onClose={onClose}
meta={
managerVersion ? (
<div className="text-xs text-muted-foreground">Manager v{managerVersion}</div>
) : null
}
/>
<SideDrawer isOpen={isOpen} onClose={onClose} side="right" ariaLabel="More" widthClass="w-screen sm:w-[min(90vw,420px)]">
<div className="flex flex-shrink-0 items-center justify-between gap-3 border-b border-border bg-background px-4 py-1.5">
{versionLabel && (
<span className="truncate text-xs leading-tight text-muted-foreground">{versionLabel}</span>
)}
<button
type="button"
onClick={onClose}
className="shrink-0 rounded-sm p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Close"
>
<X className="h-5 w-5" />
</button>
</div>
<SideDrawerContent className="flex flex-col gap-1">
{isSessionDetail && (
<div className="flex flex-col gap-1">
<button
type="button"
onClick={() => setCommandsOpen((open) => !open)}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
aria-expanded={commandsOpen}
>
<CommandIcon className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Commands</span>
{commandsOpen ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
)}
</button>
{commandsOpen && (
<div className="-mx-4 max-h-64 overflow-y-auto border-y border-border bg-muted/30 p-1 sm:mx-0 sm:rounded-lg sm:border">
{commands.map((command) => (
<button
key={command.name}
type="button"
onClick={() => handleCommandClick(command)}
className="flex w-full min-w-0 items-start gap-3 rounded-md px-3 py-2 text-left transition-colors hover:bg-accent"
>
<span className="font-mono text-sm font-medium text-blue-600 dark:text-blue-400">{command.name}</span>
{command.description && (
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{command.description}</span>
)}
</button>
))}
</div>
)}
<button
type="button"
onClick={() => setMentionFileBrowserOpen(true)}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
>
<FileText className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Mention File</span>
<ChevronRight className="w-4 h-4 text-muted-foreground" />
</button>
</div>
)}
{items.map((item) => (
<button
key={item.key}
@@ -81,6 +173,12 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
</button>
))}
</SideDrawerContent>
<FileBrowserSheet
isOpen={mentionFileBrowserOpen}
onClose={() => setMentionFileBrowserOpen(false)}
basePath={activePromptFileBasePath ?? ''}
onFileSelect={(file) => handleFileClick(file.path)}
/>
</SideDrawer>
)
}
@@ -164,4 +164,46 @@ describe('RepoQuickSwitchSheet', () => {
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/assistant')
expect(handleClose).toHaveBeenCalled()
})
it('navigates from assistant to repo detail when clicking active repo', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
id: 1,
repoUrl: 'https://github.com/test/repo1.git',
localPath: '/path/to/repo1',
sourcePath: null,
currentBranch: 'main',
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
])
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1/assistant?mobileTab=repos']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
})
fireEvent.click(screen.getByText('repo1'))
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1')
expect(handleClose).not.toHaveBeenCalled()
})
})
@@ -39,14 +39,20 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
}, [repos, searchQuery])
const handleClick = (id: number) => {
if (id === activeRepoId) {
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
if (pendingAction === 'assistant') {
navigate(`/repos/${id}/assistant`)
onClose()
return
}
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
if (pendingAction === 'assistant') {
navigate(`/repos/${id}/assistant`)
const isAssistantRoute = location.pathname === `/repos/${id}/assistant`
if (id === activeRepoId) {
if (isAssistantRoute) {
navigate(`/repos/${id}`, { replace: true })
return
}
onClose()
return
}
+34 -53
View File
@@ -13,32 +13,43 @@ import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessi
type PermissionsBySession = Record<string, PermissionRequest[]>
type QuestionsBySession = Record<string, QuestionRequest[]>
function groupPermissionsBySession(permissions: PermissionRequest[]): PermissionsBySession {
return permissions.reduce<PermissionsBySession>((grouped, permission) => {
const existing = grouped[permission.sessionID] ?? []
type SessionScopedItem = { id: string; sessionID: string }
function groupBySession<T extends SessionScopedItem>(items: T[]): Record<string, T[]> {
return items.reduce<Record<string, T[]>>((grouped, item) => {
const existing = grouped[item.sessionID] ?? []
return {
...grouped,
[permission.sessionID]: [...existing, permission],
[item.sessionID]: [...existing, item],
}
}, {})
}
function groupQuestionsBySession(questions: QuestionRequest[]): QuestionsBySession {
return questions.reduce<QuestionsBySession>((grouped, question) => {
const existing = grouped[question.sessionID] ?? []
return {
...grouped,
[question.sessionID]: [...existing, question],
function sortById<T extends SessionScopedItem>(items: T[]): T[] {
return [...items].sort((a, b) => a.id.localeCompare(b.id))
}
function reconcileBySessionForDirectory<T extends SessionScopedItem>(
prev: Record<string, T[]>,
directory: string,
items: T[],
sessionDirectories: Map<string, string>,
): Record<string, T[]> {
const grouped = groupBySession(items)
const next = { ...prev }
for (const sessionID of Object.keys(prev)) {
if (grouped[sessionID]) continue
if (sessionDirectories.get(sessionID) === directory) {
delete next[sessionID]
}
}, {})
}
}
function sortQuestionsById(questions: QuestionRequest[]): QuestionRequest[] {
return [...questions].sort((a, b) => a.id.localeCompare(b.id))
}
for (const [sessionID, sessionItems] of Object.entries(grouped)) {
next[sessionID] = sortById(sessionItems)
}
function sortPermissionsById(permissions: PermissionRequest[]): PermissionRequest[] {
return [...permissions].sort((a, b) => a.id.localeCompare(b.id))
return next
}
function optimisticallyErrorToolPart(
@@ -275,53 +286,23 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [])
const reconcilePermissionsForDirectory = useCallback((directory: string, permissions: PermissionRequest[]) => {
const grouped = groupPermissionsBySession(permissions)
permissions.forEach(permission => {
rememberSessionDirectory(permission.sessionID, directory)
})
setPermissionsBySession(prev => {
const next = { ...prev }
for (const sessionID of Object.keys(prev)) {
if (grouped[sessionID]) continue
if (sessionDirectoriesRef.current.get(sessionID) === directory) {
delete next[sessionID]
}
}
for (const [sessionID, sessionPermissions] of Object.entries(grouped)) {
next[sessionID] = sortPermissionsById(sessionPermissions)
}
return next
})
setPermissionsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, permissions, sessionDirectoriesRef.current),
)
}, [rememberSessionDirectory])
const reconcileQuestionsForDirectory = useCallback((directory: string, questions: QuestionRequest[]) => {
const grouped = groupQuestionsBySession(questions)
questions.forEach(question => {
rememberSessionDirectory(question.sessionID, directory)
})
setQuestionsBySession(prev => {
const next = { ...prev }
for (const sessionID of Object.keys(prev)) {
if (grouped[sessionID]) continue
if (sessionDirectoriesRef.current.get(sessionID) === directory) {
delete next[sessionID]
}
}
for (const [sessionID, sessionQuestions] of Object.entries(grouped)) {
next[sessionID] = sortQuestionsById(sessionQuestions)
}
return next
})
setQuestionsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, questions, sessionDirectoriesRef.current),
)
}, [rememberSessionDirectory])
useEffect(() => {
+58
View File
@@ -0,0 +1,58 @@
import { renderHook, waitFor } from '@testing-library/react'
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { useCommands } from './useCommands'
import { createOpenCodeClient } from '../api/opencode'
vi.mock('../api/opencode', () => ({
createOpenCodeClient: vi.fn(),
}))
describe('useCommands', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns commands in alphabetical order when there is no query', () => {
const { result } = renderHook(() => useCommands(null))
expect(result.current.filterCommands('').map(command => command.name).slice(0, 5)).toEqual([
'clear',
'compact',
'continue',
'details',
'editor',
])
})
it('prioritizes exact and prefix matches before other matches', () => {
const { result } = renderHook(() => useCommands(null))
expect(result.current.filterCommands('co').map(command => command.name)).toEqual([
'compact',
'continue',
])
expect(result.current.filterCommands('do').map(command => command.name)).toEqual([
'redo',
'undo',
])
})
it('sorts loaded custom commands with built-in commands', async () => {
vi.mocked(createOpenCodeClient).mockReturnValue({
listCommands: vi.fn().mockResolvedValue([
{ name: 'zebra', description: '', template: '', agent: '', model: '', hints: [] },
{ name: 'alpha', description: '', template: '', agent: '', model: '', hints: [] },
]),
} as unknown as ReturnType<typeof createOpenCodeClient>)
const { result } = renderHook(() => useCommands('http://localhost:5551'))
await waitFor(() => {
expect(result.current.filterCommands('').map(command => command.name).slice(0, 3)).toEqual([
'alpha',
'clear',
'compact',
])
})
})
})
+22 -7
View File
@@ -4,6 +4,17 @@ import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
function sortCommandsByName(commands: CommandType[]): CommandType[] {
return [...commands].sort((a, b) => a.name.localeCompare(b.name))
}
function rankCommandMatch(command: CommandType, searchTerm: string): number {
const name = command.name.toLowerCase()
if (name === searchTerm) return 0
if (name.startsWith(searchTerm)) return 1
return 2
}
// Built-in OpenCode commands
const BUILTIN_COMMANDS: CommandType[] = [
{
@@ -153,7 +164,7 @@ const BUILTIN_COMMANDS: CommandType[] = [
]
export function useCommands(opcodeUrl: string | null) {
const [commands, setCommands] = useState<CommandType[]>(BUILTIN_COMMANDS)
const [commands, setCommands] = useState<CommandType[]>(sortCommandsByName(BUILTIN_COMMANDS))
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -171,10 +182,10 @@ export function useCommands(opcodeUrl: string | null) {
const uniqueCommands = allCommands.filter((command, index, self) =>
index === self.findIndex((c) => c.name === command.name)
)
setCommands(uniqueCommands)
setCommands(sortCommandsByName(uniqueCommands))
} catch {
setError('Failed to load commands')
setCommands(BUILTIN_COMMANDS)
setCommands(sortCommandsByName(BUILTIN_COMMANDS))
} finally {
setLoading(false)
}
@@ -187,9 +198,13 @@ export function useCommands(opcodeUrl: string | null) {
if (!query.trim()) return commands
const searchTerm = query.toLowerCase()
return commands.filter(command =>
command.name.toLowerCase().includes(searchTerm)
)
return commands
.filter(command => command.name.toLowerCase().includes(searchTerm))
.sort((a, b) => {
const rankDifference = rankCommandMatch(a, searchTerm) - rankCommandMatch(b, searchTerm)
if (rankDifference !== 0) return rankDifference
return a.name.localeCompare(b.name)
})
}
return {
@@ -198,4 +213,4 @@ export function useCommands(opcodeUrl: string | null) {
error,
filterCommands
}
}
}
+74 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useSwipeBack, useSwipeDismiss } from './useMobile'
import { useRightEdgeSwipe, useSwipeBack, useSwipeDismiss } from './useMobile'
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
describe('useSwipeBack', () => {
@@ -181,6 +181,79 @@ describe('useSwipeBack', () => {
})
})
describe('useRightEdgeSwipe', () => {
const mockOnOpen = vi.fn()
beforeEach(() => {
mockOnOpen.mockClear()
Object.defineProperty(window, 'innerWidth', {
writable: true,
configurable: true,
value: 375,
})
})
it('opens when swiping left from the right edge', () => {
const element = document.createElement('div')
document.body.appendChild(element)
const { result } = renderHook(() =>
useRightEdgeSwipe(mockOnOpen, {
enabled: true,
edgeWidth: 32,
threshold: 72,
})
)
const cleanup = result.current.bind(element)
element.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 365, clientY: 100 }] as any,
}))
element.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 285, clientY: 100 }] as any,
}))
element.dispatchEvent(new TouchEvent('touchend', {
changedTouches: [{ clientX: 285, clientY: 100 }] as any,
}))
expect(mockOnOpen).toHaveBeenCalled()
cleanup?.()
document.body.removeChild(element)
})
it('ignores swipes that do not start on the right edge', () => {
const element = document.createElement('div')
document.body.appendChild(element)
const { result } = renderHook(() =>
useRightEdgeSwipe(mockOnOpen, {
enabled: true,
edgeWidth: 32,
threshold: 72,
})
)
const cleanup = result.current.bind(element)
element.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 300, clientY: 100 }] as any,
}))
element.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 220, clientY: 100 }] as any,
}))
element.dispatchEvent(new TouchEvent('touchend', {
changedTouches: [{ clientX: 220, clientY: 100 }] as any,
}))
expect(mockOnOpen).not.toHaveBeenCalled()
cleanup?.()
document.body.removeChild(element)
})
})
describe('useSwipeDismiss', () => {
const mockOnClose = vi.fn()
+96
View File
@@ -38,6 +38,12 @@ export interface UseSwipeDismissOptions {
suspendsRouteSwipe?: boolean
}
export interface UseRightEdgeSwipeOptions {
threshold?: number
edgeWidth?: number
enabled?: boolean
}
function useSwipeHandlers(
onClose: () => void,
options: UseSwipeBackOptions & { direction: 'horizontal' | 'vertical' } = { direction: 'horizontal' }
@@ -376,3 +382,93 @@ export function useSwipeDismiss(
return { bind: wrappedBind, swipeProgress, swipeStyles }
}
export function useRightEdgeSwipe(
onOpen: () => void,
options: UseRightEdgeSwipeOptions = {}
) {
const {
threshold = 80,
edgeWidth = 28,
enabled = true,
} = options
const isMobile = useMobile()
const swipeRef = useRef({
startX: 0,
startY: 0,
currentX: 0,
isSwiping: false,
isEdgeSwipe: false,
})
const handleTouchStart = useCallback((event: TouchEvent) => {
if (!enabled || !isMobile) return
const touch = event.touches[0]
swipeRef.current = {
startX: touch.clientX,
startY: touch.clientY,
currentX: touch.clientX,
isSwiping: false,
isEdgeSwipe: window.innerWidth - touch.clientX <= edgeWidth,
}
}, [edgeWidth, enabled, isMobile])
const handleTouchMove = useCallback((event: TouchEvent) => {
if (!enabled || !isMobile) return
const state = swipeRef.current
if (!state.isEdgeSwipe) return
const touch = event.touches[0]
const deltaX = touch.clientX - state.startX
const deltaY = Math.abs(touch.clientY - state.startY)
if (!state.isSwiping) {
if (deltaX < -10 && Math.abs(deltaX) > deltaY * 2) {
state.isSwiping = true
} else {
return
}
}
event.preventDefault()
state.currentX = touch.clientX
}, [enabled, isMobile])
const handleTouchEnd = useCallback(() => {
if (!enabled || !isMobile) return
const state = swipeRef.current
if (state.isSwiping && state.startX - state.currentX >= threshold) {
onOpen()
}
swipeRef.current = {
startX: 0,
startY: 0,
currentX: 0,
isSwiping: false,
isEdgeSwipe: false,
}
}, [enabled, isMobile, onOpen, threshold])
const bind = useCallback((element: HTMLElement | null) => {
if (!element || !enabled || !isMobile) return undefined
element.addEventListener('touchstart', handleTouchStart, { passive: true })
element.addEventListener('touchmove', handleTouchMove, { passive: false })
element.addEventListener('touchend', handleTouchEnd, { passive: true })
element.addEventListener('touchcancel', handleTouchEnd, { passive: true })
return () => {
element.removeEventListener('touchstart', handleTouchStart)
element.removeEventListener('touchmove', handleTouchMove)
element.removeEventListener('touchend', handleTouchEnd)
element.removeEventListener('touchcancel', handleTouchEnd)
}
}, [enabled, handleTouchEnd, handleTouchMove, handleTouchStart, isMobile])
return { bind }
}
+11 -2
View File
@@ -157,6 +157,7 @@ export function SessionDetail() {
const createSession = useCreateSession(opcodeUrl, repoDirectory);
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const setActivePromptFileBasePath = useUIState((state) => state.setActivePromptFileBasePath);
const { isEnabled: ttsEnabled } = useTTS();
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const { syncForSession: syncPermissionsForSession } = usePermissions();
@@ -169,6 +170,16 @@ export function SessionDetail() {
const latestPlayableAssistant = useMemo(() => getLatestPlayableAssistantMessage(messages), [messages]);
const hasIncompleteMessages = lastAssistantMessage ? !('completed' in lastAssistantMessage.info.time && lastAssistantMessage.info.time.completed) : false;
const isStreamingResponse = hasIncompleteMessages && isSessionActive;
const assistantFileBasePath = assistantMode?.directory.split('/').filter(Boolean).at(-1);
const workspaceBasePath = (isAssistantSession ? assistantFileBasePath : repo?.localPath) ?? repo?.localPath;
useEffect(() => {
setActivePromptFileBasePath(repoDirectory ? workspaceBasePath ?? null : null)
return () => {
setActivePromptFileBasePath(null)
}
}, [repoDirectory, setActivePromptFileBasePath, workspaceBasePath])
useAutoPlayLastResponse({
sessionId: sessionId ?? '',
@@ -403,8 +414,6 @@ export function SessionDetail() {
}
const workspaceDisplayName = isAssistantSession ? 'Assistant' : getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
const assistantFileBasePath = assistantMode?.directory.split('/').filter(Boolean).at(-1);
const workspaceBasePath = (isAssistantSession ? assistantFileBasePath : repo.localPath) ?? repo.localPath;
const sessionBackPath = isAssistantSession ? `/repos/${repoId}/assistant?view=sessions` : `/repos/${repoId}`;
return (
+19
View File
@@ -1,11 +1,30 @@
import { create } from 'zustand'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
interface UIStateStore {
isEditingMessage: boolean
pendingPromptCommand: { id: number; command: CommandType } | null
pendingPromptFile: { id: number; path: string } | null
activePromptFileBasePath: string | null
setIsEditingMessage: (isEditing: boolean) => void
selectPromptCommand: (command: CommandType) => void
clearPendingPromptCommand: () => void
selectPromptFile: (path: string) => void
clearPendingPromptFile: () => void
setActivePromptFileBasePath: (basePath: string | null) => void
}
export const useUIState = create<UIStateStore>((set) => ({
isEditingMessage: false,
pendingPromptCommand: null,
pendingPromptFile: null,
activePromptFileBasePath: null,
setIsEditingMessage: (isEditing: boolean) => set({ isEditingMessage: isEditing }),
selectPromptCommand: (command: CommandType) => set({ pendingPromptCommand: { id: Date.now(), command } }),
clearPendingPromptCommand: () => set({ pendingPromptCommand: null }),
selectPromptFile: (path: string) => set({ pendingPromptFile: { id: Date.now(), path } }),
clearPendingPromptFile: () => set({ pendingPromptFile: null }),
setActivePromptFileBasePath: (basePath: string | null) => set({ activePromptFileBasePath: basePath }),
}))