Add memory plugin with semantic search and session planning (#145)

* Add memory plugin with semantic search and session planning

* Clarify Memory Plugin is optional in docs
This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-23 15:08:56 -05:00
1 parent da283a82cf
commit 3461f86556
132 files changed
+11448 -2834

No files matched your search

@@ -1,4 +1,4 @@
import { useFileDiff, useCommitFileDiff } from "@/api/git";
import { useFileDiff } from "@/api/git";
import {
Loader2,
FileText,
@@ -10,7 +10,6 @@ import {
Minus,
ArrowLeft,
ExternalLink,
X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { CopyButton } from "@/components/ui/copy-button";
@@ -22,9 +21,7 @@ interface FileDiffViewProps {
repoId: number;
filePath: string;
includeStaged?: boolean;
commitHash?: string;
onBack?: () => void;
onClose?: () => void;
onOpenFile?: (path: string, lineNumber?: number) => void;
isMobile?: boolean;
}
@@ -139,7 +136,7 @@ function DiffLineComponent({
}) {
if (line.type === "header") {
return (
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono break-all border-b border-border/30">
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate border-b border-border/30">
{line.content}
</div>
);
@@ -147,7 +144,7 @@ function DiffLineComponent({
if (line.type === "hunk") {
return (
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono break-all border-b border-border/20">
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono border-b border-border/20">
{line.content}
</div>
);
@@ -173,7 +170,7 @@ function DiffLineComponent({
return (
<div
className={cn(
"flex font-mono text-sm border-l-2 transition-colors min-w-0",
"flex font-mono text-sm border-l-2 transition-colors",
bgClass,
line.type === "add" && "border-l-emerald-500",
line.type === "remove" && "border-l-rose-500",
@@ -204,7 +201,7 @@ function DiffLineComponent({
</div>
<pre
className={cn(
"flex-1 min-w-0 px-2 py-0.5 whitespace-pre-wrap break-words overflow-hidden",
"flex-1 px-2 py-0.5 whitespace-pre-wrap break-words",
textClass,
)}
>
@@ -218,15 +215,11 @@ export function FileDiffView({
repoId,
filePath,
includeStaged,
commitHash,
onBack,
onClose,
onOpenFile,
isMobile = false,
}: FileDiffViewProps) {
const workingDiff = useFileDiff(repoId, filePath, includeStaged);
const commitDiff = useCommitFileDiff(repoId, commitHash, filePath);
const { data: diffData, isLoading, error } = commitHash ? commitDiff : workingDiff;
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath, includeStaged);
const fileName = filePath.split("/").pop() || filePath;
const dirPath = filePath.includes("/")
@@ -266,7 +259,7 @@ export function FileDiffView({
const diffLines = diffData.diff ? parseDiff(diffData.diff) : [];
return (
<div className="flex flex-col h-full bg-background overflow-hidden">
<div className="flex flex-col h-full bg-background">
<div
className={cn(
"flex items-center gap-2 px-3 py-2 border-b border-border flex-shrink-0",
@@ -338,20 +331,10 @@ export function FileDiffView({
className="flex-shrink-0"
/>
)}
{onClose && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 flex-shrink-0"
onClick={onClose}
>
<X className="w-4 h-4" />
</Button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
<div className="flex-1 overflow-y-auto min-h-0">
{diffData.isBinary ? (
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
<p className="text-sm">Binary file - cannot display diff</p>
@@ -0,0 +1,147 @@
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>
)
}
@@ -0,0 +1,146 @@
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>
)
}
@@ -1,52 +0,0 @@
import { X, Mic, MicOff } from 'lucide-react'
interface RecordingOverlayProps {
interimTranscript: string
onStop: () => void
onCancel: () => void
}
export function RecordingOverlay({
interimTranscript,
onStop,
onCancel
}: RecordingOverlayProps) {
return (
<div className="flex flex-col gap-3 py-2">
<div className="flex items-center justify-center h-12">
<div className="flex items-center gap-2 text-red-500">
<Mic className="w-5 h-5 animate-pulse" />
<span className="text-sm font-medium">Recording...</span>
</div>
</div>
<div className="min-h-[40px] px-3 py-2 bg-muted/50 rounded-lg">
{interimTranscript ? (
<p className="text-sm text-foreground">{interimTranscript}</p>
) : (
<p className="text-sm text-muted-foreground italic">Listening...</p>
)}
</div>
<div className="flex items-center justify-between gap-2">
<button
type="button"
onClick={onCancel}
className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
>
<X className="w-4 h-4" />
<span>Cancel</span>
</button>
<button
type="button"
onClick={onStop}
className="flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-medium bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-white border border-red-500/60 shadow-md shadow-red-500/30 transition-all duration-200 active:scale-95"
>
<MicOff className="w-3 h-3" />
<span>Done</span>
</button>
</div>
</div>
)
}
@@ -0,0 +1,81 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { resetRepoPermissions } from "@/api/repos";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { showToast } from "@/lib/toast";
interface ResetPermissionsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoId: number;
repoDirectory?: string;
}
export function ResetPermissionsDialog({
open,
onOpenChange,
repoId,
repoDirectory,
}: ResetPermissionsDialogProps) {
const queryClient = useQueryClient();
const resetPermissionsMutation = useMutation({
mutationFn: () => resetRepoPermissions(repoId),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["opencode", "sessions", "http://localhost:5551", repoDirectory],
});
showToast.success("Permissions reset successfully");
onOpenChange(false);
},
onError: () => {
showToast.error("Failed to reset permissions");
},
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Reset Permissions</DialogTitle>
<DialogDescription>
This will clear all "Allow Always" permissions for this repository.
You will be prompted again for permission when opencode needs to perform
actions like running commands or editing files.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={resetPermissionsMutation.isPending}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={() => resetPermissionsMutation.mutate()}
disabled={resetPermissionsMutation.isPending}
>
{resetPermissionsMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Resetting...
</>
) : (
"Reset Permissions"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -123,6 +123,8 @@ export function GeneralSettings() {
/>
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
@@ -0,0 +1,373 @@
import { useState, useEffect } 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 { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Save, Loader2, Database, Brain, AlertCircle, RefreshCw, Play } 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 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 defaults = DEFAULT_CONFIGS[provider]
setLocalConfig({
embedding: {
provider,
model: defaults.model,
dimensions: defaults.dimensions,
},
dedupThreshold: config?.dedupThreshold ?? 0.25,
})
}
const updateMutation = useMutation({
mutationFn: updatePluginConfig,
onSuccess: (data) => {
showToast.success('Memory plugin configuration saved')
queryClient.setQueryData(['memory-plugin-config'], { config: data.config })
},
onError: () => {
showToast.error('Failed to save configuration')
},
})
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
updateMutation.mutate(localConfig, {
onSuccess: async () => {
showToast.loading('Restarting OpenCode server...', { id: 'memory-restart' })
try {
await settingsApi.restartOpenCodeServer()
showToast.success('Configuration saved and server restarted', { id: 'memory-restart' })
} catch {
showToast.error('Failed to restart server', { id: 'memory-restart' })
}
},
})
}
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 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>
</div>
<div className="space-y-4 border-t pt-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>
{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="space-y-4 border-t pt-4">
<div className="flex items-center justify-between">
<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}
>
{reindexMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<RefreshCw className="h-4 w-4 mr-1" />
)}
Reindex
</Button>
</div>
<p className="text-xs text-muted-foreground">
Regenerate embeddings for all memories. Use when changing embedding model or if embeddings are missing.
</p>
</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>
)
}
@@ -1,4 +1,5 @@
import { useState, useEffect, useRef } from 'react'
import { cn } from '@/lib/utils'
import { Loader2, Plus, Trash2, Edit, StarOff, Download, RotateCcw, FileText, ArrowUpCircle, History } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -13,6 +14,7 @@ import { AgentsEditor } from './AgentsEditor'
import { AgentsMdEditor } from './AgentsMdEditor'
import { McpManager } from './McpManager'
import { VersionSelectDialog } from './VersionSelectDialog'
import { MemoryPluginConfig } from './MemoryPluginConfig'
import { settingsApi } from '@/api/settings'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useServerHealth } from '@/hooks/useServerHealth'
@@ -183,7 +185,8 @@ export function OpenCodeConfigManager() {
}
const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent)
if (restartServer || agentsChanged) {
const pluginsChanged = JSON.stringify(previousContent?.plugin) !== JSON.stringify(newContent.plugin)
if (restartServer || agentsChanged || pluginsChanged) {
showToast.loading('Reloading server...', { id: 'update-restart' })
try {
await reloadConfigMutation.mutateAsync()
@@ -328,10 +331,10 @@ export function OpenCodeConfigManager() {
return (
<div className="space-y-6 overflow-y-auto">
{health && (
<Card className={isUnhealthy ? 'border-destructive' : ''}>
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
<CardContent className="p-3">
<div className="flex flex-col sm:flex-row sm:items-center items-center gap-3">
<div className="flex items-center gap-2 flex-wrap justify-center sm:justify-start">
<div className="flex flex-col sm:flex-row sm:items-center items-center justify-center gap-3">
<div className="flex items-center gap-2 flex-wrap justify-center ">
<div className={`h-3 w-3 rounded-full ${isUnhealthy ? 'bg-destructive animate-pulse' : 'bg-green-500'}`} />
<p className="font-medium text-sm sm:text-base">
Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}
@@ -418,8 +421,32 @@ export function OpenCodeConfigManager() {
</div>
</CardContent>
</Card>
)}
<CreateConfigDialog
)}
<MemoryPluginConfig
memoryPluginEnabled={configs.find(c => c.isDefault)?.content?.plugin?.includes('@opencode-manager/memory') ?? false}
onToggle={async (enabled) => {
const defaultConfig = configs.find(c => c.isDefault)
if (!defaultConfig) return
const currentPlugins = defaultConfig.content?.plugin ?? []
const memoryPlugin = '@opencode-manager/memory'
const newPlugins = enabled
? currentPlugins.includes(memoryPlugin)
? currentPlugins
: [...currentPlugins, memoryPlugin]
: currentPlugins.filter(p => p !== memoryPlugin)
await updateConfigContent(defaultConfig.name, {
...defaultConfig.content,
plugin: newPlugins.length > 0 ? newPlugins : undefined
}, true)
queryClient.invalidateQueries({ queryKey: ['memory-plugin-status'] })
}}
/>
<CreateConfigDialog
isOpen={isCreateDialogOpen}
onOpenChange={setIsCreateDialogOpen}
onCreate={createConfig}
@@ -446,7 +473,7 @@ export function OpenCodeConfigManager() {
return 0
})
.map((config) => (
<Card key={config.id} className={config.isDefault ? 'border-green-500' : ''}>
<Card key={config.id} className={cn('border-transparent', config.isDefault && 'border-green-500')}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 flex-wrap">
@@ -4,28 +4,23 @@ import { useGit } from '@/hooks/useGit'
import { GitFlatFileList } from './GitFlatFileList'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { DiscardDialog } from '@/components/ui/discard-dialog'
import { Loader2, GitCommit, FileText, AlertCircle } from 'lucide-react'
interface ChangesTabProps {
repoId: number
onFileSelect: (path: string, staged: boolean) => void
onClearFileSelection?: () => void
selectedFile?: {path: string, staged: boolean}
isMobile: boolean
onError?: (error: unknown) => void
}
export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selectedFile, isMobile, onError }: ChangesTabProps) {
export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onError }: ChangesTabProps) {
const { data: status, isLoading, error } = useGitStatus(repoId)
const git = useGit(repoId, onError)
const [commitMessage, setCommitMessage] = useState('')
const [discardDialogOpen, setDiscardDialogOpen] = useState(false)
const [discardPaths, setDiscardPaths] = useState<string[]>([])
const [discardStaged, setDiscardStaged] = useState(false)
const stagedFiles = status?.files.filter(f => f.staged) || []
const unstagedFiles = status?.files.filter(f => !f.staged) || []
const canCommit = commitMessage.trim() && stagedFiles.length > 0 && !git.commit.isPending
@@ -38,23 +33,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
git.unstageFiles.mutate(paths)
}
const handleDiscard = (paths: string[], staged: boolean) => {
setDiscardPaths(paths)
setDiscardStaged(staged)
setDiscardDialogOpen(true)
}
const confirmDiscard = () => {
git.discardFiles.mutate({ paths: discardPaths, staged: discardStaged })
setDiscardDialogOpen(false)
setDiscardPaths([])
}
const cancelDiscard = () => {
setDiscardDialogOpen(false)
setDiscardPaths([])
}
const handleCommit = () => {
git.commit.mutate({ message: commitMessage.trim() })
setCommitMessage('')
@@ -82,13 +60,83 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
if (isMobile && selectedFile) {
return (
<div className="flex flex-col h-full min-h-0 overflow-hidden">
<FileDiffView
repoId={repoId}
filePath={selectedFile.path}
includeStaged={selectedFile.staged}
onBack={onClearFileSelection}
/>
<div className="flex flex-col h-full">
<Tabs defaultValue="files" className="flex flex-col h-full">
<TabsList className="flex-shrink-0">
<TabsTrigger value="files">Files ({stagedFiles.length + unstagedFiles.length})</TabsTrigger>
<TabsTrigger value="diff">{selectedFile.path.split('/').pop() || selectedFile.path}</TabsTrigger>
</TabsList>
<TabsContent value="files" className="flex-1 overflow-hidden mt-0">
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-3 space-y-4">
{status.hasChanges ? (
<>
{stagedFiles.length > 0 && (
<GitFlatFileList
files={stagedFiles}
staged={true}
onSelect={onFileSelect}
onUnstage={handleUnstage}
selectedFile={selectedFile?.path}
/>
)}
{unstagedFiles.length > 0 && (
<GitFlatFileList
files={unstagedFiles}
staged={false}
onSelect={onFileSelect}
onStage={handleStage}
selectedFile={selectedFile?.path}
/>
)}
</>
) : (
<div className="text-center py-12 text-muted-foreground">
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No uncommitted changes</p>
</div>
)}
</div>
{status.hasChanges && (
<div className="p-3 border-t border-border space-y-2 flex-shrink-0">
<Textarea
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] md:text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
}
}}
/>
<Button
onClick={handleCommit}
disabled={!canCommit}
className="w-full h-9"
>
{git.commit.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<GitCommit className="w-4 h-4 mr-2" />
)}
Commit {stagedFiles.length > 0 && `(${stagedFiles.length} staged)`}
</Button>
<p className="text-[10px] text-muted-foreground text-center">
{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}+Enter to commit
</p>
</div>
)}
</div>
</TabsContent>
<TabsContent value="diff" className="flex-1 overflow-hidden mt-0">
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
</TabsContent>
</Tabs>
</div>
)
} else {
@@ -103,7 +151,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
staged={true}
onSelect={onFileSelect}
onUnstage={handleUnstage}
onDiscard={handleDiscard}
selectedFile={selectedFile?.path}
/>
)}
@@ -114,7 +161,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
staged={false}
onSelect={onFileSelect}
onStage={handleStage}
onDiscard={handleDiscard}
selectedFile={selectedFile?.path}
/>
)}
@@ -157,15 +203,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
</p>
</div>
)}
<DiscardDialog
open={discardDialogOpen}
onOpenChange={setDiscardDialogOpen}
onConfirm={confirmDiscard}
onCancel={cancelDiscard}
fileCount={discardPaths.length}
isDiscarding={git.discardFiles.isPending}
/>
</div>
)
}
@@ -1,102 +0,0 @@
import { useCommitDetails } from '@/api/git'
import { Loader2, GitCommit, ArrowLeft } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { GitFlatFileList } from './GitFlatFileList'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
interface CommitDetailViewProps {
repoId: number
commitHash: string
onBack: () => void
onFileSelect: (path: string) => void
selectedFile?: string
}
export function CommitDetailView({ repoId, commitHash, onBack, onFileSelect, selectedFile }: CommitDetailViewProps) {
const { data: commit, isLoading, error } = useCommitDetails(repoId, commitHash)
if (isLoading) {
return (
<div className="flex items-center justify-center h-full py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)
}
if (error || !commit) {
return (
<div className="text-center py-12 text-muted-foreground">
<GitCommit className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Failed to load commit details</p>
<p className="text-xs mt-1">{error?.message}</p>
<Button variant="outline" size="sm" onClick={onBack} className="mt-4">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to commits
</Button>
</div>
)
}
const commitFiles = commit.files.map(f => ({
path: f.path,
status: f.status,
staged: false,
oldPath: f.oldPath,
additions: f.additions,
deletions: f.deletions
}))
const totalAdditions = commit.files.reduce((sum, f) => sum + (f.additions || 0), 0)
const totalDeletions = commit.files.reduce((sum, f) => sum + (f.deletions || 0), 0)
if (selectedFile) {
return (
<div className="flex flex-col h-full min-h-0 overflow-hidden">
<FileDiffView
repoId={repoId}
filePath={selectedFile}
includeStaged={false}
commitHash={commitHash}
onBack={() => onFileSelect('')}
/>
</div>
)
}
return (
<div className="flex flex-col h-full">
<div className="px-3 py-3 border-b border-border flex-shrink-0 space-y-2">
<div className="flex items-start gap-2">
<Button
variant="ghost"
size="sm"
onClick={onBack}
className="h-7 w-7 p-0 flex-shrink-0 mt-0.5"
>
<ArrowLeft className="w-4 h-4" />
</Button>
<p className="text-sm font-medium leading-snug">{commit.message}</p>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground pl-9">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{new Date(parseInt(commit.date, 10) * 1000).toLocaleDateString()}</span>
</div>
</div>
<div className="flex-1 overflow-y-auto px-1 pt-1">
<GitFlatFileList
files={commitFiles}
staged={false}
onSelect={(path) => onFileSelect(path)}
selectedFile={selectedFile}
readOnly={true}
totalAdditions={totalAdditions}
totalDeletions={totalDeletions}
/>
</div>
</div>
)
}
@@ -59,41 +59,34 @@ export function CommitsTab({ repoId, onSelectCommit }: CommitsTabProps) {
}
return (
<div className="flex flex-col h-full overflow-x-hidden">
<div className="flex-1 overflow-y-auto overflow-x-hidden">
{data.commits.map((commit) => (
<button
key={commit.hash}
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
onClick={() => onSelectCommit?.(commit.hash)}
>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
<GitCommit className="w-4 h-4 text-muted-foreground" />
<div className="flex flex-col h-full overflow-y-auto">
{data.commits.map((commit) => (
<button
key={commit.hash}
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
onClick={() => onSelectCommit?.(commit.hash)}
>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
<GitCommit className="w-4 h-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{commit.message}</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
{commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
<ArrowUp className="w-3 h-3" />
Local
</span>
)}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium line-clamp-2">{commit.message}</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground overflow-hidden">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
{commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
<ArrowUp className="w-3 h-3" />
Local
</span>
)}
{!commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.pushed)}>
Remote
</span>
)}
</div>
</div>
</button>
))}
</div>
</div>
</button>
))}
</div>
)
}
@@ -1,5 +1,5 @@
import { Button } from '@/components/ui/button'
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot, RotateCcw } from 'lucide-react'
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { GitFileStatus } from '@/types/git'
import { GIT_STATUS_COLORS, GIT_UI_COLORS } from '@/lib/git-status-styles'
@@ -10,7 +10,6 @@ interface GitFlatFileItemProps {
onSelect: (path: string, staged: boolean) => void
onStage?: (path: string) => void
onUnstage?: (path: string) => void
onDiscard?: (path: string, staged: boolean) => void
}
const statusIcons = {
@@ -22,7 +21,7 @@ const statusIcons = {
copied: FilePlus,
}
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage, onDiscard }: GitFlatFileItemProps) {
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage }: GitFlatFileItemProps) {
const StatusIcon = statusIcons[file.status] || FileText
const statusColor = GIT_STATUS_COLORS[file.status] || 'text-muted-foreground'
@@ -38,13 +37,6 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
}
}
const handleDiscard = (e: React.MouseEvent) => {
e.stopPropagation()
if (onDiscard) {
onDiscard(file.path, file.staged)
}
}
return (
<div
className={cn(
@@ -67,41 +59,18 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
staged
</span>
)}
{(file.additions !== undefined || file.deletions !== undefined) && (
<div className="flex items-center gap-1 text-xs flex-shrink-0">
{file.additions !== undefined && file.additions > 0 && (
<span className="text-green-500">+{file.additions}</span>
)}
{file.deletions !== undefined && file.deletions > 0 && (
<span className="text-red-500">-{file.deletions}</span>
)}
</div>
)}
{(onStage || onUnstage) && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleAction}
>
{file.staged ? (
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
) : (
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
)}
</Button>
)}
{onDiscard && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleDiscard}
title="Discard changes"
>
<RotateCcw className="w-3 h-3 text-rose-500" />
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleAction}
>
{file.staged ? (
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
) : (
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
)}
</Button>
</div>
)
}
@@ -12,11 +12,7 @@ interface GitFlatFileListProps {
onSelect: (path: string, staged: boolean) => void
onStage?: (paths: string[]) => void
onUnstage?: (paths: string[]) => void
onDiscard?: (paths: string[], staged: boolean) => void
selectedFile?: string
readOnly?: boolean
totalAdditions?: number
totalDeletions?: number
}
interface GroupedFiles {
@@ -32,11 +28,7 @@ export function GitFlatFileList({
onSelect,
onStage,
onUnstage,
onDiscard,
selectedFile,
readOnly = false,
totalAdditions,
totalDeletions,
}: GitFlatFileListProps) {
const [collapsedGroups, setCollapsedGroups] = useState<Set<GitFileStatusType>>(new Set())
@@ -91,13 +83,6 @@ export function GitFlatFileList({
}
}
const handleDiscardAll = (e: React.MouseEvent) => {
e.stopPropagation()
if (onDiscard) {
onDiscard(filteredFiles.map(f => f.path), staged)
}
}
if (filteredFiles.length === 0) {
return null
}
@@ -108,44 +93,24 @@ export function GitFlatFileList({
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{staged ? 'Staged Changes' : 'Changes'} ({filteredFiles.length})
</span>
{(totalAdditions !== undefined && totalAdditions > 0 || totalDeletions !== undefined && totalDeletions > 0) && (
<div className="flex items-center gap-1 text-xs">
{totalAdditions !== undefined && totalAdditions > 0 && <span className="text-green-500">+{totalAdditions}</span>}
{totalDeletions !== undefined && totalDeletions > 0 && <span className="text-red-500">-{totalDeletions}</span>}
</div>
)}
{!readOnly && (
<div className="flex items-center gap-1">
{onDiscard && (
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs text-rose-500 hover:text-rose-600"
onClick={handleDiscardAll}
>
Discard All
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={staged ? handleUnstageAll : handleStageAll}
>
{staged ? (
<>
<Minus className="w-3 h-3 mr-1" />
Unstage All
</>
) : (
<>
<Plus className="w-3 h-3 mr-1" />
Stage All
</>
)}
</Button>
</div>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={staged ? handleUnstageAll : handleStageAll}
>
{staged ? (
<>
<Minus className="w-3 h-3 mr-1" />
Unstage All
</>
) : (
<>
<Plus className="w-3 h-3 mr-1" />
Stage All
</>
)}
</Button>
</div>
{groupedFiles.map(({ status, files: groupFiles }) => {
@@ -178,9 +143,8 @@ export function GitFlatFileList({
file={file}
isSelected={selectedFile === file.path}
onSelect={onSelect}
onStage={readOnly ? undefined : handleStageFile}
onUnstage={readOnly ? undefined : handleUnstageFile}
onDiscard={readOnly ? undefined : onDiscard ? ((path: string, staged: boolean) => onDiscard([path], staged)) : undefined}
onStage={handleStageFile}
onUnstage={handleUnstageFile}
/>
))}
</div>
@@ -6,7 +6,6 @@ import { useGit } from '@/hooks/useGit'
import { ChangesTab } from './ChangesTab'
import { CommitsTab } from './CommitsTab'
import { BranchesTab } from './BranchesTab'
import { CommitDetailView } from './CommitDetailView'
import { GitErrorBanner } from './GitErrorBanner'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { Button } from '@/components/ui/button'
@@ -38,7 +37,6 @@ interface SourceControlPanelProps {
}
type Tab = 'changes' | 'commits' | 'branches'
type View = 'default' | 'commit-detail'
export function SourceControlPanel({
repoId,
@@ -51,9 +49,6 @@ export function SourceControlPanel({
}: SourceControlPanelProps) {
const [activeTab, setActiveTab] = useState<Tab>('changes')
const [selectedFile, setSelectedFile] = useState<{path: string, staged: boolean} | undefined>()
const [currentView, setCurrentView] = useState<View>('default')
const [selectedCommit, setSelectedCommit] = useState<string | undefined>()
const [selectedCommitFile, setSelectedCommitFile] = useState<string | undefined>()
const [gitError, setGitError] = useState<{ summary: string; detail?: string } | null>(null)
const { data: status } = useGitStatus(repoId)
const isMobile = useMobile()
@@ -77,18 +72,6 @@ export function SourceControlPanel({
}
}
const handleSelectCommit = (hash: string) => {
setSelectedCommit(hash)
setCurrentView('commit-detail')
}
const handleBackToCommits = () => {
setSelectedCommit(undefined)
setSelectedCommitFile(undefined)
setCurrentView('default')
setActiveTab('commits')
}
const tabs: { id: Tab; label: string; icon: React.ElementType }[] = [
{ id: 'changes', label: 'Changes', icon: FileCode },
{ id: 'commits', label: 'Commits', icon: History },
@@ -99,7 +82,7 @@ export function SourceControlPanel({
const stagedCount = status?.files.filter(f => f.staged).length || 0
const content = (
<div className="flex flex-col h-full gap-0">
<div className="flex flex-col h-full">
<div className="flex items-center justify-between px-3 py-2 border-b border-border flex-shrink-0">
<div className="flex items-center gap-2">
<div className="flex items-center gap-2">
@@ -171,79 +154,69 @@ export function SourceControlPanel({
<GitErrorBanner error={gitError} onDismiss={() => setGitError(null)} />
)}
{!((currentView === 'commit-detail' && selectedCommitFile) || (isMobile && selectedFile && activeTab === 'changes')) && (
<div className="flex border-b border-border flex-shrink-0">
{tabs.map((tab) => {
const Icon = tab.icon
return (
<button
key={tab.id}
className={cn(
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
activeTab === tab.id
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
)}
onClick={() => setActiveTab(tab.id)}
>
<Icon className="w-4 h-4" />
<span>{tab.label}</span>
{tab.id === 'changes' && changesCount > 0 && (
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
</span>
)}
</button>
)
})}
</div>
)}
<div className="flex border-b border-border flex-shrink-0">
{tabs.map((tab) => {
const Icon = tab.icon
return (
<button
key={tab.id}
className={cn(
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
activeTab === tab.id
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
)}
onClick={() => setActiveTab(tab.id)}
>
<Icon className="w-4 h-4" />
<span>{tab.label}</span>
{tab.id === 'changes' && changesCount > 0 && (
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
</span>
)}
</button>
)
})}
</div>
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col gap-0' : 'flex')}>
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col' : 'flex')}>
<div className={cn(
'overflow-hidden min-h-0 h-full flex flex-col',
isMobile
? 'flex-1'
: currentView === 'commit-detail'
? 'flex-1'
: selectedFile
? 'w-[35%] border-r border-border'
: 'flex-1'
'overflow-hidden',
isMobile ? 'flex-1' : selectedFile ? 'w-[35%] border-r border-border' : 'flex-1'
)}>
{activeTab === 'changes' && (
<ChangesTab
repoId={repoId}
onFileSelect={(path, staged) => setSelectedFile({ path, staged })}
onClearFileSelection={() => setSelectedFile(undefined)}
selectedFile={selectedFile}
isMobile={isMobile}
onError={handleGitError}
/>
)}
{activeTab === 'commits' && currentView === 'default' && (
<CommitsTab repoId={repoId} onSelectCommit={handleSelectCommit} />
{activeTab === 'commits' && (
<CommitsTab repoId={repoId} />
)}
{activeTab === 'branches' && currentView === 'default' && (
{activeTab === 'branches' && (
<BranchesTab repoId={repoId} currentBranch={currentBranch} repoUrl={repoUrl} isRepoWorktree={isRepoWorktree} />
)}
{currentView === 'commit-detail' && selectedCommit && (
<div className="flex flex-1 min-h-0 overflow-hidden flex-col">
<CommitDetailView
repoId={repoId}
commitHash={selectedCommit}
onBack={handleBackToCommits}
onFileSelect={setSelectedCommitFile}
selectedFile={selectedCommitFile}
/>
</div>
)}
</div>
{selectedFile && !isMobile && currentView === 'default' && (
{selectedFile && !isMobile && (
<div className="flex-1 overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
<span className="text-sm font-medium truncate">{selectedFile.path}</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
onClick={() => setSelectedFile(undefined)}
>
<X className="w-4 h-4" />
</Button>
</div>
<div className="flex-1 overflow-auto">
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} onClose={() => setSelectedFile(undefined)} />
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
</div>
</div>
)}
@@ -257,12 +230,12 @@ export function SourceControlPanel({
mobileFullscreen
hideCloseButton={isMobile}
className={cn(
'p-0 flex flex-col bg-card border-border gap-0',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0'
'p-0 flex flex-col bg-card border-border',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh]'
)}
>
<DialogHeader className={cn(
'px-4 py-2 border-b border-border flex-shrink-0',
'px-4 py-3 border-b border-border flex-shrink-0',
isMobile && 'relative'
)}>
<DialogTitle className="flex items-center gap-2">
@@ -280,7 +253,7 @@ export function SourceControlPanel({
</Button>
)}
</DialogHeader>
<div className="flex-1 overflow-hidden pb-0">
<div className="flex-1 overflow-hidden">
{content}
</div>
</DialogContent>
@@ -1,59 +0,0 @@
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertTriangle } from 'lucide-react'
interface DiscardDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
fileCount: number
isDiscarding?: boolean
}
export function DiscardDialog({
open,
onOpenChange,
onConfirm,
onCancel,
fileCount,
isDiscarding = false
}: DiscardDialogProps) {
const itemText = fileCount === 1 ? '1 file' : `${fileCount} files`
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className='max-w-[90%] sm:max-w-sm'>
<DialogHeader>
<DialogTitle>Discard Changes</DialogTitle>
<DialogDescription>
Are you sure you want to discard changes to {itemText}? This action cannot be undone.
</DialogDescription>
</DialogHeader>
<Alert className="overflow-hidden">
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
<AlertDescription>
This will permanently delete your uncommitted changes to {itemText}. If these changes exist in the staging area, they will also be removed.
</AlertDescription>
</Alert>
<DialogFooter className='gap-2'>
<Button variant="outline" onClick={onCancel} disabled={isDiscarding}>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isDiscarding}
className="bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
>
{isDiscarding && 'Discarding...'}
{!isDiscarding && 'Discard'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,85 +0,0 @@
import { memo, type ReactNode } from 'react'
import { X, VolumeX, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
type FloatingActionVariant = 'clear' | 'stop-audio' | 'custom'
interface FloatingActionButtonProps {
variant: FloatingActionVariant
onClick: () => void
visible: boolean
loading?: boolean
icon?: ReactNode
label?: string
position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'
className?: string
}
const variantConfig: Record<FloatingActionVariant, { icon: ReactNode; label: string; colors: string }> = {
'clear': {
icon: <X className="w-5 h-5" />,
label: 'Clear',
colors: 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 border-2 border-red-500/60 hover:border-red-400 shadow-lg shadow-red-500/30 hover:shadow-red-500/50 ring-2 ring-red-500/20 hover:ring-red-500/40 text-destructive-foreground'
},
'stop-audio': {
icon: <VolumeX className="w-5 h-5" />,
label: 'Stop Audio',
colors: 'bg-gradient-to-br from-red-700 to-red-800 hover:from-red-600 hover:to-red-700 border-2 border-red-600/80 hover:border-red-500 shadow-2xl shadow-red-600/40 hover:shadow-red-600/60 ring-2 ring-red-600/30 hover:ring-red-600/50 animate-[pulse_2s_cubic-bezier(0.4,0,0.6,1)_infinite] text-destructive-foreground',
},
'custom': {
icon: null,
label: '',
colors: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground border-border'
}
}
const positionClasses: Record<NonNullable<FloatingActionButtonProps['position']>, string> = {
'top-right': 'top-4 right-4',
'top-left': 'top-4 left-4',
'bottom-right': 'bottom-4 right-4',
'bottom-left': 'bottom-4 left-4'
}
export const FloatingActionButton = memo(function FloatingActionButton({
variant,
onClick,
visible,
loading = false,
icon,
label,
position = 'top-right',
className
}: FloatingActionButtonProps) {
const config = variantConfig[variant]
const displayIcon = icon ?? config.icon
const displayLabel = label ?? config.label
if (!visible) return null
return (
<button
onClick={onClick}
disabled={loading}
className={cn(
'fixed z-50 flex items-center gap-2 px-4 py-2 rounded-xl backdrop-blur-md transition-all duration-200',
'min-w-[48px] min-h-[48px]',
'active:scale-95 hover:scale-105',
'transition-transform',
config.colors,
positionClasses[position],
loading && 'opacity-70 cursor-not-allowed grayscale',
className
)}
aria-label={displayLabel}
>
{loading ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
displayIcon
)}
{displayLabel && (
<span className="text-sm font-medium hidden sm:inline">{displayLabel}</span>
)}
</button>
)
})