Merge pull request #394 from chriswritescode-dev/feat/prompt-suggestions

feat(composer): unify prompt suggestions with fuzzy matching and a mobile keybar
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-07 19:04:23 -04:00
commit 7bb36e81cb
24 files changed
+1238 -400

No files matched your search

+6
View File
@@ -13,6 +13,7 @@ import type {
SessionInfo,
SessionMessageInfo,
SessionRevert,
SkillInfo,
} from '@opencode-manager/shared/opencode'
import type { SessionSnapshot } from '@/lib/session-projection'
@@ -273,6 +274,11 @@ export async function listCommands(directory?: string): Promise<CommandInfo[]> {
return data
}
export async function listSkills(directory?: string): Promise<SkillInfo[]> {
const { data } = await callOpenCode((api) => api.skill.list(openCodeLocation(directory)))
return data
}
export async function listPendingPermissions(directory: string): Promise<PermissionRequest[]> {
const { data } = await callOpenCode((api) => api.permission.request.list(openCodeLocation(directory)))
return data
@@ -1,91 +0,0 @@
import { useEffect, useRef } from 'react'
import { Command } from 'lucide-react'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
interface CommandSuggestionsProps {
isOpen: boolean
query: string
commands: CommandInfo[]
onSelect: (command: CommandInfo) => void
onClose: () => void
selectedIndex?: number
}
export function CommandSuggestions({
isOpen,
query,
commands,
onSelect,
onClose,
selectedIndex = 0
}: CommandSuggestionsProps) {
const listRef = useRef<HTMLDivElement>(null)
const touchTapSelect = useTouchTapSelect(onSelect)
const filteredCommands = commands.filter(command =>
command.name.toLowerCase().includes(query.toLowerCase())
)
useEffect(() => {
if (!isOpen) return
const handleClickOutside = (e: MouseEvent) => {
if (listRef.current && !listRef.current.contains(e.target as Node)) {
onClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, onClose])
useEffect(() => {
if (!isOpen || !listRef.current) return
const selectedItem = listRef.current.children[selectedIndex] as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest' })
}
}, [selectedIndex, isOpen])
if (!isOpen || filteredCommands.length === 0) {
return null
}
return (
<div
ref={listRef}
className="absolute bottom-full left-0 right-0 mb-2 z-50 bg-background border border-border rounded-lg shadow-xl max-h-48 md:max-h-[40vh] lg:max-h-[50vh] overflow-y-auto"
>
{filteredCommands.map((command, index) => {
const isSelected = index === selectedIndex
const displayName = `/${command.name}`
return (
<button
key={command.name}
onMouseDown={(e) => e.preventDefault()}
onTouchStart={touchTapSelect.onTouchStart}
onTouchMove={touchTapSelect.onTouchMove}
onTouchEnd={(e) => touchTapSelect.onTouchEnd(e, command)}
onClick={() => touchTapSelect.onClick(command)}
className={`w-full px-3 py-2 text-left transition-colors flex items-center gap-2 ${
isSelected
? 'bg-primary text-primary-foreground'
: 'hover:bg-muted text-foreground'
}`}
>
<Command className={`h-4 w-4 flex-shrink-0 ${isSelected ? 'opacity-90' : 'opacity-70'}`} />
<div className="flex-1 min-w-0">
<div className="font-mono text-sm font-medium truncate">{displayName}</div>
{command.description && (
<div className="text-xs opacity-70 mt-0.5 truncate">{command.description}</div>
)}
</div>
</button>
)
})}
</div>
)
}
@@ -1,96 +0,0 @@
import { useEffect, useRef } from 'react'
import { Bot, FileText } from 'lucide-react'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
export interface MentionItem {
type: 'file' | 'agent'
value: string
label: string
description?: string
}
interface MentionSuggestionsProps {
isOpen: boolean
items: MentionItem[]
onSelect: (item: MentionItem) => void
onClose: () => void
selectedIndex?: number
}
export function MentionSuggestions({
isOpen,
items,
onSelect,
onClose,
selectedIndex = 0
}: MentionSuggestionsProps) {
const listRef = useRef<HTMLDivElement>(null)
const touchTapSelect = useTouchTapSelect(onSelect)
useEffect(() => {
if (!isOpen) return
const handleClickOutside = (e: MouseEvent) => {
if (listRef.current && !listRef.current.contains(e.target as Node)) {
onClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, onClose])
useEffect(() => {
if (!isOpen || !listRef.current) return
const selectedItem = listRef.current.children[selectedIndex] as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest' })
}
}, [selectedIndex, isOpen])
if (!isOpen || items.length === 0) return null
const getFilename = (path: string) => path.split('/').pop() || path
const getDirectory = (path: string) => {
const parts = path.split('/')
return parts.slice(0, -1).join('/') || '.'
}
return (
<div
ref={listRef}
className="absolute bottom-full left-0 right-0 mb-2 z-50 bg-background border border-border rounded-lg shadow-xl max-h-48 md:max-h-[40vh] lg:max-h-[50vh] overflow-y-auto"
>
{items.map((item, idx) => (
<button
key={`${item.type}-${item.value}`}
onMouseDown={(e) => e.preventDefault()}
onTouchStart={touchTapSelect.onTouchStart}
onTouchMove={touchTapSelect.onTouchMove}
onTouchEnd={(e) => touchTapSelect.onTouchEnd(e, item)}
onClick={() => touchTapSelect.onClick(item)}
className={`w-full px-3 py-2 text-left transition-colors flex items-start gap-2 ${
idx === selectedIndex
? 'bg-primary text-primary-foreground'
: 'hover:bg-muted text-foreground'
}`}
>
{item.type === 'agent' ? (
<Bot className="w-4 h-4 mt-0.5 flex-shrink-0" />
) : (
<FileText className="w-4 h-4 mt-0.5 flex-shrink-0" />
)}
<div className="flex-1 min-w-0">
<div className="font-mono text-sm font-medium truncate">
{item.type === 'file' ? getFilename(item.value) : item.label}
</div>
<div className="text-xs opacity-70 mt-0.5 truncate">
{item.type === 'file' ? getDirectory(item.value) : item.description || 'Agent'}
</div>
</div>
</button>
))}
</div>
)
}
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
skills: [] as Array<{ id: string; name: string; description?: string }>,
setAgent: vi.fn(),
cycleVariant: vi.fn(),
showToast: {
@@ -35,6 +36,8 @@ const mocks = vi.hoisted(() => ({
useSendErrorStore: vi.fn(),
}))
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0 }))
vi.mock('@/api/opencode', async () => {
const actual = await vi.importActual('@/api/opencode')
return {
@@ -50,6 +53,7 @@ vi.mock('@/hooks/useOpenCode', async () => {
return {
...actual,
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
}
})
@@ -99,12 +103,18 @@ vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: () => null,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
vi.mock('./PromptSuggestions', () => ({
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => {
if (props.isOpen) {
suggestionProps.isOpen = true
suggestionProps.selectedIndex = props.selectedIndex
}
return null
},
}))
const createTestQueryClient = () => new QueryClient({
@@ -174,11 +184,12 @@ describe('PromptInput command submission', () => {
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({
filterCommands: (query: string) => {
if (query === 'review') return [{ name: 'review', description: 'Review' }]
const builtin = BUILTIN_COMMANDS.find((command) => command.name === query)
return builtin ? [builtin] : []
searchCommands: () => [],
findCommand: (name: string) => {
if (name === 'review') return { name: 'review', description: 'Review' }
return BUILTIN_COMMANDS.find((command) => command.name === name)
},
recentNames: [],
})
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
@@ -196,6 +207,8 @@ describe('PromptInput command submission', () => {
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: mocks.setAgent }))
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
suggestionProps.isOpen = false
suggestionProps.selectedIndex = 0
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
@@ -436,4 +449,113 @@ describe('PromptInput command submission', () => {
await waitFor(() => expect(input).toHaveValue(''))
expect(mocks.showToast.info).not.toHaveBeenCalled()
})
const commandSuggestions = () => ({
searchCommands: () => [
{ item: { name: 'alpha', description: 'Alpha' }, ranges: [] },
{ item: { name: 'beta', description: 'Beta' }, ranges: [] },
{ item: { name: 'gamma', description: 'Gamma' }, ranges: [] },
],
findCommand: () => undefined,
recentNames: [],
})
it('moves the command selection in the visual direction of the arrow on mobile', async () => {
mocks.useMobile.mockReturnValue(true)
mocks.useCommands.mockReturnValue(commandSuggestions())
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/', selectionStart: 1 } })
await waitFor(() => expect(suggestionProps.isOpen).toBe(true))
expect(suggestionProps.selectedIndex).toBe(0)
fireEvent.keyDown(input, { key: 'ArrowUp' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1))
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(0))
})
it('keeps the desktop command arrow direction unchanged', async () => {
mocks.useCommands.mockReturnValue(commandSuggestions())
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/', selectionStart: 1 } })
await waitFor(() => expect(suggestionProps.isOpen).toBe(true))
expect(suggestionProps.selectedIndex).toBe(0)
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1))
fireEvent.keyDown(input, { key: 'ArrowUp' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(0))
})
describe('mobile keybar', () => {
beforeEach(() => {
mocks.useMobile.mockReturnValue(true)
})
it('shows only while the prompt is focused on mobile', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
expect(screen.queryByRole('toolbar', { name: 'Insert' })).not.toBeInTheDocument()
fireEvent.focus(input)
expect(screen.getByRole('toolbar', { name: 'Insert' })).toBeInTheDocument()
})
it('is not shown on desktop', async () => {
mocks.useMobile.mockReturnValue(false)
renderComponent()
fireEvent.focus(await screen.findByPlaceholderText('Send a message...'))
expect(screen.queryByRole('toolbar', { name: 'Insert' })).not.toBeInTheDocument()
})
it('inserts a separated trigger at the cursor', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...') as HTMLTextAreaElement
fireEvent.change(input, { target: { value: 'hello world' } })
fireEvent.focus(input)
input.setSelectionRange(5, 5)
fireEvent.click(screen.getByRole('button', { name: 'mention @' }))
expect(input).toHaveValue('hello @ world')
fireEvent.change(input, { target: { value: 'hello' } })
input.setSelectionRange(5, 5)
fireEvent.click(screen.getByRole('button', { name: 'cmd /' }))
expect(input).toHaveValue('hello /')
})
it('enables bash only for an empty prompt and toggles bash mode', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.focus(input)
fireEvent.change(input, { target: { value: 'text' } })
expect(screen.getByRole('button', { name: 'bash !' })).toBeDisabled()
fireEvent.change(input, { target: { value: '' } })
const bashKey = screen.getByRole('button', { name: 'bash !' })
expect(bashKey).toBeEnabled()
fireEvent.click(bashKey)
expect(input).toHaveValue('!')
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
expect(screen.getByRole('button', { name: 'cmd /' })).toBeDisabled()
fireEvent.click(screen.getByRole('button', { name: 'bash !' }))
expect(input).toHaveValue('')
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
})
})
})
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
useSessionGoal: vi.fn(),
useSessionPermissionMode: vi.fn(),
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
skills: [] as Array<{ id: string; name: string; description?: string }>,
setAgent: vi.fn(),
cycleVariant: vi.fn(),
showToast: {
@@ -44,6 +45,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
useSendShell: () => ({ mutate: mocks.sendShell, isPending: false }),
useInterruptSession: () => ({ mutate: mocks.interrupt }),
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
}
})
@@ -121,12 +123,8 @@ vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
vi.mock('./PromptSuggestions', () => ({
PromptSuggestions: () => null,
}))
const createTestQueryClient = () => new QueryClient({
@@ -179,7 +177,7 @@ describe('PromptInput goal mode', () => {
abortRecording: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({ filterCommands: () => [] })
mocks.useCommands.mockReturnValue({ searchCommands: () => [], findCommand: () => undefined, recentNames: [] })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
@@ -298,7 +296,11 @@ describe('PromptInput goal mode', () => {
it('does not start an armed goal for a slash command', async () => {
stubMatchMedia(true)
mocks.useCommands.mockReturnValue({ filterCommands: () => [{ name: 'review' }] })
mocks.useCommands.mockReturnValue({
searchCommands: () => [],
findCommand: (name: string) => (name === 'review' ? { name: 'review' } : undefined),
recentNames: [],
})
renderComponent({ isStreamingResponse: true })
const input = await screen.findByPlaceholderText('Send a message...')
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
switchSessionAgent: vi.fn(),
runCommand: vi.fn(),
agents: [] as Array<{ name: string; description?: string }>,
skills: [] as Array<{ id: string; name: string; description?: string }>,
useSTT: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
@@ -23,6 +24,8 @@ const mocks = vi.hoisted(() => ({
useSendErrorStore: vi.fn(),
}))
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0 }))
vi.mock('@/api/opencode', async () => {
const actual = await vi.importActual('@/api/opencode')
return {
@@ -39,6 +42,7 @@ vi.mock('@/hooks/useOpenCode', async () => {
return {
...actual,
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
}
})
@@ -90,12 +94,18 @@ vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
vi.mock('./PromptSuggestions', () => ({
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => {
if (props.isOpen) {
suggestionProps.isOpen = true
suggestionProps.selectedIndex = props.selectedIndex
}
return null
},
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: () => null,
}))
const createTestQueryClient = () => new QueryClient({
@@ -151,6 +161,7 @@ describe('PromptInput agent mention submission', () => {
mocks.switchSessionAgent.mockResolvedValue(undefined)
mocks.runCommand.mockResolvedValue(undefined)
mocks.agents = [{ name: 'reviewer', description: 'Reviewer' }]
mocks.skills = [{ id: 'pr-review', name: 'PR Review', description: 'Review a PR' }]
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
@@ -165,7 +176,7 @@ describe('PromptInput agent mention submission', () => {
reset: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({ filterCommands: () => [] })
mocks.useCommands.mockReturnValue({ searchCommands: () => [], findCommand: () => undefined, recentNames: [] })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
@@ -181,6 +192,8 @@ describe('PromptInput agent mention submission', () => {
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
suggestionProps.isOpen = false
suggestionProps.selectedIndex = 0
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
@@ -221,6 +234,22 @@ describe('PromptInput agent mention submission', () => {
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
})
it('sends an @skill mention as a skill attachment', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'use @pr-review and @pr-review' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.sendPrompt).toHaveBeenCalledWith(expect.objectContaining({
text: 'use @pr-review and @pr-review',
agents: [],
skills: [{ id: 'pr-review', mention: { start: 4, end: 14, text: '@pr-review' } }],
}))
})
it('sends plain text without inferring an agent attachment or switching', async () => {
renderComponent()
@@ -238,4 +267,45 @@ describe('PromptInput agent mention submission', () => {
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
})
it('moves the mention selection in the visual direction of the arrow on mobile', async () => {
mocks.useMobile.mockReturnValue(true)
mocks.agents = [
{ name: 'alpha', description: 'Alpha agent' },
{ name: 'beta', description: 'Beta agent' },
]
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '@', selectionStart: 1 } })
await waitFor(() => expect(suggestionProps.isOpen).toBe(true))
expect(suggestionProps.selectedIndex).toBe(0)
fireEvent.keyDown(input, { key: 'ArrowUp' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1))
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(0))
})
it('keeps the desktop arrow direction unchanged', async () => {
mocks.agents = [
{ name: 'alpha', description: 'Alpha agent' },
{ name: 'beta', description: 'Beta agent' },
]
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '@', selectionStart: 1 } })
await waitFor(() => expect(suggestionProps.isOpen).toBe(true))
expect(suggestionProps.selectedIndex).toBe(0)
fireEvent.keyDown(input, { key: 'ArrowUp' })
expect(suggestionProps.selectedIndex).toBe(0)
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1))
})
})
@@ -46,6 +46,7 @@ vi.mock('@/hooks/useOpenCode', () => ({
useInterruptSession: () => ({ mutate: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
}))
vi.mock('@/hooks/useCommands', () => ({
@@ -121,12 +122,8 @@ vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
vi.mock('./PromptSuggestions', () => ({
PromptSuggestions: () => null,
}))
interface MockSTTReturn {
@@ -191,7 +188,7 @@ describe('PromptInput STT Gesture Tests', () => {
clear: mockClear,
} as unknown as MockSTTReturn)
mocks.useCommands.mockReturnValue({ filterCommands: vi.fn() })
mocks.useCommands.mockReturnValue({ searchCommands: () => [], findCommand: vi.fn(), recentNames: [] })
mocks.useCommandHandler.mockReturnValue({ executeCommand: vi.fn() })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
+346 -117
View File
@@ -1,5 +1,5 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills } from '@/hooks/useOpenCode'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
@@ -12,6 +12,8 @@ import { useUserBash } from '@/stores/userBashStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useUIState } from '@/stores/uiStateStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
import { useMobile } from '@/hooks/useMobile'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
@@ -21,8 +23,7 @@ import { ArrowDown, Upload, X, Mic, MicOff, Target } from 'lucide-react'
import { SquareFill } from '@/components/ui/square-fill'
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { MentionSuggestions, type MentionItem } from './MentionSuggestions'
import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
@@ -31,7 +32,8 @@ import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, type MentionItem } from '@/lib/promptParser'
import { matchText, rankByMatch, type MatchRange } from '@/lib/fuzzyMatch'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { randomId } from '@/lib/utils'
import { showToast } from '@/lib/toast'
@@ -61,6 +63,43 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => {
const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"]
const COMMAND_TRIGGER_PATTERN = /(^|\s)\/([a-zA-Z0-9_-]*)$/
const FILE_FALLBACK_MATCH_TIER = 4
const KEYBAR_HIDE_DELAY_MS = 250
type KeybarKey = 'command' | 'mention' | 'bash'
type ComposerMode = 'command' | 'mention' | 'bash'
const KEYBAR_KEYS: Array<{ id: KeybarKey, symbol: string, label: string }> = [
{ id: 'command', symbol: '/', label: 'cmd' },
{ id: 'mention', symbol: '@', label: 'mention' },
{ id: 'bash', symbol: '!', label: 'bash' },
]
const COMPOSER_MODE_STYLES: Record<ComposerMode, { label: string, frame: string, badge: string, key: string }> = {
command: {
label: 'COMMAND',
frame: 'border-primary/70 ring-1 ring-primary/40 shadow-lg shadow-primary/20',
badge: 'bg-primary text-primary-foreground',
key: 'bg-primary text-primary-foreground border-primary',
},
mention: {
label: 'MENTION',
frame: 'border-success/70 ring-1 ring-success/40 shadow-lg shadow-success/20',
badge: 'bg-success text-success-foreground',
key: 'bg-success text-success-foreground border-success',
},
bash: {
label: 'BASH',
frame: 'border-warning/70 ring-1 ring-warning/40 shadow-lg shadow-warning/20',
badge: 'bg-warning text-warning-foreground',
key: 'bg-warning text-warning-foreground border-warning',
},
}
const shiftRanges = (ranges: MatchRange[], offset: number): MatchRange[] =>
ranges.map(([start, end]) => [start + offset, end + offset])
const VOICE_SEND_SWIPE_ARM_THRESHOLD = 24
const VOICE_SEND_SWIPE_DISARM_THRESHOLD = 8
type VoiceButtonVariant = 'desktop' | 'mobile'
@@ -113,6 +152,9 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const [isVoiceSwipeArmed, setIsVoiceSwipeArmed] = useState(false)
const [isVoiceAutoSendPending, setIsVoiceAutoSendPending] = useState(false)
const [isVoiceAutoSendWaitingForTranscript, setIsVoiceAutoSendWaitingForTranscript] = useState(false)
const [isPromptFocused, setIsPromptFocused] = useState(false)
const promptBlurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const pendingCommandSubmitRef = useRef(false)
const lastAddedTranscriptRef = useRef('')
const voiceGestureStartYRef = useRef<number | null>(null)
const voiceSwipeArmedRef = useRef(false)
@@ -238,12 +280,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID)
const { data: permissionMode } = useSessionPermissionMode(sessionID)
const { filterCommands } = useCommands({ directory })
const { searchCommands, findCommand, recentNames } = useCommands({ directory })
const recordCommand = useRecentCommandsStore((state) => state.recordCommand)
const isExactCommandPrompt = (value: string) => {
const commandPrompt = parseCommandPrompt(value)
if (!commandPrompt) return false
const [command] = filterCommands(commandPrompt.name)
return command?.name.toLowerCase() === commandPrompt.name.toLowerCase()
return Boolean(commandPrompt && findCommand(commandPrompt.name))
}
const { files: searchResults } = useFileSearch(
@@ -253,7 +294,9 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
)
const { data: agents = [] } = useAgents(directory)
const { data: skills = [] } = useSkills(directory)
const agentNames = useMemo(() => agents.map((agent) => agent.name), [agents])
const skillIds = useMemo(() => skills.map((skill) => skill.id), [skills])
const failedPrompt = useSendErrorStore((state) => state.errors[sessionID]?.failedPrompt)
const restoredFailedPromptRef = useRef<string | null>(null)
@@ -274,28 +317,72 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
}, [failedPrompt])
const mentionItems = useMemo((): MentionItem[] => {
const filteredAgents = filterAgentsByQuery(
agents.map(a => ({ name: a.name, description: a.description })),
mentionQuery
)
const agentItems: MentionItem[] = filteredAgents.map(agent => ({
type: 'agent',
value: agent.name,
label: agent.name,
description: agent.description
const mentionSuggestions = useMemo((): PromptSuggestion<MentionItem>[] => {
const agentMatches = rankByMatch(agents, mentionQuery, {
getName: (agent) => agent.name,
getDescription: (agent) => agent.description,
}).map(({ item, tier, ranges }) => ({
tier,
suggestion: {
key: `agent-${item.name}`,
value: { type: 'agent', value: item.name } satisfies MentionItem,
kind: 'agent' as const,
label: item.name,
ranges,
detail: item.description || 'Agent',
tag: 'agent',
},
}))
const fileItems: MentionItem[] = searchResults.map(file => ({
type: 'file',
value: file,
label: getFilename(file),
description: file
const skillMatches = rankByMatch(skills, mentionQuery, {
getName: (skill) => skill.id,
getDescription: (skill) => skill.description,
}).map(({ item, tier, ranges }) => ({
tier,
suggestion: {
key: `skill-${item.id}`,
value: { type: 'skill', value: item.id } satisfies MentionItem,
kind: 'skill' as const,
label: item.id,
ranges,
detail: item.description || item.name,
tag: 'skill',
},
}))
return [...agentItems, ...fileItems]
}, [agents, searchResults, mentionQuery])
const fileMatches = searchResults.map((file) => {
const label = getFilename(file)
const match = matchText(mentionQuery, label)
return {
tier: match?.tier ?? FILE_FALLBACK_MATCH_TIER,
suggestion: {
key: `file-${file}`,
value: { type: 'file', value: file } satisfies MentionItem,
kind: 'file' as const,
label,
ranges: match?.ranges ?? [],
detail: getDirectory(file),
tag: 'file',
},
}
})
return [...agentMatches, ...skillMatches, ...fileMatches]
.sort((a, b) => a.tier - b.tier)
.map(({ suggestion }) => suggestion)
}, [agents, skills, searchResults, mentionQuery])
const commandSuggestions = useMemo((): PromptSuggestion<CommandInfo>[] =>
searchCommands(suggestionQuery).map(({ item, ranges }) => ({
key: item.name,
value: item,
kind: 'command',
label: `/${item.name}`,
ranges: shiftRanges(ranges, 1),
detail: item.description,
tag: !suggestionQuery && recentNames.includes(item.name) ? 'recent' : undefined,
})),
[searchCommands, suggestionQuery, recentNames])
const addUserBashCommand = useUserBash((s) => s.addUserBashCommand)
@@ -321,7 +408,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (isStreamingResponse) {
onScrollToBottom()
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, imageAttachments)
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, skillIds, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
@@ -376,10 +463,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const commandPrompt = parseCommandPrompt(prompt)
if (commandPrompt) {
const command = filterCommands(commandPrompt.name)[0]
const command = findCommand(commandPrompt.name)
if (command) {
const parsed = parsePromptToInput(commandPrompt.args?.trim() || '', attachedFiles, agentNames, imageAttachments)
recordCommand(command.name)
const parsed = parsePromptToInput(commandPrompt.args?.trim() || '', attachedFiles, agentNames, skillIds, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
@@ -403,7 +491,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
}
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, imageAttachments)
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, skillIds, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
@@ -451,29 +539,46 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
interruptSession.mutate(sessionID)
}
const handleCommandSelect = useCallback(async (command: CommandInfo) => {
const focusPromptAt = useCallback((cursorPosition: number) => {
setTimeout(() => {
if (!textareaRef.current) return
textareaRef.current.focus()
textareaRef.current.setSelectionRange(cursorPosition, cursorPosition)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}, 0)
}, [])
const handleCommandSelect = useCallback((command: CommandInfo, submitAfterInsert = false) => {
if (!textareaRef.current) return
setShowSuggestions(false)
setSuggestionQuery('')
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
const commandMatch = prompt.slice(0, cursorPosition).match(COMMAND_TRIGGER_PATTERN)
const beforeCommand = commandMatch ? prompt.slice(0, commandMatch.index) : ''
const beforeCommand = commandMatch ? prompt.slice(0, (commandMatch.index ?? 0) + commandMatch[1].length) : ''
const afterCommand = commandMatch ? prompt.slice(cursorPosition) : ''
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
if (submitAfterInsert && newPrompt === prompt) {
handleSubmitRef.current()
return
}
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)
pendingCommandSubmitRef.current = submitAfterInsert
setPrompt(newPrompt)
if (!submitAfterInsert) focusPromptAt(beforeCommand.length + command.name.length + 2)
}, [prompt, focusPromptAt])
const handleCommandSwipe = useCallback((command: CommandInfo) => {
handleCommandSelect(command, true)
}, [handleCommandSelect])
useEffect(() => {
if (!pendingCommandSubmitRef.current) return
pendingCommandSubmitRef.current = false
handleSubmitRef.current()
}, [prompt])
useEffect(() => {
@@ -505,15 +610,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
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])
focusPromptAt(beforeMention.length + filename.length + 2)
}, [directory, mentionRange, prompt, focusPromptAt])
useEffect(() => {
if (!pendingPromptFile) return
@@ -527,20 +625,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const beforeMention = prompt.slice(0, mentionRange.start)
const afterMention = prompt.slice(mentionRange.end)
if (item.type === 'agent') {
const newPrompt = beforeMention + '@' + item.value + ' ' + afterMention
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + item.value.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
} else {
if (item.type === 'file') {
insertFileMention(item.value, mentionRange)
} else {
setPrompt(beforeMention + '@' + item.value + ' ' + afterMention)
focusPromptAt(beforeMention.length + item.value.length + 2)
}
setShowMentionSuggestions(false)
@@ -941,25 +1030,32 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
return
}
if (showMentionSuggestions && mentionItems.length > 0) {
const suggestionStep = isMobile ? -1 : 1
if (showMentionSuggestions && mentionSuggestions.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedMentionIndex(prev =>
prev < mentionItems.length - 1 ? prev + 1 : prev
)
setSelectedMentionIndex(prev => {
const next = prev + suggestionStep
return next >= 0 && next < mentionSuggestions.length ? next : prev
})
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedMentionIndex(prev => prev > 0 ? prev - 1 : 0)
setSelectedMentionIndex(prev => {
const next = prev - suggestionStep
return next >= 0 && next < mentionSuggestions.length ? next : prev
})
return
}
if (e.key === 'Enter') {
e.preventDefault()
if (mentionItems[selectedMentionIndex]) {
handleMentionSelect(mentionItems[selectedMentionIndex])
const selectedMention = mentionSuggestions[selectedMentionIndex]
if (selectedMention) {
handleMentionSelect(selectedMention.value)
}
return
}
@@ -974,25 +1070,23 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}
if (showSuggestions) {
const filteredCommands = filterCommands(suggestionQuery)
if (e.key === 'ArrowDown') {
if (e.key === 'ArrowDown' && commandSuggestions.length > 0) {
e.preventDefault()
setSelectedCommandIndex(prev => (prev + 1) % filteredCommands.length)
setSelectedCommandIndex(prev => (prev + suggestionStep + commandSuggestions.length) % commandSuggestions.length)
return
}
if (e.key === 'ArrowUp') {
if (e.key === 'ArrowUp' && commandSuggestions.length > 0) {
e.preventDefault()
setSelectedCommandIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length)
setSelectedCommandIndex(prev => (prev - suggestionStep + commandSuggestions.length) % commandSuggestions.length)
return
}
if (e.key === 'Enter') {
e.preventDefault()
const selectedCommand = filteredCommands[selectedCommandIndex]
const selectedCommand = commandSuggestions[selectedCommandIndex]
if (selectedCommand) {
handleCommandSelect(selectedCommand)
handleCommandSelect(selectedCommand.value)
}
return
}
@@ -1013,11 +1107,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}
handleSubmit()
} else if (e.key === 'Escape') {
setShowSuggestions(false)
setSuggestionQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
closeSuggestions()
setPrompt('')
revokeBlobUrls(imageAttachments)
setImageAttachments([])
@@ -1048,8 +1138,18 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
return
}
const cursorPosition = e.target.selectionStart
updateSuggestionTriggers(value, e.target.selectionStart)
}
const closeSuggestions = () => {
setShowSuggestions(false)
setSuggestionQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}
const updateSuggestionTriggers = (value: string, cursorPosition: number) => {
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
if (mentionTrigger) {
@@ -1057,25 +1157,98 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
setMentionRange({ start: mentionTrigger.start, end: mentionTrigger.end })
setShowMentionSuggestions(true)
setSelectedMentionIndex(0)
} else {
const commandMatch = value.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const query = commandMatch[2]
setSuggestionQuery(query)
setShowSuggestions(true)
setSelectedCommandIndex(0)
} else {
setShowSuggestions(false)
setSuggestionQuery('')
}
if (showMentionSuggestions) {
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}
return
}
const commandMatch = value.slice(0, cursorPosition).match(COMMAND_TRIGGER_PATTERN)
if (commandMatch) {
setSuggestionQuery(commandMatch[2])
setShowSuggestions(true)
setSelectedCommandIndex(0)
} else {
setShowSuggestions(false)
setSuggestionQuery('')
}
if (showMentionSuggestions) {
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}
}
const insertTriggerAtCursor = (trigger: '/' | '@') => {
const selectionStart = textareaRef.current?.selectionStart ?? prompt.length
const selectionEnd = textareaRef.current?.selectionEnd ?? prompt.length
const before = prompt.slice(0, selectionStart)
const separator = before && !/\s$/.test(before) ? ' ' : ''
const nextPrompt = `${before}${separator}${trigger}${prompt.slice(selectionEnd)}`
const cursorPosition = before.length + separator.length + 1
setPrompt(nextPrompt)
updateSuggestionTriggers(nextPrompt, cursorPosition)
focusPromptAt(cursorPosition)
}
const removeActiveTrigger = () => {
const cursorPosition = textareaRef.current?.selectionStart ?? prompt.length
const commandTokenStart = prompt.slice(0, cursorPosition).search(/\/[a-zA-Z0-9_-]*$/)
const tokenStart = showMentionSuggestions && mentionRange ? mentionRange.start : commandTokenStart
const start = tokenStart >= 0 ? tokenStart : cursorPosition
setPrompt(prompt.slice(0, start) + prompt.slice(cursorPosition))
closeSuggestions()
focusPromptAt(start)
}
const toggleBashMode = () => {
closeSuggestions()
if (isBashMode) {
const nextPrompt = prompt.replace(/^!/, '')
setIsBashMode(false)
setPrompt(nextPrompt)
focusPromptAt(nextPrompt.length)
return
}
setIsBashMode(true)
setPrompt('!')
focusPromptAt(1)
}
const isBashKeyEnabled = isBashMode || (prompt === '' && imageAttachments.length === 0)
const handleKeybarKey = (key: KeybarKey) => {
if (key === 'bash') {
if (isBashKeyEnabled) toggleBashMode()
return
}
if (isBashMode) return
const isActive = key === 'command' ? showSuggestions : showMentionSuggestions
if (isActive) {
removeActiveTrigger()
return
}
insertTriggerAtCursor(key === 'command' ? '/' : '@')
}
const keybarTouch = useTouchTapSelect(handleKeybarKey)
const clearPromptBlurTimer = useCallback(() => {
if (promptBlurTimerRef.current) clearTimeout(promptBlurTimerRef.current)
promptBlurTimerRef.current = null
}, [])
useEffect(() => clearPromptBlurTimer, [clearPromptBlurTimer])
const handlePromptFocus = () => {
clearPromptBlurTimer()
setIsPromptFocused(true)
}
const handlePromptBlur = () => {
clearPromptBlurTimer()
promptBlurTimerRef.current = setTimeout(() => setIsPromptFocused(false), KEYBAR_HIDE_DELAY_MS)
}
const { data: providersData } = useProviders(directory)
@@ -1149,6 +1322,17 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
currentAgent: currentMode,
actions: commandActionsWithPrompt,
})
const isCommandListOpen = showSuggestions && commandSuggestions.length > 0
const isMentionListOpen = showMentionSuggestions && mentionSuggestions.length > 0
const composerMode: ComposerMode | null = isBashMode
? 'bash'
: isMentionListOpen
? 'mention'
: isCommandListOpen || isExactCommandPrompt(prompt)
? 'command'
: null
const composerModeStyle = composerMode ? COMPOSER_MODE_STYLES[composerMode] : null
const isTakeoverOpen = isMobile && (isCommandListOpen || isMentionListOpen)
const showStopButton = isSessionActive
const hideSecondaryButtons = isMobile && isSessionActive
const showMobileScrollButton = isMobile && showScrollButton
@@ -1287,11 +1471,21 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
return (
<div className={`relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full transition-all ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : ''}`}>
<div className={`relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full transition-all ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : composerModeStyle?.frame ?? ''} ${isTakeoverOpen ? 'z-[60]' : ''}`}>
{composerModeStyle && (
<span
data-testid="composer-mode-badge"
className={`absolute -top-2.5 left-3 z-10 px-1.5 py-0.5 rounded text-[10px] font-bold tracking-widest pointer-events-none ${composerModeStyle.badge}`}
>
{composerModeStyle.label}
</span>
)}
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onFocus={handlePromptFocus}
onBlur={handlePromptBlur}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onDragOver={handleDragOver}
@@ -1304,7 +1498,7 @@ return (
}
className={`w-full bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg [field-sizing:content] ${
isBashMode
? 'border-primary/50 bg-primary/5 focus:bg-primary/10'
? 'border-warning/50 bg-warning/5 focus:bg-warning/10'
: isDragging ? 'border-info/50 border-dashed bg-info/5' : ''
}`}
rows={1}
@@ -1468,29 +1662,64 @@ return (
</button>
</div>
</div>
<CommandSuggestions
{isMobile && isPromptFocused && !hasPendingPermissionForSession && (
<div role="toolbar" aria-label="Insert" className="flex items-center gap-1.5 mt-2 pt-2 border-t border-border/50">
{KEYBAR_KEYS.map((key) => {
const isActive = key.id === 'command'
? showSuggestions
: key.id === 'mention'
? showMentionSuggestions
: isBashMode
const isDisabled = key.id === 'bash' ? !isBashKeyEnabled : isBashMode
return (
<button
key={key.id}
type="button"
aria-pressed={isActive}
aria-label={`${key.label} ${key.symbol}`}
disabled={isDisabled}
onMouseDown={(e) => e.preventDefault()}
onTouchStart={keybarTouch.onTouchStart}
onTouchMove={keybarTouch.onTouchMove}
onTouchEnd={(e) => keybarTouch.onTouchEnd(e, key.id)}
onClick={() => keybarTouch.onClick(key.id)}
className={`flex items-center gap-1 min-h-[32px] px-3 rounded-lg border font-mono text-base font-bold transition-colors disabled:opacity-30 ${
isActive ? COMPOSER_MODE_STYLES[key.id].key : 'bg-muted border-border text-foreground active:bg-muted-foreground/20'
}`}
>
{key.symbol}
<span className="font-sans text-[11px] font-medium opacity-80">{key.label}</span>
</button>
)
})}
</div>
)}
<PromptSuggestions
isOpen={showSuggestions}
query={suggestionQuery}
commands={filterCommands(suggestionQuery)}
items={commandSuggestions}
selectedIndex={selectedCommandIndex}
takeover={isMobile}
onSelect={handleCommandSelect}
onSwipeRight={handleCommandSwipe}
onClose={() => {
setShowSuggestions(false)
setSuggestionQuery('')
}}
selectedIndex={selectedCommandIndex}
/>
<MentionSuggestions
<PromptSuggestions
isOpen={showMentionSuggestions}
items={mentionItems}
items={mentionSuggestions}
selectedIndex={selectedMentionIndex}
takeover={isMobile}
onSelect={handleMentionSelect}
onClose={() => {
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}}
selectedIndex={selectedMentionIndex}
/>
</div>
)
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions'
const items: PromptSuggestion<string>[] = [
{ key: 'review', value: 'review', kind: 'command', label: '/review', ranges: [[1, 4]], detail: 'Review changes' },
{ key: 'redo', value: 'redo', kind: 'command', label: '/redo', ranges: [[1, 3]], tag: 'recent' },
]
const renderList = (props: Partial<Parameters<typeof PromptSuggestions<string>>[0]> = {}) => {
const handlers = { onSelect: vi.fn(), onSwipeRight: vi.fn(), onClose: vi.fn() }
render(<PromptSuggestions isOpen items={items} selectedIndex={0} takeover {...handlers} {...props} />)
return handlers
}
const rowButton = (label: string) => screen.getAllByRole('button').find((button) => button.textContent?.startsWith(label))!
describe('PromptSuggestions', () => {
it('places the best match nearest the composer in takeover mode', () => {
renderList()
const rows = screen.getAllByRole('button').map((button) => button.textContent)
expect(rows[rows.length - 1]).toContain('/review')
})
it('keeps best-first order in the desktop popover', () => {
renderList({ takeover: false })
expect(screen.getAllByRole('button')[0]).toHaveTextContent('/review')
})
it('highlights matched characters', () => {
renderList()
expect(screen.getByText('rev')).toHaveClass('underline')
})
it('selects a row on tap', () => {
const handlers = renderList()
const row = rowButton('/redo')
fireEvent.touchStart(row, { touches: [{ clientX: 10, clientY: 10 }] })
fireEvent.touchEnd(row, { changedTouches: [{ clientX: 10, clientY: 10 }] })
expect(handlers.onSelect).toHaveBeenCalledWith('redo')
expect(handlers.onSwipeRight).not.toHaveBeenCalled()
})
it('runs a row on a long enough right swipe', () => {
const handlers = renderList()
const row = rowButton('/review')
fireEvent.touchStart(row, { touches: [{ clientX: 10, clientY: 10 }] })
fireEvent.touchMove(row, { touches: [{ clientX: 130, clientY: 12 }] })
fireEvent.touchEnd(row, { changedTouches: [{ clientX: 130, clientY: 12 }] })
expect(handlers.onSwipeRight).toHaveBeenCalledWith('review')
expect(handlers.onSelect).not.toHaveBeenCalled()
})
it('ignores a short swipe', () => {
const handlers = renderList()
const row = rowButton('/review')
fireEvent.touchStart(row, { touches: [{ clientX: 10, clientY: 10 }] })
fireEvent.touchMove(row, { touches: [{ clientX: 50, clientY: 10 }] })
fireEvent.touchEnd(row, { changedTouches: [{ clientX: 50, clientY: 10 }] })
expect(handlers.onSwipeRight).not.toHaveBeenCalled()
expect(handlers.onSelect).not.toHaveBeenCalled()
})
it('renders nothing without items', () => {
renderList({ items: [] })
expect(screen.queryByTestId('prompt-suggestions')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,221 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react'
import { Bot, Command, FileText, Sparkles, Play } from 'lucide-react'
import { SWIPE_COMMIT_DISTANCE, useTouchTapSelect } from '@/hooks/useTouchTapSelect'
import type { MatchRange } from '@/lib/fuzzyMatch'
export type SuggestionKind = 'command' | 'agent' | 'skill' | 'file'
export interface PromptSuggestion<T> {
key: string
value: T
kind: SuggestionKind
label: string
ranges: MatchRange[]
detail?: string
tag?: string
}
interface PromptSuggestionsProps<T> {
isOpen: boolean
items: PromptSuggestion<T>[]
selectedIndex: number
takeover: boolean
onSelect: (value: T) => void
onSwipeRight?: (value: T) => void
onClose: () => void
}
const TAKEOVER_TOP_GAP_PX = 8
const TAKEOVER_MIN_HEIGHT_PX = 160
const KIND_ICONS: Record<SuggestionKind, typeof Command> = {
command: Command,
agent: Bot,
skill: Sparkles,
file: FileText,
}
export function PromptSuggestions<T>({
isOpen,
items,
selectedIndex,
takeover,
onSelect,
onSwipeRight,
onClose,
}: PromptSuggestionsProps<T>) {
const listRef = useRef<HTMLDivElement>(null)
const [expandedKey, setExpandedKey] = useState<string | null>(null)
const isVisible = isOpen && items.length > 0
const takeoverHeight = useTakeoverHeight(listRef, isVisible && takeover)
const toggleExpanded = useCallback((value: T) => {
const key = items.find((item) => item.value === value)?.key ?? null
setExpandedKey((current) => (current === key ? null : key))
navigator.vibrate?.(10)
}, [items])
const touch = useTouchTapSelect(onSelect, { onSwipeRight, onLongPress: takeover ? toggleExpanded : undefined })
useEffect(() => {
if (!isOpen) return
const handleClickOutside = (e: MouseEvent) => {
if (listRef.current && !listRef.current.contains(e.target as Node)) {
onClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, onClose])
useEffect(() => {
if (!isVisible || !listRef.current) return
const selectedItem = listRef.current.querySelector<HTMLElement>(`[data-index="${selectedIndex}"]`)
selectedItem?.scrollIntoView?.({ block: 'nearest' })
}, [selectedIndex, isVisible])
useLayoutEffect(() => {
if (!isVisible || !takeover || !listRef.current) return
listRef.current.scrollTop = listRef.current.scrollHeight
}, [isVisible, takeover, items])
if (!isVisible) return null
const rows = items.map((item, index) => {
const isSelected = index === selectedIndex
const isExpanded = item.key === expandedKey
const swipeOffset = touch.swipe?.item === item.value ? touch.swipe.offset : 0
const Icon = KIND_ICONS[item.kind]
return (
<div key={item.key} data-index={index} className={`relative overflow-hidden ${takeover ? 'rounded-xl' : ''}`}>
{swipeOffset > 0 && (
<div className={`absolute inset-0 flex items-center gap-2 pl-4 text-xs font-bold tracking-widest ${swipeOffset >= SWIPE_COMMIT_DISTANCE ? 'bg-success text-success-foreground' : 'bg-success/40 text-foreground'}`}>
<Play className="w-4 h-4" />
RUN
</div>
)}
<button
type="button"
onMouseDown={(e) => e.preventDefault()}
onTouchStart={(e) => touch.onTouchStart(e, item.value)}
onTouchMove={(e) => touch.onTouchMove(e, item.value)}
onTouchEnd={(e) => touch.onTouchEnd(e, item.value)}
onClick={() => touch.onClick(item.value)}
style={swipeOffset > 0 ? { transform: `translateX(${swipeOffset}px)` } : undefined}
className={`relative w-full text-left flex gap-2 touch-pan-y select-none ${
takeover ? 'min-h-[52px] px-3 py-2 items-center gap-3 rounded-xl border' : 'px-3 py-2 items-start'
} ${
isSelected
? takeover ? 'bg-primary/15 border-primary text-foreground' : 'bg-primary text-primary-foreground'
: takeover ? 'bg-background border-transparent hover:bg-muted text-foreground' : 'hover:bg-muted text-foreground'
}`}
>
<span className={takeover
? `grid place-items-center w-8 h-8 flex-shrink-0 rounded-lg border ${isSelected ? 'bg-primary text-primary-foreground border-primary' : 'bg-muted border-border text-muted-foreground'}`
: 'mt-0.5 flex-shrink-0 opacity-80'}
>
<Icon className="w-4 h-4" />
</span>
<span className="flex-1 min-w-0">
<span className={`block font-mono font-medium truncate ${takeover ? 'text-base' : 'text-sm'}`}>
{renderHighlighted(item.label, item.ranges)}
</span>
{item.detail && (
<span className={`block text-xs opacity-70 mt-0.5 ${isExpanded ? 'whitespace-pre-wrap break-words' : 'truncate'}`}>
{item.detail}
</span>
)}
</span>
{item.tag && (
<span className="flex-shrink-0 text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded border border-border opacity-80">
{item.tag}
</span>
)}
</button>
</div>
)
})
if (takeover) {
return (
<div
ref={listRef}
data-testid="prompt-suggestions"
style={{ height: takeoverHeight }}
className="absolute bottom-full left-0 right-0 mb-2 z-50 overflow-y-auto overscroll-contain rounded-xl bg-background/95 backdrop-blur-md border border-border shadow-xl animate-prompt-takeover-rise"
>
<div className="min-h-full flex flex-col justify-end gap-0.5 p-1.5">
{rows.reverse()}
</div>
</div>
)
}
return (
<div
ref={listRef}
data-testid="prompt-suggestions"
className="absolute bottom-full left-0 right-0 mb-2 z-50 bg-background border border-border rounded-lg shadow-xl max-h-48 md:max-h-[40vh] lg:max-h-[50vh] overflow-y-auto"
>
{rows}
</div>
)
}
function renderHighlighted(label: string, ranges: MatchRange[]): ReactNode {
if (ranges.length === 0) return label
const parts: ReactNode[] = []
let cursor = 0
for (const [start, end] of ranges) {
if (start > cursor) parts.push(label.slice(cursor, start))
parts.push(
<span key={start} className="font-bold underline decoration-2 underline-offset-2">
{label.slice(start, end)}
</span>,
)
cursor = end
}
if (cursor < label.length) parts.push(label.slice(cursor))
return parts
}
function useTakeoverHeight(listRef: RefObject<HTMLDivElement | null>, enabled: boolean) {
const [height, setHeight] = useState<number>(TAKEOVER_MIN_HEIGHT_PX)
useLayoutEffect(() => {
if (!enabled) return
const anchor = listRef.current?.parentElement
if (!anchor) return
const boundary = findClippingAncestor(anchor)
const measure = () => {
const boundaryTop = boundary ? boundary.getBoundingClientRect().top : (window.visualViewport?.offsetTop ?? 0)
const available = anchor.getBoundingClientRect().top - boundaryTop - TAKEOVER_TOP_GAP_PX
setHeight(Math.max(TAKEOVER_MIN_HEIGHT_PX, available))
}
measure()
const resizeObserver = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure)
resizeObserver?.observe(anchor)
if (boundary) resizeObserver?.observe(boundary)
const viewport = window.visualViewport
viewport?.addEventListener('resize', measure)
viewport?.addEventListener('scroll', measure)
return () => {
resizeObserver?.disconnect()
viewport?.removeEventListener('resize', measure)
viewport?.removeEventListener('scroll', measure)
}
}, [enabled, listRef])
return height
}
function findClippingAncestor(element: HTMLElement): HTMLElement | null {
for (let current = element.parentElement; current; current = current.parentElement) {
const { overflowY } = getComputedStyle(current)
if (overflowY === 'hidden' || overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'clip') return current
}
return null
}
@@ -103,19 +103,12 @@ describe('MoreDrawer', () => {
vi.clearAllMocks()
vi.mocked(useNavigate).mockReturnValue(vi.fn())
vi.mocked(useCommands).mockReturnValue({
commands: [],
commands: [{ name: 'help', description: 'Show help' }],
recentNames: [],
loading: false,
error: null,
filterCommands: vi.fn().mockReturnValue([
{
name: 'help',
description: 'Show help',
template: '',
agent: '',
model: '',
hints: [],
},
]),
searchCommands: vi.fn(),
findCommand: vi.fn(),
})
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
@@ -38,7 +38,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const isSessionDetail = /^\/repos\/\d+\/sessions\/[^/]+$/.test(location.pathname)
const isAssistantRoute = isAssistantPath(location.pathname)
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
const { filterCommands } = useCommands({ enabled: isSessionDetail })
const { commands } = useCommands({ enabled: isSessionDetail })
const activePromptFileBasePath = useUIState((state) => state.activePromptFileBasePath)
const selectPromptCommand = useUIState((state) => state.selectPromptCommand)
const selectPromptFile = useUIState((state) => state.selectPromptFile)
@@ -121,7 +121,6 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const assistantCta = isSessionDetail && !isAssistantSession
? buildNavModel(location.pathname).primary.find((cta) => cta.key === 'assistant')
: undefined
const commands = filterCommands('')
const opencodeVersion = health?.opencodeVersion
const managerVersion = health?.opencodeManagerVersion
@@ -75,7 +75,10 @@ export function SideQuestionDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogTitle>Side question</DialogTitle>
<div className="flex items-center gap-2 pr-6">
<DialogTitle className="flex-1">Side question</DialogTitle>
{answer && !pending && <CopyButton content={answer} title="Copy answer" />}
</div>
<form onSubmit={handleSubmit} className="flex items-center gap-2 mt-4">
<Input
value={question}
@@ -102,11 +105,8 @@ export function SideQuestionDialog({
</div>
)}
{answer && !pending && (
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1 max-h-[50vh] overflow-y-auto">
<TextPart text={answer} />
</div>
<CopyButton content={answer} title="Copy answer" />
<div className="min-w-0 max-h-[50vh] overflow-y-auto">
<TextPart text={answer} />
</div>
)}
</DialogContent>
+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,
+15
View File
@@ -184,6 +184,21 @@ body {
animation: voice-overlay-in 180ms cubic-bezier(0.2, 0.9, 0.3, 1);
}
@keyframes prompt-takeover-rise {
from { transform: translateY(24px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.animate-prompt-takeover-rise {
animation: prompt-takeover-rise 240ms cubic-bezier(0.2, 1.2, 0.4, 1);
}
@media (prefers-reduced-motion: reduce) {
.animate-prompt-takeover-rise {
animation: none;
}
}
@keyframes shine-loading {
0% {
background-position: -200% 0;
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest'
import { matchText, rankByMatch } from './fuzzyMatch'
describe('matchText', () => {
it.each([
['review', 'review', 0, [[0, 6]]],
['rev', 'review', 1, [[0, 3]]],
['pr', 'plan-review', 2, [[0, 1], [5, 6]]],
['view', 'review', 3, [[2, 6]]],
['rvw', 'review', 4, [[0, 1], [2, 3], [5, 6]]],
])('matches %j against %j at tier %i', (query, name, tier, ranges) => {
expect(matchText(query, name)).toEqual({ tier, ranges })
})
it('falls back to the description without highlighting the name', () => {
expect(matchText('deploy', 'ship', 'Deploy a preview')).toEqual({ tier: 5, ranges: [] })
})
it('returns null when nothing matches', () => {
expect(matchText('xyz', 'review', 'Review changes')).toBeNull()
})
})
describe('rankByMatch', () => {
const items = ['fix-tests', 'format-code', 'fetch', 'test']
it('orders by tier, then recency, then name', () => {
const ranked = rankByMatch(items, 'ft', { getName: (item) => item, recent: ['format-code'] })
expect(ranked.map(({ item }) => item)).toEqual(['fix-tests', 'format-code', 'fetch'])
expect(rankByMatch(items, 'f', { getName: (item) => item, recent: ['format-code'] }).map(({ item }) => item))
.toEqual(['format-code', 'fetch', 'fix-tests'])
})
})
+99
View File
@@ -0,0 +1,99 @@
export type MatchRange = [start: number, end: number]
export interface TextMatch {
tier: number
ranges: MatchRange[]
}
export interface RankedMatch<T> {
item: T
tier: number
ranges: MatchRange[]
}
interface RankOptions<T> {
getName: (item: T) => string
getDescription?: (item: T) => string | undefined
recent?: string[]
}
const SEGMENT_SEPARATOR = /[-_./\s]/
const MIN_DESCRIPTION_QUERY_LENGTH = 3
/**
* Matches a query against a name, falling back to the description for queries of three or more characters.
* Lower tiers are better: exact, prefix, segment acronym, substring, subsequence, description.
*/
export function matchText(query: string, name: string, description?: string): TextMatch | null {
const needle = query.toLowerCase()
const haystack = name.toLowerCase()
if (!needle) return { tier: 0, ranges: [] }
if (haystack === needle) return { tier: 0, ranges: [[0, haystack.length]] }
if (haystack.startsWith(needle)) return { tier: 1, ranges: [[0, needle.length]] }
const acronym = matchPositions(needle, haystack, segmentStarts(haystack))
if (acronym) return { tier: 2, ranges: toRanges(acronym) }
const index = haystack.indexOf(needle)
if (index !== -1) return { tier: 3, ranges: [[index, index + needle.length]] }
const subsequence = matchPositions(needle, haystack, haystack.split('').map((_, position) => position))
if (subsequence) return { tier: 4, ranges: toRanges(subsequence) }
if (needle.length >= MIN_DESCRIPTION_QUERY_LENGTH && description?.toLowerCase().includes(needle)) return { tier: 5, ranges: [] }
return null
}
/**
* Filters and orders items by match tier, then by position in `recent`, then alphabetically.
* An empty query lists recent items first, followed by the rest alphabetically.
*/
export function rankByMatch<T>(items: T[], query: string, options: RankOptions<T>): RankedMatch<T>[] {
const recent = options.recent ?? []
const recentIndex = (item: T) => {
const index = recent.indexOf(options.getName(item))
return index === -1 ? recent.length : index
}
return items
.flatMap((item) => {
const match = matchText(query, options.getName(item), options.getDescription?.(item))
return match ? [{ item, match }] : []
})
.sort((a, b) =>
a.match.tier - b.match.tier
|| recentIndex(a.item) - recentIndex(b.item)
|| options.getName(a.item).localeCompare(options.getName(b.item)),
)
.map(({ item, match }) => ({ item, tier: match.tier, ranges: match.ranges }))
}
function segmentStarts(text: string): number[] {
return text.split('').flatMap((char, index) =>
!SEGMENT_SEPARATOR.test(char) && (index === 0 || SEGMENT_SEPARATOR.test(text[index - 1])) ? [index] : [],
)
}
function matchPositions(needle: string, haystack: string, candidates: number[]): number[] | null {
const positions: number[] = []
let cursor = 0
for (const char of needle) {
while (cursor < candidates.length && haystack[candidates[cursor]] !== char) cursor++
if (cursor === candidates.length) return null
positions.push(candidates[cursor])
cursor++
}
return positions
}
function toRanges(positions: number[]): MatchRange[] {
return positions.reduce<MatchRange[]>((ranges, position) => {
const last = ranges[ranges.length - 1]
if (last && last[1] === position) {
last[1] = position + 1
return ranges
}
ranges.push([position, position + 1])
return ranges
}, [])
}
+13 -11
View File
@@ -10,9 +10,9 @@ export interface MentionTrigger {
query: string
}
export interface AgentInfo {
name: string
description?: string
export interface MentionItem {
type: 'file' | 'agent' | 'skill'
value: string
}
export function detectMentionTrigger(
@@ -32,13 +32,6 @@ export function detectMentionTrigger(
}
}
export function filterAgentsByQuery(agents: AgentInfo[], query: string): AgentInfo[] {
const lowerQuery = query.toLowerCase()
return agents.filter(agent =>
agent.name.toLowerCase().includes(lowerQuery)
)
}
export interface ParsedPromptInput {
text: string
files: PromptFileInput[]
@@ -50,11 +43,14 @@ export function parsePromptToInput(
rawInput: string,
fileMap: Map<string, FileAttachmentInfo>,
agentNames: string[],
skillIds: string[],
imageAttachments?: ImageAttachment[]
): ParsedPromptInput {
const files: PromptFileInput[] = []
const agents: PromptAgentInput[] = []
const skills: PromptSkillInput[] = []
const agentNameByLowercase = new Map(agentNames.map((name) => [name.toLowerCase(), name]))
const skillIdByLowercase = new Map(skillIds.map((id) => [id.toLowerCase(), id]))
for (const match of rawInput.matchAll(MENTION_PATTERN)) {
const matchIndex = match.index!
@@ -70,6 +66,12 @@ export function parsePromptToInput(
const agentName = agentNameByLowercase.get(mentionText.toLowerCase())
if (agentName) {
agents.push({ name: agentName, mention })
continue
}
const skillId = skillIdByLowercase.get(mentionText.toLowerCase())
if (skillId && !skills.some((skill) => skill.id === skillId)) {
skills.push({ id: skillId, mention })
}
}
@@ -77,7 +79,7 @@ export function parsePromptToInput(
files.push({ uri: attachment.dataUrl, name: attachment.filename })
}
return { text: rawInput, files, agents, skills: [] }
return { text: rawInput, files, agents, skills }
}
export function getFilename(path: string): string {
@@ -0,0 +1,25 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
const MAX_RECENT_COMMANDS = 5
interface RecentCommandsStore {
names: string[]
recordCommand: (name: string) => void
}
export const useRecentCommandsStore = create<RecentCommandsStore>()(
persist(
(set) => ({
names: [],
recordCommand: (name: string) =>
set((state) => ({
names: [name, ...state.names.filter((existing) => existing !== name)].slice(0, MAX_RECENT_COMMANDS),
})),
}),
{
name: 'opencode-recent-commands',
partialize: (state) => ({ names: state.names }),
}
)
)