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

+10 -7
View File
@@ -6,7 +6,6 @@ import { Toaster } from 'sonner'
import { Repos } from './pages/Repos'
import { RepoDetail } from './pages/RepoDetail'
import { SessionDetail } from './pages/SessionDetail'
import { Memories } from './pages/Memories'
import { Schedules } from './pages/Schedules'
import { GlobalSchedules } from './pages/GlobalSchedules'
import { Login } from './pages/Login'
@@ -30,6 +29,8 @@ import { PermissionRequestDialog } from './components/session/PermissionRequestD
import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog'
import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders'
import { getSwipeBackTarget } from '@/lib/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
const queryClient = new QueryClient({
defaultOptions: {
@@ -52,6 +53,12 @@ function SSHHostKeyDialogWrapper() {
)
}
function HealthMonitor() {
const { isAuthenticated } = useAuth()
useServerHealth(isAuthenticated)
return null
}
function PermissionDialogWrapper() {
const {
current: currentPermission,
@@ -115,7 +122,7 @@ function AppShell() {
{
enabled: canOpenMoreWithSwipe(),
edgeWidth: 32,
threshold: 72,
threshold: 60,
}
)
@@ -158,6 +165,7 @@ function AppShell() {
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
<PwaUpdatePrompt />
<Toaster
@@ -216,11 +224,6 @@ const router = createBrowserRouter([
element: <SessionDetail />,
loader: protectedLoader,
},
{
path: '/repos/:id/memories',
element: <Memories />,
loader: protectedLoader,
},
{
path: '/repos/:id/schedules',
element: <Schedules />,
-136
View File
@@ -1,136 +0,0 @@
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig, KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest, LoopState } from '@opencode-manager/shared/types'
export async function listMemories(filters?: {
projectId?: string
scope?: string
content?: string
limit?: number
offset?: number
}): Promise<{ memories: Memory[] }> {
const params = new URLSearchParams()
if (filters?.projectId) params.set('projectId', filters.projectId)
if (filters?.scope) params.set('scope', filters.scope)
if (filters?.content) params.set('content', filters.content)
if (filters?.limit) params.set('limit', String(filters.limit))
if (filters?.offset) params.set('offset', String(filters.offset))
const query = params.toString()
return fetchWrapper(`${API_BASE_URL}/api/memory${query ? `?${query}` : ''}`)
}
export async function createMemory(data: CreateMemoryRequest): Promise<{ memory: Memory }> {
return fetchWrapper(`${API_BASE_URL}/api/memory`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function getMemory(id: number): Promise<{ memory: Memory }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/${id}`)
}
export async function updateMemory(id: number, data: UpdateMemoryRequest): Promise<{ memory: Memory }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function deleteMemory(id: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/memory/${id}`, {
method: 'DELETE',
})
}
export async function getProjectSummary(
repoId: number
): Promise<{ projectId: string | null; stats: MemoryStats; error?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/project-summary?repoId=${repoId}`)
}
export async function getPluginConfig(): Promise<{ config: PluginConfig }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/plugin-config`)
}
export async function updatePluginConfig(config: PluginConfig): Promise<{ success: boolean; config: PluginConfig }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/plugin-config`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config),
})
}
export interface ReindexResult {
success: boolean
message: string
total: number
embedded: number
failed: number
requiresRestart?: boolean
}
export async function reindexMemories(): Promise<ReindexResult> {
return fetchWrapper(`${API_BASE_URL}/api/memory/reindex`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
}
export interface TestEmbeddingResult {
success: boolean
error?: string
message?: string
dimensions?: number
}
export async function testEmbeddingConfig(): Promise<TestEmbeddingResult> {
return fetchWrapper(`${API_BASE_URL}/api/memory/test-embedding`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
}
export async function listKvEntries(projectId: string, prefix?: string): Promise<{ entries: KvEntry[] }> {
const params = new URLSearchParams({ projectId })
if (prefix) params.set('prefix', prefix)
return fetchWrapper(`${API_BASE_URL}/api/memory/kv?${params.toString()}`)
}
export async function deleteKvEntry(projectId: string, key: string): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/memory/kv/${encodeURIComponent(key)}?projectId=${encodeURIComponent(projectId)}`, {
method: 'DELETE',
})
}
export async function createKvEntry(data: CreateKvEntryRequest): Promise<{ entry: KvEntry }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/kv`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function updateKvEntry(projectId: string, key: string, data: UpdateKvEntryRequest): Promise<{ entry: KvEntry }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/kv/${encodeURIComponent(key)}?projectId=${encodeURIComponent(projectId)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function getLoopStatus(repoId: number): Promise<{ loops: LoopState[]; projectId?: string | null }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/loop/status?repoId=${repoId}`)
}
export async function cancelLoop(repoId: number, sessionId: string): Promise<{ cancelled: boolean; worktreeName?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/loop/cancel`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repoId, sessionId }),
})
}
+20 -4
View File
@@ -1,14 +1,16 @@
import type { paths } from './opencode-types'
import { fetchWrapper } from './fetchWrapper'
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
type CreateSessionRequest = NonNullable<paths['/session']['post']['requestBody']>['content']['application/json']
type MessageListResponse = paths['/session/{sessionID}/message']['get']['responses']['200']['content']['application/json']
type SendPromptRequest = NonNullable<paths['/session/{sessionID}/message']['post']['requestBody']>['content']['application/json']
type SendPromptAsyncRequest = NonNullable<paths['/session/{sessionID}/prompt_async']['post']['requestBody']>['content']['application/json']
type ConfigResponse = paths['/config']['get']['responses']['200']['content']['application/json']
type CommandListResponse = paths['/command']['get']['responses']['200']['content']['application/json']
type CommandRequest = NonNullable<paths['/session/{sessionID}/command']['post']['requestBody']>['content']['application/json']
type SendCommandResponse = paths['/session/{sessionID}/command']['post']['responses']['200']['content']['application/json']
type ShellRequest = NonNullable<paths['/session/{sessionID}/shell']['post']['requestBody']>['content']['application/json']
type AgentListResponse = paths['/agent']['get']['responses']['200']['content']['application/json']
type PermissionListResponse = paths['/permission']['get']['responses']['200']['content']['application/json']
@@ -17,7 +19,7 @@ type SendPromptResponse = paths['/session/{sessionID}/message']['post']['respons
type LspStatusResponse = paths['/lsp']['get']['responses']['200']['content']['application/json']
type LspStatus = LspStatusResponse[number]
export type { SendPromptResponse, LspStatus }
export type { SendPromptResponse, SendCommandResponse, LspStatus }
export class OpenCodeClient {
private baseURL: string
@@ -109,6 +111,19 @@ export class OpenCodeClient {
)
}
async sendPromptAsync(sessionID: string, data: SendPromptAsyncRequest): Promise<void> {
return fetchWrapperVoid(
`${this.baseURL}/session/${sessionID}/prompt_async`,
{
method: 'POST',
params: this.getParams(),
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
timeout: 0,
}
)
}
async summarizeSession(sessionID: string, providerID: string, modelID: string) {
return fetchWrapper(`${this.baseURL}/session/${sessionID}/summarize`, {
method: 'POST',
@@ -157,12 +172,13 @@ export class OpenCodeClient {
})
}
async sendCommand(sessionID: string, data: CommandRequest) {
return fetchWrapper(`${this.baseURL}/session/${sessionID}/command`, {
async sendCommand(sessionID: string, data: CommandRequest): Promise<SendCommandResponse> {
return fetchWrapper<SendCommandResponse>(`${this.baseURL}/session/${sessionID}/command`, {
method: 'POST',
params: this.getParams(),
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
timeout: 0,
})
}
+17 -4
View File
@@ -229,10 +229,6 @@ export const settingsApi = {
return fetchWrapper(`${API_BASE_URL}/api/health/version`)
},
getMemoryPluginStatus: async (): Promise<{ memoryPluginEnabled: boolean }> => {
return fetchWrapper(`${API_BASE_URL}/api/settings/memory-plugin-status`)
},
listManagedSkills: async (repoId?: number): Promise<SkillFileInfo[]> => {
const params = repoId ? `?repoId=${repoId}` : ''
return fetchWrapper(`${API_BASE_URL}/api/settings/skills${params}`)
@@ -278,3 +274,20 @@ export interface VersionInfo {
releaseUrl: string | null
releaseName: string | null
}
export interface OpenCodeServerAuthStatus {
isSet: boolean
source: 'db' | 'env' | 'none'
}
export async function getOpenCodeServerAuth(): Promise<OpenCodeServerAuthStatus> {
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`)
}
export async function updateOpenCodeServerAuth(password: string | null): Promise<OpenCodeServerAuthStatus> {
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
})
}
-1
View File
@@ -63,7 +63,6 @@ export interface UserPreferences {
notifications?: NotificationPreferences
repoOrder?: number[]
repoSortMode?: 'recent' | 'manual' | 'name'
memoryDedupThreshold?: number
}
export interface SettingsResponse {
@@ -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}
+77 -14
View File
@@ -1,11 +1,11 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { PermissionRequest, QuestionRequest } from '@/api/types'
import { EventProvider, usePermissions, useQuestions } from './EventContext'
import { EventProvider, usePermissions, useQuestions, useSSEHealth } from './EventContext'
const mocks = vi.hoisted(() => ({
listRepos: vi.fn(),
@@ -13,9 +13,8 @@ const mocks = vi.hoisted(() => ({
listPendingQuestions: vi.fn(),
replyToQuestion: vi.fn(),
rejectQuestion: vi.fn(),
subscribeToSSE: vi.fn(),
addSSEDirectory: vi.fn(),
ensureSSEConnected: vi.fn(),
subscribeGlobalMonitor: vi.fn(),
getHealth: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
@@ -31,10 +30,11 @@ vi.mock('@/api/opencode', () => ({
})),
}))
vi.mock('@/lib/sseManager', () => ({
subscribeToSSE: mocks.subscribeToSSE,
addSSEDirectory: mocks.addSSEDirectory,
ensureSSEConnected: mocks.ensureSSEConnected,
vi.mock('@/lib/opencode-event-stream', () => ({
openCodeEventStream: {
subscribeGlobalMonitor: mocks.subscribeGlobalMonitor,
getHealth: mocks.getHealth,
},
}))
vi.mock('@/lib/toast', () => ({
@@ -140,9 +140,13 @@ describe('EventProvider questions', () => {
mocks.listPendingQuestions.mockResolvedValue([])
mocks.replyToQuestion.mockResolvedValue(undefined)
mocks.rejectQuestion.mockResolvedValue(undefined)
mocks.subscribeToSSE.mockReturnValue(() => {})
mocks.addSSEDirectory.mockReturnValue(() => {})
mocks.ensureSSEConnected.mockResolvedValue(true)
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
reconnect: vi.fn(),
reportVisibility: vi.fn(),
})
})
it('syncs missed pending questions for a session', async () => {
@@ -247,8 +251,8 @@ describe('EventProvider questions', () => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
const lastSubscribeCall = mocks.subscribeToSSE.mock.calls[mocks.subscribeToSSE.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[1] as (connected: boolean) => void
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
handleStatusChange(true)
await waitFor(() => {
@@ -313,4 +317,63 @@ describe('EventProvider questions', () => {
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
it('adds a pending question received via the global monitor onEvent', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()
})
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({
type: 'question.asked',
properties: pendingQuestion,
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
expect(screen.getByTestId('current')).toHaveTextContent('question-1')
})
})
it('exposes sseHealth through context', async () => {
mocks.getHealth.mockReturnValue({ isConnected: true, isHealthy: true, lastEventAt: Date.now(), isStalled: false })
mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange }) => {
onHealthChange({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
return {
dispose: vi.fn(),
updateDirectories: vi.fn(),
reconnect: vi.fn(),
reportVisibility: vi.fn(),
}
})
const TestComponent = () => {
const { isConnected, isHealthy, isStalled } = useSSEHealth()
return (
<div>
<div data-testid="connected">{String(isConnected)}</div>
<div data-testid="healthy">{String(isHealthy)}</div>
<div data-testid="stalled">{String(isStalled)}</div>
</div>
)
}
render(<TestComponent />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByTestId('connected')).toHaveTextContent('false')
expect(screen.getByTestId('healthy')).toHaveTextContent('false')
})
})
})
+34 -35
View File
@@ -6,7 +6,7 @@ import { OpenCodeClient } from '@/api/opencode'
import { listRepos } from '@/api/repos'
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts } from '@/api/types'
import { showToast } from '@/lib/toast'
import { subscribeToSSE, addSSEDirectory, ensureSSEConnected } from '@/lib/sseManager'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
@@ -149,6 +149,7 @@ interface EventContextValue {
navigateToCurrent: () => void
syncForSession: (directory: string, sessionID: string) => Promise<void>
}
sseHealth: EventStreamHealthState
getRepoIdForSession: (sessionID: string) => number | null
getClient: (sessionID: string) => OpenCodeClient | null
}
@@ -160,6 +161,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const navigate = useNavigate()
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
const [sseHealth, setSseHealth] = useState<EventStreamHealthState>(() => openCodeEventStream.getHealth())
const respondToSSHHostKey = useCallback(async (requestId: string, approved: boolean) => {
try {
@@ -179,6 +181,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
const prevPermissionCountRef = useRef(0)
const initialFetchDoneRef = useRef(false)
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
const reposRef = useRef<typeof repos>(null)
const MAX_CACHED_CLIENTS = 50
useEffect(() => {
@@ -320,11 +324,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [allPermissions.length, showPermissionDialog])
const respondToPermission = useCallback(async (permissionID: string, sessionID: string, response: PermissionResponse) => {
const connected = await ensureSSEConnected()
if (!connected) {
showToast.error('Unable to connect. Please try again.')
throw new Error('SSE connection failed')
}
const client = getClient(sessionID)
if (!client) throw new Error('No client found for session')
@@ -340,11 +339,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [getClient, permissionsBySession, queryClient, removePermission])
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
const connected = await ensureSSEConnected()
if (!connected) {
showToast.error('Unable to connect. Please try again.')
throw new Error('SSE connection failed')
}
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
if (!question) throw new Error('Question not found')
const client = getClient(question.sessionID)
@@ -354,11 +348,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [getClient, questionsBySession, removeQuestion])
const rejectQuestion = useCallback(async (requestID: string) => {
const connected = await ensureSSEConnected()
if (!connected) {
showToast.error('Unable to connect. Please try again.')
throw new Error('SSE connection failed')
}
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
if (!question) throw new Error('Question not found')
const client = getClient(question.sessionID)
@@ -416,9 +405,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [currentPermission, getRepoIdForSession, navigate])
const fetchInitialPendingData = useCallback(async () => {
if (!repos || repos.length === 0) return
const reposToUse = reposRef.current
if (!reposToUse || reposToUse.length === 0) return
const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))]
const uniqueDirectories = [...new Set(reposToUse.map(r => r.fullPath))]
for (const directory of uniqueDirectories) {
try {
@@ -433,7 +423,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
}
}
}, [repos, reconcilePermissionsForDirectory, reconcileQuestionsForDirectory])
}, [reconcilePermissionsForDirectory, reconcileQuestionsForDirectory])
const syncPermissionsForSession = useCallback(async (directory: string, sessionID: string) => {
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
@@ -527,24 +517,27 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
}
const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange)
return unsubscribe
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient])
const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))]
const subscription = openCodeEventStream.subscribeGlobalMonitor({
directories: initialDirectories,
onEvent: handleSSEMessage,
onStatusChange: handleStatusChange,
onHealthChange: setSseHealth,
})
subscriptionRef.current = subscription
return () => {
subscription.dispose()
subscriptionRef.current = null
}
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient, setSseHealth])
useEffect(() => {
if (!repos || repos.length === 0) return
const cleanupFns: (() => void)[] = []
const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))]
uniqueDirectories.forEach(directory => {
const cleanup = addSSEDirectory(directory)
cleanupFns.push(cleanup)
})
return () => {
cleanupFns.forEach(fn => fn())
}
reposRef.current = repos
const sub = subscriptionRef.current
if (!sub) return
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
sub.updateDirectories(directories)
}, [repos])
useEffect(() => {
@@ -583,6 +576,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
navigateToCurrent: navigateToCurrentQuestion,
syncForSession: syncQuestionsForSession,
},
sseHealth,
getRepoIdForSession,
getClient,
}), [
@@ -606,6 +600,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
hasQuestionsForSession,
navigateToCurrentQuestion,
syncQuestionsForSession,
sseHealth,
getRepoIdForSession,
getClient,
])
@@ -635,3 +630,7 @@ export function usePendingAlerts(): boolean {
const { permissions, questions } = useEventContext()
return permissions.pendingCount + questions.pendingCount > 0
}
export function useSSEHealth(): EventStreamHealthState {
return useEventContext().sseHealth
}
@@ -0,0 +1,119 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useCommandHandler } from '../useCommandHandler'
const mocks = vi.hoisted(() => ({
sendCommand: vi.fn(),
summarizeSession: vi.fn(),
setStatus: vi.fn(),
}))
vi.mock('@/api/opencode', () => ({
createOpenCodeClient: vi.fn().mockImplementation(() => ({
sendCommand: mocks.sendCommand,
summarizeSession: mocks.summarizeSession,
})),
}))
vi.mock('@/lib/toast', () => ({
showToast: {
error: vi.fn(),
success: vi.fn(),
info: vi.fn(),
loading: vi.fn(),
},
}))
vi.mock('@/hooks/useOpenCode', () => ({
useCreateSession: vi.fn(() => ({
mutateAsync: vi.fn(),
})),
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({
model: { providerID: 'test-provider', modelID: 'test-model' },
modelString: 'test-provider/test-model',
})),
}))
vi.mock('react-router-dom', () => ({
useNavigate: vi.fn(() => vi.fn()),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })),
}))
describe('useCommandHandler', () => {
const baseProps = {
opcodeUrl: 'http://localhost:5551',
sessionID: 'test-session-id',
directory: '/test/dir',
currentAgent: 'test-agent',
}
beforeEach(() => {
vi.clearAllMocks()
})
it('themes command sends command', async () => {
mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1' }, parts: [] })
const { result } = renderHook(() => useCommandHandler(baseProps))
const themesCommand = { name: 'themes' as const }
await result.current.executeCommand(themesCommand, '')
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', {
command: 'themes',
arguments: '',
agent: 'test-agent',
model: 'test-provider/test-model',
})
})
it('compact command summarizes session', async () => {
mocks.summarizeSession.mockResolvedValue(undefined)
const { result } = renderHook(() => useCommandHandler(baseProps))
const compactCommand = { name: 'compact' as const }
await result.current.executeCommand(compactCommand, '')
expect(mocks.summarizeSession).toHaveBeenCalledWith(
'test-session-id',
'test-provider',
'test-model'
)
})
it('unknown command sends command', async () => {
mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1' }, parts: [] })
const { result } = renderHook(() => useCommandHandler(baseProps))
const unknownCommand = { name: 'myskill' as const }
await result.current.executeCommand(unknownCommand, '')
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', {
command: 'myskill',
arguments: '',
agent: 'test-agent',
model: 'test-provider/test-model',
})
})
it('sessions command opens sessions dialog without sending command', async () => {
const onShowSessionsDialog = vi.fn()
const { result } = renderHook(() =>
useCommandHandler({ ...baseProps, onShowSessionsDialog })
)
const sessionsCommand = { name: 'sessions' as const }
await result.current.executeCommand(sessionsCommand, '')
expect(mocks.sendCommand).not.toHaveBeenCalled()
expect(onShowSessionsDialog).toHaveBeenCalled()
})
})
@@ -0,0 +1,250 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useLoadSkill } from '../useOpenCode'
import type { MessageWithParts } from '../../api/types'
import { showToast } from '../../lib/toast'
const mocks = vi.hoisted(() => ({
sendCommand: vi.fn(),
setStatus: vi.fn(),
}))
vi.mock('../../api/opencode', () => ({
OpenCodeClient: vi.fn().mockImplementation(() => ({
sendCommand: mocks.sendCommand,
})),
}))
vi.mock('../../lib/toast', () => ({
showToast: {
error: vi.fn(),
success: vi.fn(),
info: vi.fn(),
},
}))
vi.mock('../../stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })),
}))
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
describe('useLoadSkill', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('calls sendCommand with correct parameters when mutate is called', async () => {
const mockResponse = {
info: { id: 'asm_1', sessionID: 'test-session-id', role: 'assistant' },
parts: []
}
mocks.sendCommand.mockResolvedValue(mockResponse)
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper: createWrapper() }
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isSuccess).toBe(true)
})
expect(mocks.sendCommand).toHaveBeenCalledTimes(1)
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', {
command: 'my-skill',
arguments: '',
})
})
it('throws error when sessionID is undefined', async () => {
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', undefined, '/test/dir'),
{ wrapper: createWrapper() }
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isError).toBe(true)
})
expect(result.current.error).toBeInstanceOf(Error)
expect((result.current.error as Error).message).toBe('No active session')
})
it('throws error when client is not available', async () => {
const { result } = renderHook(
() => useLoadSkill(null, 'test-session-id', '/test/dir'),
{ wrapper: createWrapper() }
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isError).toBe(true)
})
expect(result.current.error).toBeInstanceOf(Error)
expect((result.current.error as Error).message).toBe('No OpenCode client available')
})
it('calls showToast.error when sendCommand fails', async () => {
const testError = new Error('Command failed')
mocks.sendCommand.mockRejectedValue(testError)
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper: createWrapper() }
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isError).toBe(true)
})
expect(showToast.error).toHaveBeenCalledTimes(1)
expect(showToast.error).toHaveBeenCalledWith('Command failed')
})
it('calls showToast.error with default message for non-Error objects', async () => {
mocks.sendCommand.mockRejectedValue('string error')
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper: createWrapper() }
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isError).toBe(true)
})
expect(showToast.error).toHaveBeenCalledTimes(1)
expect(showToast.error).toHaveBeenCalledWith('Failed to load skill')
})
it('adds optimistic user message with skill name on mutate', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const messagesKey = ['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir']
queryClient.setQueryData(messagesKey, [])
mocks.sendCommand.mockReturnValue(new Promise(() => {}))
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> },
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
const messages = queryClient.getQueryData<MessageWithParts[]>(messagesKey)
expect(messages).toHaveLength(1)
expect(messages?.[0].info.id).toMatch(/^optimistic_user_/)
expect((messages?.[0].parts[0] as { text?: string }).text).toBe('Loading skill: my-skill')
})
})
it('sets session status to busy on mutate and idle on error', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const testError = new Error('Command failed')
mocks.sendCommand.mockRejectedValue(testError)
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> },
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isError).toBe(true)
})
expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'busy' })
expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'idle' })
})
it('removes optimistic message from cache on error', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const messagesKey = ['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir']
queryClient.setQueryData(messagesKey, [])
const testError = new Error('Command failed')
mocks.sendCommand.mockRejectedValue(testError)
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> },
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isError).toBe(true)
})
const messages = queryClient.getQueryData<MessageWithParts[]>(messagesKey)
expect(messages).toHaveLength(0)
})
it('replaces optimistic message with assistant response on success', async () => {
const assistant = {
info: { id: 'asm_skill_1', sessionID: 'test-session-id', role: 'assistant' },
parts: [{ type: 'text', text: 'done' }]
}
mocks.sendCommand.mockResolvedValue(assistant)
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const wrapper = ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
const { result } = renderHook(
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
{ wrapper }
)
result.current.mutate({ skillName: 'my-skill' })
await waitFor(() => {
expect(result.current.isSuccess).toBe(true)
})
const messages = queryClient.getQueryData<MessageWithParts[]>(['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir'])
expect(messages?.some(m => m.info.id === 'asm_skill_1')).toBe(true)
})
})
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useMessages } from '../useOpenCode'
const mocks = vi.hoisted(() => ({
listMessages: vi.fn(),
}))
vi.mock('@/api/opencode', () => ({
OpenCodeClient: vi.fn(() => ({
listMessages: mocks.listMessages,
})),
}))
describe('useMessages fallback poll', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const createQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={createQueryClient()}>
{children}
</QueryClientProvider>
)
it('should poll every 5s when fallbackPoll is enabled', async () => {
vi.useFakeTimers()
mocks.listMessages.mockResolvedValue([])
renderHook(
() => useMessages('http://localhost:5003', 'session-1', '/repo', { fallbackPoll: true }),
{ wrapper }
)
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(5000)
await waitFor(() => {
expect(mocks.listMessages).toHaveBeenCalledTimes(2)
})
vi.useRealTimers()
})
it('should not poll when fallbackPoll is disabled', async () => {
vi.useFakeTimers()
mocks.listMessages.mockResolvedValue([])
renderHook(
() => useMessages('http://localhost:5003', 'session-1', '/repo', { fallbackPoll: false }),
{ wrapper }
)
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(15000)
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
it('should not poll by default (no opts)', async () => {
vi.useFakeTimers()
mocks.listMessages.mockResolvedValue([])
renderHook(
() => useMessages('http://localhost:5003', 'session-1', '/repo'),
{ wrapper }
)
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(15000)
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
})
+301
View File
@@ -0,0 +1,301 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useAutoScroll } from './useAutoScroll'
import type { Message } from '../api/types'
function createScrollContainer() {
const div = document.createElement('div')
document.body.appendChild(div)
let scrollTopValue = 0
const clientHeight = 400
let scrollHeightValue = 800
Object.defineProperty(div, 'clientHeight', {
configurable: true,
get: () => clientHeight,
})
Object.defineProperty(div, 'scrollHeight', {
configurable: true,
get: () => scrollHeightValue,
})
Object.defineProperty(div, 'scrollTop', {
configurable: true,
get: () => scrollTopValue,
set: (value: number) => {
scrollTopValue = Math.max(0, Math.min(value, scrollHeightValue - clientHeight))
div.dispatchEvent(new Event('scroll'))
},
})
return {
div,
setScrollHeight: (value: number) => {
scrollHeightValue = value
},
getScrollTop: () => scrollTopValue,
setScrollTop: (value: number) => {
scrollTopValue = value
},
cleanup: () => {
document.body.removeChild(div)
},
}
}
describe('useAutoScroll', () => {
let containerHarness: ReturnType<typeof createScrollContainer> | null = null
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
if (containerHarness) {
containerHarness.cleanup()
containerHarness = null
}
vi.restoreAllMocks()
vi.clearAllTimers()
})
const createMessage = (id: string, role: 'user' | 'assistant'): Message => ({
id,
sessionID: 'session-1',
role,
time: { created: Date.now() },
} as Message)
const setupHook = (messages: Message[], sessionId = 'session-1') => {
containerHarness = createScrollContainer()
const containerRef = { current: containerHarness.div }
const onScrollStateChange = vi.fn()
const renderResult = renderHook(
(props) =>
useAutoScroll({
containerRef: props.containerRef,
messages: props.messages,
sessionId: props.sessionId,
contentVersion: props.contentVersion,
onScrollStateChange: props.onScrollStateChange,
}),
{
initialProps: {
containerRef,
messages,
sessionId,
contentVersion: messages.length,
onScrollStateChange,
},
}
)
return { renderResult, containerHarness, onScrollStateChange }
}
it('scrolls to bottom on initial messages', () => {
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
const { containerHarness } = setupHook(messages)
act(() => {
vi.advanceTimersByTime(100)
})
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
it('auto-follows when new assistant message arrives', () => {
const messages = [createMessage('1', 'user')]
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
act(() => {
vi.advanceTimersByTime(100)
})
const initialScrollTop = containerHarness.getScrollTop()
expect(initialScrollTop).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 200)
const newMessages = [...messages, createMessage('2', 'assistant')]
act(() => {
renderResult.rerender({
containerRef: { current: containerHarness.div },
messages: newMessages,
sessionId: 'session-1',
contentVersion: newMessages.length,
onScrollStateChange,
})
vi.advanceTimersByTime(100)
})
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
it('stays engaged after scrollToBottom() through streaming reflow drift', () => {
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
act(() => {
renderResult.result.current.scrollToBottom()
})
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
containerHarness.setScrollTop(bottomPosition - 2)
act(() => {
containerHarness.div.dispatchEvent(new Event('scroll'))
})
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 100)
act(() => {
renderResult.rerender({
containerRef: { current: containerHarness.div },
messages,
sessionId: 'session-1',
contentVersion: messages.length + 1,
onScrollStateChange,
})
})
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
it('disengages when user fires a wheel-up event', () => {
const messages = [createMessage('1', 'user')]
const { containerHarness, onScrollStateChange } = setupHook(messages)
act(() => {
containerHarness.div.dispatchEvent(
new WheelEvent('wheel', {
deltaY: -50,
bubbles: true,
})
)
})
expect(onScrollStateChange).toHaveBeenCalledWith(true)
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
containerHarness.setScrollHeight(bottomPosition + 200)
const currentScrollTop = containerHarness.getScrollTop()
expect(currentScrollTop).not.toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
it('disengages when user drags upward (pointer down -> move up -> up)', () => {
const messages = [createMessage('1', 'user')]
const { containerHarness, onScrollStateChange } = setupHook(messages)
act(() => {
containerHarness.div.dispatchEvent(
new PointerEvent('pointerdown', {
clientY: 200,
bubbles: true,
})
)
containerHarness.div.dispatchEvent(
new PointerEvent('pointermove', {
clientY: 260,
bubbles: true,
})
)
})
expect(onScrollStateChange).toHaveBeenCalledWith(true)
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
containerHarness.setScrollHeight(bottomPosition + 200)
const currentScrollTop = containerHarness.getScrollTop()
expect(currentScrollTop).not.toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
it('re-engages when user scrolls back to within threshold', () => {
const messages = [createMessage('1', 'user')]
const { containerHarness, onScrollStateChange } = setupHook(messages)
act(() => {
containerHarness.div.dispatchEvent(
new WheelEvent('wheel', {
deltaY: -50,
bubbles: true,
})
)
})
expect(onScrollStateChange).toHaveBeenCalledWith(true)
const scrollHeight = containerHarness.div.scrollHeight
const clientHeight = containerHarness.div.clientHeight
const withinThresholdPosition = scrollHeight - clientHeight - 30
act(() => {
containerHarness.setScrollTop(withinThresholdPosition)
})
expect(onScrollStateChange).toHaveBeenCalledWith(false)
})
it('always scrolls to bottom when user sends a message', () => {
const messages = [createMessage('1', 'assistant')]
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
act(() => {
containerHarness.div.dispatchEvent(
new WheelEvent('wheel', {
deltaY: -50,
bubbles: true,
})
)
})
expect(onScrollStateChange).toHaveBeenCalledWith(true)
const newMessages = [...messages, createMessage('2', 'user')]
act(() => {
renderResult.rerender({
containerRef: { current: containerHarness.div },
messages: newMessages,
sessionId: 'session-1',
contentVersion: newMessages.length,
onScrollStateChange,
})
})
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
it('resets state when sessionId changes', () => {
const messages = [createMessage('1', 'user')]
const { renderResult, containerHarness } = setupHook(messages, 'session-1')
act(() => {
containerHarness.div.dispatchEvent(
new WheelEvent('wheel', {
deltaY: -50,
bubbles: true,
})
)
})
const newMessages = [createMessage('2', 'user')]
act(() => {
renderResult.rerender({
containerRef: { current: containerHarness.div },
messages: newMessages,
sessionId: 'session-2',
contentVersion: newMessages.length,
onScrollStateChange: vi.fn(),
})
})
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
})
})
+10 -8
View File
@@ -2,6 +2,7 @@ import { useRef, useEffect, useCallback } from 'react'
import type { Message } from '@/api/types'
const SCROLL_LOCK_MS = 300
const BOTTOM_THRESHOLD_PX = 48
interface UseAutoScrollOptions {
containerRef?: React.RefObject<HTMLDivElement | null>
@@ -52,6 +53,9 @@ export function useAutoScroll({
const markDisengaged = () => {
userScrolledAtRef.current = Date.now()
if (!userDisengagedRef.current) {
onScrollStateChangeRef.current?.(true)
}
userDisengagedRef.current = true
}
@@ -84,20 +88,18 @@ export function useAutoScroll({
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = container
const isAtBottom = scrollHeight - scrollTop - clientHeight < 150
const isAtBottom = scrollHeight - scrollTop - clientHeight < BOTTOM_THRESHOLD_PX
if (isAtBottom) {
if (userDisengagedRef.current) {
userScrolledAtRef.current = 0
userDisengagedRef.current = false
onScrollStateChangeRef.current?.(false)
}
} else {
if (!userDisengagedRef.current) {
userScrolledAtRef.current = Date.now()
userDisengagedRef.current = true
onScrollStateChangeRef.current?.(true)
}
} else if (!userDisengagedRef.current) {
userScrolledAtRef.current = Date.now()
userDisengagedRef.current = true
onScrollStateChangeRef.current?.(true)
}
}
+7 -4
View File
@@ -57,7 +57,7 @@ export function useCommandHandler({
onShowModelsDialog?.()
break
case 'themes':
case 'themes': {
await client.sendCommand(sessionID, {
command: command.name,
arguments: args,
@@ -65,6 +65,7 @@ export function useCommandHandler({
model: modelString || undefined
})
break
}
case 'help':
onShowHelpDialog?.()
@@ -130,7 +131,7 @@ export function useCommandHandler({
case 'undo':
case 'redo':
case 'editor':
case 'init':
case 'init': {
await client.sendCommand(sessionID, {
command: command.name,
arguments: args,
@@ -138,14 +139,16 @@ export function useCommandHandler({
model: modelString || undefined
})
break
}
default:
default: {
await client.sendCommand(sessionID, {
command: command.name,
arguments: args,
agent: currentAgent,
model: modelString || undefined
})
}
}
} catch (error) {
showToast.error(`Command failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
@@ -159,4 +162,4 @@ export function useCommandHandler({
executeCommand,
loading
}
}
}
-48
View File
@@ -1,48 +0,0 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getLoopStatus, cancelLoop } from '@/api/memory'
import { showToast } from '@/lib/toast'
export function useLoopStatus(repoId: number | undefined, open: boolean) {
const queryClient = useQueryClient()
const { data, isLoading, error } = useQuery({
queryKey: ['memory-loop-status', repoId],
queryFn: () => getLoopStatus(repoId!),
enabled: open && !!repoId,
staleTime: 0,
refetchInterval: ({ state }) => {
const loops = state.data?.loops ?? []
return loops.some(l => l.active) ? 5000 : false
},
})
const cancelMutation = useMutation({
mutationFn: ({ sessionId }: { sessionId: string }) =>
cancelLoop(repoId!, sessionId),
onSuccess: (result) => {
if (result.cancelled) {
queryClient.invalidateQueries({ queryKey: ['memory-loop-status', repoId] })
} else {
showToast.error('Memory loop is no longer active')
}
},
onError: () => {
showToast.error('Unable to cancel the memory loop. Please try again.')
},
})
const pendingSessionId = cancelMutation.isPending ? (cancelMutation.variables?.sessionId ?? null) : null
return { data, isLoading, error, cancelMutation, pendingSessionId }
}
export function useLoopActiveCount(repoId: number | undefined, enabled: boolean) {
const { data } = useQuery({
queryKey: ['memory-loop-status', repoId],
queryFn: () => getLoopStatus(repoId!),
enabled: enabled && !!repoId,
staleTime: 0,
refetchInterval: 10000,
})
return data?.loops.filter(l => l.active).length ?? 0
}
-156
View File
@@ -1,156 +0,0 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
listMemories,
createMemory,
getMemory,
updateMemory,
deleteMemory,
getProjectSummary,
listKvEntries,
deleteKvEntry,
createKvEntry,
updateKvEntry,
} from '@/api/memory'
import type { CreateMemoryRequest, UpdateMemoryRequest, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
import { showToast } from '@/lib/toast'
export function useMemories(filters?: {
projectId?: string
scope?: string
content?: string
limit?: number
offset?: number
}) {
return useQuery({
queryKey: ['memories', filters?.projectId, filters?.scope, filters?.content],
queryFn: () => listMemories(filters).then(r => r.memories),
enabled: !!filters?.projectId,
})
}
export function useMemory(id: number | undefined) {
return useQuery({
queryKey: ['memory', id],
queryFn: () => {
if (id === undefined) throw new Error('Memory ID required')
return getMemory(id).then(r => r.memory)
},
enabled: id !== undefined,
})
}
export function useCreateMemory() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (data: CreateMemoryRequest) => createMemory(data).then(r => r.memory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['memories'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('Memory created')
},
onError: (error) => {
showToast.error(`Failed to create memory: ${error}`)
},
})
}
export function useUpdateMemory() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ id, data }: { id: number; data: UpdateMemoryRequest }) =>
updateMemory(id, data).then(r => r.memory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['memories'] })
showToast.success('Memory updated')
},
onError: (error) => {
showToast.error(`Failed to update memory: ${error}`)
},
})
}
export function useDeleteMemory() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (id: number) => deleteMemory(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['memories'] })
showToast.success('Memory deleted')
},
onError: (error) => {
showToast.error(`Failed to delete memory: ${error}`)
},
})
}
export function useProjectSummary(repoId: number | undefined) {
return useQuery({
queryKey: ['projectSummary', repoId],
queryFn: () => {
if (repoId === undefined) throw new Error('Repo ID required')
return getProjectSummary(repoId)
},
enabled: repoId !== undefined,
})
}
export function useKvEntries(projectId?: string, prefix?: string) {
return useQuery({
queryKey: ['kvEntries', projectId, prefix],
queryFn: () => listKvEntries(projectId!, prefix).then(r => r.entries),
enabled: !!projectId,
})
}
export function useDeleteKvEntry() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ projectId, key }: { projectId: string; key: string }) =>
deleteKvEntry(projectId, key),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('KV entry deleted')
},
onError: (error) => {
showToast.error(`Failed to delete KV entry: ${error}`)
},
})
}
export function useCreateKvEntry() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (data: CreateKvEntryRequest) => createKvEntry(data).then(r => r.entry),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('KV entry created')
},
onError: (error) => {
showToast.error(`Failed to create KV entry: ${error}`)
},
})
}
export function useUpdateKvEntry() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ projectId, key, data }: { projectId: string; key: string; data: UpdateKvEntryRequest }) =>
updateKvEntry(projectId, key, data).then(r => r.entry),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('KV entry updated')
},
onError: (error) => {
showToast.error(`Failed to update KV entry: ${error}`)
},
})
}
@@ -1,12 +0,0 @@
import { useQuery } from '@tanstack/react-query'
import { settingsApi } from '@/api/settings'
export function useMemoryPluginStatus() {
const { data } = useQuery({
queryKey: ['memory-plugin-status'],
queryFn: () => settingsApi.getMemoryPluginStatus(),
staleTime: 60000,
})
return { memoryPluginEnabled: data?.memoryPluginEnabled ?? false }
}
+99 -24
View File
@@ -2,7 +2,6 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useMemo, useRef, useEffect, useCallback } from "react";
import { OpenCodeClient } from "../api/opencode";
import { FetchError } from "../api/fetchWrapper";
import { cancelLoop } from "../api/memory";
import type {
Message,
Part,
@@ -13,7 +12,6 @@ import type { paths, components } from "../api/opencode-types";
import { parseNetworkError } from "../lib/opencode-errors";
import { showToast } from "../lib/toast";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { ensureSSEConnected, reconnectSSE } from "../lib/sseManager";
type AssistantMessage = components["schemas"]["AssistantMessage"];
@@ -21,6 +19,8 @@ type SendPromptRequest = NonNullable<
paths["/session/{sessionID}/message"]["post"]["requestBody"]
>["content"]["application/json"];
type SendCommandResponse = paths["/session/{sessionID}/command"]["post"]["responses"]["200"]["content"]["application/json"];
const parseModelString = (model: string) => {
const [providerID, ...rest] = model.split("/");
const modelID = rest.join("/");
@@ -61,7 +61,7 @@ export const useSession = (opcodeUrl: string | null | undefined, sessionID: stri
});
};
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => {
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string, opts?: { fallbackPoll?: boolean }) => {
const client = useOpenCodeClient(opcodeUrl, directory);
return useQuery({
@@ -76,7 +76,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str
refetchOnReconnect: true,
staleTime: 30000,
gcTime: 10 * 60 * 1000,
refetchInterval: opts?.fallbackPoll ? 5000 : undefined,
});
};
@@ -239,6 +239,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
model,
agent,
variant,
queued,
}: {
sessionID: string;
prompt?: string;
@@ -246,15 +247,10 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
model?: string;
agent?: string;
variant?: string;
queued?: boolean;
}) => {
if (!client) throw new Error("No client available");
const connected = await ensureSSEConnected();
if (!connected) {
showToast.error("Unable to connect. Please try again.");
throw new Error("SSE connection failed");
}
setSessionStatus(sessionID, { type: "busy" });
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
@@ -319,9 +315,14 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
requestData.variant = variant;
}
if (queued) {
await client.sendPromptAsync(sessionID, requestData);
return { optimisticUserID, queued: true };
}
const response = await client.sendPrompt(sessionID, requestData);
return { optimisticUserID, response };
return { optimisticUserID, response, queued: false };
},
onError: (error, variables) => {
const { sessionID } = variables;
@@ -334,19 +335,12 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
);
const isNetworkError = error instanceof TypeError ||
(error instanceof FetchError && error.code === 'TIMEOUT');
(error instanceof FetchError && (error.code === 'TIMEOUT' || error.statusCode === 524));
if (isNetworkError) {
return;
}
const fetchError = error as { statusCode?: number };
const isCloudflareTimeout = fetchError.statusCode === 524;
if (isCloudflareTimeout) {
reconnectSSE();
return;
}
const parsed = parseNetworkError(error);
showToast.error(parsed.title, {
description: parsed.message,
@@ -358,6 +352,11 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
const { response } = data;
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
if (data.queued || !response) {
queryClient.invalidateQueries({ queryKey: messagesQueryKey });
return;
}
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => {
@@ -386,7 +385,6 @@ export const useAbortSession = (
opcodeUrl: string | null | undefined,
directory?: string,
sessionID?: string,
repoId?: number
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
@@ -506,10 +504,6 @@ export const useAbortSession = (
attemptAbort();
if (repoId) {
cancelLoop(repoId, targetSessionID).catch(() => {})
}
retryIntervalRef.current = setInterval(() => {
retryCountRef.current++;
@@ -590,6 +584,8 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
return old.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_"));
},
);
setSessionStatus(sessionID!, { type: "idle" });
},
onSuccess: (data, variables) => {
const { sessionID } = variables;
@@ -631,3 +627,82 @@ export const useAgents = (opcodeUrl: string | null | undefined, directory?: stri
enabled: !!client,
});
};
export const useLoadSkill = (
opcodeUrl: string | null | undefined,
sessionID: string | undefined,
directory?: string,
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
const setSessionStatus = useSessionStatus((state) => state.setStatus);
return useMutation<
{ optimisticUserID: string; response: SendCommandResponse },
Error,
{ skillName: string }
>({
mutationFn: async ({ skillName }: { skillName: string }) => {
if (!client) throw new Error("No OpenCode client available");
if (!sessionID) throw new Error("No active session");
setSessionStatus(sessionID, { type: "busy" });
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
const userMessageParts = createOptimisticUserMessageParts(
sessionID,
[{ type: "text" as const, content: `Loading skill: ${skillName}` }],
optimisticUserID,
);
const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID);
const optimisticMessageWithParts: MessageWithParts = {
info: userMessageInfo,
parts: userMessageParts,
};
await queryClient.cancelQueries({ queryKey: messagesQueryKey });
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => [...(old || []), optimisticMessageWithParts],
);
const response = await client.sendCommand(sessionID, { command: skillName, arguments: "" });
return { optimisticUserID, response };
},
onError: (error) => {
if (sessionID) {
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
setSessionStatus(sessionID!, { type: "idle" });
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => old?.filter((m) => !m.info.id.startsWith("optimistic_")),
);
}
showToast.error(error instanceof Error ? error.message : "Failed to load skill");
},
onSuccess: (data) => {
const { response } = data;
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => {
if (!old) return old;
const existingIdx = old.findIndex(m => m.info.id === response.info.id);
if (existingIdx >= 0) {
const updated = [...old];
updated[existingIdx] = { info: response.info, parts: response.parts };
return updated;
}
return [...old, { info: response.info, parts: response.parts }];
},
);
setSessionStatus(sessionID!, { type: "idle" });
},
});
};
@@ -0,0 +1,33 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getOpenCodeServerAuth, updateOpenCodeServerAuth } from '@/api/settings'
import type { OpenCodeServerAuthStatus as OpenCodeServerAuthStatusType } from '@/api/settings'
export function useOpenCodeServerAuth() {
const queryClient = useQueryClient()
const query = useQuery({
queryKey: ['settings', 'opencode-server-auth'],
queryFn: getOpenCodeServerAuth,
})
const setPassword = useMutation({
mutationFn: (password: string) => updateOpenCodeServerAuth(password),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings', 'opencode-server-auth'] })
},
})
const clearPassword = useMutation({
mutationFn: () => updateOpenCodeServerAuth(null),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings', 'opencode-server-auth'] })
},
})
return {
status: query.data as OpenCodeServerAuthStatusType | undefined,
isLoading: query.isLoading,
setPassword,
clearPassword,
}
}
+21 -10
View File
@@ -6,7 +6,8 @@ import { showToast } from '@/lib/toast'
import { settingsApi } from '@/api/settings'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import { sseManager, subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager'
import { openCodeEventStream } from '@/lib/opencode-event-stream'
import type { EventStreamSubscription } from '@/lib/opencode-event-stream'
import { parseOpenCodeError } from '@/lib/opencode-errors'
import { createPartsBatcher } from '@/lib/partsBatcher'
@@ -51,6 +52,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
const mountedRef = useRef(true)
const sessionIdRef = useRef(currentSessionId)
const statusSyncVersionRef = useRef(0)
const eventStreamSubscriptionRef = useRef<EventStreamSubscription | null>(null)
sessionIdRef.current = currentSessionId
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -351,6 +353,9 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
queryClient.invalidateQueries({
queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory],
})
queryClient.invalidateQueries({
queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, directory],
})
}, [queryClient, opcodeUrl, directory])
useEffect(() => {
@@ -378,22 +383,25 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
setError(null)
fetchInitialData()
syncCurrentSession()
sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
} else {
setError('Connection lost. Reconnecting...')
}
}
const directoryCleanup = addSSEDirectory(directory)
const unsubscribe = subscribeToSSE(handleMessage, handleStatusChange)
const subscription = openCodeEventStream.subscribeToDirectory({
directory,
onEvent: handleMessage,
onStatusChange: handleStatusChange,
})
eventStreamSubscriptionRef.current = subscription
const handleReconnect = () => {
reconnectSSE()
subscription.reconnect()
}
const handleVisibilityChange = () => {
sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
subscription.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
}
document.addEventListener('visibilitychange', handleVisibilityChange)
@@ -406,14 +414,17 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
document.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('focus', handleReconnect)
window.removeEventListener('online', handleReconnect)
unsubscribe()
directoryCleanup()
subscription.reportVisibility(false, undefined)
subscription.dispose()
if (eventStreamSubscriptionRef.current === subscription) {
eventStreamSubscriptionRef.current = null
}
}
}, [opcodeUrl, directory, handleSSEEvent, fetchInitialData, syncCurrentSession])
useEffect(() => {
if (isConnected && document.visibilityState === 'visible') {
sseManager.reportVisibility(true, currentSessionId)
eventStreamSubscriptionRef.current?.reportVisibility(true, currentSessionId)
}
}, [currentSessionId, isConnected])
+70 -4
View File
@@ -5,6 +5,8 @@ import { AudioRecorder } from '@/lib/audioRecorder'
import { sttApi } from '@/api/stt'
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
const STT_START_TIMEOUT_MS = 10_000
export function useSTT(userId = 'default') {
const { preferences } = useSettings(userId)
const [isRecording, setIsRecording] = useState(false)
@@ -21,6 +23,8 @@ export function useSTT(userId = 'default') {
const userIdRef = useRef(userId)
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const lastProcessedBlobRef = useRef<Blob | null>(null)
const startupTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const startOpIdRef = useRef(0)
useEffect(() => {
userIdRef.current = userId
@@ -183,6 +187,26 @@ export function useSTT(userId = 'default') {
}
}, [isEnabled, isExternalProvider, setupAudioRecorder])
const clearStartupTimeout = useCallback(() => {
if (startupTimeoutRef.current) {
clearTimeout(startupTimeoutRef.current)
startupTimeoutRef.current = null
}
}, [])
const abortAndResetOnTimeout = useCallback(() => {
if (isExternalProvider && audioRecorder.current) {
audioRecorder.current.abort()
} else {
recognizer.current.abort()
}
setIsRecording(false)
setIsProcessing(false)
setState('idle')
setIsError(true)
setError('Microphone start timed out')
}, [isExternalProvider])
const startRecording = useCallback(async (): Promise<boolean> => {
if (!isSupported) {
setError('Speech recognition is not supported in this browser')
@@ -202,6 +226,9 @@ export function useSTT(userId = 'default') {
setError(null)
lastProcessedBlobRef.current = null
const startOpId = ++startOpIdRef.current
clearStartupTimeout()
if (isExternalProvider) {
if (!audioRecorder.current) {
audioRecorder.current = new AudioRecorder()
@@ -210,11 +237,30 @@ export function useSTT(userId = 'default') {
try {
setIsProcessing(true)
await audioRecorder.current.start()
const startupPromise = audioRecorder.current.start()
const timeoutPromise = new Promise<never>((_, reject) => {
startupTimeoutRef.current = setTimeout(() => {
if (startOpIdRef.current !== startOpId) return
reject(new Error('Microphone start timed out'))
}, STT_START_TIMEOUT_MS)
})
await Promise.race([startupPromise, timeoutPromise])
clearStartupTimeout()
if (startOpIdRef.current !== startOpId) return false
setIsProcessing(false)
return true
} catch (err) {
clearStartupTimeout()
if (startOpIdRef.current !== startOpId) return false
setIsProcessing(false)
if (err instanceof Error && err.message === 'Microphone start timed out') {
abortAndResetOnTimeout()
return false
}
setIsError(true)
setError(err instanceof Error ? err.message : 'Failed to start recording')
return false
@@ -228,16 +274,35 @@ export function useSTT(userId = 'default') {
try {
setIsProcessing(true)
await recognizer.current.start(options)
const startupPromise = recognizer.current.start(options)
const timeoutPromise = new Promise<never>((_, reject) => {
startupTimeoutRef.current = setTimeout(() => {
if (startOpIdRef.current !== startOpId) return
reject(new Error('Microphone start timed out'))
}, STT_START_TIMEOUT_MS)
})
await Promise.race([startupPromise, timeoutPromise])
clearStartupTimeout()
if (startOpIdRef.current !== startOpId) return false
return true
} catch (err) {
clearStartupTimeout()
if (startOpIdRef.current !== startOpId) return false
setIsProcessing(false)
if (err instanceof Error && err.message === 'Microphone start timed out') {
abortAndResetOnTimeout()
return false
}
setIsError(true)
setError(err instanceof Error ? err.message : 'Failed to start recording')
return false
}
}
}, [isSupported, isEnabled, isExternalProvider, config.language, setupAudioRecorder])
}, [isSupported, isEnabled, isExternalProvider, config.language, setupAudioRecorder, clearStartupTimeout, abortAndResetOnTimeout])
const stopRecording = useCallback(() => {
if (isExternalProvider && audioRecorder.current) {
@@ -286,8 +351,9 @@ export function useSTT(userId = 'default') {
useEffect(() => {
return () => {
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
clearStartupTimeout()
}
}, [])
}, [clearStartupTimeout])
return {
isRecording,
+20 -2
View File
@@ -4,6 +4,13 @@ import { toast } from 'sonner'
import { settingsApi } from '@/api/settings'
import { invalidateConfigCaches, invalidateSettingsCaches } from '@/lib/queryInvalidation'
import { fetchWrapper } from '@/api/fetchWrapper'
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
const MISSING_PASSWORD_ERROR_PATTERN = /no password is configured|OPENCODE_SERVER_PASSWORD/i
function isMissingPasswordError(error: string | undefined): boolean {
return !!error && MISSING_PASSWORD_ERROR_PATTERN.test(error)
}
interface HealthResponse {
status: 'healthy' | 'degraded' | 'unhealthy'
@@ -24,8 +31,10 @@ async function fetchHealth(): Promise<HealthResponse> {
export function useServerHealth(enabled = true) {
const queryClient = useQueryClient()
const { isOpen: isSettingsOpen, setActiveTab } = useSettingsDialog()
const lastHealthStatusRef = useRef<'healthy' | 'unhealthy'>('healthy')
const prevHealthRef = useRef<string | null>(null)
const hasAutoOpenedSettingsRef = useRef(false)
const restartMutation = useMutation({
mutationFn: async () => {
@@ -76,8 +85,16 @@ export function useServerHealth(enabled = true) {
const currentStatus = isUnhealthy ? 'unhealthy' : 'healthy'
const previousStatus = lastHealthStatusRef.current
const prevHealth = prevHealthRef.current
const missingPassword = isUnhealthy && isMissingPasswordError(health.error)
if (prevHealth && currentStatus !== prevHealth) {
if (isUnhealthy && missingPassword && !hasAutoOpenedSettingsRef.current && !isSettingsOpen) {
hasAutoOpenedSettingsRef.current = true
setActiveTab('opencode')
toast.error(health.error || 'OpenCode server requires a password', {
duration: Infinity,
description: 'Set a password under Settings → OpenCode to start the server.',
})
} else if (prevHealth && currentStatus !== prevHealth) {
if (isUnhealthy && previousStatus === 'healthy') {
toast.error(health.error || 'OpenCode server is currently unhealthy', {
duration: Infinity,
@@ -88,12 +105,13 @@ export function useServerHealth(enabled = true) {
})
} else if (!isUnhealthy && previousStatus === 'unhealthy') {
toast.success('Server is back online')
hasAutoOpenedSettingsRef.current = false
}
}
lastHealthStatusRef.current = currentStatus
prevHealthRef.current = currentStatus
}, [health, restartMutation])
}, [health, restartMutation, isSettingsOpen, setActiveTab])
return {
...query,
+1 -1
View File
@@ -18,7 +18,7 @@ interface SwipeState {
export function useSwipe(options: SwipeOptions = {}) {
const {
threshold = 80,
threshold = 60,
directionRatio = 1.5,
enabled = true,
onSwipeStart,
-7
View File
@@ -52,13 +52,6 @@ describe('getSwipeBackTarget', () => {
});
});
describe('memories route', () => {
it('returns repo path', () => {
expect(getSwipeBackTarget('/repos/42/memories', '')).toBe('/repos/42');
expect(getSwipeBackTarget('/repos/123/memories', '?filter=all')).toBe('/repos/123');
});
});
describe('schedules routes', () => {
it('returns repo path for repo schedules', () => {
expect(getSwipeBackTarget('/repos/42/schedules', '')).toBe('/repos/42');
-5
View File
@@ -30,11 +30,6 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
return '/';
}
if (/^\/repos\/[^/]+\/memories$/.test(pathname)) {
const repoId = pathname.split('/')[2];
return `/repos/${repoId}`;
}
if (/^\/repos\/[^/]+\/schedules$/.test(pathname)) {
const repoId = pathname.split('/')[2];
return `/repos/${repoId}`;
@@ -0,0 +1,97 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { OpenCodeEventStream, TestEventStreamTransport } from '..'
import type { EventStreamHealthState } from '..'
describe('OpenCodeEventStream', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('delivers raw events to the global monitor', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const onEvent = vi.fn()
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent })
transport.openConnection()
transport.connected()
transport.message({ type: 'permission.asked', properties: { sessionID: 'session-1' }, directory: '/repo' })
expect(onEvent).toHaveBeenCalledWith({
type: 'permission.asked',
properties: { sessionID: 'session-1' },
directory: '/repo',
})
})
it('publishes health through monitor output', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const healthStates: EventStreamHealthState[] = []
stream.subscribeGlobalMonitor({
directories: [],
onEvent: vi.fn(),
onHealthChange: (health) => healthStates.push(health),
})
transport.openConnection()
expect(healthStates.at(-1)).toMatchObject({ isConnected: true, isHealthy: true, isStalled: false })
})
it('reconnects when the watchdog detects a stall', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
stream.subscribeGlobalMonitor({ directories: [], onEvent: vi.fn() })
transport.openConnection()
await vi.advanceTimersByTimeAsync(105_001)
expect(transport.closeCount).toBeGreaterThan(0)
})
it('diffs global monitor directories through the transport adapter', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const subscription = stream.subscribeGlobalMonitor({ directories: ['/repo-a'], onEvent: vi.fn() })
transport.openConnection()
transport.connected('client-1')
subscription.updateDirectories(['/repo-a', '/repo-b'])
await Promise.resolve()
subscription.updateDirectories(['/repo-b'])
await Promise.resolve()
expect(transport.posts).toContainEqual({
path: '/api/sse/subscribe',
body: { clientId: 'client-1', directories: ['/repo-b'] },
})
expect(transport.posts).toContainEqual({
path: '/api/sse/unsubscribe',
body: { clientId: 'client-1', directories: ['/repo-a'] },
})
})
it('reports visibility through the transport adapter', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const subscription = stream.subscribeToDirectory({ directory: '/repo', onEvent: vi.fn() })
transport.openConnection()
transport.connected('client-1')
subscription.reportVisibility(true, 'session-1')
await Promise.resolve()
expect(transport.posts).toContainEqual({
path: '/api/sse/visibility',
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1' },
})
})
})
@@ -0,0 +1,31 @@
import type { EventStreamConnection, EventStreamTransport, EventStreamTransportHandlers } from './types'
export function createBrowserEventStreamTransport(): EventStreamTransport {
return {
open(url: string, handlers: EventStreamTransportHandlers): EventStreamConnection {
const eventSource = new EventSource(url, { withCredentials: true })
eventSource.onopen = handlers.onOpen
eventSource.onerror = handlers.onError
eventSource.onmessage = (event) => handlers.onMessage(event.data)
eventSource.addEventListener('connected', (event) => {
handlers.onConnected((event as MessageEvent).data)
})
eventSource.addEventListener('heartbeat', handlers.onHeartbeat)
return {
close: () => eventSource.close(),
}
},
async post(path: string, body: unknown): Promise<boolean> {
const response = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return response.ok
},
}
}
@@ -0,0 +1,13 @@
export { openCodeEventStream, OpenCodeEventStream } from './openCodeEventStream'
export { createBrowserEventStreamTransport } from './browserTransport'
export { TestEventStreamTransport } from './testTransport'
export type {
EventStreamConnection,
EventStreamHealthState,
EventStreamStatusHandler,
EventStreamSubscription,
EventStreamTransport,
EventStreamTransportHandlers,
GlobalMonitorSubscription,
OpenCodeEventHandler,
} from './types'
@@ -0,0 +1,401 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
import { createBrowserEventStreamTransport } from './browserTransport'
import type {
EventStreamHealthState,
EventStreamStatusHandler,
EventStreamSubscription,
EventStreamTransport,
GlobalMonitorSubscription,
OpenCodeEventHandler,
} from './types'
interface Subscriber {
id: string
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
directories: Set<string>
}
interface OpenCodeEventStreamOptions {
transport?: EventStreamTransport
}
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, STALL_THRESHOLD_MS, WATCHDOG_TICK_MS } = DEFAULTS.SSE
export class OpenCodeEventStream {
private connection: { close(): void } | null = null
private readonly transport: EventStreamTransport
private subscribers = new Map<string, Subscriber>()
private directoryRefCounts = new Map<string, number>()
private pendingDirectories = new Set<string>()
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
private reconnectDelay: number = RECONNECT_DELAY_MS
private connected = false
private subscriberIdCounter = 0
private clientId: string | null = null
private lastEventAt: number | null = null
private watchdogTimer: ReturnType<typeof setInterval> | null = null
constructor(options: OpenCodeEventStreamOptions = {}) {
this.transport = options.transport ?? createBrowserEventStreamTransport()
}
subscribeGlobalMonitor(input: {
directories: string[]
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
}): GlobalMonitorSubscription {
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange)
this.updateSubscriberDirectories(id, input.directories)
return {
updateDirectories: (directories) => this.updateSubscriberDirectories(id, directories),
reconnect: () => this.reconnect(),
reportVisibility: (visible, activeSessionId) => this.reportVisibility(visible, activeSessionId),
dispose: () => this.removeSubscriber(id),
}
}
subscribeToDirectory(input: {
directory: string
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
}): EventStreamSubscription {
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange)
this.updateSubscriberDirectories(id, [input.directory])
return {
reconnect: () => this.reconnect(),
reportVisibility: (visible, activeSessionId) => this.reportVisibility(visible, activeSessionId),
dispose: () => this.removeSubscriber(id),
}
}
getHealth(): EventStreamHealthState {
return this.buildHealth()
}
private addSubscriber(
onEvent: OpenCodeEventHandler,
onStatusChange?: EventStreamStatusHandler,
onHealthChange?: (state: EventStreamHealthState) => void,
): string {
const id = `sub_${++this.subscriberIdCounter}`
this.subscribers.set(id, {
id,
onEvent,
onStatusChange,
onHealthChange,
directories: new Set(),
})
onStatusChange?.(this.connected)
onHealthChange?.(this.buildHealth())
if (this.subscribers.size === 1) {
this.connect()
}
return id
}
private removeSubscriber(id: string): void {
const subscriber = this.subscribers.get(id)
if (!subscriber) return
this.updateSubscriberDirectories(id, [])
this.subscribers.delete(id)
if (this.subscribers.size === 0) {
this.disconnect()
}
}
private updateSubscriberDirectories(id: string, directories: string[]): void {
const subscriber = this.subscribers.get(id)
if (!subscriber) return
const nextDirectories = new Set(directories.filter(Boolean))
for (const directory of subscriber.directories) {
if (!nextDirectories.has(directory)) {
this.removeDirectory(directory)
}
}
for (const directory of nextDirectories) {
if (!subscriber.directories.has(directory)) {
this.addDirectory(directory)
}
}
subscriber.directories = nextDirectories
}
private addDirectory(directory: string): void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
this.directoryRefCounts.set(directory, currentCount + 1)
if (currentCount > 0) return
if (this.clientId && this.connected) {
void this.subscribeToRemoteDirectories([directory])
return
}
this.pendingDirectories.add(directory)
if (!this.connection) {
this.reconnect()
}
}
private removeDirectory(directory: string): void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
if (currentCount > 1) {
this.directoryRefCounts.set(directory, currentCount - 1)
return
}
this.directoryRefCounts.delete(directory)
this.pendingDirectories.delete(directory)
if (this.clientId && this.connected) {
void this.transport.post('/api/sse/unsubscribe', {
clientId: this.clientId,
directories: [directory],
})
}
}
private buildUrl(): string {
const url = new URL('/api/sse/stream', window.location.origin)
const directories = Array.from(this.directoryRefCounts.keys())
if (directories.length > 0) {
url.searchParams.set('directories', directories.join(','))
}
return url.toString()
}
private connect(): void {
if (this.connection) return
this.connection = this.transport.open(this.buildUrl(), {
onOpen: () => this.handleOpen(),
onError: () => this.handleError(),
onMessage: (data) => this.handleMessage(data),
onConnected: (data) => this.handleConnected(data),
onHeartbeat: () => this.markActivity(),
})
}
private handleOpen(): void {
this.connected = true
this.reconnectDelay = RECONNECT_DELAY_MS
this.startWatchdog()
this.markActivity()
this.notifyStatusChange(true)
}
private handleError(): void {
this.connected = false
this.clientId = null
this.stopWatchdog()
this.lastEventAt = null
if (this.connection) {
this.connection.close()
this.connection = null
}
this.notifyStatusChange(false)
this.notifyHealth()
if (this.subscribers.size > 0) {
this.scheduleReconnect()
}
}
private handleMessage(data: string): void {
try {
this.markActivity()
this.broadcast(JSON.parse(data))
} catch {
this.markActivity()
}
}
private handleConnected(data: string): void {
try {
const parsed = JSON.parse(data) as { clientId?: unknown }
if (typeof parsed.clientId === 'string') {
this.clientId = parsed.clientId
}
} catch {
this.clientId = null
}
this.connected = true
this.startWatchdog()
this.markActivity()
this.notifyStatusChange(true)
this.flushPendingDirectories()
}
private disconnect(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
this.stopWatchdog()
this.connection?.close()
this.connection = null
this.connected = false
this.clientId = null
this.lastEventAt = null
this.pendingDirectories.clear()
this.notifyHealth()
}
private reconnect(): void {
if (this.subscribers.size === 0) return
this.reconnectDelay = RECONNECT_DELAY_MS
this.disconnectConnectionOnly()
this.connect()
}
private disconnectConnectionOnly(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
this.stopWatchdog()
this.connection?.close()
this.connection = null
this.connected = false
this.clientId = null
this.lastEventAt = null
this.pendingDirectories = new Set(this.directoryRefCounts.keys())
this.notifyStatusChange(false)
this.notifyHealth()
}
private scheduleReconnect(): void {
if (this.reconnectTimeout) return
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
this.connect()
}, this.reconnectDelay)
}
private startWatchdog(): void {
if (this.watchdogTimer) return
this.watchdogTimer = setInterval(() => {
if (this.lastEventAt == null) return
if (Date.now() - this.lastEventAt > STALL_THRESHOLD_MS) {
this.handleStall()
}
}, WATCHDOG_TICK_MS)
}
private stopWatchdog(): void {
if (!this.watchdogTimer) return
clearInterval(this.watchdogTimer)
this.watchdogTimer = null
}
private handleStall(): void {
this.disconnectConnectionOnly()
this.connect()
}
private markActivity(): void {
this.lastEventAt = Date.now()
this.notifyHealth()
}
private buildHealth(): EventStreamHealthState {
const isStalled = this.connected && this.lastEventAt != null && Date.now() - this.lastEventAt > STALL_THRESHOLD_MS
return {
isConnected: this.connected,
isHealthy: this.connected && this.lastEventAt != null && !isStalled,
lastEventAt: this.lastEventAt,
isStalled,
}
}
private notifyHealth(): void {
const health = this.buildHealth()
this.subscribers.forEach((subscriber) => {
try {
subscriber.onHealthChange?.(health)
} catch {
void 0
}
})
}
private notifyStatusChange(connected: boolean): void {
this.subscribers.forEach((subscriber) => {
try {
subscriber.onStatusChange?.(connected)
} catch {
void 0
}
})
}
private broadcast(data: unknown): void {
this.subscribers.forEach((subscriber) => {
try {
subscriber.onEvent(data)
} catch {
void 0
}
})
}
private async subscribeToRemoteDirectories(directories: string[]): Promise<void> {
if (!this.clientId || directories.length === 0) return
const success = await this.transport.post('/api/sse/subscribe', {
clientId: this.clientId,
directories,
})
if (!success) {
directories.forEach((directory) => this.pendingDirectories.add(directory))
this.reconnect()
}
}
private flushPendingDirectories(): void {
if (this.pendingDirectories.size === 0) return
if (!this.clientId || !this.connected) return
const directories = Array.from(this.pendingDirectories)
this.pendingDirectories.clear()
void this.subscribeToRemoteDirectories(directories)
}
private reportVisibility(visible: boolean, activeSessionId?: string): void {
if (!this.clientId || !this.connected) return
void this.transport.post('/api/sse/visibility', {
clientId: this.clientId,
visible,
activeSessionId: activeSessionId ?? null,
})
}
}
export const openCodeEventStream = new OpenCodeEventStream()
@@ -0,0 +1,46 @@
import type { EventStreamConnection, EventStreamTransport, EventStreamTransportHandlers } from './types'
export class TestEventStreamTransport implements EventStreamTransport {
readonly posts: Array<{ path: string; body: unknown }> = []
closeCount = 0
private handlers: EventStreamTransportHandlers | null = null
private connection: EventStreamConnection | null = null
open(_url: string, handlers: EventStreamTransportHandlers): EventStreamConnection {
this.handlers = handlers
this.connection = {
close: () => {
if (this.connection) {
this.connection = null
this.closeCount += 1
}
},
}
return this.connection
}
async post(path: string, body: unknown): Promise<boolean> {
this.posts.push({ path, body })
return true
}
openConnection(): void {
this.handlers?.onOpen()
}
connected(clientId = 'test-client'): void {
this.handlers?.onConnected(JSON.stringify({ clientId }))
}
message(data: unknown): void {
this.handlers?.onMessage(JSON.stringify(data))
}
heartbeat(): void {
this.handlers?.onHeartbeat()
}
fail(): void {
this.handlers?.onError()
}
}
@@ -0,0 +1,36 @@
export type OpenCodeEventHandler = (data: unknown) => void
export type EventStreamStatusHandler = (connected: boolean) => void
export interface EventStreamHealthState {
isConnected: boolean
isHealthy: boolean
lastEventAt: number | null
isStalled: boolean
}
export interface EventStreamConnection {
close(): void
}
export interface EventStreamTransportHandlers {
onOpen(): void
onError(): void
onMessage(data: string): void
onConnected(data: string): void
onHeartbeat(): void
}
export interface EventStreamTransport {
open(url: string, handlers: EventStreamTransportHandlers): EventStreamConnection
post(path: string, body: unknown): Promise<boolean>
}
export interface EventStreamSubscription {
dispose(): void
reconnect(): void
reportVisibility(visible: boolean, activeSessionId?: string): void
}
export interface GlobalMonitorSubscription extends EventStreamSubscription {
updateDirectories(directories: string[]): void
}
-351
View File
@@ -1,351 +0,0 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
type SSEEventHandler = (data: unknown) => void
type SSEStatusHandler = (connected: boolean) => void
interface SSESubscriber {
id: string
onMessage: SSEEventHandler
onStatusChange?: SSEStatusHandler
}
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
class SSEManager {
private static instance: SSEManager
private eventSource: EventSource | null = null
private subscribers: Map<string, SSESubscriber> = new Map()
private directoryRefCounts: Map<string, number> = new Map()
private pendingDirectories: Set<string> = new Set()
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
private reconnectDelay: number = RECONNECT_DELAY_MS
private isConnected = false
private subscriberIdCounter = 0
private clientId: string | null = null
private constructor() {}
static getInstance(): SSEManager {
if (!SSEManager.instance) {
SSEManager.instance = new SSEManager()
}
return SSEManager.instance
}
subscribe(
onMessage: SSEEventHandler,
onStatusChange?: SSEStatusHandler
): () => void {
const id = `sub_${++this.subscriberIdCounter}`
const subscriber: SSESubscriber = {
id,
onMessage,
onStatusChange
}
this.subscribers.set(id, subscriber)
if (onStatusChange) {
onStatusChange(this.isConnected)
}
if (this.subscribers.size === 1) {
this.connect()
}
return () => this.unsubscribe(id)
}
private unsubscribe(id: string): void {
this.subscribers.delete(id)
if (this.subscribers.size === 0) {
this.disconnect()
}
}
addDirectory(directory: string): () => void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
this.directoryRefCounts.set(directory, currentCount + 1)
if (currentCount === 0) {
if (this.clientId && this.isConnected) {
this.subscribeToDirectory(directory)
} else {
this.pendingDirectories.add(directory)
if (!this.eventSource) {
this.reconnect()
}
}
}
return () => this.cleanupDirectory(directory)
}
private cleanupDirectory(directory: string): void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
if (currentCount <= 1) {
this.directoryRefCounts.delete(directory)
this.pendingDirectories.delete(directory)
if (this.clientId && this.isConnected) {
fetch('/api/sse/unsubscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
}).catch(() => {})
}
} else {
this.directoryRefCounts.set(directory, currentCount - 1)
}
}
private subscribeToDirectory(directory: string): void {
fetch('/api/sse/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
}).then(res => {
if (!res.ok) {
this.reconnect()
}
}).catch(() => {
this.reconnect()
})
}
private flushPendingDirectories(): void {
if (this.pendingDirectories.size === 0) return
if (!this.clientId || !this.isConnected) return
const dirs = Array.from(this.pendingDirectories)
this.pendingDirectories.clear()
fetch('/api/sse/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, directories: dirs })
}).then(res => {
if (!res.ok) {
dirs.forEach(d => this.pendingDirectories.add(d))
this.reconnect()
}
}).catch(() => {
dirs.forEach(d => this.pendingDirectories.add(d))
this.reconnect()
})
}
removeDirectory(directory: string): void {
this.cleanupDirectory(directory)
}
getDirectories(): string[] {
return Array.from(this.directoryRefCounts.keys())
}
private buildUrl(): string {
const url = new URL('/api/sse/stream', window.location.origin)
if (this.directoryRefCounts.size > 0) {
url.searchParams.set('directories', Array.from(this.directoryRefCounts.keys()).join(','))
}
return url.toString()
}
private connect(): void {
if (this.eventSource) return
const url = this.buildUrl()
this.eventSource = new EventSource(url, { withCredentials: true })
this.eventSource.onopen = () => {
this.isConnected = true
this.reconnectDelay = RECONNECT_DELAY_MS
this.notifyStatusChange(true)
}
this.eventSource.onerror = () => {
this.isConnected = false
this.clientId = null
this.notifyStatusChange(false)
if (this.eventSource) {
this.eventSource.close()
this.eventSource = null
}
if (this.subscribers.size > 0) {
this.scheduleReconnect()
}
}
this.eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
this.broadcast(data)
} catch {
// Ignore parse errors
}
}
this.eventSource.addEventListener('connected', (event) => {
try {
const data = JSON.parse((event as MessageEvent).data)
if (data.clientId) {
this.clientId = data.clientId
}
this.isConnected = true
this.notifyStatusChange(true)
this.flushPendingDirectories()
} catch {
// Ignore
}
})
this.eventSource.addEventListener('heartbeat', () => {
// Heartbeat received - connection is alive
})
}
private disconnect(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.eventSource) {
this.eventSource.close()
this.eventSource = null
}
this.isConnected = false
this.clientId = null
}
private scheduleReconnect(): void {
if (this.reconnectTimeout) return
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
this.connect()
}, this.reconnectDelay)
}
private notifyStatusChange(connected: boolean): void {
this.subscribers.forEach(sub => {
if (sub.onStatusChange) {
try {
sub.onStatusChange(connected)
} catch {
// Ignore callback errors
}
}
})
}
private broadcast(data: unknown): void {
this.subscribers.forEach(sub => {
try {
sub.onMessage(data)
} catch {
// Ignore callback errors
}
})
}
reconnect(): void {
if (this.subscribers.size === 0) return
this.reconnectDelay = RECONNECT_DELAY_MS
this.disconnect()
this.connect()
}
getConnectionStatus(): boolean {
return this.isConnected
}
reportVisibility(visible: boolean, activeSessionId?: string): void {
if (!this.clientId || !this.isConnected) return
fetch('/api/sse/visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, visible, activeSessionId: activeSessionId ?? null })
}).catch(() => {})
}
async ensureConnected(timeoutMs: number = 5000): Promise<boolean> {
if (this.isConnected && this.clientId) {
return true
}
if (this.subscribers.size === 0) {
return false
}
this.reconnectDelay = RECONNECT_DELAY_MS
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.eventSource) {
this.eventSource.close()
this.eventSource = null
}
return new Promise<boolean>((resolve) => {
const timeout = setTimeout(() => {
resolve(false)
}, timeoutMs)
const checkConnection = () => {
if (this.isConnected && this.clientId) {
clearTimeout(timeout)
resolve(true)
}
}
const originalNotify = this.notifyStatusChange.bind(this)
this.notifyStatusChange = (connected: boolean) => {
originalNotify(connected)
if (connected) {
this.notifyStatusChange = originalNotify
checkConnection()
}
}
this.connect()
})
}
}
export const sseManager = SSEManager.getInstance()
export function subscribeToSSE(
onMessage: SSEEventHandler,
onStatusChange?: SSEStatusHandler
): () => void {
return sseManager.subscribe(onMessage, onStatusChange)
}
export function addSSEDirectory(directory: string): () => void {
return sseManager.addDirectory(directory)
}
export function removeSSEDirectory(directory: string): void {
sseManager.removeDirectory(directory)
}
export function reconnectSSE(): void {
sseManager.reconnect()
}
export function isSSEConnected(): boolean {
return sseManager.getConnectionStatus()
}
export async function ensureSSEConnected(timeoutMs?: number): Promise<boolean> {
return sseManager.ensureConnected(timeoutMs)
}
-164
View File
@@ -1,164 +0,0 @@
import { useState } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useProjectSummary, useKvEntries } from '@/hooks/useMemories'
import { useLoopStatus } from '@/hooks/useLoopStatus'
import { useRepoActivity } from '@/hooks/useRepoActivity'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Loader2, Plus, Brain, Key, Bot } from 'lucide-react'
import { getRepoDisplayName } from '@/lib/utils'
import { MemoryList } from '@/components/memory/MemoryList'
import { MemoryFormDialog } from '@/components/memory/MemoryFormDialog'
import { KvList } from '@/components/memory/KvList'
import { RepoLoopList } from '@/components/repo/RepoLoopList'
export function Memories() {
const { id } = useParams<{ id: string }>()
const repoId = id ? Number(id) : undefined
const [createOpen, setCreateOpen] = useState(false)
const [activeTab, setActiveTab] = useState('memories')
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId!),
enabled: repoId !== undefined,
})
useRepoActivity(repoId ?? 0, Boolean(repo))
const { data: projectSummary, isLoading: projectSummaryLoading } = useProjectSummary(repoId)
const { data: kvEntries } = useKvEntries(projectSummary?.projectId ?? undefined)
const { data: loopData, isLoading: loopLoading, error: loopError, cancelMutation, pendingSessionId } = useLoopStatus(repoId, activeTab === 'loops')
const projectId = projectSummary?.projectId ?? null
const stats = projectSummary?.stats ?? null
if (repoLoading || projectSummaryLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
)
}
if (!repo) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">Repository not found</p>
</div>
)
}
if (!projectId) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">No project ID found - the repository may not have any commits yet</p>
</div>
)
}
const scopeLabels: Record<string, string> = {
convention: 'Convention',
decision: 'Decision',
context: 'Context',
}
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<div className="min-w-0 flex-1 flex justify-center ml-2">
<Header.Title className="hidden sm:flex ">
Memory: {getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
</Header.Title>
<Header.Title className="sm:hidden truncate">
{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
</Header.Title>
</div>
<Header.Actions>
{activeTab === 'memories' && (
<>
<Button onClick={() => setCreateOpen(true)} size="sm" className="hidden sm:flex">
<Plus className="w-4 h-4 mr-2" />
New Memory
</Button>
<Button onClick={() => setCreateOpen(true)} size="sm" className="sm:hidden h-10 w-10 p-0">
<Plus className="w-5 h-5" />
</Button>
</>
)}
</Header.Actions>
</Header>
<div className="flex-1 overflow-auto p-4 pb-20 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
{stats && (
<Card className="mb-6 hidden sm:block">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-3">
<Brain className="w-4 h-4 text-blue-500" />
<span className="font-medium">Total Memories: {stats.total}</span>
</div>
{Object.keys(stats.byScope).length > 0 && (
<div className="flex flex-wrap gap-2">
{Object.entries(stats.byScope).map(([scope, count]) => (
<Badge key={scope} variant="outline" className="text-sm">
{scopeLabels[scope] || scope}: {count}
</Badge>
))}
</div>
)}
{kvEntries && kvEntries.length > 0 && (
<Badge variant="outline" className="text-sm">
KV Entries: {kvEntries.length}
</Badge>
)}
</CardContent>
</Card>
)}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="memories">
<Brain className="w-4 h-4 mr-2" />
Memories
</TabsTrigger>
<TabsTrigger value="kv">
<Key className="w-4 h-4 mr-2" />
Key-Value
</TabsTrigger>
<TabsTrigger value="loops">
<Bot className="w-4 h-4 mr-2" />
Loops
</TabsTrigger>
</TabsList>
<TabsContent value="memories">
<MemoryList projectId={projectId} showFilters={true} />
</TabsContent>
<TabsContent value="kv">
<KvList projectId={projectId ?? undefined} />
</TabsContent>
<TabsContent value="loops">
<RepoLoopList
isLoading={loopLoading}
data={loopData?.loops}
error={loopError}
onCancel={(sessionId) => cancelMutation.mutate({ sessionId })}
pendingSessionId={pendingSessionId}
/>
</TabsContent>
</Tabs>
</div>
<MemoryFormDialog
projectId={projectId}
open={createOpen}
onOpenChange={setCreateOpen}
/>
</div>
)
}
+100 -50
View File
@@ -41,7 +41,7 @@ import { RepoLspDialog } from "@/components/repo/RepoLspDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { createOpenCodeClient } from "@/api/opencode";
import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore";
import { usePermissions, useQuestions } from "@/contexts/EventContext";
import { usePermissions, useQuestions, useSSEHealth } from "@/contexts/EventContext";
import type { QuestionRequest } from "@/api/types";
import { QuestionPrompt } from "@/components/session/QuestionPrompt";
import { MinimizedQuestionIndicator } from "@/components/session/MinimizedQuestionIndicator";
@@ -83,6 +83,8 @@ export function SessionDetail() {
const [showScrollButton, setShowScrollButton] = useState(false);
const [hasPromptContent, setHasPromptContent] = useState(false);
const [minimizedQuestion, setMinimizedQuestion] = useState<QuestionRequest | null>(null);
const [isHeaderVisible, setIsHeaderVisible] = useState(true);
const lastHeaderScrollTopRef = useRef(0);
const isMobile = useMobile();
const { keyboardHeight } = useVisualViewport();
@@ -126,7 +128,12 @@ export function SessionDetail() {
const repoDirectory = isAssistantSession ? assistantMode?.directory : repo?.fullPath;
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory);
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
const sseHealth = useSSEHealth();
const sessionStatus = useSessionStatusForSession(sessionId);
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'compact' || sessionStatus.type === 'retry';
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory, { fallbackPoll: !sseHealth.isHealthy && isSessionActive });
const { data: session, isLoading: sessionLoading } = useSession(
opcodeUrl,
sessionId,
@@ -151,8 +158,6 @@ export function SessionDetail() {
contentVersion: messages?.reduce((sum, m) => sum + m.parts.length, 0) ?? 0,
onScrollStateChange: setShowScrollButton
});
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId);
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
const createSession = useCreateSession(opcodeUrl, repoDirectory);
@@ -164,8 +169,6 @@ export function SessionDetail() {
const { syncForSession: syncPermissionsForSession } = usePermissions();
const { current: currentQuestion, reply: replyToQuestion, reject: rejectQuestion, syncForSession: syncQuestionsForSession } = useQuestions();
const sessionStatus = useSessionStatusForSession(sessionId);
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'compact' || sessionStatus.type === 'retry';
const lastAssistantMessage = messages?.filter(m => m.info.role === 'assistant').at(-1);
const lastAssistantText = getAssistantText(lastAssistantMessage);
const latestPlayableAssistant = useMemo(() => getLatestPlayableAssistantMessage(messages), [messages]);
@@ -207,6 +210,38 @@ export function SessionDetail() {
}
}, [sessionId, minimizedQuestion])
useEffect(() => {
const container = messageContainerRef.current
if (!container) return
lastHeaderScrollTopRef.current = container.scrollTop
setIsHeaderVisible(true)
const handleScroll = () => {
if (!isMobile) {
setIsHeaderVisible(true)
return
}
const currentScrollTop = container.scrollTop
const previousScrollTop = lastHeaderScrollTopRef.current
const maxScrollTop = container.scrollHeight - container.clientHeight
const isAtBottom = maxScrollTop - currentScrollTop < 24
const isScrollingDown = currentScrollTop > previousScrollTop + 4
const isScrollingUp = currentScrollTop < previousScrollTop - 4
if (isAtBottom || isScrollingDown) {
setIsHeaderVisible(true)
} else if (isScrollingUp) {
setIsHeaderVisible(false)
}
lastHeaderScrollTopRef.current = currentScrollTop
}
container.addEventListener('scroll', handleScroll, { passive: true })
return () => container.removeEventListener('scroll', handleScroll)
}, [repoDirectory, sessionId, isMobile])
const syncPendingActionsForSession = useCallback(async () => {
if (!repoDirectory || !sessionId) return
await Promise.all([
@@ -225,7 +260,7 @@ export function SessionDetail() {
refetchOnMount: 'always',
refetchOnReconnect: true,
refetchOnWindowFocus: true,
refetchInterval: isSessionActive || hasIncompleteMessages ? PENDING_ACTION_SYNC_INTERVAL_MS : false,
refetchInterval: !sseHealth.isHealthy && (isSessionActive || hasIncompleteMessages) ? PENDING_ACTION_SYNC_INTERVAL_MS : false,
retry: false,
})
@@ -421,51 +456,61 @@ export function SessionDetail() {
<div
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col"
>
<Header>
<div className="flex items-center gap-1.5 sm:gap-3 min-w-0 flex-1">
{session?.parentID ? (
<>
<Button
variant="ghost"
size="sm"
onClick={handleParentSessionClick}
className="text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/20 h-7 px-2 gap-1"
title="Back to parent session"
>
<CornerUpLeft className="w-3.5 h-3.5" />
<span className="hidden sm:inline text-xs">Parent</span>
</Button>
<div className="hidden sm:block">
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
</div>
</>
) : (
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
)}
<div
className={`flex-shrink-0 overflow-hidden bg-background transition-all duration-200 ease-out ${
isHeaderVisible
? 'max-h-40 opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-2'
}`}
>
<Header className="bg-background [&_button]:bg-black [&_button]:text-white [&_button]:border-zinc-700 [&_button:hover]:bg-zinc-900">
<div className="flex items-center gap-1.5 sm:gap-3 min-w-0 flex-1">
{session?.parentID ? (
<>
<Button
variant="ghost"
size="sm"
onClick={handleParentSessionClick}
className="text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/20 h-7 px-2 gap-1"
title="Back to parent session"
>
<CornerUpLeft className="w-3.5 h-3.5" />
<span className="hidden sm:inline text-xs">Parent</span>
</Button>
<div className="hidden sm:block">
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
</div>
</>
) : (
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
)}
<Header.EditableTitle
value={session?.title || "Untitled Session"}
onChange={handleSessionTitleUpdate}
subtitle={<span className="text-orange-600 dark:text-orange-400">{workspaceDisplayName}</span>}
/>
</div>
<Header.Actions className="gap-2 sm:gap-4">
<div className="flex items-center gap-1">
<PendingActionsGroup />
</div>
<ContextUsageIndicator
opcodeUrl={opcodeUrl}
sessionID={sessionId}
directory={repoDirectory}
isConnected={isConnected}
isReconnecting={isReconnecting}
/>
<SessionMoreButton />
</Header.Actions>
</Header>
<Header.Actions className="gap-2 sm:gap-4">
<div className="flex items-center gap-1">
<PendingActionsGroup />
</div>
<ContextUsageIndicator
opcodeUrl={opcodeUrl}
sessionID={sessionId}
directory={repoDirectory}
isConnected={isConnected}
isReconnecting={isReconnecting}
/>
<SessionMoreButton />
</Header.Actions>
</Header>
<SessionTodoDisplay sessionID={sessionId} />
<div className="px-3 sm:px-4">
<SessionTodoDisplay sessionID={sessionId} />
</div>
</div>
<div className="flex-1 overflow-hidden flex flex-col relative">
<div className="flex-1 overflow-hidden flex flex-col">
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + 16 }}>
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
<MessageSkeleton />
@@ -538,7 +583,6 @@ export function SessionDetail() {
opcodeUrl={opcodeUrl}
directory={repoDirectory}
sessionID={sessionId}
repoId={repoId}
disabled={!isConnected}
showScrollButton={showScrollButton}
isSessionActive={isSessionActive}
@@ -599,11 +643,17 @@ export function SessionDetail() {
directory={repoDirectory}
/>
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
/>
{repoDirectory && opcodeUrl && sessionId && (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
sessionId={sessionId}
opcodeUrl={opcodeUrl}
directory={repoDirectory}
onSkillLoaded={(skill) => showToast.success(`Loaded skill: ${skill.name}`)}
/>
)}
<RepoMcpDialog
open={mcpDialogOpen}
@@ -0,0 +1,94 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useQuery } from '@tanstack/react-query'
const mocks = vi.hoisted(() => ({
syncPendingActions: vi.fn(),
}))
describe('SessionDetail pending-actions polling', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const createQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={createQueryClient()}>
{children}
</QueryClientProvider>
)
it('should poll pending-actions when refetchInterval is set', async () => {
vi.useFakeTimers()
mocks.syncPendingActions.mockResolvedValue(null)
const testQueryOptions = {
queryKey: ['opencode', 'pending-actions', 'http://localhost:5003', 'session-1', '/repo'] as const,
queryFn: async () => {
await mocks.syncPendingActions()
return null
},
enabled: true,
refetchOnMount: 'always' as const,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
refetchInterval: 30000,
retry: false,
}
renderHook(
() => useQuery(testQueryOptions),
{ wrapper }
)
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(30000)
await waitFor(() => {
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2)
})
vi.useRealTimers()
})
it('should not poll pending-actions when refetchInterval is false', async () => {
vi.useFakeTimers()
mocks.syncPendingActions.mockResolvedValue(null)
const testQueryOptions = {
queryKey: ['opencode', 'pending-actions', 'http://localhost:5003', 'session-1', '/repo'] as const,
queryFn: async () => {
await mocks.syncPendingActions()
return null
},
enabled: true,
refetchOnMount: 'always' as const,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
refetchInterval: false as const,
retry: false,
}
renderHook(
() => useQuery(testQueryOptions),
{ wrapper }
)
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(60000)
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
})
+5 -4
View File
@@ -28,11 +28,12 @@ interface PushNotificationData {
tag?: string;
data?: {
url?: string;
eventType: string;
eventType?: string;
sessionId?: string;
directory?: string;
repoId?: number;
repoName?: string;
priority?: 'normal' | 'high';
};
}
@@ -56,7 +57,7 @@ self.addEventListener("push", (event) => {
badge: payload.badge ?? "/icons/icon-192x192.png",
tag: payload.tag,
data: payload.data,
requireInteraction: isHighPriority(payload.data?.eventType),
requireInteraction: isHighPriority(payload.data?.eventType, payload.data?.priority),
};
event.waitUntil(self.registration.showNotification(payload.title, options));
@@ -84,6 +85,6 @@ self.addEventListener("notificationclick", (event) => {
);
});
function isHighPriority(eventType?: string): boolean {
return eventType === "permission.asked" || eventType === "question.asked";
function isHighPriority(eventType?: string, priority?: 'normal' | 'high'): boolean {
return eventType === "permission.asked" || eventType === "question.asked" || priority === 'high';
}