mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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
@@ -9,7 +9,7 @@
|
||||
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "pnpm run test:bun && pnpm run test:vitest",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal/repo-mirror.test.ts src/db/model-state.test.ts src/routes/providers.test.ts",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts src/db/model-state.test.ts src/routes/providers.test.ts",
|
||||
"test:vitest": "vitest run",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:watch": "vitest --watch",
|
||||
@@ -23,7 +23,6 @@
|
||||
"archiver": "^7.0.1",
|
||||
"better-auth": "^1.4.17",
|
||||
"croner": "^10.0.1",
|
||||
"dotenv": "^17.2.3",
|
||||
"eventsource": "^4.1.0",
|
||||
"hono": "^4.11.7",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
|
||||
@@ -81,6 +81,30 @@ export function addRecentOpenCodeModel(
|
||||
return insertMany()
|
||||
}
|
||||
|
||||
export function removeRecentOpenCodeModel(
|
||||
db: Database,
|
||||
model: ModelSelectionRecord,
|
||||
userId = 'default',
|
||||
): OpenCodeModelStateRecord {
|
||||
const remove = db.transaction(() => {
|
||||
const current = getOpenCodeModelState(db, userId)
|
||||
const updated = current.recent.filter(
|
||||
m => m.providerID !== model.providerID || m.modelID !== model.modelID,
|
||||
)
|
||||
const now = Date.now()
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET recent=excluded.recent, updated_at=excluded.updated_at
|
||||
`).run(userId, JSON.stringify(updated), JSON.stringify(current.favorite), JSON.stringify(current.variant), now)
|
||||
|
||||
return { recent: updated, favorite: current.favorite, variant: current.variant }
|
||||
})
|
||||
|
||||
return remove()
|
||||
}
|
||||
|
||||
export function toggleFavoriteOpenCodeModel(
|
||||
db: Database,
|
||||
model: ModelSelectionRecord,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { spawn } from 'child_process'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { Readable } from 'stream'
|
||||
import { mkdtempSync, mkdirSync, readdirSync, statSync, existsSync, writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { dirname, join } from 'path'
|
||||
import * as fsp from 'fs/promises'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { getRepoById, updateLastPulled, updateRepoBranch, deleteRepo } from '../../db/queries'
|
||||
@@ -60,7 +60,7 @@ export function createInternalRepoMirrorRoutes(db: Database) {
|
||||
}
|
||||
|
||||
let staging: string | undefined
|
||||
let oldDirMoved = false
|
||||
let backupDir: string | undefined
|
||||
try {
|
||||
const stagingParent = join(getReposPath(), '.ocm-staging')
|
||||
mkdirSync(stagingParent, { recursive: true })
|
||||
@@ -100,17 +100,19 @@ export function createInternalRepoMirrorRoutes(db: Database) {
|
||||
} catch { /* ignore stat errors */ }
|
||||
}
|
||||
|
||||
await fsp.mkdir(dirname(fullPath), { recursive: true })
|
||||
|
||||
if (existsSync(fullPath)) {
|
||||
try {
|
||||
await fsp.rename(fullPath, fullPath + '.ocm-old')
|
||||
oldDirMoved = true
|
||||
} catch { /* ignore rename errors */ }
|
||||
backupDir = `${fullPath}.ocm-old-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
await fsp.rename(fullPath, backupDir)
|
||||
}
|
||||
|
||||
await fsp.rename(extractedRoot, fullPath)
|
||||
|
||||
const oldDir = fullPath + '.ocm-old'
|
||||
await fsp.rm(oldDir, { recursive: true, force: true }).catch(() => {})
|
||||
if (backupDir) {
|
||||
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {})
|
||||
backupDir = undefined
|
||||
}
|
||||
|
||||
const branchName = await safeGitOut(fullPath, ['rev-parse', '--abbrev-ref', 'HEAD'])
|
||||
const head = await safeGitOut(fullPath, ['rev-parse', 'HEAD'])
|
||||
@@ -132,11 +134,14 @@ export function createInternalRepoMirrorRoutes(db: Database) {
|
||||
} catch (error) {
|
||||
logger.error('mirror POST failed:', error)
|
||||
|
||||
if (oldDirMoved) {
|
||||
if (backupDir) {
|
||||
try {
|
||||
await fsp.rename(fullPath + '.ocm-old', fullPath)
|
||||
if (existsSync(fullPath)) {
|
||||
await fsp.rm(fullPath, { recursive: true, force: true })
|
||||
}
|
||||
await fsp.rename(backupDir, fullPath)
|
||||
} catch {
|
||||
logger.error('failed to restore old repo from .ocm-old')
|
||||
logger.error('failed to restore old repo from backup')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
addRecentOpenCodeModel,
|
||||
getOpenCodeModelState as readModelStateFromDb,
|
||||
removeRecentOpenCodeModel,
|
||||
toggleFavoriteOpenCodeModel,
|
||||
type OpenCodeModelStateRecord,
|
||||
} from '../db/model-state'
|
||||
@@ -31,6 +32,7 @@ export const ModelStateSchema = z.object({
|
||||
const UpdateModelStateSchema = z.object({
|
||||
recent: ModelSelectionSchema.optional(),
|
||||
favorite: ModelSelectionSchema.optional(),
|
||||
removeRecent: ModelSelectionSchema.optional(),
|
||||
}).strict()
|
||||
|
||||
export function getModelStatePath(): string {
|
||||
@@ -86,6 +88,8 @@ export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClie
|
||||
nextState = toggleFavoriteOpenCodeModel(db, validated.favorite)
|
||||
} else if (validated.recent) {
|
||||
nextState = addRecentOpenCodeModel(db, validated.recent)
|
||||
} else if (validated.removeRecent) {
|
||||
nextState = removeRecentOpenCodeModel(db, validated.removeRecent)
|
||||
} else {
|
||||
nextState = readModelStateFromDb(db)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import { spawn, execSync, spawnSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -24,17 +24,20 @@ import { patchConfigWithRecovery } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { writeFileContent } from './file-operations'
|
||||
|
||||
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
||||
export const OPENCODE_SERVER_CONNECT_HOST = OPENCODE_SERVER_HOST === '0.0.0.0' ? '127.0.0.1' : OPENCODE_SERVER_HOST
|
||||
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
const HEALTH_CHECK_TIMEOUT_MS = 3000
|
||||
const DEPRECATED_PLUGIN_PACKAGES = ['opencode-openai-codex-auth', 'opencode-copilot-auth']
|
||||
|
||||
type StartupValidationIssue = {
|
||||
path: string
|
||||
message: string
|
||||
}
|
||||
|
||||
type OpenCodePluginOptions = Record<string, unknown>
|
||||
type OpenCodePluginSpec = string | [string, OpenCodePluginOptions]
|
||||
|
||||
export class ConfigReloadError extends Error {
|
||||
validationIssues: StartupValidationIssue[]
|
||||
removedFields: string[]
|
||||
@@ -302,7 +305,9 @@ class OpenCodeServerManager {
|
||||
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
|
||||
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
const configuredPluginCount = await this.getConfiguredPluginCount(openCodeConfigPath)
|
||||
const configuredPlugins = await this.getConfiguredPlugins(openCodeConfigPath)
|
||||
await this.installConfiguredPlugins(configuredPlugins)
|
||||
const configuredPluginCount = configuredPlugins.length
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
@@ -482,13 +487,99 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async getConfiguredPluginCount(configPath: string): Promise<number> {
|
||||
private isPathPluginSpec(spec: string): boolean {
|
||||
return spec.startsWith('file://') || spec.startsWith('.') || path.isAbsolute(spec)
|
||||
}
|
||||
|
||||
private getPluginInstallSpec(spec: string): string {
|
||||
if (spec.startsWith('@')) {
|
||||
const slashIndex = spec.indexOf('/')
|
||||
return slashIndex !== -1 && spec.indexOf('@', slashIndex + 1) === -1 ? `${spec}@latest` : spec
|
||||
}
|
||||
return spec.includes('@') ? spec : `${spec}@latest`
|
||||
}
|
||||
|
||||
private getPluginPackageName(spec: string): string {
|
||||
if (spec.startsWith('@')) {
|
||||
const slashIndex = spec.indexOf('/')
|
||||
if (slashIndex === -1) return spec
|
||||
const versionIndex = spec.indexOf('@', slashIndex + 1)
|
||||
return versionIndex === -1 ? spec : spec.slice(0, versionIndex)
|
||||
}
|
||||
const versionIndex = spec.indexOf('@')
|
||||
return versionIndex === -1 ? spec : spec.slice(0, versionIndex)
|
||||
}
|
||||
|
||||
private sanitizeNpmCacheSegment(spec: string): string {
|
||||
if (process.platform !== 'win32') return spec
|
||||
return Array.from(spec, (char) => /[<>:"|?*]/.test(char) || char.charCodeAt(0) < 32 ? '_' : char).join('')
|
||||
}
|
||||
|
||||
private getPluginSpecifier(plugin: OpenCodePluginSpec): string {
|
||||
return Array.isArray(plugin) ? plugin[0] : plugin
|
||||
}
|
||||
|
||||
private isOpenCodePluginSpec(plugin: unknown): plugin is OpenCodePluginSpec {
|
||||
if (typeof plugin === 'string') return plugin.trim().length > 0
|
||||
if (!Array.isArray(plugin) || plugin.length !== 2 || typeof plugin[0] !== 'string' || plugin[0].trim().length === 0) return false
|
||||
const options = plugin[1]
|
||||
return options !== null && typeof options === 'object' && !Array.isArray(options)
|
||||
}
|
||||
|
||||
private async getConfiguredPlugins(configPath: string): Promise<OpenCodePluginSpec[]> {
|
||||
try {
|
||||
const content = await fs.readFile(configPath, 'utf-8')
|
||||
const config = parseJsonc(content) as { plugin?: unknown }
|
||||
return Array.isArray(config.plugin) ? config.plugin.length : 0
|
||||
if (!Array.isArray(config.plugin)) return []
|
||||
return config.plugin
|
||||
.filter((plugin): plugin is OpenCodePluginSpec => this.isOpenCodePluginSpec(plugin))
|
||||
} catch {
|
||||
return 0
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private async installConfiguredPlugins(plugins: OpenCodePluginSpec[]): Promise<void> {
|
||||
const npmPlugins = plugins
|
||||
.map((plugin) => this.getPluginSpecifier(plugin))
|
||||
.filter((plugin) => !this.isPathPluginSpec(plugin) && !DEPRECATED_PLUGIN_PACKAGES.some((pkg) => plugin.includes(pkg)))
|
||||
if (npmPlugins.length === 0) return
|
||||
|
||||
const cacheHome = process.env.XDG_CACHE_HOME || path.join(process.env.HOME || '/home/node', '.cache')
|
||||
logger.info(`Pre-installing ${npmPlugins.length} configured OpenCode plugin(s)`)
|
||||
|
||||
for (const plugin of npmPlugins) {
|
||||
const installSpec = this.getPluginInstallSpec(plugin)
|
||||
const packageName = this.getPluginPackageName(plugin)
|
||||
const installDir = path.join(cacheHome, 'opencode', 'packages', this.sanitizeNpmCacheSegment(installSpec))
|
||||
const packageJsonPath = path.join(installDir, 'node_modules', packageName, 'package.json')
|
||||
|
||||
try {
|
||||
await fs.access(packageJsonPath)
|
||||
logger.info(`OpenCode plugin already installed: ${plugin}`)
|
||||
continue
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as NodeJS.ErrnoException).code : ''
|
||||
if (errorCode !== 'ENOENT') {
|
||||
logger.warn(`Could not check OpenCode plugin install state for ${plugin}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
await fs.mkdir(installDir, { recursive: true })
|
||||
if (!await fs.access(path.join(installDir, 'package.json')).then(() => true).catch(() => false)) {
|
||||
const init = spawnSync('bun', ['init', '-y'], { cwd: installDir, encoding: 'utf8' })
|
||||
if (init.status !== 0) {
|
||||
logger.warn(`Failed to initialize OpenCode plugin cache for ${plugin}: ${init.stderr || init.stdout}`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const result = spawnSync('bun', ['add', '--ignore-scripts', installSpec], { cwd: installDir, encoding: 'utf8' })
|
||||
if (result.status === 0) {
|
||||
logger.info(`Installed OpenCode plugin: ${plugin}`)
|
||||
continue
|
||||
}
|
||||
|
||||
logger.warn(`Failed to install OpenCode plugin ${plugin}: ${result.stderr || result.stdout}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -156,6 +156,30 @@ describe('internal-repo-mirror routes', () => {
|
||||
expect(mockCreateRepoRow).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('creates the mirror target parent before final rename', async () => {
|
||||
const targetPath = join(getTmpRoot(), 'nested', 'test-repo')
|
||||
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'nested/test-repo', fullPath: targetPath })
|
||||
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
|
||||
|
||||
const sourceDir = join(getTmpRoot(), 'source-nested')
|
||||
mkdirSync(sourceDir, { recursive: true })
|
||||
writeFileSync(join(sourceDir, 'payload.txt'), 'payload data')
|
||||
|
||||
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
|
||||
const tarball = result.stdout as Buffer
|
||||
|
||||
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=test-repo', {
|
||||
method: 'POST',
|
||||
body: tarball,
|
||||
headers: { 'content-type': 'application/x-tar' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = (await res.json()) as { fullPath: string }
|
||||
expect(json.fullPath).toBe(targetPath)
|
||||
expect(existsSync(join(targetPath, 'payload.txt'))).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 409 when repo is in use and force not set', async () => {
|
||||
const repoDir = join(getTmpRoot(), 'test-repo')
|
||||
mkdirSync(repoDir, { recursive: true })
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@opencode-manager/shared": "workspace:*",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
@@ -33,12 +32,10 @@
|
||||
"better-auth": "^1.4.17",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"cronstrue": "^3.13.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^8.0.2",
|
||||
"highlight.js": "^11.11.1",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"lucide-react": "^0.546.0",
|
||||
"mermaid": "^11.12.2",
|
||||
"react": "^19.1.1",
|
||||
@@ -63,7 +60,6 @@
|
||||
"@types/react": "^19.2.2",
|
||||
"@types/react-dom": "^19.2.2",
|
||||
"@vitejs/plugin-react": "^5.0.4",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.22",
|
||||
|
||||
@@ -102,14 +102,6 @@ async function fetchWrapper<T = unknown>(
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchWrapperText(
|
||||
url: string,
|
||||
options: FetchWrapperOptions = {}
|
||||
): Promise<string> {
|
||||
const response = await fetchWithTimeout(url, options)
|
||||
return response.text()
|
||||
}
|
||||
|
||||
async function fetchWrapperVoid(
|
||||
url: string,
|
||||
options: FetchWrapperOptions = {}
|
||||
@@ -125,4 +117,4 @@ async function fetchWrapperBlob(
|
||||
return response.blob()
|
||||
}
|
||||
|
||||
export { fetchWrapper, fetchWrapperText, fetchWrapperVoid, fetchWrapperBlob }
|
||||
export { fetchWrapper, fetchWrapperVoid, fetchWrapperBlob }
|
||||
@@ -249,6 +249,14 @@ export async function addOpenCodeRecentModel(model: ModelSelection): Promise<Ope
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeOpenCodeRecentModel(model: ModelSelection): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ removeRecent: model }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function toggleOpenCodeFavoriteModel(model: ModelSelection): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -626,11 +626,6 @@ export function useQuestions() {
|
||||
return questions
|
||||
}
|
||||
|
||||
export function usePendingAlerts(): boolean {
|
||||
const { permissions, questions } = useEventContext()
|
||||
return permissions.pendingCount + questions.pendingCount > 0
|
||||
}
|
||||
|
||||
export function useSSEHealth(): EventStreamHealthState {
|
||||
return useEventContext().sseHealth
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useTallScrollContent } from '../useTallScrollContent'
|
||||
|
||||
let mockObserve: ReturnType<typeof vi.fn>
|
||||
let mockDisconnect: ReturnType<typeof vi.fn>
|
||||
let resizeCallback: ((entries: ResizeObserverEntry[]) => void) | null = null
|
||||
|
||||
vi.stubGlobal('ResizeObserver', vi.fn((cb: (entries: ResizeObserverEntry[]) => void) => {
|
||||
resizeCallback = cb
|
||||
return {
|
||||
observe: mockObserve,
|
||||
disconnect: mockDisconnect,
|
||||
unobserve: vi.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
describe('useTallScrollContent', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockObserve = vi.fn()
|
||||
mockDisconnect = vi.fn()
|
||||
resizeCallback = null
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function createContainerRef(scrollHeight: number, clientHeight: number) {
|
||||
const el = document.createElement('div')
|
||||
Object.defineProperty(el, 'scrollHeight', { value: scrollHeight, configurable: true })
|
||||
Object.defineProperty(el, 'clientHeight', { value: clientHeight, configurable: true })
|
||||
return { current: el }
|
||||
}
|
||||
|
||||
it('returns false when scrollHeight <= clientHeight * ratio', () => {
|
||||
const ref = createContainerRef(500, 400)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when scrollHeight > clientHeight * ratio', () => {
|
||||
const ref = createContainerRef(2000, 800)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(true)
|
||||
})
|
||||
|
||||
it('updates from false to true when ResizeObserver fires with taller content', () => {
|
||||
const ref = createContainerRef(500, 400)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(false)
|
||||
|
||||
Object.defineProperty(ref.current, 'scrollHeight', { value: 2000 })
|
||||
act(() => {
|
||||
resizeCallback?.([] as ResizeObserverEntry[])
|
||||
})
|
||||
|
||||
expect(result.current).toBe(true)
|
||||
})
|
||||
|
||||
it('updates from true to false when ResizeObserver fires with smaller container', () => {
|
||||
const ref = createContainerRef(2000, 800)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(true)
|
||||
|
||||
Object.defineProperty(ref.current, 'clientHeight', { value: 2000 })
|
||||
act(() => {
|
||||
resizeCallback?.([] as ResizeObserverEntry[])
|
||||
})
|
||||
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -50,6 +50,7 @@ describe('useAutoScroll', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 0))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -58,6 +59,7 @@ describe('useAutoScroll', () => {
|
||||
containerHarness = null
|
||||
}
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
vi.clearAllTimers()
|
||||
})
|
||||
|
||||
@@ -165,11 +167,100 @@ describe('useAutoScroll', () => {
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('scrolls to bottom again after layout frames', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 300)
|
||||
|
||||
act(() => {
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('does not keep forcing bottom after user scrolls up', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
const userPosition = 100
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(userPosition)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
expect(containerHarness.getScrollTop()).toBe(userPosition)
|
||||
})
|
||||
|
||||
it('cancels pending bottom scroll as soon as user touches the list', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
const userPosition = 120
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
containerHarness.setScrollTop(userPosition)
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(userPosition)
|
||||
})
|
||||
|
||||
it('does not show scroll button on tiny upward drag from bottom', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(bottomPosition - 20)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointermove', {
|
||||
clientY: 260,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).not.toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('disengages when user fires a wheel-up event', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
@@ -192,6 +283,7 @@ describe('useAutoScroll', () => {
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
@@ -220,6 +312,7 @@ describe('useAutoScroll', () => {
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
@@ -246,6 +339,7 @@ describe('useAutoScroll', () => {
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { Message } from '@/api/types'
|
||||
|
||||
const SCROLL_LOCK_MS = 300
|
||||
const BOTTOM_THRESHOLD_PX = 48
|
||||
const SHOW_SCROLL_BUTTON_THRESHOLD_PX = 120
|
||||
const SCROLL_TO_BOTTOM_FRAME_COUNT = 2
|
||||
|
||||
interface UseAutoScrollOptions {
|
||||
containerRef?: React.RefObject<HTMLDivElement | null>
|
||||
@@ -30,6 +32,8 @@ export function useAutoScroll({
|
||||
const pointerStartYRef = useRef<number | null>(null)
|
||||
const pointerActiveRef = useRef(false)
|
||||
const onScrollStateChangeRef = useRef(onScrollStateChange)
|
||||
const scrollRequestIdRef = useRef(0)
|
||||
const isScrollButtonVisibleRef = useRef(false)
|
||||
|
||||
onScrollStateChangeRef.current = onScrollStateChange
|
||||
|
||||
@@ -37,7 +41,25 @@ export function useAutoScroll({
|
||||
if (!containerRef?.current) return
|
||||
userScrolledAtRef.current = 0
|
||||
userDisengagedRef.current = false
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight
|
||||
isScrollButtonVisibleRef.current = false
|
||||
const scrollRequestId = scrollRequestIdRef.current + 1
|
||||
scrollRequestIdRef.current = scrollRequestId
|
||||
const scroll = () => {
|
||||
if (!containerRef?.current) return
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight
|
||||
}
|
||||
|
||||
scroll()
|
||||
let frameCount = 0
|
||||
const scrollAfterLayout = () => {
|
||||
if (scrollRequestIdRef.current !== scrollRequestId) return
|
||||
frameCount += 1
|
||||
scroll()
|
||||
if (frameCount < SCROLL_TO_BOTTOM_FRAME_COUNT) {
|
||||
requestAnimationFrame(scrollAfterLayout)
|
||||
}
|
||||
}
|
||||
requestAnimationFrame(scrollAfterLayout)
|
||||
onScrollStateChangeRef.current?.(false)
|
||||
}, [containerRef])
|
||||
|
||||
@@ -53,8 +75,13 @@ export function useAutoScroll({
|
||||
if (!container) return
|
||||
|
||||
const markDisengaged = () => {
|
||||
const container = containerRef?.current
|
||||
if (!container) return
|
||||
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
|
||||
userScrolledAtRef.current = Date.now()
|
||||
if (!userDisengagedRef.current) {
|
||||
scrollRequestIdRef.current += 1
|
||||
if (!isScrollButtonVisibleRef.current && distanceFromBottom > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
userDisengagedRef.current = true
|
||||
@@ -63,6 +90,7 @@ export function useAutoScroll({
|
||||
const handlePointerDown = (e: PointerEvent) => {
|
||||
pointerStartYRef.current = e.clientY
|
||||
pointerActiveRef.current = true
|
||||
scrollRequestIdRef.current += 1
|
||||
}
|
||||
|
||||
const handlePointerMove = (e: PointerEvent) => {
|
||||
@@ -98,12 +126,19 @@ export function useAutoScroll({
|
||||
if (userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = 0
|
||||
userDisengagedRef.current = false
|
||||
isScrollButtonVisibleRef.current = false
|
||||
onScrollStateChangeRef.current?.(false)
|
||||
}
|
||||
} else if (userDisengagedRef.current && !isScrollButtonVisibleRef.current && scrollHeight - scrollTop - clientHeight > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
} else if (pointerActiveRef.current && !userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = Date.now()
|
||||
userDisengagedRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
if (scrollHeight - scrollTop - clientHeight > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
export function useDebounce<T>(value: T, delay: number): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedValue(value), delay)
|
||||
return () => clearTimeout(timer)
|
||||
}, [value, delay])
|
||||
|
||||
return debouncedValue
|
||||
}
|
||||
@@ -83,12 +83,17 @@ function useSwipeHandlers(
|
||||
const [swipeProgress, setSwipeProgress] = useState(0)
|
||||
const [swipeDeltaPx, setSwipeDeltaPx] = useState(0)
|
||||
const [dismissing, setDismissing] = useState(false)
|
||||
const dismissingRef = useRef(false)
|
||||
dismissingRef.current = dismissing
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
if (enabled) {
|
||||
setDismissing(false)
|
||||
setSwipeDeltaPx(0)
|
||||
setSwipeProgress(0)
|
||||
} else if (!dismissingRef.current) {
|
||||
setSwipeDeltaPx(0)
|
||||
setSwipeProgress(0)
|
||||
}
|
||||
}, [enabled])
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useModelSelection } from './useModelSelection'
|
||||
import { useModelStore, type ModelSelection } from '@/stores/modelStore'
|
||||
@@ -30,6 +30,7 @@ vi.mock('@/api/providers', async () => {
|
||||
getProviders: vi.fn(),
|
||||
getOpenCodeModelState: vi.fn(),
|
||||
addOpenCodeRecentModel: vi.fn(),
|
||||
removeOpenCodeRecentModel: vi.fn(),
|
||||
toggleOpenCodeFavoriteModel: vi.fn(),
|
||||
}
|
||||
})
|
||||
@@ -47,6 +48,7 @@ const mockUseOpenCodeClient = vi.mocked(useOpenCodeExports.useOpenCodeClient)
|
||||
const mockGetProviders = vi.mocked(providersApi.getProviders)
|
||||
const mockGetOpenCodeModelState = vi.mocked(providersApi.getOpenCodeModelState)
|
||||
const mockAddOpenCodeRecentModel = vi.mocked(providersApi.addOpenCodeRecentModel)
|
||||
const mockRemoveOpenCodeRecentModel = vi.mocked(providersApi.removeOpenCodeRecentModel)
|
||||
const mockToggleOpenCodeFavoriteModel = vi.mocked(providersApi.toggleOpenCodeFavoriteModel)
|
||||
|
||||
describe('useModelSelection', () => {
|
||||
@@ -72,6 +74,11 @@ describe('useModelSelection', () => {
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
mockRemoveOpenCodeRecentModel.mockResolvedValue({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
mockToggleOpenCodeFavoriteModel.mockResolvedValue({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
@@ -140,7 +147,6 @@ describe('useModelSelection', () => {
|
||||
|
||||
expect(returnValue).toBe(true)
|
||||
expect(useModelStore.getState().model).toEqual(testModel)
|
||||
expect(useModelStore.getState().recentModels).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects unknown model after providers are loaded', async () => {
|
||||
@@ -174,13 +180,150 @@ describe('useModelSelection', () => {
|
||||
})
|
||||
|
||||
const initialModel = useModelStore.getState().model
|
||||
const initialRecentModels = useModelStore.getState().recentModels
|
||||
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'missing-model' }
|
||||
const returnValue = result.current.setActiveModel(testModel)
|
||||
|
||||
expect(returnValue).toBe(false)
|
||||
expect(useModelStore.getState().model).toEqual(initialModel)
|
||||
expect(useModelStore.getState().recentModels).toEqual(initialRecentModels)
|
||||
})
|
||||
|
||||
describe('recentModels/favoriteModels derived from React Query', () => {
|
||||
it('filters out models not present in providers', async () => {
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [
|
||||
{ providerID: 'AI2', modelID: 'foo' },
|
||||
{ providerID: 'GreatScott', modelID: 'mimo' },
|
||||
],
|
||||
favorite: [
|
||||
{ providerID: 'VLLM', modelID: 'bar' },
|
||||
{ providerID: 'GreatScott', modelID: 'mimo' },
|
||||
],
|
||||
variant: {},
|
||||
})
|
||||
mockGetProviders.mockResolvedValue({
|
||||
providers: [
|
||||
{
|
||||
id: 'AI2',
|
||||
name: 'AI2',
|
||||
models: { foo: { id: 'foo', name: 'Foo' } },
|
||||
isConnected: true,
|
||||
env: [],
|
||||
options: {},
|
||||
},
|
||||
{
|
||||
id: 'VLLM',
|
||||
name: 'VLLM',
|
||||
models: { bar: { id: 'bar', name: 'Bar' } },
|
||||
isConnected: true,
|
||||
env: [],
|
||||
options: {},
|
||||
},
|
||||
],
|
||||
connected: ['AI2', 'VLLM'],
|
||||
default: {},
|
||||
} as any)
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([{ providerID: 'AI2', modelID: 'foo' }])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.favoriteModels).toEqual([{ providerID: 'VLLM', modelID: 'bar' }])
|
||||
})
|
||||
})
|
||||
|
||||
it('returns raw values when providers query is loading (undefined)', async () => {
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [{ providerID: 'AI2', modelID: 'foo' }],
|
||||
favorite: [{ providerID: 'VLLM', modelID: 'bar' }],
|
||||
variant: {},
|
||||
})
|
||||
mockGetProviders.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([{ providerID: 'AI2', modelID: 'foo' }])
|
||||
})
|
||||
|
||||
expect(result.current.favoriteModels).toEqual([{ providerID: 'VLLM', modelID: 'bar' }])
|
||||
})
|
||||
|
||||
it('returns raw values when providers returns empty array', async () => {
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [{ providerID: 'AI2', modelID: 'foo' }],
|
||||
favorite: [{ providerID: 'VLLM', modelID: 'bar' }],
|
||||
variant: {},
|
||||
})
|
||||
mockGetProviders.mockResolvedValue({
|
||||
providers: [],
|
||||
connected: [],
|
||||
default: {},
|
||||
} as any)
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([{ providerID: 'AI2', modelID: 'foo' }])
|
||||
})
|
||||
|
||||
expect(result.current.favoriteModels).toEqual([{ providerID: 'VLLM', modelID: 'bar' }])
|
||||
})
|
||||
})
|
||||
|
||||
it('toggleFavorite calls toggleOpenCodeFavoriteModel and does not mutate Zustand', async () => {
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBeDefined()
|
||||
})
|
||||
|
||||
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
result.current.toggleFavorite(testModel)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToggleOpenCodeFavoriteModel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(mockToggleOpenCodeFavoriteModel.mock.calls[0][0]).toEqual(testModel)
|
||||
expect(useModelStore.getState().model).not.toEqual(testModel)
|
||||
})
|
||||
|
||||
it('removes recent models optimistically and rolls back on failure', async () => {
|
||||
const removedModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
const retainedModel: ModelSelection = { providerID: 'openai', modelID: 'gpt-4.1' }
|
||||
let rejectRemove: (error: Error) => void = () => {}
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [removedModel, retainedModel],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
mockRemoveOpenCodeRecentModel.mockImplementation(() => new Promise((_, reject) => {
|
||||
rejectRemove = reject
|
||||
}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([removedModel, retainedModel])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.removeRecentModel(removedModel)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([retainedModel])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
rejectRemove(new Error('remove failed'))
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([removedModel, retainedModel])
|
||||
})
|
||||
})
|
||||
|
||||
it('user selection still updates recents', async () => {
|
||||
@@ -222,10 +365,24 @@ describe('useModelSelection', () => {
|
||||
result.current.setModel(testModel)
|
||||
|
||||
expect(useModelStore.getState().model).toEqual(testModel)
|
||||
expect(useModelStore.getState().recentModels[0]).toEqual(testModel)
|
||||
await waitFor(() => {
|
||||
expect(mockAddOpenCodeRecentModel).toHaveBeenCalled()
|
||||
expect(mockAddOpenCodeRecentModel.mock.calls[0][0]).toEqual(testModel)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAddOpenCodeRecentModel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('restoreSessionModel sets model without requiring providers', async () => {
|
||||
mockGetProviders.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
const sessionModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
result.current.restoreSessionModel(sessionModel)
|
||||
|
||||
expect(useModelStore.getState().model).toEqual(sessionModel)
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useConfig } from './useOpenCode'
|
||||
import { useOpenCodeClient } from './useOpenCode'
|
||||
import { useModelStore, type ModelSelection } from '@/stores/modelStore'
|
||||
import { addOpenCodeRecentModel, getOpenCodeModelState, getProviders, toggleOpenCodeFavoriteModel } from '@/api/providers'
|
||||
import { useModelStore, modelExists, type ModelSelection } from '@/stores/modelStore'
|
||||
import { addOpenCodeRecentModel, getOpenCodeModelState, getProviders, removeOpenCodeRecentModel, toggleOpenCodeFavoriteModel, type OpenCodeModelState } from '@/api/providers'
|
||||
|
||||
interface UseModelSelectionResult {
|
||||
model: ModelSelection | null
|
||||
@@ -12,12 +12,18 @@ interface UseModelSelectionResult {
|
||||
favoriteModels: ModelSelection[]
|
||||
setModel: (model: ModelSelection) => void
|
||||
setActiveModel: (model: ModelSelection) => boolean
|
||||
restoreSessionModel: (model: ModelSelection) => void
|
||||
toggleFavorite: (model: ModelSelection) => void
|
||||
removeRecentModel: (model: ModelSelection) => void
|
||||
isModelStateLoading: boolean
|
||||
}
|
||||
|
||||
const modelStateQueryKey = ['opencode', 'model-state']
|
||||
|
||||
const isSameModel = (left: ModelSelection, right: ModelSelection) => (
|
||||
left.providerID === right.providerID && left.modelID === right.modelID
|
||||
)
|
||||
|
||||
export function useModelSelection(
|
||||
opcodeUrl: string | null | undefined,
|
||||
directory?: string
|
||||
@@ -35,12 +41,9 @@ export function useModelSelection(
|
||||
|
||||
const {
|
||||
model,
|
||||
recentModels,
|
||||
favoriteModels,
|
||||
setModel: setStoreModel,
|
||||
setActiveModel: setStoreActiveModel,
|
||||
syncModelState,
|
||||
toggleFavorite: toggleStoreFavorite,
|
||||
validateAndSyncModel,
|
||||
getModelString
|
||||
} = useModelStore()
|
||||
@@ -77,6 +80,52 @@ export function useModelSelection(
|
||||
},
|
||||
})
|
||||
|
||||
const removeRecentMutation = useMutation({
|
||||
mutationFn: removeOpenCodeRecentModel,
|
||||
onMutate: async (removedModel) => {
|
||||
const queryKey = [...modelStateQueryKey, opcodeUrl, directory]
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
const previousState = queryClient.getQueryData<OpenCodeModelState>(queryKey)
|
||||
|
||||
if (previousState) {
|
||||
const nextState: OpenCodeModelState = {
|
||||
...previousState,
|
||||
recent: previousState.recent.filter((model) => !isSameModel(model, removedModel)),
|
||||
}
|
||||
queryClient.setQueryData(queryKey, nextState)
|
||||
syncModelState(nextState)
|
||||
}
|
||||
|
||||
return { previousState }
|
||||
},
|
||||
onSuccess: (state) => {
|
||||
syncModelState(state)
|
||||
queryClient.setQueryData([...modelStateQueryKey, opcodeUrl, directory], state)
|
||||
queryClient.invalidateQueries({ queryKey: [...modelStateQueryKey, opcodeUrl, directory] })
|
||||
},
|
||||
onError: (error, _removedModel, context) => {
|
||||
if (context?.previousState) {
|
||||
syncModelState(context.previousState)
|
||||
queryClient.setQueryData([...modelStateQueryKey, opcodeUrl, directory], context.previousState)
|
||||
}
|
||||
console.error('Failed to remove recent model on backend', error)
|
||||
},
|
||||
})
|
||||
|
||||
const providers = providersData?.providers
|
||||
|
||||
const recentModels = useMemo(() => {
|
||||
const raw = modelState?.recent ?? []
|
||||
if (!providers || providers.length === 0) return raw
|
||||
return raw.filter((m) => modelExists(m, providers))
|
||||
}, [modelState?.recent, providers])
|
||||
|
||||
const favoriteModels = useMemo(() => {
|
||||
const raw = modelState?.favorite ?? []
|
||||
if (!providers || providers.length === 0) return raw
|
||||
return raw.filter((m) => modelExists(m, providers))
|
||||
}, [modelState?.favorite, providers])
|
||||
|
||||
const defaultModelString = providersData?.providers
|
||||
.map((provider) => {
|
||||
const modelID = providersData.default[provider.id] || Object.keys(provider.models || {})[0]
|
||||
@@ -113,11 +162,18 @@ export function useModelSelection(
|
||||
return true
|
||||
}
|
||||
|
||||
const restoreSessionModel = (sessionModel: ModelSelection): void => {
|
||||
setStoreActiveModel(sessionModel)
|
||||
}
|
||||
|
||||
const toggleFavorite = (nextModel: ModelSelection) => {
|
||||
toggleStoreFavorite(nextModel)
|
||||
updateFavoriteModel.mutate(nextModel)
|
||||
}
|
||||
|
||||
const removeRecentModel = (nextModel: ModelSelection) => {
|
||||
removeRecentMutation.mutate(nextModel)
|
||||
}
|
||||
|
||||
return {
|
||||
model,
|
||||
modelString: getModelString(),
|
||||
@@ -125,7 +181,9 @@ export function useModelSelection(
|
||||
favoriteModels,
|
||||
setModel,
|
||||
setActiveModel,
|
||||
restoreSessionModel,
|
||||
toggleFavorite,
|
||||
removeRecentModel,
|
||||
isModelStateLoading,
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
|
||||
export function useTallScrollContent(
|
||||
containerRef: React.RefObject<HTMLElement | null>,
|
||||
ratio = 1.5
|
||||
): boolean {
|
||||
const [isTall, setIsTall] = useState(false)
|
||||
const observingRef = useRef<HTMLElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const recompute = () => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
setIsTall(el.scrollHeight > el.clientHeight * ratio)
|
||||
}
|
||||
|
||||
const el = containerRef.current
|
||||
|
||||
if (!el || el === observingRef.current) return
|
||||
|
||||
observingRef.current = el
|
||||
recompute()
|
||||
|
||||
const observer = new ResizeObserver(recompute)
|
||||
observer.observe(el)
|
||||
el.addEventListener('scroll', recompute)
|
||||
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
el.removeEventListener('scroll', recompute)
|
||||
observingRef.current = null
|
||||
}
|
||||
})
|
||||
|
||||
return isTall
|
||||
}
|
||||
@@ -30,7 +30,7 @@ function isValidHex(color: string | undefined): color is string {
|
||||
return /^#[0-9A-Fa-f]{6}$/.test(color)
|
||||
}
|
||||
|
||||
export function getAgentColor(
|
||||
function getAgentColor(
|
||||
agentName: string,
|
||||
apiColor?: string
|
||||
): { light: string; dark: string } {
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AudioRecorder, downsampleAndConvert, encodeWavFromInt16 } from './audioRecorder'
|
||||
|
||||
const blobToArrayBuffer = (blob: Blob): Promise<ArrayBuffer> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as ArrayBuffer)
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsArrayBuffer(blob)
|
||||
})
|
||||
|
||||
describe('downsampleAndConvert', () => {
|
||||
it('should produce correct output length for 48kHz to 16kHz', () => {
|
||||
const inputLength = 4800
|
||||
@@ -61,7 +69,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should have RIFF header at offset 0', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const riff = String.fromCharCode(
|
||||
@@ -76,7 +84,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should have WAVE identifier at offset 8', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const wave = String.fromCharCode(
|
||||
@@ -91,7 +99,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should have sample rate at offset 24', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const sampleRate = view.getUint32(24, true)
|
||||
@@ -101,7 +109,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should have data identifier at offset 36', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const data = String.fromCharCode(
|
||||
@@ -116,7 +124,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should have correct file size for 1000 samples', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
|
||||
expect(arrayBuffer.byteLength).toBe(44 + 1000 * 2)
|
||||
})
|
||||
@@ -124,7 +132,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should handle different sample rates', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 44100, 1)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const sampleRate = view.getUint32(24, true)
|
||||
@@ -134,7 +142,7 @@ describe('encodeWavFromInt16', () => {
|
||||
it('should handle stereo channels', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 2)
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const channels = view.getUint16(22, true)
|
||||
|
||||
@@ -78,7 +78,7 @@ function formatPatchPart(part: Part): string {
|
||||
return content
|
||||
}
|
||||
|
||||
export function generateSessionMarkdown(
|
||||
function generateSessionMarkdown(
|
||||
messages: MessageWithParts[],
|
||||
session: Session
|
||||
): string {
|
||||
|
||||
@@ -6,7 +6,7 @@ export interface FileReference {
|
||||
fullMatch: string
|
||||
}
|
||||
|
||||
export const FILE_REFERENCE_PATTERN = /\b([\w\-./]+\.(ts|tsx|js|jsx|py|java|cpp|c|h|hpp|go|rs|rb|php|swift|kt|cs|vue|svelte|css|scss|sass|less|html|xml|json|yaml|yml|md|txt|sh|bash|sql|graphql|proto|toml|ini|conf|env))(?::(\d+))?\b/gi
|
||||
const FILE_REFERENCE_PATTERN = /\b([\w\-./]+\.(ts|tsx|js|jsx|py|java|cpp|c|h|hpp|go|rs|rb|php|swift|kt|cs|vue|svelte|css|scss|sass|less|html|xml|json|yaml|yml|md|txt|sh|bash|sql|graphql|proto|toml|ini|conf|env))(?::(\d+))?\b/gi
|
||||
|
||||
export function detectFileReferences(text: string): FileReference[] {
|
||||
const references: FileReference[] = []
|
||||
@@ -30,21 +30,4 @@ export function detectFileReferences(text: string): FileReference[] {
|
||||
return references
|
||||
}
|
||||
|
||||
export function isFileReference(text: string): boolean {
|
||||
return FILE_REFERENCE_PATTERN.test(text)
|
||||
}
|
||||
|
||||
export function parseFileReference(text: string): FileReference | null {
|
||||
const regex = new RegExp(FILE_REFERENCE_PATTERN)
|
||||
const match = regex.exec(text)
|
||||
|
||||
if (!match) return null
|
||||
|
||||
return {
|
||||
filePath: match[1],
|
||||
lineNumber: match[3] ? parseInt(match[3], 10) : undefined,
|
||||
startIndex: match.index,
|
||||
endIndex: match.index + match[0].length,
|
||||
fullMatch: match[0],
|
||||
}
|
||||
}
|
||||
@@ -205,7 +205,7 @@ export function Login() {
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder=""
|
||||
className="bg-input border-border focus:border-primary"
|
||||
className="border-border focus:border-primary"
|
||||
{...register('email')}
|
||||
aria-invalid={!!errors.email}
|
||||
/>
|
||||
@@ -219,7 +219,7 @@ export function Login() {
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder=""
|
||||
className="bg-input border-border focus:border-primary"
|
||||
className="border-border focus:border-primary"
|
||||
{...register('password')}
|
||||
aria-invalid={!!errors.password}
|
||||
/>
|
||||
|
||||
@@ -5,8 +5,7 @@ import { getRepo, initializeAssistantMode } from "@/api/repos";
|
||||
import { MessageThread } from "@/components/message/MessageThread";
|
||||
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
|
||||
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
|
||||
import { X, CornerUpLeft, ArrowDown } from "lucide-react";
|
||||
import { ModelSelectDialog } from "@/components/model/ModelSelectDialog";
|
||||
import { X, CornerUpLeft } from "lucide-react";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { SessionList } from "@/components/session/SessionList";
|
||||
import { getSessionListPath } from '@/lib/navigation'
|
||||
@@ -27,7 +26,6 @@ import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { useAutoScroll } from "@/hooks/useAutoScroll";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { useVisualViewport } from "@/hooks/useVisualViewport";
|
||||
import { useTallScrollContent } from "@/hooks/useTallScrollContent";
|
||||
import { useTTS } from "@/hooks/useTTS";
|
||||
import { getAssistantText, getLatestPlayableAssistantMessage, useAutoPlayLastResponse } from "@/hooks/useAutoPlayLastResponse";
|
||||
import { useEffect, useRef, useCallback, useMemo } from "react";
|
||||
@@ -62,7 +60,7 @@ const compareMessageIds = (id1: string, id2: string): number => {
|
||||
}
|
||||
|
||||
const PENDING_ACTION_SYNC_INTERVAL_MS = 30000
|
||||
|
||||
const PROMPT_OVERLAY_CLEARANCE_PX = 16
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
@@ -73,7 +71,6 @@ export function SessionDetail() {
|
||||
const { open: openSettings } = useSettingsDialog();
|
||||
const messageContainerRef = useRef<HTMLDivElement>(null);
|
||||
const promptInputRef = useRef<PromptInputHandle>(null);
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files');
|
||||
const [lspDialogOpen, setLspDialogOpen] = useDialogParam('lsp');
|
||||
@@ -85,16 +82,12 @@ export function SessionDetail() {
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
const [hasPromptContent, setHasPromptContent] = useState(false);
|
||||
const [minimizedQuestion, setMinimizedQuestion] = useState<QuestionRequest | null>(null);
|
||||
const [isHeaderVisible, setIsHeaderVisible] = useState(true);
|
||||
const lastHeaderScrollTopRef = useRef(0);
|
||||
const lastHeaderScrollHeightRef = useRef(0);
|
||||
|
||||
const isMobile = useMobile();
|
||||
const { keyboardHeight } = useVisualViewport();
|
||||
const inputBottomOffset = isMobile ? keyboardHeight : 0;
|
||||
const promptOverlayRef = useRef<HTMLDivElement>(null);
|
||||
const [promptOverlayHeight, setPromptOverlayHeight] = useState(112);
|
||||
const isContentTall = useTallScrollContent(messageContainerRef, 1.5);
|
||||
|
||||
useEffect(() => {
|
||||
const el = promptOverlayRef.current;
|
||||
@@ -196,7 +189,6 @@ export function SessionDetail() {
|
||||
isStreamingResponse,
|
||||
});
|
||||
|
||||
const handleShowModelsDialog = useCallback(() => setModelDialogOpen(true), []);
|
||||
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
|
||||
const handleShowHelpDialog = useCallback(() => openSettings(), [openSettings]);
|
||||
|
||||
@@ -214,52 +206,6 @@ export function SessionDetail() {
|
||||
}
|
||||
}, [sessionId, minimizedQuestion])
|
||||
|
||||
useEffect(() => {
|
||||
const container = messageContainerRef.current
|
||||
if (!container) return
|
||||
|
||||
lastHeaderScrollTopRef.current = container.scrollTop
|
||||
lastHeaderScrollHeightRef.current = container.scrollHeight
|
||||
setIsHeaderVisible(true)
|
||||
|
||||
const SCROLL_DELTA_THRESHOLD = 8
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!isMobile) {
|
||||
setIsHeaderVisible(true)
|
||||
return
|
||||
}
|
||||
const currentScrollTop = container.scrollTop
|
||||
const previousScrollTop = lastHeaderScrollTopRef.current
|
||||
const currentScrollHeight = container.scrollHeight
|
||||
const previousScrollHeight = lastHeaderScrollHeightRef.current
|
||||
|
||||
lastHeaderScrollTopRef.current = currentScrollTop
|
||||
lastHeaderScrollHeightRef.current = currentScrollHeight
|
||||
|
||||
if (currentScrollHeight !== previousScrollHeight) return
|
||||
|
||||
const delta = currentScrollTop - previousScrollTop
|
||||
if (Math.abs(delta) < SCROLL_DELTA_THRESHOLD) return
|
||||
|
||||
const isAtTop = currentScrollTop < 24
|
||||
|
||||
if (isAtTop) {
|
||||
setIsHeaderVisible(true)
|
||||
return
|
||||
}
|
||||
|
||||
if (delta > 0) {
|
||||
setIsHeaderVisible(true)
|
||||
} else {
|
||||
setIsHeaderVisible(false)
|
||||
}
|
||||
}
|
||||
|
||||
container.addEventListener('scroll', handleScroll, { passive: true })
|
||||
return () => container.removeEventListener('scroll', handleScroll)
|
||||
}, [repoDirectory, sessionId, isMobile])
|
||||
|
||||
const syncPendingActionsForSession = useCallback(async () => {
|
||||
if (!repoDirectory || !sessionId) return
|
||||
await Promise.all([
|
||||
@@ -355,7 +301,12 @@ export function SessionDetail() {
|
||||
}, [navigate, repoId, isAssistantSession])
|
||||
|
||||
const { leaderActive } = useKeyboardShortcuts({
|
||||
openModelDialog: () => setModelDialogOpen(true),
|
||||
openModelDialog: () => {
|
||||
const modelSelectTrigger = document.querySelector(
|
||||
"[data-model-select-trigger]",
|
||||
) as HTMLElement;
|
||||
modelSelectTrigger?.click();
|
||||
},
|
||||
openSessions: () => setSessionsDialogOpen(true),
|
||||
openSettings,
|
||||
newSession: handleNewSession,
|
||||
@@ -478,11 +429,7 @@ export function SessionDetail() {
|
||||
>
|
||||
<div
|
||||
data-testid="session-header-region"
|
||||
className={`flex-shrink-0 overflow-hidden bg-background transition-all duration-200 ease-out ${
|
||||
isHeaderVisible
|
||||
? 'max-h-72 sm:max-h-80 opacity-100 translate-y-0'
|
||||
: 'max-h-0 opacity-0 -translate-y-2'
|
||||
}`}
|
||||
className="flex-shrink-0 overflow-hidden bg-background max-h-72 sm:max-h-80"
|
||||
>
|
||||
<Header className="bg-background [&_button]:bg-black [&_button]:text-white [&_button]:border-zinc-700 [&_button:hover]:bg-zinc-900">
|
||||
<div className="flex items-center gap-1.5 sm:gap-3 min-w-0 flex-1">
|
||||
@@ -532,7 +479,7 @@ export function SessionDetail() {
|
||||
</div>
|
||||
|
||||
<div className="relative flex-1 overflow-hidden flex flex-col">
|
||||
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + 16 }}>
|
||||
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + PROMPT_OVERLAY_CLEARANCE_PX }}>
|
||||
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
|
||||
<MessageSkeleton />
|
||||
) : opcodeUrl && repoDirectory ? (
|
||||
@@ -578,18 +525,6 @@ export function SessionDetail() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{isMobile && showScrollButton && isContentTall && (
|
||||
<div className="absolute -top-9 left-0 z-50 flex flex-col items-start gap-2">
|
||||
<button
|
||||
onClick={scrollToBottom}
|
||||
className="flex items-center justify-center px-3 py-1.5 rounded-lg bg-zinc-950/80 hover:bg-zinc-900/90 text-blue-300 hover:text-blue-200 border border-blue-400/20 shadow-md backdrop-blur-md transition-all duration-200 active:scale-95 hover:scale-105 ring-1 ring-blue-400/15"
|
||||
aria-label="Scroll to bottom"
|
||||
title="Scroll to bottom"
|
||||
>
|
||||
<ArrowDown className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{leaderActive && (
|
||||
<div className="absolute -top-12 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
|
||||
<span className="text-sm font-medium">Waiting for shortcut key...</span>
|
||||
@@ -618,11 +553,10 @@ export function SessionDetail() {
|
||||
directory={repoDirectory}
|
||||
sessionID={sessionId}
|
||||
disabled={!isConnected}
|
||||
showScrollButton={showScrollButton}
|
||||
showScrollButton={showScrollButton && !hasPromptContent}
|
||||
isSessionActive={isSessionActive}
|
||||
isStreamingResponse={isStreamingResponse}
|
||||
onScrollToBottom={scrollToBottom}
|
||||
onShowModelsDialog={handleShowModelsDialog}
|
||||
onShowSessionsDialog={handleShowSessionsDialog}
|
||||
onShowHelpDialog={handleShowHelpDialog}
|
||||
onToggleDetails={handleToggleDetails}
|
||||
@@ -634,13 +568,6 @@ export function SessionDetail() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ModelSelectDialog
|
||||
open={modelDialogOpen}
|
||||
onOpenChange={setModelDialogOpen}
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={repoDirectory}
|
||||
/>
|
||||
|
||||
{/* Sessions Dialog */}
|
||||
<Dialog open={sessionsDialogOpen} onOpenChange={setSessionsDialogOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { useEffect } from 'react'
|
||||
import { SessionDetail } from '../SessionDetail'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -22,7 +23,7 @@ const mocks = vi.hoisted(() => ({
|
||||
useAutoScroll: vi.fn(),
|
||||
useDialogParam: vi.fn(),
|
||||
useSidebarAction: vi.fn(),
|
||||
useTallScrollContent: vi.fn(),
|
||||
PromptInput: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/config', () => ({
|
||||
@@ -53,10 +54,6 @@ vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeClient', () => ({
|
||||
useOpenCodeClient: mocks.useOpenCodeClient,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTTS', () => ({
|
||||
useTTS: vi.fn(() => ({ isEnabled: false })),
|
||||
}))
|
||||
@@ -97,10 +94,6 @@ vi.mock('@/hooks/useSidebarAction', () => ({
|
||||
useSidebarAction: vi.fn(() => {}),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTallScrollContent', () => ({
|
||||
useTallScrollContent: mocks.useTallScrollContent,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
|
||||
getAssistantText: vi.fn(() => ''),
|
||||
getLatestPlayableAssistantMessage: vi.fn(() => null),
|
||||
@@ -198,7 +191,7 @@ vi.mock('@/components/notifications/PendingActionsGroup', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/components/message/PromptInput', () => ({
|
||||
PromptInput: vi.fn(() => <div>MockedPromptInput</div>),
|
||||
PromptInput: mocks.PromptInput,
|
||||
}))
|
||||
|
||||
describe('SessionDetail scroll floating button', () => {
|
||||
@@ -233,6 +226,7 @@ describe('SessionDetail scroll floating button', () => {
|
||||
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
|
||||
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
|
||||
mocks.useSidebarAction.mockReturnValue(undefined)
|
||||
mocks.PromptInput.mockImplementation(() => <div>MockedPromptInput</div>)
|
||||
})
|
||||
|
||||
const createQueryClient = () =>
|
||||
@@ -240,11 +234,11 @@ describe('SessionDetail scroll floating button', () => {
|
||||
|
||||
const renderWith = (opts: {
|
||||
mobile: boolean
|
||||
tallContent: boolean
|
||||
showScrollButton: boolean
|
||||
promptContent?: boolean
|
||||
sessionActive?: boolean
|
||||
}) => {
|
||||
mocks.useMobile.mockReturnValue(opts.mobile)
|
||||
mocks.useTallScrollContent.mockReturnValue(opts.tallContent)
|
||||
mocks.useAutoScroll.mockImplementation(
|
||||
({ onScrollStateChange }: { onScrollStateChange?: (v: boolean) => void }) => {
|
||||
if (opts.showScrollButton) {
|
||||
@@ -254,6 +248,24 @@ describe('SessionDetail scroll floating button', () => {
|
||||
}
|
||||
)
|
||||
|
||||
mocks.PromptInput.mockImplementation((props: { onPromptChange?: (hasContent: boolean) => void; showScrollButton?: boolean; onScrollToBottom: () => void }) => {
|
||||
const { onPromptChange } = props
|
||||
useEffect(() => {
|
||||
onPromptChange?.(opts.promptContent ?? false)
|
||||
}, [onPromptChange])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<span>MockedPromptInput</span>
|
||||
{props.showScrollButton && (
|
||||
<button type="button" title="Scroll to bottom" aria-label="Scroll to bottom" onClick={props.onScrollToBottom}>
|
||||
Latest
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/repos/1/sessions/test-session']}>
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
@@ -265,8 +277,8 @@ describe('SessionDetail scroll floating button', () => {
|
||||
)
|
||||
}
|
||||
|
||||
it('renders floating ArrowDown when mobile + showScrollButton + isContentTall', async () => {
|
||||
renderWith({ mobile: true, tallContent: true, showScrollButton: true })
|
||||
it('passes scroll button state to PromptInput when showScrollButton is true', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: true })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTitle('Scroll to bottom')).toBeInTheDocument()
|
||||
@@ -274,29 +286,38 @@ describe('SessionDetail scroll floating button', () => {
|
||||
expect(screen.getByLabelText('Scroll to bottom')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does NOT render floating ArrowDown when mobile + showScrollButton but not tall content', async () => {
|
||||
renderWith({ mobile: true, tallContent: false, showScrollButton: true })
|
||||
it('still passes scroll button state when content height is below tall threshold', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: true })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('Scroll to bottom')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('does NOT pass scroll button state when mobile + tall content but no showScrollButton', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: false })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
|
||||
expect(screen.queryByLabelText('Scroll to bottom')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does NOT render floating ArrowDown when mobile + tall content but no showScrollButton', async () => {
|
||||
renderWith({ mobile: true, tallContent: true, showScrollButton: false })
|
||||
it('passes scroll button state on desktop for PromptInput desktop handling', async () => {
|
||||
renderWith({ mobile: false, showScrollButton: true })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('Scroll to bottom')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('does NOT pass scroll button state when prompt has content', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: true, promptContent: true })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
|
||||
expect(screen.queryByLabelText('Scroll to bottom')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does NOT render floating ArrowDown on desktop even with showScrollButton and tall content', async () => {
|
||||
renderWith({ mobile: false, tallContent: true, showScrollButton: true })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
|
||||
expect(screen.queryByLabelText('Scroll to bottom')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clicking floating ArrowDown calls scrollToBottom from useAutoScroll', async () => {
|
||||
renderWith({ mobile: true, tallContent: true, showScrollButton: true })
|
||||
it('clicking PromptInput scroll button calls scrollToBottom from useAutoScroll', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: true })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('Scroll to bottom')).toBeInTheDocument()
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { useModelStore } from '@/stores/modelStore'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { useModelStore, modelExists, modelStorePartialize, modelStoreMigrate } from '@/stores/modelStore'
|
||||
import type { Provider } from '@/api/providers'
|
||||
|
||||
vi.mock('zustand/middleware', async () => {
|
||||
const actual = await vi.importActual('zustand/middleware')
|
||||
return {
|
||||
...actual,
|
||||
persist: (config: any) => config,
|
||||
}
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
function makeProvider(overrides: Partial<Provider>): Provider {
|
||||
@@ -27,8 +29,6 @@ describe('validateAndSyncModel', () => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
recentModels: [],
|
||||
favoriteModels: [],
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
@@ -74,34 +74,21 @@ describe('validateAndSyncModel', () => {
|
||||
expect(useModelStore.getState().model).toBeNull()
|
||||
})
|
||||
|
||||
it('prunes stale recents and favorites, keeps valid entries', () => {
|
||||
it('invalidates stale hydrated model when current model not in providers and no config fallback', () => {
|
||||
const providers = [
|
||||
makeProvider({
|
||||
id: 'anthropic',
|
||||
models: { 'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' } },
|
||||
id: 'openrouter',
|
||||
models: { 'qwen/qwen3-235b-a22b': { id: 'qwen/qwen3-235b-a22b', name: 'Qwen3 235B' } },
|
||||
}),
|
||||
]
|
||||
|
||||
useModelStore.setState({
|
||||
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
recentModels: [
|
||||
{ providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
{ providerID: 'openai', modelID: 'gpt-4o' },
|
||||
],
|
||||
favoriteModels: [
|
||||
{ providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
{ providerID: 'openai', modelID: 'gpt-4o' },
|
||||
],
|
||||
model: { providerID: 'openrouter', modelID: 'qwen/qwen3-35b' },
|
||||
})
|
||||
|
||||
useModelStore.getState().validateAndSyncModel('anthropic/claude-sonnet-4', providers)
|
||||
useModelStore.getState().validateAndSyncModel(undefined, providers)
|
||||
|
||||
expect(useModelStore.getState().recentModels).toEqual([
|
||||
{ providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
])
|
||||
expect(useModelStore.getState().favoriteModels).toEqual([
|
||||
{ providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
])
|
||||
expect(useModelStore.getState().model).toBeNull()
|
||||
})
|
||||
|
||||
it('is idempotent when re-running with same valid state', () => {
|
||||
@@ -114,8 +101,6 @@ describe('validateAndSyncModel', () => {
|
||||
|
||||
useModelStore.setState({
|
||||
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
recentModels: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
|
||||
favoriteModels: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
|
||||
})
|
||||
|
||||
useModelStore.getState().validateAndSyncModel('anthropic/claude-sonnet-4', providers)
|
||||
@@ -134,7 +119,373 @@ describe('validateAndSyncModel', () => {
|
||||
|
||||
expect(updateCount).toBe(0)
|
||||
expect(afterSecond.model).toEqual(afterFirst.model)
|
||||
expect(afterSecond.recentModels).toEqual(afterFirst.recentModels)
|
||||
expect(afterSecond.favoriteModels).toEqual(afterFirst.favoriteModels)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setModel', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('sets the model', () => {
|
||||
const model = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
useModelStore.getState().setModel(model)
|
||||
expect(useModelStore.getState().model).toEqual(model)
|
||||
})
|
||||
|
||||
it('replaces the previous model', () => {
|
||||
useModelStore.setState({ model: { providerID: 'openai', modelID: 'gpt-4o' } })
|
||||
useModelStore.getState().setModel({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
|
||||
expect(useModelStore.getState().model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('setActiveModel', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('sets the active model', () => {
|
||||
const model = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
useModelStore.getState().setActiveModel(model)
|
||||
expect(useModelStore.getState().model).toEqual(model)
|
||||
})
|
||||
})
|
||||
|
||||
describe('agentModels', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('setAgentModel stores model for agent', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
useModelStore.getState().setAgentModel('agent-1', model)
|
||||
expect(useModelStore.getState().agentModels['agent-1']).toEqual(model)
|
||||
})
|
||||
|
||||
it('getAgentModel returns model for agent', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
useModelStore.getState().setAgentModel('agent-1', model)
|
||||
expect(useModelStore.getState().getAgentModel('agent-1')).toEqual(model)
|
||||
})
|
||||
|
||||
it('getAgentModel returns null for unknown agent', () => {
|
||||
expect(useModelStore.getState().getAgentModel('unknown')).toBeNull()
|
||||
})
|
||||
|
||||
it('setAgentModel replaces existing model for same agent', () => {
|
||||
useModelStore.getState().setAgentModel('agent-1', { providerID: 'openai', modelID: 'gpt-4o' })
|
||||
useModelStore.getState().setAgentModel('agent-1', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
|
||||
expect(useModelStore.getState().agentModels['agent-1']).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('syncFromConfig', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('sets model and lastConfigModel from valid config string', () => {
|
||||
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4')
|
||||
expect(useModelStore.getState().model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
|
||||
expect(useModelStore.getState().lastConfigModel).toBe('anthropic/claude-sonnet-4')
|
||||
})
|
||||
|
||||
it('does nothing when same config already synced', () => {
|
||||
useModelStore.setState({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' }, lastConfigModel: 'anthropic/claude-sonnet-4' })
|
||||
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4')
|
||||
|
||||
expect(useModelStore.getState().lastConfigModel).toBe('anthropic/claude-sonnet-4')
|
||||
})
|
||||
|
||||
it('updates when force is true even if same config', () => {
|
||||
useModelStore.setState({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' }, lastConfigModel: 'anthropic/claude-sonnet-4' })
|
||||
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4', true)
|
||||
|
||||
expect(useModelStore.getState().lastConfigModel).toBe('anthropic/claude-sonnet-4')
|
||||
})
|
||||
|
||||
it('handles invalid config string gracefully', () => {
|
||||
useModelStore.getState().syncFromConfig('invalid')
|
||||
expect(useModelStore.getState().model).toBeNull()
|
||||
expect(useModelStore.getState().lastConfigModel).toBe('invalid')
|
||||
})
|
||||
|
||||
it('handles undefined config string', () => {
|
||||
useModelStore.getState().syncFromConfig(undefined)
|
||||
expect(useModelStore.getState().lastConfigModel).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getModelString', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when no model selected', () => {
|
||||
expect(useModelStore.getState().getModelString()).toBeNull()
|
||||
})
|
||||
|
||||
it('returns providerID/modelID string when model is set', () => {
|
||||
useModelStore.setState({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' } })
|
||||
expect(useModelStore.getState().getModelString()).toBe('anthropic/claude-sonnet-4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('variants', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('setVariant stores variant for model', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
|
||||
expect(useModelStore.getState().variants['openai/gpt-4o']).toBe('gpt-4o-2024-05-13')
|
||||
})
|
||||
|
||||
it('getVariant returns variant for model', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
|
||||
expect(useModelStore.getState().getVariant(model)).toBe('gpt-4o-2024-05-13')
|
||||
})
|
||||
|
||||
it('getVariant returns undefined when no variant set', () => {
|
||||
expect(useModelStore.getState().getVariant({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })).toBeUndefined()
|
||||
})
|
||||
|
||||
it('clearVariant removes variant for model', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
|
||||
useModelStore.getState().clearVariant(model)
|
||||
expect(useModelStore.getState().variants['openai/gpt-4o']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('clearVariant is idempotent', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
expect(() => useModelStore.getState().clearVariant(model)).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('syncModelState', () => {
|
||||
beforeEach(() => {
|
||||
useModelStore.setState({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('merges variants from model state', () => {
|
||||
useModelStore.getState().syncModelState({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
variant: { 'anthropic/claude-sonnet-4': 'claude-sonnet-4-20250514' },
|
||||
})
|
||||
|
||||
expect(useModelStore.getState().variants['anthropic/claude-sonnet-4']).toBe('claude-sonnet-4-20250514')
|
||||
})
|
||||
|
||||
it('existing store variants take precedence over incoming variants', () => {
|
||||
useModelStore.setState({ variants: { 'anthropic/claude-sonnet-4': 'existing-variant' } })
|
||||
|
||||
useModelStore.getState().syncModelState({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
variant: { 'anthropic/claude-sonnet-4': 'incoming-variant' },
|
||||
})
|
||||
|
||||
expect(useModelStore.getState().variants['anthropic/claude-sonnet-4']).toBe('existing-variant')
|
||||
})
|
||||
|
||||
it('ignores recent and favorite fields from model state', () => {
|
||||
useModelStore.getState().syncModelState({
|
||||
recent: [{ providerID: 'openai', modelID: 'gpt-4o' }],
|
||||
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
|
||||
variant: {},
|
||||
})
|
||||
|
||||
const state = useModelStore.getState() as Record<string, unknown>
|
||||
expect(state).not.toHaveProperty('recentModels')
|
||||
expect(state).not.toHaveProperty('favoriteModels')
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelExists', () => {
|
||||
const providers = [
|
||||
makeProvider({
|
||||
id: 'openai',
|
||||
models: { 'gpt-4o': { id: 'gpt-4o', name: 'GPT-4o' } },
|
||||
}),
|
||||
makeProvider({
|
||||
id: 'anthropic',
|
||||
models: { 'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' } },
|
||||
}),
|
||||
]
|
||||
|
||||
it('returns true when provider and model exist', () => {
|
||||
expect(modelExists({ providerID: 'openai', modelID: 'gpt-4o' }, providers)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when provider does not exist', () => {
|
||||
expect(modelExists({ providerID: 'nonexistent', modelID: 'gpt-4o' }, providers)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when model does not exist in provider', () => {
|
||||
expect(modelExists({ providerID: 'openai', modelID: 'nonexistent' }, providers)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when model is null', () => {
|
||||
expect(modelExists(null, providers)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when providers list is empty', () => {
|
||||
expect(modelExists({ providerID: 'openai', modelID: 'gpt-4o' }, [])).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelStorePartialize', () => {
|
||||
it('returns only model and agentModels', () => {
|
||||
const result = modelStorePartialize({
|
||||
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
agentModels: { 'agent-1': { providerID: 'openai', modelID: 'gpt-4o' } },
|
||||
variants: { 'anthropic/claude-sonnet-4': 'some-variant' },
|
||||
lastConfigModel: 'anthropic/claude-sonnet-4',
|
||||
} as Parameters<typeof modelStorePartialize>[0])
|
||||
|
||||
expect(result).toEqual({
|
||||
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
agentModels: { 'agent-1': { providerID: 'openai', modelID: 'gpt-4o' } },
|
||||
})
|
||||
expect(result).not.toHaveProperty('variants')
|
||||
expect(result).not.toHaveProperty('lastConfigModel')
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelStoreMigrate', () => {
|
||||
it('strips legacy recentModels, favoriteModels, and variants keys from flat state (Zustand v5 call shape)', () => {
|
||||
const legacy = {
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
recentModels: [{ providerID: 'old', modelID: 'old' }],
|
||||
favoriteModels: [{ providerID: 'old', modelID: 'old' }],
|
||||
variants: { 'old/old': 'v1' },
|
||||
}
|
||||
|
||||
const migrated = modelStoreMigrate(legacy)
|
||||
|
||||
expect(migrated).toEqual({
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves model and agentModels during migration of flat state', () => {
|
||||
const legacy = {
|
||||
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
agentModels: { 'agent-1': { providerID: 'openai', modelID: 'gpt-4o' } },
|
||||
recentModels: [{ providerID: 'openai', modelID: 'gpt-4o' }],
|
||||
favoriteModels: [],
|
||||
variants: {},
|
||||
}
|
||||
|
||||
const migrated = modelStoreMigrate(legacy)
|
||||
|
||||
expect(migrated).toEqual({
|
||||
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
|
||||
agentModels: { 'agent-1': { providerID: 'openai', modelID: 'gpt-4o' } },
|
||||
})
|
||||
})
|
||||
|
||||
it('handles null/undefined input gracefully', () => {
|
||||
expect(modelStoreMigrate(null)).toBeNull()
|
||||
expect(modelStoreMigrate(undefined)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('also strips legacy keys from nested Zustand state envelope', () => {
|
||||
const legacy = {
|
||||
state: {
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
recentModels: [{ providerID: 'old', modelID: 'old' }],
|
||||
favoriteModels: [{ providerID: 'old', modelID: 'old' }],
|
||||
variants: { 'old/old': 'v1' },
|
||||
},
|
||||
version: 0,
|
||||
}
|
||||
|
||||
const migrated = modelStoreMigrate(legacy)
|
||||
|
||||
expect(migrated).toEqual({
|
||||
state: {
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
},
|
||||
version: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns non-object input unchanged', () => {
|
||||
expect(modelStoreMigrate('string')).toBe('string')
|
||||
expect(modelStoreMigrate(42)).toBe(42)
|
||||
})
|
||||
|
||||
it('handles state without legacy keys (new users)', () => {
|
||||
const clean = {
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
}
|
||||
|
||||
const migrated = modelStoreMigrate(clean)
|
||||
|
||||
expect(migrated).toEqual(clean)
|
||||
})
|
||||
|
||||
it('migrate function is wired through persist.getOptions()', () => {
|
||||
const legacy = {
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
recentModels: [{ providerID: 'old', modelID: 'old' }],
|
||||
favoriteModels: [{ providerID: 'old', modelID: 'old' }],
|
||||
variants: { 'old/old': 'v1' },
|
||||
}
|
||||
|
||||
const options = useModelStore.persist.getOptions()
|
||||
const migrated = options.migrate?.(legacy, 0)
|
||||
|
||||
expect(migrated).toEqual({
|
||||
model: { providerID: 'p', modelID: 'm' },
|
||||
agentModels: {},
|
||||
})
|
||||
})
|
||||
})
|
||||
+125
-157
@@ -10,8 +10,6 @@ export interface ModelSelection {
|
||||
interface ModelStore {
|
||||
model: ModelSelection | null
|
||||
agentModels: Record<string, ModelSelection>
|
||||
recentModels: ModelSelection[]
|
||||
favoriteModels: ModelSelection[]
|
||||
variants: Record<string, string | undefined>
|
||||
lastConfigModel: string | undefined
|
||||
|
||||
@@ -20,7 +18,6 @@ interface ModelStore {
|
||||
setAgentModel: (agent: string, model: ModelSelection) => void
|
||||
getAgentModel: (agent: string) => ModelSelection | null
|
||||
syncModelState: (state: { recent: ModelSelection[], favorite: ModelSelection[], variant: Record<string, string | undefined> }) => void
|
||||
toggleFavorite: (model: ModelSelection) => void
|
||||
syncFromConfig: (configModel: string | undefined, force?: boolean) => void
|
||||
validateAndSyncModel: (configModel: string | undefined, providers?: Provider[]) => void
|
||||
getModelString: () => string | null
|
||||
@@ -29,7 +26,12 @@ interface ModelStore {
|
||||
clearVariant: (model: ModelSelection) => void
|
||||
}
|
||||
|
||||
const MAX_RECENT_MODELS = 10
|
||||
export function modelExists(model: ModelSelection | null, providers: Provider[]): boolean {
|
||||
if (!model) return false
|
||||
return providers.some(
|
||||
(p) => p.id === model.providerID && p.models && model.modelID in p.models
|
||||
)
|
||||
}
|
||||
|
||||
function parseModelString(model: string): ModelSelection | null {
|
||||
const [providerID, ...rest] = model.split('/')
|
||||
@@ -38,182 +40,148 @@ function parseModelString(model: string): ModelSelection | null {
|
||||
return { providerID, modelID }
|
||||
}
|
||||
|
||||
export function modelStorePartialize(state: ModelStore): { model: ModelStore['model']; agentModels: ModelStore['agentModels'] } {
|
||||
return {
|
||||
model: state.model,
|
||||
agentModels: state.agentModels,
|
||||
}
|
||||
}
|
||||
|
||||
function stripLegacyKeys(obj: Record<string, unknown>): void {
|
||||
delete obj.recentModels
|
||||
delete obj.favoriteModels
|
||||
delete obj.variants
|
||||
}
|
||||
|
||||
export function modelStoreMigrate(persistedState: unknown): unknown {
|
||||
if (!persistedState || typeof persistedState !== 'object') return persistedState
|
||||
const next = { ...persistedState } as Record<string, unknown>
|
||||
stripLegacyKeys(next)
|
||||
if (next.state && typeof next.state === 'object' && !Array.isArray(next.state)) {
|
||||
const state = { ...(next.state as Record<string, unknown>) }
|
||||
stripLegacyKeys(state)
|
||||
next.state = state
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
export const useModelStore = create<ModelStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
model: null,
|
||||
agentModels: {},
|
||||
recentModels: [],
|
||||
favoriteModels: [],
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
model: null,
|
||||
agentModels: {},
|
||||
variants: {},
|
||||
lastConfigModel: undefined,
|
||||
|
||||
setModel: (model: ModelSelection) => {
|
||||
set((state) => {
|
||||
const newRecent = [
|
||||
model,
|
||||
...state.recentModels.filter(
|
||||
(m) => !(m.providerID === model.providerID && m.modelID === model.modelID)
|
||||
),
|
||||
].slice(0, MAX_RECENT_MODELS)
|
||||
setModel: (model: ModelSelection) => {
|
||||
set({ model })
|
||||
},
|
||||
|
||||
return {
|
||||
model,
|
||||
recentModels: newRecent,
|
||||
}
|
||||
})
|
||||
},
|
||||
setActiveModel: (model: ModelSelection) => {
|
||||
set({ model })
|
||||
},
|
||||
|
||||
setActiveModel: (model: ModelSelection) => {
|
||||
set({ model })
|
||||
},
|
||||
setAgentModel: (agent: string, model: ModelSelection) => {
|
||||
set((state) => ({
|
||||
agentModels: {
|
||||
...state.agentModels,
|
||||
[agent]: model,
|
||||
},
|
||||
}))
|
||||
},
|
||||
|
||||
setAgentModel: (agent: string, model: ModelSelection) => {
|
||||
set((state) => ({
|
||||
agentModels: {
|
||||
...state.agentModels,
|
||||
[agent]: model,
|
||||
},
|
||||
}))
|
||||
},
|
||||
getAgentModel: (agent: string) => {
|
||||
const state = get()
|
||||
return state.agentModels[agent] ?? null
|
||||
},
|
||||
|
||||
getAgentModel: (agent: string) => {
|
||||
const state = get()
|
||||
return state.agentModels[agent] ?? null
|
||||
},
|
||||
syncModelState: (modelState) => {
|
||||
set((state) => ({
|
||||
variants: {
|
||||
...modelState.variant,
|
||||
...state.variants,
|
||||
},
|
||||
}))
|
||||
},
|
||||
|
||||
syncModelState: (modelState) => {
|
||||
set((state) => ({
|
||||
recentModels: modelState.recent,
|
||||
favoriteModels: modelState.favorite,
|
||||
variants: {
|
||||
...modelState.variant,
|
||||
...state.variants,
|
||||
},
|
||||
}))
|
||||
},
|
||||
syncFromConfig: (configModel: string | undefined, force = false) => {
|
||||
const state = get()
|
||||
if (!force && state.lastConfigModel === configModel) return
|
||||
|
||||
toggleFavorite: (model: ModelSelection) => {
|
||||
set((state) => {
|
||||
const exists = state.favoriteModels.some(
|
||||
(favorite) => favorite.providerID === model.providerID && favorite.modelID === model.modelID
|
||||
)
|
||||
|
||||
return {
|
||||
favoriteModels: exists
|
||||
? state.favoriteModels.filter((favorite) => favorite.providerID !== model.providerID || favorite.modelID !== model.modelID)
|
||||
: [model, ...state.favoriteModels],
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
syncFromConfig: (configModel: string | undefined, force = false) => {
|
||||
const state = get()
|
||||
if (!force && state.lastConfigModel === configModel) return
|
||||
|
||||
if (configModel) {
|
||||
const parsed = parseModelString(configModel)
|
||||
if (parsed) {
|
||||
const newRecent = [
|
||||
parsed,
|
||||
...state.recentModels.filter(
|
||||
(m) => !(m.providerID === parsed.providerID && m.modelID === parsed.modelID)
|
||||
),
|
||||
].slice(0, MAX_RECENT_MODELS)
|
||||
|
||||
set({ model: parsed, lastConfigModel: configModel, recentModels: newRecent })
|
||||
return
|
||||
}
|
||||
}
|
||||
set({ lastConfigModel: configModel })
|
||||
},
|
||||
|
||||
validateAndSyncModel: (configModel: string | undefined, providers?: Provider[]) => {
|
||||
if (!providers) {
|
||||
if (configModel) {
|
||||
get().syncFromConfig(configModel)
|
||||
}
|
||||
if (configModel) {
|
||||
const parsed = parseModelString(configModel)
|
||||
if (parsed) {
|
||||
set({ model: parsed, lastConfigModel: configModel })
|
||||
return
|
||||
}
|
||||
}
|
||||
set({ lastConfigModel: configModel })
|
||||
},
|
||||
|
||||
const state = get()
|
||||
|
||||
const modelExists = (model: ModelSelection) =>
|
||||
providers.some(
|
||||
(p) => p.id === model.providerID && p.models && model.modelID in p.models
|
||||
)
|
||||
|
||||
const currentModelExists = state.model ? modelExists(state.model) : false
|
||||
|
||||
const cleanedRecentModels = state.recentModels.filter(modelExists)
|
||||
const cleanedFavoriteModels = state.favoriteModels.filter(modelExists)
|
||||
|
||||
if (cleanedRecentModels.length !== state.recentModels.length) {
|
||||
set({ recentModels: cleanedRecentModels })
|
||||
validateAndSyncModel: (configModel: string | undefined, providers?: Provider[]) => {
|
||||
if (!providers) {
|
||||
if (configModel) {
|
||||
get().syncFromConfig(configModel)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (cleanedFavoriteModels.length !== state.favoriteModels.length) {
|
||||
set({ favoriteModels: cleanedFavoriteModels })
|
||||
const state = get()
|
||||
|
||||
const currentModelExists = state.model ? modelExists(state.model, providers) : false
|
||||
|
||||
if (!currentModelExists) {
|
||||
const parsedConfig = configModel ? parseModelString(configModel) : null
|
||||
const configIsValid = parsedConfig ? modelExists(parsedConfig, providers) : false
|
||||
|
||||
if (configIsValid && configModel) {
|
||||
get().syncFromConfig(configModel, true)
|
||||
} else {
|
||||
set({ model: null, lastConfigModel: configModel })
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
if (!currentModelExists) {
|
||||
const parsedConfig = configModel ? parseModelString(configModel) : null
|
||||
const configIsValid = parsedConfig
|
||||
? providers.some(p => p.id === parsedConfig.providerID && p.models && parsedConfig.modelID in p.models)
|
||||
: false
|
||||
getModelString: () => {
|
||||
const { model } = get()
|
||||
if (!model) return null
|
||||
return `${model.providerID}/${model.modelID}`
|
||||
},
|
||||
|
||||
if (configIsValid && configModel) {
|
||||
get().syncFromConfig(configModel, true)
|
||||
} else {
|
||||
set({ model: null, lastConfigModel: configModel })
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
getModelString: () => {
|
||||
const { model } = get()
|
||||
if (!model) return null
|
||||
return `${model.providerID}/${model.modelID}`
|
||||
},
|
||||
|
||||
setVariant: (model: ModelSelection, variant: string | undefined) => {
|
||||
set((state) => {
|
||||
const key = `${model.providerID}/${model.modelID}`
|
||||
return {
|
||||
variants: {
|
||||
...state.variants,
|
||||
[key]: variant,
|
||||
},
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
getVariant: (model: ModelSelection) => {
|
||||
const state = get()
|
||||
setVariant: (model: ModelSelection, variant: string | undefined) => {
|
||||
set((state) => {
|
||||
const key = `${model.providerID}/${model.modelID}`
|
||||
return state.variants[key]
|
||||
},
|
||||
return {
|
||||
variants: {
|
||||
...state.variants,
|
||||
[key]: variant,
|
||||
},
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
clearVariant: (model: ModelSelection) => {
|
||||
set((state) => {
|
||||
const key = `${model.providerID}/${model.modelID}`
|
||||
const newVariants = { ...state.variants }
|
||||
delete newVariants[key]
|
||||
return {
|
||||
variants: newVariants,
|
||||
}
|
||||
})
|
||||
},
|
||||
getVariant: (model: ModelSelection) => {
|
||||
const state = get()
|
||||
const key = `${model.providerID}/${model.modelID}`
|
||||
return state.variants[key]
|
||||
},
|
||||
|
||||
clearVariant: (model: ModelSelection) => {
|
||||
set((state) => {
|
||||
const key = `${model.providerID}/${model.modelID}`
|
||||
const newVariants = { ...state.variants }
|
||||
delete newVariants[key]
|
||||
return {
|
||||
variants: newVariants,
|
||||
}
|
||||
})
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'opencode-model-selection',
|
||||
partialize: (state) => ({
|
||||
model: state.model,
|
||||
agentModels: state.agentModels,
|
||||
recentModels: state.recentModels,
|
||||
favoriteModels: state.favoriteModels,
|
||||
variants: state.variants,
|
||||
}),
|
||||
version: 2,
|
||||
migrate: modelStoreMigrate,
|
||||
partialize: modelStorePartialize,
|
||||
}
|
||||
)
|
||||
)
|
||||
+1
-2
@@ -39,7 +39,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"dotenv": "^17.2.3"
|
||||
"class-variance-authority": "^0.7.1"
|
||||
}
|
||||
}
|
||||
Generated
+2
-111
@@ -14,9 +14,6 @@ importers:
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
dotenv:
|
||||
specifier: ^17.2.3
|
||||
version: 17.2.3
|
||||
devDependencies:
|
||||
concurrently:
|
||||
specifier: ^9.1.0
|
||||
@@ -42,9 +39,6 @@ importers:
|
||||
croner:
|
||||
specifier: ^10.0.1
|
||||
version: 10.0.1
|
||||
dotenv:
|
||||
specifier: ^17.2.3
|
||||
version: 17.2.3
|
||||
eventsource:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0
|
||||
@@ -118,9 +112,6 @@ importers:
|
||||
'@hookform/resolvers':
|
||||
specifier: ^5.2.2
|
||||
version: 5.2.2(react-hook-form@7.69.0(react@19.2.3))
|
||||
'@monaco-editor/react':
|
||||
specifier: ^4.7.0
|
||||
version: 4.7.0(monaco-editor@0.55.1)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@opencode-manager/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
@@ -166,9 +157,6 @@ importers:
|
||||
clsx:
|
||||
specifier: ^2.1.1
|
||||
version: 2.1.1
|
||||
cmdk:
|
||||
specifier: ^1.1.1
|
||||
version: 1.1.1(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
cronstrue:
|
||||
specifier: ^3.13.0
|
||||
version: 3.13.0
|
||||
@@ -181,9 +169,6 @@ importers:
|
||||
highlight.js:
|
||||
specifier: ^11.11.1
|
||||
version: 11.11.1
|
||||
jsonc-parser:
|
||||
specifier: ^3.3.1
|
||||
version: 3.3.1
|
||||
lucide-react:
|
||||
specifier: ^0.546.0
|
||||
version: 0.546.0(react@19.2.3)
|
||||
@@ -251,9 +236,6 @@ importers:
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^5.0.4
|
||||
version: 5.1.2(vite@7.3.0(@types/node@24.10.4)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0))
|
||||
autoprefixer:
|
||||
specifier: ^10.4.21
|
||||
version: 10.4.23(postcss@8.5.6)
|
||||
eslint:
|
||||
specifier: ^9.39.1
|
||||
version: 9.39.2(jiti@2.6.1)
|
||||
@@ -829,16 +811,6 @@ packages:
|
||||
'@mermaid-js/parser@0.6.3':
|
||||
resolution: {integrity: sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==}
|
||||
|
||||
'@monaco-editor/loader@1.7.0':
|
||||
resolution: {integrity: sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==}
|
||||
|
||||
'@monaco-editor/react@4.7.0':
|
||||
resolution: {integrity: sha512-cyzXQCtO47ydzxpQtCGSQGOC8Gk3ZUeBXFAxD+CWXYFo5OqZyZUonFl0DwUlTyAfRHntBfw2p3w4s9R6oe1eCA==}
|
||||
peerDependencies:
|
||||
monaco-editor: '>= 0.25.0 < 1'
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
|
||||
'@noble/ciphers@2.1.1':
|
||||
resolution: {integrity: sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==}
|
||||
engines: {node: '>= 20.19.0'}
|
||||
@@ -1946,13 +1918,6 @@ packages:
|
||||
async@3.2.6:
|
||||
resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}
|
||||
|
||||
autoprefixer@10.4.23:
|
||||
resolution: {integrity: sha512-YYTXSFulfwytnjAPlw8QHncHJmlvFKtczb8InXaAx9Q0LbfDnfEYDE55omerIJKihhmU61Ft+cAOSzQVaBUmeA==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
postcss: ^8.1.0
|
||||
|
||||
b4a@1.7.3:
|
||||
resolution: {integrity: sha512-5Q2mfq2WfGuFp3uS//0s6baOJLMoVduPYVeNmDYxu5OUA1/cBfvr2RIS7vi62LdNj/urk1hfmj867I3qt6uZ7Q==}
|
||||
peerDependencies:
|
||||
@@ -2169,12 +2134,6 @@ packages:
|
||||
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
cmdk@1.1.1:
|
||||
resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}
|
||||
peerDependencies:
|
||||
react: ^18 || ^19 || ^19.0.0-rc
|
||||
react-dom: ^18 || ^19 || ^19.0.0-rc
|
||||
|
||||
color-convert@2.0.1:
|
||||
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
|
||||
engines: {node: '>=7.0.0'}
|
||||
@@ -2491,9 +2450,6 @@ packages:
|
||||
dom-accessibility-api@0.6.3:
|
||||
resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
|
||||
|
||||
dompurify@3.2.7:
|
||||
resolution: {integrity: sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw==}
|
||||
|
||||
dompurify@3.3.1:
|
||||
resolution: {integrity: sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==}
|
||||
|
||||
@@ -2685,9 +2641,6 @@ packages:
|
||||
resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
fraction.js@5.3.4:
|
||||
resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
|
||||
|
||||
fs-constants@1.0.0:
|
||||
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
|
||||
|
||||
@@ -3127,11 +3080,6 @@ packages:
|
||||
markdown-table@3.0.4:
|
||||
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
|
||||
|
||||
marked@14.0.0:
|
||||
resolution: {integrity: sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==}
|
||||
engines: {node: '>= 18'}
|
||||
hasBin: true
|
||||
|
||||
marked@16.4.2:
|
||||
resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==}
|
||||
engines: {node: '>= 20'}
|
||||
@@ -3311,9 +3259,6 @@ packages:
|
||||
mlly@1.8.0:
|
||||
resolution: {integrity: sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==}
|
||||
|
||||
monaco-editor@0.55.1:
|
||||
resolution: {integrity: sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==}
|
||||
|
||||
mrmime@2.0.1:
|
||||
resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -3433,9 +3378,6 @@ packages:
|
||||
points-on-path@0.2.1:
|
||||
resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==}
|
||||
|
||||
postcss-value-parser@4.2.0:
|
||||
resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}
|
||||
|
||||
postcss@8.5.6:
|
||||
resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
@@ -3721,9 +3663,6 @@ packages:
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
state-local@1.0.7:
|
||||
resolution: {integrity: sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==}
|
||||
|
||||
std-env@3.10.0:
|
||||
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
|
||||
|
||||
@@ -4688,17 +4627,6 @@ snapshots:
|
||||
dependencies:
|
||||
langium: 3.3.1
|
||||
|
||||
'@monaco-editor/loader@1.7.0':
|
||||
dependencies:
|
||||
state-local: 1.0.7
|
||||
|
||||
'@monaco-editor/react@4.7.0(monaco-editor@0.55.1)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
|
||||
dependencies:
|
||||
'@monaco-editor/loader': 1.7.0
|
||||
monaco-editor: 0.55.1
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3(react@19.2.3)
|
||||
|
||||
'@noble/ciphers@2.1.1': {}
|
||||
|
||||
'@noble/hashes@2.0.1': {}
|
||||
@@ -5934,15 +5862,6 @@ snapshots:
|
||||
|
||||
async@3.2.6: {}
|
||||
|
||||
autoprefixer@10.4.23(postcss@8.5.6):
|
||||
dependencies:
|
||||
browserslist: 4.28.1
|
||||
caniuse-lite: 1.0.30001762
|
||||
fraction.js: 5.3.4
|
||||
picocolors: 1.1.1
|
||||
postcss: 8.5.6
|
||||
postcss-value-parser: 4.2.0
|
||||
|
||||
b4a@1.7.3: {}
|
||||
|
||||
bail@2.0.2: {}
|
||||
@@ -6120,18 +6039,6 @@ snapshots:
|
||||
|
||||
clsx@2.1.1: {}
|
||||
|
||||
cmdk@1.1.1(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3):
|
||||
dependencies:
|
||||
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3)
|
||||
'@radix-ui/react-dialog': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@radix-ui/react-id': 1.1.1(@types/react@19.2.7)(react@19.2.3)
|
||||
'@radix-ui/react-primitive': 2.1.4(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3(react@19.2.3)
|
||||
transitivePeerDependencies:
|
||||
- '@types/react'
|
||||
- '@types/react-dom'
|
||||
|
||||
color-convert@2.0.1:
|
||||
dependencies:
|
||||
color-name: 1.1.4
|
||||
@@ -6454,15 +6361,12 @@ snapshots:
|
||||
|
||||
dom-accessibility-api@0.6.3: {}
|
||||
|
||||
dompurify@3.2.7:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
dompurify@3.3.1:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
dotenv@17.2.3: {}
|
||||
dotenv@17.2.3:
|
||||
optional: true
|
||||
|
||||
eastasianwidth@0.2.0: {}
|
||||
|
||||
@@ -6667,8 +6571,6 @@ snapshots:
|
||||
cross-spawn: 7.0.6
|
||||
signal-exit: 4.1.0
|
||||
|
||||
fraction.js@5.3.4: {}
|
||||
|
||||
fs-constants@1.0.0: {}
|
||||
|
||||
fsevents@2.3.3:
|
||||
@@ -7111,8 +7013,6 @@ snapshots:
|
||||
|
||||
markdown-table@3.0.4: {}
|
||||
|
||||
marked@14.0.0: {}
|
||||
|
||||
marked@16.4.2: {}
|
||||
|
||||
mdast-util-find-and-replace@3.0.2:
|
||||
@@ -7519,11 +7419,6 @@ snapshots:
|
||||
pkg-types: 1.3.1
|
||||
ufo: 1.6.1
|
||||
|
||||
monaco-editor@0.55.1:
|
||||
dependencies:
|
||||
dompurify: 3.2.7
|
||||
marked: 14.0.0
|
||||
|
||||
mrmime@2.0.1: {}
|
||||
|
||||
ms@2.1.3: {}
|
||||
@@ -7641,8 +7536,6 @@ snapshots:
|
||||
path-data-parser: 0.1.0
|
||||
points-on-curve: 0.2.0
|
||||
|
||||
postcss-value-parser@4.2.0: {}
|
||||
|
||||
postcss@8.5.6:
|
||||
dependencies:
|
||||
nanoid: 3.3.11
|
||||
@@ -7985,8 +7878,6 @@ snapshots:
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
state-local@1.0.7: {}
|
||||
|
||||
std-env@3.10.0: {}
|
||||
|
||||
streamx@2.23.0:
|
||||
|
||||
@@ -278,6 +278,12 @@ export const ProviderConfigSchema = z.object({
|
||||
export type ProviderSource = z.infer<typeof ProviderSourceSchema>;
|
||||
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>;
|
||||
|
||||
export const OpenCodePluginOptionsSchema = z.record(z.string(), z.unknown());
|
||||
export const OpenCodePluginSpecSchema = z.union([
|
||||
z.string(),
|
||||
z.tuple([z.string(), OpenCodePluginOptionsSchema]),
|
||||
]);
|
||||
|
||||
export const OpenCodeConfigSchema = z.object({
|
||||
$schema: z.string().optional(),
|
||||
theme: z.string().optional(),
|
||||
@@ -295,7 +301,7 @@ export const OpenCodeConfigSchema = z.object({
|
||||
instructions: z.array(z.string()).optional(),
|
||||
disabled_providers: z.array(z.string()).optional(),
|
||||
share: z.enum(["manual", "auto", "disabled"]).optional(),
|
||||
plugin: z.array(z.string()).optional(),
|
||||
plugin: z.array(OpenCodePluginSpecSchema).optional(),
|
||||
skills: z.object({
|
||||
paths: z.array(z.string()).optional(),
|
||||
urls: z.array(z.string()).optional(),
|
||||
|
||||
Reference in new issue
Block a user