Fix eslint (#46)

* Fix mobile image upload and paste with improved file type handling

* Replace older sessions header with separator line

* Add ESLint no-console rules and fix lint errors

- Add eslint configuration for backend with no-console rule
- Add reusable error type guard utility
- Replace all error: any with error: unknown and type guards across backend
- Update logger to use console.warn/console.error only
- Remove unused variables and dead code functions
- Fix regex escape characters
- Update AGENTS.md with lint commands and requirements
This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-03 15:19:28 -05:00
1 parent c9bf962ac0
commit 8166044d6e
23 files changed
+642 -334

No files matched your search

+5 -1
View File
@@ -10,11 +10,14 @@
- `cd backend && bun test <filename>` - Run single test file
- `cd backend && vitest --ui` - Test UI with coverage
- `cd backend && vitest --coverage` - Coverage report (80% threshold)
- `cd frontend && npm run lint` - Frontend linting
- `pnpm lint` - Lint both backend and frontend
- `pnpm lint:backend` - Backend linting
- `pnpm lint:frontend` - Frontend linting
## Code Style
- No comments, self-documenting code only
- No console logs (use Bun's logger or proper error handling)
- Strict TypeScript everywhere, proper typing required
- Named imports only: `import { Hono } from 'hono'`, `import { useState } from 'react'`
@@ -41,3 +44,4 @@
- Use shared types from workspace package (@opencode-manager/shared)
- OpenCode server runs on port 5551, backend API on port 5001
- Prefer pnpm over npm for all package management
- Run `pnpm lint` after completing tasks to ensure code quality
+28
View File
@@ -0,0 +1,28 @@
import js from '@eslint/js'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist', '.env*', 'coverage', 'src/utils/logger.ts']),
{
files: ['**/*.ts'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
],
languageOptions: {
ecmaVersion: 2022,
globals: {
process: 'readonly',
Buffer: 'readonly',
console: 'readonly',
},
parserOptions: {
project: true,
},
},
rules: {
'no-console': ['warn', { allow: ['warn', 'error'] }],
},
},
])
+6 -1
View File
@@ -9,7 +9,9 @@
"build": "bun build src/index.ts --outdir=dist --target=bun",
"test": "vitest",
"test:ui": "vitest --ui",
"test:watch": "vitest --watch"
"test:watch": "vitest --watch",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix"
},
"dependencies": {
"@hono/node-server": "^1.19.5",
@@ -21,10 +23,13 @@
"zod": "^4.1.12"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@types/archiver": "^7.0.0",
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "latest",
"@vitest/ui": "^3.2.4",
"eslint": "^9.39.1",
"typescript-eslint": "^8.45.0",
"vitest": "^3.2.4"
},
"peerDependencies": {
+16 -4
View File
@@ -1,11 +1,20 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
interface ColumnInfo {
cid: number
name: string
type: string
notnull: number
dflt_value: unknown
pk: number
}
export function runMigrations(db: Database): void {
try {
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as any[]
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as ColumnInfo[]
const repoUrlColumn = tableInfo.find((col: any) => col.name === 'repo_url')
const repoUrlColumn = tableInfo.find((col: ColumnInfo) => col.name === 'repo_url')
if (repoUrlColumn && repoUrlColumn.notnull === 1) {
logger.info('Migrating repos table to allow nullable repo_url for local repos')
db.run('BEGIN TRANSACTION')
@@ -26,7 +35,7 @@ export function runMigrations(db: Database): void {
)
`)
const existingColumns = tableInfo.map((col: any) => col.name)
const existingColumns = tableInfo.map((col: ColumnInfo) => col.name)
const columnsToCopy = ['id', 'repo_url', 'local_path', 'branch', 'default_branch', 'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name', 'is_worktree', 'is_local']
.filter(col => existingColumns.includes(col))
@@ -107,7 +116,10 @@ export function runMigrations(db: Database): void {
}
try {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as any[]
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
id: number
local_path: string
}>
if (repos.length > 0) {
logger.info(`Migrating ${repos.length} repos to remove 'repos/' prefix from local_path`)
const updateStmt = db.prepare("UPDATE repos SET local_path = ? WHERE id = ?")
+5 -3
View File
@@ -1,6 +1,7 @@
import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { getErrorMessage } from '../utils/error-utils'
import path from 'path'
export interface RepoRow {
@@ -67,8 +68,9 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo {
throw new Error(`Failed to retrieve newly created repo with id ${result.lastInsertRowid}`)
}
return newRepo
} catch (error: any) {
if (error.message?.includes('UNIQUE constraint failed') || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
} catch (error: unknown) {
const errorMessage = getErrorMessage(error)
if (errorMessage.includes('UNIQUE constraint failed') || (error && typeof error === 'object' && 'code' in error && error.code === 'SQLITE_CONSTRAINT_UNIQUE')) {
const conflictRepo = repo.isLocal
? getRepoByLocalPath(db, normalizedPath)
: getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch)
@@ -81,7 +83,7 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo {
throw new Error(`Repository with ${identifier} already exists but could not be retrieved. This may indicate database corruption.`)
}
throw new Error(`Failed to create repository: ${error.message}`)
throw new Error(`Failed to create repository: ${errorMessage}`)
}
}
+1 -1
View File
@@ -225,7 +225,7 @@ try {
app.route('/api/repos', createRepoRoutes(db))
app.route('/api/settings', createSettingsRoutes(db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/files', createFileRoutes(db))
app.route('/api/files', createFileRoutes())
app.route('/api/providers', createProvidersRoutes())
app.route('/api/oauth', createOAuthRoutes())
app.route('/api/tts', createTTSRoutes(db))
+13 -12
View File
@@ -1,9 +1,10 @@
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import * as fileService from '../services/files'
import type { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
export function createFileRoutes(_database: Database) {
export function createFileRoutes() {
const app = new Hono()
app.get('/*', async (c) => {
@@ -50,9 +51,9 @@ export function createFileRoutes(_database: Database) {
}
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get file:', error)
return c.json({ error: error.message || 'Failed to get file' }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) || 'Failed to get file' }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -69,9 +70,9 @@ export function createFileRoutes(_database: Database) {
const relativePath = body.relativePath as string | undefined
const result = await fileService.uploadFile(path, file, relativePath)
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to upload file:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -82,9 +83,9 @@ export function createFileRoutes(_database: Database) {
const result = await fileService.createFileOrFolder(path, body)
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create file/folder:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -94,9 +95,9 @@ export function createFileRoutes(_database: Database) {
await fileService.deleteFileOrFolder(path)
return c.json({ success: true })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to delete file/folder:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -112,9 +113,9 @@ export function createFileRoutes(_database: Database) {
const result = await fileService.renameOrMoveFile(path, body)
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to patch file:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
+26 -24
View File
@@ -1,4 +1,5 @@
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { Database } from 'bun:sqlite'
import * as db from '../db/queries'
import * as repoService from '../services/repo'
@@ -9,6 +10,7 @@ import { SettingsService } from '../services/settings'
import { writeFileContent } from '../services/file-operations'
import { opencodeServerManager } from '../services/opencode-single-server'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
import { getOpenCodeConfigFilePath, getReposPath } from '@opencode-manager/shared/config/env'
import path from 'path'
@@ -55,9 +57,9 @@ export function createRepoRoutes(database: Database) {
}
return c.json(repo)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -71,9 +73,9 @@ export function createRepoRoutes(database: Database) {
})
)
return c.json(reposWithCurrentBranch)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to list repos:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -89,9 +91,9 @@ export function createRepoRoutes(database: Database) {
const currentBranch = await repoService.getCurrentBranch(repo)
return c.json({ ...repo, currentBranch })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -107,9 +109,9 @@ export function createRepoRoutes(database: Database) {
await repoService.deleteRepoFiles(database, id)
return c.json({ success: true })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to delete repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -120,9 +122,9 @@ export function createRepoRoutes(database: Database) {
const repo = db.getRepoById(database, id)
return c.json(repo)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to pull repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -164,9 +166,9 @@ export function createRepoRoutes(database: Database) {
const updatedRepo = db.getRepoById(database, id)
return c.json(updatedRepo)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to switch repo config:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -192,12 +194,12 @@ export function createRepoRoutes(database: Database) {
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
return c.json({ ...updatedRepo, currentBranch })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to switch branch:', error)
if (error instanceof GitAuthenticationError) {
return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401)
}
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -223,12 +225,12 @@ export function createRepoRoutes(database: Database) {
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
return c.json({ ...updatedRepo, currentBranch })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create branch:', error)
if (error instanceof GitAuthenticationError) {
return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401)
}
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -245,9 +247,9 @@ export function createRepoRoutes(database: Database) {
return c.json(branches)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to list branches:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -265,9 +267,9 @@ export function createRepoRoutes(database: Database) {
return c.json(status)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get git status:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -291,9 +293,9 @@ export function createRepoRoutes(database: Database) {
return c.json(diff)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get file diff:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -329,9 +331,9 @@ export function createRepoRoutes(database: Database) {
'Content-Length': archiveSize.toString(),
}
})
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create repo archive:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
+6 -6
View File
@@ -106,11 +106,11 @@ export async function getFile(userPath: string): Promise<FileInfo> {
} else {
// It's a file - get content
let content = ''
let mimeType = getMimeType(validatedPath, new Uint8Array())
const mimeType = getMimeType(validatedPath)
if (stats.size < FILE_LIMITS.MAX_SIZE_BYTES) {
try {
const mimeType = getMimeType(validatedPath, new Uint8Array())
const mimeType = getMimeType(validatedPath)
if (mimeType.startsWith('image/') || !mimeType.startsWith('text/')) {
content = await readFileAsBase64(validatedPath)
@@ -144,8 +144,8 @@ export async function uploadFile(userPath: string, file: File, relativePath?: st
throw new Error('File too large')
}
const mimeType = file.type || getMimeType(file.name, new Uint8Array())
if (!ALLOWED_MIME_TYPES.includes(mimeType as any) && !mimeType.startsWith('text/')) {
const mimeType = file.type || getMimeType(file.name)
if (!ALLOWED_MIME_TYPES.includes(mimeType) && !mimeType.startsWith('text/')) {
throw new Error('File type not allowed')
}
@@ -246,7 +246,7 @@ function validatePath(userPath: string): string {
return resolved
}
function getMimeType(filePath: string, _content: Uint8Array): string {
function getMimeType(filePath: string): string {
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
@@ -323,7 +323,7 @@ export async function getFileRange(userPath: string, startLine: number, endLine:
const totalLines = await countFileLines(validatedPath)
const clampedEnd = Math.min(endLine, totalLines)
const lines = await readFileLines(validatedPath, startLine, clampedEnd)
const mimeType = getMimeType(validatedPath, new Uint8Array())
const mimeType = getMimeType(validatedPath)
return {
name: path.basename(validatedPath),
+11 -9
View File
@@ -1,5 +1,6 @@
import { executeCommand } from '../utils/process'
import { logger } from '../utils/logger'
import { getErrorMessage } from '../utils/error-utils'
import { SettingsService } from './settings'
import type { Database } from 'bun:sqlite'
import path from 'path'
@@ -153,9 +154,9 @@ export async function getGitStatus(repoPath: string, database?: Database): Promi
files,
hasChanges: files.length > 0
}
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to get git status for ${repoPath}:`, error)
throw new Error(`Failed to get git status: ${error.message}`)
throw new Error(`Failed to get git status: ${getErrorMessage(error)}`)
}
}
@@ -187,9 +188,10 @@ export async function getFileDiff(repoPath: string, filePath: string, database?:
try {
const content = await executeCommand(['git', '-C', fullRepoPath, 'diff', '--no-index', '--', '/dev/null', filePath], { env })
diff = content
} catch (error: any) {
if (error.message?.includes('exit code 1') || error.message?.includes('Command failed with code 1')) {
const output = error.message || ''
} catch (error: unknown) {
const errorMessage = getErrorMessage(error)
if (errorMessage?.includes('exit code 1') || errorMessage?.includes('Command failed with code 1')) {
const output = errorMessage || ''
const diffMatch = output.match(/diff --git[\s\S]*/)
diff = diffMatch ? diffMatch[0] : `New file: ${filePath}`
} else {
@@ -204,8 +206,8 @@ export async function getFileDiff(repoPath: string, filePath: string, database?:
} else {
diff = `New file (no commits yet): ${filePath}`
}
} catch (error: any) {
logger.warn(`Failed to get diff for ${filePath}:`, error.message)
} catch (error: unknown) {
logger.warn(`Failed to get diff for ${filePath}:`, getErrorMessage(error))
diff = null
}
}
@@ -233,8 +235,8 @@ export async function getFileDiff(repoPath: string, filePath: string, database?:
deletions,
isBinary
}
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to get file diff for ${filePath}:`, error)
throw new Error(`Failed to get file diff: ${error.message}`)
throw new Error(`Failed to get file diff: ${getErrorMessage(error)}`)
}
}
@@ -190,10 +190,9 @@ class OpenCodeServerManager {
await new Promise(r => setTimeout(r, 2000))
try {
process.kill(this.serverPid, 0)
process.kill(this.serverPid, 'SIGKILL')
} catch {
} catch (error) {
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
}
this.serverPid = null
-48
View File
@@ -693,26 +693,7 @@ export async function cleanupOrphanedDirectories(database: Database): Promise<vo
}
}
async function checkWorktreeExists(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
const worktreeList = await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'list', '--porcelain'])
return worktreeList.includes(worktreePath)
} catch {
return false
}
}
async function removeStaleWorktree(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
logger.info(`Attempting to remove stale worktree: ${worktreePath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', worktreePath])
logger.info(`Successfully removed stale worktree: ${worktreePath}`)
return true
} catch (error: any) {
logger.warn(`Failed to remove stale worktree ${worktreePath}:`, error.message)
return false
}
}
async function pruneWorktreeReferences(baseRepoPath: string): Promise<void> {
try {
@@ -749,36 +730,7 @@ async function cleanupStaleWorktree(baseRepoPath: string, worktreePath: string):
}
}
async function isBranchCheckedOutInMainWorktree(baseRepoPath: string, branch: string): Promise<boolean> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
return currentBranch === branch
}
async function getAvailableBranchForWorktree(baseRepoPath: string, targetBranch: string): Promise<string> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
if (!currentBranch) {
return targetBranch
}
if (currentBranch === targetBranch) {
logger.info(`Branch '${targetBranch}' is currently checked out in main worktree`)
const defaultBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'origin/HEAD']).then(ref => ref.trim()).catch(() => 'main')
const cleanDefaultBranch = defaultBranch.replace('origin/', '')
if (cleanDefaultBranch !== currentBranch) {
logger.info(`Switching to '${cleanDefaultBranch}' to free up '${targetBranch}' for worktree`)
await executeCommand(['git', '-C', baseRepoPath, 'checkout', cleanDefaultBranch])
return targetBranch
} else {
logger.warn(`Cannot free up branch '${targetBranch}' - it's the default branch`)
return `${targetBranch}-worktree-${Date.now()}`
}
}
return targetBranch
}
async function createWorktreeSafely(baseRepoPath: string, worktreePath: string, branch: string): Promise<void> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
+34
View File
@@ -0,0 +1,34 @@
export function isError(error: unknown): error is Error {
return error instanceof Error
}
export function getErrorMessage(error: unknown): string {
if (isError(error)) {
return error.message
}
return String(error)
}
export function getErrorStack(error: unknown): string | undefined {
if (isError(error)) {
return error.stack
}
return undefined
}
interface ErrorWithStatusCode {
statusCode?: number
status?: number
}
const VALID_STATUS_CODES = new Set([200, 201, 204, 301, 302, 304, 400, 401, 403, 404, 405, 409, 413, 422, 500, 501, 502, 503])
export function getStatusCode(error: unknown): number {
let code = 500
if (error && typeof error === 'object' && 'statusCode' in error) {
code = (error as ErrorWithStatusCode).statusCode || 500
} else if (error && typeof error === 'object' && 'status' in error) {
code = (error as ErrorWithStatusCode).status || 500
}
return VALID_STATUS_CODES.has(code) ? code : 500
}
+3
View File
@@ -19,6 +19,9 @@ export default defineConfig([
ecmaVersion: 2020,
globals: globals.browser,
},
rules: {
'no-console': ['warn', { allow: ['warn', 'error'] }],
},
},
{
files: ['src/components/ui/**/*.{ts,tsx}', 'src/components/message/FileToolRender.tsx'],
+4 -1
View File
@@ -2,12 +2,13 @@ import {
DEFAULT_TTS_CONFIG,
DEFAULT_KEYBOARD_SHORTCUTS,
DEFAULT_USER_PREFERENCES,
DEFAULT_LEADER_KEY,
type TTSConfig,
type OpenCodeConfigContent,
} from '@opencode-manager/shared'
export type { TTSConfig, OpenCodeConfigContent }
export { DEFAULT_TTS_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES }
export { DEFAULT_TTS_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY }
export interface CustomCommand {
name: string
@@ -42,6 +43,8 @@ export interface UserPreferences {
showReasoning: boolean
expandToolCalls: boolean
expandDiffs: boolean
leaderKey?: string
directShortcuts?: string[]
keyboardShortcuts: Record<string, string>
customCommands: CustomCommand[]
customAgents: CustomAgent[]
@@ -147,7 +147,7 @@ useEffect(() => {
}
}, [initialFileError])
const loadFiles = async (path: string) => {
const loadFiles = useCallback(async (path: string) => {
setLoading(true)
setError(null)
@@ -166,7 +166,7 @@ useEffect(() => {
} finally {
setLoading(false)
}
}
}, [onDirectoryLoad])
const handleFileSelect = useCallback(async (file: FileInfo) => {
if (file.isDirectory) {
@@ -274,7 +274,7 @@ useEffect(() => {
} : null)
await loadFiles(currentPath)
}, [currentPath, uploadSingleFile])
}, [currentPath, uploadSingleFile, loadFiles])
const handleUpload = useCallback(async (fileList: FileList) => {
const items = getUploadItemsFromFileList(fileList)
@@ -301,7 +301,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Create failed')
}
}, [currentPath])
}, [currentPath, loadFiles])
const handleDelete = useCallback(async (path: string) => {
try {
@@ -318,7 +318,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Delete failed')
}
}, [currentPath])
}, [currentPath, loadFiles])
const handleRename = useCallback(async (oldPath: string, newPath: string) => {
try {
@@ -336,7 +336,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Rename failed')
}
}, [currentPath])
}, [currentPath, loadFiles])
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
@@ -370,7 +370,7 @@ useEffect(() => {
useEffect(() => {
loadFiles(basePath)
}, [basePath])
}, [basePath, loadFiles])
useEffect(() => {
const handleFileSaved = (event: CustomEvent<{ path: string; content: string }>) => {
@@ -383,19 +383,18 @@ useEffect(() => {
return () => window.removeEventListener('fileSaved', handleFileSaved as EventListener)
}, [selectedFile, handleFileSelect])
// Handle escape key to close modal
useEffect(() => {
if (!isPreviewModalOpen) return
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isPreviewModalOpen) {
if (e.key === 'Escape') {
handleCloseModal()
}
}
if (isPreviewModalOpen) {
document.addEventListener('keydown', handleEscape)
return () => document.removeEventListener('keydown', handleEscape)
}
}, [isPreviewModalOpen])
document.addEventListener('keydown', handleEscape)
return () => document.removeEventListener('keydown', handleEscape)
}, [isPreviewModalOpen, handleCloseModal])
const filteredFiles = files?.children?.filter(file =>
file.name.toLowerCase().includes(searchQuery.toLowerCase())
+46 -27
View File
@@ -23,6 +23,16 @@ import type { components } from '@/api/opencode-types'
import type { MessageWithParts, FileInfo, ImageAttachment } from '@/api/types'
const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"]
const revokeBlobUrls = (attachments: ImageAttachment[]) => {
attachments.forEach((attachment) => {
if (attachment.dataUrl.startsWith('blob:')) {
URL.revokeObjectURL(attachment.dataUrl)
}
})
}
const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"]
@@ -64,31 +74,6 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
onPromptChange
}, ref) {
const [prompt, setPrompt] = useState('')
useImperativeHandle(ref, () => ({
setPromptValue: (value: string) => {
setPrompt(value)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
textareaRef.current.focus()
}
},
clearPrompt: () => {
setPrompt('')
setAttachedFiles(new Map())
setImageAttachments([])
setSelectedAgent(null)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.focus()
}
},
triggerFileUpload: () => {
fileInputRef.current?.click()
}
}), [])
const [isBashMode, setIsBashMode] = useState(false)
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
@@ -104,6 +89,31 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
useImperativeHandle(ref, () => ({
setPromptValue: (value: string) => {
setPrompt(value)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
textareaRef.current.focus()
}
},
clearPrompt: () => {
setPrompt('')
setAttachedFiles(new Map())
revokeBlobUrls(imageAttachments)
setImageAttachments([])
setSelectedAgent(null)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.focus()
}
},
triggerFileUpload: () => {
fileInputRef.current?.click()
}
}), [imageAttachments])
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
@@ -170,6 +180,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
})
setPrompt('')
setAttachedFiles(new Map())
revokeBlobUrls(imageAttachments)
setImageAttachments([])
setSelectedAgent(null)
if (textareaRef.current) {
@@ -222,6 +233,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
setPrompt('')
setAttachedFiles(new Map())
revokeBlobUrls(imageAttachments)
setImageAttachments([])
setSelectedAgent(null)
if (textareaRef.current) {
@@ -386,7 +398,13 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
}
const removeImageAttachment = (id: string) => {
setImageAttachments((prev) => prev.filter((a) => a.id !== id))
setImageAttachments((prev) => {
const attachment = prev.find((a) => a.id === id)
if (attachment?.dataUrl.startsWith('blob:')) {
URL.revokeObjectURL(attachment.dataUrl)
}
return prev.filter((a) => a.id !== id)
})
}
const handlePaste = async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
@@ -481,7 +499,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
const handleFileInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.currentTarget.files?.[0]
if (file) {
if (file && ACCEPTED_FILE_TYPES.includes(file.type)) {
addImageAttachment(file)
}
event.currentTarget.value = ''
@@ -573,6 +591,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
setMentionQuery('')
setMentionRange(null)
setPrompt('')
revokeBlobUrls(imageAttachments)
setImageAttachments([])
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
@@ -1,7 +1,8 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { DEFAULT_KEYBOARD_SHORTCUTS } from '@/api/types/settings'
import { useMobile } from '@/hooks/useMobile'
import { Loader2, X } from 'lucide-react'
import { DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
@@ -10,94 +11,121 @@ const normalizeShortcut = (shortcut: string): string => {
return shortcut.replace(/Cmd/g, CMD_KEY)
}
const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
export function KeyboardShortcuts() {
const { preferences, isLoading, updateSettings } = useSettings()
const isMobile = useMobile()
const [recordingKey, setRecordingKey] = useState<string | null>(null)
const [recordingLeader, setRecordingLeader] = useState(false)
const [tempShortcuts, setTempShortcuts] = useState<Record<string, string>>({})
const [tempLeaderKey, setTempLeaderKey] = useState<string | null>(null)
const [currentKeys, setCurrentKeys] = useState<string>('')
const shortcuts = { ...DEFAULT_KEYBOARD_SHORTCUTS, ...preferences?.keyboardShortcuts, ...tempShortcuts }
const leaderKey = tempLeaderKey ?? preferences?.leaderKey ?? DEFAULT_LEADER_KEY
const directShortcuts = preferences?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
const handleKeyDown = (e: KeyboardEvent, action: string) => {
e.preventDefault()
const keys = []
if (e.ctrlKey) keys.push('Ctrl')
if (e.metaKey) keys.push('Cmd')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
// Get the actual key pressed (excluding modifier keys)
const mainKey = e.key
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
// Handle special keys
let displayKey = mainKey
if (mainKey === ' ') displayKey = 'Space'
else if (mainKey === 'ArrowUp') displayKey = 'Up'
else if (mainKey === 'ArrowDown') displayKey = 'Down'
else if (mainKey === 'ArrowLeft') displayKey = 'Left'
else if (mainKey === 'ArrowRight') displayKey = 'Right'
else if (mainKey === 'Enter') displayKey = 'Return'
else if (mainKey === 'Escape') displayKey = 'Esc'
else if (mainKey === 'Tab') displayKey = 'Tab'
else if (mainKey === 'Backspace') displayKey = 'Backspace'
else if (mainKey === 'Delete') displayKey = 'Delete'
else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
keys.push(displayKey)
// Only complete recording if we have a non-modifier key
if (keys.length > 0) {
const shortcut = keys.join('+')
setTempShortcuts(prev => ({ ...prev, [action]: shortcut }))
setRecordingKey(null)
setCurrentKeys('')
updateSettings({
keyboardShortcuts: { ...shortcuts, [action]: shortcut }
})
}
} else {
// Show current modifier keys being held
setCurrentKeys(keys.join('+'))
}
}
const shortcuts = useMemo(() => ({
...DEFAULT_KEYBOARD_SHORTCUTS,
...preferences?.keyboardShortcuts,
...tempShortcuts
}), [preferences?.keyboardShortcuts, tempShortcuts])
const handleKeyUp = (e: KeyboardEvent) => {
// Clear current keys display when modifiers are released
if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) {
setCurrentKeys('')
}
}
const shortcutsRef = useRef(shortcuts)
shortcutsRef.current = shortcuts
const updateSettingsRef = useRef(updateSettings)
updateSettingsRef.current = updateSettings
const startRecording = (action: string) => {
setRecordingKey(action)
setRecordingLeader(false)
setCurrentKeys('')
}
const stopRecording = () => {
const startRecordingLeader = () => {
setRecordingLeader(true)
setRecordingKey(null)
setCurrentKeys('')
}
const stopRecording = useCallback(() => {
setRecordingKey(null)
setRecordingLeader(false)
setCurrentKeys('')
}, [])
const clearShortcut = useCallback((action: string) => {
setTempShortcuts(prev => ({ ...prev, [action]: '' }))
updateSettingsRef.current({
keyboardShortcuts: { ...shortcutsRef.current, [action]: '' }
})
}, [])
useEffect(() => {
if (recordingKey) {
const handleGlobalKeyDown = (e: KeyboardEvent) => {
handleKeyDown(e, recordingKey)
}
if (!recordingKey && !recordingLeader) return
const handleKeyDown = (e: KeyboardEvent) => {
e.preventDefault()
const handleGlobalKeyUp = (e: KeyboardEvent) => {
handleKeyUp(e)
}
const keys = []
if (e.ctrlKey) keys.push('Ctrl')
if (e.metaKey) keys.push('Cmd')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
document.addEventListener('keydown', handleGlobalKeyDown)
document.addEventListener('keyup', handleGlobalKeyUp)
return () => {
document.removeEventListener('keydown', handleGlobalKeyDown)
document.removeEventListener('keyup', handleGlobalKeyUp)
const mainKey = e.key
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
let displayKey = mainKey
if (mainKey === ' ') displayKey = 'Space'
else if (mainKey === 'ArrowUp') displayKey = 'Up'
else if (mainKey === 'ArrowDown') displayKey = 'Down'
else if (mainKey === 'ArrowLeft') displayKey = 'Left'
else if (mainKey === 'ArrowRight') displayKey = 'Right'
else if (mainKey === 'Enter') displayKey = 'Return'
else if (mainKey === 'Escape') displayKey = 'Esc'
else if (mainKey === 'Tab') displayKey = 'Tab'
else if (mainKey === 'Backspace') displayKey = 'Backspace'
else if (mainKey === 'Delete') displayKey = 'Delete'
else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
keys.push(displayKey)
if (keys.length > 0) {
const shortcut = keys.join('+')
if (recordingLeader) {
setTempLeaderKey(shortcut)
setRecordingLeader(false)
setCurrentKeys('')
updateSettingsRef.current({ leaderKey: shortcut })
} else if (recordingKey) {
setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
setRecordingKey(null)
setCurrentKeys('')
updateSettingsRef.current({
keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut }
})
}
}
} else {
setCurrentKeys(keys.join('+'))
}
}
}, [recordingKey, handleKeyDown, handleKeyUp])
const handleKeyUp = (e: KeyboardEvent) => {
if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) {
setCurrentKeys('')
}
}
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('keyup', handleKeyUp)
}
}, [recordingKey, recordingLeader])
if (isLoading) {
return (
@@ -107,17 +135,83 @@ export function KeyboardShortcuts() {
)
}
const formatShortcutDisplay = (action: string, keys: string) => {
if (!keys) return 'Not set'
if (directShortcuts.includes(action)) {
return normalizeShortcut(keys)
}
return `${normalizeShortcut(leaderKey)} → ${normalizeShortcut(keys)}`
}
const toggleDirectShortcut = (action: string) => {
const newDirectShortcuts = directShortcuts.includes(action)
? directShortcuts.filter(s => s !== action)
: [...directShortcuts, action]
updateSettings({ directShortcuts: newDirectShortcuts })
}
if (isMobile) {
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">Keyboard Shortcuts</h2>
<p className="text-sm text-muted-foreground">
Keyboard shortcuts are not available on mobile devices.
</p>
</div>
)
}
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Keyboard Shortcuts</h2>
<div className="space-y-4">
<div className="flex items-center justify-between py-3 border-b border-border">
<div className="space-y-1">
<p className="text-foreground font-medium">Leader Key</p>
<p className="text-xs text-muted-foreground">Press this first, then the shortcut key</p>
</div>
{recordingLeader ? (
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
onBlur={stopRecording}
readOnly
/>
<button
onClick={stopRecording}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
) : (
<button
onClick={startRecordingLeader}
className="px-3 py-1.5 bg-primary/20 border border-primary/50 hover:border-primary rounded text-sm text-foreground font-mono transition-colors"
>
{normalizeShortcut(leaderKey)}
</button>
)}
</div>
{Object.entries(shortcuts).map(([action, keys]) => (
<div key={action} className="flex items-center justify-between py-3 border-b border-border last:border-0">
<div className="space-y-1">
<p className="text-foreground font-medium capitalize">
{action.replace(/([A-Z])/g, ' $1').trim()}
</p>
<button
onClick={() => toggleDirectShortcut(action)}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{directShortcuts.includes(action) ? 'Direct (click to require leader)' : 'Requires leader key (click to make direct)'}
</button>
</div>
{recordingKey === action ? (
@@ -139,19 +233,30 @@ export function KeyboardShortcuts() {
</button>
</div>
) : (
<button
onClick={() => startRecording(action)}
className="px-3 py-1.5 bg-accent border border-border hover:border-border rounded text-sm text-foreground font-mono transition-colors"
>
{normalizeShortcut(keys)}
</button>
<div className="flex items-center gap-2">
<button
onClick={() => startRecording(action)}
className={`px-3 py-1.5 bg-accent border border-border hover:border-border rounded text-sm font-mono transition-colors ${keys ? 'text-foreground' : 'text-muted-foreground italic'}`}
>
{formatShortcutDisplay(action, keys)}
</button>
{keys && (
<button
onClick={() => clearShortcut(action)}
className="p-1 text-muted-foreground hover:text-destructive transition-colors"
title="Clear shortcut"
>
<X className="w-4 h-4" />
</button>
)}
</div>
)}
</div>
))}
</div>
<p className="mt-6 text-sm text-muted-foreground">
Click on any shortcut to record a new key combination
Click on any shortcut to record a new key combination. Click on the status text below each action to toggle whether it requires the leader key.
</p>
</div>
)
+118 -76
View File
@@ -1,10 +1,10 @@
import { useEffect, useCallback } from 'react'
import { useEffect, useCallback, useRef, useState } from 'react'
import { useSettings } from './useSettings'
import { DEFAULT_LEADER_KEY } from '@/api/types/settings'
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
const normalizeShortcut = (shortcut: string): string => {
// Convert stored shortcuts to platform-specific format for comparison
return shortcut.replace(/Cmd/g, isMac ? 'Cmd' : 'Ctrl')
}
@@ -36,6 +36,9 @@ const parseEventShortcut = (e: KeyboardEvent): string => {
return ''
}
const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
const LEADER_TIMEOUT = 1500
interface ShortcutActions {
openModelDialog?: () => void
openSessions?: () => void
@@ -55,96 +58,135 @@ interface ShortcutActions {
export function useKeyboardShortcuts(actions: ShortcutActions = {}) {
const { preferences } = useSettings()
const [leaderActive, setLeaderActive] = useState(false)
const leaderTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const preferencesRef = useRef(preferences)
preferencesRef.current = preferences
const actionsRef = useRef(actions)
actionsRef.current = actions
const clearLeaderTimeout = useCallback(() => {
if (leaderTimeoutRef.current) {
clearTimeout(leaderTimeoutRef.current)
leaderTimeoutRef.current = null
}
}, [])
const executeAction = useCallback((action: string, e: KeyboardEvent) => {
e.preventDefault()
const currentActions = actionsRef.current
switch (action) {
case 'selectModel':
currentActions.openModelDialog?.()
break
case 'sessions':
currentActions.openSessions?.()
break
case 'newSession':
currentActions.newSession?.()
break
case 'closeSession':
currentActions.closeSession?.()
break
case 'toggleSidebar':
currentActions.toggleSidebar?.()
break
case 'submit':
currentActions.submitPrompt?.()
break
case 'abort':
currentActions.abortSession?.()
break
case 'toggleMode':
currentActions.toggleMode?.()
break
case 'undo':
currentActions.undo?.()
break
case 'redo':
currentActions.redo?.()
break
case 'compact':
currentActions.compact?.()
break
case 'fork':
currentActions.fork?.()
break
case 'settings':
currentActions.openSettings?.()
break
}
}, [])
const handleKeyDown = useCallback((e: KeyboardEvent) => {
const shortcut = parseEventShortcut(e)
if (!shortcut) return
const shortcuts = preferences?.keyboardShortcuts || {}
const prefs = preferencesRef.current
const shortcuts = prefs?.keyboardShortcuts || {}
const leaderKey = normalizeShortcut(prefs?.leaderKey || DEFAULT_LEADER_KEY)
const directShortcuts = prefs?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
// Check if any file editor is active on the page
const activeFileEditor = document.querySelector('[data-file-editor="true"]')
if (activeFileEditor && document.activeElement === activeFileEditor) {
return // Block all shortcuts when a file editor is active
return
}
// Don't trigger shortcuts when user is typing in input fields or editing files
const target = e.target as HTMLElement
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.contentEditable === 'true' || target.getAttribute('data-file-editor') === 'true') {
// Allow some shortcuts to work even in input fields (but not in file editor)
const allowedInInput = ['submit', 'abort', 'toggleMode']
const isFileEditor = target.getAttribute('data-file-editor') === 'true'
const action = Object.entries(shortcuts).find(([, keys]) => normalizeShortcut(keys) === shortcut)?.[0]
if (!action || !allowedInInput.includes(action) || isFileEditor) {
const isInInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.contentEditable === 'true'
const isFileEditor = target.getAttribute('data-file-editor') === 'true'
if (isFileEditor) return
if (leaderActive) {
clearLeaderTimeout()
setLeaderActive(false)
const action = Object.entries(shortcuts).find(([actionName, keys]) => {
if (directShortcuts.includes(actionName)) return false
if (!keys) return false
return normalizeShortcut(keys) === shortcut
})?.[0]
if (action) {
executeAction(action, e)
}
return
}
if (shortcut === leaderKey && !isInInput) {
e.preventDefault()
setLeaderActive(true)
clearLeaderTimeout()
leaderTimeoutRef.current = setTimeout(() => {
setLeaderActive(false)
}, LEADER_TIMEOUT)
return
}
const directAction = Object.entries(shortcuts).find(([actionName, keys]) => {
if (!directShortcuts.includes(actionName)) return false
if (!keys) return false
return normalizeShortcut(keys) === shortcut
})?.[0]
if (directAction) {
if (isInInput && directAction !== 'submit' && directAction !== 'abort') {
return
}
executeAction(directAction, e)
}
// Find the action that matches the current shortcut
const action = Object.entries(shortcuts).find(([, keys]) => normalizeShortcut(keys) === shortcut)?.[0]
if (!action) return
switch (action) {
case 'selectModel':
e.preventDefault()
actions.openModelDialog?.()
break
case 'sessions':
e.preventDefault()
actions.openSessions?.()
break
case 'newSession':
e.preventDefault()
actions.newSession?.()
break
case 'closeSession':
e.preventDefault()
actions.closeSession?.()
break
case 'toggleSidebar':
e.preventDefault()
actions.toggleSidebar?.()
break
case 'submit':
e.preventDefault()
actions.submitPrompt?.()
break
case 'abort':
e.preventDefault()
actions.abortSession?.()
break
case 'toggleMode':
e.preventDefault()
actions.toggleMode?.()
break
case 'undo':
e.preventDefault()
actions.undo?.()
break
case 'redo':
e.preventDefault()
actions.redo?.()
break
case 'compact':
e.preventDefault()
actions.compact?.()
break
case 'fork':
e.preventDefault()
actions.fork?.()
break
case 'settings':
e.preventDefault()
actions.openSettings?.()
break
}
}, [preferences?.keyboardShortcuts, actions])
}, [leaderActive, clearLeaderTimeout, executeAction])
useEffect(() => {
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}, [handleKeyDown])
return () => {
document.removeEventListener('keydown', handleKeyDown)
clearLeaderTimeout()
}
}, [handleKeyDown, clearLeaderTimeout])
return { leaderActive }
}
+94 -17
View File
@@ -11,7 +11,7 @@ import { SessionList } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { useSession, useAbortSession, useUpdateSession, useMessages, useTitleGenerating } from "@/hooks/useOpenCode";
import { useSession, useAbortSession, useUpdateSession, useMessages, useTitleGenerating, useCreateSession } from "@/hooks/useOpenCode";
import { OPENCODE_API_ENDPOINT, API_BASE_URL } from "@/config";
import { useSSE } from "@/hooks/useSSE";
import { useUIState } from "@/stores/uiStateStore";
@@ -27,6 +27,8 @@ import { MessageSkeleton } from "@/components/message/MessageSkeleton";
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
import { showToast } from "@/lib/toast";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { createOpenCodeClient } from "@/api/opencode";
import { useSessionStatus } from "@/stores/sessionStatusStore";
export function SessionDetail() {
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
@@ -99,14 +101,97 @@ export function SessionDetail() {
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory);
const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId);
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
const createSession = useCreateSession(opcodeUrl, repoDirectory);
const isTitleGenerating = useTitleGenerating(sessionId);
const { open: openSettings } = useSettingsDialog();
const { modelString } = useModelSelection(opcodeUrl, repoDirectory);
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const { isPlaying, stop } = useTTS();
const setSessionStatus = useSessionStatus((state) => state.setStatus);
useKeyboardShortcuts({
const handleNewSession = useCallback(async () => {
try {
const newSession = await createSession.mutateAsync({ agent: undefined });
if (newSession?.id) {
navigate(`/repos/${repoId}/sessions/${newSession.id}`);
}
} catch {
showToast.error('Failed to create new session');
}
}, [createSession, navigate, repoId]);
const handleCompact = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
if (!model?.providerID || !model?.modelID) {
showToast.error('No model selected. Please select a provider and model first.');
return;
}
showToast.loading('Compacting session...', { id: `compact-${sessionId}` });
setSessionStatus(sessionId, { type: 'compact' });
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
await client.summarizeSession(sessionId, model.providerID, model.modelID);
} catch (error) {
showToast.error(`Compact failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
setSessionStatus(sessionId, { type: 'idle' });
}
}, [opcodeUrl, sessionId, model, repoDirectory, setSessionStatus]);
const handleUndo = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
await client.sendCommand(sessionId, { command: 'undo', arguments: '' });
} catch (error) {
showToast.error(`Undo failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, repoDirectory]);
const handleRedo = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
await client.sendCommand(sessionId, { command: 'redo', arguments: '' });
} catch (error) {
showToast.error(`Redo failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, repoDirectory]);
const handleFork = useCallback(async () => {
if (!opcodeUrl || !sessionId) return;
try {
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
const forkedSession = await client.forkSession(sessionId);
if (forkedSession?.id) {
navigate(`/repos/${repoId}/sessions/${forkedSession.id}`);
showToast.success('Session forked');
}
} catch (error) {
showToast.error(`Fork failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId]);
const handleCloseSession = useCallback(() => {
navigate(`/repos/${repoId}`);
}, [navigate, repoId]);
const { leaderActive } = useKeyboardShortcuts({
openModelDialog: () => setModelDialogOpen(true),
openSessions: () => setSessionsDialogOpen(true),
openSettings,
newSession: handleNewSession,
closeSession: handleCloseSession,
compact: handleCompact,
undo: handleUndo,
redo: handleRedo,
fork: handleFork,
toggleSidebar: () => setFileBrowserOpen(prev => !prev),
toggleMode: () => {
const newMode = preferences?.mode === "plan" ? "build" : "plan";
updateSettings({ mode: newMode });
},
submitPrompt: () => {
const submitButton = document.querySelector(
"[data-submit-prompt]",
@@ -120,19 +205,6 @@ export function SessionDetail() {
},
});
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Tab") {
e.preventDefault();
const newMode = preferences?.mode === "plan" ? "build" : "plan";
updateSettings({ mode: newMode });
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [preferences?.mode, updateSettings]);
const handleFileClick = useCallback((filePath: string) => {
@@ -281,7 +353,12 @@ export function SessionDetail() {
<span className="text-sm font-medium hidden sm:inline">Clear</span>
</button>
)}
{isPlaying && (
{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>
</div>
)}
{isPlaying && !leaderActive && (
<button
onMouseDown={(e) => e.preventDefault()}
onTouchEnd={(e) => {
+5 -1
View File
@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"packageManager": "pnpm@9.15.0",
"scripts": {
"scripts": {
"predev": "bash scripts/setup-dev.sh",
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
"dev:backend": "bun --watch backend/src/index.ts",
@@ -14,6 +14,10 @@
"build:frontend": "pnpm --filter frontend build",
"test": "pnpm run test:backend",
"test:backend": "pnpm --filter backend test",
"lint": "pnpm run lint:frontend && pnpm run lint:backend",
"lint:frontend": "pnpm --filter frontend lint",
"lint:backend": "pnpm --filter backend lint",
"lint:fix": "pnpm run lint:frontend -- --fix && pnpm run lint:backend -- --fix",
"generate:openapi": "bun scripts/generate-openapi.ts",
"docker:build": "docker-compose build",
"docker:up": "docker-compose up -d",
+9
View File
@@ -46,6 +46,9 @@ importers:
specifier: ^4.1.12
version: 4.3.2
devDependencies:
'@eslint/js':
specifier: ^9.36.0
version: 9.39.2
'@types/archiver':
specifier: ^7.0.0
version: 7.0.0
@@ -58,6 +61,12 @@ importers:
'@vitest/ui':
specifier: ^3.2.4
version: 3.2.4(vitest@3.2.4)
eslint:
specifier: ^9.39.1
version: 9.39.2(jiti@2.6.1)
typescript-eslint:
specifier: ^8.45.0
version: 8.51.0(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3)
vitest:
specifier: ^3.2.4
version: 3.2.4(@types/debug@4.1.12)(@types/node@24.10.4)(@vitest/ui@3.2.4)(jiti@2.6.1)(lightningcss@1.30.2)
+17 -11
View File
@@ -44,20 +44,22 @@ const isBrowser = typeof navigator !== 'undefined';
const isMac = isBrowser && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl';
export const DEFAULT_LEADER_KEY = `${CMD_KEY}+O`;
export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
submit: `${CMD_KEY}+Enter`,
abort: 'Escape',
toggleMode: 'Tab',
undo: `${CMD_KEY}+Z`,
redo: `${CMD_KEY}+Shift+Z`,
compact: `${CMD_KEY}+K`,
fork: `${CMD_KEY}+Shift+F`,
settings: `${CMD_KEY}+,`,
sessions: `${CMD_KEY}+S`,
newSession: `${CMD_KEY}+N`,
closeSession: `${CMD_KEY}+W`,
toggleSidebar: `${CMD_KEY}+B`,
selectModel: `${CMD_KEY}+M`,
toggleMode: 'T',
undo: 'Z',
redo: 'Shift+Z',
compact: 'K',
fork: 'F',
settings: ',',
sessions: 'S',
newSession: 'N',
closeSession: 'W',
toggleSidebar: 'B',
selectModel: 'M',
};
export const GitCredentialSchema = z.object({
@@ -90,6 +92,8 @@ export const UserPreferencesSchema = z.object({
showReasoning: z.boolean(),
expandToolCalls: z.boolean(),
expandDiffs: z.boolean(),
leaderKey: z.string().optional(),
directShortcuts: z.array(z.string()).optional(),
keyboardShortcuts: z.record(z.string(), z.string()),
customCommands: z.array(CustomCommandSchema),
customAgents: z.array(CustomAgentSchema),
@@ -120,6 +124,8 @@ export const DEFAULT_USER_PREFERENCES = {
showReasoning: false,
expandToolCalls: false,
expandDiffs: true,
leaderKey: DEFAULT_LEADER_KEY,
directShortcuts: ['submit', 'abort'],
keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
customCommands: [],
customAgents: [],