feat(composer): unify prompt suggestions with fuzzy matching and a mobile keybar

This commit is contained in:
Chris Scott committed 2026-10-07 18:04:08 -04:00
1 parent 704f81884b
commit 855b78297e
24 files changed
+1121 -399

No files matched your search

+40 -8
View File
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useCommands } from './useCommands'
import { listCommands } from '../api/opencode'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
vi.mock('../api/opencode', () => ({
listCommands: vi.fn(),
@@ -23,12 +24,13 @@ const createWrapper = () => {
describe('useCommands', () => {
beforeEach(() => {
vi.clearAllMocks()
useRecentCommandsStore.setState({ names: [] })
})
it('returns the built-in commands sorted by name when disabled', () => {
const { result } = renderHook(() => useCommands({ enabled: false }), { wrapper: createWrapper() })
const names = result.current.filterCommands('').map(command => command.name)
const names = result.current.searchCommands('').map(({ item }) => item.name)
expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)))
for (const command of BUILTIN_COMMANDS) {
@@ -44,13 +46,13 @@ describe('useCommands', () => {
it('prioritizes exact and prefix matches before other matches', () => {
const { result } = renderHook(() => useCommands({ enabled: false }), { wrapper: createWrapper() })
expect(result.current.filterCommands('co').map(command => command.name)).toEqual([
expect(result.current.searchCommands('co').map(({ item }) => item.name)).toEqual([
'compact',
'connect',
'continue',
'copy',
])
expect(result.current.filterCommands('do').map(command => command.name)).toEqual([
expect(result.current.searchCommands('do').map(({ item }) => item.name)).toEqual([
'redo',
'undo',
])
@@ -65,7 +67,7 @@ describe('useCommands', () => {
const { result } = renderHook(() => useCommands({ directory: '/repo' }), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.filterCommands('').map(command => command.name).slice(0, 3)).toEqual([
expect(result.current.searchCommands('').map(({ item }) => item.name).slice(0, 3)).toEqual([
'agent',
'alpha',
'btw',
@@ -81,12 +83,12 @@ describe('useCommands', () => {
const { result } = renderHook(() => useCommands({ directory: '/repo' }), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.filterCommands('copy')).toEqual([
expect(result.current.searchCommands('copy').map(({ item }) => item)).toEqual([
{ name: 'copy', description: 'server copy' },
])
})
const [copy] = result.current.filterCommands('copy')
const copy = result.current.findCommand('copy')!
expect('action' in copy).toBe(false)
})
@@ -96,12 +98,42 @@ describe('useCommands', () => {
const { result } = renderHook(() => useCommands({ directory: '/repo' }), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.filterCommands('').some(command => command.name === 'xundo')).toBe(true)
expect(result.current.commands.some(command => command.name === 'xundo')).toBe(true)
})
expect(result.current.filterCommands('undo').map(command => command.name)).toEqual([
expect(result.current.searchCommands('undo').map(({ item }) => item.name)).toEqual([
'undo',
'xundo',
'redo',
])
})
it('lists recent commands first for an empty query and uses recency to break ties', () => {
useRecentCommandsStore.setState({ names: ['copy', 'undo'] })
const { result } = renderHook(() => useCommands({ enabled: false }), { wrapper: createWrapper() })
expect(result.current.searchCommands('').map(({ item }) => item.name).slice(0, 2)).toEqual(['copy', 'undo'])
expect(result.current.searchCommands('co').map(({ item }) => item.name)).toEqual([
'copy',
'compact',
'connect',
'continue',
])
})
it('matches command descriptions after name matches', async () => {
vi.mocked(listCommands).mockResolvedValue([{ name: 'ship', description: 'Deploy a preview build' }])
const { result } = renderHook(() => useCommands({ directory: '/repo' }), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.searchCommands('preview').map(({ item }) => item.name)).toEqual(['ship'])
})
})
it('finds only exact command names, ignoring case', () => {
const { result } = renderHook(() => useCommands({ enabled: false }), { wrapper: createWrapper() })
expect(result.current.findCommand('UNDO')?.name).toBe('undo')
expect(result.current.findCommand('und')).toBeUndefined()
})
})
+16 -19
View File
@@ -1,19 +1,15 @@
import { useCallback } from 'react'
import { useQuery } from '@tanstack/react-query'
import { listCommands } from '@/api/opencode'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
import { rankByMatch } from '@/lib/fuzzyMatch'
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
function sortCommandsByName(commands: CommandInfo[]): CommandInfo[] {
return [...commands].sort((a, b) => a.name.localeCompare(b.name))
}
function rankCommandMatch(command: CommandInfo, searchTerm: string): number {
const name = command.name.toLowerCase()
if (name === searchTerm) return 0
if (name.startsWith(searchTerm)) return 1
return 2
}
const SORTED_BUILTIN_COMMANDS = sortCommandsByName([...BUILTIN_COMMANDS])
interface UseCommandsOptions {
@@ -23,6 +19,7 @@ interface UseCommandsOptions {
export function useCommands(options: UseCommandsOptions = {}) {
const { directory, enabled = true } = options
const recentNames = useRecentCommandsStore((state) => state.names)
const { data: commands, isLoading: loading, error } = useQuery({
queryKey: ['opencode', 'commands', directory ?? null],
@@ -38,23 +35,23 @@ export function useCommands(options: UseCommandsOptions = {}) {
initialData: SORTED_BUILTIN_COMMANDS,
})
const filterCommands = (query: string) => {
if (!query.trim()) return commands
const searchCommands = useCallback((query: string) => rankByMatch(commands, query, {
getName: (command) => command.name,
getDescription: (command) => command.description,
recent: recentNames,
}), [commands, recentNames])
const searchTerm = query.toLowerCase()
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)
})
}
const findCommand = useCallback((name: string) => {
const lowerName = name.toLowerCase()
return commands.find((command) => command.name.toLowerCase() === lowerName)
}, [commands])
return {
commands,
recentNames,
loading,
error: error ? 'Failed to load commands' : null,
filterCommands
searchCommands,
findCommand,
}
}
@@ -0,0 +1,34 @@
import { describe, expect, it, vi } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useKeyboardShortcuts } from './useKeyboardShortcuts'
vi.mock('./useSettings', () => ({
useSettings: () => ({
preferences: { keyboardShortcuts: { submit: 'Return' }, directShortcuts: ['submit'] },
}),
}))
describe('useKeyboardShortcuts', () => {
it('runs a direct shortcut from a text input', () => {
const submitPrompt = vi.fn()
renderHook(() => useKeyboardShortcuts({ submitPrompt }))
const textarea = document.body.appendChild(document.createElement('textarea'))
textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
expect(submitPrompt).toHaveBeenCalledTimes(1)
textarea.remove()
})
it('ignores key events a component already handled', () => {
const submitPrompt = vi.fn()
renderHook(() => useKeyboardShortcuts({ submitPrompt }))
const textarea = document.body.appendChild(document.createElement('textarea'))
textarea.addEventListener('keydown', (event) => event.preventDefault())
textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
expect(submitPrompt).not.toHaveBeenCalled()
textarea.remove()
})
})
@@ -121,6 +121,7 @@ export function useKeyboardShortcuts(actions: ShortcutActions = {}) {
}, [])
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.defaultPrevented) return
const shortcut = parseEventShortcut(e)
if (!shortcut) return
+9
View File
@@ -10,6 +10,7 @@ import {
interruptSession,
backgroundSession,
listAgents,
listSkills,
runShell,
sendPrompt,
switchSessionAgent,
@@ -504,6 +505,14 @@ export const useAgents = (directory?: string, options?: { enabled?: boolean }) =
});
};
export const useSkills = (directory?: string, options?: { enabled?: boolean }) => {
return useQuery({
queryKey: ["opencode", "skills", directory],
queryFn: () => listSkills(directory),
enabled: options?.enabled ?? true,
});
};
export const useLoadSkill = (sessionID: string | undefined) => {
return useMutation<void, Error, { skillName: string }>({
mutationFn: async ({ skillName }: { skillName: string }) => {
+71 -11
View File
@@ -1,12 +1,36 @@
import { useCallback, useRef, type TouchEvent } from 'react'
import { useCallback, useEffect, useRef, useState, type TouchEvent } from 'react'
const TOUCH_TAP_MOVE_THRESHOLD = 8
const TOUCH_CLICK_SUPPRESS_MS = 400
const LONG_PRESS_MS = 450
export const SWIPE_COMMIT_DISTANCE = 96
export function useTouchTapSelect<T>(onSelect: (item: T) => void) {
interface TouchGestureOptions<T> {
onSwipeRight?: (item: T) => void
onLongPress?: (item: T) => void
}
interface ActiveSwipe<T> {
item: T
offset: number
}
export function useTouchTapSelect<T>(onSelect: (item: T) => void, options: TouchGestureOptions<T> = {}) {
const { onSwipeRight, onLongPress } = options
const touchStartRef = useRef<{ x: number, y: number } | null>(null)
const hasTouchMovedRef = useRef(false)
const isSwipingRef = useRef(false)
const suppressClickRef = useRef(false)
const longPressTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const longPressFiredRef = useRef(false)
const [swipe, setSwipe] = useState<ActiveSwipe<T> | null>(null)
const clearLongPress = useCallback(() => {
if (longPressTimerRef.current) clearTimeout(longPressTimerRef.current)
longPressTimerRef.current = null
}, [])
useEffect(() => clearLongPress, [clearLongPress])
const suppressNextClick = useCallback(() => {
suppressClickRef.current = true
@@ -15,33 +39,68 @@ export function useTouchTapSelect<T>(onSelect: (item: T) => void) {
}, TOUCH_CLICK_SUPPRESS_MS)
}, [])
const onTouchStart = useCallback((event: TouchEvent<HTMLElement>) => {
const onTouchStart = useCallback((event: TouchEvent<HTMLElement>, item?: T) => {
const touch = event.touches[0]
if (!touch) return
touchStartRef.current = { x: touch.clientX, y: touch.clientY }
hasTouchMovedRef.current = false
}, [])
isSwipingRef.current = false
longPressFiredRef.current = false
clearLongPress()
const onTouchMove = useCallback((event: TouchEvent<HTMLElement>) => {
if (onLongPress && item !== undefined) {
longPressTimerRef.current = setTimeout(() => {
longPressFiredRef.current = true
onLongPress(item)
}, LONG_PRESS_MS)
}
}, [clearLongPress, onLongPress])
const onTouchMove = useCallback((event: TouchEvent<HTMLElement>, item?: T) => {
const start = touchStartRef.current
const touch = event.touches[0]
if (!start || !touch) return
const deltaX = Math.abs(touch.clientX - start.x)
const deltaY = Math.abs(touch.clientY - start.y)
if (deltaX > TOUCH_TAP_MOVE_THRESHOLD || deltaY > TOUCH_TAP_MOVE_THRESHOLD) {
const deltaX = touch.clientX - start.x
const deltaY = touch.clientY - start.y
if (Math.abs(deltaX) > TOUCH_TAP_MOVE_THRESHOLD || Math.abs(deltaY) > TOUCH_TAP_MOVE_THRESHOLD) {
hasTouchMovedRef.current = true
clearLongPress()
}
}, [])
if (!onSwipeRight || item === undefined) return
if (!isSwipingRef.current && deltaX > TOUCH_TAP_MOVE_THRESHOLD && deltaX > Math.abs(deltaY) * 2) {
isSwipingRef.current = true
}
if (isSwipingRef.current) {
setSwipe({ item, offset: Math.max(0, deltaX) })
}
}, [clearLongPress, onSwipeRight])
const onTouchEnd = useCallback((event: TouchEvent<HTMLElement>, item: T) => {
const hasTouchMoved = hasTouchMovedRef.current
const wasSwiping = isSwipingRef.current
const longPressFired = longPressFiredRef.current
const start = touchStartRef.current
const touch = event.changedTouches[0]
touchStartRef.current = null
hasTouchMovedRef.current = false
isSwipingRef.current = false
longPressFiredRef.current = false
clearLongPress()
setSwipe(null)
if (hasTouchMoved) {
if (wasSwiping && start && touch && touch.clientX - start.x >= SWIPE_COMMIT_DISTANCE) {
event.preventDefault()
suppressNextClick()
onSwipeRight?.(item)
return
}
if (hasTouchMoved || longPressFired) {
if (longPressFired) event.preventDefault()
suppressNextClick()
return
}
@@ -49,7 +108,7 @@ export function useTouchTapSelect<T>(onSelect: (item: T) => void) {
event.preventDefault()
suppressNextClick()
onSelect(item)
}, [onSelect, suppressNextClick])
}, [clearLongPress, onSelect, onSwipeRight, suppressNextClick])
const onClick = useCallback((item: T) => {
if (suppressClickRef.current) {
@@ -61,6 +120,7 @@ export function useTouchTapSelect<T>(onSelect: (item: T) => void) {
}, [onSelect])
return {
swipe,
onTouchStart,
onTouchMove,
onTouchEnd,