Add message undo/refresh functionality with editable user prompts

- Add revertMessage and unrevertSession methods to OpenCode API client
- Create useRemoveMessage and useRefreshMessage hooks for message operations
- Add MessageActionButtons component with X (remove) and refresh buttons
- Add EditableUserMessage component for editing prompts before resend
- Update MessageThread to integrate action buttons and editable messages
- Update AGENTS.md with improved guidelines and pnpm preference
This commit is contained in:
OpenCode Agent committed 2025-12-16 18:53:31 +00:00
1 parent b27d4a9cbb
commit 6c4daaeae7
7 files changed
+525 -43

No files matched your search

+12 -10
View File
@@ -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
+10
View File
@@ -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>
)
})
+142 -33
View File
@@ -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>
)
})
})
+123
View File
@@ -0,0 +1,123 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createOpenCodeClient } from '@/api/opencode'
import { toast } 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
)
}
toast.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)
toast.error('Failed to refresh message')
}
})
}
+3
View File
@@ -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>