import { memo, useCallback, useMemo, useState } from 'react'
import { Pencil, Loader2 } from 'lucide-react'
import { assistantText, formatOpenCodeModelRef } 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 { useSettings } from '@/hooks/useSettings'
import { CopyButton } from '@/components/ui/copy-button'
import { TTSButton } from '@/components/ui/tts-button'
import { backgroundShellID, collectBackgroundParts, type ShellNoticeOutcome } from '@/lib/backgroundWork'
import { readShowArtifactCall } from '@/lib/artifactTool'
import { groupExplorationParts, type AssistantContentItem } from '@/lib/explorationGroups'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { ExplorationGroup } from './ExplorationGroup'
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 ''
}
}
function isSubagentTool(
part: SessionMessageAssistant['content'][number],
): part is SessionMessageAssistantTool {
return part.type === 'tool' && part.name === 'subagent'
}
function isArtifactTool(
part: SessionMessageAssistant['content'][number],
): part is SessionMessageAssistantTool {
return part.type === 'tool' && readShowArtifactCall(part) !== undefined
}
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) || isArtifactTool(part)
return false
})
case 'synthetic':
case 'system': {
const notice = sessionNoticeContent(message)
return notice.completion !== undefined || notice.text.trim().length > 0
}
case 'shell':
case 'skill':
case 'compaction':
case 'agent-switched':
case 'model-switched':
case 'location-switched':
return true
default:
return false
}
}
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 (
{files.map((file, index) => (
@
{attachmentLabel(file)}
))}
{agents.map((agent, index) => (
agent: {agent.name}
))}
{skills.map((skill, index) => (
skill: {skill.name}
))}
)
}
function MessageDivider({ label }: { label: string }) {
return (
{label}
)
}
type SessionNoticeMessage = Extract
interface SessionNoticeContent {
text: string
completion?: {
heading: string
state?: string
childID?: string
}
}
function noticeMetadataString(message: SessionNoticeMessage, key: string): string | undefined {
const value = message.metadata?.[key]
return typeof value === 'string' ? value : undefined
}
function sessionNoticeContent(message: SessionNoticeMessage): SessionNoticeContent {
const source = noticeMetadataString(message, 'source')
const text = message.type === 'system'
? message.description ?? 'Instructions updated'
: message.description ?? (source === 'shell' || source === 'subagent' ? '' : message.text)
if (source !== 'shell' && source !== 'subagent') return { text }
const state = noticeMetadataString(message, 'state')
const agent = noticeMetadataString(message, 'agent')
const actor = source === 'shell' ? 'Shell' : agent ? agent.charAt(0).toUpperCase() + agent.slice(1) : 'Subagent'
const status = state === 'error' ? 'failed' : state === 'completed' || state === undefined ? 'finished' : state
return {
text: source === 'shell' ? text.replace(/\s+/g, ' ').trim() : text,
completion: {
heading: `${state === 'completed' ? '↳' : '!'} ${actor} ${status}`,
state,
childID: source === 'subagent' ? noticeMetadataString(message, 'childID') : undefined,
},
}
}
function SessionNotice({
message,
onChildSessionClick,
}: {
message: SessionNoticeMessage
onChildSessionClick?: (sessionId: string) => void
}) {
const { text, completion } = sessionNoticeContent(message)
if (!completion) {
return ◈ {text}
}
const tone = completion.state === 'error'
? 'text-destructive'
: completion.state === 'cancelled'
? 'text-warning'
: 'text-info'
const content = (
<>
{completion.heading}
{text && · {text}}
>
)
const childID = completion.childID
if (childID && onChildSessionClick) {
return (
)
}
return {content}
}
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 (
$
{message.command}
{statusLabel}
{output && (
)}
)
}
function CompactionBanner({ message }: { message: SessionMessageCompaction }) {
if (message.status === 'running') {
return (
Compacting session...
)
}
if (message.status === 'failed') {
return (
Compaction failed: {message.error.message}
)
}
return (
Session compacted
{message.summary &&
{message.summary}
}
)
}
function QueuedPromptRow({ item }: { item: SessionInboxUser }) {
return (
You
{new Date(item.time.created).toLocaleTimeString()}
{item.delivery === 'queue' ? 'QUEUED' : 'STEERING'}
{}} isEditable={false} />
)
}
interface MessageRowProps {
message: SessionMessageInfo
nextAssistantMessageId: string | undefined
isLastUserMessage: boolean
isSessionBusy: boolean
onUndoMessage?: (restoredPrompt: string) => void
editingUserMessageId: string | null
handleStartEditUserMessage: (userMessageId: string, assistantMessageId: string) => void
handleCancelEdit: () => void
sessionID: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
model?: string
simpleChatMode: boolean
showReasoning: boolean
groupToolCalls: boolean
shellOutcomes: ReadonlyMap
}
const MessageRow = memo(function MessageRow({
message,
nextAssistantMessageId,
isLastUserMessage,
isSessionBusy,
onUndoMessage,
editingUserMessageId,
handleStartEditUserMessage,
handleCancelEdit,
sessionID,
directory,
repoFullPath,
repoLocalPath,
onFileClick,
onChildSessionClick,
onOpenWalkthrough,
model,
simpleChatMode,
showReasoning,
groupToolCalls,
shellOutcomes,
}: MessageRowProps) {
const messageTextContent = getMessageText(message)
const shellOutcomeFor = (part: SessionMessageAssistant['content'][number]) =>
part.type === 'tool' ? shellOutcomes.get(backgroundShellID(part) ?? '') : undefined
const streaming = message.type === 'assistant' && message.time.completed === undefined
const isEditingThisMessage = editingUserMessageId === message.id
const canEditUserMessage = isLastUserMessage && !isSessionBusy
const canUndoUserMessage = isLastUserMessage && !isSessionBusy && onUndoMessage
if (message.type === 'user') {
if (!hasRenderableContent(message, simpleChatMode, showReasoning)) return null
return (
You
{new Date(message.time.created).toLocaleTimeString()}
{canEditUserMessage && nextAssistantMessageId && (
)}
{canUndoUserMessage && (
)}
{isEditingThisMessage && nextAssistantMessageId ? (
) : simpleChatMode ? (
{}}
isEditable={false}
/>
) : (
handleStartEditUserMessage(message.id, nextAssistantMessageId ?? '')}
isEditable={false}
/>
)}
)
}
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 (
{message.content.filter(isSubagentTool).map((part, partIndex) => (
))}
)
}
const contentItems: AssistantContentItem[] = groupToolCalls && !simpleChatMode
? groupExplorationParts(message.content, showReasoning)
: message.content.map((part) => ({ type: 'part', part }))
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 (
{message.model.id}
{new Date(message.time.created).toLocaleTimeString()}
{contentItems.map((item, itemIndex) => (
{item.type === 'exploration' ? (
) : (
)}
))}
{!simpleChatMode && message.snapshot?.files && (
)}
{message.retry &&
}
{message.error &&
}
{!(isFree) && ${(message.cost ?? 0).toFixed(4)} • {totalTokens} tokens}
{messageTextContent && }
)
}
if (message.type === 'shell') {
return
}
if (message.type === 'compaction') {
return
}
if (message.type === 'agent-switched') {
return
}
if (message.type === 'model-switched') {
return
}
if (message.type === 'location-switched') {
return
}
if (message.type === 'skill') {
return (
Skill loaded: {message.name}
)
}
if (message.type === 'synthetic' || message.type === 'system') {
return
}
return null
})
interface MessageThreadProps {
sessionID: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
messages: SessionMessageInfo[]
pending: SessionInboxInfo[]
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
onUndoMessage?: (restoredPrompt: string) => void
model?: string
isSessionBusy?: boolean
}
export const MessageThread = memo(function MessageThread({
sessionID,
directory,
repoFullPath,
repoLocalPath,
messages,
pending,
onFileClick,
onChildSessionClick,
onOpenWalkthrough,
onUndoMessage,
model,
isSessionBusy = false,
}: MessageThreadProps) {
const [editingUserMessageId, setEditingUserMessageId] = useState(null)
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
const groupToolCalls = preferences?.groupToolCalls ?? true
const lastUserMessageId = useMemo(() => findLastUserMessageId(messages), [messages])
const shellOutcomesKey = useMemo(
() => [...collectBackgroundParts(messages).shellNotices].map(([id, outcome]) => `${id}=${outcome}`).join(','),
[messages],
)
const shellOutcomes = useMemo(
() => new Map(shellOutcomesKey ? shellOutcomesKey.split(',').map((entry) => entry.split('=') as [string, ShellNoticeOutcome]) : []),
[shellOutcomesKey],
)
const nextAssistantIdByMessageId = useMemo(() => {
const map = new Map()
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 handleStartEditUserMessage = useCallback((userMessageId: string) => {
setEditingUserMessageId(userMessageId)
}, [])
const handleCancelEdit = useCallback(() => {
setEditingUserMessageId(null)
}, [])
if (messages.length === 0 && pending.length === 0) {
return (
No messages yet. Start a conversation below.
)
}
return (
{messages.map((message) => (
))}
{pending.map((item) => (
item.type === 'user'
?
: null
))}
)
})