feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-02 21:51:37 -04:00
1 parent 3cc24288a6
commit c3d6549f01
133 files changed
+7284 -6293

No files matched your search

@@ -1,186 +0,0 @@
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useCreateKvEntry, useUpdateKvEntry } from '@/hooks/useMemories'
import type { KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
const kvSchema = z.object({
key: z.string().min(1, 'Key is required'),
data: z.string().min(1, 'Data is required'),
ttlHours: z.number().optional(),
})
type KvFormData = z.infer<typeof kvSchema>
interface KvFormDialogProps {
entry?: KvEntry
projectId?: string
open: boolean
onOpenChange: (open: boolean) => void
}
export function KvFormDialog({ entry, projectId, open, onOpenChange }: KvFormDialogProps) {
const createMutation = useCreateKvEntry()
const updateMutation = useUpdateKvEntry()
const [jsonError, setJsonError] = useState<string | undefined>()
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<KvFormData>({
resolver: zodResolver(kvSchema),
defaultValues: {
key: '',
data: '',
ttlHours: undefined,
},
})
useEffect(() => {
if (open) {
if (entry) {
const ttlMs = entry.expiresAt - entry.updatedAt
const ttlHoursValue = ttlMs > 0 && ttlMs < Number.MAX_SAFE_INTEGER
? Math.round(ttlMs / (1000 * 60 * 60))
: undefined
reset({
key: entry.key,
data: JSON.stringify(entry.data, null, 2),
ttlHours: ttlHoursValue,
})
} else {
reset({
key: '',
data: '',
ttlHours: undefined,
})
}
setJsonError(undefined)
}
}, [open, entry, reset])
const validateJson = (value: string): boolean => {
try {
JSON.parse(value)
setJsonError(undefined)
return true
} catch (e) {
setJsonError(e instanceof Error ? e.message : 'Invalid JSON')
return false
}
}
const onSubmit = async (data: KvFormData) => {
if (!validateJson(data.data)) {
return
}
const parsedData = JSON.parse(data.data)
const ttlMs = data.ttlHours ? data.ttlHours * 1000 * 60 * 60 : undefined
if (entry) {
const updateData: UpdateKvEntryRequest = {
data: parsedData,
ttlMs,
}
await updateMutation.mutateAsync({ projectId: projectId!, key: entry.key, data: updateData })
} else if (projectId) {
const createData: CreateKvEntryRequest = {
projectId,
key: data.key,
data: parsedData,
ttlMs,
}
await createMutation.mutateAsync(createData)
}
onOpenChange(false)
}
const isLoading = createMutation.isPending || updateMutation.isPending
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{entry ? 'Edit KV Entry' : 'Create KV Entry'}</DialogTitle>
<DialogDescription>
{entry
? 'Update the KV entry data and TTL.'
: 'Add a new key-value entry to store project data.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="key">Key</Label>
<Input
id="key"
{...register('key')}
placeholder="Enter key..."
disabled={!!entry}
/>
{errors.key && (
<p className="text-sm text-destructive">{errors.key.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="data">Data (JSON)</Label>
<Textarea
id="data"
{...register('data')}
placeholder='{"key": "value"}'
rows={6}
className="resize-none font-mono"
onBlur={(e) => validateJson(e.target.value)}
/>
{errors.data && (
<p className="text-sm text-destructive">{errors.data.message}</p>
)}
{jsonError && (
<p className="text-sm text-destructive">{jsonError}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="ttlHours">TTL (hours, optional)</Label>
<Input
id="ttlHours"
type="number"
min="0"
step="1"
{...register('ttlHours', { valueAsNumber: true })}
placeholder="Enter TTL in hours..."
/>
</div>
<DialogFooter className='flex gap-2 flex-wrap'>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit" disabled={isLoading || !!jsonError}>
{isLoading ? 'Saving...' : entry ? 'Update' : 'Create'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
-182
View File
@@ -1,182 +0,0 @@
import { useState } from 'react'
import { useKvEntries, useDeleteKvEntry } from '@/hooks/useMemories'
import { useDebounce } from '@/hooks/useDebounce'
import type { KvEntry } from '@opencode-manager/shared/types'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Loader2, Trash2, Key, ChevronDown, ChevronRight, Plus } from 'lucide-react'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { KvFormDialog } from './KvFormDialog'
interface KvListProps {
projectId?: string
}
function formatTimeRemaining(expiresAt: number): string {
const now = Date.now()
const diff = expiresAt - now
if (diff <= 0) {
return 'expired'
}
const hours = Math.floor(diff / (1000 * 60 * 60))
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
if (hours > 0) {
return `${hours}h ${minutes}m`
}
return `${minutes}m`
}
export function KvList({ projectId }: KvListProps) {
const [searchQuery, setSearchQuery] = useState<string>('')
const debouncedSearch = useDebounce(searchQuery, 300)
const [expandedKey, setExpandedKey] = useState<string | null>(null)
const [deleteKey, setDeleteKey] = useState<string | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editingEntry, setEditingEntry] = useState<KvEntry | undefined>(undefined)
const { data: entries, isLoading } = useKvEntries(projectId, debouncedSearch || undefined)
const deleteMutation = useDeleteKvEntry()
const handleDelete = () => {
if (deleteKey && projectId) {
deleteMutation.mutate({ projectId, key: deleteKey })
setDeleteKey(null)
}
}
const toggleExpand = (key: string) => {
setExpandedKey(expandedKey === key ? null : key)
}
const handleEdit = (entry: KvEntry) => {
setEditingEntry(entry)
setDialogOpen(true)
}
const handleCreate = () => {
setEditingEntry(undefined)
setDialogOpen(true)
}
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Input
placeholder="Filter by key prefix..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-64"
/>
<Button onClick={handleCreate} size="sm">
<Plus className="w-4 h-4 mr-2" />
Add KV Entry
</Button>
</div>
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : !entries || entries.length === 0 ? (
<div className="text-center p-8 text-muted-foreground">
<Key className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No KV entries found</p>
</div>
) : (
<div className="space-y-2">
{entries.map((entry: KvEntry) => {
const isExpanded = expandedKey === entry.key
const dataPreview = JSON.stringify(entry.data)
const formattedData = JSON.stringify(entry.data, null, 2)
const truncatedPreview = dataPreview.length > 100
? dataPreview.slice(0, 100) + '...'
: dataPreview
return (
<div
key={entry.key}
className="p-4 rounded-lg border border-border bg-card hover:bg-accent/50 transition-colors"
>
<div className="flex items-center justify-between gap-2 mb-2">
<div className="flex items-center gap-2 flex-wrap min-w-0 flex-1">
<Button
variant="ghost"
size="icon"
className="h-6 w-6 p-0"
onClick={() => toggleExpand(entry.key)}
>
{isExpanded ? (
<ChevronDown className="w-4 h-4" />
) : (
<ChevronRight className="w-4 h-4" />
)}
</Button>
<span className="font-medium truncate">{entry.key}</span>
<Badge
variant="outline"
className="text-xs bg-amber-600/20 text-amber-400 border-amber-600/40"
>
{formatTimeRemaining(entry.expiresAt)}
</Badge>
</div>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => handleEdit(entry)}
>
<Key className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive"
onClick={() => setDeleteKey(entry.key)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{truncatedPreview}
</div>
{isExpanded && (
<pre className="mt-2 p-2 bg-muted rounded text-xs overflow-auto max-h-64">
{formattedData}
</pre>
)}
<p className="text-xs text-muted-foreground mt-2">
Updated: {new Date(entry.updatedAt).toLocaleString()}
</p>
</div>
)
})}
</div>
)}
<DeleteDialog
open={deleteKey !== null}
onOpenChange={(open: boolean) => !open && setDeleteKey(null)}
onConfirm={handleDelete}
onCancel={() => setDeleteKey(null)}
title="Delete KV Entry"
description="Are you sure you want to delete this KV entry? This action cannot be undone."
itemName={deleteKey || undefined}
isDeleting={deleteMutation.isPending}
/>
<KvFormDialog
entry={editingEntry}
projectId={projectId}
open={dialogOpen}
onOpenChange={setDialogOpen}
/>
</div>
)
}
@@ -1,147 +0,0 @@
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useCreateMemory, useUpdateMemory } from '@/hooks/useMemories'
import type { Memory, CreateMemoryRequest, UpdateMemoryRequest } from '@opencode-manager/shared/types'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
const memorySchema = z.object({
content: z.string().min(1, 'Content is required').max(10000),
scope: z.enum(['convention', 'decision', 'context']),
})
type MemoryFormData = z.infer<typeof memorySchema>
interface MemoryFormDialogProps {
memory?: Memory
projectId?: string
open: boolean
onOpenChange: (open: boolean) => void
}
export function MemoryFormDialog({ memory, projectId, open, onOpenChange }: MemoryFormDialogProps) {
const createMutation = useCreateMemory()
const updateMutation = useUpdateMemory()
const {
register,
handleSubmit,
setValue,
watch,
reset,
formState: { errors },
} = useForm<MemoryFormData>({
resolver: zodResolver(memorySchema),
defaultValues: {
content: '',
scope: 'context',
},
})
const selectedScope = watch('scope')
useEffect(() => {
if (open) {
if (memory) {
reset({
content: memory.content,
scope: memory.scope,
})
} else {
reset({
content: '',
scope: 'context',
})
}
}
}, [open, memory, reset])
const onSubmit = async (data: MemoryFormData) => {
if (memory) {
const updateData: UpdateMemoryRequest = {
content: data.content,
scope: data.scope,
}
await updateMutation.mutateAsync({ id: memory.id, data: updateData })
} else if (projectId) {
const createData: CreateMemoryRequest = {
projectId,
content: data.content,
scope: data.scope,
}
await createMutation.mutateAsync(createData)
}
onOpenChange(false)
}
const isLoading = createMutation.isPending || updateMutation.isPending
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{memory ? 'Edit Memory' : 'Create Memory'}</DialogTitle>
<DialogDescription>
{memory
? 'Update the memory content and scope.'
: 'Add a new memory to store project knowledge.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="scope">Scope</Label>
<Select
value={selectedScope}
onValueChange={(value) => setValue('scope', value as MemoryFormData['scope'])}
>
<SelectTrigger>
<SelectValue placeholder="Select scope" />
</SelectTrigger>
<SelectContent>
<SelectItem value="convention">Convention</SelectItem>
<SelectItem value="decision">Decision</SelectItem>
<SelectItem value="context">Context</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="content">Content</Label>
<Textarea
id="content"
{...register('content')}
placeholder="Enter memory content..."
rows={5}
className="resize-none"
/>
{errors.content && (
<p className="text-sm text-destructive">{errors.content.message}</p>
)}
</div>
<DialogFooter className='flex gap-2 flex-wrap'>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Saving...' : memory ? 'Update' : 'Create'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -1,146 +0,0 @@
import { useState } from 'react'
import { useMemories, useDeleteMemory } from '@/hooks/useMemories'
import { useDebounce } from '@/hooks/useDebounce'
import type { Memory } from '@opencode-manager/shared/types'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Loader2, Trash2, Edit, Search } from 'lucide-react'
import { MemoryFormDialog } from './MemoryFormDialog'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
interface MemoryListProps {
projectId?: string
scope?: string
showFilters?: boolean
}
const scopeColors: Record<string, string> = {
convention: 'bg-blue-600/20 text-blue-400 border-blue-600/40',
decision: 'bg-green-600/20 text-green-400 border-green-600/40',
context: 'bg-purple-600/20 text-purple-400 border-purple-600/40',
}
export function MemoryList({ projectId, scope, showFilters = true }: MemoryListProps) {
const [filterScope, setFilterScope] = useState<string>(scope || 'all')
const [searchQuery, setSearchQuery] = useState<string>('')
const debouncedSearch = useDebounce(searchQuery, 300)
const [editMemory, setEditMemory] = useState<Memory | null>(null)
const [deleteMemoryId, setDeleteMemoryId] = useState<number | null>(null)
const filters = {
projectId,
scope: filterScope !== 'all' ? filterScope : undefined,
...(debouncedSearch ? { content: debouncedSearch } : undefined),
}
const { data: memories, isLoading } = useMemories(filters)
const deleteMutation = useDeleteMemory()
const handleDelete = () => {
if (deleteMemoryId !== null) {
deleteMutation.mutate(deleteMemoryId)
setDeleteMemoryId(null)
}
}
return (
<div className="space-y-4">
{showFilters && (
<div className="flex flex-wrap gap-2 items-center">
<Input
placeholder="Search memories..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-64"
/>
<Select value={filterScope} onValueChange={setFilterScope}>
<SelectTrigger className="w-36">
<SelectValue placeholder="Scope" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Scopes</SelectItem>
<SelectItem value="convention">Convention</SelectItem>
<SelectItem value="decision">Decision</SelectItem>
<SelectItem value="context">Context</SelectItem>
</SelectContent>
</Select>
</div>
)}
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : memories && memories.length === 0 ? (
<div className="text-center p-8 text-muted-foreground">
<Search className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No memories found</p>
</div>
) : (
<div className="space-y-2">
{memories?.map((memory) => (
<div
key={memory.id}
className="p-4 rounded-lg border border-border bg-card hover:bg-accent/50 transition-colors"
>
<div className="flex items-center justify-between gap-2 mb-2">
<div className="flex items-center gap-2 flex-wrap min-w-0">
<Badge className={`text-xs ${scopeColors[memory.scope]}`}>
{memory.scope}
</Badge>
{memory.filePath && (
<span className="text-xs text-muted-foreground truncate max-w-xs">
{memory.filePath}
</span>
)}
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setEditMemory(memory)}
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive"
onClick={() => setDeleteMemoryId(memory.id)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
<p className="text-sm whitespace-pre-wrap break-words">{memory.content}</p>
<p className="text-xs text-muted-foreground mt-2">
Created: {new Date(memory.createdAt).toLocaleDateString()}
</p>
</div>
))}
</div>
)}
{editMemory && (
<MemoryFormDialog
memory={editMemory}
projectId={projectId}
open={!!editMemory}
onOpenChange={(open: boolean) => !open && setEditMemory(null)}
/>
)}
<DeleteDialog
open={deleteMemoryId !== null}
onOpenChange={(open: boolean) => !open && setDeleteMemoryId(null)}
onConfirm={handleDelete}
onCancel={() => setDeleteMemoryId(null)}
title="Delete Memory"
description="Are you sure you want to delete this memory? This action cannot be undone."
/>
</div>
)
}
@@ -47,7 +47,7 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => {
const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"]
const VOICE_SEND_SWIPE_THRESHOLD = 48
const VOICE_SEND_SWIPE_THRESHOLD = 30
type VoiceButtonVariant = 'desktop' | 'mobile'
@@ -63,7 +63,6 @@ interface PromptInputProps {
opcodeUrl: string
directory?: string
sessionID: string
repoId?: number
disabled?: boolean
showScrollButton?: boolean
isSessionActive?: boolean
@@ -81,7 +80,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
opcodeUrl,
directory,
sessionID,
repoId,
disabled,
showScrollButton,
isSessionActive = false,
@@ -177,7 +175,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState])
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory, sessionID, repoId)
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
@@ -241,7 +239,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
parts,
model: currentModel,
agent: agentUsed,
variant: currentVariant
variant: currentVariant,
queued: true
})
setStoredAgent(sessionID, agentUsed)
if (model) {
@@ -1241,10 +1240,10 @@ return (
</div>
<div className="flex items-center gap-1.5 md:gap-2 flex-shrink-0">
{isMobile && showScrollButton ? (
{isMobile && showScrollButton && !showVoiceFeedback ? (
<button
onClick={onScrollToBottom}
className="px-4 py-2 rounded-lg bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-all duration-200 active:scale-95 shadow-md flex items-center justify-center min-w-[52px] border border-border"
className="px-4 py-2 rounded-lg bg-black hover:bg-zinc-900 text-white transition-all duration-200 active:scale-95 shadow-md flex items-center justify-center min-w-[52px] border border-zinc-700"
title="Scroll to bottom"
>
<ArrowDown className="w-5 h-5" />
@@ -1252,7 +1251,7 @@ return (
) : !isMobile ? (
<button
onClick={onScrollToBottom}
className={`p-2 rounded-lg bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-all duration-200 active:scale-95 hover:scale-105 shadow-md ${showScrollButton ? 'visible' : 'invisible'}`}
className={`p-2 rounded-lg bg-black hover:bg-zinc-900 text-white transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border border-zinc-700 ${showScrollButton ? 'visible' : 'invisible'}`}
title="Scroll to bottom"
>
<ArrowDown className="w-6 h-6" />
@@ -1286,7 +1285,7 @@ return (
{sttEnabled && sttSupported && (
renderVoiceButton('desktop')
)}
{isMobile && !showScrollButton && sttEnabled && sttSupported && !hasPendingPermissionForSession && (
{isMobile && sttEnabled && sttSupported && !hasPendingPermissionForSession && (!showScrollButton || showVoiceFeedback) && (
renderVoiceButton('mobile')
)}
<button
@@ -1,8 +1,7 @@
import { useState, useMemo } from 'react'
import { ChevronDown, ChevronRight } from 'lucide-react'
import { useState, useMemo, useEffect, useRef } from 'react'
import { ChevronDown, ChevronRight, X } from 'lucide-react'
import { TodoItem } from './TodoItem'
import { useSessionTodosForSession } from '@/stores/sessionTodosStore'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import type { components } from '@/api/opencode-types'
export type Todo = components['schemas']['Todo']
@@ -11,12 +10,28 @@ interface SessionTodoDisplayProps {
sessionID: string | undefined
}
const todoSignature = (todos: Todo[]) =>
todos.map((t) => `${t.id}:${t.status}`).join(',')
export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
const todos = useSessionTodosForSession(sessionID)
const sessionStatus = useSessionStatusForSession(sessionID)
const [isCollapsed, setIsCollapsed] = useState(false)
const [isDismissed, setIsDismissed] = useState(false)
const dismissedSignatureRef = useRef<string>('')
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'compact' || sessionStatus.type === 'retry'
const signature = useMemo(() => todoSignature(todos), [todos])
useEffect(() => {
if (isDismissed && signature !== dismissedSignatureRef.current) {
setIsDismissed(false)
}
}, [signature, isDismissed])
const handleDismiss = (e: React.MouseEvent) => {
e.stopPropagation()
dismissedSignatureRef.current = signature
setIsDismissed(true)
}
const stats = useMemo(() => {
const completed = todos.filter((t) => t.status === 'completed').length
@@ -57,7 +72,7 @@ export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
)
}
if (!sessionID || !isSessionActive || todos.length === 0 || stats.completed === stats.total) {
if (!sessionID || todos.length === 0 || stats.completed === stats.total || isDismissed) {
return null
}
@@ -78,6 +93,13 @@ export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
style={{ width: `${stats.percentage}%` }}
/>
</div>
<button
onClick={handleDismiss}
className="ml-1 p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
aria-label="Dismiss tasks"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
</div>
)
@@ -99,6 +121,13 @@ export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
style={{ width: `${stats.percentage}%` }}
/>
</div>
<button
onClick={handleDismiss}
className="ml-1 p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
aria-label="Dismiss tasks"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
<div className="max-h-[80px] sm:max-h-[160px] overflow-y-auto p-1.5 sm:p-2 bg-muted/30">
{renderGroup('In Progress', inProgress)}
@@ -186,32 +186,6 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
}
if (isTodoTool) {
if (part.state.status === 'pending') {
return (
<div className="my-2 text-sm text-muted-foreground flex items-center gap-2">
<Loader2 className="w-3 h-3 animate-spin" />
<span>Preparing task list...</span>
</div>
)
}
if (part.state.status === 'running') {
return (
<div className="my-2 text-sm text-muted-foreground flex items-center gap-2">
<Loader2 className="w-3 h-3 animate-spin" />
<span>Updating task list...</span>
</div>
)
}
if (part.state.status === 'completed') {
return (
<div className="my-2 text-xs text-muted-foreground">
Task list updated
</div>
)
}
if (part.state.status === 'error') {
return (
<div className="my-2 text-sm text-red-600 dark:text-red-400">
@@ -8,31 +8,36 @@ interface VoiceStatusOverlayProps {
state: VoiceStatusOverlayState | null
}
function WaveformBars() {
return (
<div className="flex items-end gap-[3px] h-8">
{[0, 1, 2, 3, 4].map((i) => (
<div
key={i}
className="w-1.5 rounded-full bg-white"
style={{
height: '100%',
animation: `waveBar 0.9s ease-in-out infinite`,
animationDelay: `${i * 0.12}s`,
}}
/>
))}
<style>{`
@keyframes waveBar {
0%, 100% { transform: scaleY(0.2); }
50% { transform: scaleY(1); }
}
`}</style>
</div>
)
}
export function VoiceStatusOverlay({ show, label, state }: VoiceStatusOverlayProps) {
if (!show || !label || !state) {
return null
}
const isLoading = state === 'starting' || state === 'processing' || state === 'sending'
const showLoadingText = state !== 'starting'
const topLabel = state === 'readyToSend'
? 'Release'
: state === 'starting'
? 'Starting'
: state === 'processing'
? 'Transcribe'
: state === 'sending'
? 'Sending'
: 'Swipe'
const bottomLabel = state === 'starting'
? 'Mic'
: state === 'processing'
? 'Speech'
: state === 'sending'
? 'Prompt'
: state === 'readyToSend'
? 'Send'
: 'Send'
const actionWords = state === 'readyToSend'
? ['Release', 'To', 'Send']
: ['Swipe', 'To', 'Send']
@@ -47,12 +52,11 @@ export function VoiceStatusOverlay({ show, label, state }: VoiceStatusOverlayPro
<div className="absolute inset-x-1 top-1 h-10 rounded-full bg-white/20 blur-sm" />
<div className="relative flex flex-1 flex-col items-center justify-center gap-1">
{isLoading ? (
<>
state === 'processing' ? (
<WaveformBars />
) : (
<LoaderCircle className="h-6 w-6 animate-spin" />
{showLoadingText && (
<span className="text-[10px] font-bold uppercase leading-none tracking-wide">{topLabel}</span>
)}
</>
)
) : (
<>
<ArrowUp className="h-8 w-8 animate-bounce" />
@@ -64,11 +68,9 @@ export function VoiceStatusOverlay({ show, label, state }: VoiceStatusOverlayPro
</>
)}
</div>
{isLoading && showLoadingText ? (
<span className="relative text-[10px] font-bold uppercase leading-none tracking-wide">{bottomLabel}</span>
) : !isLoading ? (
{!isLoading && (
<X className="relative h-4 w-4" />
) : null}
)}
</div>
</div>
)
@@ -5,12 +5,10 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { DesktopSidebar } from './DesktopSidebar'
import * as useDesktopModule from '@/hooks/useDesktop'
import * as useSidebarCollapsedModule from '@/hooks/useSidebarCollapsed'
import * as useMemoryPluginStatusModule from '@/hooks/useMemoryPluginStatus'
import * as useAuthModule from '@/hooks/useAuth'
vi.mock('@/hooks/useDesktop')
vi.mock('@/hooks/useSidebarCollapsed')
vi.mock('@/hooks/useMemoryPluginStatus')
vi.mock('@/hooks/useAuth')
function LocationDisplay() {
@@ -44,7 +42,6 @@ describe('DesktopSidebar', () => {
it('returns null when user is not authenticated', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(false)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: false,
isLoading: false,
@@ -63,7 +60,6 @@ describe('DesktopSidebar', () => {
it('returns null when auth state is loading', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(false)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: true,
@@ -82,7 +78,6 @@ describe('DesktopSidebar', () => {
it('returns null when not desktop', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(false)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -101,7 +96,6 @@ describe('DesktopSidebar', () => {
it('renders primary CTA for root path', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -117,7 +111,6 @@ describe('DesktopSidebar', () => {
it('renders primary CTAs for repo detail', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -133,7 +126,6 @@ describe('DesktopSidebar', () => {
it('renders primary CTAs for session detail', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -149,7 +141,6 @@ describe('DesktopSidebar', () => {
it('renders primary CTA for schedules routes', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -166,7 +157,6 @@ describe('DesktopSidebar', () => {
const dispatchEventSpy = vi.spyOn(window, 'dispatchEvent')
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -188,7 +178,6 @@ describe('DesktopSidebar', () => {
it('opens dialog items by updating the dialog query param', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -211,7 +200,6 @@ describe('DesktopSidebar', () => {
it('opens settings by updating settings query params', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useMemoryPluginStatusModule, 'useMemoryPluginStatus').mockReturnValue({ memoryPluginEnabled: false })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
@@ -2,7 +2,6 @@ import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDesktop } from '@/hooks/useDesktop'
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
import { useMemoryPluginStatus } from '@/hooks/useMemoryPluginStatus'
import { useAuth } from '@/hooks/useAuth'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
@@ -19,7 +18,6 @@ export function DesktopSidebar() {
const navigate = useNavigate()
const [collapsed, toggle] = useSidebarCollapsed()
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
const { memoryPluginEnabled } = useMemoryPluginStatus()
const { isAuthenticated, isLoading, logout } = useAuth()
const isDesktop = useDesktop()
@@ -32,7 +30,7 @@ export function DesktopSidebar() {
return null
}
const { primary, items } = buildNavModel(location.pathname, { memoryPluginEnabled })
const { primary, items } = buildNavModel(location.pathname)
const handlePrimaryClick = (item: NavPrimaryCta) => {
if (item.to) {
@@ -238,20 +238,4 @@ describe('MobileTabBar', () => {
expect(container.firstChild).toBeNull()
})
it('renders tab bar on Memories path /repos/:id/memories', () => {
vi.mocked(useMobile).mockReturnValue(true)
const queryClient = new QueryClient()
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/1/memories']}>
<MobileTabBar />
</MemoryRouter>
</QueryClientProvider>,
)
expect(screen.getByText('Repos')).toBeInTheDocument()
expect(screen.getByText('Files')).toBeInTheDocument()
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.getByText('Schedules')).toBeInTheDocument()
expect(screen.getByText('More')).toBeInTheDocument()
})
})
@@ -48,7 +48,6 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
switch (repoSection) {
case undefined:
case 'memories':
case 'assistant':
return { mode: 'global', isInsideRepo: true, repoId }
case 'schedules':
@@ -1,17 +1,19 @@
import { render, screen, fireEvent } from '@testing-library/react'
import { beforeEach, describe, it, expect, vi } from 'vitest'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MoreDrawer } from './MoreDrawer'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useCommands } from '@/hooks/useCommands'
import { useUIState } from '@/stores/uiStateStore'
import { getRepo } from '@/api/repos'
vi.mock('@/hooks/useAuth')
vi.mock('@/hooks/useServerHealth')
vi.mock('@/hooks/useCommands')
vi.mock('@/hooks/useMemoryPluginStatus', () => ({
useMemoryPluginStatus: () => ({ memoryPluginEnabled: false }),
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: ({ isOpen, basePath, onFileSelect }: { isOpen: boolean; basePath: string; onFileSelect: (file: { path: string }) => void }) => (
@@ -72,6 +74,32 @@ const mockServerHealth = (health?: Partial<ReturnType<typeof useServerHealth>['d
})
}
const createQueryClient = () => new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
})
const renderMoreDrawer = ({
initialEntry = '/',
routePath = '*',
onClose = vi.fn(),
}: {
initialEntry?: string
routePath?: string
onClose?: () => void
} = {}) => render(
<QueryClientProvider client={createQueryClient()}>
<MemoryRouter initialEntries={[initialEntry]}>
<Routes>
<Route path={routePath} element={<MoreDrawer isOpen onClose={onClose} />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
describe('MoreDrawer', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -94,16 +122,22 @@ describe('MoreDrawer', () => {
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
useUIState.getState().setActivePromptFileBasePath(null)
vi.mocked(getRepo).mockResolvedValue({
id: 1,
localPath: 'wrong-repo',
fullPath: '/workspace/repos/wrong-repo',
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
})
})
it('renders Settings and Logout menu items', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
})
@@ -112,10 +146,7 @@ describe('MoreDrawer', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
expect(screen.queryByText('Theme')).not.toBeInTheDocument()
expect(screen.queryByText('Light')).not.toBeInTheDocument()
expect(screen.queryByText('Dark')).not.toBeInTheDocument()
@@ -128,10 +159,7 @@ describe('MoreDrawer', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
fireEvent.click(screen.getByText('Settings'))
expect(navigateMock).toHaveBeenCalledWith(
{ search: 'settings=open&tab=account' },
@@ -144,10 +172,7 @@ describe('MoreDrawer', () => {
mockAuth(logoutMock)
mockServerHealth()
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
fireEvent.click(screen.getByText('Logout'))
expect(logoutMock).toHaveBeenCalled()
})
@@ -156,10 +181,7 @@ describe('MoreDrawer', () => {
mockAuth()
mockServerHealth({ opencodeVersion: '1.4.11', opencodeManagerVersion: '0.9.16' })
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
expect(screen.getByText('v1.4.11 · Manager v0.9.16')).toBeInTheDocument()
})
@@ -167,10 +189,7 @@ describe('MoreDrawer', () => {
mockAuth()
mockServerHealth({ opencode: 'unhealthy' as const, opencodeVersion: '1.4.11' })
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
expect(screen.getByText('v1.4.11')).toBeInTheDocument()
})
@@ -178,10 +197,7 @@ describe('MoreDrawer', () => {
mockAuth()
mockServerHealth({ opencodeVersion: null, opencodeManagerVersion: null })
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
)
renderMoreDrawer({ onClose: handleClose })
expect(screen.queryByText('OpenCode')).not.toBeInTheDocument()
})
@@ -189,10 +205,7 @@ describe('MoreDrawer', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter initialEntries={['/repos/1/sessions/session-1']}>{children}</MemoryRouter> },
)
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId', onClose: handleClose })
fireEvent.click(screen.getByText('Commands'))
expect(screen.queryByText('/help')).not.toBeInTheDocument()
@@ -207,10 +220,7 @@ describe('MoreDrawer', () => {
mockServerHealth()
const handleClose = vi.fn()
useUIState.getState().setActivePromptFileBasePath('repo')
render(
<MoreDrawer isOpen onClose={handleClose} />,
{ wrapper: ({ children }) => <MemoryRouter initialEntries={['/repos/1/sessions/session-1']}>{children}</MemoryRouter> },
)
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId', onClose: handleClose })
fireEvent.click(screen.getByText('Mention File'))
expect(screen.getByTestId('mention-file-browser')).toHaveAttribute('data-base-path', 'repo')
@@ -220,4 +230,14 @@ describe('MoreDrawer', () => {
expect(handleClose).toHaveBeenCalled()
})
it('shows Assistant instead of the source repo on assistant routes', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
renderMoreDrawer({ initialEntry: '/repos/1/assistant', routePath: '/repos/:id/assistant', onClose: handleClose })
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.queryByText('wrong-repo')).not.toBeInTheDocument()
})
})
@@ -1,15 +1,18 @@
import { useNavigate, useLocation } from 'react-router-dom'
import { useState } from 'react'
import { ChevronDown, ChevronRight, Command as CommandIcon, FileText, X } from 'lucide-react'
import { useNavigate, useLocation, useParams } from 'react-router-dom'
import { useState, useRef, useEffect } from 'react'
import { ChevronDown, ChevronRight, Command as CommandIcon, FileText, X, GitBranch } from 'lucide-react'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useMemoryPluginStatus } from '@/hooks/useMemoryPluginStatus'
import { useCommands } from '@/hooks/useCommands'
import { useUIState } from '@/stores/uiStateStore'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { buildMoreItems } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { getRepoDisplayName } from '@/lib/utils'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
@@ -22,17 +25,40 @@ interface MoreDrawerProps {
export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const navigate = useNavigate()
const location = useLocation()
const { id } = useParams<{ id: string }>()
const repoId = id ? Number(id) : null
const [commandsOpen, setCommandsOpen] = useState(false)
const [mentionFileBrowserOpen, setMentionFileBrowserOpen] = useState(false)
const swipeRef = useRef<HTMLDivElement>(null)
const { bind } = useSwipeBack(onClose, { enabled: true, suspendsRouteSwipe: false })
const { logout } = useAuth()
const { data: health } = useServerHealth()
const { memoryPluginEnabled } = useMemoryPluginStatus()
const isSessionDetail = /^\/repos\/\d+\/sessions\/[^/]+$/.test(location.pathname)
const isAssistantRoute = /^\/repos\/\d+\/assistant$/.test(location.pathname)
const isAssistantSession = isSessionDetail && new URLSearchParams(location.search).get('assistant') === '1'
const { filterCommands } = useCommands(isSessionDetail ? OPENCODE_API_ENDPOINT : null)
const activePromptFileBasePath = useUIState((state) => state.activePromptFileBasePath)
const selectPromptCommand = useUIState((state) => state.selectPromptCommand)
const selectPromptFile = useUIState((state) => state.selectPromptFile)
useEffect(() => {
if (isOpen && swipeRef.current) {
const cleanup = bind(swipeRef.current)
return cleanup
}
}, [isOpen, bind])
const { data: repo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => repoId ? getRepo(repoId) : null,
enabled: !!repoId,
})
const currentBranch = repo?.currentBranch || repo?.branch
const repoDisplayName = isAssistantRoute || isAssistantSession
? 'Assistant'
: repo ? getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath) : null
const handleSettingsClick = () => {
const newParams = new URLSearchParams(location.search)
newParams.delete('mobileTab')
@@ -83,7 +109,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
onClose()
}
const items = buildMoreItems(location.pathname, { memoryPluginEnabled })
const items = buildMoreItems(location.pathname)
const commands = filterCommands('')
const opencodeVersion = health?.opencodeVersion
@@ -95,18 +121,34 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
return (
<SideDrawer isOpen={isOpen} onClose={onClose} side="right" ariaLabel="More" widthClass="w-screen sm:w-[min(90vw,420px)]">
<div className="flex flex-shrink-0 items-center justify-between gap-3 border-b border-border bg-background px-4 py-1.5">
{versionLabel && (
<span className="truncate text-xs leading-tight text-muted-foreground">{versionLabel}</span>
<div ref={swipeRef} className="flex flex-col flex-shrink-0 border-b border-border bg-background px-4 py-1.5">
<div className="flex items-center justify-between gap-3 mb-2">
{versionLabel && (
<span className="truncate text-xs leading-tight text-muted-foreground">{versionLabel}</span>
)}
<button
type="button"
onClick={onClose}
className="shrink-0 rounded-sm p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Close"
>
<X className="h-5 w-5" />
</button>
</div>
{(repoDisplayName || currentBranch) && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{repoDisplayName && (
<span className="font-medium text-orange-600 dark:text-orange-400">{repoDisplayName}</span>
)}
{currentBranch && (
<>
<GitBranch className="h-3.5 w-3.5" />
<span>{currentBranch}</span>
</>
)}
</div>
)}
<button
type="button"
onClick={onClose}
className="shrink-0 rounded-sm p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Close"
>
<X className="h-5 w-5" />
</button>
</div>
<SideDrawerContent className="flex flex-col gap-1">
{isSessionDetail && (
@@ -3,9 +3,11 @@ import { useNavigate, useLocation } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Input } from '@/components/ui/input'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
import { Button } from '@/components/ui/button'
import { cn, getRepoDisplayName } from '@/lib/utils'
import { listRepos } from '@/api/repos'
import { FolderGit2, Check } from 'lucide-react'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Check, Plus } from 'lucide-react'
interface RepoQuickSwitchSheetProps {
isOpen: boolean
@@ -16,6 +18,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const navigate = useNavigate()
const location = useLocation()
const [searchQuery, setSearchQuery] = useState('')
const [addRepoOpen, setAddRepoOpen] = useState(false)
const activeRepoId = useMemo(() => {
const match = location.pathname.match(/^\/repos\/(\d+)/)
@@ -69,17 +72,29 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
}
return (
<BottomSheet isOpen={isOpen} onClose={onClose} heightClass="h-[70dvh]" ariaLabel="Switch repo">
<BottomSheetHeader>
<Input
type="text"
placeholder="Search projects..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
autoFocus
className="flex-shrink-0"
/>
</BottomSheetHeader>
<>
<BottomSheet isOpen={isOpen} onClose={onClose} heightClass="h-[70dvh]" ariaLabel="Switch repo">
<BottomSheetHeader>
<div className="flex items-center gap-2">
<Input
type="text"
placeholder="Search projects..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
autoFocus
className="flex-1"
/>
<Button
type="button"
size="sm"
onClick={() => setAddRepoOpen(true)}
className="flex-shrink-0"
>
<Plus className="h-4 w-4" /> Repo
<span className="sr-only">Add repository</span>
</Button>
</div>
</BottomSheetHeader>
<BottomSheetContent className="flex flex-col gap-2 overflow-y-auto pt-2">
{isLoading ? (
<div className="flex flex-col gap-2">
@@ -129,6 +144,8 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
</div>
)}
</BottomSheetContent>
</BottomSheet>
</BottomSheet>
<AddRepoDialog open={addRepoOpen} onOpenChange={setAddRepoOpen} />
</>
)
}
@@ -11,80 +11,52 @@ describe('buildMoreItems', () => {
expect(items[3].key).toBe('logout')
})
it('returns repo-specific items with memory when plugin enabled for /repos/:id', () => {
const items = buildMoreItems('/repos/42', { memoryPluginEnabled: true })
expect(items).toHaveLength(9)
expect(items[0].key).toBe('files')
expect(items[0].dialog).toBe('files')
expect(items[1].key).toBe('memory')
expect(items[1].to).toBe('/repos/42/memories')
expect(items[2].key).toBe('mcp')
expect(items[2].dialog).toBe('mcp')
expect(items[3].key).toBe('skills')
expect(items[3].dialog).toBe('skills')
expect(items[4].key).toBe('reset-permissions')
expect(items[4].dialog).toBe('resetPermissions')
expect(items[4].danger).toBe(true)
expect(items[5].key).toBe('schedules')
expect(items[5].to).toBe('/repos/42/schedules')
expect(items[6].key).toBe('source-control')
expect(items[6].dialog).toBe('sourceControl')
expect(items[7].key).toBe('settings')
expect(items[8].key).toBe('logout')
})
it('omits memory item for /repos/:id when plugin disabled', () => {
it('returns repo-specific items for /repos/:id', () => {
const items = buildMoreItems('/repos/42')
expect(items).toHaveLength(8)
expect(items.some((item) => item.key === 'memory')).toBe(false)
expect(items[0].key).toBe('files')
expect(items[0].dialog).toBe('files')
expect(items[1].key).toBe('mcp')
expect(items[1].dialog).toBe('mcp')
expect(items[2].key).toBe('skills')
expect(items[2].dialog).toBe('skills')
expect(items[3].key).toBe('reset-permissions')
expect(items[3].dialog).toBe('resetPermissions')
expect(items[3].danger).toBe(true)
expect(items[4].key).toBe('schedules')
expect(items[4].to).toBe('/repos/42/schedules')
expect(items[5].key).toBe('source-control')
expect(items[5].dialog).toBe('sourceControl')
expect(items[6].key).toBe('settings')
expect(items[7].key).toBe('logout')
})
it('returns session-specific items with memory when plugin enabled for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc', { memoryPluginEnabled: true })
expect(items).toHaveLength(9)
expect(items[0].key).toBe('files')
expect(items[1].key).toBe('memory')
expect(items[2].key).toBe('mcp')
expect(items[3].key).toBe('skills')
expect(items[4].key).toBe('lsp')
expect(items[4].dialog).toBe('lsp')
expect(items[5].key).toBe('reset-permissions')
expect(items[6].key).toBe('source-control')
expect(items[7].key).toBe('settings')
expect(items[8].key).toBe('logout')
})
it('omits memory item for /repos/:id/sessions/:sid when plugin disabled', () => {
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc')
expect(items).toHaveLength(8)
expect(items.some((item) => item.key === 'memory')).toBe(false)
expect(items[0].key).toBe('files')
expect(items[1].key).toBe('mcp')
expect(items[2].key).toBe('skills')
expect(items[3].key).toBe('lsp')
expect(items[3].dialog).toBe('lsp')
expect(items[4].key).toBe('reset-permissions')
expect(items[5].key).toBe('source-control')
expect(items[6].key).toBe('settings')
expect(items[7].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
const items = buildMoreItems('/repos/42/assistant', { memoryPluginEnabled: true })
expect(items).toHaveLength(9)
const items = buildMoreItems('/repos/42/assistant')
expect(items).toHaveLength(8)
expect(items[0].key).toBe('files')
expect(items[0].dialog).toBe('files')
expect(items[1].key).toBe('memory')
expect(items[1].to).toBe('/repos/42/memories')
expect(items[2].key).toBe('mcp')
expect(items[3].key).toBe('skills')
expect(items[4].key).toBe('reset-permissions')
expect(items[5].key).toBe('schedules')
expect(items[6].key).toBe('source-control')
expect(items[7].key).toBe('settings')
expect(items[8].key).toBe('logout')
})
it('returns only Settings + Logout for /repos/:id/memories', () => {
const items = buildMoreItems('/repos/42/memories')
expect(items).toHaveLength(2)
expect(items[0].key).toBe('settings')
expect(items[1].key).toBe('logout')
expect(items[1].key).toBe('mcp')
expect(items[2].key).toBe('skills')
expect(items[3].key).toBe('reset-permissions')
expect(items[4].key).toBe('schedules')
expect(items[5].key).toBe('source-control')
expect(items[6].key).toBe('settings')
expect(items[7].key).toBe('logout')
})
it('returns only Settings + Logout for /schedules', () => {
@@ -166,13 +138,6 @@ describe('buildNavModel', () => {
expect(model2.primary[1].to).toBe('/repos/5/assistant')
})
it('returns empty primary for memories routes', () => {
const model = buildNavModel('/repos/5/memories')
expect(model.primary).toHaveLength(1)
expect(model.primary[0].key).toBe('assistant')
expect(model.primary[0].to).toBe('/repos/5/assistant')
})
it('returns assistant primary for unknown routes', () => {
const model = buildNavModel('/unknown/path')
expect(model.primary).toHaveLength(1)
@@ -181,8 +146,8 @@ describe('buildNavModel', () => {
})
it('preserves backwards compatibility with buildMoreItems', () => {
const model = buildNavModel('/repos/42', { memoryPluginEnabled: true })
const items = buildMoreItems('/repos/42', { memoryPluginEnabled: true })
const model = buildNavModel('/repos/42')
const items = buildMoreItems('/repos/42')
expect(model.items).toEqual(items)
})
})
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { Brain, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Code2, Settings, LogOut, Plus, Bot, Folder, Clock, SquarePlus } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Code2, Settings, LogOut, Plus, Bot, Folder, Clock, SquarePlus } from 'lucide-react'
export interface MoreDrawerItem {
key: string
@@ -24,12 +24,6 @@ export interface NavModel {
items: MoreDrawerItem[]
}
export interface BuildMoreItemsOptions {
memoryPluginEnabled?: boolean
}
export type BuildNavOptions = BuildMoreItemsOptions
function getAssistantNavItem(pathname: string, variant: NavPrimaryCta['variant'] = 'secondary'): NavPrimaryCta {
const repoMatch = /^\/repos\/(\d+)/.exec(pathname)
@@ -49,8 +43,7 @@ function getBaseItems(): MoreDrawerItem[] {
]
}
export function buildNavModel(pathname: string, options: BuildNavOptions = {}): NavModel {
const { memoryPluginEnabled = false } = options
export function buildNavModel(pathname: string): NavModel {
const baseItems = getBaseItems()
const repoDetailMatch = /^\/repos\/(\d+)$/.exec(pathname)
@@ -58,9 +51,6 @@ export function buildNavModel(pathname: string, options: BuildNavOptions = {}):
const id = repoDetailMatch[1]
const items: MoreDrawerItem[] = [
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
...(memoryPluginEnabled
? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }]
: []),
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
@@ -83,9 +73,6 @@ export function buildNavModel(pathname: string, options: BuildNavOptions = {}):
const id = sessionDetailMatch[1]
const items: MoreDrawerItem[] = [
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
...(memoryPluginEnabled
? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }]
: []),
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'lsp', label: 'LSP', icon: Code2, dialog: 'lsp' },
@@ -108,9 +95,6 @@ export function buildNavModel(pathname: string, options: BuildNavOptions = {}):
const id = assistantMatch[1]
const items: MoreDrawerItem[] = [
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
...(memoryPluginEnabled
? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }]
: []),
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
@@ -152,15 +136,6 @@ export function buildNavModel(pathname: string, options: BuildNavOptions = {}):
}
}
if (/^\/repos\/\d+\/memories$/.test(pathname)) {
return {
primary: [
getAssistantNavItem(pathname),
],
items: baseItems,
}
}
return {
primary: [
getAssistantNavItem(pathname),
@@ -169,6 +144,6 @@ export function buildNavModel(pathname: string, options: BuildNavOptions = {}):
}
}
export function buildMoreItems(pathname: string, options: BuildMoreItemsOptions = {}): MoreDrawerItem[] {
return buildNavModel(pathname, options).items
export function buildMoreItems(pathname: string): MoreDrawerItem[] {
return buildNavModel(pathname).items
}
@@ -1,100 +0,0 @@
import { Loader2, CheckCircle2, XCircle, Ban, AlertCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import type { LoopState } from '@opencode-manager/shared'
interface RepoLoopListProps {
isLoading: boolean
data: LoopState[] | undefined
error: Error | null
onCancel: (sessionId: string) => void
pendingSessionId: string | null
}
function StatusIcon({ loop }: { loop: LoopState }) {
if (loop.active) return <Loader2 className="h-4 w-4 animate-spin text-blue-400" />
if (loop.terminationReason === 'completed') return <CheckCircle2 className="h-4 w-4 text-green-400" />
if (loop.terminationReason === 'cancelled' || loop.terminationReason === 'user_aborted') return <Ban className="h-4 w-4 text-yellow-400" />
return <XCircle className="h-4 w-4 text-red-400" />
}
function formatDuration(startedAt: string, completedAt?: string): string {
const start = new Date(startedAt).getTime()
const end = completedAt ? new Date(completedAt).getTime() : Date.now()
const seconds = Math.floor((end - start) / 1000)
if (seconds < 60) return `${seconds}s`
const minutes = Math.floor(seconds / 60)
if (minutes < 60) return `${minutes}m ${seconds % 60}s`
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
}
export function RepoLoopList({ isLoading, data, error, onCancel, pendingSessionId }: RepoLoopListProps) {
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="flex items-center gap-2 p-6 text-destructive">
<AlertCircle className="h-4 w-4" />
<span className="text-sm">Failed to load loop status</span>
</div>
)
}
if (!data?.length) {
return (
<div className="flex flex-col items-center justify-center p-8 text-muted-foreground">
<span className="text-sm">No loops found</span>
</div>
)
}
return (
<div className="flex flex-col gap-3 p-4 overflow-y-auto">
{data.map((loop) => (
<div key={loop.sessionId} className="rounded-lg border bg-card p-4 flex flex-col gap-2">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<StatusIcon loop={loop} />
<span className="font-medium text-sm truncate">{loop.worktreeName}</span>
</div>
<div className="flex items-center gap-2 shrink-0">
<Badge variant="outline" className="text-xs capitalize">
{loop.phase ?? 'coding'}
</Badge>
{loop.active && (
<Button
variant="destructive"
size="sm"
onClick={() => onCancel(loop.sessionId)}
disabled={pendingSessionId === loop.sessionId}
className="h-7 text-xs"
>
Cancel
</Button>
)}
</div>
</div>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<span>Iteration {loop.iteration ?? 0}/{loop.maxIterations ?? 0}</span>
<span>{formatDuration(loop.startedAt ?? new Date().toISOString(), loop.completedAt)}</span>
{loop.worktreeBranch && <span className="truncate">{loop.worktreeBranch}</span>}
</div>
{loop.terminationReason && !loop.active && (
<span className="text-xs text-muted-foreground capitalize">
{loop.terminationReason.replace(/_/g, ' ')}
</span>
)}
{loop.lastAuditResult && (
<p className="text-xs text-muted-foreground line-clamp-2 mt-1">{loop.lastAuditResult}</p>
)}
</div>
))}
</div>
)
}
@@ -0,0 +1,268 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { RepoSkillsDialog } from './RepoSkillsDialog'
import type { SkillFileInfo } from '@opencode-manager/shared'
const mocks = vi.hoisted(() => ({
listManagedSkills: vi.fn(),
sendCommand: vi.fn(),
}))
vi.mock('@/api/settings', () => ({
settingsApi: {
listManagedSkills: mocks.listManagedSkills,
},
}))
vi.mock('@/api/opencode', () => ({
OpenCodeClient: vi.fn(() => ({
sendCommand: mocks.sendCommand,
})),
}))
vi.mock('@/lib/toast', () => ({
showToast: {
error: vi.fn(),
success: vi.fn(),
},
}))
describe('RepoSkillsDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
const mockSkills: SkillFileInfo[] = [
{
name: 'test-skill',
description: 'A test skill for testing',
body: 'Test skill content',
location: '/repo/.opencode/skills/test-skill/SKILL.md',
scope: 'project',
},
{
name: 'global-skill',
description: 'A global skill',
body: 'Global skill content',
location: '/home/user/.config/opencode/skills/global-skill/SKILL.md',
scope: 'global',
},
]
describe('tabs and skill filtering', () => {
it('shows both tabs when skills exist', async () => {
mocks.listManagedSkills.mockResolvedValue(mockSkills)
render(
<RepoSkillsDialog
open
onOpenChange={vi.fn()}
repoId={1}
/>,
{ wrapper: createWrapper() }
)
expect(screen.getByText('Project')).toBeInTheDocument()
expect(screen.getByText('Global')).toBeInTheDocument()
})
it('shows project skills in project tab', async () => {
mocks.listManagedSkills.mockResolvedValue(mockSkills)
render(
<RepoSkillsDialog
open
onOpenChange={vi.fn()}
repoId={1}
/>,
{ wrapper: createWrapper() }
)
await waitFor(() => {
expect(screen.getByText('Test skill')).toBeInTheDocument()
})
})
it('shows global skills in global tab', async () => {
mocks.listManagedSkills.mockResolvedValue(mockSkills)
render(
<RepoSkillsDialog
open
onOpenChange={vi.fn()}
repoId={1}
/>,
{ wrapper: createWrapper() }
)
await waitFor(() => {
expect(screen.getByText('Project')).toBeInTheDocument()
})
const globalTab = screen.getByText('Global')
await userEvent.click(globalTab)
expect(screen.getByText('Global skill')).toBeInTheDocument()
})
it('shows empty state for project tab when no project skills', async () => {
mocks.listManagedSkills.mockResolvedValue([
{
name: 'global-skill',
description: 'A global skill',
body: 'Global skill content',
location: '/home/user/.config/opencode/skills/global-skill/SKILL.md',
scope: 'global',
},
])
render(
<RepoSkillsDialog
open
onOpenChange={vi.fn()}
repoId={1}
/>,
{ wrapper: createWrapper() }
)
const projectTab = screen.getByText('Project')
await userEvent.click(projectTab)
await waitFor(() => {
expect(screen.getByText('No local skills found')).toBeInTheDocument()
})
})
})
describe('load functionality', () => {
it('shows Load button when sessionId and opcodeUrl are provided', async () => {
mocks.listManagedSkills.mockResolvedValue(mockSkills)
mocks.sendCommand.mockResolvedValue(undefined)
const onSkillLoaded = vi.fn()
const onOpenChange = vi.fn()
render(
<RepoSkillsDialog
open
onOpenChange={onOpenChange}
repoId={1}
sessionId="test-session"
opcodeUrl="http://localhost:5551"
directory="/test/repo"
onSkillLoaded={onSkillLoaded}
/>,
{ wrapper: createWrapper() }
)
await waitFor(() => {
expect(screen.getByText('Test skill')).toBeInTheDocument()
})
expect(screen.getByText('Load')).toBeInTheDocument()
})
it('does not show Load button when sessionId is not provided', async () => {
mocks.listManagedSkills.mockResolvedValue(mockSkills)
render(
<RepoSkillsDialog
open
onOpenChange={vi.fn()}
repoId={1}
/>,
{ wrapper: createWrapper() }
)
await waitFor(() => {
expect(screen.getByText('Test skill')).toBeInTheDocument()
})
expect(screen.queryByText('Load')).not.toBeInTheDocument()
})
it('calls sendCommand and closes dialog on Load click', async () => {
mocks.listManagedSkills.mockResolvedValue(mockSkills)
mocks.sendCommand.mockReturnValue(new Promise(() => {}))
const onSkillLoaded = vi.fn()
const onOpenChange = vi.fn()
const user = userEvent.setup()
render(
<RepoSkillsDialog
open
onOpenChange={onOpenChange}
repoId={1}
sessionId="test-session"
opcodeUrl="http://localhost:5551"
directory="/test/repo"
onSkillLoaded={onSkillLoaded}
/>,
{ wrapper: createWrapper() }
)
await waitFor(() => {
expect(screen.getByText('Test skill')).toBeInTheDocument()
})
const loadButton = screen.getByText('Load')
await user.click(loadButton)
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(onSkillLoaded).toHaveBeenCalledWith(mockSkills[0])
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session', {
command: 'test-skill',
arguments: '',
})
})
it('shows toast error on sendCommand failure', async () => {
const { showToast } = await import('@/lib/toast')
mocks.listManagedSkills.mockResolvedValue(mockSkills)
mocks.sendCommand.mockRejectedValue(new Error('Failed to load'))
const onOpenChange = vi.fn()
const user = userEvent.setup()
render(
<RepoSkillsDialog
open
onOpenChange={onOpenChange}
repoId={1}
sessionId="test-session"
opcodeUrl="http://localhost:5551"
directory="/test/repo"
/>,
{ wrapper: createWrapper() }
)
await waitFor(() => {
expect(screen.getByText('Test skill')).toBeInTheDocument()
})
const loadButton = screen.getByText('Load')
await user.click(loadButton)
await waitFor(() => {
expect(showToast.error).toHaveBeenCalledWith('Failed to load')
})
expect(onOpenChange).toHaveBeenCalledWith(false)
})
})
})
@@ -1,15 +1,32 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { RepoSkillsList } from './RepoSkillsList'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { useQuery } from '@tanstack/react-query'
import { settingsApi } from '@/api/settings'
import { useLoadSkill } from '@/hooks/useOpenCode'
import type { SkillFileInfo } from '@opencode-manager/shared'
import { useMemo, useState, useEffect } from 'react'
interface RepoSkillsDialogProps {
type RepoSkillsDialogBaseProps = {
open: boolean
onOpenChange: (open: boolean) => void
repoId: number
}
export function RepoSkillsDialog({ open, onOpenChange, repoId }: RepoSkillsDialogProps) {
type RepoSkillsDialogProps = RepoSkillsDialogBaseProps & (
| { sessionId: string; opcodeUrl: string; directory: string; onSkillLoaded?: (skill: SkillFileInfo) => void }
| { sessionId?: undefined; opcodeUrl?: undefined; directory?: undefined; onSkillLoaded?: undefined }
)
export function RepoSkillsDialog({
open,
onOpenChange,
repoId,
sessionId,
opcodeUrl,
directory,
onSkillLoaded,
}: RepoSkillsDialogProps) {
const { isLoading, data, error } = useQuery({
queryKey: ['settings', 'skills', repoId],
queryFn: () => settingsApi.listManagedSkills(repoId),
@@ -17,19 +34,75 @@ export function RepoSkillsDialog({ open, onOpenChange, repoId }: RepoSkillsDialo
staleTime: 30000,
})
const projectSkills = useMemo(
() => data?.filter((s) => s.scope === 'project') ?? [],
[data],
)
const globalSkills = useMemo(
() => data?.filter((s) => s.scope === 'global') ?? [],
[data],
)
const canLoad = !!sessionId && !!opcodeUrl
const loadSkill = useLoadSkill(opcodeUrl, sessionId, directory)
const [activeTab, setActiveTab] = useState<'project' | 'global'>('project')
useEffect(() => {
if (data && projectSkills.length === 0 && globalSkills.length > 0) {
setActiveTab('global')
}
}, [data, projectSkills.length, globalSkills.length])
const handleTabChange = (value: string) => {
setActiveTab(value as 'project' | 'global')
}
const handleLoad = (skill: SkillFileInfo) => {
loadSkill.mutate({ skillName: skill.name })
onSkillLoaded?.(skill)
onOpenChange(false)
}
if (!repoId) {
return null
}
const repoSkills = data?.filter(skill => skill.scope === 'project')
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0 shrink-0">
<DialogHeader className="p-4 sm:p-6 border-b shrink-0">
<DialogTitle>Skills</DialogTitle>
<DialogDescription>
{canLoad ? 'Load a skill into the current session' : 'Skills available for this repository'}
</DialogDescription>
</DialogHeader>
<RepoSkillsList isLoading={isLoading} data={repoSkills} error={error} />
<Tabs value={activeTab} onValueChange={handleTabChange} className="flex-1 flex flex-col min-h-0">
<TabsList className="mx-4 sm:mx-6 mt-3">
<TabsTrigger value="project">Project</TabsTrigger>
<TabsTrigger value="global">Global</TabsTrigger>
</TabsList>
<TabsContent value="project" className="flex-1 min-h-0 flex flex-col">
<RepoSkillsList
isLoading={isLoading}
data={projectSkills}
error={error as Error | null}
emptyTitle="No local skills found"
emptyHint="Add skills to .opencode/skills/&lt;name&gt;/SKILL.md in this repository."
onLoad={canLoad ? handleLoad : undefined}
/>
</TabsContent>
<TabsContent value="global" className="flex-1 min-h-0 flex flex-col">
<RepoSkillsList
isLoading={isLoading}
data={globalSkills}
error={error as Error | null}
emptyTitle="No global skills"
emptyHint="Global skills live under ~/.config/opencode/skills/."
onLoad={canLoad ? handleLoad : undefined}
/>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
)
+34 -10
View File
@@ -5,9 +5,19 @@ interface RepoSkillsListProps {
isLoading: boolean
data: SkillFileInfo[] | undefined
error: Error | null
emptyTitle?: string
emptyHint?: string
onLoad?: (skill: SkillFileInfo) => void
}
export function RepoSkillsList({ isLoading, data, error }: RepoSkillsListProps) {
export function RepoSkillsList({
isLoading,
data,
error,
emptyTitle,
emptyHint,
onLoad,
}: RepoSkillsListProps) {
const formatSkillName = (name: string): string => {
const formatted = name.replace(/-/g, ' ')
return formatted.charAt(0).toUpperCase() + formatted.slice(1)
@@ -35,8 +45,11 @@ export function RepoSkillsList({ isLoading, data, error }: RepoSkillsListProps)
if (!data || data.length === 0) {
return (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No skills available</p>
<p className="text-xs mt-1">Skills will appear here when configured in the project's .opencode/skills/ directory</p>
<p className="text-sm">{emptyTitle || 'No skills available'}</p>
<p className="text-xs mt-1">
{emptyHint ||
'Skills will appear here when configured in the project\'s .opencode/skills/ directory'}
</p>
</div>
)
}
@@ -47,15 +60,26 @@ export function RepoSkillsList({ isLoading, data, error }: RepoSkillsListProps)
{data.map((skill) => (
<div
key={skill.name}
className="p-2 rounded-lg border border-border bg-card"
className="p-2 rounded-lg border border-border bg-card flex items-center justify-between gap-2"
>
<p className="text-sm font-medium truncate">
{formatSkillName(skill.name)}
</p>
{skill.description && (
<p className="text-xs text-muted-foreground truncate mt-0.5">
{skill.description}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{formatSkillName(skill.name)}
</p>
{skill.description && (
<p className="text-xs text-muted-foreground truncate mt-0.5">
{skill.description}
</p>
)}
</div>
{onLoad && (
<button
type="button"
onClick={() => onLoad(skill)}
className="shrink-0 text-xs font-medium text-primary hover:text-foreground transition-colors"
>
Load
</button>
)}
</div>
))}
@@ -1,611 +0,0 @@
import { useState, useEffect, useMemo } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Combobox } from '@/components/ui/combobox'
import type { ComboboxOption } from '@/components/ui/combobox'
import { getProviders } from '@/api/providers'
import { useModelStore } from '@/stores/modelStore'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Save, Loader2, Database, Brain, AlertCircle, RefreshCw, Play, Cpu, FileText, Layers, Syringe, MessageSquare } from 'lucide-react'
import { getPluginConfig, updatePluginConfig, reindexMemories, testEmbeddingConfig } from '@/api/memory'
import { FetchError } from '@/api/fetchWrapper'
import { settingsApi } from '@/api/settings'
import type { PluginConfig, EmbeddingProviderType } from '@opencode-manager/shared/types'
import { showToast } from '@/lib/toast'
const EMBEDDING_PROVIDERS: { value: EmbeddingProviderType; label: string }[] = [
{ value: 'local', label: 'Local (all-MiniLM-L6-v2)' },
{ value: 'openai', label: 'OpenAI' },
{ value: 'voyage', label: 'Voyage AI' },
]
const DEFAULT_CONFIGS: Record<EmbeddingProviderType, { model: string; dimensions: number }> = {
local: { model: 'all-MiniLM-L6-v2', dimensions: 384 },
openai: { model: 'text-embedding-3-small', dimensions: 1536 },
voyage: { model: 'voyage-3', dimensions: 1024 },
}
interface MemoryPluginConfigProps {
memoryPluginEnabled: boolean
onToggle: (enabled: boolean) => void
}
export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPluginConfigProps) {
const queryClient = useQueryClient()
const [expanded, setExpanded] = useState(false)
const [showApiKey, setShowApiKey] = useState(false)
const { data, isLoading, error } = useQuery({
queryKey: ['memory-plugin-config'],
queryFn: getPluginConfig,
staleTime: 60000,
enabled: memoryPluginEnabled && expanded,
})
const { data: providersData } = useQuery({
queryKey: ['providers-for-execution-model'],
queryFn: async () => getProviders(),
staleTime: 60000,
enabled: memoryPluginEnabled && expanded,
})
const recentModels = useModelStore((s) => s.recentModels)
const executionModelOptions = useMemo<ComboboxOption[]>(() => {
if (!providersData?.providers) return []
const connectedProviders = providersData.providers.filter((p) => p.isConnected)
const recentSet = new Set<string>()
const recentOptions: ComboboxOption[] = []
for (const recent of recentModels) {
const modelValue = `${recent.providerID}/${recent.modelID}`
const provider = connectedProviders.find((p) => p.id === recent.providerID)
const model = provider?.models[recent.modelID]
if (!model || !provider) continue
recentSet.add(modelValue)
recentOptions.push({
value: modelValue,
label: model.name || model.id,
description: provider.name,
group: 'Recent',
})
}
const providerOptions: ComboboxOption[] = []
for (const provider of connectedProviders.sort((a, b) => a.name.localeCompare(b.name))) {
for (const [modelId, model] of Object.entries(provider.models)) {
const modelValue = `${provider.id}/${modelId}`
if (recentSet.has(modelValue)) continue
providerOptions.push({
value: modelValue,
label: model.name || model.id,
description: modelId,
group: provider.name,
})
}
}
return [...recentOptions, ...providerOptions]
}, [providersData, recentModels])
const config = data?.config
const [localConfig, setLocalConfig] = useState<PluginConfig | null>(null)
useEffect(() => {
if (config && !localConfig) {
setLocalConfig(config)
}
}, [config, localConfig])
const handleProviderChange = (provider: EmbeddingProviderType) => {
if (!localConfig && !config) return
const current = localConfig ?? config!
const defaults = DEFAULT_CONFIGS[provider]
setLocalConfig({
...current,
embedding: {
provider,
model: defaults.model,
dimensions: defaults.dimensions,
},
})
}
const updateMutation = useMutation({
mutationFn: updatePluginConfig,
onSuccess: (data) => {
queryClient.setQueryData(['memory-plugin-config'], { config: data.config })
},
})
const reindexMutation = useMutation({
mutationFn: reindexMemories,
onSuccess: (data) => {
if (data.requiresRestart) {
showToast.success(data.message)
} else {
showToast.success(`Reindex complete: ${data.embedded}/${data.total} memories embedded`)
}
},
onError: () => {
showToast.error('Failed to reindex memories')
},
})
const testMutation = useMutation({
mutationFn: testEmbeddingConfig,
onSuccess: (data) => {
showToast.success(data.message || 'Configuration test passed')
},
onError: (error) => {
const message = error instanceof FetchError ? error.message : 'Failed to test configuration'
showToast.error(message)
},
})
const handleReindex = () => {
reindexMutation.mutate()
}
const handleTest = async () => {
if (isDirty && localConfig) {
await updateMutation.mutateAsync(localConfig)
}
testMutation.mutate()
}
const handleSave = async () => {
if (!localConfig) return
showToast.loading('Saving configuration...', { id: 'memory-save' })
updateMutation.mutate(localConfig, {
onSuccess: async () => {
showToast.loading('Restarting OpenCode server...', { id: 'memory-save' })
try {
await settingsApi.restartOpenCodeServer()
showToast.success('Configuration saved and server restarted', { id: 'memory-save' })
} catch {
showToast.error('Failed to restart server', { id: 'memory-save' })
}
},
onError: () => {
showToast.error('Failed to save configuration', { id: 'memory-save' })
},
})
}
const handleFieldChange = (field: keyof PluginConfig['embedding'], value: string | number | undefined) => {
if (!localConfig && !config) return
setLocalConfig({
...(localConfig ?? config!),
embedding: {
...(localConfig?.embedding ?? config!.embedding),
[field]: value === '' ? undefined : value,
},
})
}
const handleNestedChange = <K extends 'logging' | 'compaction' | 'memoryInjection' | 'messagesTransform'>(
section: K,
field: string,
value: string | number | boolean | undefined,
) => {
if (!localConfig && !config) return
const current = localConfig ?? config!
setLocalConfig({
...current,
[section]: {
...current[section],
[field]: value === '' ? undefined : value,
},
})
}
const displayConfig = localConfig ?? config
const isApiProvider = displayConfig?.embedding.provider !== 'local'
const isDirty = localConfig !== null && JSON.stringify(localConfig) !== JSON.stringify(config)
return (
<Card className="mt-4 border-transparent">
<CardHeader className="py-3">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-4">
<button
onClick={() => setExpanded(!expanded)}
className="flex items-center gap-2 p-1 hover:opacity-80 transition-opacity"
>
{expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
<Brain className="h-4 w-4 text-blue-500" />
<CardTitle className="text-sm">Memory Plugin</CardTitle>
</button>
<Switch
checked={memoryPluginEnabled}
onCheckedChange={onToggle}
/>
</div>
</div>
<CardDescription className="text-xs">
Configure embedding, deduplication, and storage options
</CardDescription>
</CardHeader>
{memoryPluginEnabled && expanded && (
<CardContent className="space-y-6 pt-0">
{isLoading && (
<div className="flex items-center gap-2 p-4">
<Loader2 className="h-4 w-4 animate-spin" />
<span className="text-muted-foreground">Loading configuration...</span>
</div>
)}
{error && (
<div className="flex items-center gap-2 p-4 text-destructive">
<AlertCircle className="h-4 w-4" />
<span>Failed to load plugin configuration</span>
</div>
)}
{config && !isLoading && !error && displayConfig && (
<>
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<span className="text-sm font-medium">Embedding</span>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="provider">Provider</Label>
<select
id="provider"
className="flex h-10 w-full rounded-md bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
value={displayConfig.embedding.provider}
onChange={(e) => handleProviderChange(e.target.value as EmbeddingProviderType)}
>
{EMBEDDING_PROVIDERS.map((p) => (
<option key={p.value} value={p.value}>
{p.label}
</option>
))}
</select>
</div>
<div className="space-y-2">
<Label htmlFor="model">Model</Label>
<Input
id="model"
value={displayConfig.embedding.model}
onChange={(e) => handleFieldChange('model', e.target.value)}
placeholder="Model name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="dimensions">Dimensions</Label>
<Input
id="dimensions"
type="number"
value={displayConfig.embedding.dimensions ?? ''}
onChange={(e) => handleFieldChange('dimensions', e.target.value ? parseInt(e.target.value, 10) : undefined)}
placeholder="384"
/>
</div>
{isApiProvider && (
<>
<div className="space-y-2">
<Label htmlFor="apiKey">API Key</Label>
<div className="relative">
<Input
id="apiKey"
type={showApiKey ? 'text' : 'password'}
value={displayConfig.embedding.apiKey ?? ''}
onChange={(e) => handleFieldChange('apiKey', e.target.value)}
placeholder="Enter API key"
className="pr-10"
/>
<button
type="button"
onClick={() => setShowApiKey(!showApiKey)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showApiKey ? <span className="text-xs">Hide</span> : <span className="text-xs">Show</span>}
</button>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="baseUrl">Base URL (optional)</Label>
<Input
id="baseUrl"
value={displayConfig.embedding.baseUrl ?? ''}
onChange={(e) => handleFieldChange('baseUrl', e.target.value)}
placeholder="https://api.openai.com"
/>
<p className="text-xs text-muted-foreground">
Root URL without path — /v1/embeddings is appended automatically
</p>
</div>
</>
)}
<div className="space-y-2">
<div className="flex items-center gap-2">
<RefreshCw className="h-4 w-4 text-purple-500" />
<span className="text-sm font-medium">Reindex</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleReindex}
disabled={reindexMutation.isPending}
className="w-full justify-start"
>
{reindexMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<RefreshCw className="h-4 w-4 mr-2" />
)}
Reindex
</Button>
<p className="text-xs text-muted-foreground">
Regenerate embeddings for all memories
</p>
</div>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2 border-t pt-4">
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<Database className="h-4 w-4 text-green-500" />
<span className="text-sm font-medium">Storage</span>
</div>
<div className="space-y-2">
<Label htmlFor="dedupThreshold">Deduplication Threshold</Label>
<div className="flex items-center gap-4">
<input
id="dedupThreshold"
type="range"
min="0"
max="0.4"
step="0.05"
value={displayConfig.dedupThreshold ?? 0.25}
onChange={(e) => {
setLocalConfig({
...displayConfig,
dedupThreshold: parseFloat(e.target.value),
})
}}
className="flex-1"
/>
<span className="text-sm text-muted-foreground w-12">
{(displayConfig.dedupThreshold ?? 0.25).toFixed(2)}
</span>
</div>
<p className="text-xs text-muted-foreground">
Lower values = more aggressive deduplication (0.0 - 0.4)
</p>
</div>
</div>
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<Cpu className="h-4 w-4 text-orange-500" />
<span className="text-sm font-medium">Plan Execution</span>
</div>
<div className="space-y-2">
<Label htmlFor="executionModel">Execution Model</Label>
<Combobox
value={displayConfig.executionModel ?? ''}
onChange={(value) => {
setLocalConfig({
...displayConfig,
executionModel: value || undefined,
})
}}
options={executionModelOptions}
placeholder="default model"
allowCustomValue
showClear
/>
<p className="text-xs text-muted-foreground">
Model used when executing plans from the Architect. Format: provider/model. Leave empty to use the current session's model.
</p>
</div>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2 border-t pt-4">
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<FileText className="h-4 w-4 text-yellow-500" />
<span className="text-sm font-medium">Logging</span>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="loggingEnabled">Enabled</Label>
<Switch
id="loggingEnabled"
checked={displayConfig.logging?.enabled ?? false}
onCheckedChange={(checked) => handleNestedChange('logging', 'enabled', checked)}
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="loggingDebug">Debug</Label>
<Switch
id="loggingDebug"
checked={displayConfig.logging?.debug ?? false}
onCheckedChange={(checked) => handleNestedChange('logging', 'debug', checked)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="loggingFile">Log File</Label>
<Input
id="loggingFile"
value={displayConfig.logging?.file ?? ''}
onChange={(e) => handleNestedChange('logging', 'file', e.target.value)}
placeholder="Path to log file"
/>
</div>
</div>
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<Layers className="h-4 w-4 text-cyan-500" />
<span className="text-sm font-medium">Compaction</span>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="customPrompt">Custom Prompt</Label>
<Switch
id="customPrompt"
checked={displayConfig.compaction?.customPrompt ?? true}
onCheckedChange={(checked) => handleNestedChange('compaction', 'customPrompt', checked)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxContextTokens">Max Context Tokens</Label>
<Input
id="maxContextTokens"
type="number"
value={displayConfig.compaction?.maxContextTokens ?? 4000}
onChange={(e) => handleNestedChange('compaction', 'maxContextTokens', e.target.value ? parseInt(e.target.value, 10) : undefined)}
placeholder="4000"
/>
</div>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2 border-t pt-4">
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<Syringe className="h-4 w-4 text-pink-500" />
<span className="text-sm font-medium">Memory Injection</span>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="injectionEnabled">Enabled</Label>
<Switch
id="injectionEnabled"
checked={displayConfig.memoryInjection?.enabled ?? true}
onCheckedChange={(checked) => handleNestedChange('memoryInjection', 'enabled', checked)}
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="injectionDebug">Debug</Label>
<Switch
id="injectionDebug"
checked={displayConfig.memoryInjection?.debug ?? false}
onCheckedChange={(checked) => handleNestedChange('memoryInjection', 'debug', checked)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="injectionMaxTokens">Max Tokens</Label>
<Input
id="injectionMaxTokens"
type="number"
value={displayConfig.memoryInjection?.maxTokens ?? 2000}
onChange={(e) => handleNestedChange('memoryInjection', 'maxTokens', e.target.value ? parseInt(e.target.value, 10) : undefined)}
placeholder="2000"
/>
</div>
<div className="space-y-2">
<Label htmlFor="cacheTtlMs">Cache TTL (ms)</Label>
<Input
id="cacheTtlMs"
type="number"
value={displayConfig.memoryInjection?.cacheTtlMs ?? 30000}
onChange={(e) => handleNestedChange('memoryInjection', 'cacheTtlMs', e.target.value ? parseInt(e.target.value, 10) : undefined)}
placeholder="30000"
/>
<p className="text-xs text-muted-foreground">
How long injected memories are cached before re-querying
</p>
</div>
</div>
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<MessageSquare className="h-4 w-4 text-teal-500" />
<span className="text-sm font-medium">Messages Transform</span>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="transformEnabled">Enabled</Label>
<Switch
id="transformEnabled"
checked={displayConfig.messagesTransform?.enabled ?? true}
onCheckedChange={(checked) => handleNestedChange('messagesTransform', 'enabled', checked)}
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="transformDebug">Debug</Label>
<Switch
id="transformDebug"
checked={displayConfig.messagesTransform?.debug ?? false}
onCheckedChange={(checked) => handleNestedChange('messagesTransform', 'debug', checked)}
/>
</div>
</div>
</div>
{displayConfig.dataDir && (
<div className="space-y-2">
<Label>Data Directory</Label>
<Input value={displayConfig.dataDir} disabled className="text-muted-foreground text-xs" />
</div>
)}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<AlertCircle className="h-3 w-3" />
<span>Server will restart automatically after saving</span>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={handleTest}
disabled={testMutation.isPending}
>
{testMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Play className="h-4 w-4 mr-1" />
)}
Test
</Button>
<Button
size="sm"
onClick={handleSave}
disabled={!isDirty || updateMutation.isPending}
>
{updateMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Save className="h-4 w-4 mr-1" />
)}
Save
</Button>
</div>
</div>
</>
)}
</CardContent>
)}
</Card>
)
}
@@ -0,0 +1,101 @@
import { useState } from 'react'
import { useOpenCodeServerAuth } from '@/hooks/useOpenCodeServerAuth'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertTriangle, CheckCircle2, Eye, EyeOff, XCircle } from 'lucide-react'
export function OpenCodeServerAuthSettings() {
const { status, setPassword, clearPassword } = useOpenCodeServerAuth()
const [password, setPasswordValue] = useState('')
const [showPassword, setShowPassword] = useState(false)
const handleSave = () => {
if (password.length >= 8) {
setPassword.mutate(password)
setPasswordValue('')
setShowPassword(false)
}
}
const getStatusText = () => {
if (!status) return 'Loading...'
if (status.source === 'db') return 'Set (configured via UI)'
if (status.source === 'env') return 'Set (configured via env var)'
return 'Not set'
}
const getStatusIcon = () => {
if (!status) return null
if (status.source === 'db') return <CheckCircle2 className="h-4 w-4 text-green-500" />
if (status.source === 'env') return <CheckCircle2 className="h-4 w-4 text-blue-500" />
return <XCircle className="h-4 w-4 text-red-500" />
}
return (
<div className="space-y-4 mb-6">
<div className="rounded-lg border bg-card p-6">
<h3 className="text-lg font-semibold mb-4">OpenCode Server Authentication</h3>
<div className="space-y-4">
<div className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground">Status:</span>
<span className="flex items-center gap-2 font-medium">
{getStatusIcon()}
{getStatusText()}
</span>
</div>
{status?.source === 'none' && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
If you set OPENCODE_HOST=0.0.0.0 in Docker without a password, the server will refuse to start.
</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="password">Password (min 8 characters)</Label>
<div className="flex gap-2">
<Input
id="password"
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPasswordValue(e.target.value)}
placeholder="Enter new password"
className="flex-1"
/>
<Button
variant="outline"
size="icon"
type="button"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
<div className="flex gap-2">
<Button
onClick={handleSave}
disabled={password.length < 8 || setPassword.isPending}
>
{setPassword.isPending ? 'Saving...' : 'Save'}
</Button>
{status?.source === 'db' && (
<Button
variant="outline"
onClick={() => clearPassword.mutate()}
disabled={clearPassword.isPending}
>
{clearPassword.isPending ? 'Clearing...' : 'Clear stored password'}
</Button>
)}
</div>
</div>
</div>
</div>
</div>
)
}
@@ -3,6 +3,7 @@ import { GeneralSettings } from '@/components/settings/GeneralSettings'
import { GitSettings } from '@/components/settings/GitSettings'
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { AccountSettings } from '@/components/settings/AccountSettings'
import { VoiceSettings } from '@/components/settings/VoiceSettings'
@@ -163,7 +164,12 @@ export function SettingsDialog() {
<TabsContent key="voice" value="voice" className="mt-0"><VoiceSettings /></TabsContent>
<TabsContent key="git" value="git" className="mt-0"><GitSettings /></TabsContent>
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
<TabsContent key="opencode" value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
<TabsContent key="opencode" value="opencode" className="mt-0">
<div className="space-y-6">
<OpenCodeServerAuthSettings />
<OpenCodeConfigManager />
</div>
</TabsContent>
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
</div>
</div>
@@ -225,9 +231,14 @@ export function SettingsDialog() {
{mobileView === 'notifications' && <div key="notifications"><NotificationSettings /></div>}
{mobileView === 'voice' && <div key="voice"><VoiceSettings /></div>}
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
{mobileView === 'opencode' && <div key="opencode"><OpenCodeConfigManager /></div>}
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
{mobileView === 'opencode' && (
<div key="opencode" className="space-y-6">
<OpenCodeServerAuthSettings />
<OpenCodeConfigManager />
</div>
)}
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
</div>
</div>
</DialogContent>
@@ -21,9 +21,6 @@ const skillFormSchema = z.object({
description: z.string().min(1, 'Description is required').max(1024, 'Description must be 1024 characters or less'),
body: z.string().min(1, 'Skill body is required'),
scope: z.enum(['global', 'project']),
license: z.string().optional(),
compatibility: z.string().optional(),
metadata: z.record(z.string(), z.string()).optional(),
})
type SkillFormValues = z.infer<typeof skillFormSchema>
@@ -51,9 +48,6 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
description: skill?.description || '',
body: skill?.body || '',
scope: skill?.scope || 'global',
license: skill?.license || '',
compatibility: skill?.compatibility || '',
metadata: skill?.metadata || {},
}
}
@@ -84,9 +78,6 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
repoId: editingSkill.scope === 'project' ? editingSkill.repoId : undefined,
description: values.description,
body: values.body,
license: values.license || undefined,
compatibility: values.compatibility || undefined,
metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined,
})
} else {
onSubmit({
@@ -95,9 +86,6 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
body: values.body,
scope: values.scope,
repoId: values.scope === 'project' ? selectedRepoId : undefined,
license: values.license || undefined,
compatibility: values.compatibility || undefined,
metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined,
})
}
form.reset()
@@ -204,68 +192,28 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
/>
{scope === 'project' && (
<FormField
control={form.control}
name="metadata"
render={() => (
<FormItem>
<FormLabel>Repository</FormLabel>
<FormControl>
<Select
value={selectedRepoId?.toString()}
onValueChange={(value) => setSelectedRepoId(value ? parseInt(value, 10) : undefined)}
>
<SelectTrigger>
<SelectValue placeholder="Select repository" />
</SelectTrigger>
<SelectContent>
{repos.map((repo) => (
<SelectItem key={repo.id} value={repo.id.toString()}>
{repo.localPath}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormItem>
<FormLabel>Repository</FormLabel>
<FormControl>
<Select
value={selectedRepoId?.toString()}
onValueChange={(value) => setSelectedRepoId(value ? parseInt(value, 10) : undefined)}
>
<SelectTrigger>
<SelectValue placeholder="Select repository" />
</SelectTrigger>
<SelectContent>
{repos.map((repo) => (
<SelectItem key={repo.id} value={repo.id.toString()}>
{repo.localPath}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
<FormField
control={form.control}
name="license"
render={({ field }) => (
<FormItem>
<FormLabel>License (Optional)</FormLabel>
<FormControl>
<Input
{...field}
placeholder="MIT"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="compatibility"
render={({ field }) => (
<FormItem>
<FormLabel>Compatibility (Optional)</FormLabel>
<FormControl>
<Input
{...field}
placeholder="opencode"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</Form>
</div>
+2 -2
View File
@@ -25,7 +25,7 @@ export function BottomSheet({
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
enabled: isOpen,
threshold: 80,
threshold: 60,
})
useEffect(() => {
@@ -63,7 +63,7 @@ export function BottomSheet({
return (
<div
className="fixed inset-0 z-50"
className="fixed inset-0 z-[60]"
style={{
opacity: isOpen ? 1 : 0,
pointerEvents: isOpen ? 'auto' : 'none',
+1 -1
View File
@@ -11,7 +11,7 @@ export const PageHeader = React.forwardRef<HTMLElement, PageHeaderProps>(
<header
ref={ref}
className={cn(
"sticky top-0 z-10 bg-gradient-to-b from-background via-background to-background backdrop-blur-sm pt-safe",
"sticky top-0 z-10 bg-transparent pt-safe",
className
)}
{...props}