mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(composer): unify prompt suggestions with fuzzy matching and a mobile keybar
This commit is contained in:
1 parent
704f81884b
commit
855b78297e
24 files changed
+1121
-399
No files matched your search
@@ -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: {
|
||||
@@ -50,6 +51,7 @@ vi.mock('@/hooks/useOpenCode', async () => {
|
||||
return {
|
||||
...actual,
|
||||
useAgents: () => ({ data: mocks.agents }),
|
||||
useSkills: () => ({ data: mocks.skills }),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -99,12 +101,12 @@ 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: () => null,
|
||||
}))
|
||||
|
||||
const createTestQueryClient = () => new QueryClient({
|
||||
@@ -174,11 +176,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({
|
||||
@@ -436,4 +439,68 @@ describe('PromptInput command submission', () => {
|
||||
await waitFor(() => expect(input).toHaveValue(''))
|
||||
expect(mocks.showToast.info).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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(),
|
||||
@@ -39,6 +40,7 @@ vi.mock('@/hooks/useOpenCode', async () => {
|
||||
return {
|
||||
...actual,
|
||||
useAgents: () => ({ data: mocks.agents }),
|
||||
useSkills: () => ({ data: mocks.skills }),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -90,12 +92,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({
|
||||
@@ -151,6 +149,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 +164,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' },
|
||||
@@ -221,6 +220,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()
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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,11 +1030,11 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
return
|
||||
}
|
||||
|
||||
if (showMentionSuggestions && mentionItems.length > 0) {
|
||||
if (showMentionSuggestions && mentionSuggestions.length > 0) {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
setSelectedMentionIndex(prev =>
|
||||
prev < mentionItems.length - 1 ? prev + 1 : prev
|
||||
prev < mentionSuggestions.length - 1 ? prev + 1 : prev
|
||||
)
|
||||
return
|
||||
}
|
||||
@@ -958,8 +1047,9 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
if (mentionItems[selectedMentionIndex]) {
|
||||
handleMentionSelect(mentionItems[selectedMentionIndex])
|
||||
const selectedMention = mentionSuggestions[selectedMentionIndex]
|
||||
if (selectedMention) {
|
||||
handleMentionSelect(selectedMention.value)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -974,25 +1064,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 + 1) % 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 - 1 + 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 +1101,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 +1132,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 +1151,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 +1316,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 +1465,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 +1492,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 +1656,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
|
||||
}
|
||||
Reference in new issue
Block a user