Initial release v0.2.5

This commit is contained in:
Chris Scott committed 2025-11-23 23:25:27 -05:00
commit bbf66c259b
158 files changed
+37115

No files matched your search

@@ -0,0 +1,83 @@
import { useEffect, useRef } from 'react'
interface FileSuggestionsProps {
isOpen: boolean
query: string
files: string[]
onSelect: (file: string) => void
onClose: () => void
position: { bottom: number, left: number, width: number }
selectedIndex?: number
}
export function FileSuggestions({
isOpen,
files,
onSelect,
onClose,
position,
selectedIndex = 0
}: FileSuggestionsProps) {
const listRef = useRef<HTMLDivElement>(null)
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 || files.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="fixed bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl z-50 max-h-64 overflow-y-auto"
style={{
bottom: `${position.bottom}px`,
left: `${position.left}px`,
width: `${position.width}px`
}}
>
{files.map((file, idx) => (
<button
key={file}
onClick={() => onSelect(file)}
className={`w-full px-3 py-2 text-left transition-colors ${
idx === selectedIndex
? 'bg-blue-600 text-white'
: 'hover:bg-zinc-800 text-zinc-100'
}`}
>
<div className="font-mono text-sm font-medium">
{getFilename(file)}
</div>
<div className="text-xs opacity-70 mt-0.5">
{getDirectory(file)}
</div>
</button>
))}
</div>
)
}
@@ -0,0 +1,146 @@
import type { components } from '@/api/opencode-types'
import { Copy } from 'lucide-react'
import { TextPart } from './TextPart'
import { PatchPart } from './PatchPart'
import { ToolCallPart } from './ToolCallPart'
type Part = components['schemas']['Part']
interface MessagePartProps {
part: Part
role?: string
allParts?: Part[]
partIndex?: number
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function getCopyableContent(part: Part, allParts?: Part[]): string {
switch (part.type) {
case 'text':
return part.text || ''
case 'patch':
return `Patch: ${part.hash}\nFiles: ${part.files.join(', ')}`
case 'tool':
if (part.state.status === 'completed' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
} else if (part.state.status === 'running' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
}
return `Tool: ${part.tool} (${part.state.status})`
case 'reasoning':
return part.text || ''
case 'snapshot':
return part.snapshot || ''
case 'agent':
return `Agent: ${part.name}`
case 'step-start':
return 'Starting step...'
case 'step-finish':
if (allParts) {
return allParts
.filter(p => p.type === 'text')
.map(p => p.text || '')
.join('\n\n')
.trim()
}
return ''
case 'file':
return part.filename || part.url || 'File'
default:
return ''
}
}
function CopyButton({ content, title, className = "" }: { content: string; title: string; className?: string }) {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
if (!content.trim()) {
return null
}
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
>
<Copy className="w-4 h-4" />
</button>
)
}
export function MessagePart({ part, role, allParts, partIndex, onFileClick }: MessagePartProps) {
const copyableContent = getCopyableContent(part, allParts)
switch (part.type) {
case 'text':
if (role === 'user' && allParts && partIndex !== undefined) {
const nextPart = allParts[partIndex + 1]
if (nextPart && nextPart.type === 'file') {
return null
}
}
return <TextPart part={part} />
case 'patch':
return <PatchPart part={part} />
case 'tool':
return <ToolCallPart part={part} onFileClick={onFileClick} />
case 'reasoning':
return (
<details className="border border-zinc-800 rounded-lg my-2">
<summary className="px-4 py-2 bg-zinc-900 hover:bg-zinc-800 cursor-pointer text-sm font-medium">
Reasoning
</summary>
<div className="p-4 bg-zinc-950 text-sm text-zinc-300 whitespace-pre-wrap">
{part.text}
</div>
</details>
)
case 'snapshot':
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500 font-mono">Snapshot: {part.snapshot}</div>
</div>
)
case 'agent':
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-sm font-medium text-blue-400">Agent: {part.name}</div>
</div>
)
case 'step-start':
return (
<div className="text-xs text-muted-foreground my-1">
→ Starting step...
</div>
)
case 'step-finish':
return (
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
<span>✓ Step complete • ${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
<CopyButton content={copyableContent} title="Copy step complete" />
</div>
)
case 'file':
return (
<span className="inline-flex items-center gap-1 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-sm text-zinc-300">
<span className="text-blue-400">@</span>
<span className="font-medium">{part.filename || 'File'}</span>
</span>
)
default:
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500">Unknown part type</div>
</div>
)
}
}
@@ -0,0 +1,109 @@
import { useMessages } from '@/hooks/useOpenCode'
import { MessagePart } from './MessagePart'
import type { MessageWithParts } from '@/api/types'
interface MessageThreadProps {
opcodeUrl: string
sessionID: string
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const isMessageThinking = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return msg.parts.length === 0 && isMessageStreaming(msg)
}
export function MessageThread({ opcodeUrl, sessionID, directory, onFileClick }: MessageThreadProps) {
const { data: messages, isLoading, error } = useMessages(opcodeUrl, sessionID, directory)
if (isLoading) {
return (
<div className="flex items-center justify-center h-full text-zinc-500">
Loading messages...
</div>
)
}
if (error) {
return (
<div className="flex items-center justify-center h-full text-red-400">
Error loading messages: {error instanceof Error ? error.message : 'Unknown error'}
</div>
)
}
if (!messages || messages.length === 0) {
return (
<div className="flex items-center justify-center h-full text-zinc-600">
No messages yet. Start a conversation below.
</div>
)
}
return (
<div className="flex flex-col space-y-2 p-4">
{messages.map((msg) => {
const streaming = isMessageStreaming(msg)
const thinking = isMessageThinking(msg)
return (
<div
key={msg.info.id}
className="flex flex-col"
>
<div
className={`w-full rounded-lg p-2 ${
msg.info.role === 'user'
? 'bg-blue-600/20 border border-blue-600/30'
: 'bg-card/50 border border-border'
} ${streaming ? 'animate-pulse-subtle' : ''}`}
>
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-medium text-zinc-400">
{msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')}
</span>
{msg.info.time && (
<span className="text-xs text-muted-foreground">
{new Date(msg.info.time.created).toLocaleTimeString()}
</span>
)}
{streaming && (
<span className="text-xs text-blue-400 flex items-center gap-1">
<span className="animate-pulse">●</span> <span className="shine-loading">Generating...</span>
</span>
)}
</div>
{thinking ? (
<div className="flex items-center gap-2 text-zinc-500">
<span className="animate-pulse">▋</span>
<span className="text-sm shine-loading">Thinking...</span>
</div>
) : (
<div className="space-y-2">
{msg.parts.map((part, index) => (
<div key={`${msg.info.id}-${part.id}-${index}`}>
<MessagePart
part={part}
role={msg.info.role}
allParts={msg.parts}
partIndex={index}
onFileClick={onFileClick}
/>
</div>
))}
</div>
)}
</div>
</div>
)
})}
</div>
)
}
@@ -0,0 +1,38 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
type PatchPart = components['schemas']['PatchPart']
interface PatchPartProps {
part: PatchPart
}
export function PatchPart({ part }: PatchPartProps) {
const [expanded, setExpanded] = useState(true)
return (
<div className="border border-zinc-800 rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-zinc-900 hover:bg-zinc-800 text-left flex items-center justify-between text-sm"
>
<span className="font-medium">
File Changes ({part.files.length} file{part.files.length !== 1 ? 's' : ''})
</span>
<span className="text-zinc-400 text-xs font-mono">{part.hash.slice(0, 8)}</span>
</button>
{expanded && (
<div className="bg-zinc-950 p-4">
<div className="space-y-2">
{part.files.map((file, index) => (
<div key={index} className="text-sm">
<div className="font-mono text-zinc-400 mb-1">{file}</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,605 @@
import { useState, useRef, useEffect, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell } from '@/hooks/useOpenCode'
import { useSettings } from '@/hooks/useSettings'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
import { useMobile } from '@/hooks/useMobile'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { FileSuggestions } from './FileSuggestions'
import { detectMentionTrigger, parsePromptToParts, getFilename } from '@/lib/promptParser'
import { getModel, formatModelName } from '@/api/providers'
import type { components } from '@/api/opencode-types'
import type { MessageWithParts, FileInfo } from '@/api/types'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
type CommandType = components['schemas']['Command']
interface PromptInputProps {
opcodeUrl: string
directory?: string
sessionID: string
disabled?: boolean
onShowSessionsDialog?: () => void
onShowModelsDialog?: () => void
onShowHelpDialog?: () => void
}
export function PromptInput({
opcodeUrl,
directory,
sessionID,
disabled,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
}: PromptInputProps) {
const [prompt, setPrompt] = useState('')
const [modelName, setModelName] = useState<string>('')
const [isBashMode, setIsBashMode] = useState(false)
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
const [suggestionPosition, setSuggestionPosition] = useState({ bottom: 0, left: 0, width: 0 })
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileInfo>())
const [showFileSuggestions, setShowFileSuggestions] = useState(false)
const [fileQuery, setFileQuery] = useState('')
const [fileSuggestionPosition, setFileSuggestionPosition] = useState({ bottom: 0, left: 0, width: 0 })
const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null)
const [selectedFileIndex, setSelectedFileIndex] = useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const isMobile = useMobile()
const textareaRef = useRef<HTMLTextAreaElement>(null)
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory)
const { data: messages } = useMessages(opcodeUrl, sessionID, directory)
const { preferences, updateSettings } = useSettings()
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
sessionID,
directory,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
})
const { files: searchResults } = useFileSearch(
opcodeUrl,
fileQuery,
showFileSuggestions,
directory
)
const handleSubmit = () => {
if (!prompt.trim() || disabled) return
if (isBashMode) {
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
sendShell.mutate({
sessionID,
command,
agent: currentMode
})
setPrompt('')
setIsBashMode(false)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
return
}
const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/)
if (commandMatch) {
const [, commandName] = commandMatch
const command = filterCommands(commandName)[0]
if (command) {
executeCommand(command)
setPrompt('')
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
return
}
}
const parts = parsePromptToParts(prompt, attachedFiles)
sendPrompt.mutate({
sessionID,
parts,
model: currentModel,
agent: currentMode
})
setPrompt('')
setAttachedFiles(new Map())
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
}
const handleStop = () => {
abortSession.mutate(sessionID)
}
const handleCommandSelect = async (command: CommandType) => {
if (!textareaRef.current) return
setShowSuggestions(false)
setSuggestionQuery('')
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const beforeCommand = prompt.slice(0, commandMatch.index)
const afterCommand = prompt.slice(cursorPosition)
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
}
const handleFileSelect = (filePath: string) => {
if (!mentionRange || !textareaRef.current) return
const filename = getFilename(filePath)
const beforeMention = prompt.slice(0, mentionRange.start)
const afterMention = prompt.slice(mentionRange.end)
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = filePath.startsWith('/')
? filePath
: directory
? `${directory}/${filePath}`
: filePath
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
})
return next
})
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
const handleModeToggle = () => {
const newMode = currentMode === 'plan' ? 'build' : 'plan'
updateSettings({ mode: newMode })
}
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (isBashMode && e.key === 'Escape') {
e.preventDefault()
setIsBashMode(false)
setPrompt('')
return
}
if (showFileSuggestions && searchResults.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedFileIndex(prev =>
prev < searchResults.length - 1 ? prev + 1 : prev
)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedFileIndex(prev => prev > 0 ? prev - 1 : 0)
return
}
if (e.key === 'Enter') {
e.preventDefault()
if (searchResults[selectedFileIndex]) {
handleFileSelect(searchResults[selectedFileIndex])
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
return
}
}
if (showSuggestions) {
const filteredCommands = filterCommands(suggestionQuery)
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedCommandIndex(prev => (prev + 1) % filteredCommands.length)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedCommandIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length)
return
}
if (e.key === 'Enter') {
e.preventDefault()
const selectedCommand = filteredCommands[selectedCommandIndex]
if (selectedCommand) {
handleCommandSelect(selectedCommand)
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowSuggestions(false)
setSuggestionQuery('')
setSelectedCommandIndex(0)
return
}
}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
handleSubmit()
} else if (e.key === 'Escape') {
setShowSuggestions(false)
setSuggestionQuery('')
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
setPrompt('')
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
}
}
const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value
if (value === '!' && prompt === '') {
setIsBashMode(true)
setPrompt(value)
return
}
if (isBashMode && value === '') {
setIsBashMode(false)
}
setPrompt(value)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
}
if (isBashMode) {
return
}
const cursorPosition = e.target.selectionStart
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
if (mentionTrigger) {
setFileQuery(mentionTrigger.query)
setMentionRange({ start: mentionTrigger.start, end: mentionTrigger.end })
setShowFileSuggestions(true)
setSelectedFileIndex(0)
if (textareaRef.current) {
const rect = textareaRef.current.getBoundingClientRect()
setFileSuggestionPosition({
bottom: window.innerHeight - rect.top + window.scrollY + 4,
left: rect.left + window.scrollX,
width: rect.width
})
}
} 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)
if (textareaRef.current) {
const rect = textareaRef.current.getBoundingClientRect()
setSuggestionPosition({
bottom: window.innerHeight - rect.top + window.scrollY + 4,
left: rect.left + window.scrollX,
width: rect.width
})
}
} else {
setShowSuggestions(false)
setSuggestionQuery('')
}
if (showFileSuggestions) {
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
}
}
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const hasActiveStream = messages?.some(msg => isMessageStreaming(msg)) || false
const currentMode = preferences?.mode || 'build'
const currentModel = preferences?.defaultModel || ''
const modeColor = currentMode === 'plan' ? 'text-yellow-600 dark:text-yellow-500' : 'text-green-600 dark:text-green-500'
const modeBg = currentMode === 'plan' ? 'bg-yellow-500/10 border-yellow-500/30' : 'bg-green-500/10 border-green-500/30'
useEffect(() => {
const loadModelName = async () => {
if (currentModel) {
try {
const [providerId, modelId] = currentModel.split('/')
if (providerId && modelId) {
const model = await getModel(providerId, modelId)
if (model) {
setModelName(formatModelName(model))
} else {
setModelName(currentModel)
}
} else {
setModelName(currentModel)
}
} catch {
setModelName(currentModel)
}
} else {
setModelName('No model selected')
}
}
loadModelName()
}, [currentModel])
useEffect(() => {
if (textareaRef.current && !disabled && !hasActiveStream) {
textareaRef.current.focus()
}
}, [disabled, hasActiveStream])
return (
<div className="border-t border-border bg-background p-2 sm:p-3">
{isMobile ? (
<>
<div className="mb-2">
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Message..."
}
disabled={disabled || hasActiveStream}
className="w-full bg-background border rounded-lg px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed"
rows={1}
/>
</div>
<div className="flex gap-2 items-center justify-between mx-2">
<div className="flex gap-2 items-center">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName}
</button>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
title="Help"
>
?
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? 'Stop' : 'Send'}
</button>
</div>
</>
) : (
<>
<div className="flex gap-2 items-end mb-2 justify-between">
<div className="flex gap-2 items-end">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName}
</button>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
title="Help"
>
?
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex gap-2 items-end">
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Send a message... (Cmd/Ctrl+Enter)"
}
disabled={disabled || hasActiveStream}
className={`flex-1 bg-background border rounded-lg px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm ${
isBashMode
? 'border-purple-500/50 focus:ring-purple-500/50 bg-purple-500/5'
: 'border-border focus:ring-primary/50'
}`}
rows={1}
/>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? '■' : '↑'}
</button>
</div>
</>
)}
<CommandSuggestions
isOpen={showSuggestions}
query={suggestionQuery}
commands={filterCommands(suggestionQuery)}
onSelect={handleCommandSelect}
onClose={() => {
setShowSuggestions(false)
setSuggestionQuery('')
}}
position={suggestionPosition}
selectedIndex={selectedCommandIndex}
/>
<FileSuggestions
isOpen={showFileSuggestions}
query={fileQuery}
files={searchResults}
onSelect={handleFileSelect}
onClose={() => {
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
}}
position={fileSuggestionPosition}
selectedIndex={selectedFileIndex}
/>
</div>
)
}
@@ -0,0 +1,121 @@
import React from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import { Copy, Check } from 'lucide-react'
import type { components } from '@/api/opencode-types'
import 'highlight.js/styles/github-dark.css'
type TextPart = components['schemas']['TextPart']
interface TextPartProps {
part: TextPart
}
interface CodeBlockProps {
children?: React.ReactNode
className?: string
[key: string]: unknown
}
function CodeBlock({ children, className, ...props }: CodeBlockProps) {
const [copied, setCopied] = React.useState(false)
const extractTextContent = (node: React.ReactNode): string => {
if (typeof node === 'string') return node
if (typeof node === 'number') return node.toString()
if (Array.isArray(node)) return node.map(extractTextContent).join('')
if (React.isValidElement(node)) {
const element = node as React.ReactElement<any, any>
if (element.props.children) {
return extractTextContent(element.props.children as React.ReactNode)
}
}
return ''
}
const codeContent = extractTextContent(children)
const handleCopyCode = async () => {
try {
await navigator.clipboard.writeText(codeContent)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy code:', error)
}
}
return (
<div className="relative">
<pre className={`bg-accent p-4 rounded-lg overflow-x-auto border border-border my-4 ${className || ''}`} {...props}>
{children}
</pre>
<button
onClick={handleCopyCode}
className="absolute top-2 right-2 p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground"
title="Copy code"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</button>
</div>
)
}
export function TextPart({ part }: TextPartProps) {
if (!part.text || part.text.trim() === '') {
return (
<div className="text-muted-foreground italic text-sm">
[Empty message content]
</div>
)
}
return (
<div className="prose prose-invert prose-enhanced max-w-none text-foreground">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight, rehypeRaw]}
components={{
code({ className, children, ...props }) {
const isInline = !className || !className.includes('language-')
if (isInline) {
return (
<code className={className || "bg-accent px-1.5 py-0.5 rounded text-sm text-foreground"} {...props}>
{children}
</code>
)
}
return (
<code className={className} {...props}>
{children}
</code>
)
},
pre({ children }) {
return (
<CodeBlock>
{children}
</CodeBlock>
)
},
p({ children }) {
return <p className="text-foreground">{children}</p>
},
strong({ children }) {
return <strong className="font-semibold text-foreground">{children}</strong>
},
ul({ children }) {
return <ul className="list-disc text-foreground">{children}</ul>
},
ol({ children }) {
return <ol className="list-decimal text-foreground">{children}</ol>
}
}}
>
{part.text}
</ReactMarkdown>
</div>
)
}
@@ -0,0 +1,181 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
import { detectFileReferences } from '@/lib/fileReferences'
type ToolPart = components['schemas']['ToolPart']
interface ToolCallPartProps {
part: ToolPart
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
const jsonString = JSON.stringify(json, null, 2)
const references = detectFileReferences(jsonString)
if (references.length === 0) {
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{jsonString}</pre>
}
const parts: React.ReactNode[] = []
let lastIndex = 0
references.forEach((ref, index) => {
if (ref.startIndex > lastIndex) {
parts.push(jsonString.slice(lastIndex, ref.startIndex))
}
parts.push(
<span
key={`ref-${index}`}
onClick={(e) => {
e.stopPropagation()
onFileClick?.(ref.filePath)
}}
className="text-blue-300 hover:text-blue-200 cursor-pointer underline decoration-dotted"
title={`Click to open ${ref.filePath}`}
>
{ref.fullMatch}
</span>
)
lastIndex = ref.endIndex
})
if (lastIndex < jsonString.length) {
parts.push(jsonString.slice(lastIndex))
}
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{parts}</pre>
}
export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const defaultExpanded = preferences?.expandToolCalls ?? false
const [expanded, setExpanded] = useState(defaultExpanded)
const getStatusColor = () => {
switch (part.state.status) {
case 'completed':
return 'text-green-400'
case 'error':
return 'text-red-400'
case 'running':
return 'text-yellow-400'
default:
return 'text-zinc-400'
}
}
const getStatusIcon = () => {
switch (part.state.status) {
case 'completed':
return '✓'
case 'error':
return '✗'
case 'running':
return '⟳'
default:
return '○'
}
}
const getPreviewText = () => {
if (part.state.status === 'pending') return null
const input = part.state.input as Record<string, unknown>
if (!input) return null
switch (part.tool) {
case 'read':
case 'write':
case 'edit':
return (input.filePath as string) || null
case 'bash':
return (input.command as string) || null
case 'glob':
return (input.pattern as string) || null
case 'grep':
return (input.pattern as string) || null
case 'list':
return (input.path as string) || '.'
case 'task':
return (input.description as string) || null
default:
return null
}
}
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-card hover:bg-card-hover text-left flex items-center gap-2 text-sm"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.tool}</span>
{previewText && isFileTool ? (
<span
onClick={(e) => {
e.stopPropagation()
if (onFileClick) {
onFileClick(previewText)
}
}}
className="text-blue-300 text-xs truncate hover:text-blue-200 cursor-pointer underline decoration-dotted"
title={`Click to open ${previewText}`}
>
{previewText}
</span>
) : previewText ? (
<span className="text-zinc-400 text-xs truncate">{previewText}</span>
) : null}
<span className="text-muted-foreground text-xs ml-auto">({part.state.status})</span>
</button>
{expanded && (
<div className="bg-card p-4 space-y-2">
{part.state.status === 'running' && (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
{part.state.status === 'completed' && (
<>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">
{part.state.output}
</pre>
</div>
{part.state.time && (
<div className="text-xs text-zinc-500">
Duration: {((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
</div>
)}
</>
)}
{part.state.status === 'error' && (
<div className="text-sm">
<div className="text-red-400 mb-1">Error:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto text-red-300">
{part.state.error}
</pre>
</div>
)}
</div>
)}
</div>
)
}