feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

@@ -6,7 +6,6 @@ import { useMobile } from '@/hooks/useMobile'
import { useSessionAgent } from '@/hooks/useSessionAgent'
interface EditableUserMessageProps {
opcodeUrl: string
sessionId: string
directory?: string
content: string
@@ -16,7 +15,6 @@ interface EditableUserMessageProps {
}
export const EditableUserMessage = memo(function EditableUserMessage({
opcodeUrl,
sessionId,
directory,
content,
@@ -27,9 +25,9 @@ export const EditableUserMessage = memo(function EditableUserMessage({
const [editedContent, setEditedContent] = useState(content)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const isMobile = useMobile()
const refreshMessage = useRefreshMessage({ opcodeUrl, sessionId, directory })
const refreshMessage = useRefreshMessage({ sessionId, directory })
const setIsEditingMessage = useUIState((state) => state.setIsEditingMessage)
const sessionAgent = useSessionAgent(opcodeUrl, sessionId, directory)
const sessionAgent = useSessionAgent(sessionId, directory)
const currentMode = sessionAgent.agent
useEffect(() => {
@@ -1,35 +1,22 @@
import React, { useState } from 'react'
import type { components } from '@/api/opencode-types'
import type { FileDiffInfo, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { useSettings } from '@/hooks/useSettings'
import { DiffStats } from './DiffStats'
import { ContentDiffViewer } from './ContentDiffViewer'
import { CodePreview } from './CodePreview'
import { ChevronDown, ChevronUp } from 'lucide-react'
type ToolPart = components['schemas']['ToolPart']
export interface FileDiffData {
file: string
before: string
after: string
additions: number
deletions: number
}
function isFileDiff(data: unknown): data is FileDiffData {
function isFileDiff(data: unknown): data is FileDiffInfo {
return (
typeof data === 'object' &&
data !== null &&
'file' in data &&
'before' in data &&
'after' in data &&
'patch' in data &&
'additions' in data &&
'deletions' in data &&
typeof (data as FileDiffData).file === 'string' &&
typeof (data as FileDiffData).before === 'string' &&
typeof (data as FileDiffData).after === 'string' &&
typeof (data as FileDiffData).additions === 'number' &&
typeof (data as FileDiffData).deletions === 'number'
typeof (data as FileDiffInfo).file === 'string' &&
typeof (data as FileDiffInfo).patch === 'string' &&
typeof (data as FileDiffInfo).additions === 'number' &&
typeof (data as FileDiffInfo).deletions === 'number'
)
}
@@ -53,16 +40,37 @@ export function getRelativePath(filePath: string): string {
return filePath
}
function PatchViewer({ patch }: { patch: string }) {
const lines = patch.split('\n')
return (
<pre className="bg-accent p-2 text-xs overflow-x-auto">
{lines.map((line, index) => {
const tone = line.startsWith('@@')
? 'text-blue-600 dark:text-blue-400'
: line.startsWith('+++') || line.startsWith('---')
? 'text-muted-foreground'
: line.startsWith('+')
? 'text-green-600 dark:text-green-400'
: line.startsWith('-')
? 'text-red-600 dark:text-red-400'
: 'text-muted-foreground'
return <div key={index} className={tone}>{line || ' '}</div>
})}
</pre>
)
}
interface FileToolRenderProps {
part: ToolPart
filediff?: FileDiffData
part: SessionMessageAssistantTool
filediff?: FileDiffInfo
filePath?: string
content?: string
toolName: string
onFileClick?: (filePath: string, lineNumber?: number) => void
}
export function FileToolRender({ part, filediff, filePath, content, toolName, onFileClick }: FileToolRenderProps) {
function FileToolRender({ part, filediff, filePath, content, toolName, onFileClick }: FileToolRenderProps) {
const { preferences } = useSettings()
const isReadTool = toolName === 'Read'
const isEditTool = toolName === 'Edit'
@@ -76,10 +84,8 @@ export function FileToolRender({ part, filediff, filePath, content, toolName, on
const [expanded, setExpanded] = useState(defaultExpanded)
const getDuration = () => {
if (part.state.status === 'completed' && part.state.time) {
return ((part.state.time.end - part.state.time.start) / 1000).toFixed(2) + 's'
}
return ''
if (part.time.ran === undefined || part.time.completed === undefined) return ''
return ((part.time.completed - part.time.ran) / 1000).toFixed(2) + 's'
}
const handleFileClick = (e: React.MouseEvent) => {
@@ -118,7 +124,7 @@ export function FileToolRender({ part, filediff, filePath, content, toolName, on
{expanded && hasExpandableContent && (
<div className="bg-card p-0">
{filediff && <ContentDiffViewer before={filediff.before} after={filediff.after} />}
{filediff && <PatchViewer patch={filediff.patch} />}
{content && !filediff && <CodePreview fileName={filePath || ''} content={content} />}
</div>
)}
@@ -126,31 +132,47 @@ export function FileToolRender({ part, filediff, filePath, content, toolName, on
)
}
export function getToolSpecificRender(part: ToolPart, onFileClick?: (filePath: string) => void): React.ReactElement | null {
function fileDiffs(part: SessionMessageAssistantTool): FileDiffInfo[] {
if (part.state.status !== 'completed') return []
const files = part.state.metadata?.files
if (!Array.isArray(files)) return []
return files.filter(isFileDiff)
}
export function getToolSpecificRender(part: SessionMessageAssistantTool, onFileClick?: (filePath: string) => void): React.ReactElement | null {
if (part.state.status !== 'completed') return null
if (part.tool === 'edit') {
const filediff = part.state.metadata?.filediff
const filePath = part.state.input?.filePath as string | undefined
if (filediff && isFileDiff(filediff)) {
return <FileToolRender part={part} filediff={filediff} filePath={filePath} toolName="Edit" onFileClick={onFileClick} />
}
const input = part.state.input
const inputPath = typeof input.path === 'string' ? input.path : undefined
if (part.name === 'edit' || part.name === 'patch') {
const diffs = fileDiffs(part)
if (diffs.length === 0) return null
const toolName = part.name === 'edit' ? 'Edit' : 'Patch'
return (
<>
{diffs.map((filediff, index) => (
<FileToolRender
key={`${filediff.file}-${index}`}
part={part}
filediff={filediff}
filePath={filediff.file}
toolName={toolName}
onFileClick={onFileClick}
/>
))}
</>
)
}
if (part.tool === 'write') {
const filePath = part.state.input?.filePath as string | undefined
const content = part.state.input?.content as string | undefined
if (filePath) {
return <FileToolRender part={part} filePath={filePath} content={content} toolName="Write" onFileClick={onFileClick} />
}
if (part.name === 'write' && inputPath) {
const content = input.content as string | undefined
return <FileToolRender part={part} filePath={inputPath} content={content} toolName="Write" onFileClick={onFileClick} />
}
if (part.tool === 'read') {
const filePath = part.state.input?.filePath as string | undefined
if (filePath) {
return <FileToolRender part={part} filePath={filePath} toolName="Read" onFileClick={onFileClick} />
}
if (part.name === 'read' && inputPath) {
return <FileToolRender part={part} filePath={inputPath} toolName="Read" onFileClick={onFileClick} />
}
return null
}
}
@@ -1,18 +1,29 @@
import { memo } from 'react'
import type { SessionStructuredError } from '@opencode-manager/shared/opencode'
import { AlertCircle, KeyRound, XCircle, Clock } from 'lucide-react'
import { parseOpenCodeError, type OpenCodeError } from '@/lib/opencode-errors'
interface MessageErrorProps {
error: OpenCodeError
error: SessionStructuredError
}
const getErrorIcon = (errorName: string) => {
switch (errorName) {
case 'ProviderAuthError':
const ERROR_LABELS: Record<string, string> = {
'provider.auth': 'Provider authentication failed',
'provider.rate-limit': 'Provider rate limit reached',
'provider.quota': 'Provider quota exceeded',
'provider.timeout': 'Provider request timed out',
'permission.rejected': 'Permission denied',
'tool.execution': 'Tool execution failed',
aborted: 'Message aborted',
}
function getErrorIcon(errorType: string) {
switch (errorType) {
case 'provider.auth':
return KeyRound
case 'MessageAbortedError':
case 'permission.rejected':
case 'aborted':
return XCircle
case 'MessageOutputLengthError':
case 'provider.timeout':
return Clock
default:
return AlertCircle
@@ -20,17 +31,15 @@ const getErrorIcon = (errorName: string) => {
}
export const MessageError = memo(function MessageError({ error }: MessageErrorProps) {
const parsed = parseOpenCodeError(error)
if (!parsed) return null
const Icon = getErrorIcon(error.name)
const Icon = getErrorIcon(error.type)
const label = ERROR_LABELS[error.type] ?? 'Error'
return (
<div className="flex items-start gap-2 p-3 rounded-md bg-destructive/10 border border-destructive/30 text-destructive">
<Icon className="h-4 w-4 mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">{parsed.title}</div>
<div className="text-xs text-destructive/80 mt-0.5">{parsed.message}</div>
<div className="font-medium text-sm">{label}</div>
<div className="text-xs text-destructive/80 mt-0.5">{error.message}</div>
</div>
</div>
)
File diff suppressed because it is too large. Load diff
+16 -160
View File
@@ -1,132 +1,29 @@
import { memo } from 'react'
import type { components } from '@/api/opencode-types'
import { Volume2, VolumeX, Loader2 } from 'lucide-react'
import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import { TextPart } from './TextPart'
import { PatchPart } from './PatchPart'
import { ToolCallPart } from './ToolCallPart'
import { RetryPart } from './RetryPart'
import { useTTS } from '@/hooks/useTTS'
import { useMobile } from '@/hooks/useMobile'
import { useSettings } from '@/hooks/useSettings'
import { CopyButton } from '@/components/ui/copy-button'
type RetryPartType = components['schemas']['RetryPart']
type Part = components['schemas']['Part']
type AssistantContentPart = SessionMessageAssistant['content'][number]
interface MessagePartProps {
part: Part
role?: string
allParts?: Part[]
partIndex?: number
part: AssistantContentPart
messageID?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
messageTextContent?: string
}
function getCopyableContent(part: Part, allParts?: Part[]): string {
switch (part.type) {
case 'text':
return part.text || ''
case 'patch':
return `Patch: ${part.hash}\nFiles: ${part.files.join(', ')}`
case 'tool':
if (part.state.status === 'completed' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
} else if (part.state.status === 'running' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
}
return `Tool: ${part.tool} (${part.state.status})`
case 'reasoning':
return part.text || ''
case 'snapshot':
return part.snapshot || ''
case 'agent':
return `Agent: ${part.name}`
case 'subtask':
return `${part.agent}: ${part.description}\n\n${part.prompt}`.trim()
case 'step-finish':
if (allParts) {
return allParts
.filter(p => p.type === 'text')
.map(p => p.text || '')
.join('\n\n')
.trim()
}
return ''
case 'file':
return part.filename || part.url || 'File'
default:
return ''
}
}
interface TTSButtonProps {
messageId: string
content: string
className?: string
}
function TTSButton({ messageId, content, className = "" }: TTSButtonProps) {
const { speakMessage, stop, isEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
if (!isEnabled || !content.trim()) {
return null
}
const isThisPlaying = (isPlaying || isLoading) && activeMessageId === messageId
const handleClick = () => {
if (isThisPlaying) {
stop()
} else {
speakMessage(messageId, content)
}
}
return (
<button
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 && !isThisPlaying}
>
{isLoading && isThisPlaying ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : isThisPlaying ? (
<VolumeX className="w-4 h-4" />
) : (
<Volume2 className="w-4 h-4" />
)}
</button>
)
}
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick, onChildSessionClick, messageTextContent }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, messageID, onFileClick, onChildSessionClick }: MessagePartProps) {
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
const copyableContent = getCopyableContent(part, allParts)
const isMobile = useMobile()
switch (part.type) {
case 'text':
if (part.synthetic) return null
if (role === 'user' && allParts && partIndex !== undefined) {
const nextPart = allParts[partIndex + 1]
if (nextPart && nextPart.type === 'file') {
return null
}
}
return <TextPart part={part} />
case 'patch':
if (simpleChatMode) return null
return <PatchPart part={part} onFileClick={onFileClick} />
case 'tool':
if (simpleChatMode && part.tool !== 'task') return null
return <ToolCallPart part={part} onFileClick={onFileClick} onChildSessionClick={onChildSessionClick} />
return <TextPart text={part.text} />
case 'reasoning':
if (simpleChatMode || !showReasoning) return null
if (!part.text.trim()) return null
return (
<details className="border border-border rounded-lg my-2">
<summary className="px-4 py-2 bg-muted hover:bg-accent cursor-pointer text-sm font-medium">
@@ -137,57 +34,16 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
</div>
</details>
)
case 'snapshot':
if (simpleChatMode) return null
case 'tool':
if (simpleChatMode && part.name !== 'subagent') return null
return (
<div className="border border-border rounded-lg p-4 my-2 bg-card">
<div className="text-xs text-muted-foreground font-mono">Snapshot: {part.snapshot}</div>
</div>
<ToolCallPart
part={part}
messageID={messageID}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
)
case 'agent':
if (simpleChatMode) return null
return (
<div className="border border-border rounded-lg p-4 my-2 bg-card">
<div className="text-sm font-medium text-blue-600 dark:text-blue-400">Agent: {part.name}</div>
</div>
)
case 'step-finish':
if (simpleChatMode) return null
{
const isFree = part.cost === 0
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}
<CopyButton content={copyableContent} title="Copy step complete" />
{messageTextContent && part.messageID && <TTSButton messageId={part.messageID} content={messageTextContent} />}
</div>
)
}
case 'file':
return (
<span className="inline-flex items-center gap-1 px-2 py-1 rounded bg-muted border border-border text-sm text-foreground">
<span className="text-blue-600 dark:text-blue-400">@</span>
<span className="font-medium">{part.filename || 'File'}</span>
</span>
)
case 'retry':
return <RetryPart part={part as RetryPartType} />
case 'subtask': {
const label = part.description || part.prompt || 'Sub-agent task'
return (
<div className="my-1 w-full rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-1.5 text-left text-xs text-muted-foreground shadow-sm shadow-blue-500/5">
<div className="flex items-center gap-2 min-w-0">
<span className="truncate">{label}</span>
<span className="ml-auto shrink-0 text-[11px] text-muted-foreground">sub-agent</span>
</div>
</div>
)
}
case 'step-start':
case 'compaction':
return null
default:
return null
}
@@ -2,34 +2,32 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MessageThread } from './MessageThread'
import { useUIState } from '@/stores/uiStateStore'
import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection'
import {
SESSION_ID,
compactionSequence,
promptSequence,
shellSequence,
} from '@/test/fixtures/session-projection'
import type {
SessionInboxUser,
SessionMessageAssistant,
SessionMessageAssistantTool,
SessionMessageInfo,
SessionMessageUser,
V2Event,
} from '@opencode-manager/shared/opencode'
const mocks = vi.hoisted(() => ({
useSessionStatus: vi.fn(),
useSessionTodos: vi.fn(),
useSettings: vi.fn(),
usePermissions: vi.fn(),
useQuestions: vi.fn(),
useRefreshMessage: vi.fn(),
useSessionAgent: vi.fn(),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatusForSession: () => mocks.useSessionStatus(),
}))
vi.mock('@/stores/sessionTodosStore', () => ({
useSessionTodos: mocks.useSessionTodos,
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: mocks.useSettings,
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => mocks.usePermissions(),
useQuestions: () => mocks.useQuestions(),
}))
vi.mock('@/hooks/useRemoveMessage', () => ({
useRefreshMessage: () => mocks.useRefreshMessage(),
}))
@@ -38,6 +36,17 @@ vi.mock('@/hooks/useSessionAgent', () => ({
useSessionAgent: () => mocks.useSessionAgent(),
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: () => ({
speakMessage: vi.fn(),
stop: vi.fn(),
isEnabled: false,
isPlaying: false,
isLoading: false,
activeMessageId: null,
}),
}))
interface MockSettingsReturn {
preferences: {
simpleChatMode: boolean
@@ -54,110 +63,63 @@ const setupSettings = (preferences: MockSettingsReturn['preferences']) => {
})
}
const createTextPart = (text: string, messageId: string) => ({
type: 'text' as const,
text,
sessionID: 'test-session',
messageID: messageId,
id: 'part-1',
})
const project = (events: V2Event[]): SessionMessageInfo[] =>
events.reduce(applySessionEvent, emptySessionTranscript).messages
const createTaskToolPart = (description: string, sessionId: string | undefined, messageId: string) => ({
type: 'tool' as const,
tool: 'task',
sessionID: 'test-session',
messageID: messageId,
id: 'part-2',
callID: 'call-1',
metadata: sessionId ? { sessionId } : undefined,
state: {
status: 'completed' as const,
input: { description },
output: 'done',
title: 'Task',
metadata: {},
time: { start: Date.now(), end: Date.now() + 100 },
},
})
const createSubtaskPart = (description: string, messageId: string) => ({
type: 'subtask' as const,
prompt: 'Please review this',
description,
agent: 'reviewer',
sessionID: 'test-session',
messageID: messageId,
id: 'part-3',
})
const createStepFinishPart = (messageId: string) => ({
type: 'step-finish' as const,
sessionID: 'test-session',
messageID: messageId,
id: 'part-4',
reason: 'stop',
cost: 0,
tokens: {
input: 0,
output: 0,
reasoning: 0,
cache: { read: 0, write: 0 },
},
})
const createReasoningPart = (text: string, messageId: string) => ({
type: 'reasoning' as const,
text,
sessionID: 'test-session',
messageID: messageId,
id: 'part-5',
})
const createAssistantMessage = (
const assistantMessage = (
id: string,
parts: unknown[],
modelID?: string
) => ({
info: {
id,
role: 'assistant' as const,
sessionID: 'test-session',
parentID: 'parent-1',
providerID: 'test-provider',
mode: 'build',
time: {
created: Date.now(),
completed: Date.now() + 100,
},
modelID: modelID || 'test-model',
},
parts,
content: SessionMessageAssistant['content'],
extra: Partial<SessionMessageAssistant> = {},
): SessionMessageAssistant => ({
id,
type: 'assistant',
agent: 'test-agent',
model: { providerID: 'test-provider', id: 'test-model' },
content,
time: { created: Date.now(), completed: Date.now() + 100 },
...extra,
})
const createUserMessage = (id: string, text: string) => ({
info: {
id,
role: 'user' as const,
sessionID: 'test-session',
agent: 'test-agent',
model: 'test-model',
time: {
created: Date.now(),
},
const userMessage = (id: string, text: string): SessionMessageUser => ({
id,
type: 'user',
text,
time: { created: Date.now() },
})
const subagentTool = (description: string, sessionID?: string): SessionMessageAssistantTool => ({
type: 'tool',
id: 'tool_subagent',
name: 'subagent',
state: {
status: 'completed',
input: { description },
content: [{ type: 'text', text: 'done' }],
metadata: sessionID ? { sessionID } : {},
},
parts: [createTextPart(text, id)],
time: { created: Date.now(), completed: Date.now() + 100 },
})
const textPart = (text: string): SessionMessageAssistant['content'][number] => ({ type: 'text', text })
const reasoningPart = (text: string): SessionMessageAssistant['content'][number] => ({ type: 'reasoning', text })
const shellTool = (command: string): SessionMessageAssistantTool => ({
type: 'tool',
id: 'tool_shell',
name: 'shell',
state: {
status: 'completed',
input: { command },
content: [{ type: 'text', text: 'ok' }],
metadata: {},
},
time: { created: Date.now(), completed: Date.now() + 100 },
})
describe('MessageThread', () => {
beforeEach(() => {
mocks.useSessionStatus.mockReturnValue({ type: 'idle' })
mocks.useSessionTodos.mockReturnValue({ setTodos: vi.fn() })
mocks.usePermissions.mockReturnValue({
getForCallID: vi.fn(() => null),
})
mocks.useQuestions.mockReturnValue({
getForCallID: vi.fn(() => null),
})
vi.clearAllMocks()
mocks.useRefreshMessage.mockReturnValue({
isPending: false,
mutate: vi.fn(),
@@ -166,26 +128,20 @@ describe('MessageThread', () => {
useUIState.getState().setIsEditingMessage(false)
})
it('renders assistant message with only subtask part as standalone row without header', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
it('renders assistant message with only a subagent part as standalone row without header', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [createSubtaskPart('Review changes', '2')]),
userMessage('1', 'Hello'),
assistantMessage('2', [subagentTool('Review changes', 'child-session')]),
]
const onChildSessionClick = vi.fn()
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
onChildSessionClick={onChildSessionClick}
/>
messages={messages}
pending={[]}
/>,
)
expect(screen.getByText('Review changes')).toBeInTheDocument()
@@ -193,199 +149,69 @@ describe('MessageThread', () => {
expect(screen.queryByText('test-model')).not.toBeInTheDocument()
})
it('renders assistant message with only task tool part as standalone row without header', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [createTaskToolPart('Do something', 'child-session', '2')]),
]
it('renders a subagent row that links to the child session', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const onChildSessionClick = vi.fn()
const messages = [
userMessage('1', 'Hello'),
assistantMessage('2', [subagentTool('Explore codebase structure', 'child-session')]),
]
const { container } = render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
messages={messages}
pending={[]}
onChildSessionClick={onChildSessionClick}
/>
/>,
)
expect(screen.getByText('Do something')).toBeInTheDocument()
expect(screen.getByText('Explore codebase structure')).toBeInTheDocument()
expect(screen.getByText('sub-agent')).toBeInTheDocument()
expect(screen.queryByText('test-model')).not.toBeInTheDocument()
const buttons = container.querySelectorAll('button')
expect(buttons.length).toBeGreaterThan(0)
fireEvent.click(buttons[buttons.length - 1])
expect(onChildSessionClick).toHaveBeenCalledWith('child-session')
})
it('renders assistant task message with empty text and step finish as standalone row', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [
createTextPart(' ', '2'),
createTaskToolPart('Explore codebase structure', 'child-session', '2'),
createStepFinishPart('2'),
]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
)
expect(screen.getByText('Explore codebase structure')).toBeInTheDocument()
expect(screen.getByText('sub-agent')).toBeInTheDocument()
expect(screen.queryByText('test-model')).not.toBeInTheDocument()
})
it('renders assistant task message with hidden reasoning as standalone row', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [
createReasoningPart('I should use the explore agent', '2'),
createTextPart('\n\n', '2'),
createTaskToolPart('Explore codebase structure', 'child-session', '2'),
createStepFinishPart('2'),
]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
)
expect(screen.getByText('Explore codebase structure')).toBeInTheDocument()
expect(screen.getByText('sub-agent')).toBeInTheDocument()
expect(screen.queryByText('test-model')).not.toBeInTheDocument()
expect(screen.queryByText('I should use the explore agent')).not.toBeInTheDocument()
})
it('renders assistant task message with simple-chat reasoning setting as standalone row', () => {
setupSettings({
simpleChatMode: true,
showReasoning: true,
})
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [
createReasoningPart('I should use the explore agent', '2'),
createTextPart('\n\n', '2'),
createTaskToolPart('Explore codebase structure', 'child-session', '2'),
createStepFinishPart('2'),
]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
)
expect(screen.getByText('Explore codebase structure')).toBeInTheDocument()
expect(screen.getByText('sub-agent')).toBeInTheDocument()
expect(screen.queryByText('test-model')).not.toBeInTheDocument()
expect(screen.queryByText('I should use the explore agent')).not.toBeInTheDocument()
})
it('renders assistant task message with visible reasoning as standalone row when no text exists', () => {
setupSettings({
simpleChatMode: false,
showReasoning: true,
})
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [
createReasoningPart('I should use the explore agent', '2'),
createTextPart('\n\n', '2'),
createTaskToolPart('Explore codebase structure', 'child-session', '2'),
createStepFinishPart('2'),
]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
)
expect(screen.getByText('Explore codebase structure')).toBeInTheDocument()
expect(screen.getByText('sub-agent')).toBeInTheDocument()
expect(screen.queryByText('I should use the explore agent')).not.toBeInTheDocument()
expect(screen.queryByText('test-model')).not.toBeInTheDocument()
})
it('renders assistant message with text normally with header', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [createTextPart('This is a response', '2')]),
userMessage('1', 'Hello'),
assistantMessage('2', [textPart('This is a response')]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
messages={messages}
pending={[]}
/>,
)
expect(screen.getByText('This is a response')).toBeInTheDocument()
expect(screen.getByText('test-model')).toBeInTheDocument()
})
it('renders assistant message with text and subtask normally with header', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
it('renders assistant message with text and subagent normally with header', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [
createTextPart('Here is the analysis', '2'),
createSubtaskPart('Review changes', '2'),
userMessage('1', 'Hello'),
assistantMessage('2', [
textPart('Here is the analysis'),
subagentTool('Review changes', 'child-session'),
]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
messages={messages}
pending={[]}
/>,
)
expect(screen.getByText('Here is the analysis')).toBeInTheDocument()
@@ -393,45 +219,240 @@ describe('MessageThread', () => {
expect(screen.getByText('test-model')).toBeInTheDocument()
})
it('renders user messages normally', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
it('renders reasoning, shell, and subagent entries in order for a textless assistant', () => {
setupSettings({ simpleChatMode: false, showReasoning: true })
const messages = [
createUserMessage('1', 'Hello'),
userMessage('1', 'Hello'),
assistantMessage('2', [
reasoningPart('Thinking it over'),
shellTool('bun test'),
subagentTool('Review changes', 'child-session'),
]),
]
const { container } = render(
<MessageThread
sessionID="test-session"
messages={messages}
pending={[]}
/>,
)
expect(screen.getByText('Thinking it over')).toBeInTheDocument()
expect(screen.getByText('bun test')).toBeInTheDocument()
expect(screen.getByText('Review changes')).toBeInTheDocument()
expect(screen.getByText('sub-agent')).toBeInTheDocument()
const text = container.textContent ?? ''
expect(text.indexOf('Thinking it over')).toBeLessThan(text.indexOf('bun test'))
expect(text.indexOf('bun test')).toBeLessThan(text.indexOf('Review changes'))
})
it('keeps an assistant error visible after a subagent call', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages = [
userMessage('1', 'Hello'),
assistantMessage('2', [subagentTool('Review changes', 'child-session')], {
error: { type: 'provider.auth', message: 'invalid key' },
}),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
messages={messages}
pending={[]}
/>,
)
expect(screen.getByText('Review changes')).toBeInTheDocument()
expect(screen.getByText('Provider authentication failed')).toBeInTheDocument()
expect(screen.getByText('invalid key')).toBeInTheDocument()
})
it('keeps an assistant retry visible after a subagent call', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages = [
userMessage('1', 'Hello'),
assistantMessage('2', [subagentTool('Review changes', 'child-session')], {
retry: {
attempt: 2,
at: Date.now() + 60000,
error: { type: 'provider.rate-limit', message: 'slow down' },
},
}),
]
render(
<MessageThread
sessionID="test-session"
messages={messages}
pending={[]}
/>,
)
expect(screen.getByText('Review changes')).toBeInTheDocument()
expect(screen.getByText('Retry attempt 2')).toBeInTheDocument()
expect(screen.getByText('slow down')).toBeInTheDocument()
})
it('renders user messages normally', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
render(
<MessageThread
sessionID="test-session"
messages={[userMessage('1', 'Hello')]}
pending={[]}
/>,
)
expect(screen.getByText('Hello')).toBeInTheDocument()
expect(screen.getByText('You')).toBeInTheDocument()
})
it('renders a projected shell message from the fixtures', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
render(
<MessageThread
sessionID={SESSION_ID}
messages={project(shellSequence)}
pending={[]}
/>,
)
expect(screen.getByText('bun test')).toBeInTheDocument()
expect(screen.getByText('12 tests passed')).toBeInTheDocument()
})
it('renders a projected compaction banner from the fixtures', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
render(
<MessageThread
sessionID={SESSION_ID}
messages={project(compactionSequence)}
pending={[]}
/>,
)
expect(screen.getByText('Session compacted')).toBeInTheDocument()
expect(screen.getByText('Summarizing the previous turn.')).toBeInTheDocument()
})
it('renders a projected assistant transcript from the fixtures', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
render(
<MessageThread
sessionID={SESSION_ID}
messages={project(promptSequence)}
pending={[]}
/>,
)
expect(screen.getByText('Run the tests')).toBeInTheDocument()
expect(screen.getByText('Running the tests now.')).toBeInTheDocument()
})
it('renders queued prompts before delivery', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const pending: SessionInboxUser[] = [
{
id: 'inbox_1',
sessionID: 'test-session',
type: 'user',
payload: { text: 'Wait for me' },
delivery: 'queue',
time: { created: Date.now() },
},
]
render(
<MessageThread
sessionID="test-session"
messages={[userMessage('1', 'Hello')]}
pending={pending}
/>,
)
expect(screen.getByText('Wait for me')).toBeInTheDocument()
expect(screen.getByText('QUEUED')).toBeInTheDocument()
})
it('renders step file changes from the assistant snapshot and opens clicked files', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const onFileClick = vi.fn()
render(
<MessageThread
sessionID="test-session"
messages={[
assistantMessage('2', [textPart('Updated files')], {
snapshot: { start: 'aaa', end: 'bbbbbbbbcccc', files: ['/workspace/repos/app/src/a.ts'] },
}),
]}
pending={[]}
onFileClick={onFileClick}
/>,
)
expect(screen.getByText('File Changes (1 file)')).toBeInTheDocument()
fireEvent.click(screen.getByText('app/src/a.ts'))
expect(onFileClick).toHaveBeenCalledWith('/workspace/repos/app/src/a.ts')
})
it('hides step file changes in simple chat mode', () => {
setupSettings({ simpleChatMode: true, showReasoning: false })
render(
<MessageThread
sessionID="test-session"
messages={[
assistantMessage('2', [textPart('Updated files')], {
snapshot: { files: ['/workspace/repos/app/src/a.ts'] },
}),
]}
pending={[]}
/>,
)
expect(screen.queryByText(/File Changes/)).not.toBeInTheDocument()
})
it('shows the empty state when there are no messages or pending prompts', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
render(
<MessageThread
sessionID="test-session"
messages={[]}
pending={[]}
/>,
)
expect(screen.getByText('No messages yet. Start a conversation below.')).toBeInTheDocument()
})
it('keeps global editing state active when edit textarea blurs', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [createTextPart('This is a response', '2')]),
userMessage('1', 'Hello'),
assistantMessage('2', [textPart('This is a response')]),
]
const { unmount } = render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
messages={messages}
pending={[]}
/>,
)
fireEvent.click(screen.getByTitle('Edit message'))
@@ -447,10 +468,7 @@ describe('MessageThread', () => {
})
it('resends an edited prompt after the edit textarea blurs', () => {
setupSettings({
simpleChatMode: false,
showReasoning: false,
})
setupSettings({ simpleChatMode: false, showReasoning: false })
const mutate = vi.fn()
mocks.useRefreshMessage.mockReturnValue({
isPending: false,
@@ -458,16 +476,16 @@ describe('MessageThread', () => {
})
const messages = [
createUserMessage('1', 'Hello'),
createAssistantMessage('2', [createTextPart('This is a response', '2')]),
userMessage('1', 'Hello'),
assistantMessage('2', [textPart('This is a response')]),
]
render(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
messages={messages}
pending={[]}
/>,
)
fireEvent.click(screen.getByTitle('Edit message'))
+480 -343
View File
@@ -1,422 +1,557 @@
import { memo, useMemo, useState, useCallback, useEffect } from 'react'
import { Pencil } from 'lucide-react'
import { memo, useCallback, useMemo, useState } from 'react'
import { Pencil, Loader2, Volume2, VolumeX } from 'lucide-react'
import { assistantText } from '@opencode-manager/shared/opencode'
import type {
PromptAgentAttachment,
PromptFileAttachment,
PromptSkillAttachment,
SessionInboxInfo,
SessionInboxUser,
SessionMessageAssistant,
SessionMessageAssistantTool,
SessionMessageCompaction,
SessionMessageInfo,
SessionMessageShell,
} from '@opencode-manager/shared/opencode'
import { MessagePart } from './MessagePart'
import { MessageError } from './MessageError'
import { RetryPart } from './RetryPart'
import { StepFileChanges } from './StepFileChanges'
import { UserMessageActionButtons } from './UserMessageActionButtons'
import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage'
import { MessageError } from './MessageError'
import type { Message, Part, MessageWithParts } from '@/api/types'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import { useSettings } from '@/hooks/useSettings'
import type { components } from '@/api/opencode-types'
import type { Todo } from '@/components/message/SessionTodoDisplay'
import type { OpenCodeError } from '@/lib/opencode-errors'
import { useTTS } from '@/hooks/useTTS'
import { CopyButton } from '@/components/ui/copy-button'
function getMessageTextContent(parts: Part[]): string {
return parts
.filter(p => p.type === 'text')
.map(p => p.text || '')
.join('\n\n')
.trim()
function getMessageText(message: SessionMessageInfo): string {
switch (message.type) {
case 'user':
return message.text
case 'assistant':
return assistantText(message.content).trim()
case 'synthetic':
case 'system':
case 'skill':
return message.text
case 'shell':
return message.command
default:
return ''
}
}
interface MessageThreadProps {
opcodeUrl: string
sessionID: string
directory?: string
messages?: MessageWithParts[]
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onUndoMessage?: (restoredPrompt: string) => void
model?: string
function isSubagentTool(
part: SessionMessageAssistant['content'][number],
): part is SessionMessageAssistantTool {
return part.type === 'tool' && part.name === 'subagent'
}
const isMessageStreaming = (msg: Message): boolean => {
if (msg.role !== 'assistant') return false
return !('completed' in msg.time && msg.time.completed)
}
function isSessionStatusActive(sessionStatus: { type?: string }): boolean {
return sessionStatus?.type !== undefined && sessionStatus.type !== 'idle'
}
const compareMessageIds = (id1: string, id2: string): number => {
const num1 = parseInt(id1, 10)
const num2 = parseInt(id2, 10)
if (!isNaN(num1) && !isNaN(num2)) return num1 - num2
return id1.localeCompare(id2)
}
const hasRenderableContent = (role: Message['role'], parts: Part[], simpleChatMode: boolean, showReasoning: boolean): boolean => {
if (!parts || parts.length === 0) return false
return parts.some(part => {
switch (part.type) {
case 'text':
return !!(part.text && part.text.trim())
case 'reasoning':
return !simpleChatMode && showReasoning && !!(part.text && part.text.trim())
case 'file':
return role === 'user'
case 'patch':
case 'snapshot':
case 'agent':
return !simpleChatMode
case 'tool':
return !simpleChatMode || part.tool === 'task'
case 'retry':
return true
case 'step-finish':
case 'step-start':
case 'compaction':
function hasRenderableContent(
message: SessionMessageInfo,
simpleChatMode: boolean,
showReasoning: boolean,
): boolean {
switch (message.type) {
case 'user':
return message.text.trim().length > 0 || (message.files?.length ?? 0) > 0
case 'assistant':
if (!simpleChatMode && (message.snapshot?.files?.length ?? 0) > 0) return true
return message.content.some((part) => {
if (part.type === 'text') return part.text.trim().length > 0
if (part.type === 'reasoning') return !simpleChatMode && showReasoning && part.text.trim().length > 0
if (part.type === 'tool') return !simpleChatMode || isSubagentTool(part)
return false
case 'subtask':
return true
default:
return false
}
})
}
function isTaskToolPart(part: Part): part is components['schemas']['ToolPart'] {
return part.type === 'tool' && part.tool === 'task'
}
function isSubAgentActivityPart(part: Part): boolean {
return part.type === 'subtask' || isTaskToolPart(part)
}
function hasTextContent(parts: Part[]): boolean {
return parts.some(p => p.type === 'text' && !!(p.text && p.text.trim()))
}
function isIgnorableSubAgentMessagePart(part: Part): boolean {
if (part.type === 'step-start' || part.type === 'step-finish' || part.type === 'compaction') {
return true
}
if (part.type === 'text') {
return !part.text?.trim()
}
if (part.type === 'reasoning') {
return true
}
return false
}
function isStandaloneSubAgentMessage(role: Message['role'], parts: Part[]): boolean {
if (role !== 'assistant') return false
if (parts.length === 0) return false
if (hasTextContent(parts)) return false
const hasSubAgentActivity = parts.some(isSubAgentActivityPart)
const allPartsAreSubAgentOrStructural = parts.every(part => {
if (isIgnorableSubAgentMessagePart(part)) {
})
case 'synthetic':
case 'system':
return message.text.trim().length > 0
case 'shell':
case 'skill':
case 'compaction':
case 'agent-switched':
case 'model-switched':
case 'location-switched':
return true
}
return isSubAgentActivityPart(part)
})
return hasSubAgentActivity && allPartsAreSubAgentOrStructural
default:
return false
}
}
const findLastMessageByRole = (
messages: MessageWithParts[],
role: 'user' | 'assistant',
predicate?: (msg: Message) => boolean
): string | undefined => {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i].info
if (msg.role === role && (!predicate || predicate(msg))) {
return msg.id
}
function isStandaloneSubAgentMessage(message: SessionMessageInfo): boolean {
if (message.type !== 'assistant') return false
if (message.error !== undefined || message.retry !== undefined) return false
return message.content.length > 0 && message.content.every(isSubagentTool)
}
function findLastUserMessageId(messages: SessionMessageInfo[]): string | undefined {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index]
if (message?.type === 'user') return message.id
}
return undefined
}
function attachmentLabel(attachment: PromptFileAttachment): string {
if (attachment.name) return attachment.name
if (attachment.source.type === 'uri') {
const segments = attachment.source.uri.split('/')
return segments[segments.length - 1] || attachment.source.uri
}
return 'File'
}
interface UserAttachmentsProps {
files?: PromptFileAttachment[]
agents?: PromptAgentAttachment[]
skills?: PromptSkillAttachment[]
}
function UserAttachments({ files: attachedFiles, agents: attachedAgents, skills: attachedSkills }: UserAttachmentsProps) {
const files = attachedFiles ?? []
const agents = attachedAgents ?? []
const skills = attachedSkills ?? []
if (files.length === 0 && agents.length === 0 && skills.length === 0) return null
return (
<div className="flex flex-wrap items-center gap-1 mt-1">
{files.map((file, index) => (
<span
key={`file-${index}`}
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-muted border border-border text-sm text-foreground"
>
<span className="text-blue-600 dark:text-blue-400">@</span>
<span className="font-medium">{attachmentLabel(file)}</span>
</span>
))}
{agents.map((agent, index) => (
<span
key={`agent-${index}`}
className="inline-flex items-center px-2 py-1 rounded bg-purple-500/10 border border-purple-500/30 text-xs text-purple-600 dark:text-purple-400"
>
agent: {agent.name}
</span>
))}
{skills.map((skill, index) => (
<span
key={`skill-${index}`}
className="inline-flex items-center px-2 py-1 rounded bg-blue-500/10 border border-blue-500/30 text-xs text-blue-600 dark:text-blue-400"
>
skill: {skill.name}
</span>
))}
</div>
)
}
interface TTSButtonProps {
messageId: string
content: string
}
function TTSButton({ messageId, content }: TTSButtonProps) {
const { speakMessage, stop, isEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
if (!isEnabled || !content.trim()) {
return null
}
const isThisPlaying = (isPlaying || isLoading) && activeMessageId === messageId
const handleClick = () => {
if (isThisPlaying) {
stop()
} else {
speakMessage(messageId, content)
}
}
return (
<button
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'}`}
title={isThisPlaying ? 'Stop playback' : 'Read aloud'}
disabled={isLoading && !isThisPlaying}
>
{isLoading && isThisPlaying ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : isThisPlaying ? (
<VolumeX className="w-4 h-4" />
) : (
<Volume2 className="w-4 h-4" />
)}
</button>
)
}
function MessageDivider({ label }: { label: string }) {
return (
<div className="flex items-center gap-2 my-1 text-xs text-muted-foreground">
<span className="h-px flex-1 bg-border" />
<span className="shrink-0">{label}</span>
<span className="h-px flex-1 bg-border" />
</div>
)
}
function ShellMessage({ message }: { message: SessionMessageShell }) {
const output = message.output?.output ?? ''
const statusLabel = message.status === 'running'
? 'running'
: message.exit === undefined
? message.status
: `${message.status} (exit ${message.exit})`
return (
<div className="rounded-lg border border-border bg-card/50 p-2 my-1">
<div className="flex items-center gap-2 text-sm min-w-0">
<span className="text-green-600 dark:text-green-400 shrink-0">$</span>
<span className="text-foreground truncate">{message.command}</span>
<span className="text-muted-foreground text-xs ml-auto shrink-0">{statusLabel}</span>
</div>
{output && (
<div className="relative mt-1">
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">{output}</pre>
<CopyButton content={output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
</div>
)}
</div>
)
}
function CompactionBanner({ message }: { message: SessionMessageCompaction }) {
if (message.status === 'running') {
return (
<div className="flex items-center gap-2 my-1 text-xs text-muted-foreground">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
<span>Compacting session...</span>
</div>
)
}
if (message.status === 'failed') {
return (
<div className="my-1 rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-1.5 text-xs text-red-600 dark:text-red-400">
Compaction failed: {message.error.message}
</div>
)
}
return (
<div className="my-1 rounded-lg border border-border bg-card/50 px-3 py-1.5 text-xs text-muted-foreground">
<span className="font-medium">Session compacted</span>
{message.summary && <p className="mt-0.5 whitespace-pre-wrap">{message.summary}</p>}
</div>
)
}
function QueuedPromptRow({ item }: { item: SessionInboxUser }) {
return (
<div className="w-full rounded-lg p-1.5 bg-amber-500/10 border border-amber-500/30">
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-medium text-muted-foreground">You</span>
<span className="text-xs text-muted-foreground">
{new Date(item.time.created).toLocaleTimeString()}
</span>
<span className="text-xs font-semibold bg-amber-500 text-amber-950 px-1.5 py-0.5 rounded">
{item.delivery === 'queue' ? 'QUEUED' : 'STEERING'}
</span>
</div>
<ClickableUserMessage content={item.payload.text} onClick={() => {}} isEditable={false} />
<UserAttachments
files={item.payload.files}
agents={item.payload.agents}
skills={item.payload.skills}
/>
</div>
)
}
interface MessageRowProps {
msgWithParts: MessageWithParts
nextAssistantMessage: MessageWithParts | undefined
pendingAssistantId: string | undefined
lastUserMessageId: string | undefined
message: SessionMessageInfo
nextAssistantMessageId: string | undefined
isLastUserMessage: boolean
isSessionBusy: boolean
onUndoMessage?: (restoredPrompt: string) => void
editingUserMessageId: string | null
editingForAssistantId: string | null
opcodeUrl: string
handleStartEditUserMessage: (userMessageId: string, assistantMessageId: string) => void
handleCancelEdit: () => void
sessionID: string
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
handleStartEditUserMessage: (userMessageId: string, assistantMessageId: string) => void
handleCancelEdit: () => void
model?: string
simpleChatMode: boolean
showReasoning: boolean
}
const MessageRow = memo(function MessageRow({
msgWithParts,
nextAssistantMessage,
pendingAssistantId,
lastUserMessageId,
message,
nextAssistantMessageId,
isLastUserMessage,
isSessionBusy,
onUndoMessage,
editingUserMessageId,
editingForAssistantId,
opcodeUrl,
handleStartEditUserMessage,
handleCancelEdit,
sessionID,
directory,
onFileClick,
onChildSessionClick,
handleStartEditUserMessage,
handleCancelEdit,
model,
simpleChatMode,
showReasoning,
}: MessageRowProps) {
const msg = msgWithParts.info
const parts = msgWithParts.parts
const streaming = isMessageStreaming(msg)
const isQueued = msg.role === 'user' && pendingAssistantId && compareMessageIds(msg.id, pendingAssistantId) > 0
const isLastUserMessage = msg.role === 'user' && msg.id === lastUserMessageId
const messageTextContent = getMessageTextContent(parts)
const messageTextContent = getMessageText(message)
const streaming = message.type === 'assistant' && message.time.completed === undefined
const isEditingThisMessage = editingUserMessageId === message.id
const canEditUserMessage = isLastUserMessage && !isSessionBusy
const canUndoUserMessage = isLastUserMessage && !isSessionBusy && onUndoMessage
const nextAssistantMsg = nextAssistantMessage?.info
const isUserBeforeAssistant = msg.role === 'user' && nextAssistantMessage
const canEditUserMessage = isLastUserMessage && isUserBeforeAssistant && !isSessionBusy
const canUndoUserMessage = isLastUserMessage && nextAssistantMessage && !isSessionBusy && onUndoMessage
if (message.type === 'user') {
if (!hasRenderableContent(message, simpleChatMode, showReasoning)) return null
const isEditingThisMessage = editingUserMessageId === msg.id
const hasContent = hasRenderableContent(msg.role, parts, simpleChatMode, showReasoning)
const hasError = msg.role === 'assistant' && 'error' in msg && msg.error
const standaloneSubAgentMessage = isStandaloneSubAgentMessage(msg.role, parts)
if (!hasContent && !hasError) {
return null
}
if (standaloneSubAgentMessage) {
return (
<div
key={msg.id}
className="flex flex-col group"
>
<div className="space-y-1">
{parts.filter(isSubAgentActivityPart).map((part, partIndex) => (
<div key={`${msg.id}-${part.id}-${partIndex}`}>
<MessagePart
part={part}
role={msg.role}
allParts={parts}
partIndex={partIndex}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
messageTextContent={messageTextContent}
/>
</div>
))}
</div>
</div>
)
}
return (
<div
key={msg.id}
className="flex flex-col group"
>
<div
className={`w-full rounded-lg p-1.5 ${
msg.role === 'user'
? isQueued
? 'bg-amber-500/10 border border-amber-500/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 justify-between gap-2 mb-1">
<div className="flex items-center gap-2">
<span className="text-xs font-medium text-muted-foreground">
{msg.role === 'user' ? 'You' : (msg.role === 'assistant' && 'modelID' in msg ? msg.modelID : 'Assistant')}
</span>
{msg.time && (
<div className="flex flex-col group">
<div
className={`w-full rounded-lg p-1.5 ${
isEditingThisMessage
? 'bg-blue-600/30 border border-blue-600/50'
: 'bg-blue-600/20 border border-blue-600/30'
}`}
>
<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">You</span>
<span className="text-xs text-muted-foreground">
{new Date(msg.time.created).toLocaleTimeString()}
</span>
)}
{canEditUserMessage && nextAssistantMsg && (
<button
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMsg.id)}
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
title="Edit message"
>
<Pencil className="w-3.5 h-3.5" />
</button>
)}
{isQueued && (
<span className="text-xs font-semibold bg-amber-500 text-amber-950 px-1.5 py-0.5 rounded">
QUEUED
{new Date(message.time.created).toLocaleTimeString()}
</span>
{canEditUserMessage && nextAssistantMessageId && (
<button
onClick={() => handleStartEditUserMessage(message.id, nextAssistantMessageId)}
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
title="Edit message"
>
<Pencil className="w-3.5 h-3.5" />
</button>
)}
</div>
{canUndoUserMessage && (
<UserMessageActionButtons
sessionId={sessionID}
directory={directory}
userMessageId={message.id}
userMessageContent={messageTextContent}
onUndo={onUndoMessage}
/>
)}
</div>
{msg.role === 'user' && canUndoUserMessage && (
<UserMessageActionButtons
opcodeUrl={opcodeUrl}
sessionId={sessionID}
directory={directory}
userMessageId={msg.id}
userMessageContent={messageTextContent}
onUndo={onUndoMessage}
/>
)}
</div>
<div className="space-y-2">
{msg.role === 'user' && isEditingThisMessage && editingForAssistantId ? (
{isEditingThisMessage && nextAssistantMessageId ? (
<EditableUserMessage
opcodeUrl={opcodeUrl}
sessionId={sessionID}
directory={directory}
content={messageTextContent}
assistantMessageId={editingForAssistantId}
assistantMessageId={nextAssistantMessageId}
onCancel={handleCancelEdit}
model={model}
/>
) : msg.role === 'user' && canEditUserMessage && nextAssistantMsg ? (
<ClickableUserMessage
content={messageTextContent}
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMsg.id)}
isEditable={false}
/>
) : msg.role === 'user' && simpleChatMode ? (
) : simpleChatMode ? (
<ClickableUserMessage
content={messageTextContent}
onClick={() => {}}
isEditable={false}
/>
) : parts.length > 0 ? (
parts.map((part: Part, partIndex: number) => (
<div key={`${msg.id}-${part.id}-${partIndex}`}>
<MessagePart
part={part}
role={msg.role}
allParts={parts}
partIndex={partIndex}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
messageTextContent={msg.role === 'assistant' ? messageTextContent : undefined}
/>
</div>
))
) : null}
{hasError && (
<MessageError error={msg.error as OpenCodeError} />
) : (
<ClickableUserMessage
content={messageTextContent}
onClick={() => handleStartEditUserMessage(message.id, nextAssistantMessageId ?? '')}
isEditable={false}
/>
)}
<UserAttachments
files={message.files}
agents={message.agents}
skills={message.skills}
/>
</div>
</div>
</div>
)
)
}
if (message.type === 'assistant') {
const hasError = message.error !== undefined
if (!hasRenderableContent(message, simpleChatMode, showReasoning) && !hasError && !message.retry) {
return null
}
const standaloneSubAgentMessage = isStandaloneSubAgentMessage(message)
if (standaloneSubAgentMessage) {
return (
<div className="flex flex-col group">
<div className="space-y-1">
{message.content.filter(isSubagentTool).map((part, partIndex) => (
<div key={`${message.id}-${part.id}-${partIndex}`}>
<MessagePart
part={part}
messageID={message.id}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
</div>
))}
</div>
</div>
)
}
const isFree = (message.cost ?? 0) === 0
const totalTokens = message.tokens
? message.tokens.input + message.tokens.output + message.tokens.reasoning + message.tokens.cache.read
: 0
return (
<div className="flex flex-col group">
<div
className={`w-full rounded-lg p-1.5 bg-card/50 border border-border ${streaming ? 'animate-pulse-subtle' : ''}`}
>
<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">
{message.model.id}
</span>
<span className="text-xs text-muted-foreground">
{new Date(message.time.created).toLocaleTimeString()}
</span>
</div>
</div>
<div className="space-y-2">
{message.content.map((part, partIndex) => (
<div key={`${message.id}-${part.type}-${partIndex}`}>
<MessagePart
part={part}
messageID={message.id}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
</div>
))}
{!simpleChatMode && message.snapshot?.files && (
<StepFileChanges
files={message.snapshot.files}
snapshot={message.snapshot.end}
onFileClick={onFileClick}
/>
)}
{message.retry && <RetryPart retry={message.retry} />}
{message.error && <MessageError error={message.error} />}
</div>
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
{!(isFree) && <span>${(message.cost ?? 0).toFixed(4)} • {totalTokens} tokens</span>}
<CopyButton content={messageTextContent} title="Copy message" />
{messageTextContent && <TTSButton messageId={message.id} content={messageTextContent} />}
</div>
</div>
</div>
)
}
if (message.type === 'shell') {
return <ShellMessage message={message} />
}
if (message.type === 'compaction') {
return <CompactionBanner message={message} />
}
if (message.type === 'agent-switched') {
return <MessageDivider label={`Agent: ${message.agent}`} />
}
if (message.type === 'model-switched') {
return <MessageDivider label={`Model: ${message.model.providerID}/${message.model.id}`} />
}
if (message.type === 'location-switched') {
return <MessageDivider label={`Location: ${message.location.directory}`} />
}
if (message.type === 'skill') {
return (
<div className="my-1 rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-1.5 text-xs text-muted-foreground">
Skill loaded: <span className="font-medium text-foreground">{message.name}</span>
</div>
)
}
if (message.type === 'synthetic' || message.type === 'system') {
return (
<div className="my-1 px-3 py-1.5 text-xs italic text-muted-foreground whitespace-pre-wrap">
{message.text}
</div>
)
}
return null
})
export const MessageThread = memo(function MessageThread({
opcodeUrl,
sessionID,
directory,
messages,
onFileClick,
interface MessageThreadProps {
sessionID: string
directory?: string
messages: SessionMessageInfo[]
pending: SessionInboxInfo[]
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onUndoMessage?: (restoredPrompt: string) => void
model?: string
isSessionBusy?: boolean
}
export const MessageThread = memo(function MessageThread({
sessionID,
directory,
messages,
pending,
onFileClick,
onChildSessionClick,
onUndoMessage,
model
model,
isSessionBusy = false,
}: MessageThreadProps) {
const [editingUserMessageId, setEditingUserMessageId] = useState<string | null>(null)
const [editingForAssistantId, setEditingForAssistantId] = useState<string | null>(null)
const sessionStatus = useSessionStatusForSession(sessionID)
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
const pendingAssistantId = useMemo(() => {
if (!messages) return undefined
return findLastMessageByRole(messages, 'assistant', isMessageStreaming)
}, [messages])
const lastUserMessageId = useMemo(() => {
if (!messages) return undefined
return findLastMessageByRole(messages, 'user')
}, [messages])
const lastUserMessageId = useMemo(() => findLastUserMessageId(messages), [messages])
const nextAssistantByMessageId = useMemo(() => {
const map = new Map<string, MessageWithParts | undefined>()
if (!messages) return map
let next: MessageWithParts | undefined
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
map.set(msg.info.id, next)
if (msg.info.role === 'assistant') {
next = msg
const nextAssistantIdByMessageId = useMemo(() => {
const map = new Map<string, string | undefined>()
let nextAssistantId: string | undefined
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index]
map.set(message.id, nextAssistantId)
if (message.type === 'assistant') {
nextAssistantId = message.id
}
}
return map
}, [messages])
const isSessionBusy = !!pendingAssistantId || isSessionStatusActive(sessionStatus)
const setSessionTodos = useSessionTodos((state) => state.setTodos)
useEffect(() => {
if (!messages || messages.length === 0) return
const allParts = messages.flatMap(m => m.parts)
const latestTodoPart = allParts
.filter((part): part is components['schemas']['ToolPart'] => part.type === 'tool' && (part.tool === 'todowrite' || part.tool === 'todoread'))
.filter(part => part.state.status === 'completed' && 'time' in part.state)
.sort((a, b) => {
const aState = a.state as { time?: { end?: number } }
const bState = b.state as { time?: { end?: number } }
const aEndTime = aState.time?.end ?? 0
const bEndTime = bState.time?.end ?? 0
return bEndTime - aEndTime
})[0]
if (latestTodoPart) {
const state = latestTodoPart.state
let todos: Todo[] = []
if ('metadata' in state && state.metadata?.todos && Array.isArray(state.metadata.todos)) {
todos = state.metadata.todos as Todo[]
} else if ('output' in state && state.output) {
try {
const parsed = JSON.parse(state.output)
todos = Array.isArray(parsed)
? parsed as Todo[]
: parsed?.todos ? parsed.todos as Todo[]
: []
} catch (_) {
console.warn('Failed to parse todo output:', _)
}
}
if (todos.length > 0) {
setSessionTodos(sessionID, todos)
}
}
}, [messages, sessionID, setSessionTodos])
const handleStartEditUserMessage = useCallback((userMessageId: string, assistantMessageId: string) => {
const handleStartEditUserMessage = useCallback((userMessageId: string) => {
setEditingUserMessageId(userMessageId)
setEditingForAssistantId(assistantMessageId)
}, [])
const handleCancelEdit = useCallback(() => {
setEditingUserMessageId(null)
setEditingForAssistantId(null)
}, [])
if (!messages || messages.length === 0) {
if (messages.length === 0 && pending.length === 0) {
return (
<div className="flex items-center justify-center h-full text-muted-foreground">
No messages yet. Start a conversation below.
@@ -426,29 +561,31 @@ export const MessageThread = memo(function MessageThread({
return (
<div className="flex flex-col space-y-2 p-2 overflow-x-hidden">
{messages.map((msgWithParts) => (
{messages.map((message) => (
<MessageRow
key={msgWithParts.info.id}
msgWithParts={msgWithParts}
nextAssistantMessage={nextAssistantByMessageId.get(msgWithParts.info.id)}
pendingAssistantId={pendingAssistantId}
lastUserMessageId={lastUserMessageId}
key={message.id}
message={message}
nextAssistantMessageId={nextAssistantIdByMessageId.get(message.id)}
isLastUserMessage={message.id === lastUserMessageId}
isSessionBusy={isSessionBusy}
onUndoMessage={onUndoMessage}
editingUserMessageId={editingUserMessageId}
editingForAssistantId={editingForAssistantId}
opcodeUrl={opcodeUrl}
handleStartEditUserMessage={handleStartEditUserMessage}
handleCancelEdit={handleCancelEdit}
sessionID={sessionID}
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
handleStartEditUserMessage={handleStartEditUserMessage}
handleCancelEdit={handleCancelEdit}
model={model}
simpleChatMode={simpleChatMode}
showReasoning={showReasoning}
/>
))}
{pending.map((item) => (
item.type === 'user'
? <QueuedPromptRow key={item.id} item={item} />
: null
))}
</div>
)
})
@@ -1,70 +0,0 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
import { getRelativePath } from './FileToolRender'
import { ChevronDown, ChevronUp } from 'lucide-react'
type PatchPartType = components['schemas']['PatchPart']
interface PatchPartProps {
part: PatchPartType
onFileClick?: (filePath: string) => void
}
const INITIAL_FILES_SHOWN = 3
export function PatchPart({ part, onFileClick }: PatchPartProps) {
const [expanded, setExpanded] = useState(false)
const hasMoreFiles = part.files.length > INITIAL_FILES_SHOWN
const displayedFiles = expanded ? part.files : part.files.slice(0, INITIAL_FILES_SHOWN)
const hiddenCount = part.files.length - INITIAL_FILES_SHOWN
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-3 py-1.5 bg-card hover:bg-card-hover text-left flex items-center justify-between text-sm gap-2"
>
<span className="font-medium">
File Changes ({part.files.length} file{part.files.length !== 1 ? 's' : ''})
</span>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="text-muted-foreground text-xs font-mono">{part.hash.slice(0, 8)}</span>
{expanded ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />}
</div>
</button>
<div className="bg-card px-3 py-2 space-y-1">
{displayedFiles.map((file, index) => (
<div
key={index}
className="text-xs font-mono text-blue-600 dark:text-blue-400 hover:underline cursor-pointer"
onClick={() => onFileClick?.(file)}
>
{getRelativePath(file)}
</div>
))}
{!expanded && hasMoreFiles && (
<button
onClick={() => setExpanded(true)}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 mt-1"
>
<ChevronDown className="w-3 h-3" />
+{hiddenCount} more file{hiddenCount !== 1 ? 's' : ''}
</button>
)}
{expanded && hasMoreFiles && (
<button
onClick={() => setExpanded(false)}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 mt-1"
>
<ChevronUp className="w-3 h-3" />
Show less
</button>
)}
</div>
</div>
)
}
@@ -0,0 +1,225 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
const mocks = vi.hoisted(() => ({
runCommand: vi.fn(),
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
compactSession: vi.fn(),
agents: [] as Array<{ name: string; description?: string }>,
useSTT: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useFileSearch: vi.fn(),
useModelSelection: vi.fn(),
useVariants: vi.fn(),
useSessionAgent: vi.fn(),
useUserBash: vi.fn(),
useSessionAgentStore: vi.fn(),
useSendErrorStore: vi.fn(),
}))
vi.mock('@/api/opencode', async () => {
const actual = await vi.importActual('@/api/opencode')
return {
...actual,
runCommand: mocks.runCommand,
compactSession: mocks.compactSession,
switchSessionModel: mocks.switchSessionModel,
switchSessionAgent: mocks.switchSessionAgent,
}
})
vi.mock('@/hooks/useOpenCode', async () => {
const actual = await vi.importActual('@/hooks/useOpenCode')
return {
...actual,
useAgents: () => ({ data: mocks.agents }),
}
})
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
vi.mock('@/hooks/useModelSelection', () => ({ useModelSelection: mocks.useModelSelection }))
vi.mock('@/hooks/useVariants', () => ({ useVariants: mocks.useVariants }))
vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAgent }))
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore }))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: vi.fn().mockReturnValue(false),
setShowDialog: vi.fn(),
}),
}))
vi.mock('@/components/agent/AgentQuickSelect', () => ({
AgentQuickSelect: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/components/model/ModelQuickSelect', () => ({
ModelQuickSelect: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
}))
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
id: 'test-session',
projectID: 'proj_1',
time: { created: 1000, updated: 1000 },
location: { directory: '/test' },
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
...overrides,
})
describe('PromptInput command submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
onShowSessionsDialog: vi.fn(),
onShowHelpDialog: vi.fn(),
onToggleDetails: vi.fn(),
onExportSession: vi.fn(),
onPromptChange: vi.fn(),
}
const renderComponent = () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
return render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
</QueryClientProvider>
)
}
const attachImage = async (container: HTMLElement) => {
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement
const image = new File(['img'], 'pic.png', { type: 'image/png' })
fireEvent.change(fileInput, { target: { files: [image] } })
await screen.findByText('pic.png')
}
beforeEach(() => {
vi.clearAllMocks()
mocks.runCommand.mockResolvedValue(undefined)
mocks.switchSessionModel.mockResolvedValue(undefined)
mocks.switchSessionAgent.mockResolvedValue(undefined)
mocks.agents = [{ name: 'reviewer', description: 'Reviewer' }]
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
isProcessing: false,
isSupported: false,
isEnabled: false,
interimTranscript: '',
transcript: '',
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
reset: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({
filterCommands: (query: string) => query === 'review' ? [{ name: 'review', description: 'Review' }] : [],
})
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveModel: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
it('sends parsed command attachments and offsets to runCommand without injecting the selected agent', async () => {
const { container } = renderComponent()
act(() => {
useUIState.getState().selectPromptFile('src/App.tsx')
})
const input = await screen.findByPlaceholderText('Send a message...')
await waitFor(() => expect(input).toHaveValue('@App.tsx '))
await attachImage(container)
fireEvent.change(input, { target: { value: '/review @App.tsx @reviewer' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled())
const call = mocks.runCommand.mock.calls[0][0] as {
sessionID: string
name: string
text: string
files: Array<{ uri: string; name?: string; mention?: { start: number; end: number; text: string } }>
agents: Array<{ name: string; mention?: { start: number; end: number; text: string } }>
skills: unknown[]
}
expect(call.sessionID).toBe('test-session')
expect(call.name).toBe('review')
expect(call.text).toBe('@App.tsx @reviewer')
expect(call.files).toEqual(expect.arrayContaining([
{ uri: 'file:///test/src/App.tsx', name: 'App.tsx', mention: { start: 0, end: 8, text: '@App.tsx' } },
expect.objectContaining({ name: 'pic.png', uri: expect.stringMatching(/^data:image\/png/) }),
]))
expect(call.agents).toEqual([
{ name: 'reviewer', mention: { start: 9, end: 18, text: '@reviewer' } },
])
expect(call.skills).toEqual([])
})
it('preserves the submitted command text when the command submission fails', async () => {
mocks.runCommand.mockRejectedValueOnce(new Error('command failed'))
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/review' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled())
expect(input).toHaveValue('/review')
})
})
@@ -0,0 +1,234 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
const mocks = vi.hoisted(() => ({
sendPrompt: vi.fn(),
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
runCommand: vi.fn(),
compactSession: vi.fn(),
agents: [] as Array<{ name: string; description?: string }>,
useSTT: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useFileSearch: vi.fn(),
useModelSelection: vi.fn(),
useVariants: vi.fn(),
useSessionAgent: vi.fn(),
useUserBash: vi.fn(),
useSessionAgentStore: vi.fn(),
useSendErrorStore: vi.fn(),
}))
vi.mock('@/api/opencode', async () => {
const actual = await vi.importActual('@/api/opencode')
return {
...actual,
sendPrompt: mocks.sendPrompt,
runCommand: mocks.runCommand,
compactSession: mocks.compactSession,
switchSessionModel: mocks.switchSessionModel,
switchSessionAgent: mocks.switchSessionAgent,
}
})
vi.mock('@/hooks/useOpenCode', async () => {
const actual = await vi.importActual('@/hooks/useOpenCode')
return {
...actual,
useAgents: () => ({ data: mocks.agents }),
}
})
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
vi.mock('@/hooks/useModelSelection', () => ({ useModelSelection: mocks.useModelSelection }))
vi.mock('@/hooks/useVariants', () => ({ useVariants: mocks.useVariants }))
vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAgent }))
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
vi.mock('@/stores/sendErrorStore', () => ({
useSendErrorStore: Object.assign(
(selector: (state: unknown) => unknown) => selector({ errors: {} }),
{ getState: () => ({ clearError: vi.fn(), setError: vi.fn() }) },
),
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: vi.fn().mockReturnValue(false),
setShowDialog: vi.fn(),
}),
}))
vi.mock('@/components/agent/AgentQuickSelect', () => ({
AgentQuickSelect: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/components/model/ModelQuickSelect', () => ({
ModelQuickSelect: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
}))
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
id: 'test-session',
projectID: 'proj_1',
time: { created: 1000, updated: 1000 },
location: { directory: '/test' },
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
...overrides,
})
describe('PromptInput agent mention submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
onShowSessionsDialog: vi.fn(),
onShowHelpDialog: vi.fn(),
onToggleDetails: vi.fn(),
onExportSession: vi.fn(),
onPromptChange: vi.fn(),
}
const renderComponent = (overrides: Partial<typeof defaultProps> = {}) => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
return render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} {...overrides} />
</QueryClientProvider>
)
}
beforeEach(() => {
vi.clearAllMocks()
mocks.sendPrompt.mockResolvedValue({
id: 'inbox_1',
sessionID: 'test-session',
time: { created: 1000 },
type: 'user',
payload: { text: '' },
delivery: 'queue',
})
mocks.switchSessionModel.mockResolvedValue(undefined)
mocks.switchSessionAgent.mockResolvedValue(undefined)
mocks.runCommand.mockResolvedValue(undefined)
mocks.compactSession.mockResolvedValue(undefined)
mocks.agents = [{ name: 'reviewer', description: 'Reviewer' }]
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
isProcessing: false,
isSupported: false,
isEnabled: false,
interimTranscript: '',
transcript: '',
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
reset: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({ filterCommands: () => [] })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveModel: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
it('sends an @agent mention as an attachment without switching the session agent', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'ask @reviewer' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.sendPrompt).toHaveBeenCalledWith(expect.objectContaining({
sessionID: 'test-session',
text: 'ask @reviewer',
agents: [{ name: 'reviewer', mention: { start: 4, end: 13, text: '@reviewer' } }],
}))
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
})
it('queues an @agent mention as an attachment without switching the session agent', async () => {
renderComponent({ isStreamingResponse: true })
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'ask @reviewer' } })
fireEvent.click(screen.getByTitle('Queue message'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.sendPrompt).toHaveBeenCalledWith(expect.objectContaining({
sessionID: 'test-session',
text: 'ask @reviewer',
agents: [{ name: 'reviewer', mention: { start: 4, end: 13, text: '@reviewer' } }],
delivery: 'queue',
}))
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
})
it('sends plain text without inferring an agent attachment or switching', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'plain text' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.sendPrompt).toHaveBeenCalledWith(expect.objectContaining({
sessionID: 'test-session',
text: 'plain text',
agents: [],
}))
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
})
})
@@ -42,9 +42,8 @@ vi.mock('@/hooks/useMobile', () => ({
vi.mock('@/hooks/useOpenCode', () => ({
useSendPrompt: () => ({ mutate: mocks.useSendPromptMutate, isPending: mocks.sendPromptPending() }),
useAbortSession: () => ({ mutate: vi.fn() }),
useInterruptSession: () => ({ mutate: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useOpenCodeClient: () => ({}),
useAgents: () => ({ data: [] }),
}))
@@ -135,7 +134,6 @@ describe('PromptInput STT Gesture Tests', () => {
const mockSetAgent = vi.fn()
const defaultProps = {
opcodeUrl: 'http://localhost:5551',
directory: '/test',
sessionID: 'test-session',
repoId: 1,
@@ -317,9 +315,8 @@ describe('PromptInput STT Gesture Tests', () => {
fireEvent.click(queueButton)
const [callArgs] = mocks.useSendPromptMutate.mock.calls[0] as [{ prompt: string }, unknown]
expect(callArgs.prompt).toBe('follow-up')
expect('queued' in callArgs).toBe(false)
const [callArgs] = mocks.useSendPromptMutate.mock.calls[0] as [{ text: string }, unknown]
expect(callArgs.text).toBe('follow-up')
})
it('restores a failed queued prompt when the input is empty', async () => {
@@ -334,9 +331,8 @@ describe('PromptInput STT Gesture Tests', () => {
fireEvent.change(input, { target: { value: 'queued message' } })
fireEvent.click(screen.getByTitle('Queue message'))
const [callArgs] = mocks.useSendPromptMutate.mock.calls[0] as [{ prompt: string }, unknown]
expect(callArgs.prompt).toBe('queued message')
expect('queued' in callArgs).toBe(false)
const [callArgs] = mocks.useSendPromptMutate.mock.calls[0] as [{ text: string }, unknown]
expect(callArgs.text).toBe('queued message')
await waitFor(() => {
expect(input).toHaveValue('')
@@ -421,10 +417,6 @@ describe('PromptInput STT Gesture Tests', () => {
useUIState.getState().selectPromptCommand({
name: 'help',
description: 'Show help',
template: '',
agent: '',
model: '',
hints: [],
})
})
+96 -106
View File
@@ -1,10 +1,9 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
import { useModelSelection } from '@/hooks/useModelSelection'
import { useOpenCodeClient } from '@/hooks/useOpenCode'
import { useVariants } from '@/hooks/useVariants'
import { useSessionAgent } from '@/hooks/useSessionAgent'
import { useSTT } from '@/hooks/useSTT'
@@ -27,14 +26,14 @@ import { SessionStatusIndicator } from '@/components/ui/session-status-indicator
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { randomId } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { formatModelName, getProviders } from '@/api/providers'
import { useQuery } from '@tanstack/react-query'
import { formatModelName } from '@/api/providers'
import { useProviders } from '@/hooks/useProviders'
import type { components } from '@/api/opencode-types'
import type { CommandInfo, ModelRef } from '@opencode-manager/shared/opencode'
import type { FileAttachmentInfo, ImageAttachment } from '@/api/types'
const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"]
@@ -55,8 +54,6 @@ const VOICE_SEND_SWIPE_DISARM_THRESHOLD = 8
type VoiceButtonVariant = 'desktop' | 'mobile'
type CommandType = components['schemas']['Command']
export interface PromptInputHandle {
setPromptValue: (value: string) => void
clearPrompt: () => void
@@ -64,7 +61,6 @@ export interface PromptInputHandle {
}
interface PromptInputProps {
opcodeUrl: string
directory?: string
sessionID: string
showScrollButton?: boolean
@@ -75,11 +71,12 @@ interface PromptInputProps {
onShowHelpDialog?: () => void
onToggleDetails?: () => boolean
onExportSession?: () => void
onUndo?: () => void | Promise<void>
onRedo?: () => void | Promise<void>
onPromptChange?: (hasContent: boolean) => void
}
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
opcodeUrl,
directory,
sessionID,
showScrollButton,
@@ -90,6 +87,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
onShowHelpDialog,
onToggleDetails,
onExportSession,
onUndo,
onRedo,
onPromptChange
}, ref) {
const [prompt, setPrompt] = useState('')
@@ -104,7 +103,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null)
const [selectedMentionIndex, setSelectedMentionIndex] = useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const [selectedAgent, setSelectedAgent] = useState<string | null>(null)
const [localMode, setLocalMode] = useState<string | null>(null)
const [isTogglingRecording, setIsTogglingRecording] = useState(false)
const [isVoiceSwipeArmed, setIsVoiceSwipeArmed] = useState(false)
@@ -171,7 +169,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
setAttachedFiles(new Map())
revokeBlobUrls(submittedImageAttachments)
setImageAttachments([])
setSelectedAgent(null)
clearSTT()
}, [clearSTT])
@@ -199,7 +196,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
setAttachedFiles(new Map())
revokeBlobUrls(imageAttachments)
setImageAttachments([])
setSelectedAgent(null)
resetVoiceGestureState()
if (isRecording) {
abortRecording()
@@ -212,34 +208,23 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
fileInputRef.current?.click()
}
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState])
const sessionAgent = useSessionAgent(opcodeUrl, sessionID, directory)
const sessionAgent = useSessionAgent(sessionID, directory)
const currentMode = localMode ?? sessionAgent.agent
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const sendPrompt = useSendPrompt(directory)
const sendShell = useSendShell(directory)
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
sessionID,
directory,
onShowSessionsDialog,
onShowModelsDialog: undefined,
onShowHelpDialog,
onToggleDetails,
onExportSession,
currentAgent: currentMode
})
const interruptSession = useInterruptSession()
const { filterCommands } = useCommands({ directory })
const { files: searchResults } = useFileSearch(
opcodeUrl,
mentionQuery,
showMentionSuggestions,
directory
)
const { data: agents = [] } = useAgents(opcodeUrl, directory)
const { data: agents = [] } = useAgents(directory)
const agentNames = useMemo(() => agents.map((agent) => agent.name), [agents])
const failedPrompt = useSendErrorStore((state) => state.errors[sessionID]?.failedPrompt)
const restoredFailedPromptRef = useRef<string | null>(null)
@@ -294,25 +279,26 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (isStreamingResponse) {
onScrollToBottom()
const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments)
const agentUsed = selectedAgent || currentMode
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
sendPrompt.mutate(
{
sessionID,
prompt: submittedPrompt,
parts,
model: currentModel,
agent: agentUsed,
variant: currentVariant,
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef,
agent: currentMode,
delivery: 'queue',
},
{
onSuccess: () => clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
}
)
setStoredAgent(sessionID, agentUsed)
setStoredAgent(sessionID, currentMode)
if (model) {
setStoredModel({ providerID: model.providerID, modelID: model.modelID })
}
@@ -329,7 +315,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
{
sessionID,
command,
agent: currentMode
},
{
onSuccess: () => {
@@ -352,15 +337,26 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const command = filterCommands(commandName)[0]
if (command) {
executeCommand(command, commandArgs?.trim() || '')
setPrompt('')
clearSTT()
const parsed = parsePromptToInput(commandArgs?.trim() || '', attachedFiles, agentNames, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
void executeCommand(command, {
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
}).then((shouldClear) => {
if (shouldClear) {
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
}
})
return
}
}
const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments)
const agentUsed = selectedAgent || currentMode
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
@@ -374,11 +370,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
sendPrompt.mutate(
{
sessionID,
prompt: submittedPrompt,
parts,
model: currentModel,
agent: agentUsed,
variant: currentVariant
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef,
agent: currentMode,
},
{
onSuccess: () => {
@@ -393,7 +390,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
onScrollToBottom()
setStoredAgent(sessionID, agentUsed)
setStoredAgent(sessionID, currentMode)
if (model) {
setStoredModel({ providerID: model.providerID, modelID: model.modelID })
}
@@ -402,49 +399,32 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
handleSubmitRef.current = handleSubmit
const handleStop = () => {
abortSession.mutate(sessionID)
interruptSession.mutate(sessionID)
}
const handleCommandSelect = useCallback(async (command: CommandType) => {
const handleCommandSelect = useCallback(async (command: CommandInfo) => {
if (!textareaRef.current) return
setShowSuggestions(false)
setSuggestionQuery('')
if (command.template) {
const cleanedTemplate = command.template
.replace(/\$ARGUMENTS/g, '')
.replace(/\$\d+/g, '')
.trim()
setPrompt(cleanedTemplate)
setTimeout(() => {
if (textareaRef.current) {
textareaRef.current.focus()
textareaRef.current.setSelectionRange(cleanedTemplate.length, cleanedTemplate.length)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
} else {
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
const beforeCommand = commandMatch ? prompt.slice(0, commandMatch.index) : ''
const afterCommand = commandMatch ? prompt.slice(cursorPosition) : ''
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
}
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
const beforeCommand = commandMatch ? prompt.slice(0, commandMatch.index) : ''
const afterCommand = commandMatch ? prompt.slice(cursorPosition) : ''
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
textareaRef.current.scrollTop = textareaRef.current.scrollHeight
}
}, 0)
}, [prompt])
useEffect(() => {
@@ -501,7 +481,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (item.type === 'agent') {
const newPrompt = beforeMention + '@' + item.value + ' ' + afterMention
setPrompt(newPrompt)
setSelectedAgent(item.value)
setTimeout(() => {
if (textareaRef.current) {
@@ -520,12 +499,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
setMentionRange(null)
}
const handleAgentChange = (agentName: string) => {
setLocalMode(agentName)
setStoredAgent(sessionID, agentName)
const agent = agents.find(a => a.name === agentName)
const handleAgentChange = (agentId: string) => {
setLocalMode(agentId)
setStoredAgent(sessionID, agentId)
const agent = agents.find(a => a.id === agentId)
if (agent?.model) {
setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.modelID })
setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.id })
}
}
@@ -1063,15 +1042,9 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const appliedSessionModelRef = useRef<string | undefined>(undefined)
const client = useOpenCodeClient(opcodeUrl, directory)
const { data: providersData } = useQuery({
queryKey: ['opencode', 'providers', opcodeUrl, directory],
queryFn: () => getProviders(directory),
enabled: !!client,
staleTime: 30000,
})
const { data: providersData } = useProviders(directory)
const { model, modelString, setModel: setStoredModel, restoreSessionModel } = useModelSelection(opcodeUrl, directory)
const { model, modelString, setModel: setStoredModel, restoreSessionModel } = useModelSelection(directory)
const setStoreVariant = useModelStore((state) => state.setVariant)
const clearStoreVariant = useModelStore((state) => state.clearVariant)
@@ -1109,7 +1082,26 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const isMobile = useMobile()
const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions()
const hasPendingPermissionForSession = hasPermissionsForSession(sessionID)
const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory)
const { hasVariants, currentVariant, cycleVariant } = useVariants(directory)
const modelRef = useMemo<ModelRef | undefined>(
() => model
? { providerID: model.providerID, id: model.modelID, ...(currentVariant ? { variant: currentVariant } : {}) }
: undefined,
[model, currentVariant],
)
const { executeCommand } = useCommandHandler({
sessionID,
directory,
model: modelRef,
currentAgent: currentMode,
onShowSessionsDialog,
onShowModelsDialog: undefined,
onShowHelpDialog,
onToggleDetails,
onExportSession,
onUndo,
onRedo
})
const showStopButton = isSessionActive
const hideSecondaryButtons = isMobile && isSessionActive
const showMobileScrollButton = isMobile && showScrollButton
@@ -1310,7 +1302,6 @@ return (
) : (
<>
<AgentQuickSelect
opcodeUrl={opcodeUrl}
directory={directory}
currentAgent={currentMode}
onAgentChange={handleAgentChange}
@@ -1323,7 +1314,6 @@ return (
) : (
!hideSecondaryButtons && (
<ModelQuickSelect
opcodeUrl={opcodeUrl}
directory={directory}
>
<button
+13 -19
View File
@@ -1,28 +1,24 @@
import { memo, useEffect, useState } from 'react'
import type { components } from '@/api/opencode-types'
import type { SessionMessageAssistantRetry } from '@opencode-manager/shared/opencode'
import { RefreshCw, AlertTriangle } from 'lucide-react'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
type RetryPartType = components['schemas']['RetryPart']
interface RetryPartProps {
part: RetryPartType
retry: SessionMessageAssistantRetry
}
export const RetryPart = memo(function RetryPart({ part }: RetryPartProps) {
const sessionStatus = useSessionStatusForSession(part.sessionID)
const nextTimestamp = sessionStatus.type === 'retry' ? sessionStatus.next : 0
const initialCountdown = sessionStatus.type === 'retry' && nextTimestamp > 0
export const RetryPart = memo(function RetryPart({ retry }: RetryPartProps) {
const nextTimestamp = retry.at
const initialCountdown = nextTimestamp > 0
? Math.max(0, Math.ceil((nextTimestamp - Date.now()) / 1000))
: 0
const [countdown, setCountdown] = useState(initialCountdown)
useEffect(() => {
if (sessionStatus.type !== 'retry' || nextTimestamp === 0) {
if (nextTimestamp === 0) {
setCountdown(0)
return
}
const timer = setInterval(() => {
const remaining = Math.max(0, Math.ceil((nextTimestamp - Date.now()) / 1000))
setCountdown(remaining)
@@ -30,12 +26,10 @@ export const RetryPart = memo(function RetryPart({ part }: RetryPartProps) {
clearInterval(timer)
}
}, 1000)
return () => clearInterval(timer)
}, [sessionStatus.type, nextTimestamp])
const errorMessage = part.error?.data?.message || 'An error occurred'
}, [nextTimestamp])
return (
<div className="flex items-center gap-3 p-3 my-2 rounded-lg bg-amber-500/10 border border-amber-500/30">
<div className="flex-shrink-0">
@@ -47,7 +41,7 @@ export const RetryPart = memo(function RetryPart({ part }: RetryPartProps) {
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-amber-600 dark:text-amber-400">
Retry attempt {part.attempt}
Retry attempt {retry.attempt}
</span>
{countdown > 0 ? (
<span className="text-xs text-amber-500/80">
@@ -60,7 +54,7 @@ export const RetryPart = memo(function RetryPart({ part }: RetryPartProps) {
)}
</div>
<p className="text-xs text-muted-foreground truncate mt-0.5">
{errorMessage}
{retry.error.message}
</p>
</div>
</div>
@@ -1,103 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionTodoDisplay } from './SessionTodoDisplay'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import type { Todo } from './SessionTodoDisplay'
const activeTodos: Todo[] = [
{ id: '1', content: 'Implement mobile header fix', status: 'in_progress', priority: 'high' },
{ id: '2', content: 'Add regression tests', status: 'pending', priority: 'medium' },
{ id: '3', content: 'Verify completed item grouping', status: 'completed', priority: 'low' },
]
const allCompletedTodos: Todo[] = [
{ id: '1', content: 'Task one', status: 'completed', priority: 'high' },
{ id: '2', content: 'Task two', status: 'completed', priority: 'medium' },
]
describe('SessionTodoDisplay', () => {
beforeEach(() => {
useSessionTodos.setState({ todos: new Map() })
})
it('renders collapsed by default', () => {
useSessionTodos.getState().setTodos('session-1', activeTodos)
render(<SessionTodoDisplay sessionID="session-1" />)
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
expect(screen.queryByText('Implement mobile header fix')).not.toBeInTheDocument()
expect(screen.queryByText('Add regression tests')).not.toBeInTheDocument()
})
it('expands to show a small scrollable task preview when clicked', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
render(<SessionTodoDisplay sessionID="session-1" />)
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByText('Implement mobile header fix')).toBeInTheDocument()
expect(screen.getByText('Add regression tests')).toBeInTheDocument()
expect(screen.getByText('Verify completed item grouping')).toBeInTheDocument()
const expandedContainer = screen.getByTestId('todo-expanded-list')
expect(expandedContainer).toHaveClass('max-h-[80px]')
expect(expandedContainer).toHaveClass('sm:max-h-[160px]')
expect(expandedContainer).toHaveClass('overflow-y-auto')
})
it('collapses again when expanded header is clicked', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
render(<SessionTodoDisplay sessionID="session-1" />)
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByTestId('todo-expanded-list')).toBeInTheDocument()
const expandedHeader = screen.getByText('Tasks: 1/3 complete')
await user.click(expandedHeader)
expect(screen.queryByTestId('todo-expanded-list')).not.toBeInTheDocument()
})
it('does not render when all tasks are completed', () => {
useSessionTodos.getState().setTodos('session-1', allCompletedTodos)
const { container } = render(<SessionTodoDisplay sessionID="session-1" />)
expect(container.firstChild).toBeNull()
})
it('dismisses current todo signature and reappears when todo status changes', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
const { rerender } = render(<SessionTodoDisplay sessionID="session-1" />)
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
const dismissButton = screen.getByLabelText('Dismiss tasks')
await user.click(dismissButton)
expect(screen.queryByText('Tasks: 1/3 complete')).not.toBeInTheDocument()
const updatedTodos: Todo[] = [
{ id: '1', content: 'Implement mobile header fix', status: 'completed', priority: 'high' },
{ id: '2', content: 'Add regression tests', status: 'pending', priority: 'medium' },
{ id: '3', content: 'Verify completed item grouping', status: 'completed', priority: 'low' },
]
useSessionTodos.getState().setTodos('session-1', updatedTodos)
rerender(<SessionTodoDisplay sessionID="session-1" />)
expect(screen.getByText('Tasks: 2/3 complete')).toBeInTheDocument()
})
})
@@ -1,139 +0,0 @@
import { useState, useMemo, useEffect, useRef } from 'react'
import { ChevronDown, ChevronRight, X } from 'lucide-react'
import { TodoItem } from './TodoItem'
import { useSessionTodosForSession } from '@/stores/sessionTodosStore'
import type { components } from '@/api/opencode-types'
export type Todo = components['schemas']['Todo']
interface SessionTodoDisplayProps {
sessionID: string | undefined
}
const todoSignature = (todos: Todo[]) =>
todos.map((t) => `${t.id}:${t.status}`).join(',')
export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
const todos = useSessionTodosForSession(sessionID)
const [isCollapsed, setIsCollapsed] = useState(true)
const [isDismissed, setIsDismissed] = useState(false)
const dismissedSignatureRef = useRef<string>('')
const signature = useMemo(() => todoSignature(todos), [todos])
useEffect(() => {
if (isDismissed && signature !== dismissedSignatureRef.current) {
setIsDismissed(false)
}
}, [signature, isDismissed])
const handleDismiss = (e: React.MouseEvent) => {
e.stopPropagation()
dismissedSignatureRef.current = signature
setIsDismissed(true)
}
const stats = useMemo(() => {
const completed = todos.filter((t) => t.status === 'completed').length
const total = todos.length
const percentage = total > 0 ? Math.round((completed / total) * 100) : 0
return { completed, total, percentage }
}, [todos])
const { inProgress, pending, completedTodos } = useMemo(() => ({
inProgress: todos.filter((t) => t.status === 'in_progress'),
pending: todos.filter((t) => t.status === 'pending'),
completedTodos: todos.filter((t) => t.status === 'completed'),
}), [todos])
const hasMultipleGroups =
(inProgress.length > 0 ? 1 : 0) +
(pending.length > 0 ? 1 : 0) +
(completedTodos.length > 0 ? 1 : 0) >
1
const renderGroup = (label: string, items: typeof todos) => {
if (items.length === 0) return null
return (
<div className="mb-1 last:mb-0">
{hasMultipleGroups && (
<div className="text-[9px] font-medium text-muted-foreground mb-0.5 ml-4 uppercase tracking-wider opacity-70">
{label} ({items.length})
</div>
)}
<div>
{items.map((todo) => (
<div key={todo.id}>
<TodoItem todo={todo} compact />
</div>
))}
</div>
</div>
)
}
if (!sessionID || todos.length === 0 || stats.completed === stats.total || isDismissed) {
return null
}
if (isCollapsed) {
return (
<div
className="mb-2 px-3 py-2 bg-muted/50 rounded-lg cursor-pointer select-none"
onClick={() => setIsCollapsed(false)}
>
<div className="flex items-center gap-2">
<ChevronRight className="w-4 h-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">
Tasks: {stats.completed}/{stats.total} complete
</span>
<div className="flex-1 h-1.5 bg-secondary rounded-full overflow-hidden">
<div
className="h-full bg-green-500 transition-all duration-300"
style={{ width: `${stats.percentage}%` }}
/>
</div>
<button
onClick={handleDismiss}
className="ml-1 p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
aria-label="Dismiss tasks"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
</div>
)
}
return (
<div className="mb-2 rounded-lg overflow-hidden">
<div
className="flex items-center gap-2 px-3 py-2 bg-muted/50 cursor-pointer select-none"
onClick={() => setIsCollapsed(true)}
>
<ChevronDown className="w-4 h-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">
Tasks: {stats.completed}/{stats.total} complete
</span>
<div className="flex-1 h-1.5 bg-secondary rounded-full overflow-hidden">
<div
className="h-full bg-green-500 transition-all duration-300"
style={{ width: `${stats.percentage}%` }}
/>
</div>
<button
onClick={handleDismiss}
className="ml-1 p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
aria-label="Dismiss tasks"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
<div data-testid="todo-expanded-list" className="max-h-[80px] sm:max-h-[160px] overflow-y-auto p-1.5 sm:p-2 bg-muted/30">
{renderGroup('In Progress', inProgress)}
{renderGroup('Pending', pending)}
{renderGroup('Completed', completedTodos)}
</div>
</div>
)
}
@@ -0,0 +1,44 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { StepFileChanges } from './StepFileChanges'
describe('StepFileChanges', () => {
it('renders the file count and relative paths', () => {
render(
<StepFileChanges
files={['/workspace/repos/app/src/a.ts', '/workspace/repos/app/src/b.ts']}
snapshot="0123456789abcdef"
/>,
)
expect(screen.getByText('File Changes (2 files)')).toBeInTheDocument()
expect(screen.getByText('app/src/a.ts')).toBeInTheDocument()
expect(screen.getByText('app/src/b.ts')).toBeInTheDocument()
expect(screen.getByText('01234567')).toBeInTheDocument()
})
it('calls onFileClick with the original path', () => {
const onFileClick = vi.fn()
render(<StepFileChanges files={['/workspace/repos/app/src/a.ts']} onFileClick={onFileClick} />)
fireEvent.click(screen.getByText('app/src/a.ts'))
expect(onFileClick).toHaveBeenCalledWith('/workspace/repos/app/src/a.ts')
})
it('collapses long lists and expands on demand', () => {
const files = ['a.ts', 'b.ts', 'c.ts', 'd.ts', 'e.ts']
render(<StepFileChanges files={files} />)
expect(screen.queryByText('d.ts')).not.toBeInTheDocument()
fireEvent.click(screen.getByText('+2 more files'))
expect(screen.getByText('e.ts')).toBeInTheDocument()
expect(screen.getByText('Show less')).toBeInTheDocument()
})
it('renders nothing when there are no files', () => {
const { container } = render(<StepFileChanges files={[]} />)
expect(container).toBeEmptyDOMElement()
})
})
@@ -0,0 +1,68 @@
import { useState } from 'react'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { getRelativePath } from './FileToolRender'
interface StepFileChangesProps {
files: string[]
snapshot?: string
onFileClick?: (filePath: string) => void
}
const INITIAL_FILES_SHOWN = 3
function fileNoun(count: number): string {
return count === 1 ? 'file' : 'files'
}
export function StepFileChanges({ files, snapshot, onFileClick }: StepFileChangesProps) {
const [expanded, setExpanded] = useState(false)
if (files.length === 0) return null
const hasMoreFiles = files.length > INITIAL_FILES_SHOWN
const displayedFiles = expanded ? files : files.slice(0, INITIAL_FILES_SHOWN)
const hiddenCount = files.length - INITIAL_FILES_SHOWN
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
type="button"
onClick={() => hasMoreFiles && setExpanded(!expanded)}
className="w-full px-3 py-1.5 bg-card hover:bg-card-hover text-left flex items-center justify-between text-sm gap-2"
>
<span className="font-medium">File Changes ({files.length} {fileNoun(files.length)})</span>
<div className="flex items-center gap-2 flex-shrink-0">
{snapshot && <span className="text-muted-foreground text-xs font-mono">{snapshot.slice(0, 8)}</span>}
{hasMoreFiles && (
expanded ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />
)}
</div>
</button>
<div className="bg-card px-3 py-2 space-y-1">
{displayedFiles.map((file) => (
<button
key={file}
type="button"
title={file}
onClick={() => onFileClick?.(file)}
className="block max-w-full truncate text-left text-xs font-mono text-blue-600 dark:text-blue-400 hover:underline cursor-pointer"
>
{getRelativePath(file)}
</button>
))}
{hasMoreFiles && (
<button
type="button"
onClick={() => setExpanded(!expanded)}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 mt-1"
>
{expanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
{expanded ? 'Show less' : `+${hiddenCount} more ${fileNoun(hiddenCount)}`}
</button>
)}
</div>
</div>
)
}
+6 -9
View File
@@ -6,14 +6,11 @@ import rehypeRaw from 'rehype-raw'
import mermaid from 'mermaid'
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'
type TextPart = components['schemas']['TextPart']
interface TextPartProps {
part: TextPart
text: string
}
interface MermaidBlockProps {
@@ -184,12 +181,12 @@ function isMermaidBlockComplete(text: string): boolean {
return false
}
export function TextPart({ part }: TextPartProps) {
export function TextPart({ text }: TextPartProps) {
const mermaidComplete = React.useMemo(() => {
return part.text ? isMermaidBlockComplete(part.text) : false
}, [part.text])
return text ? isMermaidBlockComplete(text) : false
}, [text])
if (!part.text || part.text.trim() === '') {
if (!text || text.trim() === '') {
return null
}
@@ -263,7 +260,7 @@ export function TextPart({ part }: TextPartProps) {
}
}}
>
{part.text}
{text}
</ReactMarkdown>
</div>
)
@@ -1,37 +0,0 @@
import type { components } from '@/api/opencode-types'
import { CheckCircle2, Circle } from 'lucide-react'
export type Todo = components['schemas']['Todo']
interface TodoItemProps {
todo: Todo
compact?: boolean
}
export function TodoItem({ todo, compact = false }: TodoItemProps) {
const isCompleted = todo.status === 'completed'
const isInProgress = todo.status === 'in_progress'
return (
<div className={`flex items-center gap-1.5 ${compact ? 'py-0.5 text-xs' : 'py-1 text-sm'} pl-0.5`}>
{isCompleted ? (
<CheckCircle2 className={`${compact ? 'w-3 h-3' : 'w-3.5 h-3.5'} text-green-600 dark:text-green-400 flex-shrink-0`} />
) : isInProgress ? (
<span className={`${compact ? 'w-3 h-3' : 'w-3.5 h-3.5'} rounded-full border-2 border-yellow-500 border-t-transparent animate-spin flex-shrink-0`} />
) : (
<Circle className={`${compact ? 'w-3 h-3' : 'w-3.5 h-3.5'} text-muted-foreground flex-shrink-0`} />
)}
<span
className={`flex-1 min-w-0 truncate ${
isInProgress
? 'text-yellow-700 dark:text-yellow-300 font-medium'
: isCompleted
? 'text-muted-foreground line-through opacity-60'
: 'text-foreground'
}`}
>
{todo.content}
</span>
</div>
)
}
@@ -0,0 +1,101 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import type { PermissionRequest, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { ToolCallPart } from './ToolCallPart'
const mocks = vi.hoisted(() => ({
useSettings: vi.fn(),
useToolCallPermission: vi.fn(),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: mocks.useSettings,
}))
vi.mock('@/contexts/EventContext', () => ({
useToolCallPermission: mocks.useToolCallPermission,
}))
const renderWithProviders = (ui: React.ReactElement) => {
const queryClient = new QueryClient()
return render(
<QueryClientProvider client={queryClient}>
<MemoryRouter>{ui}</MemoryRouter>
</QueryClientProvider>,
)
}
const runningShell = (): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_1',
name: 'shell',
time: { created: 1, ran: 2 },
state: { status: 'running', input: { command: 'git status' }, metadata: {} },
})
const permissionFor = (source: PermissionRequest['source']): PermissionRequest => ({
id: 'permission_1',
sessionID: 'ses_1',
action: 'shell',
resources: ['git status'],
source,
})
describe('ToolCallPart permission indicator', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: true },
isLoading: false,
updateSettings: vi.fn(),
isUpdating: false,
})
mocks.useToolCallPermission.mockReturnValue(null)
})
it('shows the waiting permission state for a matching tool call', () => {
mocks.useToolCallPermission.mockReturnValue(
permissionFor({ type: 'tool', messageID: 'msg_1', id: 'call_1' }),
)
renderWithProviders(<ToolCallPart part={runningShell()} messageID="msg_1" />)
expect(mocks.useToolCallPermission).toHaveBeenCalledWith('call_1', 'msg_1')
expect(screen.getByText('awaiting permission')).toBeInTheDocument()
expect(screen.getByText('Waiting for permission...')).toBeInTheDocument()
})
it('does not show the waiting permission state without a pending permission', () => {
renderWithProviders(<ToolCallPart part={runningShell()} messageID="msg_1" />)
expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument()
expect(screen.queryByText('Waiting for permission...')).not.toBeInTheDocument()
expect(screen.getByText('running')).toBeInTheDocument()
})
it('ignores a permission whose source belongs to another tool call or message', () => {
mocks.useToolCallPermission.mockReturnValue(null)
renderWithProviders(<ToolCallPart part={runningShell()} messageID="msg_1" />)
expect(mocks.useToolCallPermission).toHaveBeenCalledWith('call_1', 'msg_1')
expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument()
})
it('does not show the waiting permission state while the tool call is still streaming', () => {
mocks.useToolCallPermission.mockReturnValue(
permissionFor({ type: 'tool', messageID: 'msg_1', id: 'call_1' }),
)
renderWithProviders(
<ToolCallPart
part={{ ...runningShell(), state: { status: 'streaming', input: '' } }}
messageID="msg_1"
/>,
)
expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument()
})
})
+108 -143
View File
@@ -1,18 +1,16 @@
import { useState, useRef, useEffect, useMemo, memo } from 'react'
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import type { components } from '@/api/opencode-types'
import { toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { useSettings } from '@/hooks/useSettings'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { usePermissions, useQuestions } from '@/contexts/EventContext'
import { useToolCallPermission } from '@/contexts/EventContext'
import { detectFileReferences } from '@/lib/fileReferences'
import { ExternalLink, Loader2, Shield } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { CopyButton } from '@/components/ui/copy-button'
import { getToolSpecificRender } from './FileToolRender'
type ToolPart = components['schemas']['ToolPart']
const DISPLAY_LIMIT = 30_000
const DISPLAY_HEAD_LENGTH = 20_000
const DISPLAY_TAIL_LENGTH = 10_000
@@ -41,18 +39,30 @@ function BoundedPre({ content, className }: { content: string; className: string
}
interface ToolCallPartProps {
part: ToolPart
part: SessionMessageAssistantTool
messageID?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
simpleChatMode?: boolean
}
function getTaskSessionId(part: ToolPart): string | undefined {
let sessionId = part.metadata?.sessionId as string | undefined
if (!sessionId && part.state.status !== 'pending' && 'metadata' in part.state) {
sessionId = part.state.metadata?.sessionId as string | undefined
}
return sessionId
function toolInput(part: SessionMessageAssistantTool): Record<string, unknown> | undefined {
if (part.state.status === 'streaming') return undefined
return part.state.input
}
function toolMetadata(part: SessionMessageAssistantTool): Record<string, unknown> {
if (part.state.status === 'streaming') return {}
return part.state.metadata ?? {}
}
function toolOutputText(part: SessionMessageAssistantTool): string {
if (part.state.status === 'streaming') return ''
return toolContentText(part.state.status === 'running' ? undefined : part.state.content)
}
function getSubagentSessionId(part: SessionMessageAssistantTool): string | undefined {
const sessionID = toolMetadata(part).sessionID
return typeof sessionID === 'string' ? sessionID : undefined
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
@@ -95,41 +105,37 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
}
export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFileClick, onChildSessionClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const taskSessionId = part.tool === 'task' ? getTaskSessionId(part) : undefined
const taskSessionStatus = useSessionStatusForSession(taskSessionId)
const { getForCallID: getPermissionForCallID } = usePermissions()
const { getForCallID: getQuestionForCallID } = useQuestions()
const isSubagent = part.name === 'subagent'
const subagentSessionId = isSubagent ? getSubagentSessionId(part) : undefined
const subagentSessionStatus = useSessionStatusForSession(subagentSessionId)
const pendingPermission = useToolCallPermission(part.id, messageID)
const isWaitingPermission = part.state.status === 'running' && pendingPermission !== null
const outputRef = useRef<HTMLDivElement>(null)
const rawCommand = part.tool === 'bash' && typeof part.state.input?.command === 'string'
? part.state.input.command
const input = toolInput(part)
const rawCommand = part.name === 'shell' && typeof input?.command === 'string'
? input.command
: undefined
const displayCommand = useMemo(
() => (rawCommand === undefined ? undefined : unwrapSandboxExecCommand(rawCommand)),
[rawCommand]
)
const isSandboxedCommand = rawCommand !== undefined && (
displayCommand !== rawCommand ||
(part.state.status === 'completed' && (part.state.metadata as Record<string, unknown> | undefined)?.sandbox === true)
)
const isSandboxedCommand =
part.state.status === 'completed' &&
(toolMetadata(part).sandbox === true ||
(rawCommand !== undefined && displayCommand !== rawCommand))
const isUserBashCommand = part.state.status === 'completed' &&
typeof displayCommand === 'string' &&
userBashCommands.has(displayCommand)
const isTodoTool = part.tool === 'todowrite' || part.tool === 'todoread'
const [expanded, setExpanded] = useState(isUserBashCommand || isTodoTool || (preferences?.expandToolCalls ?? false))
const pendingPermission = getPermissionForCallID(part.callID, part.sessionID)
const isWaitingPermission = part.state.status === 'running' && !!pendingPermission
const pendingQuestion = getQuestionForCallID(part.callID, part.sessionID)
const isWaitingQuestion = part.state.status === 'running' && !!pendingQuestion
const [expanded, setExpanded] = useState(isUserBashCommand || (preferences?.expandToolCalls ?? false))
useEffect(() => {
if (part.tool === 'bash' && expanded && outputRef.current) {
if (part.name === 'shell' && expanded && outputRef.current) {
outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}
}, [expanded, part.tool])
}, [expanded, part.name])
const getStatusColor = () => {
switch (part.state.status) {
@@ -139,7 +145,6 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
return 'text-red-600 dark:text-red-400'
case 'running':
if (isWaitingPermission) return 'text-orange-600 dark:text-orange-400'
if (isWaitingQuestion) return 'text-blue-600 dark:text-blue-400'
return 'text-yellow-600 dark:text-yellow-400'
default:
return 'text-muted-foreground'
@@ -154,7 +159,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
return <span>✗</span>
case 'running':
return <Loader2 className="w-3.5 h-3.5 animate-spin" />
case 'pending':
case 'streaming':
return <span className="inline-block w-2 h-2 rounded-full bg-current animate-pulse" />
default:
return <span>○</span>
@@ -162,36 +167,32 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
}
const getPreviewText = () => {
if (part.state.status === 'pending') return null
const input = part.state.input as Record<string, unknown>
if (!input) return null
switch (part.tool) {
switch (part.name) {
case 'read':
case 'write':
case 'edit':
return (input.filePath as string) || null
case 'bash':
case 'patch':
return (input.path as string) || null
case 'shell':
return displayCommand || null
case 'glob':
return (input.pattern as string) || null
case 'grep':
return (input.pattern as string) || null
case 'list':
return (input.path as string) || '.'
case 'task':
case 'subagent':
return (input.description as string) || null
case 'todowrite':
case 'todoread':
return null
case 'webfetch':
return (input.url as string) || null
case 'websearch':
return (input.query as string) || null
default:
return null
}
}
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
const isFileTool = ['read', 'write', 'edit', 'patch'].includes(part.name)
const sandboxIndicator = isSandboxedCommand ? (
<Badge
variant="outline"
@@ -203,19 +204,16 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
</Badge>
) : null
if (part.tool === 'task') {
const sessionId = taskSessionId
const description = previewText || 'Sub-agent task'
if (isSubagent) {
const status = part.state.status
const isPending = status === 'pending'
const isRunning = status === 'running' && taskSessionStatus.type !== 'idle'
const isCompleted = status === 'completed' || (status === 'running' && !!sessionId && taskSessionStatus.type === 'idle')
const isRunning = status === 'running' && subagentSessionStatus.type !== 'idle'
const isCompleted = status === 'completed' || (status === 'running' && !!subagentSessionId && subagentSessionStatus.type === 'idle')
const isError = status === 'error'
const description = previewText || 'Sub-agent task'
const content = (
<div className="flex items-center gap-2 min-w-0">
{isPending && (
{status === 'streaming' && (
<div className="flex gap-1">
<span className="w-2 h-2 rounded-full bg-muted-foreground" />
<span className="w-2 h-2 rounded-full bg-muted-foreground" />
@@ -233,14 +231,14 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
{isError && <span className="text-red-600 text-sm font-medium">✗</span>}
<span className="font-medium text-foreground truncate">{description}</span>
<span className="text-[11px] font-medium text-orange-600 dark:text-orange-400 shrink-0">sub-agent</span>
{sessionId && <ExternalLink className="w-3 h-3 shrink-0 text-blue-600 dark:text-blue-400" />}
{subagentSessionId && <ExternalLink className="w-3 h-3 shrink-0 text-blue-600 dark:text-blue-400" />}
</div>
)
if (sessionId) {
if (subagentSessionId) {
return (
<button
onClick={() => onChildSessionClick?.(sessionId)}
onClick={() => onChildSessionClick?.(subagentSessionId)}
className="my-1 w-full rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-1.5 text-left text-xs text-muted-foreground hover:bg-blue-500/10 hover:border-blue-500/30 transition-all duration-200 shadow-sm shadow-blue-500/5"
title="View subagent session"
>
@@ -256,18 +254,6 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
)
}
if (isTodoTool) {
if (part.state.status === 'error') {
return (
<div className="my-2 text-sm text-red-600 dark:text-red-400">
Error updating tasks: {part.state.error}
</div>
)
}
return null
}
const toolSpecificRender = getToolSpecificRender(part, onFileClick)
if (toolSpecificRender) {
return toolSpecificRender
@@ -275,7 +261,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
if (isUserBashCommand) {
const command = displayCommand ?? ''
const output = part.state.status === 'completed' ? part.state.output : ''
const output = toolOutputText(part)
const ran = part.state.status === 'streaming' ? undefined : part.state.status === 'running' ? undefined : part.time.ran
const completed = part.state.status === 'streaming' ? undefined : part.state.status === 'running' ? undefined : part.time.completed
return (
<div className="my-2">
<div className="flex items-center gap-2 text-sm mb-2">
@@ -283,15 +271,15 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
<span className="font-medium">$</span>
<span className="text-foreground">{command}</span>
{sandboxIndicator}
{part.state.status === 'completed' && part.state.time && (
{ran !== undefined && completed !== undefined && (
<span className="text-muted-foreground text-xs ml-auto">
{((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
{((completed - ran) / 1000).toFixed(2)}s
</span>
)}
</div>
<div className="relative">
<BoundedPre content={output ?? ''} className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap" />
<CopyButton content={output ?? ''} title="Copy output" className="absolute top-2 right-2" />
<BoundedPre content={output} className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap" />
<CopyButton content={output} title="Copy output" className="absolute top-2 right-2" />
</div>
</div>
)
@@ -301,9 +289,8 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
switch (part.state.status) {
case 'running':
if (isWaitingPermission) return 'border-orange-500/50 shadow-sm shadow-orange-500/20'
if (isWaitingQuestion) return 'border-blue-500/50 shadow-sm shadow-blue-500/20'
return 'border-yellow-500/50 shadow-sm shadow-yellow-500/10'
case 'pending':
case 'streaming':
return 'border-blue-500/30'
case 'error':
return 'border-red-500/30'
@@ -314,6 +301,8 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
}
}
const output = toolOutputText(part)
return (
<div ref={outputRef} className={`border rounded-lg overflow-hidden my-2 transition-all ${getBorderStyle()}`}>
<button
@@ -321,7 +310,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
className="w-full px-4 py-2 bg-card hover:bg-card-hover text-left flex items-center gap-2 text-sm min-w-0"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.tool}</span>
<span className="font-medium">{part.name}</span>
{sandboxIndicator}
{previewText && isFileTool ? (
@@ -341,28 +330,12 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
) : null}
{part.tool === 'task' && (() => {
const sessionId = getTaskSessionId(part)
return sessionId ? (
<span
onClick={(e) => {
e.stopPropagation()
onChildSessionClick?.(sessionId)
}}
className="text-blue-600 dark:text-blue-400 text-xs hover:text-blue-700 dark:hover:text-blue-300 cursor-pointer underline decoration-dotted flex items-center gap-1"
title="View subagent session"
>
<ExternalLink className="w-3 h-3" />
View Session
</span>
) : null
})()}
<span className="text-muted-foreground text-xs ml-auto">({isWaitingPermission ? 'awaiting permission' : isWaitingQuestion ? 'awaiting answer' : part.state.status})</span>
<span className="text-muted-foreground text-xs ml-auto">{isWaitingPermission ? 'awaiting permission' : part.state.status}</span>
</button>
{expanded && (
<div className="bg-card space-y-2 p-3">
{part.state.status === 'pending' && (
{part.state.status === 'streaming' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<div className="flex gap-0.5">
<span className="w-1.5 h-1.5 rounded-full bg-blue-500 animate-bounce" style={{ animationDelay: '0ms' }} />
@@ -374,47 +347,39 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
)}
{part.state.status === 'running' && (
<>
{part.tool === 'bash' ? (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
<div className="text-muted-foreground">Command:</div>
<CopyButton
content={displayCommand ?? ''}
title="Copy command"
/>
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
<span className="text-green-600 dark:text-green-400">$</span> {displayCommand ?? ''}
</div>
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400'}`}>
<Loader2 className="w-3 h-3 animate-spin" />
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
</div>
part.name === 'shell' ? (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
<div className="text-muted-foreground">Command:</div>
<CopyButton content={displayCommand ?? ''} title="Copy command" />
</div>
) : (
<div className="text-sm">
<div className="text-muted-foreground mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400'}`}>
<Loader2 className="w-3 h-3 animate-spin" />
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
<span className="text-green-600 dark:text-green-400">$</span> {displayCommand ?? ''}
</div>
)}
</>
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400'}`}>
<Loader2 className="w-3 h-3 animate-spin" />
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
</div>
</div>
) : (
<div className="text-sm">
<div className="text-muted-foreground mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400'}`}>
<Loader2 className="w-3 h-3 animate-spin" />
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
</div>
</div>
)
)}
{part.state.status === 'completed' && (
<>
{part.tool === 'bash' ? (
{part.name === 'shell' ? (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
<div className="text-muted-foreground">Command:</div>
<CopyButton
content={displayCommand ?? ''}
title="Copy command"
/>
<CopyButton content={displayCommand ?? ''} title="Copy command" />
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
<span className="text-green-600 dark:text-green-400">$</span> {displayCommand ?? ''}
@@ -426,21 +391,21 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
<div className="text-sm">
<div className="text-muted-foreground mb-1">Output:</div>
<div className="relative">
<BoundedPre
content={part.state.status === 'completed' ? part.state.output ?? '' : ''}
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all"
/>
{part.state.status === 'completed' && part.state.output && (
<CopyButton content={part.state.output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
)}
{output && (
<div className="text-sm">
<div className="text-muted-foreground mb-1">Output:</div>
<div className="relative">
<BoundedPre
content={output}
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all"
/>
<CopyButton content={output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
</div>
</div>
</div>
{part.state.time && (
)}
{part.time.ran !== undefined && part.time.completed !== undefined && (
<div className="text-xs text-muted-foreground">
Duration: {((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
Duration: {((part.time.completed - part.time.ran) / 1000).toFixed(2)}s
</div>
)}
</>
@@ -450,7 +415,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onCh
<div className="text-sm">
<div className="text-red-600 dark:text-red-400 mb-1">Error:</div>
<BoundedPre
content={part.state.error ?? ''}
content={part.state.error.message}
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words text-red-600 dark:text-red-300"
/>
</div>
@@ -4,7 +4,6 @@ import { useUndoMessage } from '@/hooks/useUndoMessage'
import { useMobile } from '@/hooks/useMobile'
interface UserMessageActionButtonsProps {
opcodeUrl: string
sessionId: string
directory?: string
userMessageId: string
@@ -13,7 +12,6 @@ interface UserMessageActionButtonsProps {
}
export const UserMessageActionButtons = memo(function UserMessageActionButtons({
opcodeUrl,
sessionId,
directory,
userMessageId,
@@ -22,7 +20,6 @@ export const UserMessageActionButtons = memo(function UserMessageActionButtons({
}: UserMessageActionButtonsProps) {
const isMobile = useMobile()
const undoMessage = useUndoMessage({
opcodeUrl,
sessionId,
directory,
onSuccess: onUndo