/** * AgentChat — 人格体对话组件 * * 与光湖人格体对话,Agent 直接操作 Git 引擎管理知识库。 * 支持:对话、工具调用展示、对话历史、清空对话。 */ import { useState, useRef, useEffect } from 'react'; import { marked } from 'marked'; interface Message { role: 'user' | 'assistant' | 'tool' | 'system'; content: string; toolCalls?: Array<{ id: string; name: string; arguments: Record }>; toolResults?: Array<{ id: string; name: string; output: string; error?: string }>; timestamp: string; } interface AgentStatus { name: string; role: string; model: string; conversationLength: number; configured: boolean; operational: boolean; tools: string[]; } interface RepositoryStatus { branch: string; head: string; clean: boolean; ahead: number; behind: number; remote: { name: string; url: string } | null; } interface Props { apiBase: string; onDocSelect?: (path: string) => void; } export default function AgentChat({ apiBase, onDocSelect }: Props) { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [sending, setSending] = useState(false); const [status, setStatus] = useState(null); const [repoStatus, setRepoStatus] = useState(null); const [remoteUrl, setRemoteUrl] = useState(''); const [syncMessage, setSyncMessage] = useState(''); const [syncing, setSyncing] = useState(false); const [configOpen, setConfigOpen] = useState(false); const [modelBaseUrl, setModelBaseUrl] = useState('https://api.openai.com/v1'); const [modelName, setModelName] = useState('gpt-4o'); const [modelKey, setModelKey] = useState(''); const [configMessage, setConfigMessage] = useState(''); const bottomRef = useRef(null); const inputRef = useRef(null); useEffect(() => { fetchStatus(); fetchRepositoryStatus(); loadModelConfig(); }, []); useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); async function fetchStatus() { try { const res = await fetch(`${apiBase}/api/agent/status`); const data = await res.json(); if (data.ok) { setStatus({ name: data.persona.name, role: data.persona.role, model: data.persona.model, conversationLength: data.conversationLength, configured: data.configured, operational: data.operational, tools: data.tools || [], }); } } catch {} } async function loadModelConfig() { const bridge = (window as any).hololake?.agent; if (!bridge) return; try { const config = await bridge.getConfig(); setModelBaseUrl(config.baseUrl || 'https://api.openai.com/v1'); setModelName(config.model || 'gpt-4o'); } catch {} } async function saveModelConfig() { const bridge = (window as any).hololake?.agent; if (!bridge) { setConfigMessage('模型安全配置只在桌面 App 中提供'); return; } try { await bridge.saveConfig({ baseUrl: modelBaseUrl, model: modelName, apiKey: modelKey || undefined }); setModelKey(''); setConfigMessage('已保存到 macOS 加密存储'); await fetchStatus(); } catch (err: any) { setConfigMessage(err.message); } } async function fetchRepositoryStatus() { try { const res = await fetch(`${apiBase}/api/forgejo/status`); const data = await res.json(); if (data.ok) { setRepoStatus(data.status); if (data.status.remote?.url) setRemoteUrl(data.status.remote.url); } } catch {} } async function runForgejoAction(action: 'configure' | 'fetch' | 'pull' | 'push') { if (syncing) return; if (action === 'push' && !confirm('确认把当前知识库提交推送到已配置的 Forgejo 仓库?')) return; setSyncing(true); setSyncMessage(''); try { const endpoint = action === 'configure' ? 'remote' : action; const res = await fetch(`${apiBase}/api/forgejo/${endpoint}`, { method: action === 'configure' ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(action === 'configure' ? { url: remoteUrl } : { confirm: action === 'push' }), }); const data = await res.json(); if (!data.ok) throw new Error(data.error || '操作失败'); setRepoStatus(data.status); setSyncMessage(action === 'configure' ? 'Forgejo 已连接' : `${action} 已完成`); } catch (err: any) { setSyncMessage(err.message); } finally { setSyncing(false); } } async function sendMessage() { const text = input.trim(); if (!text || sending) return; setInput(''); setSending(true); // 本地先显示用户消息 const userMsg: Message = { role: 'user', content: text, timestamp: new Date().toISOString(), }; setMessages(prev => [...prev, userMsg]); try { const res = await fetch(`${apiBase}/api/agent/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: text }), }); const data = await res.json(); if (data.ok) { const assistantMsg: Message = { role: 'assistant', content: data.reply, timestamp: new Date().toISOString(), }; setMessages(prev => [...prev, assistantMsg]); fetchStatus(); // 刷新状态 } else { setMessages(prev => [ ...prev, { role: 'assistant', content: `错误: ${data.error}`, timestamp: new Date().toISOString() }, ]); } } catch (err: any) { setMessages(prev => [ ...prev, { role: 'assistant', content: `网络错误: ${err.message}`, timestamp: new Date().toISOString() }, ]); } finally { setSending(false); inputRef.current?.focus(); } } async function clearConversation() { try { await fetch(`${apiBase}/api/agent/clear`, { method: 'POST' }); setMessages([]); fetchStatus(); } catch {} } function handleKeyDown(e: React.KeyboardEvent) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } } return (
{/* 头部状态栏 */}
🌊

{status?.name || '光湖人格体'}

{status?.role || '知识库管理者'}
{status?.model || 'offline'}
{status?.operational ? 'Agent 已接入模型' : 'Agent 等待模型配置'} {status?.tools?.length || 0} 个工具
{configOpen && (
setModelBaseUrl(e.target.value)} placeholder="模型服务地址" /> setModelName(e.target.value)} placeholder="模型名称" /> setModelKey(e.target.value)} placeholder={status?.configured ? '留空则保留现有密钥' : '模型密钥'} /> {configMessage &&
{configMessage}
}
)}
Forgejo 代码引擎 {repoStatus?.remote ? `${repoStatus.branch} · ${repoStatus.head.slice(0, 7)}` : '尚未连接远端'}
setRemoteUrl(e.target.value)} placeholder="HTTPS 或 SSH Forgejo 仓库地址" />
{repoStatus?.remote && (
{repoStatus.clean ? '本地已提交' : '本地有未提交内容'} · 领先 {repoStatus.ahead} / 落后 {repoStatus.behind}
)} {syncMessage &&
{syncMessage}
}
{/* 对话区域 */}
{messages.length === 0 && (
🌊

光湖人格体

{status?.operational ? '我是知识库的 AI Agent,可以调用工具管理文档。' : '知识库功能已运行;Agent 需要配置模型后才会回应,不会用模拟回复冒充。'}

试试说:

)} {messages.map((msg, i) => (
{msg.role === 'user' ? (

{msg.content}

) : (
🌊
{msg.toolCalls && msg.toolCalls.length > 0 && (
{msg.toolCalls.map((tc, j) => (
⚙️ {tc.name} {JSON.stringify(tc.arguments)}
))}
)} {msg.toolResults && msg.toolResults.length > 0 && (
{msg.toolResults.map((tr, j) => (
{tr.error ? '❌' : '✅'}
{tr.error || tr.output}
))}
)}
)}
))} {sending && (
🌊
)}
{/* 输入区 */}