mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
16 files changed
+734
-50
No files matched your search
@@ -2,14 +2,14 @@
|
||||
|
||||
## Commands
|
||||
|
||||
- `npm run dev` - Start both backend (5001) and frontend (5173)
|
||||
- `npm run dev:backend` - Backend only: `bun --watch backend/src/index.ts`
|
||||
- `npm run dev:frontend` - Frontend only: `cd frontend && vite`
|
||||
- `npm run build` - Build both backend and frontend
|
||||
- `npm run test` - Run backend tests: `cd backend && bun test`
|
||||
- `pnpm dev` - Start both backend (5001) and frontend (5173)
|
||||
- `pnpm dev:backend` - Backend only: `bun --watch backend/src/index.ts`
|
||||
- `pnpm dev:frontend` - Frontend only: `cd frontend && vite`
|
||||
- `pnpm build` - Build both backend and frontend
|
||||
- `pnpm test` - Run backend tests: `cd backend && bun test`
|
||||
- `cd backend && bun test <filename>` - Run single test file
|
||||
- `cd backend && vitest --ui` - Test UI with coverage
|
||||
- `cd backend && vitest --coverage` - Coverage report
|
||||
- `cd backend && vitest --coverage` - Coverage report (80% threshold)
|
||||
- `cd frontend && npm run lint` - Frontend linting
|
||||
|
||||
## Code Style
|
||||
@@ -20,16 +20,17 @@
|
||||
|
||||
### Backend (Bun + Hono)
|
||||
|
||||
- Hono framework with Zod validation
|
||||
- Error handling with try/catch and logging
|
||||
- Hono framework with Zod validation, Better SQLite3 database
|
||||
- Error handling with try/catch and structured logging
|
||||
- Follow existing route/service/utility structure
|
||||
- Use async/await consistently, avoid .then() chains
|
||||
- Test coverage: 80% minimum required
|
||||
|
||||
### Frontend (React + Vite)
|
||||
|
||||
- @/ alias for components: `import { Button } from '@/components/ui/button'`
|
||||
- Radix UI + Tailwind CSS, React Hook Form + Zod
|
||||
- React Query for state management
|
||||
- React Query (@tanstack/react-query) for state management
|
||||
- ESLint TypeScript rules enforced
|
||||
- Use React hooks properly, no direct state mutations
|
||||
|
||||
@@ -37,5 +38,6 @@
|
||||
|
||||
- DRY principles, follow existing patterns
|
||||
- ./temp/opencode is reference only, never commit has opencode src
|
||||
- Use shared types from workspace package
|
||||
- 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
|
||||
@@ -138,6 +138,9 @@ export function createSettingsRoutes(db: Database) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('already exists')) {
|
||||
return c.json({ error: error.message }, 409)
|
||||
}
|
||||
return c.json({ error: 'Failed to create OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -156,6 +156,12 @@ export class SettingsService {
|
||||
request: CreateOpenCodeConfigRequest,
|
||||
userId: string = 'default'
|
||||
): OpenCodeConfigWithRaw {
|
||||
// Check for existing config with the same name
|
||||
const existing = this.getOpenCodeConfigByName(request.name, userId)
|
||||
if (existing) {
|
||||
throw new Error(`Config with name '${request.name}' already exists`)
|
||||
}
|
||||
|
||||
const rawContent = typeof request.content === 'string'
|
||||
? request.content
|
||||
: JSON.stringify(request.content, null, 2)
|
||||
|
||||
@@ -127,6 +127,16 @@ export class OpenCodeClient {
|
||||
return response.data
|
||||
}
|
||||
|
||||
async revertMessage(sessionID: string, data: { messageID: string, partID?: string }) {
|
||||
const response = await this.client.post(`/session/${sessionID}/revert`, data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
async unrevertSession(sessionID: string) {
|
||||
const response = await this.client.post(`/session/${sessionID}/unrevert`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
getEventSourceURL() {
|
||||
const base = this.baseURL.startsWith('http')
|
||||
? this.baseURL
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { memo, useState, useRef, useEffect } from 'react'
|
||||
import { Send, X, Pencil, Loader2 } from 'lucide-react'
|
||||
import { useRefreshMessage } from '@/hooks/useRemoveMessage'
|
||||
|
||||
interface EditableUserMessageProps {
|
||||
opcodeUrl: string
|
||||
sessionId: string
|
||||
directory?: string
|
||||
content: string
|
||||
assistantMessageId: string
|
||||
onCancel: () => void
|
||||
model?: string
|
||||
agent?: string
|
||||
}
|
||||
|
||||
export const EditableUserMessage = memo(function EditableUserMessage({
|
||||
opcodeUrl,
|
||||
sessionId,
|
||||
directory,
|
||||
content,
|
||||
assistantMessageId,
|
||||
onCancel,
|
||||
model,
|
||||
agent
|
||||
}: EditableUserMessageProps) {
|
||||
const [editedContent, setEditedContent] = useState(content)
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const refreshMessage = useRefreshMessage({ opcodeUrl, sessionId, directory })
|
||||
|
||||
useEffect(() => {
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
textareaRef.current.setSelectionRange(
|
||||
textareaRef.current.value.length,
|
||||
textareaRef.current.value.length
|
||||
)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
|
||||
}
|
||||
}, [editedContent])
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!editedContent.trim() || refreshMessage.isPending) return
|
||||
|
||||
refreshMessage.mutate({
|
||||
assistantMessageID: assistantMessageId,
|
||||
userMessageContent: editedContent.trim(),
|
||||
model,
|
||||
agent
|
||||
}, {
|
||||
onSuccess: () => {
|
||||
onCancel()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault()
|
||||
handleSubmit()
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
onCancel()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={editedContent}
|
||||
onChange={(e) => setEditedContent(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="w-full p-3 rounded-lg bg-background border border-primary/50 focus:border-primary focus:ring-1 focus:ring-primary outline-none resize-none min-h-[60px] text-sm"
|
||||
placeholder="Edit your message..."
|
||||
disabled={refreshMessage.isPending}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Press <kbd className="px-1 py-0.5 rounded bg-muted text-xs">Cmd+Enter</kbd> to send, <kbd className="px-1 py-0.5 rounded bg-muted text-xs">Esc</kbd> to cancel
|
||||
</span>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={onCancel}
|
||||
disabled={refreshMessage.isPending}
|
||||
className="flex items-center gap-1 px-3 py-1.5 rounded text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-50"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!editedContent.trim() || refreshMessage.isPending}
|
||||
className="flex items-center gap-1 px-3 py-1.5 rounded text-sm bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
|
||||
>
|
||||
{refreshMessage.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="w-4 h-4" />
|
||||
)}
|
||||
Resend
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
interface ClickableUserMessageProps {
|
||||
content: string
|
||||
onClick: () => void
|
||||
isEditable: boolean
|
||||
}
|
||||
|
||||
export const ClickableUserMessage = memo(function ClickableUserMessage({
|
||||
content,
|
||||
onClick,
|
||||
isEditable
|
||||
}: ClickableUserMessageProps) {
|
||||
if (!isEditable) {
|
||||
return (
|
||||
<div className="text-sm whitespace-pre-wrap break-words">
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="text-left text-sm whitespace-pre-wrap break-words w-full group/edit hover:bg-blue-600/10 rounded p-1 -m-1 transition-colors"
|
||||
title="Click to edit and resend"
|
||||
>
|
||||
<span>{content}</span>
|
||||
<Pencil className="w-3 h-3 inline-block ml-2 opacity-0 group-hover/edit:opacity-70 transition-opacity" />
|
||||
</button>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { memo } from 'react'
|
||||
import { X, RefreshCw, Loader2 } from 'lucide-react'
|
||||
import { useRemoveMessage, useRefreshMessage } from '@/hooks/useRemoveMessage'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
|
||||
interface MessageActionButtonsProps {
|
||||
opcodeUrl: string
|
||||
sessionId: string
|
||||
directory?: string
|
||||
message: MessageWithParts
|
||||
isLastAssistantMessage: boolean
|
||||
userMessageContent?: string
|
||||
onEditUserMessage?: () => void
|
||||
model?: string
|
||||
agent?: string
|
||||
}
|
||||
|
||||
export const MessageActionButtons = memo(function MessageActionButtons({
|
||||
opcodeUrl,
|
||||
sessionId,
|
||||
directory,
|
||||
message,
|
||||
isLastAssistantMessage,
|
||||
userMessageContent,
|
||||
onEditUserMessage,
|
||||
model,
|
||||
agent
|
||||
}: MessageActionButtonsProps) {
|
||||
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
|
||||
const refreshMessage = useRefreshMessage({ opcodeUrl, sessionId, directory })
|
||||
|
||||
const isLoading = removeMessage.isPending || refreshMessage.isPending
|
||||
|
||||
const handleRemove = () => {
|
||||
if (isLoading) return
|
||||
removeMessage.mutate({ messageID: message.info.id })
|
||||
}
|
||||
|
||||
const handleRefresh = () => {
|
||||
if (isLoading || !userMessageContent) return
|
||||
|
||||
if (onEditUserMessage) {
|
||||
onEditUserMessage()
|
||||
} else {
|
||||
refreshMessage.mutate({
|
||||
assistantMessageID: message.info.id,
|
||||
userMessageContent,
|
||||
model,
|
||||
agent
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (message.info.role !== 'assistant') {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
onClick={handleRemove}
|
||||
disabled={isLoading}
|
||||
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>
|
||||
|
||||
{isLastAssistantMessage && userMessageContent && (
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={isLoading}
|
||||
className="p-1 rounded hover:bg-primary/20 text-muted-foreground hover:text-primary transition-colors disabled:opacity-50"
|
||||
title="Try this prompt again"
|
||||
>
|
||||
{refreshMessage.isPending ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -65,13 +65,13 @@ interface TTSButtonProps {
|
||||
}
|
||||
|
||||
export function TTSButton({ content, className = "" }: TTSButtonProps) {
|
||||
const { speak, stop, isEnabled, isPlaying, isLoading, currentText } = useTTS()
|
||||
const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS()
|
||||
|
||||
if (!isEnabled || !content.trim()) {
|
||||
return null
|
||||
}
|
||||
|
||||
const isThisPlaying = (isPlaying || isLoading) && currentText === content
|
||||
const isThisPlaying = (isPlaying || isLoading) && originalText === content
|
||||
|
||||
const handleClick = () => {
|
||||
if (isThisPlaying) {
|
||||
@@ -86,7 +86,7 @@ export function TTSButton({ content, className = "" }: TTSButtonProps) {
|
||||
onClick={handleClick}
|
||||
className={`p-1.5 rounded ${isThisPlaying ? 'bg-red-500/20 text-red-500 hover:bg-red-500/30' : 'bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground'} ${className}`}
|
||||
title={isThisPlaying ? "Stop playback" : "Read aloud"}
|
||||
disabled={isLoading && currentText !== content}
|
||||
disabled={isLoading && originalText !== content}
|
||||
>
|
||||
{isLoading && isThisPlaying ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import { memo, useMemo, useState, useCallback } from 'react'
|
||||
import { MessagePart } from './MessagePart'
|
||||
import { MessageActionButtons } from './MessageActionButtons'
|
||||
import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
|
||||
function getMessageTextContent(msg: MessageWithParts): string {
|
||||
@@ -17,6 +19,8 @@ interface MessageThreadProps {
|
||||
messages?: MessageWithParts[]
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onChildSessionClick?: (sessionId: string) => void
|
||||
model?: string
|
||||
agent?: string
|
||||
}
|
||||
|
||||
const isMessageStreaming = (msg: MessageWithParts): boolean => {
|
||||
@@ -24,8 +28,6 @@ const isMessageStreaming = (msg: MessageWithParts): boolean => {
|
||||
return !('completed' in msg.info.time && msg.info.time.completed)
|
||||
}
|
||||
|
||||
|
||||
|
||||
const findPendingAssistantMessageId = (messages: MessageWithParts[]): string | undefined => {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i]
|
||||
@@ -36,11 +38,64 @@ const findPendingAssistantMessageId = (messages: MessageWithParts[]): string | u
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const MessageThread = memo(function MessageThread({ messages, onFileClick, onChildSessionClick }: MessageThreadProps) {
|
||||
const findLastAssistantMessageId = (messages: MessageWithParts[]): string | undefined => {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].info.role === 'assistant') {
|
||||
return messages[i].info.id
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const findUserMessageBeforeAssistant = (
|
||||
messages: MessageWithParts[],
|
||||
assistantMessageId: string
|
||||
): string | undefined => {
|
||||
const assistantIndex = messages.findIndex(m => m.info.id === assistantMessageId)
|
||||
if (assistantIndex <= 0) return undefined
|
||||
|
||||
for (let i = assistantIndex - 1; i >= 0; i--) {
|
||||
if (messages[i].info.role === 'user') {
|
||||
return getMessageTextContent(messages[i])
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const MessageThread = memo(function MessageThread({
|
||||
opcodeUrl,
|
||||
sessionID,
|
||||
directory,
|
||||
messages,
|
||||
onFileClick,
|
||||
onChildSessionClick,
|
||||
model,
|
||||
agent
|
||||
}: MessageThreadProps) {
|
||||
const [editingUserMessageId, setEditingUserMessageId] = useState<string | null>(null)
|
||||
const [editingForAssistantId, setEditingForAssistantId] = useState<string | null>(null)
|
||||
|
||||
const pendingAssistantId = useMemo(() => {
|
||||
if (!messages) return undefined
|
||||
return findPendingAssistantMessageId(messages)
|
||||
}, [messages])
|
||||
|
||||
const lastAssistantId = useMemo(() => {
|
||||
if (!messages) return undefined
|
||||
return findLastAssistantMessageId(messages)
|
||||
}, [messages])
|
||||
|
||||
const isSessionBusy = !!pendingAssistantId
|
||||
|
||||
const handleStartEditUserMessage = useCallback((userMessageId: string, assistantMessageId: string) => {
|
||||
setEditingUserMessageId(userMessageId)
|
||||
setEditingForAssistantId(assistantMessageId)
|
||||
}, [])
|
||||
|
||||
const handleCancelEdit = useCallback(() => {
|
||||
setEditingUserMessageId(null)
|
||||
setEditingForAssistantId(null)
|
||||
}, [])
|
||||
|
||||
if (!messages || messages.length === 0) {
|
||||
return (
|
||||
@@ -52,54 +107,108 @@ export const MessageThread = memo(function MessageThread({ messages, onFileClick
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-2 p-2 overflow-x-hidden">
|
||||
{messages.map((msg) => {
|
||||
{messages.map((msg, index) => {
|
||||
const streaming = isMessageStreaming(msg)
|
||||
const isQueued = msg.info.role === 'user' && pendingAssistantId && msg.info.id > pendingAssistantId
|
||||
const isLastAssistant = msg.info.id === lastAssistantId
|
||||
const messageTextContent = getMessageTextContent(msg)
|
||||
|
||||
const nextAssistantMessage = messages.slice(index + 1).find(m => m.info.role === 'assistant')
|
||||
const isUserBeforeAssistant = msg.info.role === 'user' && nextAssistantMessage
|
||||
const canEditUserMessage = isUserBeforeAssistant && nextAssistantMessage?.info.id === lastAssistantId && !isSessionBusy
|
||||
|
||||
const userMessageContent = msg.info.role === 'assistant'
|
||||
? findUserMessageBeforeAssistant(messages, msg.info.id)
|
||||
: undefined
|
||||
|
||||
const isEditingThisMessage = editingUserMessageId === msg.info.id
|
||||
|
||||
return (
|
||||
<div
|
||||
key={msg.info.id}
|
||||
className="flex flex-col"
|
||||
className="flex flex-col group"
|
||||
>
|
||||
<div
|
||||
className={`w-full rounded-lg p-1.5 ${
|
||||
msg.info.role === 'user'
|
||||
? isQueued
|
||||
? 'bg-amber-500/10 border border-amber-500/30'
|
||||
: 'bg-blue-600/20 border border-blue-600/30'
|
||||
: isEditingThisMessage
|
||||
? 'bg-blue-600/30 border border-blue-600/50'
|
||||
: 'bg-blue-600/20 border border-blue-600/30'
|
||||
: 'bg-card/50 border border-border'
|
||||
} ${streaming ? 'animate-pulse-subtle' : ''}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')}
|
||||
</span>
|
||||
{msg.info.time && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(msg.info.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
)}
|
||||
{isQueued && (
|
||||
<span className="text-xs font-semibold bg-amber-500 text-amber-950 px-1.5 py-0.5 rounded">
|
||||
QUEUED
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')}
|
||||
</span>
|
||||
{msg.info.time && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(msg.info.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
)}
|
||||
{isQueued && (
|
||||
<span className="text-xs font-semibold bg-amber-500 text-amber-950 px-1.5 py-0.5 rounded">
|
||||
QUEUED
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{msg.info.role === 'assistant' && !streaming && !isSessionBusy && (
|
||||
<MessageActionButtons
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
message={msg}
|
||||
isLastAssistantMessage={isLastAssistant}
|
||||
userMessageContent={userMessageContent}
|
||||
onEditUserMessage={userMessageContent ? () => {
|
||||
const userMsg = messages.slice(0, index).reverse().find(m => m.info.role === 'user')
|
||||
if (userMsg) {
|
||||
handleStartEditUserMessage(userMsg.info.id, msg.info.id)
|
||||
}
|
||||
} : undefined}
|
||||
model={model}
|
||||
agent={agent}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{msg.parts.map((part, index) => (
|
||||
<div key={`${msg.info.id}-${part.id}-${index}`}>
|
||||
<MessagePart
|
||||
part={part}
|
||||
role={msg.info.role}
|
||||
allParts={msg.parts}
|
||||
partIndex={index}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
messageTextContent={msg.info.role === 'assistant' ? getMessageTextContent(msg) : undefined}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{msg.info.role === 'user' && isEditingThisMessage && editingForAssistantId ? (
|
||||
<EditableUserMessage
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
content={messageTextContent}
|
||||
assistantMessageId={editingForAssistantId}
|
||||
onCancel={handleCancelEdit}
|
||||
model={model}
|
||||
agent={agent}
|
||||
/>
|
||||
) : msg.info.role === 'user' && canEditUserMessage && nextAssistantMessage ? (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => handleStartEditUserMessage(msg.info.id, nextAssistantMessage.info.id)}
|
||||
isEditable={true}
|
||||
/>
|
||||
) : (
|
||||
msg.parts.map((part, partIndex) => (
|
||||
<div key={`${msg.info.id}-${part.id}-${partIndex}`}>
|
||||
<MessagePart
|
||||
part={part}
|
||||
role={msg.info.role}
|
||||
allParts={msg.parts}
|
||||
partIndex={partIndex}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
messageTextContent={msg.info.role === 'assistant' ? messageTextContent : undefined}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -107,4 +216,4 @@ export const MessageThread = memo(function MessageThread({ messages, onFileClick
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -243,7 +243,7 @@ export function TextPart({ part }: TextPartProps) {
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight, rehypeRaw]}
|
||||
components={{
|
||||
code({ className, children, node, ...props }) {
|
||||
code({ className, children, ...props }) {
|
||||
const isInline = !className || !className.includes('language-')
|
||||
|
||||
if (className?.includes('language-mermaid') && mermaidComplete) {
|
||||
|
||||
@@ -36,7 +36,7 @@ export function CreateConfigDialog({ isOpen, onOpenChange, onCreate, isUpdating
|
||||
setIsDefault(false)
|
||||
setError('')
|
||||
setErrorLine(null)
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SyntaxError) {
|
||||
const match = error.message.match(/line (\d+)/i)
|
||||
const line = match ? parseInt(match[1]) : null
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState, useRef, useCallback, useEffect, type ReactNode } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { TTSContext, type TTSState } from './tts-context'
|
||||
import { sanitizeForTTS } from '@/lib/utils'
|
||||
|
||||
export { TTSContext, type TTSContextValue, type TTSState } from './tts-context'
|
||||
|
||||
@@ -30,6 +31,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const [state, setState] = useState<TTSState>('idle')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [currentText, setCurrentText] = useState<string | null>(null)
|
||||
const [originalText, setOriginalText] = useState<string | null>(null)
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
@@ -66,6 +68,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
cleanup()
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setOriginalText(null)
|
||||
setError(null)
|
||||
}, [cleanup])
|
||||
|
||||
@@ -226,13 +229,24 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Sanitize markdown for clean TTS playback
|
||||
const sanitizedText = sanitizeForTTS(text)
|
||||
|
||||
if (!sanitizedText?.trim()) {
|
||||
setError('No readable content after sanitization')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
stop()
|
||||
stoppedRef.current = false
|
||||
setError(null)
|
||||
setCurrentText(text)
|
||||
|
||||
setOriginalText(text)
|
||||
setCurrentText(sanitizedText)
|
||||
|
||||
abortControllerRef.current = new AbortController()
|
||||
chunksRef.current = splitIntoChunks(text)
|
||||
chunksRef.current = splitIntoChunks(sanitizedText)
|
||||
|
||||
playChunk(0)
|
||||
|
||||
@@ -245,6 +259,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
state,
|
||||
error,
|
||||
currentText,
|
||||
originalText,
|
||||
isEnabled,
|
||||
isPlaying: state === 'playing',
|
||||
isLoading: state === 'loading',
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface TTSContextValue {
|
||||
state: TTSState
|
||||
error: string | null
|
||||
currentText: string | null
|
||||
originalText: string | null
|
||||
isEnabled: boolean
|
||||
isPlaying: boolean
|
||||
isLoading: boolean
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { createOpenCodeClient } from '@/api/opencode'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { MessageListResponse } from '@/api/types'
|
||||
|
||||
interface UseRemoveMessageOptions {
|
||||
opcodeUrl: string | null
|
||||
sessionId: string
|
||||
directory?: string
|
||||
}
|
||||
|
||||
export function useRemoveMessage({ opcodeUrl, sessionId, directory }: UseRemoveMessageOptions) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ messageID, partID }: { messageID: string, partID?: string }) => {
|
||||
if (!opcodeUrl) throw new Error('OpenCode URL not available')
|
||||
|
||||
const client = createOpenCodeClient(opcodeUrl, directory)
|
||||
return client.revertMessage(sessionId, { messageID, partID })
|
||||
},
|
||||
onMutate: async ({ messageID }) => {
|
||||
const queryKey = ['opencode', 'messages', opcodeUrl, sessionId, directory]
|
||||
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const previousMessages = queryClient.getQueryData<MessageListResponse>(queryKey)
|
||||
|
||||
if (previousMessages) {
|
||||
const messageIndex = previousMessages.findIndex(m => m.info.id === messageID)
|
||||
if (messageIndex !== -1) {
|
||||
const newMessages = previousMessages.slice(0, messageIndex)
|
||||
queryClient.setQueryData(queryKey, newMessages)
|
||||
}
|
||||
}
|
||||
|
||||
return { previousMessages }
|
||||
},
|
||||
onError: (error, _, context) => {
|
||||
console.error('Failed to remove message:', error)
|
||||
|
||||
if (context?.previousMessages) {
|
||||
queryClient.setQueryData(
|
||||
['opencode', 'messages', opcodeUrl, sessionId, directory],
|
||||
context.previousMessages
|
||||
)
|
||||
}
|
||||
|
||||
showToast.error('Failed to remove message')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory]
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, sessionId, directory]
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
interface UseRefreshMessageOptions {
|
||||
opcodeUrl: string | null
|
||||
sessionId: string
|
||||
directory?: string
|
||||
}
|
||||
|
||||
export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefreshMessageOptions) {
|
||||
const queryClient = useQueryClient()
|
||||
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
assistantMessageID,
|
||||
userMessageContent,
|
||||
model,
|
||||
agent
|
||||
}: {
|
||||
assistantMessageID: string
|
||||
userMessageContent: string
|
||||
model?: string
|
||||
agent?: string
|
||||
}) => {
|
||||
if (!opcodeUrl) throw new Error('OpenCode URL not available')
|
||||
|
||||
await removeMessage.mutateAsync({ messageID: assistantMessageID })
|
||||
|
||||
const client = createOpenCodeClient(opcodeUrl, directory)
|
||||
|
||||
interface SendPromptRequest {
|
||||
parts: Array<{ type: 'text'; text: string }>
|
||||
model?: { providerID: string; modelID: string }
|
||||
agent?: string
|
||||
}
|
||||
|
||||
const requestData: SendPromptRequest = {
|
||||
parts: [{ type: 'text', text: userMessageContent }]
|
||||
}
|
||||
|
||||
if (model) {
|
||||
const [providerID, modelID] = model.split('/')
|
||||
if (providerID && modelID) {
|
||||
requestData.model = { providerID, modelID }
|
||||
}
|
||||
}
|
||||
|
||||
if (agent) {
|
||||
requestData.agent = agent
|
||||
}
|
||||
|
||||
return client.sendPrompt(sessionId, requestData)
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory]
|
||||
})
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to refresh message:', error)
|
||||
showToast.error('Failed to refresh message')
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { sanitizeForTTS } from './utils'
|
||||
|
||||
describe('sanitizeForTTS', () => {
|
||||
it('should handle headers', () => {
|
||||
expect(sanitizeForTTS('# Main Header\n## Sub Header\n### Detail')).toBe('Main Header\nSub Header\nDetail')
|
||||
})
|
||||
|
||||
it('should handle bullet lists', () => {
|
||||
expect(sanitizeForTTS('- Milk\n- Eggs\n* Bread')).toBe('Milk\nEggs\nBread')
|
||||
})
|
||||
|
||||
it('should handle numbered lists', () => {
|
||||
expect(sanitizeForTTS('1. First\n2. Second')).toBe('First\nSecond')
|
||||
})
|
||||
|
||||
it('should remove inline code but keep content', () => {
|
||||
expect(sanitizeForTTS('Use `const x = 1` here')).toBe('Use const x = 1 here')
|
||||
})
|
||||
|
||||
it('should remove code blocks entirely', () => {
|
||||
expect(sanitizeForTTS('Start\n```\ncode\n```\nEnd')).toBe('Start\nEnd')
|
||||
})
|
||||
|
||||
it('should handle bold formatting', () => {
|
||||
expect(sanitizeForTTS('This is **bold** text')).toBe('This is bold text')
|
||||
})
|
||||
|
||||
it('should handle italic formatting', () => {
|
||||
expect(sanitizeForTTS('Simple *italic* example')).toBe('Simple italic example')
|
||||
})
|
||||
|
||||
it('should remove markdown links but keep display text', () => {
|
||||
expect(sanitizeForTTS('Visit [OpenCode](https://opencode.ai)')).toBe('Visit OpenCode')
|
||||
})
|
||||
|
||||
it('should handle images and tables', () => {
|
||||
expect(sanitizeForTTS('See  below:\n|A|B|\n|-|-|\n|1|2|')).toBe('See diagram below:\nA B\n1 2')
|
||||
})
|
||||
|
||||
it('should handle blockquotes', () => {
|
||||
expect(sanitizeForTTS('> Important\n> Note')).toBe('Important\nNote')
|
||||
})
|
||||
|
||||
it('should remove citations and footnotes', () => {
|
||||
expect(sanitizeForTTS('See [1] and [^2] for more')).toBe('See and for more')
|
||||
})
|
||||
|
||||
it('should handle strikethrough', () => {
|
||||
expect(sanitizeForTTS('~~removed~~')).toBe('removed')
|
||||
})
|
||||
|
||||
it('should handle complex mixed content', () => {
|
||||
const input = '# Results\nFunction: `calc()`\nSee [doc](url):\n- A\n- B'
|
||||
const expected = 'Results\nFunction: calc()\nSee doc:\nA\nB'
|
||||
expect(sanitizeForTTS(input)).toBe(expected)
|
||||
})
|
||||
|
||||
it('should remove horizontal rules', () => {
|
||||
expect(sanitizeForTTS('Before\n---\nAfter')).toBe('Before\nAfter')
|
||||
})
|
||||
|
||||
it('should normalize whitespace', () => {
|
||||
expect(sanitizeForTTS('Line 1\n\n\nLine 2')).toBe('Line 1\nLine 2')
|
||||
})
|
||||
|
||||
it('should fix punctuation spacing', () => {
|
||||
expect(sanitizeForTTS('Hello , world !')).toBe('Hello, world!')
|
||||
})
|
||||
|
||||
it('should return empty string for empty input', () => {
|
||||
expect(sanitizeForTTS('')).toBe('')
|
||||
expect(sanitizeForTTS(' ')).toBe('')
|
||||
expect(sanitizeForTTS(null as unknown as string)).toBe('')
|
||||
})
|
||||
|
||||
it('should handle headers and lists combined', () => {
|
||||
expect(sanitizeForTTS('## Shopping List\n- Milk\n- Eggs')).toBe('Shopping List\nMilk\nEggs')
|
||||
})
|
||||
|
||||
it('should handle HTML tags', () => {
|
||||
expect(sanitizeForTTS('Text with <tag>content</tag> here')).toBe('Text with content here')
|
||||
})
|
||||
})
|
||||
@@ -13,3 +13,96 @@ export const GPU_ACCELERATED_STYLE: CSSProperties = {
|
||||
}
|
||||
|
||||
export const MODAL_TRANSITION_MS = 300
|
||||
|
||||
/**
|
||||
* Sanitizes markdown text for TTS playback by removing non-read-aloud symbols
|
||||
* Converts markdown into clean, readable text suitable for speech synthesis
|
||||
*/
|
||||
export function sanitizeForTTS(text: string): string {
|
||||
if (!text) return ''
|
||||
|
||||
let sanitized = text
|
||||
|
||||
// Remove code blocks entirely (not readable for TTS)
|
||||
sanitized = sanitized.replace(/```[\s\S]*?```/g, '')
|
||||
|
||||
// Remove inline code, keep content: `code` -> code
|
||||
sanitized = sanitized.replace(/`([^`]+)`/g, '$1')
|
||||
|
||||
// Remove markdown links, keep display text: [text](url) -> text
|
||||
sanitized = sanitized.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
|
||||
// Remove markdown images:  -> alt
|
||||
sanitized = sanitized.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
|
||||
|
||||
// Remove bold markers: **text** -> text or __text__ -> text
|
||||
sanitized = sanitized.replace(/\*\*([^*]+)\*\*/g, '$1')
|
||||
sanitized = sanitized.replace(/__([^_]+)__/g, '$1')
|
||||
|
||||
// Remove italic markers: *text* -> text or _text_ -> text
|
||||
sanitized = sanitized.replace(/\*([^*]+)\*/g, '$1')
|
||||
sanitized = sanitized.replace(/_([^_]+)_/g, '$1')
|
||||
|
||||
// Remove strikethrough: ~~text~~ -> text
|
||||
sanitized = sanitized.replace(/~~([^~]+)~~/g, '$1')
|
||||
|
||||
// Remove headers: ### Header -> Header
|
||||
sanitized = sanitized.replace(/^#{1,6}\s+/gm, '')
|
||||
|
||||
// Remove list markers: - item, * item, + item, or 1. item -> item
|
||||
sanitized = sanitized.replace(/^\s*[-*+]\s+/gm, '')
|
||||
sanitized = sanitized.replace(/^\s*\d+\.\s+/gm, '')
|
||||
|
||||
// Remove blockquotes: > quote -> quote
|
||||
sanitized = sanitized.replace(/^>\s+/gm, '')
|
||||
|
||||
// Remove horizontal rules: --- or *** or ___
|
||||
sanitized = sanitized.replace(/^(\*\*\*|---|___)\s*$/gm, '')
|
||||
|
||||
// Remove footnote references: [^1] -> remove
|
||||
sanitized = sanitized.replace(/\[\^[^\]]+\]/g, '')
|
||||
|
||||
// Remove citation references: [1] or [1,2] -> remove
|
||||
sanitized = sanitized.replace(/\[\d+(,\d+)*\]/g, '')
|
||||
|
||||
// Remove HTML tags: <tag> -> remove
|
||||
sanitized = sanitized.replace(/<[^>]*>/g, '')
|
||||
|
||||
// Process tables: handle line-by-line for proper cell separation
|
||||
const lines = sanitized.split('\n')
|
||||
const processedLines: string[] = []
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
|
||||
// Skip table separator rows (only dashes, pipes, equals, spaces)
|
||||
if (/^[|\s\-_=]+$/.test(trimmed)) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle table rows (contain pipes)
|
||||
if (trimmed.includes('|')) {
|
||||
// Remove pipes and multiple spaces
|
||||
const cells = trimmed.split('|')
|
||||
.map(s => s.trim())
|
||||
.filter(s => s.length > 0)
|
||||
.join(' ')
|
||||
if (cells) processedLines.push(cells)
|
||||
} else if (trimmed) {
|
||||
// Non-table line
|
||||
processedLines.push(trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
sanitized = processedLines.join('\n')
|
||||
|
||||
// Clean up whitespace
|
||||
sanitized = sanitized.replace(/\n{3,}/g, '\n\n')
|
||||
sanitized = sanitized.replace(/[ \t]{2,}/g, ' ')
|
||||
sanitized = sanitized.trim()
|
||||
|
||||
// Fix common punctuation spacing issues
|
||||
sanitized = sanitized.replace(/\s+([.,!?;:])/g, '$1')
|
||||
|
||||
return sanitized
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { useSession, useSessions, useAbortSession, useUpdateSession, useOpenCode
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config";
|
||||
import { useSSE } from "@/hooks/useSSE";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useModelSelection } from "@/hooks/useModelSelection";
|
||||
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";
|
||||
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { usePermissionRequests } from "@/hooks/usePermissionRequests";
|
||||
@@ -81,6 +82,7 @@ export function SessionDetail() {
|
||||
const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId);
|
||||
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
|
||||
const { open: openSettings } = useSettingsDialog();
|
||||
const { modelString } = useModelSelection(opcodeUrl, repoDirectory);
|
||||
|
||||
useKeyboardShortcuts({
|
||||
openModelDialog: () => setModelDialogOpen(true),
|
||||
@@ -229,6 +231,7 @@ export function SessionDetail() {
|
||||
messages={messages}
|
||||
onFileClick={handleFileClick}
|
||||
onChildSessionClick={handleChildSessionClick}
|
||||
model={modelString || undefined}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user