Files
Agent-Workbench/src/client/ProjectMemoryPanel.tsx
T
2026-10-30 18:16:46 +08:00

53 lines
7.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { Archive, Brain, CircleHelp, LoaderCircle, Plus, RefreshCw, ShieldCheck } from 'lucide-react';
import type { Project, ProjectMemory, ProjectMemoryView, Session } from './types';
import { api } from './api';
import './ProjectMemory.css';
const statusLabel: Record<string, string> = { current: '当前', unverified: '扫描不完整', expired: '已过期', archived: '已归档' };
export function ProjectMemoryPanel({ project, session }: { project: Project; session: Session | null }) {
const [view, setView] = useState<ProjectMemoryView | null>(null);
const [loading, setLoading] = useState(false);
const [working, setWorking] = useState(false);
const [notice, setNotice] = useState('');
const [error, setError] = useState('');
const [draft, setDraft] = useState({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' });
const alive = useRef(true);
const load = async () => {
setLoading(true); setError('');
try { const result = await api<ProjectMemoryView>('/projects/' + project.id + '/memories'); if (alive.current) setView(result); }
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆读取失败。'); }
finally { if (alive.current) setLoading(false); }
};
useEffect(() => { alive.current = true; void load(); return () => { alive.current = false; }; }, [project.id]);
const create = async (event: FormEvent) => {
event.preventDefault(); if (!session || !draft.content.trim()) return;
setWorking(true); setError(''); setNotice('');
try {
await api('/sessions/' + session.id + '/memories', { title: draft.title || '未命名记忆', content: draft.content, tags: draft.tags.split(',').map(value => value.trim()).filter(Boolean), ...(draft.sourcePath.trim() ? { source: { kind: 'file', path: draft.sourcePath.trim() } } : {}), ...(draft.expiresAt ? { expiresAt: new Date(draft.expiresAt).toISOString() } : {}) });
if (alive.current) { setDraft({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' }); setNotice('记忆已保存,并绑定当前源码指纹。'); await load(); }
} catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆保存失败。'); }
finally { if (alive.current) setWorking(false); }
};
const archive = async (memory: ProjectMemory) => {
if (!session) return;
setWorking(true); setError('');
try { await api('/sessions/' + session.id + '/memories/' + memory.id + '/archive', {}); if (alive.current) { setNotice('已归档这条记忆。'); await load(); } }
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆归档失败。'); }
finally { if (alive.current) setWorking(false); }
};
const memories = view?.memories ?? [];
return <section className="project-memory" aria-label="项目记忆">
<header className="memory-overview"><div><span className="memory-eyebrow"><Brain size={14} />PROJECT MEMORY</span><h3>项目记忆</h3><p>当前记忆按预算提供给本项目后续任务;来源匹配后仍需结合实际代码核对内容。</p></div><button type="button" className="button secondary" onClick={() => void load()} disabled={loading || working}><RefreshCw size={14} className={loading ? 'spin' : ''} />重新核对</button></header>
{notice && <p className="memory-notice" role="status"><ShieldCheck size={14} />{notice}</p>}
{error && <p className="memory-error" role="alert">{error}</p>}
{view && <div className="memory-summary"><span><strong>{view.summary.current}</strong> 条当前记忆</span>{(view.summary.unverified ?? 0) > 0 && <span><strong>{view.summary.unverified}</strong> 条未能验证</span>}<span><strong>{view.summary.expired}</strong> 条需重新核对</span><span>源码 <code>{view.sourceFingerprint.slice(0, 12)}</code></span></div>}
{view && !view.scope.complete && <p className="memory-warning memory-scope-warning" role="status"><CircleHelp size={14} />本次源码扫描未覆盖完整工程(已扫描 {view.scope.scannedFiles} 个文件,{view.scope.bytes.toLocaleString()} 字节);现有记忆暂标为“扫描不完整”,不会作为当前事实。请缩小项目范围或排除超预算文件后重新核对。</p>}
{!memories.length && !loading && <div className="memory-empty"><Brain size={25} /><strong>这个项目还没有记忆</strong><p>保存架构决策、约束和经过核对的工程事实,后续任务可以直接查看来源。</p></div>}
<div className="memory-list">{memories.map(memory => <article key={memory.id} className={'memory-card memory-' + memory.status}><div className="memory-card-heading"><span className="memory-state">{statusLabel[memory.status] || memory.status}</span><h4>{memory.title}</h4><time>{new Date(memory.updatedAt).toLocaleString('zh-CN')}</time></div><p className="memory-content">{memory.content}</p><div className="memory-meta"><span>来源:{memory.source.kind === 'file' ? memory.source.path : memory.source.label || memory.source.kind}</span>{memory.source.sha256 && <code>来源 SHA {memory.source.sha256.slice(0, 12)}</code>}<code>工程 {memory.sourceFingerprint.slice(0, 12)}</code>{memory.tags.map(tag => <span className="memory-tag" key={tag}>{tag}</span>)}</div>{memory.expiredReason && <p className="memory-warning"><CircleHelp size={14} />{memory.expiredReason}</p>}{memory.status !== 'archived' && <button type="button" className="text-button" disabled={working || memory.sessionId !== session?.id} onClick={() => void archive(memory)}><Archive size={13} />归档</button>}</article>)}</div>
<form className="memory-editor" onSubmit={create}><div className="memory-editor-heading"><div><h4>保存一条项目记忆</h4><p>来源默认绑定当前会话;填写文件路径后会额外保存文件 SHA256。</p></div><Plus size={18} /></div><div className="memory-form-grid"><label>标题<input value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} maxLength={240} placeholder="例如:接口层必须保持本地鉴权" /></label><label>来源文件(可选)<input value={draft.sourcePath} onChange={event => setDraft({ ...draft, sourcePath: event.target.value })} placeholder="src/server/app.mjs" /></label><label>标签(逗号分隔)<input value={draft.tags} onChange={event => setDraft({ ...draft, tags: event.target.value })} placeholder="架构,约束" /></label><label>到期时间(可选)<input type="datetime-local" value={draft.expiresAt} onChange={event => setDraft({ ...draft, expiresAt: event.target.value })} /></label><label className="memory-full">内容<textarea required value={draft.content} onChange={event => setDraft({ ...draft, content: event.target.value })} maxLength={16000} rows={4} placeholder="记录可验证的事实、决策或限制……" /></label></div><div className="memory-editor-footer"><span><ShieldCheck size={14} />不会调用模型,也不会执行项目命令。</span><button type="submit" className="button primary" disabled={!session || working || !draft.content.trim() || Boolean(view && !view.scope.complete)}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}保存记忆</button></div></form>
</section>;
}