add typecheck script and fix TypeScript errors (#48)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-04 17:11:53 -05:00
1 parent e853660ad3
commit ed4bc17987
14 files changed
+371 -137

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
"dev": "bun --watch src/index.ts",
"start": "bun src/index.ts",
"build": "bun build src/index.ts --outdir=dist --target=bun",
"typecheck": "tsc --noEmit",
"test": "vitest",
"test:ui": "vitest --ui",
"test:watch": "vitest --watch",
+4 -4
View File
@@ -14,7 +14,7 @@ import {
listDirectory
} from './file-operations'
import { getReposPath, FILE_LIMITS } from '@opencode-manager/shared/config/env'
import { ALLOWED_MIME_TYPES } from '@opencode-manager/shared'
import { ALLOWED_MIME_TYPES, type AllowedMimeType } from '@opencode-manager/shared'
import type { ChunkedFileInfo, PatchOperation } from '@opencode-manager/shared'
const SHARED_WORKSPACE_BASE = getReposPath()
@@ -144,7 +144,7 @@ export async function uploadFile(userPath: string, file: File, relativePath?: st
throw new Error('File too large')
}
const mimeType = file.type || getMimeType(file.name)
const mimeType = (file.type || getMimeType(file.name)) as AllowedMimeType
if (!ALLOWED_MIME_TYPES.includes(mimeType) && !mimeType.startsWith('text/')) {
throw new Error('File type not allowed')
}
@@ -246,10 +246,10 @@ function validatePath(userPath: string): string {
return resolved
}
function getMimeType(filePath: string): string {
function getMimeType(filePath: string): AllowedMimeType {
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
const mimeTypes: Record<string, AllowedMimeType> = {
'.txt': 'text/plain',
'.html': 'text/html',
'.css': 'text/css',
+48 -2
View File
@@ -4,6 +4,7 @@ import { getErrorMessage } from '../utils/error-utils'
import { SettingsService } from './settings'
import type { Database } from 'bun:sqlite'
import path from 'path'
import fs from 'fs/promises'
import { createGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
async function hasCommits(repoPath: string): Promise<boolean> {
@@ -140,6 +141,37 @@ function parsePorcelainV2(output: string): { branch: string; ahead: number; behi
return { branch, ahead, behind, files }
}
async function expandUntrackedDirectory(repoPath: string, dirPath: string): Promise<GitFileStatus[]> {
const cleanDirPath = dirPath.endsWith('/') ? dirPath.slice(0, -1) : dirPath
const fullDirPath = path.join(repoPath, cleanDirPath)
const files: GitFileStatus[] = []
async function walkDir(currentPath: string, relativePath: string): Promise<void> {
try {
const entries = await fs.readdir(currentPath, { withFileTypes: true })
for (const entry of entries) {
const entryRelPath = relativePath ? `${relativePath}/${entry.name}` : entry.name
const entryFullPath = path.join(currentPath, entry.name)
if (entry.isDirectory()) {
await walkDir(entryFullPath, entryRelPath)
} else {
files.push({
path: `${cleanDirPath}/${entryRelPath}`,
status: 'untracked',
staged: false
})
}
}
} catch {
// Ignore errors reading directory
}
}
await walkDir(fullDirPath, '')
return files
}
export async function getGitStatus(repoPath: string, database?: Database): Promise<GitStatusResponse> {
try {
const fullPath = path.resolve(repoPath)
@@ -147,12 +179,26 @@ export async function getGitStatus(repoPath: string, database?: Database): Promi
const output = await executeCommand(['git', '-C', fullPath, 'status', '--porcelain=v2', '--branch'], { env })
const { branch, ahead, behind, files } = parsePorcelainV2(output)
const expandedFiles: GitFileStatus[] = []
for (const file of files) {
if (file.status === 'untracked' && file.path.endsWith('/')) {
const dirFiles = await expandUntrackedDirectory(fullPath, file.path)
if (dirFiles.length > 0) {
expandedFiles.push(...dirFiles)
} else {
expandedFiles.push(file)
}
} else {
expandedFiles.push(file)
}
}
return {
branch,
ahead,
behind,
files,
hasChanges: files.length > 0
files: expandedFiles,
hasChanges: expandedFiles.length > 0
}
} catch (error: unknown) {
logger.error(`Failed to get git status for ${repoPath}:`, error)
+31 -25
View File
@@ -22,8 +22,8 @@ describe('fetchGitHubUserInfo', () => {
{ email: 'verified@email.com', primary: true, verified: true }
])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -43,8 +43,8 @@ describe('fetchGitHubUserInfo', () => {
})
}
const emailsResponse = { ok: false }
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -65,8 +65,8 @@ describe('fetchGitHubUserInfo', () => {
ok: true,
json: vi.fn().mockResolvedValue([])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -89,8 +89,8 @@ describe('fetchGitHubUserInfo', () => {
{ email: 'unverified@email.com', primary: false, verified: false }
])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -100,7 +100,8 @@ describe('fetchGitHubUserInfo', () => {
it('should return null when user API fails', async () => {
const userResponse = { ok: false }
global.fetch = vi.fn().mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
const result = await fetchGitHubUserInfo('invalid_token')
@@ -116,7 +117,8 @@ describe('fetchGitHubUserInfo', () => {
id: null
})
}
global.fetch = vi.fn().mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -132,7 +134,8 @@ describe('fetchGitHubUserInfo', () => {
id: 123456
})
}
global.fetch = vi.fn().mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -149,8 +152,8 @@ describe('fetchGitHubUserInfo', () => {
})
}
const emailsResponse = { ok: false }
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await fetchGitHubUserInfo('test_token')
@@ -160,7 +163,8 @@ describe('fetchGitHubUserInfo', () => {
})
it('should handle network errors gracefully', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('Network error'))
global.fetch = vi.fn() as any;
(global.fetch as any).mockRejectedValue(new Error('Network error'))
const result = await fetchGitHubUserInfo('test_token')
@@ -182,8 +186,8 @@ describe('fetchGitHubUserInfo', () => {
{ email: 'verified@email.com', primary: true, verified: true }
])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
await fetchGitHubUserInfo('test_token')
@@ -250,7 +254,7 @@ describe('findGitHubCredential', () => {
describe('resolveGitIdentity', () => {
beforeEach(() => {
vi.clearAllMocks()
global.fetch = vi.fn()
global.fetch = vi.fn() as any;
})
it('should return manual identity when both name and email provided', async () => {
@@ -287,8 +291,8 @@ describe('resolveGitIdentity', () => {
])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await resolveGitIdentity(manual, credentials)
@@ -320,8 +324,8 @@ describe('resolveGitIdentity', () => {
])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await resolveGitIdentity(manual, credentials)
@@ -353,8 +357,8 @@ describe('resolveGitIdentity', () => {
])
}
global.fetch = vi.fn()
.mockResolvedValueOnce(userResponse)
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce(userResponse)
.mockResolvedValueOnce(emailsResponse)
const result = await resolveGitIdentity(manual, credentials)
@@ -371,7 +375,8 @@ describe('resolveGitIdentity', () => {
{ name: 'github', host: 'https://github.com/', token: 'invalid-token' },
]
global.fetch = vi.fn().mockResolvedValueOnce({ ok: false })
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce({ ok: false })
const result = await resolveGitIdentity(manual, credentials)
@@ -397,7 +402,8 @@ describe('resolveGitIdentity', () => {
{ name: 'github', host: 'https://github.com/', token: 'invalid-token' },
]
global.fetch = vi.fn().mockResolvedValueOnce({ ok: false })
global.fetch = vi.fn() as any;
(global.fetch as any).mockResolvedValueOnce({ ok: false })
const result = await resolveGitIdentity(manual, credentials)
+1
View File
@@ -5,6 +5,7 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"preview": "vite preview",
"test": "vitest"
@@ -1,6 +1,7 @@
import { useFileDiff } from '@/api/git'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, Plus, Minus, ArrowLeft, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { CopyButton } from '@/components/ui/copy-button'
import { cn } from '@/lib/utils'
import type { GitFileStatusType } from '@/types/git'
@@ -60,6 +61,8 @@ const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: st
copied: { icon: FileText, color: 'text-purple-500', bgColor: 'bg-purple-500/10', label: 'Copied' },
}
function DiffLineComponent({ line, showLineNumbers, onLineClick }: { line: DiffLine; showLineNumbers: boolean; onLineClick?: (lineNumber: number) => void }) {
if (line.type === 'header') {
return (
@@ -198,6 +201,7 @@ export function FileDiffView({ repoId, filePath, onBack, onOpenFile, isMobile =
<span className="text-red-500">-{diffData.deletions}</span>
</>
)}
{diffData.diff && <CopyButton content={diffData.diff} title="Copy diff" iconSize="sm" variant="ghost" />}
</div>
</div>
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { useState, useMemo } from 'react'
import { useGitStatus } from '@/api/git'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, ChevronRight, ArrowUp, ArrowDown } from 'lucide-react'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, ChevronRight, ChevronDown, ArrowUp, ArrowDown, Folder, FolderOpen } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { GitFileStatus, GitFileStatusType } from '@/types/git'
@@ -10,6 +10,16 @@ interface GitChangesPanelProps {
selectedFile?: string
}
interface GitTreeNode {
name: string
path: string
isDirectory: boolean
children: GitTreeNode[]
file?: GitFileStatus
fileCount: number
statusCounts: Partial<Record<GitFileStatusType, number>>
}
const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: string; label: string }> = {
modified: { icon: FileEdit, color: 'text-yellow-500', label: 'Modified' },
added: { icon: FilePlus, color: 'text-green-500', label: 'Added' },
@@ -19,31 +29,201 @@ const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: st
copied: { icon: FileText, color: 'text-purple-500', label: 'Copied' },
}
function FileStatusItem({ file, isSelected, onClick }: { file: GitFileStatus; isSelected: boolean; onClick: () => void }) {
function buildTree(files: GitFileStatus[]): GitTreeNode[] {
const root: GitTreeNode[] = []
const nodeMap = new Map<string, GitTreeNode>()
for (const file of files) {
const isDirectoryPath = file.path.endsWith('/')
const cleanPath = isDirectoryPath ? file.path.slice(0, -1) : file.path
const parts = cleanPath.split('/').filter(p => p)
if (parts.length === 0) continue
let currentPath = ''
let currentLevel = root
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
const isLast = i === parts.length - 1
currentPath = currentPath ? `${currentPath}/${part}` : part
let node = nodeMap.get(currentPath)
if (!node) {
const isDir = !isLast || isDirectoryPath
node = {
name: part,
path: currentPath,
isDirectory: isDir,
children: [],
file: (isLast && !isDirectoryPath) ? file : undefined,
fileCount: 0,
statusCounts: isDirectoryPath && isLast ? { [file.status]: 1 } : {},
}
nodeMap.set(currentPath, node)
currentLevel.push(node)
} else if (isLast && isDirectoryPath) {
node.statusCounts[file.status] = (node.statusCounts[file.status] || 0) + 1
}
if (isLast && !isDirectoryPath) {
node.file = file
node.isDirectory = false
}
currentLevel = node.children
}
}
function aggregateCounts(node: GitTreeNode): void {
if (node.isDirectory) {
const existingCounts = { ...node.statusCounts }
node.fileCount = 0
node.statusCounts = {}
if (node.children.length === 0) {
node.statusCounts = existingCounts
node.fileCount = Object.values(existingCounts).reduce((a, b) => a + (b || 0), 0) || 1
} else {
for (const child of node.children) {
aggregateCounts(child)
node.fileCount += child.isDirectory ? child.fileCount : 1
for (const [status, count] of Object.entries(child.statusCounts)) {
node.statusCounts[status as GitFileStatusType] =
(node.statusCounts[status as GitFileStatusType] || 0) + (count as number)
}
if (child.file) {
node.statusCounts[child.file.status] =
(node.statusCounts[child.file.status] || 0) + 1
}
}
}
}
}
function sortNodes(nodes: GitTreeNode[]): GitTreeNode[] {
return nodes.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1
if (!a.isDirectory && b.isDirectory) return 1
return a.name.localeCompare(b.name)
}).map(node => ({
...node,
children: sortNodes(node.children)
}))
}
for (const node of root) {
aggregateCounts(node)
}
return sortNodes(root)
}
function filterTree(nodes: GitTreeNode[], filter: GitFileStatusType | 'all'): GitTreeNode[] {
if (filter === 'all') return nodes
return nodes
.map(node => {
if (node.isDirectory) {
const filteredChildren = filterTree(node.children, filter)
if (filteredChildren.length === 0) return null
return { ...node, children: filteredChildren }
}
return node.file?.status === filter ? node : null
})
.filter((node): node is GitTreeNode => node !== null)
}
interface GitTreeNodeItemProps {
node: GitTreeNode
level: number
selectedFile?: string
expandedPaths: Set<string>
onToggle: (path: string) => void
onSelect: (path: string) => void
}
function GitTreeNodeItem({ node, level, selectedFile, expandedPaths, onToggle, onSelect }: GitTreeNodeItemProps) {
const isExpanded = expandedPaths.has(node.path)
const isSelected = selectedFile === node.path
if (node.isDirectory) {
const statusEntries = Object.entries(node.statusCounts) as [GitFileStatusType, number][]
const dominantStatus = statusEntries.length > 0
? statusEntries.reduce((a, b) => a[1] > b[1] ? a : b)[0]
: null
return (
<div>
<button
onClick={() => onToggle(node.path)}
className={cn(
'w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-accent/50 transition-colors rounded-md'
)}
style={{ paddingLeft: `${level * 12 + 12}px` }}
>
<span className="w-4 h-4 flex items-center justify-center flex-shrink-0">
{isExpanded ? (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
)}
</span>
{isExpanded ? (
<FolderOpen className="w-4 h-4 text-muted-foreground flex-shrink-0" />
) : (
<Folder className="w-4 h-4 text-muted-foreground flex-shrink-0" />
)}
<span className="text-sm text-foreground truncate flex-1">{node.name}</span>
<div className="flex items-center gap-1 flex-shrink-0">
{dominantStatus && (
<span className={cn('text-[10px] px-1 py-0.5 rounded', statusConfig[dominantStatus].color)}>
{node.fileCount}
</span>
)}
</div>
</button>
{isExpanded && (
<div>
{node.children.map(child => (
<GitTreeNodeItem
key={child.path}
node={child}
level={level + 1}
selectedFile={selectedFile}
expandedPaths={expandedPaths}
onToggle={onToggle}
onSelect={onSelect}
/>
))}
</div>
)}
</div>
)
}
const file = node.file!
const config = statusConfig[file.status]
const Icon = config.icon
const fileName = file.path.split('/').pop() || file.path
const dirPath = file.path.includes('/') ? file.path.substring(0, file.path.lastIndexOf('/')) : ''
return (
<button
onClick={onClick}
onClick={() => onSelect(node.path)}
className={cn(
'w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-accent/50 transition-colors rounded-md',
isSelected && 'bg-accent'
)}
style={{ paddingLeft: `${level * 12 + 12}px` }}
>
<span className="w-4 h-4 flex-shrink-0" />
<Icon className={cn('w-4 h-4 flex-shrink-0', config.color)} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1">
<span className="text-sm text-foreground truncate">{fileName}</span>
<span className="text-sm text-foreground truncate">{node.name}</span>
{file.staged && (
<span className="text-[10px] px-1 py-0.5 bg-green-500/20 text-green-500 rounded">staged</span>
)}
</div>
{dirPath && (
<span className="text-xs text-muted-foreground truncate block">{dirPath}</span>
)}
{file.oldPath && (
<span className="text-xs text-muted-foreground truncate block">← {file.oldPath}</span>
)}
@@ -56,6 +236,28 @@ function FileStatusItem({ file, isSelected, onClick }: { file: GitFileStatus; is
export function GitChangesPanel({ repoId, onFileSelect, selectedFile }: GitChangesPanelProps) {
const { data: status, isLoading, error } = useGitStatus(repoId)
const [filter, setFilter] = useState<GitFileStatusType | 'all'>('all')
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(new Set())
const tree = useMemo(() => {
if (!status?.files) return []
return buildTree(status.files)
}, [status?.files])
const filteredTree = useMemo(() => {
return filterTree(tree, filter)
}, [tree, filter])
const handleToggle = (path: string) => {
setExpandedPaths(prev => {
const next = new Set(prev)
if (next.has(path)) {
next.delete(path)
} else {
next.add(path)
}
return next
})
}
if (isLoading) {
return (
@@ -83,10 +285,6 @@ export function GitChangesPanel({ repoId, onFileSelect, selectedFile }: GitChang
)
}
const filteredFiles = filter === 'all'
? status.files
: status.files.filter(f => f.status === filter)
const statusCounts = status.files.reduce((acc, file) => {
acc[file.status] = (acc[file.status] || 0) + 1
return acc
@@ -140,13 +338,16 @@ export function GitChangesPanel({ repoId, onFileSelect, selectedFile }: GitChang
</div>
</div>
<div className="flex-1 overflow-y-auto p-2">
<div className="space-y-1 pb-8">
{filteredFiles.map((file) => (
<FileStatusItem
key={`${file.path}-${file.staged}`}
file={file}
isSelected={selectedFile === file.path}
onClick={() => onFileSelect(file.path)}
<div className="space-y-0.5 pb-8">
{filteredTree.map((node) => (
<GitTreeNodeItem
key={node.path}
node={node}
level={0}
selectedFile={selectedFile}
expandedPaths={expandedPaths}
onToggle={handleToggle}
onSelect={onFileSelect}
/>
))}
</div>
@@ -1,5 +1,5 @@
import React from 'react'
import { Copy } from 'lucide-react'
import { CopyButton } from '@/components/ui/copy-button'
import { useMobile } from '@/hooks/useMobile'
import { cn } from '@/lib/utils'
@@ -59,7 +59,6 @@ function detectLanguage(fileName: string): string {
export function CodePreview({ fileName, content }: CodePreviewProps) {
const isMobile = useMobile()
const [copied, setCopied] = React.useState(false)
const [showMore, setShowMore] = React.useState(false)
const language = detectLanguage(fileName)
@@ -73,27 +72,11 @@ export function CodePreview({ fileName, content }: CodePreviewProps) {
? lines.slice(0, INITIAL_CODE_LINES).join('\n')
: content
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) {
console.error('Failed to copy:', err)
}
}
return (
<div className="flex flex-col bg-background">
<div className="px-3 py-2 bg-muted/30 border-b border-border/50 flex items-center justify-between text-xs">
<span className="font-medium truncate flex-1">{extractFileFromPath(fileName)}</span>
<button
onClick={handleCopy}
className="p-1 hover:bg-accent rounded flex-shrink-0"
title={copied ? 'Copied!' : 'Copy'}
>
<Copy className={cn('w-3.5 h-3.5', copied && 'text-green-500')} />
</button>
<CopyButton content={content} title="Copy" iconSize="sm" variant="ghost" className="flex-shrink-0" />
</div>
<div className={cn('overflow-y-auto', isMobile ? 'max-h-64' : 'max-h-96')}>
@@ -145,7 +145,8 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
)
case 'step-finish': {
const isFree = part.cost === 0
const costText = isMobile && isFree ? null : <span>${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
const totalTokens = part.tokens.input + part.tokens.output + (part.tokens.cache?.read || 0)
const costText = isMobile && isFree ? null : <span>${part.cost.toFixed(4)} • {totalTokens} tokens</span>
return (
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
{costText}
+5 -45
View File
@@ -4,7 +4,8 @@ import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import mermaid from 'mermaid'
import { Copy, Check, Maximize2, X, AlertCircle } from 'lucide-react'
import { Maximize2, X, AlertCircle } from 'lucide-react'
import { CopyButton } from '@/components/ui/copy-button'
import type { components } from '@/api/opencode-types'
import { useTheme } from '@/hooks/useTheme'
import 'highlight.js/styles/github-dark.css'
@@ -23,7 +24,6 @@ function MermaidBlock({ code }: MermaidBlockProps) {
const [svg, setSvg] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [isExpanded, setIsExpanded] = useState(false)
const [copied, setCopied] = useState(false)
const theme = useTheme()
const uniqueId = useId().replace(/:/g, '-')
const renderAttempt = React.useRef(0)
@@ -71,16 +71,6 @@ function MermaidBlock({ code }: MermaidBlockProps) {
renderDiagram()
}, [renderDiagram, theme])
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(code)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) {
console.error('Failed to copy:', err)
}
}
if (error) {
return (
<div className="relative my-4">
@@ -94,13 +84,7 @@ function MermaidBlock({ code }: MermaidBlockProps) {
<code>{code}</code>
</pre>
</div>
<button
onClick={handleCopy}
className="absolute top-2 right-2 p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground"
title="Copy code"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</button>
<CopyButton content={code} title="Copy code" className="absolute top-2 right-2" />
</div>
)
}
@@ -128,13 +112,7 @@ function MermaidBlock({ code }: MermaidBlockProps) {
>
<Maximize2 className="w-4 h-4" />
</button>
<button
onClick={handleCopy}
className="p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground"
title="Copy code"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</button>
<CopyButton content={code} title="Copy code" />
</div>
</div>
@@ -172,8 +150,6 @@ interface CodeBlockProps {
}
function CodeBlock({ children, className, ...props }: CodeBlockProps) {
const [copied, setCopied] = React.useState(false)
const extractTextContent = (node: React.ReactNode): string => {
if (typeof node === 'string') return node
if (typeof node === 'number') return node.toString()
@@ -188,29 +164,13 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) {
}
const codeContent = extractTextContent(children)
const handleCopyCode = async () => {
try {
await navigator.clipboard.writeText(codeContent)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy code:', error)
}
}
return (
<div className="relative">
<pre className={`bg-accent p-1 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
{children}
</pre>
<button
onClick={handleCopyCode}
className="absolute top-2 right-2 p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground"
title="Copy code"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</button>
<CopyButton content={codeContent} title="Copy code" className="absolute top-2 right-2" />
</div>
)
}
@@ -247,11 +247,12 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
</span>
)}
</div>
<pre className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => navigator.clipboard.writeText(output)}
title="Click to copy output">
{output}
</pre>
<div className="relative">
<pre className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap">
{output}
</pre>
<CopyButton content={output} title="Copy output" className="absolute top-2 right-2" />
</div>
</div>
)
}
@@ -387,11 +388,14 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
)}
<div className="text-sm">
<div className="text-muted-foreground mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => part.state.status === 'completed' && navigator.clipboard.writeText(part.state.output)}
title="Click to copy output">
{part.state.status === 'completed' ? part.state.output : ''}
</pre>
<div className="relative">
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all">
{part.state.status === 'completed' ? part.state.output : ''}
</pre>
{part.state.status === 'completed' && part.state.output && (
<CopyButton content={part.state.output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
)}
</div>
</div>
{part.state.time && (
<div className="text-xs text-muted-foreground">
+32 -8
View File
@@ -1,17 +1,32 @@
import { Copy } from 'lucide-react'
import { useState } from 'react'
import { Copy, Check } from 'lucide-react'
import { cn } from '@/lib/utils'
interface CopyButtonProps {
content: string
title: string
title?: string
className?: string
iconSize?: 'sm' | 'md'
variant?: 'default' | 'ghost'
}
export function CopyButton({ content, title, className = "" }: CopyButtonProps) {
export function CopyButton({
content,
title = 'Copy',
className = '',
iconSize = 'md',
variant = 'default'
}: CopyButtonProps) {
const [copied, setCopied] = useState(false)
const handleCopy = async () => {
if (!content.trim()) return
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch {
// Clipboard access denied or not supported
}
}
@@ -19,13 +34,22 @@ export function CopyButton({ content, title, className = "" }: CopyButtonProps)
return null
}
const sizeClasses = iconSize === 'sm' ? 'w-3.5 h-3.5' : 'w-4 h-4'
const variantClasses = variant === 'ghost'
? 'p-1 hover:bg-accent rounded'
: 'p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground'
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
className={cn(variantClasses, className)}
title={copied ? 'Copied!' : title}
>
<Copy className="w-4 h-4" />
{copied ? (
<Check className={cn(sizeClasses, 'text-green-500')} />
) : (
<Copy className={cn(sizeClasses, copied && 'text-green-500')} />
)}
</button>
)
}
+2 -2
View File
@@ -58,7 +58,7 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
let latestAssistantMessage = assistantMessages[assistantMessages.length - 1]
if (latestAssistantMessage?.info.role === 'assistant') {
const tokens = latestAssistantMessage.info.tokens.input + latestAssistantMessage.info.tokens.output + latestAssistantMessage.info.tokens.reasoning
const tokens = latestAssistantMessage.info.tokens.input + latestAssistantMessage.info.tokens.output + latestAssistantMessage.info.tokens.reasoning + (latestAssistantMessage.info.tokens.cache?.read || 0)
if (tokens === 0 && assistantMessages.length > 1) {
latestAssistantMessage = assistantMessages[assistantMessages.length - 2]
}
@@ -88,7 +88,7 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
let totalTokens = 0
if (latestAssistantMessage?.info.role === 'assistant') {
totalTokens = latestAssistantMessage.info.tokens.input + latestAssistantMessage.info.tokens.output + latestAssistantMessage.info.tokens.reasoning
totalTokens = latestAssistantMessage.info.tokens.input + latestAssistantMessage.info.tokens.output + latestAssistantMessage.info.tokens.reasoning + (latestAssistantMessage.info.tokens.cache?.read || 0)
}
const usagePercentage = contextLimit ? (totalTokens / contextLimit) * 100 : null
+3
View File
@@ -12,6 +12,9 @@
"build": "pnpm run build:backend && pnpm run build:frontend",
"build:backend": "pnpm --filter backend build",
"build:frontend": "pnpm --filter frontend build",
"typecheck": "pnpm run typecheck:frontend && pnpm run typecheck:backend",
"typecheck:frontend": "pnpm --filter frontend typecheck",
"typecheck:backend": "pnpm --filter backend typecheck",
"test": "pnpm run test:backend",
"test:backend": "pnpm --filter backend test",
"lint": "pnpm run lint:frontend && pnpm run lint:backend",