mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(frontend): improve model selection experience (#237)
* chore: remove dead code and unused exports * fix: preserve model form during config refresh Signed-off-by: mehmet turac <mehmetturac@gmail.com> * loop: model-select-fix completed after 11 iterations * fix(frontend): show provider prefix for duplicate models in quick select dropdown When the same model exists under multiple providers, show the provider name for both entries so users can distinguish them. Detects duplicates by modelID across all favorites and recents. * refactor(frontend): replace useTallScrollContent with scroll visibility hook * fix: harden mirror push rollback * Remove Load button from skill cards, clicking card loads skill * feat(backend): add plugin installation support and schema updates * refactor(frontend): remove unused useHeaderScrollVisibility hook * refactor(frontend): replace model dropdown with bottom sheet selector Replace DropdownMenu-based ModelQuickSelect with a bottom sheet implementation featuring favorites, recents, provider browsing, and search. Remove onShowModelsDialog prop from PromptInput and SessionDetail, using data attribute trigger instead. Fix ZodIssueCode deprecation, input text color, and portal rendering for bottom sheet. * fix(frontend): simplify session model restore and fix mobile swipe reset * loop: single-source-models completed after 10 iterations * refactor(frontend): add desktop sidebar layout to model quick select * refactor(frontend): improve model selector with connected providers, favorites, and recent management * fix(frontend): constrain model name width to prevent overflow in prompt input * fix(frontend): adjust padding and styling in model quick select * fix(frontend): add optimistic removal with rollback for recent models ---------
This commit is contained in:
1 parent
f492faa84b
commit
03bd3dac95
45 files changed
+1728
-1148
No files matched your search
@@ -1,93 +0,0 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog'
|
||||
import { FilePreview } from './FilePreview'
|
||||
import { Loader2, FileText } from 'lucide-react'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
|
||||
interface FilePreviewDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
filePath: string
|
||||
repoBasePath?: string
|
||||
onFileSaved?: () => void
|
||||
initialLineNumber?: number
|
||||
}
|
||||
|
||||
export function FilePreviewDialog({ isOpen, onClose, filePath, repoBasePath, onFileSaved, initialLineNumber }: FilePreviewDialogProps) {
|
||||
const [file, setFile] = useState<FileInfo | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !filePath) {
|
||||
setFile(null)
|
||||
setError(null)
|
||||
return
|
||||
}
|
||||
|
||||
const fetchFile = async () => {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const fullPath = repoBasePath ? `${repoBasePath}/${filePath}` : filePath
|
||||
const response = await fetch(`${API_BASE_URL}/api/files/${fullPath}`)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load file: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
setFile(data)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load file')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
fetchFile()
|
||||
}, [isOpen, filePath, repoBasePath])
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent
|
||||
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col"
|
||||
hideCloseButton
|
||||
fullscreen
|
||||
mobileSwipeToClose
|
||||
>
|
||||
<div className="flex-1 overflow-hidden min-h-0">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
|
||||
<FileText className="w-8 h-8 mb-2 opacity-50" />
|
||||
<p className="text-sm">Failed to load file</p>
|
||||
<p className="text-xs mt-1">{error}</p>
|
||||
</div>
|
||||
) : file ? (
|
||||
<FilePreview
|
||||
key={file.path}
|
||||
file={file}
|
||||
hideHeader={false}
|
||||
isMobileModal={true}
|
||||
onCloseModal={onClose}
|
||||
onFileSaved={onFileSaved}
|
||||
initialLineNumber={initialLineNumber}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
interface FileSuggestionsProps {
|
||||
isOpen: boolean
|
||||
files: string[]
|
||||
onSelect: (file: string) => void
|
||||
onClose: () => void
|
||||
selectedIndex?: number
|
||||
}
|
||||
|
||||
export function FileSuggestions({
|
||||
isOpen,
|
||||
files,
|
||||
onSelect,
|
||||
onClose,
|
||||
selectedIndex = 0
|
||||
}: FileSuggestionsProps) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (listRef.current && !listRef.current.contains(e.target as Node)) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [isOpen, onClose])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !listRef.current) return
|
||||
|
||||
const selectedItem = listRef.current.children[selectedIndex] as HTMLElement
|
||||
if (selectedItem) {
|
||||
selectedItem.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
}, [selectedIndex, isOpen])
|
||||
|
||||
if (!isOpen || files.length === 0) return null
|
||||
|
||||
const getFilename = (path: string) => path.split('/').pop() || path
|
||||
const getDirectory = (path: string) => {
|
||||
const parts = path.split('/')
|
||||
return parts.slice(0, -1).join('/') || '.'
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={listRef}
|
||||
className="absolute bottom-full left-0 right-0 mb-2 z-50 bg-background border border-border rounded-lg shadow-xl max-h-48 md:max-h-[40vh] lg:max-h-[50vh] overflow-y-auto"
|
||||
>
|
||||
{files.map((file, idx) => (
|
||||
<button
|
||||
key={file}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onTouchEnd={(e) => {
|
||||
e.preventDefault()
|
||||
onSelect(file)
|
||||
}}
|
||||
onClick={() => onSelect(file)}
|
||||
className={`w-full px-3 py-2 text-left transition-colors ${
|
||||
idx === selectedIndex
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'hover:bg-muted text-foreground'
|
||||
}`}
|
||||
>
|
||||
<div className="font-mono text-sm font-medium">
|
||||
{getFilename(file)}
|
||||
</div>
|
||||
<div className="text-xs opacity-70 mt-0.5">
|
||||
{getDirectory(file)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { memo } from 'react'
|
||||
import { X, Loader2 } from 'lucide-react'
|
||||
import { useRemoveMessage } from '@/hooks/useRemoveMessage'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
|
||||
interface MessageActionButtonsProps {
|
||||
opcodeUrl: string
|
||||
sessionId: string
|
||||
directory?: string
|
||||
message: MessageWithParts
|
||||
}
|
||||
|
||||
export const MessageActionButtons = memo(function MessageActionButtons({
|
||||
opcodeUrl,
|
||||
sessionId,
|
||||
directory,
|
||||
message
|
||||
}: MessageActionButtonsProps) {
|
||||
const isMobile = useMobile()
|
||||
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
|
||||
|
||||
const handleRemove = () => {
|
||||
if (removeMessage.isPending) return
|
||||
removeMessage.mutate({ messageID: message.info.id })
|
||||
}
|
||||
|
||||
if (message.info.role !== 'assistant') {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`flex items-center gap-1 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<button
|
||||
onClick={handleRemove}
|
||||
disabled={removeMessage.isPending}
|
||||
className="p-1 rounded hover:bg-destructive/20 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
|
||||
title="Remove this message and all after it"
|
||||
>
|
||||
{removeMessage.isPending ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<X className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -77,10 +77,6 @@ vi.mock('@/stores/sessionAgentStore', () => ({
|
||||
useSessionAgentStore: mocks.useSessionAgentStore,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useAgents', () => ({
|
||||
useAgents: mocks.useAgents,
|
||||
}))
|
||||
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePermissions: () => ({
|
||||
hasForSession: vi.fn().mockReturnValue(false),
|
||||
@@ -399,7 +395,7 @@ describe('PromptInput STT Gesture Tests', () => {
|
||||
expect(voiceButtons.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('does NOT render mobile in-row ArrowDown button', async () => {
|
||||
it('renders mobile in-row Latest button when showScrollButton is true', async () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
|
||||
render(
|
||||
@@ -408,7 +404,8 @@ describe('PromptInput STT Gesture Tests', () => {
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
expect(screen.queryByTitle('Scroll to bottom')).not.toBeInTheDocument()
|
||||
expect(screen.getByTitle('Scroll to bottom')).toBeInTheDocument()
|
||||
expect(screen.getByText('Latest')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -67,9 +67,8 @@ interface PromptInputProps {
|
||||
showScrollButton?: boolean
|
||||
isSessionActive?: boolean
|
||||
isStreamingResponse?: boolean
|
||||
onScrollToBottom?: () => void
|
||||
onScrollToBottom: () => void
|
||||
onShowSessionsDialog?: () => void
|
||||
onShowModelsDialog?: () => void
|
||||
onShowHelpDialog?: () => void
|
||||
onToggleDetails?: () => boolean
|
||||
onExportSession?: () => void
|
||||
@@ -86,7 +85,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
isStreamingResponse = false,
|
||||
onScrollToBottom,
|
||||
onShowSessionsDialog,
|
||||
onShowModelsDialog,
|
||||
onShowHelpDialog,
|
||||
onToggleDetails,
|
||||
onExportSession,
|
||||
@@ -182,7 +180,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
sessionID,
|
||||
directory,
|
||||
onShowSessionsDialog,
|
||||
onShowModelsDialog,
|
||||
onShowModelsDialog: undefined,
|
||||
onShowHelpDialog,
|
||||
onToggleDetails,
|
||||
onExportSession,
|
||||
@@ -994,7 +992,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
staleTime: 30000,
|
||||
})
|
||||
|
||||
const { model, modelString, setModel: setStoredModel, setActiveModel } = useModelSelection(opcodeUrl, directory)
|
||||
const { model, modelString, setModel: setStoredModel, restoreSessionModel } = useModelSelection(opcodeUrl, directory)
|
||||
const setStoreVariant = useModelStore((state) => state.setVariant)
|
||||
const clearStoreVariant = useModelStore((state) => state.clearVariant)
|
||||
|
||||
@@ -1005,8 +1003,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
if (syncedSessionModelRef.current === sessionModelSyncKey) return
|
||||
if (!sessionAgent.model) return
|
||||
|
||||
const restored = setActiveModel(sessionAgent.model)
|
||||
if (!restored) return
|
||||
restoreSessionModel(sessionAgent.model)
|
||||
|
||||
syncedSessionModelRef.current = sessionModelSyncKey
|
||||
|
||||
@@ -1015,7 +1012,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
} else {
|
||||
clearStoreVariant(sessionAgent.model)
|
||||
}
|
||||
}, [clearStoreVariant, sessionAgent.model, sessionAgent.variant, sessionModelSyncKey, setActiveModel, setStoreVariant])
|
||||
}, [clearStoreVariant, sessionAgent.model, sessionAgent.variant, sessionModelSyncKey, restoreSessionModel, setStoreVariant])
|
||||
|
||||
const currentModel = modelString || ''
|
||||
const displayModelName = useMemo(() => {
|
||||
@@ -1034,6 +1031,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory)
|
||||
const showStopButton = isSessionActive
|
||||
const hideSecondaryButtons = isMobile && isSessionActive
|
||||
const showMobileScrollButton = isMobile && showScrollButton
|
||||
const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording
|
||||
? 'starting'
|
||||
: isProcessing
|
||||
@@ -1211,27 +1209,39 @@ return (
|
||||
|
||||
<div className="flex gap-1.5 md:gap-2 items-center justify-between">
|
||||
<div className="flex gap-1.5 md:gap-2 items-center min-w-0">
|
||||
<AgentQuickSelect
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={directory}
|
||||
currentAgent={currentMode}
|
||||
onAgentChange={handleAgentChange}
|
||||
isBashMode={isBashMode}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{showMobileScrollButton ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onScrollToBottom}
|
||||
className="flex items-center gap-1.5 px-3 min-h-[36px] rounded-lg text-xs font-medium border bg-zinc-950/80 hover:bg-zinc-900/90 text-blue-300 hover:text-blue-200 border-blue-400/20 shadow-md backdrop-blur-md transition-all duration-200 active:scale-95 ring-1 ring-blue-400/15"
|
||||
title="Scroll to bottom"
|
||||
aria-label="Scroll to bottom"
|
||||
>
|
||||
<ArrowDown className="w-4 h-4" />
|
||||
<span>Latest</span>
|
||||
</button>
|
||||
) : (
|
||||
<AgentQuickSelect
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={directory}
|
||||
currentAgent={currentMode}
|
||||
onAgentChange={handleAgentChange}
|
||||
isBashMode={isBashMode}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
{isSessionActive ? (
|
||||
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
|
||||
<SessionStatusIndicator sessionID={sessionID} showLabel />
|
||||
</div>
|
||||
) : (
|
||||
!hideSecondaryButtons && (
|
||||
<ModelQuickSelect
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={directory}
|
||||
onOpenFullDialog={() => onShowModelsDialog?.()}
|
||||
>
|
||||
!hideSecondaryButtons && !showMobileScrollButton && (
|
||||
<ModelQuickSelect
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={directory}
|
||||
>
|
||||
<button
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer w-full md:w-auto md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer w-full md:w-auto max-w-[130px] md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
>
|
||||
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
|
||||
{hasVariants && currentVariant && (
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Lock, AlertCircle } from 'lucide-react'
|
||||
|
||||
interface PassphraseModalProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (passphrase: string) => void
|
||||
credentialName?: string
|
||||
}
|
||||
|
||||
export function PassphraseModal({ open, onOpenChange, onSubmit, credentialName = 'SSH key' }: PassphraseModalProps) {
|
||||
const [passphrase, setPassphrase] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setPassphrase('')
|
||||
setError(null)
|
||||
setTimeout(() => inputRef.current?.focus(), 100)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!passphrase.trim()) {
|
||||
setError('Passphrase is required')
|
||||
return
|
||||
}
|
||||
|
||||
onSubmit(passphrase)
|
||||
setPassphrase('')
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[90%] sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Lock className="h-5 w-5" />
|
||||
SSH Key Passphrase Required
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter the passphrase for your <span className="font-medium">{credentialName}</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="passphrase">Passphrase</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="passphrase"
|
||||
type="password"
|
||||
ref={inputRef}
|
||||
value={passphrase}
|
||||
onChange={(e) => {
|
||||
setPassphrase(e.target.value)
|
||||
setError(null)
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter your passphrase"
|
||||
className={error ? 'border-destructive' : ''}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm text-destructive flex items-center gap-1">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This passphrase is NOT stored and will be required each time you access this SSH key.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={!passphrase.trim()}>
|
||||
Submit
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,34 +1,61 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { Check, ChevronRight, Star } from 'lucide-react'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { Check, ChevronLeft, ChevronRight, Clock, MoreVertical, Search, Star, Trash2, X } from 'lucide-react'
|
||||
import { useModelSelection } from '@/hooks/useModelSelection'
|
||||
import { useVariants } from '@/hooks/useVariants'
|
||||
import { formatModelName, formatProviderName, getProviders } from '@/api/providers'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useOpenCodeClient } from '@/hooks/useOpenCode'
|
||||
import { BottomSheet } from '@/components/ui/bottom-sheet'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { Model, Provider } from '@/api/providers'
|
||||
|
||||
interface ModelQuickSelectProps {
|
||||
opcodeUrl: string | null | undefined
|
||||
directory?: string
|
||||
onOpenFullDialog: () => void
|
||||
disabled?: boolean
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
interface ModelListItem {
|
||||
providerID: string
|
||||
modelID: string
|
||||
key: string
|
||||
displayName: string
|
||||
providerName: string
|
||||
model?: Model
|
||||
}
|
||||
|
||||
interface ModelSection {
|
||||
title: string
|
||||
icon: React.ReactNode
|
||||
models: ModelListItem[]
|
||||
}
|
||||
|
||||
interface ProviderListItem {
|
||||
id: string
|
||||
label: string
|
||||
count: number
|
||||
isConnected: boolean
|
||||
}
|
||||
|
||||
export function ModelQuickSelect({
|
||||
opcodeUrl,
|
||||
directory,
|
||||
onOpenFullDialog,
|
||||
disabled,
|
||||
children,
|
||||
}: ModelQuickSelectProps) {
|
||||
const { model, modelString, recentModels, favoriteModels, setModel, toggleFavorite } = useModelSelection(opcodeUrl, directory)
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [showAllModels, setShowAllModels] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
|
||||
const { model, modelString, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(opcodeUrl, directory)
|
||||
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(opcodeUrl, directory)
|
||||
const client = useOpenCodeClient(opcodeUrl, directory)
|
||||
|
||||
@@ -51,17 +78,26 @@ export function ModelQuickSelect({
|
||||
return provider ? formatProviderName(provider) : providerID
|
||||
}, [providersData])
|
||||
|
||||
const getModelData = useCallback((providerID: string, modelID: string) => {
|
||||
return providersData?.providers
|
||||
.find(provider => provider.id === providerID)
|
||||
?.models?.[modelID]
|
||||
}, [providersData])
|
||||
|
||||
const toModelListItem = useCallback((selection: { providerID: string, modelID: string }): ModelListItem => ({
|
||||
...selection,
|
||||
displayName: getDisplayName(selection.providerID, selection.modelID),
|
||||
providerName: getProviderName(selection.providerID),
|
||||
key: `${selection.providerID}/${selection.modelID}`,
|
||||
model: getModelData(selection.providerID, selection.modelID),
|
||||
}), [getDisplayName, getModelData, getProviderName])
|
||||
|
||||
const favoriteModelsWithNames = useMemo(() => {
|
||||
return favoriteModels
|
||||
.filter(favorite => `${favorite.providerID}/${favorite.modelID}` !== modelString)
|
||||
.slice(0, 5)
|
||||
.map(favorite => ({
|
||||
...favorite,
|
||||
displayName: getDisplayName(favorite.providerID, favorite.modelID),
|
||||
providerName: getProviderName(favorite.providerID),
|
||||
key: `${favorite.providerID}/${favorite.modelID}`,
|
||||
}))
|
||||
}, [favoriteModels, getDisplayName, getProviderName, modelString])
|
||||
.map(toModelListItem)
|
||||
}, [favoriteModels, modelString, toModelListItem])
|
||||
|
||||
const recentModelsWithNames = useMemo(() => {
|
||||
return recentModels
|
||||
@@ -70,152 +106,452 @@ export function ModelQuickSelect({
|
||||
return key !== modelString && !favoriteModels.some(favorite => favorite.providerID === recent.providerID && favorite.modelID === recent.modelID)
|
||||
})
|
||||
.slice(0, 5)
|
||||
.map(recent => ({
|
||||
...recent,
|
||||
displayName: getDisplayName(recent.providerID, recent.modelID),
|
||||
providerName: getProviderName(recent.providerID),
|
||||
key: `${recent.providerID}/${recent.modelID}`,
|
||||
}))
|
||||
}, [recentModels, favoriteModels, getDisplayName, getProviderName, modelString])
|
||||
.map(toModelListItem)
|
||||
}, [recentModels, favoriteModels, modelString, toModelListItem])
|
||||
|
||||
const duplicateDisplayNames = useMemo(() => {
|
||||
const counts = [...favoriteModelsWithNames, ...recentModelsWithNames].reduce<Record<string, number>>((acc, item) => {
|
||||
acc[item.displayName] = (acc[item.displayName] || 0) + 1
|
||||
return acc
|
||||
}, {})
|
||||
const allModels = useMemo((): ModelListItem[] => {
|
||||
return providersData?.providers.flatMap((provider: Provider) => Object.entries(provider.models || {}).map(([modelID, providerModel]) => ({
|
||||
providerID: provider.id,
|
||||
modelID,
|
||||
key: `${provider.id}/${modelID}`,
|
||||
displayName: formatModelName(providerModel),
|
||||
providerName: formatProviderName(provider),
|
||||
model: providerModel,
|
||||
}))) || []
|
||||
}, [providersData])
|
||||
|
||||
return new Set(Object.entries(counts).filter(([, count]) => count > 1).map(([name]) => name))
|
||||
}, [favoriteModelsWithNames, recentModelsWithNames])
|
||||
const quickModels = useMemo(() => {
|
||||
const items = [
|
||||
...(model ? [toModelListItem(model)] : []),
|
||||
...favoriteModelsWithNames,
|
||||
...recentModelsWithNames,
|
||||
...allModels,
|
||||
]
|
||||
|
||||
const duplicateModelIds = useMemo(() => {
|
||||
const counts = [...favoriteModelsWithNames, ...recentModelsWithNames].reduce<Record<string, number>>((acc, item) => {
|
||||
acc[item.modelID] = (acc[item.modelID] || 0) + 1
|
||||
return acc
|
||||
}, {})
|
||||
return items.filter((item, index, list) => list.findIndex(candidate => candidate.key === item.key) === index).slice(0, 3)
|
||||
}, [allModels, favoriteModelsWithNames, model, recentModelsWithNames, toModelListItem])
|
||||
|
||||
return new Set(Object.entries(counts).filter(([, count]) => count > 1).map(([id]) => id))
|
||||
}, [favoriteModelsWithNames, recentModelsWithNames])
|
||||
const quickSections = useMemo((): ModelSection[] => {
|
||||
const sections: ModelSection[] = []
|
||||
|
||||
const handleVariantSelect = (variant: string | undefined) => {
|
||||
if (variant === undefined) {
|
||||
clearVariant()
|
||||
} else {
|
||||
setVariant(variant)
|
||||
if (favoriteModelsWithNames.length > 0) {
|
||||
sections.push({
|
||||
title: 'Favorites',
|
||||
icon: <Star className="h-3.5 w-3.5" />,
|
||||
models: favoriteModelsWithNames,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (recentModelsWithNames.length > 0) {
|
||||
sections.push({
|
||||
title: 'Recent',
|
||||
icon: <Clock className="h-3.5 w-3.5" />,
|
||||
models: recentModelsWithNames,
|
||||
})
|
||||
}
|
||||
|
||||
if (sections.length === 0 && quickModels.length > 0) {
|
||||
sections.push({
|
||||
title: 'Models',
|
||||
icon: <ChevronRight className="h-3.5 w-3.5" />,
|
||||
models: quickModels,
|
||||
})
|
||||
}
|
||||
|
||||
return sections
|
||||
}, [favoriteModelsWithNames, quickModels, recentModelsWithNames])
|
||||
|
||||
const selectedProviderModels = useMemo(() => {
|
||||
if (!selectedProviderId) return []
|
||||
|
||||
return allModels.filter(item => item.providerID === selectedProviderId)
|
||||
}, [allModels, selectedProviderId])
|
||||
|
||||
const filteredSelectedProviderModels = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return selectedProviderModels
|
||||
|
||||
return selectedProviderModels.filter(item =>
|
||||
item.displayName.toLowerCase().includes(query) ||
|
||||
item.modelID.toLowerCase().includes(query)
|
||||
)
|
||||
}, [searchQuery, selectedProviderModels])
|
||||
|
||||
const providerItems = useMemo((): ProviderListItem[] => {
|
||||
return providersData?.providers
|
||||
.map(provider => ({
|
||||
id: provider.id,
|
||||
label: formatProviderName(provider),
|
||||
count: Object.keys(provider.models || {}).length,
|
||||
isConnected: provider.isConnected ?? false,
|
||||
}))
|
||||
.filter(provider => provider.count > 0)
|
||||
.sort((a, b) => {
|
||||
if (a.isConnected !== b.isConnected) {
|
||||
return a.isConnected ? -1 : 1
|
||||
}
|
||||
return a.label.localeCompare(b.label)
|
||||
}) || []
|
||||
}, [providersData])
|
||||
|
||||
const filteredAllModels = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
const items = selectedProviderId
|
||||
? allModels.filter(item => item.providerID === selectedProviderId)
|
||||
: allModels
|
||||
|
||||
if (!query) return items
|
||||
|
||||
return items.filter(item =>
|
||||
item.displayName.toLowerCase().includes(query) ||
|
||||
item.modelID.toLowerCase().includes(query)
|
||||
)
|
||||
}, [allModels, selectedProviderId, searchQuery])
|
||||
|
||||
const filteredProviderItems = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return providerItems
|
||||
|
||||
return providerItems.filter(provider =>
|
||||
provider.label.toLowerCase().includes(query) ||
|
||||
provider.id.toLowerCase().includes(query)
|
||||
)
|
||||
}, [providerItems, searchQuery])
|
||||
|
||||
const connectedProviderItems = useMemo(
|
||||
() => filteredProviderItems.filter(p => p.isConnected),
|
||||
[filteredProviderItems]
|
||||
)
|
||||
|
||||
const availableProviderItems = useMemo(
|
||||
() => filteredProviderItems.filter(p => !p.isConnected),
|
||||
[filteredProviderItems]
|
||||
)
|
||||
|
||||
const handleModelSelect = (providerID: string, modelID: string) => {
|
||||
setModel({ providerID, modelID })
|
||||
setIsOpen(false)
|
||||
}
|
||||
|
||||
const handleCurrentFavoriteToggle = () => {
|
||||
if (!model) return
|
||||
toggleFavorite(model)
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
setIsOpen(open)
|
||||
if (!open) {
|
||||
setShowAllModels(false)
|
||||
setSearchQuery('')
|
||||
setSelectedProviderId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const currentModelDisplayName = model ? getDisplayName(model.providerID, model.modelID) : ''
|
||||
const currentProviderName = model ? getProviderName(model.providerID) : ''
|
||||
const isCurrentFavorite = model
|
||||
? favoriteModels.some((favorite) => favorite.providerID === model.providerID && favorite.modelID === model.modelID)
|
||||
: false
|
||||
const hasFavorites = favoriteModelsWithNames.length > 0
|
||||
const hasRecents = recentModelsWithNames.length > 0
|
||||
const handleProviderSelect = (providerID: string) => {
|
||||
setSelectedProviderId(providerID)
|
||||
setSearchQuery('')
|
||||
}
|
||||
|
||||
const getDescription = (item: ModelListItem) => {
|
||||
const context = item.model?.limit?.context
|
||||
if (context) {
|
||||
const formattedContext = context >= 1000000 ? `${(context / 1000000).toFixed(1)}M` : context.toLocaleString()
|
||||
return `${item.providerName} · ${formattedContext} context`
|
||||
}
|
||||
|
||||
return item.providerName
|
||||
}
|
||||
|
||||
const getPrimaryLabel = (item: ModelListItem) => item.displayName || item.modelID
|
||||
|
||||
const renderModelOption = (item: ModelListItem) => {
|
||||
const isSelected = modelString === item.key
|
||||
const isFavorite = favoriteModels.some(favorite => favorite.providerID === item.providerID && favorite.modelID === item.modelID)
|
||||
const isRecent = recentModels.some(recent => recent.providerID === item.providerID && recent.modelID === item.modelID)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-white/5 ${isSelected ? 'bg-orange-500/10' : ''}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleModelSelect(item.providerID, item.modelID)}
|
||||
className="min-w-0 flex-1 px-2 text-left"
|
||||
>
|
||||
<span className="block truncate text-sm font-medium text-white">
|
||||
{getPrimaryLabel(item)}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-xs text-white/50">
|
||||
{getDescription(item)}
|
||||
</span>
|
||||
</button>
|
||||
{isRecent && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
removeRecentModel({ providerID: item.providerID, modelID: item.modelID })
|
||||
}}
|
||||
className="rounded-full p-1.5 text-white/30 hover:bg-white/10 hover:text-white/70"
|
||||
aria-label="Remove from recent"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-red-400" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
toggleFavorite({ providerID: item.providerID, modelID: item.modelID })
|
||||
}}
|
||||
className="rounded-full p-1.5 text-white/50 transition-opacity hover:bg-white/10 hover:text-white"
|
||||
aria-label={isFavorite ? 'Remove from favorites' : 'Add to favorites'}
|
||||
>
|
||||
<Star className={`h-4 w-4 ${isFavorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />
|
||||
</button>
|
||||
{isSelected && <Check className="h-5 w-5 shrink-0 pr-2 text-orange-500" />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const selectedModelItem = model ? toModelListItem(model) : null
|
||||
|
||||
const renderProviderOption = (provider: ProviderListItem) => {
|
||||
return (
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
onClick={() => handleProviderSelect(provider.id)}
|
||||
className="flex w-full items-center gap-3 rounded-xl py-2.5 text-left transition-colors hover:bg-white/5"
|
||||
>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium text-white">{provider.label}</span>
|
||||
<span className="mt-0.5 block truncate text-xs text-white/50">{provider.count} {provider.count === 1 ? 'model' : 'models'}</span>
|
||||
</span>
|
||||
<ChevronRight className="h-5 w-5 shrink-0 text-white/40" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
const renderVariantMenuItems = () => {
|
||||
if (!hasVariants) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuLabel>Variant</DropdownMenuLabel>
|
||||
<DropdownMenuItem onClick={() => clearVariant()} className={!currentVariant ? 'text-orange-500' : ''}>
|
||||
Default
|
||||
{!currentVariant && <Check className="ml-auto h-4 w-4" />}
|
||||
</DropdownMenuItem>
|
||||
{availableVariants.map(variant => (
|
||||
<DropdownMenuItem key={variant} onClick={() => setVariant(variant)} className={currentVariant === variant ? 'text-orange-500' : ''}>
|
||||
<span className="capitalize">{variant}</span>
|
||||
{currentVariant === variant && <Check className="ml-auto h-4 w-4" />}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const handleMoreModelsBack = () => {
|
||||
if (selectedProviderId) {
|
||||
setSelectedProviderId(null)
|
||||
setSearchQuery('')
|
||||
return
|
||||
}
|
||||
|
||||
setShowAllModels(false)
|
||||
}
|
||||
|
||||
const selectedModelLabel = selectedModelItem ? getPrimaryLabel(selectedModelItem) : 'Select model'
|
||||
const selectedModelDescription = selectedModelItem ? getDescription(selectedModelItem) : 'Choose a model'
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild disabled={disabled}>
|
||||
<>
|
||||
<span onClick={() => !disabled && handleOpenChange(true)} data-model-select-trigger>
|
||||
{children}
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-56">
|
||||
{model && (
|
||||
<>
|
||||
<DropdownMenuItem className="flex items-center justify-between font-medium">
|
||||
<span className="truncate text-orange-500">
|
||||
{duplicateModelIds.has(model.modelID) || duplicateDisplayNames.has(currentModelDisplayName)
|
||||
? `${currentProviderName}/${currentModelDisplayName}`
|
||||
: currentModelDisplayName}
|
||||
</span>
|
||||
<Check className="h-4 w-4 text-orange-500" />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={handleCurrentFavoriteToggle}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>{isCurrentFavorite ? 'Remove from favorites' : 'Add to favorites'}</span>
|
||||
<Star className={`h-4 w-4 ${isCurrentFavorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{hasVariants && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleVariantSelect(undefined)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>Default</span>
|
||||
{!currentVariant && <Check className="h-4 w-4" />}
|
||||
</DropdownMenuItem>
|
||||
{availableVariants.map((variant) => (
|
||||
<DropdownMenuItem
|
||||
key={variant}
|
||||
onClick={() => handleVariantSelect(variant)}
|
||||
className="flex items-center justify-between"
|
||||
</span>
|
||||
<BottomSheet
|
||||
isOpen={isOpen}
|
||||
onClose={() => handleOpenChange(false)}
|
||||
heightClass="h-[70dvh] max-h-[720px]"
|
||||
className="z-[300] border-white/10 bg-zinc-950 text-white shadow-2xl"
|
||||
ariaLabel="Select model"
|
||||
>
|
||||
<div className={`flex items-center justify-between gap-2 px-4 ${showAllModels ? 'pb-2 pt-2' : 'pb-3 pt-0'}`}>
|
||||
{showAllModels ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleMoreModelsBack}
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/5 text-white/80 hover:bg-white/10"
|
||||
aria-label="Back to quick models"
|
||||
>
|
||||
<span className="capitalize text-orange-500 text-center">{variant}</span>
|
||||
{currentVariant === variant && <Check className="h-4 w-4" />}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{hasFavorites && (
|
||||
<>
|
||||
{favoriteModelsWithNames.map((favorite) => (
|
||||
<DropdownMenuItem
|
||||
key={favorite.key}
|
||||
onClick={() => handleModelSelect(favorite.providerID, favorite.modelID)}
|
||||
className="flex items-center justify-between"
|
||||
<ChevronLeft className="h-5 w-5" />
|
||||
</button>
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/40" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder={selectedProviderId ? 'Search models...' : 'Search providers...'}
|
||||
className="h-9 border-white/10 bg-white/5 pl-9 text-sm text-white placeholder:text-white/40"
|
||||
autoComplete="off"
|
||||
name="model-search"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full border border-white/10 bg-white/5 text-white/80 hover:bg-white/10"
|
||||
aria-label="Close model selector"
|
||||
>
|
||||
<span className="truncate">
|
||||
{duplicateModelIds.has(favorite.modelID) || duplicateDisplayNames.has(favorite.displayName)
|
||||
? `${favorite.providerName}/${favorite.displayName}`
|
||||
: favorite.displayName}
|
||||
</span>
|
||||
{modelString === favorite.key && <Check className="h-4 w-4" />}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
<div className="min-w-0 flex-1 px-3 text-center">
|
||||
<h2 className="truncate text-base font-semibold tracking-tight">{selectedModelLabel}</h2>
|
||||
<p className="truncate text-xs text-white/45">
|
||||
{currentVariant ? `${selectedModelDescription} · ${currentVariant}` : selectedModelDescription}
|
||||
</p>
|
||||
</div>
|
||||
{hasVariants && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!model && !hasVariants}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full text-white/70 hover:bg-white/10 disabled:opacity-30"
|
||||
aria-label="Model actions"
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="z-[350] min-w-56">
|
||||
{renderVariantMenuItems()}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hasRecents && (
|
||||
<>
|
||||
{recentModelsWithNames.map((recent) => (
|
||||
<DropdownMenuItem
|
||||
key={recent.key}
|
||||
onClick={() => handleModelSelect(recent.providerID, recent.modelID)}
|
||||
className="flex items-center justify-between"
|
||||
{showAllModels ? (
|
||||
<div className="flex-1 flex overflow-hidden min-h-0">
|
||||
{/* Provider sidebar — desktop only */}
|
||||
<div className="hidden md:flex md:flex-col w-48 lg:w-56 border-r border-white/10 overflow-y-auto flex-shrink-0">
|
||||
<div className="p-3 space-y-1">
|
||||
{connectedProviderItems.length > 0 && (
|
||||
<>
|
||||
<p className="px-3 pb-1 text-xs font-medium text-white/45">Connected</p>
|
||||
{connectedProviderItems.map(provider => (
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
onClick={() => handleProviderSelect(provider.id)}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
selectedProviderId === provider.id
|
||||
? 'bg-orange-500/20 text-orange-300 font-medium'
|
||||
: 'text-white/70 hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
<div className="truncate">{provider.label}</div>
|
||||
<div className="text-xs text-white/40">{provider.count} {provider.count === 1 ? 'model' : 'models'}</div>
|
||||
</button>
|
||||
))}
|
||||
{availableProviderItems.length > 0 && <div className="mx-3 my-1 h-px bg-white/10" />}
|
||||
</>
|
||||
)}
|
||||
{availableProviderItems.length > 0 && (
|
||||
<>
|
||||
<p className="px-3 pb-1 text-xs font-medium text-white/45">Available</p>
|
||||
{availableProviderItems.map(provider => (
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
onClick={() => handleProviderSelect(provider.id)}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
selectedProviderId === provider.id
|
||||
? 'bg-orange-500/20 text-orange-300 font-medium'
|
||||
: 'text-white/70 hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
<div className="truncate">{provider.label}</div>
|
||||
<div className="text-xs text-white/40">{provider.count} {provider.count === 1 ? 'model' : 'models'}</div>
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right panel */}
|
||||
<div className="flex-1 flex flex-col overflow-hidden min-w-0">
|
||||
{/* Desktop: model grid */}
|
||||
<div className="hidden md:block flex-1 overflow-y-auto px-4 pb-4 pt-2">
|
||||
<div className="space-y-1">{filteredAllModels.map(renderModelOption)}</div>
|
||||
{filteredAllModels.length === 0 && (
|
||||
<div className="py-10 text-center text-sm text-white/50">No models found</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Mobile: current single-column navigation */}
|
||||
<div className="md:hidden flex-1 overflow-y-auto px-4 pb-4">
|
||||
<div className="space-y-1">
|
||||
{selectedProviderId
|
||||
? filteredSelectedProviderModels.map(renderModelOption)
|
||||
: <>
|
||||
{connectedProviderItems.length > 0 && (
|
||||
<>
|
||||
<p className="px-1 pb-1 text-xs font-medium text-white/45">Connected</p>
|
||||
{connectedProviderItems.map(renderProviderOption)}
|
||||
{availableProviderItems.length > 0 && <div className="-mx-4 my-2 h-px bg-white/10" />}
|
||||
</>
|
||||
)}
|
||||
{availableProviderItems.length > 0 && (
|
||||
<>
|
||||
<p className="px-1 pb-1 text-xs font-medium text-white/45">Available</p>
|
||||
{availableProviderItems.map(renderProviderOption)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
</div>
|
||||
{selectedProviderId && filteredSelectedProviderModels.length === 0 && (
|
||||
<div className="py-10 text-center text-sm text-white/50">No models found</div>
|
||||
)}
|
||||
{!selectedProviderId && filteredProviderItems.length === 0 && (
|
||||
<div className="py-10 text-center text-sm text-white/50">No providers found</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
|
||||
{quickSections.map(section => (
|
||||
<section key={section.title}>
|
||||
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-white/45">
|
||||
{section.icon}
|
||||
{section.title}
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{section.models.map(renderModelOption)}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex-shrink-0 border-t border-white/10">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAllModels(true)}
|
||||
className="flex w-full items-center justify-between bg-card px-6 py-4 text-left text-sm font-semibold text-white transition-colors hover:bg-accent active:bg-card"
|
||||
>
|
||||
<span className="truncate">
|
||||
{duplicateModelIds.has(recent.modelID) || duplicateDisplayNames.has(recent.displayName)
|
||||
? `${recent.providerName}/${recent.displayName}`
|
||||
: recent.displayName}
|
||||
</span>
|
||||
{modelString === recent.key && <Check className="h-4 w-4" />}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</>
|
||||
<span>More models</span>
|
||||
<ChevronRight className="h-5 w-5 text-white/50" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onOpenFullDialog}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>All Models...</span>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -149,7 +149,7 @@ describe('RepoSkillsDialog', () => {
|
||||
})
|
||||
|
||||
describe('load functionality', () => {
|
||||
it('shows Load button when sessionId and opcodeUrl are provided', async () => {
|
||||
it('makes skill cards clickable when sessionId and opcodeUrl are provided', async () => {
|
||||
mocks.listManagedSkills.mockResolvedValue(mockSkills)
|
||||
mocks.sendCommand.mockResolvedValue(undefined)
|
||||
|
||||
@@ -173,10 +173,11 @@ describe('RepoSkillsDialog', () => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(screen.getByText('Load')).toBeInTheDocument()
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')
|
||||
expect(card).toBeTruthy()
|
||||
})
|
||||
|
||||
it('does not show Load button when sessionId is not provided', async () => {
|
||||
it('does not make skill cards clickable when sessionId is not provided', async () => {
|
||||
mocks.listManagedSkills.mockResolvedValue(mockSkills)
|
||||
|
||||
render(
|
||||
@@ -192,10 +193,11 @@ describe('RepoSkillsDialog', () => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(screen.queryByText('Load')).not.toBeInTheDocument()
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')
|
||||
expect(card).toBeNull()
|
||||
})
|
||||
|
||||
it('calls sendCommand and closes dialog on Load click', async () => {
|
||||
it('calls sendCommand and closes dialog on card click', async () => {
|
||||
mocks.listManagedSkills.mockResolvedValue(mockSkills)
|
||||
mocks.sendCommand.mockReturnValue(new Promise(() => {}))
|
||||
|
||||
@@ -220,8 +222,8 @@ describe('RepoSkillsDialog', () => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const loadButton = screen.getByText('Load')
|
||||
await user.click(loadButton)
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')!
|
||||
await user.click(card)
|
||||
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||
expect(onSkillLoaded).toHaveBeenCalledWith(mockSkills[0])
|
||||
@@ -255,8 +257,8 @@ describe('RepoSkillsDialog', () => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const loadButton = screen.getByText('Load')
|
||||
await user.click(loadButton)
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')!
|
||||
await user.click(card)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(showToast.error).toHaveBeenCalledWith('Failed to load')
|
||||
|
||||
@@ -60,8 +60,8 @@ export function RepoSkillsList({
|
||||
{data.map((skill) => (
|
||||
<div
|
||||
key={skill.name}
|
||||
onClick={() => onLoad?.(skill)}
|
||||
className={`p-2 rounded-lg border border-border bg-card flex items-center justify-between gap-2 ${onLoad ? 'cursor-pointer hover:bg-accent transition-colors' : ''}`}
|
||||
onClick={onLoad ? () => onLoad(skill) : undefined}
|
||||
className={`p-2 rounded-lg border border-border bg-card flex items-center gap-2 ${onLoad ? 'cursor-pointer hover:bg-accent transition-colors' : ''}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate text-orange-600 dark:text-orange-400">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useCallback, useEffect, useMemo } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -78,7 +78,7 @@ function jsonObjectField(label: string) {
|
||||
if (!value.trim()) return
|
||||
if (!parseJsonObject(value)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
code: 'custom',
|
||||
message: `${label} must be a valid JSON object`,
|
||||
})
|
||||
}
|
||||
@@ -114,19 +114,19 @@ const modelFormSchema = z.object({
|
||||
}).superRefine((data, ctx) => {
|
||||
if (data.createNewProvider) {
|
||||
if (!data.newProviderId?.trim()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Provider ID is required when creating a new provider', path: ['newProviderId'] })
|
||||
ctx.addIssue({ code: 'custom', message: 'Provider ID is required when creating a new provider', path: ['newProviderId'] })
|
||||
} else if (!/^[a-z0-9-]+$/.test(data.newProviderId)) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Must be lowercase letters, numbers, and hyphens only', path: ['newProviderId'] })
|
||||
ctx.addIssue({ code: 'custom', message: 'Must be lowercase letters, numbers, and hyphens only', path: ['newProviderId'] })
|
||||
}
|
||||
if (data.newProviderType === 'api' && !data.newProviderBaseUrl?.trim()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Base URL is required for API providers', path: ['newProviderBaseUrl'] })
|
||||
ctx.addIssue({ code: 'custom', message: 'Base URL is required for API providers', path: ['newProviderBaseUrl'] })
|
||||
}
|
||||
if (data.newProviderType === 'npm' && !data.newProviderNpm?.trim()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'NPM package is required for npm providers', path: ['newProviderNpm'] })
|
||||
ctx.addIssue({ code: 'custom', message: 'NPM package is required for npm providers', path: ['newProviderNpm'] })
|
||||
}
|
||||
} else {
|
||||
if (!data.providerId?.trim()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Provider is required', path: ['providerId'] })
|
||||
ctx.addIssue({ code: 'custom', message: 'Provider is required', path: ['providerId'] })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ const modelFormSchema = z.object({
|
||||
] as const) {
|
||||
const value = data[field]
|
||||
if (value.trim() && parseOptionalNumber(value) === undefined) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} must be a number`, path: [field] })
|
||||
ctx.addIssue({ code: 'custom', message: `${label} must be a number`, path: [field] })
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -248,13 +248,23 @@ export function OpenCodeModelDialog({
|
||||
const { isValid } = form.formState
|
||||
const createNewProvider = form.watch('createNewProvider')
|
||||
const newProviderType = form.watch('newProviderType')
|
||||
const resetKeyRef = useRef<string | null>(null)
|
||||
const resetKey = editingModel
|
||||
? `edit-${editingModel.providerId}-${editingModel.modelId}`
|
||||
: `create-${selectedProviderId || availableProviders[0] || ''}`
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (!open) {
|
||||
resetKeyRef.current = null
|
||||
return
|
||||
}
|
||||
|
||||
if (resetKeyRef.current !== resetKey) {
|
||||
resetKeyRef.current = resetKey
|
||||
form.reset(getDefaultValues())
|
||||
void form.trigger()
|
||||
}
|
||||
}, [open, form, getDefaultValues])
|
||||
}, [open, resetKey, form, getDefaultValues])
|
||||
|
||||
const handleSubmit = (values: ModelFormValues) => {
|
||||
const extra = parseOptionalJsonField(values.extraJson)
|
||||
|
||||
@@ -172,6 +172,29 @@ describe('OpenCodeModelDialog', () => {
|
||||
expect(screen.getByText(/must use only letters, numbers/i)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('should preserve create form values when provider props refresh', async () => {
|
||||
const { OpenCodeModelDialog } = await import('./OpenCodeModelDialog')
|
||||
const props = {
|
||||
...defaultProps,
|
||||
availableProviders: ['openai'],
|
||||
existingProviders: { openai: { name: 'OpenAI' } },
|
||||
}
|
||||
const { rerender } = render(<OpenCodeModelDialog {...props} />)
|
||||
|
||||
const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement
|
||||
fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } })
|
||||
|
||||
rerender(
|
||||
<OpenCodeModelDialog
|
||||
{...props}
|
||||
availableProviders={['openai']}
|
||||
existingProviders={{ openai: { name: 'OpenAI' } }}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(modelIdInput).toHaveValue('gpt-5')
|
||||
})
|
||||
})
|
||||
|
||||
describe('form submission', () => {
|
||||
|
||||
@@ -101,8 +101,13 @@ export function ProviderSettings() {
|
||||
|
||||
const oauthProviders = useMemo(() => {
|
||||
if (!providers || !authMethods) return []
|
||||
return providers.filter(provider => supportsOAuth(provider.id))
|
||||
}, [providers, authMethods, supportsOAuth])
|
||||
const oauth = providers.filter(provider => supportsOAuth(provider.id))
|
||||
return oauth.slice().sort((a, b) => {
|
||||
const aConnected = hasCredentials(a.id) ? 1 : 0
|
||||
const bConnected = hasCredentials(b.id) ? 1 : 0
|
||||
return bConnected - aConnected
|
||||
})
|
||||
}, [providers, authMethods, supportsOAuth, hasCredentials])
|
||||
|
||||
const apiKeyProviders = useMemo(() => {
|
||||
if (!providers || !authMethods) return { connected: [], available: [] }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
@@ -61,9 +62,9 @@ export function BottomSheet({
|
||||
|
||||
if (!isOpen && !shouldRender) return null
|
||||
|
||||
return (
|
||||
const sheet = (
|
||||
<div
|
||||
className="fixed inset-0 z-[60]"
|
||||
className="fixed inset-0 z-[250]"
|
||||
style={{
|
||||
opacity: isOpen ? 1 : 0,
|
||||
pointerEvents: isOpen ? 'auto' : 'none',
|
||||
@@ -94,6 +95,10 @@ export function BottomSheet({
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
if (typeof document === 'undefined') return sheet
|
||||
|
||||
return createPortal(sheet, document.body)
|
||||
}
|
||||
|
||||
export interface BottomSheetHeaderProps {
|
||||
|
||||
@@ -141,7 +141,7 @@ describe("DialogContent", () => {
|
||||
const content = screen.getByTestId("dialog-content");
|
||||
expect(content).toHaveClass("custom-class");
|
||||
expect(content).toHaveClass("fixed");
|
||||
expect(content).toHaveClass("z-50");
|
||||
expect(content).toHaveClass("z-[70]");
|
||||
});
|
||||
|
||||
it("renders children correctly", () => {
|
||||
|
||||
@@ -8,7 +8,7 @@ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] text-foreground file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
Reference in new issue
Block a user