studio / src /components /ChatView.jsx
cheumk's picture
Upload 32 files
4e039c5 verified
Raw History Blame Contribute Delete
11.8 kB
import { useEffect, useRef, useState } from 'react'
import {
Menu, Send, Square, Wrench, Copy, Trash2, RotateCcw, Brain, Loader2, Check, PanelLeftOpen, Plus,
} from 'lucide-react'
import { useStore, useActiveConversation, useActiveProject } from '../store/useStore'
import Markdown from './Markdown'
function CopyBtn({ text }) {
const [ok, setOk] = useState(false)
return (
<button
type="button"
title="複製"
className="p-1 rounded hover:bg-field text-muted"
onClick={async () => {
try { await navigator.clipboard.writeText(text); setOk(true); setTimeout(() => setOk(false), 1200) } catch { /* ignore */ }
}}
>
{ok ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
</button>
)
}
function ToolCallBlock({ call, result }) {
let args = call.function?.arguments || ''
try { args = JSON.stringify(JSON.parse(args), null, 2) } catch { /* 串流中可能還不完整 */ }
const pending = !result || result.pending
return (
<details className="mt-2 rounded-lg border border-edge bg-app text-sm group">
<summary className="cursor-pointer select-none px-3 py-2 flex items-center gap-2 text-amber-500">
{pending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Wrench className="w-3.5 h-3.5" />}
<span className="font-medium">{call.function?.name || '…'}</span>
<span className="text-xs text-muted truncate">
{pending ? '執行中…' : String(result.content).slice(0, 60).replace(/\s+/g, ' ')}
</span>
</summary>
<div className="px-3 pb-3 space-y-2">
<div>
<div className="text-[11px] text-muted mb-1">參數</div>
<pre className="text-xs whitespace-pre-wrap break-words bg-field rounded p-2">{args || '{}'}</pre>
</div>
{result && !result.pending && (
<div>
<div className="text-[11px] text-muted mb-1 flex items-center justify-between">結果 <CopyBtn text={String(result.content)} /></div>
<pre className="text-xs whitespace-pre-wrap break-words bg-field rounded p-2 max-h-80 overflow-y-auto">{String(result.content)}</pre>
</div>
)}
</div>
</details>
)
}
function AssistantMessage({ msg, results, onDelete, agentIcon }) {
const isError = msg.error
const isInfo = msg.info
return (
<div className="group flex gap-3">
<div className="w-8 h-8 shrink-0 rounded-full bg-field flex items-center justify-center text-base">{agentIcon || '🤖'}</div>
<div className="min-w-0 flex-1">
{msg.reasoning && (
<details className="mb-2 text-sm" open={msg.streaming && !msg.content}>
<summary className="cursor-pointer select-none text-muted flex items-center gap-1.5">
<Brain className="w-3.5 h-3.5" /> 推理過程
</summary>
<div className="mt-1 pl-3 border-l-2 border-edge text-muted whitespace-pre-wrap text-xs leading-relaxed">{msg.reasoning}</div>
</details>
)}
{(msg.content || (msg.streaming && !msg.tool_calls?.length && !msg.reasoning)) && (
<div
className={`rounded-2xl px-4 py-3 ${isError ? 'bg-red-900/40 text-red-300 border border-red-900' : isInfo ? 'bg-field text-muted text-sm' : 'bg-panel border border-edge'} ${msg.streaming ? 'cursor-blink' : ''}`}
>
{msg.content ? <Markdown text={msg.content} /> : <span className="text-muted text-sm">思考中</span>}
</div>
)}
{(msg.tool_calls || []).map((c, i) => <ToolCallBlock key={c.id || i} call={c} result={results[c.id]} />)}
{!msg.streaming && (
<div className="flex items-center gap-1 mt-1 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition">
{msg.content && <CopyBtn text={msg.content} />}
<button type="button" title="刪除這則" className="p-1 rounded hover:bg-field text-muted" onClick={onDelete}>
<Trash2 className="w-3.5 h-3.5" />
</button>
{msg.model && <span className="text-[11px] text-muted ml-1 truncate">{msg.model}</span>}
</div>
)}
</div>
</div>
)
}
export default function ChatView({ onOpenSidebar, desktopCollapsed, onExpandDesktop }) {
const conv = useActiveConversation()
const project = useActiveProject()
const agents = useStore((s) => s.agents)
const providers = useStore((s) => s.providers)
const running = useStore((s) => (conv ? s.running[conv.id] : 0))
const { send, stop, regenerate, deleteMessage, createConversation } = useStore.getState()
const [input, setInput] = useState('')
const scrollRef = useRef(null)
const stickRef = useRef(true)
const taRef = useRef(null)
const agent = agents.find((a) => a.id === conv?.agentId)
const provider = providers.find((p) => p.id === conv?.providerId)
// 使用者沒往上捲時自動捲到底
useEffect(() => {
const el = scrollRef.current
if (el && stickRef.current) el.scrollTop = el.scrollHeight
}, [conv?.messages])
useEffect(() => {
const ta = taRef.current
if (!ta) return
ta.style.height = 'auto'
ta.style.height = `${Math.min(ta.scrollHeight, 220)}px`
}, [input])
const submit = async () => {
const text = input.trim()
if (!text || running) return
let id = conv?.id
if (!id) id = createConversation()
setInput('')
stickRef.current = true
await useStore.getState().send(id, text)
}
const results = {}
;(conv?.messages || []).forEach((m) => { if (m.role === 'tool') results[m.tool_call_id] = m })
const lastIsAssistant = conv?.messages?.length && conv.messages[conv.messages.length - 1].role !== 'user'
return (
<div className="flex flex-col h-full min-w-0 flex-1">
{/* 頂列:只有開關側邊欄與標題,所有設定都在側邊欄 */}
<div className="h-12 shrink-0 flex items-center gap-2 px-3 border-b border-edge bg-panel">
<button type="button" className="md:hidden p-2 -ml-1 rounded-lg hover:bg-field" onClick={() => onOpenSidebar()} aria-label="開啟側邊欄">
<Menu className="w-5 h-5" />
</button>
{desktopCollapsed && (
<button type="button" className="hidden md:inline-flex p-2 -ml-1 rounded-lg hover:bg-field" onClick={onExpandDesktop} title="展開側邊欄">
<PanelLeftOpen className="w-5 h-5" />
</button>
)}
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold truncate">{conv?.title || '新對話'}</div>
<div className="text-[11px] text-muted truncate">
{project?.name} · {agent ? `${agent.icon} ${agent.name}` : '未選 Agent'} · {provider ? `${provider.name} / ${conv?.model || '未選模型'}` : '未選供應商'}
</div>
</div>
<button type="button" className="md:hidden p-2 rounded-lg hover:bg-field" onClick={() => onOpenSidebar('conversation')} title="對話設定">
<span className="text-lg leading-none">{agent?.icon || '🤖'}</span>
</button>
</div>
<div
ref={scrollRef}
onScroll={(e) => {
const el = e.currentTarget
stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80
}}
className="flex-1 overflow-y-auto"
>
<div className="max-w-3xl mx-auto px-3 md:px-6 py-6 space-y-5">
{(!conv || conv.messages.length === 0) && (
<div className="text-center text-muted py-16 space-y-3">
<div className="text-5xl">{agent?.icon || '💬'}</div>
<div className="text-lg text-ink font-semibold">{agent?.name || '開始新對話'}</div>
<p className="text-sm">{agent?.description || '輸入訊息開始'}</p>
<p className="text-xs">
專案「{project?.name}」· 可用工具 {agent?.tools?.length || 0} 個
</p>
{!conv && (
<button type="button" onClick={() => createConversation()} className="inline-flex items-center gap-1.5 text-sm px-3 py-2 rounded-lg bg-field hover:bg-edge text-ink">
<Plus className="w-4 h-4" /> 新對話
</button>
)}
</div>
)}
{(conv?.messages || []).map((m) => {
if (m.role === 'tool') return null // 結果併入對應的工具呼叫區塊顯示
if (m.role === 'user') {
return (
<div key={m.id} className="group flex justify-end">
<div className="max-w-[85%]">
<div className="bg-purple-600 text-white rounded-2xl px-4 py-3 whitespace-pre-wrap break-words">{m.content}</div>
<div className="flex justify-end gap-1 mt-1 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition">
<CopyBtn text={m.content} />
{!running && (
<button type="button" title="刪除這則" className="p-1 rounded hover:bg-field text-muted" onClick={() => deleteMessage(conv.id, m.id)}>
<Trash2 className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
</div>
)
}
return (
<AssistantMessage
key={m.id}
msg={m}
results={results}
agentIcon={agents.find((a) => a.id === m.agentId)?.icon || agent?.icon}
onDelete={() => !running && deleteMessage(conv.id, m.id)}
/>
)
})}
{running > 0 && (
<div className="flex items-center gap-2 text-xs text-muted pl-11">
<Loader2 className="w-3.5 h-3.5 animate-spin" /> 第 {running} 步執行中(不設逾時,可隨時停止)
</div>
)}
{!running && lastIsAssistant && (
<div className="pl-11">
<button type="button" onClick={() => regenerate(conv.id)} className="inline-flex items-center gap-1.5 text-xs text-muted hover:text-ink">
<RotateCcw className="w-3.5 h-3.5" /> 重新生成
</button>
</div>
)}
</div>
</div>
<div className="shrink-0 border-t border-edge bg-panel px-3 md:px-6 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<div className="max-w-3xl mx-auto flex items-end gap-2">
<textarea
ref={taRef}
rows={1}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault()
submit()
}
}}
placeholder={`傳訊息給 ${agent?.name || 'Agent'}…`}
className="flex-1 resize-none bg-field border border-edge rounded-2xl px-4 py-3 text-[15px] focus:outline-none focus:border-purple-500 max-h-[220px]"
/>
{running ? (
<button type="button" onClick={() => stop(conv.id)} className="h-12 w-12 shrink-0 rounded-2xl bg-red-600 hover:bg-red-700 text-white flex items-center justify-center" title="停止">
<Square className="w-4 h-4 fill-current" />
</button>
) : (
<button type="button" onClick={submit} disabled={!input.trim()} className="h-12 w-12 shrink-0 rounded-2xl bg-purple-600 hover:bg-purple-700 text-white flex items-center justify-center disabled:opacity-40" title="送出">
<Send className="w-4 h-4" />
</button>
)}
</div>
</div>
</div>
)
}