feat(hololake): ship language platform 0.7.0

This commit is contained in:
冰朔 2026-08-09 03:37:41 +08:00
commit 5105ec5e32
47 changed files with 4566 additions and 398 deletions

View file

@ -26,52 +26,49 @@ interface AgentStatus {
tools: string[];
}
interface RepositoryStatus {
branch: string;
head: string;
clean: boolean;
ahead: number;
behind: number;
remote: { name: string; url: string } | null;
interface PendingAction {
id: string;
tool: string;
effect: 'write' | 'delete';
target: string;
summary: string;
createdAt: string;
}
interface Props {
apiBase: string;
onDocSelect?: (path: string) => void;
runtimeRevision?: number;
}
export default function AgentChat({ apiBase, onDocSelect }: Props) {
export default function AgentChat({ apiBase, onDocSelect, runtimeRevision = 0 }: Props) {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const [status, setStatus] = useState<AgentStatus | null>(null);
const [repoStatus, setRepoStatus] = useState<RepositoryStatus | null>(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 [statusError, setStatusError] = useState('');
const [pendingActions, setPendingActions] = useState<PendingAction[]>([]);
const [actionBusy, setActionBusy] = useState('');
const bottomRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
fetchStatus();
fetchRepositoryStatus();
loadModelConfig();
}, []);
}, [runtimeRevision]);
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
if (messages.length > 0 || sending) {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}
}, [messages, sending]);
async function fetchStatus() {
try {
const res = await fetch(`${apiBase}/api/agent/status`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data.ok) {
setStatusError('');
setStatus({
name: data.persona.name,
role: data.persona.role,
@ -82,66 +79,9 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
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);
} catch {
setStatus(null);
setStatusError('HoloLake 本地服务未启动');
}
}
@ -175,6 +115,7 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
timestamp: new Date().toISOString(),
};
setMessages(prev => [...prev, assistantMsg]);
setPendingActions(data.pendingActions || []);
fetchStatus(); // 刷新状态
} else {
setMessages(prev => [
@ -193,6 +134,27 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
}
}
async function resolveAction(action: PendingAction, decision: 'confirm' | 'reject') {
setActionBusy(action.id);
try {
const res = await fetch(`${apiBase}/api/agent/actions/${encodeURIComponent(action.id)}/${decision}`, {
method: 'POST',
});
const data = await res.json();
if (!data.ok) throw new Error(data.error || '动作处理失败');
setPendingActions(data.actions || []);
const content = decision === 'confirm'
? (data.result?.error ? `执行失败:${data.result.error}` : `已确认并执行:${data.result?.output || action.target}`)
: `已取消:${action.summary}`;
setMessages(prev => [...prev, { role: 'system', content, timestamp: new Date().toISOString() }]);
fetchStatus();
} catch (err: any) {
setMessages(prev => [...prev, { role: 'system', content: `动作未执行:${err.message}`, timestamp: new Date().toISOString() }]);
} finally {
setActionBusy('');
}
}
async function clearConversation() {
try {
await fetch(`${apiBase}/api/agent/clear`, { method: 'POST' });
@ -213,15 +175,14 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
{/* 头部状态栏 */}
<div className="agent-header">
<div className="agent-info">
<div className="agent-avatar">🌊</div>
<div className="agent-avatar" aria-hidden="true"><span /></div>
<div className="agent-meta">
<h3>{status?.name || 'HoloLake 助手'}</h3>
<span className="agent-role">{status?.role || '知识工作助手'}</span>
<h3>{status?.name || 'HoloLake'}</h3>
<span className="agent-role">{status?.role || '语言操作入口'}</span>
</div>
</div>
<div className="agent-actions">
<span className="agent-model">{status?.model || 'offline'}</span>
<button className="btn-config" onClick={() => setConfigOpen(!configOpen)} title="配置模型"></button>
<button className="btn-clear" onClick={clearConversation} title="清空对话">
</button>
@ -231,41 +192,8 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
<div className="runtime-status">
<div className="runtime-row">
<span className={`runtime-dot ${status?.operational ? 'online' : 'waiting'}`} />
<span>{status?.operational ? 'Agent 已接入模型' : 'Agent 等待模型配置'}</span>
<span className="runtime-tools">{status?.tools?.length || 0} </span>
</div>
{configOpen && (
<div className="model-config">
<input value={modelBaseUrl} onChange={e => setModelBaseUrl(e.target.value)} placeholder="模型服务地址" />
<input value={modelName} onChange={e => setModelName(e.target.value)} placeholder="模型名称" />
<input type="password" value={modelKey} onChange={e => setModelKey(e.target.value)} placeholder={status?.configured ? '留空则保留现有密钥' : '模型密钥'} />
<button onClick={saveModelConfig}></button>
{configMessage && <div className="forgejo-message">{configMessage}</div>}
</div>
)}
<div className="forgejo-status">
<div className="forgejo-title">
<strong>Forgejo </strong>
<span>{repoStatus?.remote ? `${repoStatus.branch} · ${repoStatus.head.slice(0, 7)}` : '尚未连接远端'}</span>
</div>
<input
className="forgejo-url"
value={remoteUrl}
onChange={e => setRemoteUrl(e.target.value)}
placeholder="HTTPS 或 SSH Forgejo 仓库地址"
/>
<div className="forgejo-actions">
<button onClick={() => runForgejoAction('configure')} disabled={syncing || !remoteUrl.trim()}></button>
<button onClick={() => runForgejoAction('fetch')} disabled={syncing || !repoStatus?.remote}></button>
<button onClick={() => runForgejoAction('pull')} disabled={syncing || !repoStatus?.remote}></button>
<button onClick={() => runForgejoAction('push')} disabled={syncing || !repoStatus?.remote}></button>
</div>
{repoStatus?.remote && (
<div className="forgejo-detail">
{repoStatus.clean ? '本地已提交' : '本地有未提交内容'} · {repoStatus.ahead} / {repoStatus.behind}
</div>
)}
{syncMessage && <div className="forgejo-message">{syncMessage}</div>}
<span>{statusError || (status?.operational ? '语言操作入口可用' : status?.configured ? '模型已保存,等待连通验证' : '请在设置中配置模型')}</span>
<span className="runtime-tools">{status?.tools?.length || 0} </span>
</div>
</div>
@ -273,19 +201,18 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
<div className="agent-messages">
{messages.length === 0 && (
<div className="agent-welcome">
<div className="welcome-icon">🌊</div>
<h2>HoloLake </h2>
<p>{status?.operational ? '可以检索、整理和编辑当前知识库,并为操作保留版本记录。' : '知识库已运行;配置模型后即可使用智能整理功能。'}</p>
<h2> HoloLake</h2>
<p>{statusError || (status?.operational ? '可以检索、整理和编辑当前知识库,并为操作保留版本记录。' : '知识库可以独立使用;模型服务在设置中配置并验证。')}</p>
<p className="welcome-hint"></p>
<div className="welcome-suggestions">
<button onClick={() => { setInput('帮我列出所有文档'); inputRef.current?.focus(); }}>
📋
</button>
<button onClick={() => { setInput('搜索关于协议的内容'); inputRef.current?.focus(); }}>
🔍
</button>
<button onClick={() => { setInput('创建一篇新的学习笔记'); inputRef.current?.focus(); }}>
</button>
</div>
</div>
@ -299,13 +226,13 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
</div>
) : (
<div className="msg-bubble msg-assistant-bubble">
<div className="msg-avatar">🌊</div>
<div className="msg-avatar" aria-hidden="true"><span /></div>
<div className="msg-content">
{msg.toolCalls && msg.toolCalls.length > 0 && (
<div className="tool-calls">
{msg.toolCalls.map((tc, j) => (
<div key={j} className="tool-call">
<span className="tool-icon"></span>
<span className="tool-icon"></span>
<span className="tool-name">{tc.name}</span>
<code className="tool-args">{JSON.stringify(tc.arguments)}</code>
</div>
@ -316,7 +243,7 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
<div className="tool-results">
{msg.toolResults.map((tr, j) => (
<div key={j} className={`tool-result ${tr.error ? 'tool-error' : ''}`}>
<span className="tool-icon">{tr.error ? '❌' : '✅'}</span>
<span className="tool-icon">{tr.error ? '失败' : '完成'}</span>
<pre>{tr.error || tr.output}</pre>
</div>
))}
@ -334,10 +261,30 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
</div>
))}
{pendingActions.length > 0 && (
<div className="pending-actions" aria-label="待确认动作">
<div className="pending-actions-heading"></div>
{pendingActions.map(action => (
<div className={`pending-action ${action.effect}`} key={action.id}>
<div>
<strong>{action.effect === 'delete' ? '删除' : '写入'} · {action.target}</strong>
<small>{action.summary}</small>
</div>
<div className="pending-action-buttons">
<button onClick={() => resolveAction(action, 'reject')} disabled={Boolean(actionBusy)}></button>
<button className={action.effect === 'delete' ? 'danger' : 'confirm'} onClick={() => resolveAction(action, 'confirm')} disabled={Boolean(actionBusy)}>
{actionBusy === action.id ? '处理中…' : '确认执行'}
</button>
</div>
</div>
))}
</div>
)}
{sending && (
<div className="msg msg-assistant">
<div className="msg-bubble msg-assistant-bubble">
<div className="msg-avatar">🌊</div>
<div className="msg-avatar" aria-hidden="true"><span /></div>
<div className="msg-content typing">
<span className="dot" />
<span className="dot" />
@ -355,7 +302,7 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
<textarea
ref={inputRef}
className="agent-input"
placeholder="向 HoloLake 助手提问…"
placeholder="向 HoloLake 发出语言指令…"
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
@ -371,7 +318,7 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
</button>
</div>
<div className="agent-hint">
{status?.operational ? 'Enter 发送 · 写操作由本地 Git 留痕 · Forgejo 推送需确认' : 'Agent 尚未接入模型;知识库与 Forgejo 功能仍可独立使用'}
{status?.operational ? 'Enter 发送 · 写操作先确认并由本地 Git 留痕 · 服务器推送独立确认' : '语言操作入口暂不可用;知识库仍可独立使用'}
</div>
</div>
</div>