refactor: improve virtualized text viewer with React Query infinite scroll and simplified buffering (#108)

* Add OAuth authentication support for MCP servers

* Improve mobile text sizing with responsive text classes

* refactor: improve virtualized text viewer with React Query infinite scroll and simplified buffering
This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-05 20:18:27 -05:00
1 parent c453235839
commit f570758b74
24 files changed
+930 -471

No files matched your search

+8 -21
View File
@@ -274,36 +274,24 @@ function getMimeType(filePath: string): AllowedMimeType {
return mimeTypes[ext] || 'text/plain'
}
async function countFileLines(filePath: string): Promise<number> {
return new Promise((resolve, reject) => {
let lineCount = 0
const stream = createReadStream(filePath, { encoding: 'utf8' })
const rl = createInterface({ input: stream, crlfDelay: Infinity })
rl.on('line', () => { lineCount++ })
rl.on('close', () => resolve(lineCount))
rl.on('error', reject)
})
}
async function readFileLines(filePath: string, startLine: number, endLine: number): Promise<string[]> {
async function readFileLinesAndCount(
filePath: string,
startLine: number,
endLine: number
): Promise<{ lines: string[]; totalLines: number }> {
return new Promise((resolve, reject) => {
const lines: string[] = []
let currentLine = 0
const stream = createReadStream(filePath, { encoding: 'utf8' })
const rl = createInterface({ input: stream, crlfDelay: Infinity })
rl.on('line', (line) => {
if (currentLine >= startLine && currentLine < endLine) {
lines.push(line)
}
currentLine++
if (currentLine >= endLine) {
rl.close()
stream.destroy()
}
})
rl.on('close', () => resolve(lines))
rl.on('close', () => resolve({ lines, totalLines: currentLine }))
rl.on('error', reject)
})
}
@@ -322,9 +310,8 @@ export async function getFileRange(userPath: string, startLine: number, endLine:
throw { message: 'Path is a directory', statusCode: 400 }
}
const totalLines = await countFileLines(validatedPath)
const { lines, totalLines } = await readFileLinesAndCount(validatedPath, startLine, endLine)
const clampedEnd = Math.min(endLine, totalLines)
const lines = await readFileLines(validatedPath, startLine, clampedEnd)
const mimeType = getMimeType(validatedPath)
return {
@@ -9,7 +9,7 @@ import { MarkdownRenderer } from './MarkdownRenderer'
const API_BASE = API_BASE_URL
const VIRTUALIZATION_THRESHOLD_BYTES = 8_000
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
const MARKDOWN_PREVIEW_SIZE_LIMIT = 1_000_000
interface FilePreviewProps {
@@ -89,7 +89,7 @@ export const EditableUserMessage = memo(function EditableUserMessage({
onKeyDown={handleKeyDown}
onFocus={() => setIsEditingMessage(true)}
onBlur={() => setIsEditingMessage(false)}
className="w-full p-3 rounded-lg bg-background border border-primary/50 focus:border-primary focus:ring-1 focus:ring-primary outline-none resize-none min-h-[60px] text-sm"
className="w-full p-3 rounded-lg bg-background border border-primary/50 focus:border-primary focus:ring-1 focus:ring-primary outline-none resize-none min-h-[60px] text-[16px] md:text-sm"
placeholder="Edit your message..."
disabled={refreshMessage.isPending}
/>
@@ -57,7 +57,7 @@ function SearchInput({ onSearch, initialValue = "" }: SearchInputProps) {
placeholder="Search models..."
value={value}
onChange={(e) => setValue(e.target.value)}
className="pl-10 text-sm"
className="pl-10 md:text-sm"
/>
</div>
</div>
+137 -19
View File
@@ -1,21 +1,17 @@
import { useState, useEffect, useCallback } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { Switch } from '@/components/ui/switch'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Loader2, XCircle, AlertCircle, Plug } from 'lucide-react'
import { mcpApi, type McpStatus } from '@/api/mcp'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
import { Loader2, XCircle, AlertCircle, Plug, Shield, MoreVertical, Key, RefreshCw } from 'lucide-react'
import { McpOAuthDialog } from '@/components/settings/McpOAuthDialog'
import { mcpApi, type McpStatus, type McpServerConfig, type McpAuthStartResponse } from '@/api/mcp'
import { useMutation } from '@tanstack/react-query'
import { showToast } from '@/lib/toast'
interface McpServerConfig {
type: 'local' | 'remote'
enabled?: boolean
command?: string[]
url?: string
environment?: Record<string, string>
timeout?: number
}
interface RepoMcpDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
@@ -28,6 +24,8 @@ interface RepoMcpDialogProps {
export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcpDialogProps) {
const [localStatus, setLocalStatus] = useState<Record<string, McpStatus>>({})
const [isLoadingStatus, setIsLoadingStatus] = useState(false)
const [removeAuthConfirmServer, setRemoveAuthConfirmServer] = useState<string | null>(null)
const [authDialogServerId, setAuthDialogServerId] = useState<string | null>(null)
const mcpServers = config?.content?.mcp as Record<string, McpServerConfig> | undefined || {}
const serverIds = Object.keys(mcpServers)
@@ -68,6 +66,40 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp
showToast.error(error instanceof Error ? error.message : 'Failed to update MCP server')
},
})
const removeAuthMutation = useMutation({
mutationFn: async (serverId: string) => {
if (!directory) throw new Error('No directory provided')
await mcpApi.removeAuthDirectory(serverId, directory)
},
onSuccess: async () => {
showToast.success('Authentication removed for this location')
setRemoveAuthConfirmServer(null)
await fetchStatus()
},
onError: (error) => {
showToast.error(error instanceof Error ? error.message : 'Failed to remove authentication')
},
})
const handleOAuthAutoAuth = async () => {
if (!authDialogServerId || !directory) return
await mcpApi.authenticateDirectory(authDialogServerId, directory)
await fetchStatus()
setAuthDialogServerId(null)
}
const handleOAuthStartAuth = async (): Promise<McpAuthStartResponse> => {
if (!authDialogServerId) throw new Error('No server ID')
return await mcpApi.startAuth(authDialogServerId)
}
const handleOAuthCompleteAuth = async (code: string) => {
if (!authDialogServerId) return
await mcpApi.completeAuth(authDialogServerId, code)
await fetchStatus()
setAuthDialogServerId(null)
}
useEffect(() => {
if (open && directory) {
@@ -156,7 +188,14 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp
const serverConfig = mcpServers[serverId]
const status = localStatus[serverId]
const isConnected = status?.status === 'connected'
const needsAuth = status?.status === 'needs_auth'
const failed = status?.status === 'failed'
const isRemote = serverConfig.type === 'remote'
const hasOAuthConfig = isRemote && !!serverConfig.oauth
const hasOAuthError = failed && isRemote && /oauth|auth.*state/i.test(status.error)
const isOAuthServer = hasOAuthConfig || hasOAuthError || (needsAuth && isRemote)
const connectedWithOAuth = isOAuthServer && isConnected
const showAuthButton = needsAuth || (isOAuthServer && failed)
return (
<div
@@ -168,6 +207,11 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp
<p className="text-sm font-medium truncate">
{getDisplayName(serverId)}
</p>
{connectedWithOAuth && (
<span title="OAuth authenticated">
<Shield className="h-3 w-3 text-muted-foreground" />
</span>
)}
{getStatusBadge(status)}
</div>
<p className="text-xs text-muted-foreground truncate">
@@ -181,20 +225,94 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp
)}
</div>
<Switch
checked={isConnected}
disabled={toggleMutation.isPending}
onCheckedChange={(enabled) => {
toggleMutation.mutate({ serverId, enable: enabled })
}}
onClick={(e) => e.stopPropagation()}
/>
<div className="flex items-center gap-2">
{showAuthButton ? (
<Button
onClick={() => setAuthDialogServerId(serverId)}
disabled={toggleMutation.isPending}
variant="default"
size="sm"
>
<Key className="h-3 w-3 mr-1" />
Auth
</Button>
) : (
<Switch
checked={isConnected}
disabled={toggleMutation.isPending || removeAuthMutation.isPending}
onCheckedChange={(enabled) => {
toggleMutation.mutate({ serverId, enable: enabled })
}}
onClick={(e) => e.stopPropagation()}
/>
)}
{(isOAuthServer || needsAuth) && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{showAuthButton && (
<DropdownMenuItem onClick={() => setAuthDialogServerId(serverId)}>
<Key className="h-4 w-4 mr-2" />
Authenticate
</DropdownMenuItem>
)}
{connectedWithOAuth && (
<DropdownMenuItem onClick={() => setAuthDialogServerId(serverId)}>
<RefreshCw className="h-4 w-4 mr-2" />
Re-authenticate
</DropdownMenuItem>
)}
{connectedWithOAuth && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setRemoveAuthConfirmServer(serverId)}
disabled={removeAuthMutation.isPending}
>
<Shield className="h-4 w-4 mr-2" />
{removeAuthMutation.isPending ? 'Removing...' : 'Remove Auth'}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
)
})}
</div>
)}
</div>
<DeleteDialog
open={!!removeAuthConfirmServer}
onOpenChange={() => setRemoveAuthConfirmServer(null)}
onConfirm={() => {
if (removeAuthConfirmServer) {
removeAuthMutation.mutate(removeAuthConfirmServer)
}
}}
onCancel={() => setRemoveAuthConfirmServer(null)}
title="Remove Authentication"
description="This will remove the OAuth credentials for this MCP server at this location. You will need to re-authenticate to use this server here again."
itemName={removeAuthConfirmServer ? getDisplayName(removeAuthConfirmServer) : ''}
isDeleting={removeAuthMutation.isPending}
/>
<McpOAuthDialog
open={!!authDialogServerId}
onOpenChange={(o) => !o && setAuthDialogServerId(null)}
serverName={authDialogServerId || ''}
onAutoAuth={handleOAuthAutoAuth}
onStartAuth={handleOAuthStartAuth}
onCompleteAuth={handleOAuthCompleteAuth}
directory={directory}
/>
</DialogContent>
</Dialog>
)
@@ -435,7 +435,7 @@ function QuestionStep({
value={customInput}
onChange={(e) => onCustomInputChange(e.target.value)}
placeholder="Type your own answer..."
className="min-h-[60px] sm:min-h-[80px] text-xs sm:text-sm resize-none border-blue-500/30 focus:border-blue-500"
className="min-h-[60px] sm:min-h-[80px] text-[16px] sm:text-xs md:text-sm resize-none border-blue-500/30 focus:border-blue-500"
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
@@ -163,11 +163,11 @@ export function AccountSettings() {
<div className="space-y-3 sm:space-y-4">
<div className="space-y-1.5">
<Label className="text-xs sm:text-sm">Name</Label>
<Input value={user.name} disabled className="h-9 sm:h-10 text-sm" />
<Input value={user.name} disabled className="h-9 sm:h-10 md:text-sm" />
</div>
<div className="space-y-1.5">
<Label className="text-xs sm:text-sm">Email</Label>
<Input value={user.email} disabled className="h-9 sm:h-10 text-sm" />
<Input value={user.email} disabled className="h-9 sm:h-10 md:text-sm" />
</div>
<Button variant="outline" onClick={() => setEditingProfile(false)} className="h-9 sm:h-10">
Done
@@ -216,7 +216,7 @@ export function AccountSettings() {
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
placeholder="Enter current password"
className="h-9 sm:h-10 text-sm"
className="h-9 sm:h-10 md:text-sm"
/>
</div>
<div className="space-y-1.5">
@@ -227,7 +227,7 @@ export function AccountSettings() {
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="At least 8 characters"
className="h-9 sm:h-10 text-sm"
className="h-9 sm:h-10 md:text-sm"
/>
</div>
<div className="flex gap-2">
@@ -271,7 +271,7 @@ export function AccountSettings() {
placeholder="Passkey name (optional)"
value={passkeyName}
onChange={(e) => setPasskeyName(e.target.value)}
className="h-9 sm:h-10 text-sm"
className="h-9 sm:h-10 md:text-sm"
/>
<Button
onClick={handleAddPasskey}
@@ -30,6 +30,10 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
const [environment, setEnvironment] = useState<EnvironmentVariable[]>([])
const [timeout, setTimeout] = useState('')
const [enabled, setEnabled] = useState(true)
const [oauthEnabled, setOauthEnabled] = useState(false)
const [oauthClientId, setOauthClientId] = useState('')
const [oauthClientSecret, setOauthClientSecret] = useState('')
const [oauthScope, setOauthScope] = useState('')
const queryClient = useQueryClient()
const { addServerAsync, isAddingServer } = useMcpServers()
@@ -67,6 +71,14 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
throw new Error('URL is required for remote MCP servers')
}
mcpConfig.url = url.trim()
if (oauthEnabled) {
const oauthConfig: Record<string, string> = {}
if (oauthClientId.trim()) oauthConfig.clientId = oauthClientId.trim()
if (oauthClientSecret.trim()) oauthConfig.clientSecret = oauthClientSecret.trim()
if (oauthScope.trim()) oauthConfig.scope = oauthScope.trim()
mcpConfig.oauth = Object.keys(oauthConfig).length > 0 ? oauthConfig : true
}
}
if (timeout && parseInt(timeout)) {
@@ -84,6 +96,15 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
await settingsApi.updateOpenCodeConfig(config.name, { content: updatedConfig })
if (enabled) {
const buildOauthField = () => {
if (serverType !== 'remote' || !oauthEnabled) return undefined
const cfg: Record<string, string> = {}
if (oauthClientId.trim()) cfg.clientId = oauthClientId.trim()
if (oauthClientSecret.trim()) cfg.clientSecret = oauthClientSecret.trim()
if (oauthScope.trim()) cfg.scope = oauthScope.trim()
return Object.keys(cfg).length > 0 ? cfg : true
}
await addServerAsync({
name: serverId,
config: {
@@ -100,6 +121,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
}, {} as Record<string, string>)
: undefined,
timeout: timeout && parseInt(timeout) ? parseInt(timeout) : undefined,
oauth: buildOauthField(),
}
})
}
@@ -146,6 +168,10 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
setEnvironment([])
setTimeout('')
setEnabled(true)
setOauthEnabled(false)
setOauthClientId('')
setOauthClientSecret('')
setOauthScope('')
onOpenChange(false)
}
@@ -153,149 +179,203 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="w-full max-w-3xl bg-card border-border">
<DialogHeader>
<DialogContent mobileFullscreen className="sm:inset-auto sm:left-[50%] sm:top-[50%] sm:w-[95vw] sm:max-w-3xl sm:h-auto sm:max-h-[90vh] flex flex-col gap-0 bg-card border-border pb-safe">
<DialogHeader className="px-4 sm:px-6 pt-4 sm:pt-6 pb-2 sm:pb-3 shrink-0">
<DialogTitle>Add MCP Server</DialogTitle>
<DialogDescription>
Configure a new Model Context Protocol server for your OpenCode configuration
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="serverId">Server ID</Label>
<Input
id="serverId"
value={serverId}
onChange={(e) => setServerId(e.target.value)}
placeholder="e.g., filesystem, git, my-server"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Unique identifier for this MCP server (lowercase, no spaces)
</p>
</div>
<div>
<Label htmlFor="serverType">Server Type</Label>
<Select value={serverType} onValueChange={(value: 'local' | 'remote') => setServerType(value)}>
<SelectTrigger className="bg-background border-border">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="local">Local (Command)</SelectItem>
<SelectItem value="remote">Remote (HTTP)</SelectItem>
</SelectContent>
</Select>
</div>
{serverType === 'local' ? (
<div className="flex-1 overflow-y-auto min-h-0 px-4 sm:px-6 py-3 sm:py-4">
<div className="space-y-4">
<div>
<Label htmlFor="command">Command</Label>
<Label htmlFor="serverId">Server ID</Label>
<Input
id="command"
value={command}
onChange={(e) => setCommand(e.target.value)}
placeholder="npx @modelcontextprotocol/server-filesystem /tmp"
className="bg-background border-border font-mono"
id="serverId"
value={serverId}
onChange={(e) => setServerId(e.target.value)}
placeholder="e.g., filesystem, git, my-server"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Command and arguments to run the MCP server
Unique identifier for this MCP server (lowercase, no spaces)
</p>
</div>
) : (
<div>
<Label htmlFor="url">Server URL</Label>
<Input
id="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="http://localhost:3000/mcp"
className="bg-background border-border font-mono"
/>
<p className="text-xs text-muted-foreground">
URL of the remote MCP server
</p>
</div>
)}
{serverType === 'local' && (
<div>
<div className="flex items-center justify-between">
<Label>Environment Variables</Label>
<Button
type="button"
variant="outline"
size="sm"
className='h-6'
onClick={handleAddEnvironmentVar}
>
+
</Button>
<Label htmlFor="serverType">Server Type</Label>
<Select value={serverType} onValueChange={(value: 'local' | 'remote') => setServerType(value)}>
<SelectTrigger className="bg-background border-border">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="local">Local (Command)</SelectItem>
<SelectItem value="remote">Remote (HTTP)</SelectItem>
</SelectContent>
</Select>
</div>
{serverType === 'local' ? (
<div>
<Label htmlFor="command">Command</Label>
<Input
id="command"
value={command}
onChange={(e) => setCommand(e.target.value)}
placeholder="npx @modelcontextprotocol/server-filesystem /tmp"
className="bg-background border-border font-mono"
/>
<p className="text-xs text-muted-foreground">
Command and arguments to run the MCP server
</p>
</div>
{environment.map((env, index) => (
<div key={index} className="flex gap-2">
<Input
value={env.key}
onChange={(e) => handleUpdateEnvironmentVar(index, 'key', e.target.value)}
placeholder="API_KEY"
className="bg-background border-border font-mono"
) : (
<div>
<Label htmlFor="url">Server URL</Label>
<Input
id="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="http://localhost:3000/mcp"
className="bg-background border-border font-mono"
/>
<p className="text-xs text-muted-foreground">
URL of the remote MCP server
</p>
</div>
)}
{serverType === 'remote' && (
<div className="space-y-3">
<div className="flex items-center space-x-2">
<Switch
id="oauth"
checked={oauthEnabled}
onCheckedChange={setOauthEnabled}
/>
<Input
value={env.value}
onChange={(e) => handleUpdateEnvironmentVar(index, 'value', e.target.value)}
placeholder="your-api-key-here"
className="bg-background border-border font-mono"
/>
{environment.length > 1 && (
<Button
type="button"
variant="outline"
size="icon"
onClick={() => handleRemoveEnvironmentVar(index)}
>
x
</Button>
)}
<Label htmlFor="oauth">Enable OAuth</Label>
</div>
))}
{oauthEnabled && (
<div className="space-y-3 pl-4 border-l-2 border-border">
<p className="text-xs text-muted-foreground">
Leave fields blank to use the server's default OAuth discovery
</p>
<div>
<Label htmlFor="oauthClientId">Client ID</Label>
<Input
id="oauthClientId"
value={oauthClientId}
onChange={(e) => setOauthClientId(e.target.value)}
placeholder="Optional"
className="bg-background border-border font-mono"
/>
</div>
<div>
<Label htmlFor="oauthClientSecret">Client Secret</Label>
<Input
id="oauthClientSecret"
type="password"
value={oauthClientSecret}
onChange={(e) => setOauthClientSecret(e.target.value)}
placeholder="Optional"
className="bg-background border-border font-mono"
/>
</div>
<div>
<Label htmlFor="oauthScope">Scope</Label>
<Input
id="oauthScope"
value={oauthScope}
onChange={(e) => setOauthScope(e.target.value)}
placeholder="e.g., read write"
className="bg-background border-border font-mono"
/>
</div>
</div>
)}
</div>
)}
{serverType === 'local' && (
<div>
<div className="flex items-center justify-between">
<Label>Environment Variables</Label>
<Button
type="button"
variant="outline"
size="sm"
className='h-6'
onClick={handleAddEnvironmentVar}
>
+
</Button>
</div>
{environment.map((env, index) => (
<div key={index} className="flex gap-2">
<Input
value={env.key}
onChange={(e) => handleUpdateEnvironmentVar(index, 'key', e.target.value)}
placeholder="API_KEY"
className="bg-background border-border font-mono"
/>
<Input
value={env.value}
onChange={(e) => handleUpdateEnvironmentVar(index, 'value', e.target.value)}
placeholder="your-api-key-here"
className="bg-background border-border font-mono"
/>
{environment.length > 1 && (
<Button
type="button"
variant="outline"
size="icon"
onClick={() => handleRemoveEnvironmentVar(index)}
>
x
</Button>
)}
</div>
))}
<p className="text-xs text-muted-foreground">
Environment variables to set when running the MCP server
</p>
</div>
)}
<div>
<Label htmlFor="timeout">Timeout (ms)</Label>
<Input
id="timeout"
value={timeout}
onChange={(e) => setTimeout(e.target.value)}
placeholder="5000"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Environment variables to set when running the MCP server
Timeout in milliseconds for fetching tools (default: 5000)
</p>
</div>
)}
<div>
<Label htmlFor="timeout">Timeout (ms)</Label>
<Input
id="timeout"
value={timeout}
onChange={(e) => setTimeout(e.target.value)}
placeholder="5000"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Timeout in milliseconds for fetching tools (default: 5000)
</p>
</div>
<div className="flex items-center space-x-2">
<Switch
id="enabled"
checked={enabled}
onCheckedChange={setEnabled}
/>
<Label htmlFor="enabled">Connect immediately after adding</Label>
<div className="flex items-center space-x-2">
<Switch
id="enabled"
checked={enabled}
onCheckedChange={setEnabled}
/>
<Label htmlFor="enabled">Connect immediately after adding</Label>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
<DialogFooter className="flex flex-row gap-2 w-full px-4 sm:px-6 pb-4 sm:pb-6 pt-3 shrink-0 border-t border-border gap-2">
<Button variant="outline" onClick={handleClose} className="flex-1">
Cancel
</Button>
<Button
onClick={handleAdd}
disabled={!serverId || isPending}
className="flex-1"
>
{isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Add MCP Server
@@ -233,7 +233,7 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
{...field}
placeholder="The system prompt that defines the agent's behavior and role"
rows={6}
className="font-mono text-sm"
className="font-mono md:text-sm"
/>
</FormControl>
<FormMessage />
@@ -122,7 +122,7 @@ export function AgentsMdEditor() {
<Textarea
value={content}
onChange={(e) => handleContentChange(e.target.value)}
className="font-mono text-sm min-h-[300px] resize-y"
className="font-mono md:text-sm min-h-[300px] resize-y"
placeholder="# Agent Instructions&#10;&#10;Add global instructions for AI agents here..."
/>
@@ -160,7 +160,7 @@ export function CommandDialog({
{...field}
placeholder="The prompt template that will be sent to the LLM. Use $ARGUMENTS or $1, $2, etc. for parameters."
rows={8}
className="font-mono text-sm"
className="font-mono md:text-sm"
/>
</FormControl>
<FormDescription>
@@ -138,7 +138,7 @@ export function CreateConfigDialog({ isOpen, onOpenChange, onCreate, isUpdating
onChange={(e) => handleContentChange(e.target.value)}
placeholder='{"$schema": "https://opencode.ai/config.json", "theme": "dark"}'
rows={12}
className="font-mono text-sm"
className="font-mono md:text-sm"
/>
{error && (
<p className="text-sm text-red-500 mt-2">
@@ -176,7 +176,7 @@ export function KeyboardShortcuts() {
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-sm text-foreground font-mono outline-none"
className="px-3 py-1.5 bg-accent border border-primary rounded text-[16px] md:text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
@@ -218,7 +218,7 @@ export function KeyboardShortcuts() {
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-sm text-foreground font-mono outline-none"
className="px-3 py-1.5 bg-accent border border-primary rounded text-[16px] md:text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
+85 -18
View File
@@ -1,23 +1,17 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Dialog, DialogTrigger } from '@/components/ui/dialog'
import { Plus, Loader2, RefreshCw } from 'lucide-react'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { AddMcpServerDialog } from './AddMcpServerDialog'
import { McpServerCard } from './McpServerCard'
import { McpOAuthDialog } from './McpOAuthDialog'
import { useMcpServers } from '@/hooks/useMcpServers'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
interface McpServerConfig {
type: 'local' | 'remote'
enabled?: boolean
command?: string[]
url?: string
environment?: Record<string, string>
timeout?: number
}
import type { McpServerConfig } from '@/api/mcp'
import { mcpApi } from '@/api/mcp'
import type { McpAuthStartResponse } from '@/api/mcp'
interface McpManagerProps {
config: {
@@ -34,6 +28,8 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
const [deleteConfirmServer, setDeleteConfirmServer] = useState<{ id: string; name: string } | null>(null)
const [togglingServerId, setTogglingServerId] = useState<string | null>(null)
const [authDialogServerId, setAuthDialogServerId] = useState<string | null>(null)
const [removeAuthConfirmServer, setRemoveAuthConfirmServer] = useState<string | null>(null)
const queryClient = useQueryClient()
const {
@@ -43,6 +39,8 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
connect,
disconnect,
authenticate,
removeAuth,
isRemovingAuth,
isToggling
} = useMcpServers()
@@ -74,15 +72,24 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
const handleToggleServer = async (serverId: string) => {
const currentStatus = mcpStatus?.[serverId]
if (!currentStatus) return
const serverConfig = mcpServers[serverId]
const isRemote = serverConfig?.type === 'remote'
const hasOAuthConfig = isRemote && !!serverConfig?.oauth
const hasOAuthError = currentStatus.status === 'failed' && isRemote && /oauth|auth.*state/i.test(currentStatus.error)
const isOAuthServer = hasOAuthConfig || hasOAuthError || (currentStatus.status === 'needs_auth' && isRemote)
if (currentStatus.status === 'needs_auth' || (currentStatus.status === 'failed' && isOAuthServer)) {
setAuthDialogServerId(serverId)
return
}
setTogglingServerId(serverId)
try {
if (currentStatus.status === 'connected') {
await disconnect(serverId)
} else if (currentStatus.status === 'disabled') {
await connect(serverId)
} else if (currentStatus.status === 'needs_auth') {
await authenticate(serverId)
} else if (currentStatus.status === 'failed') {
await connect(serverId)
}
@@ -92,6 +99,40 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
}
}
const handleAuthenticate = (serverId: string) => {
setAuthDialogServerId(serverId)
}
const handleOAuthAutoAuth = async () => {
if (!authDialogServerId) return
await authenticate(authDialogServerId)
refetchStatus()
setAuthDialogServerId(null)
}
const handleOAuthStartAuth = async (): Promise<McpAuthStartResponse> => {
if (!authDialogServerId) throw new Error('No server ID')
return await mcpApi.startAuth(authDialogServerId)
}
const handleOAuthCompleteAuth = async (code: string) => {
if (!authDialogServerId) return
await mcpApi.completeAuth(authDialogServerId, code)
refetchStatus()
setAuthDialogServerId(null)
}
const handleRemoveAuth = (serverId: string) => {
setRemoveAuthConfirmServer(serverId)
}
const handleConfirmRemoveAuth = () => {
if (removeAuthConfirmServer) {
removeAuth(removeAuthConfirmServer)
setRemoveAuthConfirmServer(null)
}
}
const handleDeleteServer = () => {
if (deleteConfirmServer) {
deleteServerMutation.mutate(deleteConfirmServer.id)
@@ -164,13 +205,11 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
</div>
{Object.keys(mcpServers).length === 0 ? (
<Card>
<CardContent className="p-2 sm:p-8 text-center">
<p className="text-muted-foreground">No MCP servers configured. Add your first server to get started.</p>
</CardContent>
</Card>
<div className="rounded-lg border border-border p-6 sm:p-8 text-center">
<p className="text-muted-foreground">No MCP servers configured. Add your first server to get started.</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div className="space-y-2">
{Object.entries(mcpServers).map(([serverId, serverConfig]) => {
const status = mcpStatus?.[serverId]
const isConnected = status?.status === 'connected'
@@ -186,7 +225,10 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
errorMessage={errorMessage}
isAnyOperationPending={isAnyOperationPending}
togglingServerId={togglingServerId}
isRemovingAuth={isRemovingAuth}
onToggleServer={handleToggleServer}
onAuthenticate={handleAuthenticate}
onRemoveAuth={handleRemoveAuth}
onDeleteServer={(id, name) => setDeleteConfirmServer({ id, name })}
/>
)
@@ -204,6 +246,31 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
itemName={deleteConfirmServer?.name}
isDeleting={deleteServerMutation.isPending}
/>
<McpOAuthDialog
open={!!authDialogServerId}
onOpenChange={(open) => !open && setAuthDialogServerId(null)}
serverName={authDialogServerId || ''}
onAutoAuth={handleOAuthAutoAuth}
onStartAuth={handleOAuthStartAuth}
onCompleteAuth={handleOAuthCompleteAuth}
/>
<DeleteDialog
open={!!removeAuthConfirmServer}
onOpenChange={() => setRemoveAuthConfirmServer(null)}
onConfirm={handleConfirmRemoveAuth}
onCancel={() => setRemoveAuthConfirmServer(null)}
title="Remove Authentication"
description="This will remove the OAuth credentials for this MCP server. You will need to re-authenticate to use this server again."
itemName={mcpServers[removeAuthConfirmServer || ''] ? getDisplayName(removeAuthConfirmServer || '') : ''}
isDeleting={isRemovingAuth}
/>
</div>
)
function getDisplayName(serverId: string): string {
const name = serverId.replace(/[-_]/g, ' ')
return name.charAt(0).toUpperCase() + name.slice(1)
}
}
@@ -0,0 +1,266 @@
import { useState } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Loader2, ExternalLink, Key, XCircle } from 'lucide-react'
import type { McpAuthStartResponse } from '@/api/mcp'
interface McpOAuthDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
serverName: string
onAutoAuth: () => Promise<void>
onStartAuth: () => Promise<McpAuthStartResponse>
onCompleteAuth: (code: string) => Promise<void>
directory?: string
}
export function McpOAuthDialog({
open,
onOpenChange,
serverName,
onAutoAuth,
onStartAuth,
onCompleteAuth,
directory
}: McpOAuthDialogProps) {
const [step, setStep] = useState<'method' | 'auto' | 'manual' | 'enter_code'>('method')
const [loading, setLoading] = useState(false)
const [authUrl, setAuthUrl] = useState<string | null>(null)
const [authCode, setAuthCode] = useState('')
const [error, setError] = useState<string | null>(null)
const handleAutoAuth = async () => {
setLoading(true)
setError(null)
setStep('auto')
try {
await onAutoAuth()
onOpenChange(false)
resetState()
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to authenticate')
setStep('method')
} finally {
setLoading(false)
}
}
const handleStartManualAuth = async () => {
setLoading(true)
setError(null)
try {
const result = await onStartAuth()
setAuthUrl(result.authorizationUrl)
setStep('manual')
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to start authentication')
} finally {
setLoading(false)
}
}
const handleCompleteAuth = async () => {
if (!authCode.trim()) return
setLoading(true)
setError(null)
try {
await onCompleteAuth(authCode.trim())
onOpenChange(false)
resetState()
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to complete authentication')
} finally {
setLoading(false)
}
}
const handleOpenAuthUrl = () => {
if (authUrl) {
window.open(authUrl, '_blank')
setStep('enter_code')
}
}
const resetState = () => {
setStep('method')
setAuthUrl(null)
setAuthCode('')
setError(null)
setLoading(false)
}
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
resetState()
}
onOpenChange(newOpen)
}
const scopes = directory ? 'this location' : 'global'
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Key className="h-5 w-5" />
Connect {serverName}
</DialogTitle>
<DialogDescription>
Authenticate to use this MCP server for {scopes}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{error && (
<Alert variant="destructive">
<XCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{step === 'method' && (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">Choose an authentication method:</p>
<div className="flex flex-col gap-2">
<Button
onClick={handleAutoAuth}
disabled={loading}
variant="outline"
className="justify-start h-auto py-3"
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Starting authentication...
</>
) : (
<>
<Loader2 className="h-4 w-4 mr-2" />
<div className="text-left">
<div className="font-medium">Auto (Recommended)</div>
<div className="text-xs text-muted-foreground">
Opens browser, handles redirect automatically
</div>
</div>
</>
)}
</Button>
<Button
onClick={handleStartManualAuth}
disabled={loading}
variant="outline"
className="justify-start h-auto py-3"
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Starting authentication...
</>
) : (
<>
<Key className="h-4 w-4 mr-2" />
<div className="text-left">
<div className="font-medium">Manual with Code</div>
<div className="text-xs text-muted-foreground">
Open URL, then paste the authorization code
</div>
</div>
</>
)}
</Button>
</div>
</div>
)}
{step === 'auto' && (
<div className="flex items-center justify-center py-8">
<div className="flex flex-col items-center gap-3">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">
Waiting for browser authorization...
</p>
</div>
</div>
)}
{step === 'manual' && authUrl && (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
Open the authorization link in your browser to begin the flow. Then paste the code below.
</p>
<Button
onClick={handleOpenAuthUrl}
className="w-full"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open Auth Page
</Button>
<div className="text-xs text-muted-foreground break-all bg-muted p-2 rounded">
{authUrl}
</div>
</div>
)}
{step === 'enter_code' && (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
Paste the authorization code from the browser:
</p>
<div className="space-y-2">
<Label htmlFor="auth-code">Authorization Code</Label>
<Input
id="auth-code"
value={authCode}
onChange={(e) => setAuthCode(e.target.value)}
placeholder="Paste code here..."
disabled={loading}
/>
</div>
</div>
)}
</div>
<DialogFooter>
{step === 'enter_code' && (
<>
<Button
variant="outline"
onClick={() => setStep('method')}
disabled={loading}
>
Back
</Button>
<Button
onClick={handleCompleteAuth}
disabled={loading || !authCode.trim()}
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Authenticating...
</>
) : (
'Complete Authentication'
)}
</Button>
</>
)}
{(step === 'method' || step === 'manual') && (
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={loading}
>
Cancel
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,18 +1,10 @@
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { Button } from '@/components/ui/button'
import { Trash2, XCircle, AlertCircle, Key } from 'lucide-react'
import type { McpStatus } from '@/api/mcp'
interface McpServerConfig {
type: 'local' | 'remote'
enabled?: boolean
command?: string[]
url?: string
environment?: Record<string, string>
timeout?: number
}
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
import { XCircle, AlertCircle, Key, MoreVertical, Shield, Trash2, RefreshCw } from 'lucide-react'
import type { McpStatus, McpServerConfig } from '@/api/mcp'
interface McpServerCardProps {
serverId: string
@@ -22,7 +14,10 @@ interface McpServerCardProps {
errorMessage: string | null
isAnyOperationPending: boolean
togglingServerId: string | null
isRemovingAuth: boolean
onToggleServer: (serverId: string) => void
onAuthenticate?: (serverId: string) => void
onRemoveAuth?: (serverId: string) => void
onDeleteServer: (serverId: string, serverName: string) => void
}
@@ -91,55 +86,103 @@ export function McpServerCard({
errorMessage,
isAnyOperationPending,
togglingServerId,
isRemovingAuth,
onToggleServer,
onAuthenticate,
onRemoveAuth,
onDeleteServer
}: McpServerCardProps) {
const needsAuth = status?.status === 'needs_auth'
const isRemote = serverConfig.type === 'remote'
const hasOAuthConfig = isRemote && !!serverConfig.oauth
const hasOAuthError = status?.status === 'failed' && isRemote && /oauth|auth.*state/i.test(status.error)
const isOAuthServer = hasOAuthConfig || hasOAuthError || (needsAuth && isRemote)
const connectedWithOAuth = isOAuthServer && isConnected
const showAuthButton = needsAuth || (isOAuthServer && status?.status === 'failed')
const displayName = getServerDisplayName(serverId)
return (
<Card key={serverId} className={errorMessage ? 'border-red-500/50' : ''}>
<CardHeader className="pb-3">
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg">{getServerDisplayName(serverId)}</CardTitle>
<div className="flex items-center gap-2">
{status ? getStatusBadge(status) : (
<Badge variant="outline" className="text-xs">Loading...</Badge>
)}
</div>
<div className={`flex items-center justify-between gap-3 p-3 rounded-lg border bg-card ${errorMessage ? 'border-red-500/50' : 'border-border'}`}>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-0.5">
<p className="text-sm font-medium truncate">{displayName}</p>
{connectedWithOAuth && (
<span title="OAuth authenticated">
<Shield className="h-3 w-3 text-muted-foreground" />
</span>
)}
{status ? getStatusBadge(status) : (
<Badge variant="outline" className="text-xs">Loading...</Badge>
)}
</div>
<p className="text-xs text-muted-foreground truncate">
{getServerDescription(serverConfig)}
</p>
{errorMessage && (
<div className="flex items-start gap-1.5 mt-1.5 text-xs text-red-500">
<XCircle className="h-3 w-3 flex-shrink-0 mt-0.5" />
<span className="break-words line-clamp-2">{errorMessage}</span>
</div>
<div className="flex items-center gap-2">
<Switch
checked={isConnected}
onCheckedChange={() => onToggleServer(serverId)}
disabled={isAnyOperationPending || togglingServerId === serverId}
/>
<Button
variant="ghost"
size="sm"
onClick={() => onDeleteServer(serverId, getServerDisplayName(serverId))}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{showAuthButton && onAuthenticate ? (
<Button
onClick={() => onAuthenticate(serverId)}
disabled={isAnyOperationPending || togglingServerId === serverId}
variant="default"
size="sm"
>
<Key className="h-3 w-3 mr-1" />
Auth
</Button>
) : (
<Switch
checked={isConnected}
onCheckedChange={() => onToggleServer(serverId)}
disabled={isAnyOperationPending || togglingServerId === serverId}
/>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent className='p-2'>
<div className="text-sm text-muted-foreground space-y-1">
<p>{getServerDescription(serverConfig)}</p>
{serverConfig.timeout && (
<p>Timeout: {serverConfig.timeout}ms</p>
)}
{serverConfig.environment && Object.keys(serverConfig.environment).length > 0 && (
<p>Environment variables: {Object.keys(serverConfig.environment).length} configured</p>
)}
{errorMessage && (
<div className="flex items-start gap-2 mt-2 p-2 bg-red-500/10 rounded text-red-600 text-xs">
<XCircle className="h-4 w-4 flex-shrink-0 mt-0.5" />
<span className="break-words">{errorMessage}</span>
</div>
)}
</div>
</CardContent>
</Card>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{showAuthButton && onAuthenticate && (
<DropdownMenuItem onClick={() => onAuthenticate(serverId)}>
<Key className="h-4 w-4 mr-2" />
Authenticate
</DropdownMenuItem>
)}
{connectedWithOAuth && onAuthenticate && (
<DropdownMenuItem onClick={() => onAuthenticate(serverId)}>
<RefreshCw className="h-4 w-4 mr-2" />
Re-authenticate
</DropdownMenuItem>
)}
{connectedWithOAuth && onRemoveAuth && (
<DropdownMenuItem
onClick={() => onRemoveAuth(serverId)}
disabled={isRemovingAuth}
>
<Shield className="h-4 w-4 mr-2" />
{isRemovingAuth ? 'Removing...' : 'Remove Auth'}
</DropdownMenuItem>
)}
{(showAuthButton || connectedWithOAuth) && <DropdownMenuSeparator />}
<DropdownMenuItem
onClick={() => onDeleteServer(serverId, displayName)}
className="text-red-600"
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Server
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)
}
@@ -87,7 +87,7 @@ export function OpenCodeConfigEditor({
setEditError('')
setEditErrorLine(null)
}}
className="flex-1 font-mono text-xs sm:text-sm resize-none h-full rounded-none sm:rounded-md"
className="flex-1 font-mono text-[16px] sm:text-xs md:text-sm resize-none h-full rounded-none sm:rounded-md"
/>
{editError && (
<div className="absolute bottom-0 left-0 right-0 bg-background/95 border-t p-2 sm:p-3">
@@ -353,7 +353,7 @@ export function ProviderSettings() {
placeholder="Search providers..."
value={availableSearch}
onChange={(e) => setAvailableSearch(e.target.value)}
className="pl-9 text-sm"
className="pl-9 md:text-sm"
/>
</div>
@@ -262,7 +262,7 @@ export function STTSettings() {
<input
type="text"
placeholder="https://api.openai.com"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] md:text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
{...field}
/>
</FormControl>
@@ -285,7 +285,7 @@ export function STTSettings() {
<input
type={showApiKey ? 'text' : 'password'}
placeholder="sk-..."
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-[16px] md:text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
{...field}
/>
<button
@@ -132,7 +132,7 @@ export function BranchesTab({ repoId, currentBranch, repoUrl, isRepoWorktree }:
placeholder="New branch name..."
value={newBranchName}
onChange={(e) => setNewBranchName(e.target.value)}
className="h-8 text-sm"
className="h-8 md:text-sm"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreateBranch()
@@ -128,7 +128,7 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: Cha
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] text-sm resize-none"
className="min-h-[80px] md:text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
@@ -211,7 +211,7 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: Cha
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] text-sm resize-none"
className="min-h-[80px] md:text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
+1 -1
View File
@@ -173,7 +173,7 @@ export function Combobox({
placeholder={placeholder}
disabled={disabled}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors',
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-[16px] md:text-sm shadow-sm transition-colors',
'file:border-0 file:bg-transparent file:text-sm file:font-medium',
'placeholder:text-muted-foreground',
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
@@ -111,7 +111,7 @@ const VirtualizedLine = memo(function VirtualizedLine({
type="text"
value={content}
onChange={(e) => onLineChange(lineNum, e.target.value)}
className={`flex-1 bg-transparent outline-none pl-2 ${
className={`flex-1 bg-transparent outline-none pl-2 text-[16px] md:text-sm ${
isEdited ? 'bg-yellow-500/10' : ''
} ${
lineWrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre'
@@ -145,27 +145,19 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
onContentLoaded,
}, ref) {
const containerRef = useRef<HTMLDivElement>(null)
const scrollTopRef = useRef(0)
const [renderTrigger, setRenderTrigger] = useState(0)
const [scrollTop, setScrollTop] = useState(0)
const [viewportHeight, setViewportHeight] = useState(600)
const [containerWidth, setContainerWidth] = useState(0)
const [highlightedLine, setHighlightedLine] = useState<number | undefined>(initialLineNumber)
const loadedBufferRef = useRef<{ start: number; end: number }>({ start: 0, end: 0 })
const heightCacheRef = useRef<Map<number, number>>(new Map())
const lineOffsetsRef = useRef<{ offsets: Map<number, { height: number; top: number }>; totalHeight: number } | null>(null)
const lastContainerWidthRef = useRef(0)
const lastTotalLinesRef = useRef(0)
const lastVisibleRangeRef = useRef<{ start: number; end: number }>({ start: 0, end: 0 })
const currentVisibleRangeRef = useRef<{ start: number; end: number }>({ start: 0, end: 200 })
const scrollRafRef = useRef<number | null>(null)
const isMobile = useMobile()
void renderTrigger
const chunkSize = isMobile && lineWrap ? 800 : 400
const chunkSize = isMobile && lineWrap ? 1500 : 1000
const overscan = isMobile && lineWrap ? 200 : 100
const bufferMultiplier = 4
const preRenderMultiplier = 3
const {
lines,
@@ -201,7 +193,6 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
}, [isFullyLoaded, fullContent, onContentLoaded])
useEffect(() => {
loadedBufferRef.current = { start: 0, end: 0 }
heightCacheRef.current.clear()
lineOffsetsRef.current = null
}, [filePath])
@@ -275,14 +266,15 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
return result
}, [lineWrap, containerWidth, totalLines, lines, editedLines, lineHeight])
const totalHeight = lineOffsets?.totalHeight ?? totalLines * lineHeight
const displayLineCount = totalLines > 0 ? totalLines : chunkSize
const totalHeight = lineOffsets?.totalHeight ?? displayLineCount * lineHeight
const lineOffsetsForCalcRef = useRef(lineOffsets)
lineOffsetsForCalcRef.current = lineOffsets
const calculateVisibleRange = useCallback((scrollTop: number) => {
const currentLineOffsets = lineOffsetsForCalcRef.current
if (currentLineOffsets) {
if (currentLineOffsets && totalLines > 0) {
const searchTop = scrollTop - overscan * lineHeight
const searchBottom = scrollTop + viewportHeight + overscan * lineHeight
@@ -327,66 +319,26 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
}, [viewportHeight, lineHeight, getVisibleRange, totalLines, overscan])
const visibleRange = useMemo(() => {
const range = calculateVisibleRange(scrollTopRef.current)
currentVisibleRangeRef.current = range
return range
}, [calculateVisibleRange])
return calculateVisibleRange(scrollTop)
}, [calculateVisibleRange, scrollTop])
useEffect(() => {
const { start, end } = visibleRange
const buffer = loadedBufferRef.current
const visibleCount = end - start
const desiredBuffer = visibleCount * bufferMultiplier
const needsLoadBefore = start < buffer.start + visibleCount
const needsLoadAfter = end > buffer.end - visibleCount
if (needsLoadBefore || needsLoadAfter || buffer.start === 0 && buffer.end === 0) {
const newStart = Math.max(0, start - desiredBuffer)
const newEnd = Math.min(totalLines, end + desiredBuffer)
loadedBufferRef.current = { start: newStart, end: newEnd }
loadRange(newStart, newEnd)
}
}, [visibleRange, loadRange, totalLines, bufferMultiplier])
const lastRenderTimeRef = useRef(0)
const pendingRenderRef = useRef(false)
const RENDER_THROTTLE_MS = 32
if (start >= end) return
loadRange(start, end)
}, [visibleRange, loadRange])
const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
const newScrollTop = e.currentTarget.scrollTop
scrollTopRef.current = newScrollTop
if (scrollRafRef.current) {
cancelAnimationFrame(scrollRafRef.current)
}
scrollRafRef.current = requestAnimationFrame(() => {
const newRange = calculateVisibleRange(newScrollTop)
const currentRange = currentVisibleRangeRef.current
const rangeChanged = newRange.start !== currentRange.start || newRange.end !== currentRange.end
if (!rangeChanged) return
currentVisibleRangeRef.current = newRange
const now = performance.now()
const timeSinceLastRender = now - lastRenderTimeRef.current
if (timeSinceLastRender >= RENDER_THROTTLE_MS) {
lastRenderTimeRef.current = now
setRenderTrigger(t => t + 1)
} else if (!pendingRenderRef.current) {
pendingRenderRef.current = true
setTimeout(() => {
pendingRenderRef.current = false
lastRenderTimeRef.current = performance.now()
setRenderTrigger(t => t + 1)
}, RENDER_THROTTLE_MS - timeSinceLastRender)
}
setScrollTop(newScrollTop)
})
}, [calculateVisibleRange])
}, [])
const handleLineChange = useCallback((lineNum: number, value: string) => {
setLineContent(lineNum, value)
@@ -396,8 +348,8 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
try {
await saveEdits()
onSave?.()
} catch (err) {
console.error('Failed to save:', err)
} catch {
void 0
}
}, [saveEdits, onSave])
@@ -433,25 +385,9 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
const visibleLines = useMemo(() => {
const result: Array<{ lineNum: number; content: string; isEdited: boolean; height: number; top: number; isLoaded: boolean }> = []
const upperBound = totalLines > 0 ? totalLines : visibleRange.end
const lastRange = lastVisibleRangeRef.current
const visibleCount = visibleRange.end - visibleRange.start
const maxExpansion = visibleCount * preRenderMultiplier
const expandedStart = Math.max(
0,
visibleRange.start - maxExpansion,
Math.min(visibleRange.start, lastRange.start)
)
const expandedEnd = Math.min(
totalLines,
visibleRange.end + maxExpansion,
Math.max(visibleRange.end, lastRange.end)
)
lastVisibleRangeRef.current = visibleRange
for (let i = expandedStart; i < expandedEnd; i++) {
for (let i = visibleRange.start; i < Math.min(visibleRange.end, upperBound); i++) {
const editedContent = editedLines.get(i)
const lineData = lines.get(i)
const isLoaded = lineData?.loaded === true || editedContent !== undefined
@@ -472,7 +408,7 @@ export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, Virtual
}
return result
}, [visibleRange, lines, editedLines, lineOffsets, lineHeight, totalLines, preRenderMultiplier])
}, [visibleRange, lines, editedLines, lineOffsets, lineHeight, totalLines])
if (error) {
return (
+100 -138
View File
@@ -1,4 +1,5 @@
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import { useState, useCallback, useMemo } from 'react'
import { useInfiniteQuery } from '@tanstack/react-query'
import { fetchFileRange, applyFilePatches } from '@/api/files'
import type { PatchOperation } from '@/types/files'
@@ -20,7 +21,7 @@ interface UseVirtualizedContentReturn {
totalLines: number
isLoading: boolean
error: Error | null
loadRange: (startLine: number, endLine: number) => Promise<void>
loadRange: (startLine: number, endLine: number) => void
getVisibleRange: (scrollTop: number, viewportHeight: number, lineHeight: number) => { start: number; end: number }
editedLines: Map<number, string>
setLineContent: (lineNumber: number, content: string) => void
@@ -40,101 +41,67 @@ export function useVirtualizedContent({
chunkSize = 200,
overscan = 50,
enabled = true,
initialTotalLines = 0,
}: UseVirtualizedContentOptions): UseVirtualizedContentReturn {
const [lines, setLines] = useState<Map<number, LineData>>(new Map())
const [totalLines, setTotalLines] = useState(initialTotalLines)
const [isLoading, setIsLoading] = useState(false)
const [isSaving, setIsSaving] = useState(false)
const [error, setError] = useState<Error | null>(null)
const [editedLines, setEditedLines] = useState<Map<number, string>>(new Map())
const loadingRanges = useRef<Set<string>>(new Set())
const loadedRanges = useRef<Array<{ start: number; end: number }>>([])
const isRangeLoaded = useCallback((start: number, end: number): boolean => {
for (const range of loadedRanges.current) {
if (range.start <= start && range.end >= end) {
return true
}
}
return false
}, [])
const mergeRanges = useCallback(() => {
if (loadedRanges.current.length <= 1) return
loadedRanges.current.sort((a, b) => a.start - b.start)
const merged: Array<{ start: number; end: number }> = []
let current = loadedRanges.current[0]
for (let i = 1; i < loadedRanges.current.length; i++) {
const next = loadedRanges.current[i]
if (next.start <= current.end + 1) {
current = { start: current.start, end: Math.max(current.end, next.end) }
} else {
merged.push(current)
current = next
}
}
merged.push(current)
loadedRanges.current = merged
}, [])
const loadRange = useCallback(async (startLine: number, endLine: number) => {
if (!enabled || !filePath) return
const rangeKey = `${startLine}-${endLine}`
if (loadingRanges.current.has(rangeKey)) return
if (isRangeLoaded(startLine, endLine)) return
loadingRanges.current.add(rangeKey)
setIsLoading(true)
setError(null)
try {
const result = await fetchFileRange(filePath, startLine, endLine)
setTotalLines(result.totalLines)
setLines(prev => {
const next = new Map(prev)
result.lines.forEach((content, idx) => {
const lineNum = result.startLine + idx
next.set(lineNum, { content, loaded: true })
})
return next
const [isSaving, setIsSaving] = useState(false)
const [saveError, setSaveError] = useState<Error | null>(null)
const {
data,
isLoading,
error: queryError,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['file-range', filePath],
queryFn: async ({ pageParam }) => {
const result = await fetchFileRange(filePath, pageParam, pageParam + chunkSize)
return result
},
initialPageParam: 0,
getNextPageParam: (lastPage) => {
if (!lastPage.hasMore) return undefined
return lastPage.endLine
},
enabled: enabled && !!filePath,
staleTime: 30_000,
refetchOnWindowFocus: false,
})
const totalLines = data?.pages[0]?.totalLines ?? 0
const lines = useMemo(() => {
const map = new Map<number, LineData>()
if (!data?.pages) return map
for (const page of data.pages) {
page.lines.forEach((content, idx) => {
map.set(page.startLine + idx, { content, loaded: true })
})
loadedRanges.current.push({ start: result.startLine, end: result.endLine })
mergeRanges()
} catch (err) {
setError(err instanceof Error ? err : new Error('Failed to load file range'))
} finally {
loadingRanges.current.delete(rangeKey)
setIsLoading(false)
}
}, [enabled, filePath, isRangeLoaded, mergeRanges])
const prefetchAdjacent = useCallback((visibleStart: number, visibleEnd: number) => {
const prefetchBefore = Math.max(0, visibleStart - chunkSize)
const prefetchAfter = Math.min(totalLines, visibleEnd + chunkSize)
if (!isRangeLoaded(prefetchBefore, visibleStart) && prefetchBefore < visibleStart) {
loadRange(prefetchBefore, visibleStart)
return map
}, [data?.pages])
const loadedEndLine = useMemo(() => {
if (!data?.pages?.length) return 0
return Math.max(...data.pages.map(p => p.endLine))
}, [data?.pages])
const loadRange = useCallback((_startLine: number, endLine: number) => {
if (endLine > loadedEndLine && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
if (!isRangeLoaded(visibleEnd, prefetchAfter) && prefetchAfter > visibleEnd) {
loadRange(visibleEnd, prefetchAfter)
}
}, [chunkSize, totalLines, isRangeLoaded, loadRange])
}, [loadedEndLine, hasNextPage, isFetchingNextPage, fetchNextPage])
const getVisibleRange = useCallback((scrollTop: number, viewportHeight: number, lineHeight: number) => {
const start = Math.max(0, Math.floor(scrollTop / lineHeight) - overscan)
const visibleCount = Math.ceil(viewportHeight / lineHeight)
const end = Math.min(totalLines, start + visibleCount + overscan * 2)
const upperBound = totalLines > 0 ? totalLines : start + visibleCount + overscan * 2
const end = Math.min(upperBound, start + visibleCount + overscan * 2)
return { start, end }
}, [totalLines, overscan])
const setLineContent = useCallback((lineNumber: number, content: string) => {
setEditedLines(prev => {
const next = new Map(prev)
@@ -142,21 +109,21 @@ export function useVirtualizedContent({
return next
})
}, [])
const clearEdits = useCallback(() => {
setEditedLines(new Map())
}, [])
const getDirtyRanges = useCallback((): Array<{ startLine: number; endLine: number; content: string }> => {
if (editedLines.size === 0) return []
const sortedLineNums = Array.from(editedLines.keys()).sort((a, b) => a - b)
const ranges: Array<{ startLine: number; endLine: number; content: string }> = []
let rangeStart = sortedLineNums[0]
let rangeLines: string[] = [editedLines.get(rangeStart)!]
let lastLine = rangeStart
for (let i = 1; i < sortedLineNums.length; i++) {
const lineNum = sortedLineNums[i]
if (lineNum === lastLine + 1) {
@@ -173,22 +140,22 @@ export function useVirtualizedContent({
lastLine = lineNum
}
}
ranges.push({
startLine: rangeStart,
endLine: lastLine + 1,
content: rangeLines.join('\n'),
})
return ranges
}, [editedLines])
const saveEdits = useCallback(async () => {
if (editedLines.size === 0) return
setIsSaving(true)
setError(null)
setSaveError(null)
try {
const dirtyRanges = getDirtyRanges()
const patches: PatchOperation[] = dirtyRanges.map(range => ({
@@ -197,67 +164,62 @@ export function useVirtualizedContent({
endLine: range.endLine,
content: range.content,
}))
const result = await applyFilePatches(filePath, patches)
if (result.success) {
setTotalLines(result.totalLines)
setLines(prev => {
const next = new Map(prev)
editedLines.forEach((content, lineNum) => {
next.set(lineNum, { content, loaded: true })
})
return next
})
clearEdits()
}
} catch (err) {
setError(err instanceof Error ? err : new Error('Failed to save edits'))
throw err
const error = err instanceof Error ? err : new Error('Failed to save edits')
setSaveError(error)
throw error
} finally {
setIsSaving(false)
}
}, [filePath, editedLines, getDirtyRanges, clearEdits])
useEffect(() => {
if (enabled && filePath && totalLines === 0) {
loadRange(0, chunkSize)
const prefetchAdjacent = useCallback((_visibleStart: number, visibleEnd: number) => {
if (visibleEnd >= loadedEndLine - chunkSize && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [enabled, filePath, totalLines, chunkSize, loadRange])
useEffect(() => {
setLines(new Map())
setEditedLines(new Map())
setTotalLines(initialTotalLines)
loadedRanges.current = []
loadingRanges.current.clear()
}, [filePath, initialTotalLines])
const hasUnsavedChanges = editedLines.size > 0
}, [loadedEndLine, chunkSize, hasNextPage, isFetchingNextPage, fetchNextPage])
const loadAll = useCallback(async () => {
if (!enabled || !filePath || totalLines === 0) return
if (isRangeLoaded(0, totalLines)) return
await loadRange(0, totalLines)
}, [enabled, filePath, totalLines, isRangeLoaded, loadRange])
if (loadedEndLine >= totalLines) return
let safety = 0
const maxIterations = Math.ceil(totalLines / chunkSize) + 1
while (safety < maxIterations) {
const result = await fetchNextPage()
const pages = result.data?.pages
if (!pages?.length) break
const lastPage = pages[pages.length - 1]
if (!lastPage.hasMore || lastPage.endLine >= totalLines) break
safety++
}
}, [enabled, filePath, totalLines, loadedEndLine, chunkSize, fetchNextPage])
const isFullyLoaded = useMemo(() => {
if (totalLines === 0) return false
return isRangeLoaded(0, totalLines)
}, [totalLines, isRangeLoaded])
return loadedEndLine >= totalLines
}, [totalLines, loadedEndLine])
const fullContent = useMemo(() => {
if (!isFullyLoaded || totalLines === 0) return null
const result: string[] = []
for (let i = 0; i < totalLines; i++) {
const editedContent = editedLines.get(i)
const lineData = lines.get(i)
result.push(lineData?.content ?? '')
result.push(editedContent ?? lineData?.content ?? '')
}
return result.join('\n')
}, [isFullyLoaded, totalLines, lines])
}, [isFullyLoaded, totalLines, lines, editedLines])
const hasUnsavedChanges = editedLines.size > 0
const error = queryError ?? saveError
return {
lines,
totalLines,