File size: 11,802 Bytes
4e039c5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | 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>
)
}
|