feat: Agent 安全纵深防御、Checkpoint 快照、会话 Rewind/Branch、自进化

Skill、流式执行优化与系统架构全面升级

  本次提交对标 Claude Code 与 Hermes-Agent 的工程细节,在安全、可靠性、
  会话管理、自我进化四个维度进行了系统性加固,变更总量 48 文件 / +12680 -2292 行。

  ═══════ 安全纵深防御 ═══════

  1. Hardline 硬阻止层 (src/agent/runtime/hardline.rs, +534 行)
     - 不可绕过的危险命令拦截(关重启、磁盘擦除、Fork 炸弹、rm -rf /、kill -1)
     - 反规避标准化管线: ANSI 序列剥离 → Unicode NFKC → shell 反斜杠还原 → 空字面量清理
     - 在 PermissionChecker 之前执行,YOLO/Bypass 模式下同样生效
     - 集成到 executor Phase 2,被拒绝工具直接注入错误结果

  2. Permission 优先级裁决器 (src/agent/runtime/permission.rs, +200 行)
     - 7 层正式优先级规则 (P0 Deny → P7 Allow),带冲突日志
     - explain() 方法支持审计追溯
     - Hook PermissionRequired 与 Checker 结果的正确叠加逻辑

  ═══════ Checkpoint 文件快照系统 ═══════

  3. git2 原生快照 (src/agent/runtime/checkpoint.rs, +920 行)
     - 基于 git2 bare repo,内容寻址自动去重
     - 文件变更操作前自动触发 (file_write/file_edit/run_bash)
     - 每目录每 turn 最多一次快照,防止同一轮重复
     - 支持 list/diff/restore API + pre-rollback 安全快照
     - 旧快照自动 prune(保留最近 N 个)+ 按目录隔离 ref
     - 排除规则自动过滤 node_modules/target/.git/*.pdf 等
     - 集成到 executor: 文件操作前 ckpt.ensure_checkpoint()

  ═══════ 错误恢复系统大升级 ═══════

  4. 21 种 FailoverReason 分类 (src/agent/runtime/error_recovery.rs, +1200 行)
     - 参考 Hermes-Agent error_classifier.py
     - 8 步分类管线: provider-specific → HTTP status → text pattern → error body → fallback
     - is_retryable / should_compress / should_failover / is_permanent 方法
     - Context Overflow 自动修复: 从错误消息提取 token 限制,自动下调预算
     - RecoveryStep::AdjustMaxTokens 实现 (参考 Claude Code 自动修复)
     - 向后兼容 ErrorKind 别名

  ═══════ 会话 Rewind / Branch / Retry 体系 ═══════

  5. 完整 undo 栈 (src/agent/runtime/session.rs, +800 行 + 2 迁移脚本)
     - Rewind (软删除): active=0 标记,审计 trail 保留,LLM 不可见
     - Restore (撤销回退): 冲突检测——回退后有新消息则拒绝,引导使用 Branch
     - Branch: 分叉会话,复制所有 active=1 消息到新会话
     - Retry: 硬删除最后一轮对话,返回原消息文本供前端重提交
     - 数据库: agent_messages.active 列 + agent_sessions.rewind_count + parent_session_id
     - API: 4 个新端点 (/branch, /retry, /rewind, /rewind/restore)
     - load_history_for_agent 全面使用 active=1 过滤

  ═══════ Hooks 系统模块化重构 ═══════

  6. 单文件 → 7 模块体系 (src/agent/hooks/)
     hooks.rs (994 行) 拆分为:
     - mod.rs    — 入口 + HookRegistry + SessionHookManager
     - types.rs  — 类型定义 (Context, TaggedContext, PermissionRequestAction 等)
     - traits.rs — AgentHook + AsyncAgentHook + 15 种生命周期事件
     - matcher.rs — 工具名/参数匹配 + session 作用域过滤
     - dispatch.rs — 并行调度引擎 (run_pre/post_tool_use 等)
     - registry.rs — 注册/注销/查询
     - builtins.rs — CancellationHook + MetricsHook + AuditLogHook + ContextDeduplicator

     关键改进:
     - run_pre_tool_use 并行执行所有匹配 hooks,聚合 Block/MutateInput/Continue
     - TaggedContext 带完整来源标记的上下文注入 (hook_name + event)
     - ContextDeduplicator 单 dispatch cycle 内内容哈希去重
     - AsyncAgentHook 支持 fire-and-forget 异步 hooks

  ═══════ Executor 并发执行升级 ═══════

  7. 三阶段管道重写 (src/agent/runtime/executor.rs, +600 行)
     - Phase 1: 死循环检测 + 参数解析 (不变)
     - Phase 2: Hardline 预检查 (新增) → PermissionChecker (改进)
     - Phase 3: ToolPartitioner 分区 → 逐批次执行 (重写)
       - 并行批次内 FuturesUnordered 并发
       - 串行批次确保非并发安全工具独占执行
       - Checkpoint 预触发集成
     - Hook 上下文注入: system-reminder 格式 + ContextDeduplicator 去重
     - Hook 阻塞错误详细记录

  ═══════ 流式执行真正的流式调度 ═══════

  8. StreamingExecutor 重写 (src/agent/runtime/streaming_executor.rs, ~400 行变更)
     - on_tool_use 中对并发安全工具立即 tokio::spawn,不等待 flush
     - executing_non_concurrent 标志阻塞后继工具直到独占工具完成
     - JoinHandle 管理替代自定义 cancel channel
     - completed_queue 按流顺序 yield
     - Sibling Abort 通过 broadcast channel + tokio::select! 竞速
     - ToolContext 实现 Clone (支持 per-task 上下文复制)

  ═══════ 自改进 Skill 系统 ═══════

  9. PatternDetector + SkillCreator + Curator (src/agent/skills/, +1500 行)
     - PatternDetector: 扫描 agent_messages 表,检测跨 session 重复工具调用模式
     - SkillCreator: 将高置信度模式自动生成 SKILL.md (YAML frontmatter + 工作流步骤)
     - SelfImprovePipeline: 一站式 模式检测 → 创建 → 质量审查
     - Curator: 分析 skill 使用统计,标记 stale/deprecated,建议清理
     - Skill frontmatter 新增 pinned 字段 (禁止 Curator 自动清理)

  ═══════ 基础设施优化 ═══════

  10. 系统提示词缓存 (src/agent/runtime/system_prompt.rs + mod.rs)
      - SystemPromptCache: 首次计算后永久复用,/clear 时失效
      - 新增 SAFETY / SYSTEM_CONTEXT / TOOL_USAGE 静态 section
      - 环境/tools/skills/memory 动态 section 通过 get_or_compute 缓存

  11. ToolRegistry schema 缓存 (src/agent/tools/mod.rs)
      - schema_cache + schema_generation 版本号
      - 工具变更/过滤器变更时自动失效
      - precompute_definitions() 预计算 (AgentRuntime 初始化时调用)

  12. 迭代摘要融合 (src/agent/compact.rs, +100 行)
      - 参考 Hermes context_compressor.py
      - CollapseLog 追踪压缩历史,支持溢出合并
      - extract_prior_summary: 提取已有摘要融入新压缩

  13. SubAgent 系统提示词模块化 (src/agent/tools/subagent.rs)
      - 复用 5 个标准 section + 子代理专有上下文 section
      - 独立 ToolRegistry 构建工具列表

  ═══════ 前端 — CSS 变量主题系统 ═══════

  14. 全新主题变量体系 (dashboard/src/index.css + App.tsx + 各面板)
      - CSS 自定义属性: --bg-card, --text-main, --text-muted, --border-precision
      - 语义化颜色: --accent-blueprint, --accent-star
      - 全面替换硬编码 Tailwind 颜色 (slate-xxx → var(--xxx))
      - 文献入库提示优化 ("核心知识节点" 替代 "向量块")
      - ReaderPanel 样式变量化
This commit is contained in:
fmq
2026-06-22 20:29:37 +08:00
parent f6df9d8136
commit 698d007f39
48 changed files with 12706 additions and 2318 deletions
+57 -57
View File
@@ -337,7 +337,7 @@ export default function App() {
}
};
// 5.5. 对文献进行向量化分块入库 (独立任务)
// 5.5. 对文献进行知识入库 (独立任务)
const handleVectorize = async (bibcode: string) => {
setVectorizing(true);
try {
@@ -347,10 +347,10 @@ export default function App() {
if (selectedPaper?.bibcode === bibcode) {
setSelectedPaper(prev => prev ? { ...prev, has_vector: true } : null);
}
showAlert(`文献向量化分块入库成功,共切片并录入 ${res.data.chunk_count}向量块`, '向量化成功');
showAlert(`文献已成功录入馆藏智能库,共提炼并录入 ${res.data.chunk_count}核心知识节点`, '知识入库成功');
} catch (e) {
console.error('文献向量化失败', e);
showAlert('向量化失败,请检查 .env 中的 Embedding API 配置。', '向量化失败');
console.error('知识入库失败', e);
showAlert('知识入库失败,请检查 .env 中的 Embedding API 配置。', '知识入库失败');
} finally {
setVectorizing(false);
}
@@ -698,11 +698,11 @@ export default function App() {
>
<div
onClick={(e) => e.stopPropagation()}
className="bg-white rounded-xl border border-slate-200 shadow-xl max-w-sm w-full p-6 space-y-4"
className="bg-[var(--bg-card)] rounded-xl border border-[var(--border-precision)] shadow-md max-w-sm w-full p-6 space-y-4"
>
<div className="flex items-center justify-between border-b border-slate-100 pb-2.5">
<h3 className="text-xs font-bold text-slate-900 flex items-center gap-1.5">
<span className={`w-2 h-2 rounded-full ${dialog.type === 'confirm' ? 'bg-sky-500' : 'bg-red-500'} animate-pulse`} />
<h3 className="text-xs font-bold text-[var(--text-main)] flex items-center gap-1.5">
<span className={`w-2 h-2 rounded-full ${dialog.type === 'confirm' ? 'bg-[var(--accent-blueprint)]' : 'bg-[#ef4444]'} animate-pulse`} />
<span>{dialog.title}</span>
</h3>
<button
@@ -719,7 +719,7 @@ export default function App() {
</button>
</div>
<div className="space-y-2">
<p className="text-xs text-slate-705 leading-relaxed">{dialog.message}</p>
<p className="text-xs text-[var(--text-muted)] leading-relaxed">{dialog.message}</p>
</div>
<div className="flex gap-2 pt-2">
<button
@@ -737,7 +737,7 @@ export default function App() {
if (dialog.onCancel) dialog.onCancel();
setDialog(null);
}}
className="px-4 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-lg text-[11px] font-bold text-center transition-all cursor-pointer"
className="px-4 btn-console btn-console-secondary py-2 rounded-lg text-[11px] font-bold text-center cursor-pointer"
>
</button>
@@ -755,11 +755,11 @@ export default function App() {
>
<div
onClick={(e) => e.stopPropagation()}
className="bg-white rounded-xl border border-slate-200 shadow-xl max-w-sm w-full p-6 space-y-4"
className="bg-[var(--bg-card)] rounded-xl border border-[var(--border-precision)] shadow-md max-w-sm w-full p-6 space-y-4"
>
<div className="flex items-center justify-between border-b border-slate-100 pb-2.5">
<h3 className="text-xs font-bold text-slate-900 flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" />
<h3 className="text-xs font-bold text-[var(--text-main)] flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full bg-[var(--accent-star)] animate-pulse" />
<span></span>
</h3>
<button
@@ -773,10 +773,10 @@ export default function App() {
</button>
</div>
<div className="space-y-2">
<p className="text-xs text-slate-700 leading-relaxed">
<span className="font-mono bg-slate-100 px-1.5 py-0.5 rounded text-sky-700 font-bold select-all">{uncachedBibcode}</span>
<p className="text-xs text-[var(--text-main)] leading-relaxed">
<span className="font-mono bg-slate-100 px-1.5 py-0.5 rounded text-[var(--accent-blueprint)] font-bold select-all">{uncachedBibcode}</span>
</p>
<p className="text-[11px] text-slate-400 leading-relaxed">
<p className="text-[11px] text-[var(--text-muted)] leading-relaxed">
线 NASA ADS
</p>
</div>
@@ -795,13 +795,13 @@ export default function App() {
axios.post('/api/active_bibcode', { bibcode: uncachedBibcode }).catch(() => {});
window.open(`https://ui.adsabs.harvard.edu/abs/${uncachedBibcode}/abstract`, '_blank');
}}
className="flex-1 bg-white hover:bg-slate-50 text-slate-700 border border-slate-250 py-2 rounded-lg text-[11px] font-bold text-center transition-all shadow-sm cursor-pointer"
className="flex-1 btn-console btn-console-secondary py-2 rounded-lg text-[11px] font-bold text-center cursor-pointer"
>
ADS
</button>
<button
onClick={() => setUncachedBibcode(null)}
className="px-3 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-lg text-xs font-medium text-center transition-all cursor-pointer"
className="px-3 btn-console btn-console-secondary py-2 rounded-lg text-[11px] font-bold text-center cursor-pointer"
>
</button>
@@ -818,13 +818,13 @@ export default function App() {
>
<div
onClick={(e) => e.stopPropagation()}
className="bg-white rounded-xl border border-slate-200 shadow-xl max-w-lg w-full p-6 space-y-4 cursor-default animate-fade-in"
className="bg-[var(--bg-card)] rounded-xl border border-[var(--border-precision)] shadow-md max-w-lg w-full p-6 space-y-4 cursor-default animate-fade-in"
>
{/* 标题 & 关闭 */}
<div className="flex items-start justify-between border-b border-slate-100 pb-3">
<div className="space-y-1 pr-4">
<span className="text-[10px] font-bold text-sky-700 uppercase tracking-wider"></span>
<h3 className="text-xs font-bold text-slate-900 leading-snug">
<span className="text-[10px] font-bold text-[var(--accent-blueprint)] uppercase tracking-wider"></span>
<h3 className="text-xs font-bold text-[var(--text-main)] leading-snug">
{getDoctypeBadge(detailPaper.doctype)}
<span className="align-middle">{detailPaper.title}</span>
</h3>
@@ -844,48 +844,48 @@ export default function App() {
<div className="space-y-4 h-[460px] flex flex-col overflow-y-auto pr-1 text-xs scrollbar-thin">
{/* 作者 */}
<div className="space-y-1 h-12 overflow-y-auto scrollbar-thin shrink-0">
<span className="text-slate-450 font-bold"></span>
<p className="text-slate-800 leading-relaxed font-semibold">{detailPaper.authors.join(', ')}</p>
<span className="text-[var(--text-muted)] font-bold"></span>
<p className="text-[var(--text-main)] leading-relaxed font-semibold">{detailPaper.authors.join(', ')}</p>
</div>
{/* 期刊 & 年份 */}
<div className="grid grid-cols-5 gap-4 border-y border-slate-100 py-2.5 shrink-0 h-14">
<div className="space-y-0.5 flex flex-col justify-center min-w-0 col-span-4">
<span className="text-slate-450 font-bold block text-[10px] leading-tight"></span>
<span className="text-[var(--text-muted)] font-bold block text-[10px] leading-tight"></span>
<span
className="text-slate-800 font-bold italic truncate block text-[11px] leading-tight"
className="text-[var(--text-main)] font-bold italic truncate block text-[11px] leading-tight"
title={detailPaper.pub_journal || '未标注'}
>
{detailPaper.pub_journal || '未标注'}
</span>
</div>
<div className="space-y-0.5 flex flex-col justify-center col-span-1">
<span className="text-slate-450 font-bold block text-[10px] leading-tight"></span>
<span className="text-slate-850 font-extrabold block text-[11px] leading-tight">{detailPaper.year}</span>
<span className="text-[var(--text-muted)] font-bold block text-[10px] leading-tight"></span>
<span className="text-[var(--text-main)] font-extrabold block text-[11px] leading-tight">{detailPaper.year}</span>
</div>
</div>
{/* 摘要 */}
<div className="space-y-1.5 flex flex-col h-40 shrink-0">
<span className="text-slate-450 font-bold block"></span>
<p className="text-slate-700 leading-relaxed font-normal bg-slate-50 p-3 flex-1 rounded-lg border border-slate-200 text-justify overflow-y-auto scrollbar-thin select-text">
<span className="text-[var(--text-muted)] font-bold block"></span>
<p className="text-[var(--text-main)] leading-relaxed font-normal bg-[#f8fafc] p-3 flex-1 rounded-lg border border-[var(--border-precision)] text-justify overflow-y-auto scrollbar-thin select-text">
{detailPaper.abstract_text || '该文献暂无摘要数据。'}
</p>
</div>
{/* 关键字 */}
<div className="space-y-1.5 flex flex-col h-16 shrink-0">
<span className="text-slate-450 font-bold block"></span>
<span className="text-[var(--text-muted)] font-bold block"></span>
{detailPaper.keywords && detailPaper.keywords.length > 0 ? (
<div className="flex flex-wrap gap-1.5 flex-1 content-start items-start overflow-y-auto scrollbar-thin pr-1">
{detailPaper.keywords.map(kw => (
<span key={kw} className="px-2 py-0.5 rounded bg-slate-100 border border-slate-200 text-slate-600 font-bold text-[9px]">
<span key={kw} className="px-2 py-0.5 rounded bg-[#f1f5f9] border border-[var(--border-precision)] text-[var(--text-muted)] font-bold text-[9px]">
{kw}
</span>
))}
</div>
) : (
<div className="flex items-center justify-center flex-1 bg-slate-50 border border-slate-200 rounded-lg text-[10px] text-slate-400 font-bold select-none">
<div className="flex items-center justify-center flex-1 bg-[#f8fafc] border border-[var(--border-precision)] rounded-lg text-[10px] text-[var(--text-muted)] font-bold select-none">
</div>
)}
@@ -893,48 +893,48 @@ export default function App() {
{/* 标识符 */}
<div className="border-t border-slate-100 pt-3 grid grid-cols-1 sm:grid-cols-3 gap-2 text-[10px] font-mono mt-auto shrink-0">
<div className="bg-slate-50 px-2.5 py-1.5 rounded border border-slate-150">
<span className="text-slate-400 font-bold block">BIBCODE</span>
<span className="text-slate-700 font-semibold select-all truncate block" title={detailPaper.bibcode === detailPaper.arxiv_id ? '暂无' : detailPaper.bibcode}>
<div className="bg-[#f8fafc] px-2.5 py-1.5 rounded border border-[var(--border-precision)]">
<span className="text-[var(--text-muted)] font-bold block">BIBCODE</span>
<span className="text-[var(--text-main)] font-semibold select-all truncate block" title={detailPaper.bibcode === detailPaper.arxiv_id ? '暂无' : detailPaper.bibcode}>
{detailPaper.bibcode === detailPaper.arxiv_id ? '暂无' : (
<a
href={`https://ui.adsabs.harvard.edu/abs/${detailPaper.bibcode}/abstract`}
target="_blank"
rel="noreferrer"
onClick={() => axios.post('/api/active_bibcode', { bibcode: detailPaper.bibcode }).catch(() => {})}
className="hover:underline text-sky-600"
className="text-[var(--accent-blueprint)] hover:underline"
>
{detailPaper.bibcode}
</a>
)}
</span>
</div>
<div className="bg-slate-50 px-2.5 py-1.5 rounded border border-slate-150">
<span className="text-slate-400 font-bold block">DOI</span>
<span className="text-slate-700 font-semibold select-all truncate block" title={detailPaper.doi || '无'}>
<div className="bg-[#f8fafc] px-2.5 py-1.5 rounded border border-[var(--border-precision)]">
<span className="text-[var(--text-muted)] font-bold block">DOI</span>
<span className="text-[var(--text-main)] font-semibold select-all truncate block" title={detailPaper.doi || '无'}>
{detailPaper.doi ? (
<a
href={`https://doi.org/${detailPaper.doi}`}
target="_blank"
rel="noreferrer"
onClick={() => axios.post('/api/active_bibcode', { bibcode: detailPaper.bibcode }).catch(() => {})}
className="hover:underline text-sky-600"
className="text-[var(--accent-blueprint)] hover:underline"
>
{detailPaper.doi}
</a>
) : '无'}
</span>
</div>
<div className="bg-slate-50 px-2.5 py-1.5 rounded border border-slate-150">
<span className="text-slate-450 font-bold block">ARXIV ID</span>
<span className="text-slate-700 font-semibold select-all truncate block" title={detailPaper.arxiv_id || '无'}>
<div className="bg-[#f8fafc] px-2.5 py-1.5 rounded border border-[var(--border-precision)]">
<span className="text-[var(--text-muted)] font-bold block">ARXIV ID</span>
<span className="text-[var(--text-main)] font-semibold select-all truncate block" title={detailPaper.arxiv_id || '无'}>
{detailPaper.arxiv_id ? (
<a
href={`https://arxiv.org/abs/${detailPaper.arxiv_id}`}
target="_blank"
rel="noreferrer"
onClick={() => axios.post('/api/active_bibcode', { bibcode: detailPaper.bibcode }).catch(() => {})}
className="hover:underline text-sky-600"
className="text-[var(--accent-blueprint)] hover:underline"
>
{detailPaper.arxiv_id}
</a>
@@ -946,14 +946,14 @@ export default function App() {
{/* 手动上传文件(应对防爬阻断) */}
<div className="border-t border-slate-100 pt-3 space-y-2">
<div className="flex items-center justify-between">
<span className="text-slate-450 font-bold block">线</span>
<span className="text-[var(--text-muted)] font-bold block">线</span>
<span className="text-[9px] text-amber-700 font-bold bg-amber-50 px-2 py-0.5 rounded border border-amber-200">/</span>
</div>
<p className="text-[10px] text-slate-450 leading-relaxed">
<p className="text-[10px] text-[var(--text-muted)] leading-relaxed">
PDF HTML
</p>
<div className="grid grid-cols-2 gap-2">
<div className="flex flex-col items-center justify-center border border-dashed border-slate-300 rounded-lg p-2 hover:bg-slate-50 transition-colors relative cursor-pointer group min-h-[50px]">
<div className="flex flex-col items-center justify-center border border-dashed border-[var(--border-precision)] rounded-lg p-2 hover:bg-[#f8fafc] transition-colors relative cursor-pointer group min-h-[50px]">
<input
type="file"
accept="application/pdf"
@@ -969,13 +969,13 @@ export default function App() {
</span>
)}
<span className="text-[10px] font-bold text-sky-600 group-hover:underline">
<span className="text-[10px] font-bold text-[var(--accent-blueprint)] group-hover:underline">
{uploadingBibcode === detailPaper.bibcode ? '上传中...' : '上传 PDF 文献'}
</span>
<span className="text-[8px] text-slate-400"> .pdf </span>
<span className="text-[8px] text-[var(--text-muted)]"> .pdf </span>
</div>
<div className="flex flex-col items-center justify-center border border-dashed border-slate-300 rounded-lg p-2 hover:bg-slate-50 transition-colors relative cursor-pointer group min-h-[50px]">
<div className="flex flex-col items-center justify-center border border-dashed border-[var(--border-precision)] rounded-lg p-2 hover:bg-[#f8fafc] transition-colors relative cursor-pointer group min-h-[50px]">
<input
type="file"
accept="text/html,.html"
@@ -991,10 +991,10 @@ export default function App() {
</span>
)}
<span className="text-[10px] font-bold text-sky-600 group-hover:underline">
<span className="text-[10px] font-bold text-[var(--accent-blueprint)] group-hover:underline">
{uploadingBibcode === detailPaper.bibcode ? '上传中...' : '上传 HTML 文献'}
</span>
<span className="text-[8px] text-slate-400"> .html </span>
<span className="text-[8px] text-[var(--text-muted)]"> .html </span>
</div>
</div>
@@ -1004,7 +1004,7 @@ export default function App() {
<button
type="button"
onClick={() => handleMarkNoResource(detailPaper.bibcode, true)}
className="w-full py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-[10px] font-bold transition-all border border-slate-250 cursor-pointer flex items-center justify-center gap-1.5"
className="btn-console btn-console-secondary w-full py-2 rounded-lg text-[10px] font-bold transition-all cursor-pointer flex items-center justify-center gap-1.5"
>
<RefreshCw className="w-3 h-3" /> ()
</button>
@@ -1012,9 +1012,9 @@ export default function App() {
<button
type="button"
onClick={() => handleMarkNoResource(detailPaper.bibcode, false)}
className="w-full py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-[10px] font-bold transition-all border border-slate-250 cursor-pointer flex items-center justify-center gap-1.5"
className="btn-console btn-console-secondary w-full py-2 rounded-lg text-[10px] font-bold transition-all cursor-pointer flex items-center justify-center gap-1.5"
>
<AlertTriangle className="w-3 h-3 text-amber-500" /> ()
<AlertTriangle className="w-3 h-3 text-[var(--accent-star)]" /> ()
</button>
)}
</div>
@@ -1080,7 +1080,7 @@ export default function App() {
setActiveTab('citation');
loadCitations(detailPaper.bibcode);
}}
className="flex-1 bg-white hover:bg-slate-50 text-slate-700 border border-slate-250 py-2.5 rounded-lg text-xs font-bold text-center transition-all cursor-pointer shadow-sm"
className="flex-1 btn-console btn-console-secondary py-2.5 rounded-lg text-xs font-bold text-center cursor-pointer"
>
</button>
@@ -1091,7 +1091,7 @@ export default function App() {
}, '确认重新下载');
}}
disabled={downloadingBibcodes[detailPaper.bibcode]}
className="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-amber-700 rounded-lg text-xs font-bold transition-all cursor-pointer disabled:opacity-50"
className="px-4 btn-console btn-console-secondary text-[var(--accent-star)] py-2.5 rounded-lg text-xs font-bold transition-all cursor-pointer disabled:opacity-50"
>
{downloadingBibcodes[detailPaper.bibcode] ? '重下中...' : '重新下载'}
</button>
@@ -1124,7 +1124,7 @@ export default function App() {
setActiveTab('citation');
loadCitations(detailPaper.bibcode);
}}
className="px-6 bg-white hover:bg-slate-50 text-slate-700 border border-slate-250 py-2.5 rounded-lg text-xs font-bold text-center transition-all cursor-pointer shadow-sm"
className="px-6 btn-console btn-console-secondary py-2.5 rounded-lg text-xs font-bold text-center cursor-pointer"
>
</button>
@@ -11,7 +11,8 @@ import 'katex/dist/katex.min.css';
import {
Brain, Settings, Eye, CheckCircle2, AlertTriangle,
Send, Loader, Plus, Trash2, Compass, Clock, Square,
BarChart3, ScrollText, Network
BarChart3, ScrollText, Network, Rewind, RotateCcw,
GitBranch, RefreshCw
} from 'lucide-react';
import { AskUserQuestionCard } from './AskUserQuestionCard';
import { PermissionRequestCard } from './PermissionRequestCard';
@@ -76,6 +77,7 @@ interface ActiveTurn {
interface ProcessedTurn {
turn_index: number;
question: string;
questionMessageId?: number;
timeline: TimelineItem[];
usage?: {
prompt_tokens: number;
@@ -85,6 +87,26 @@ interface ProcessedTurn {
createdAt: string;
}
interface RewindResult {
rewound_count: number;
target_preview: string;
new_turn_index: number;
session_id: string;
}
interface BranchResult {
branch_session_id: string;
forked_at_message_id: number;
copied_count: number;
}
interface RetryResult {
retried_message: string;
new_turn_index: number;
deleted_count: number;
session_id: string;
}
const safeSchema = {
...defaultSchema,
attributes: {
@@ -119,9 +141,9 @@ function getToolDisplayName(name: string): string {
case 'download_paper': return '下载文献全文资源';
case 'parse_paper': return '结构化解析文献内容';
case 'get_paper_content': return '获取文献全文内容';
case 'rag_search': return '语义库检索 (RAG)';
case 'query_target': return '查询 CDS Sesame 天体物理参数';
case 'save_note': return '保存研究笔记';
case 'rag_search': return '检索馆藏知识库';
case 'query_target': return '查询天体物理参数 (CDS)';
case 'save_note': return '保存文献手札';
// Agent 控制工具
case 'todo_write': return '管理任务列表';
case 'compress_context': return '压缩上下文窗口';
@@ -325,6 +347,156 @@ export function ResearchAgentPanel({ showConfirm, showAlert }: ResearchAgentPane
}
};
// 回退会话到指定消息
const handleRewind = async (messageId?: number, n?: number) => {
if (!currentSessionId) return;
const msg = messageId
? '确定要回退到此消息之前吗?此后的对话将被移除(可通过“恢复”按钮撤销)。'
: `确定要回退最近 ${n || 1} 个对话轮次吗?`;
const performRewind = async () => {
try {
const body: { n?: number; message_id?: number } = {};
if (messageId) body.message_id = messageId;
else body.n = n || 1;
const res = await axios.post<RewindResult>(
`/api/chat/sessions/${currentSessionId}/rewind`,
body
);
if (showAlert) {
showAlert(`已回退 ${res.data.rewound_count} 条消息`, '成功');
} else {
alert(`已回退 ${res.data.rewound_count} 条消息`);
}
// 重新加载会话(静默刷新,避免闪烁)
loadSessionHistory(currentSessionId, true);
fetchSessions(); // 更新侧栏 turn_count
} catch (e: any) {
const errMsg = `回退失败: ${e.response?.data || e.message}`;
if (showAlert) {
showAlert(errMsg, '错误');
} else {
alert(errMsg);
}
}
};
if (showConfirm) {
showConfirm(msg, performRewind, '确认回退');
} else {
if (window.confirm(msg)) {
performRewind();
}
}
};
// 恢复上次回退(undo-of-undo
const handleRestoreRewind = async () => {
if (!currentSessionId) return;
try {
const res = await axios.post<{ restored_count: number }>(
`/api/chat/sessions/${currentSessionId}/rewind/restore`
);
if (res.data.restored_count > 0) {
const msg = `已恢复 ${res.data.restored_count} 条被回退的消息`;
if (showAlert) {
showAlert(msg, '成功');
} else {
alert(msg);
}
loadSessionHistory(currentSessionId, true);
fetchSessions();
} else {
const msg = '没有可恢复的回退操作';
if (showAlert) {
showAlert(msg, '提示');
} else {
alert(msg);
}
}
} catch (e: any) {
const errMsg = `恢复失败: ${e.response?.data || e.message}`;
if (showAlert) {
showAlert(errMsg, '错误');
} else {
alert(errMsg);
}
}
};
// 分叉当前会话
const handleBranch = async () => {
if (!currentSessionId) return;
const confirmed = window.confirm('确定要将当前活跃的消息分叉到一个新会话吗?');
if (!confirmed) return;
try {
const res = await axios.post<BranchResult>(
`/api/chat/sessions/${currentSessionId}/branch`
);
if (showAlert) {
showAlert(`成功分叉会话!已复制 ${res.data.copied_count} 条消息`, '成功');
} else {
alert(`成功分叉会话!已复制 ${res.data.copied_count} 条消息`);
}
// 刷新列表并选中新的分叉会话
await fetchSessions();
setCurrentSessionId(res.data.branch_session_id);
} catch (e: any) {
const errMsg = `分叉失败: ${e.response?.data || e.message}`;
if (showAlert) {
showAlert(errMsg, '错误');
} else {
alert(errMsg);
}
}
};
// 重试最后一轮
const handleRetry = async () => {
if (!currentSessionId || streaming) return;
const confirmed = window.confirm('确定要重试最后一轮对话吗?原回答将被删除。');
if (!confirmed) return;
try {
const res = await axios.post<RetryResult>(
`/api/chat/sessions/${currentSessionId}/retry`
);
const questionText = res.data.retried_message;
if (!questionText) {
if (showAlert) {
showAlert('没有找到可重试的上一轮问题', '提示');
} else {
alert('没有找到可重试的上一轮问题');
}
return;
}
// 重新加载会话以移除已被硬删除的消息,然后自动触发发送
await loadSessionHistory(currentSessionId, true);
await fetchSessions();
// 触发自动重发
handleSend(questionText);
} catch (e: any) {
const errMsg = `重试失败: ${e.response?.data || e.message}`;
if (showAlert) {
showAlert(errMsg, '错误');
} else {
alert(errMsg);
}
}
};
// 手动停止智能体执行
const handleStop = async () => {
if (!currentSessionId) return;
@@ -1082,10 +1254,21 @@ export function ResearchAgentPanel({ showConfirm, showAlert }: ResearchAgentPane
{turns.map((turn) => (
<div key={turn.turn_index} className="space-y-4">
{/* 用户提问 */}
<div className="flex flex-col items-end space-y-1">
<div className="flex flex-col items-end space-y-1 group relative">
<span className="text-[10px] font-bold text-slate-400 px-1"></span>
<div className="max-w-[85%] rounded-2xl px-4 py-3 text-xs leading-relaxed font-semibold shadow-2xs border bg-sky-600 text-white border-sky-600 select-text">
{turn.question}
<div className="flex items-center gap-2 max-w-[85%]">
{turn.questionMessageId && (
<button
onClick={() => handleRewind(turn.questionMessageId)}
className="opacity-0 group-hover:opacity-100 text-slate-400 hover:text-amber-600 p-1.5 rounded-lg hover:bg-slate-100 transition-all cursor-pointer shrink-0"
title="回退到此消息之前"
>
<Rewind className="w-3.5 h-3.5" />
</button>
)}
<div className="rounded-2xl px-4 py-3 text-xs leading-relaxed font-semibold shadow-2xs border bg-sky-600 text-white border-sky-600 select-text flex-1">
{turn.question}
</div>
</div>
</div>
@@ -1151,7 +1334,7 @@ export function ResearchAgentPanel({ showConfirm, showAlert }: ResearchAgentPane
{/* Error block */}
{activeTurn.error && (
<div className="flex items-start gap-2 bg-red-50 border border-red-200 text-red-700 rounded-lg p-3 text-xs w-[90%] font-semibold">
<div className="flex items-start gap-2 bg-red-50 border border-red-200 text-red-750 rounded-lg p-3 text-xs w-[90%] font-semibold">
<AlertTriangle className="w-4 h-4 text-red-500 shrink-0 mt-0.5" />
<div>
<div className="font-bold"></div>
@@ -1161,6 +1344,40 @@ export function ResearchAgentPanel({ showConfirm, showAlert }: ResearchAgentPane
)}
</div>
)}
{/* 会话操作小图标栏 */}
{currentSessionId && turns.length > 0 && !streaming && (
<div className="flex items-center gap-1 pt-2.5 justify-start border-t border-slate-100/60 mt-4 max-w-[200px]">
<button
onClick={() => handleRewind(undefined, 1)}
className="p-1.5 rounded-lg text-slate-400 hover:text-amber-600 hover:bg-slate-100 transition-all cursor-pointer"
title="回退最近一轮对话 (undo)"
>
<Rewind className="w-4 h-4" />
</button>
<button
onClick={handleRestoreRewind}
className="p-1.5 rounded-lg text-slate-400 hover:text-green-600 hover:bg-slate-100 transition-all cursor-pointer"
title="恢复上次回退操作"
>
<RotateCcw className="w-4 h-4" />
</button>
<button
onClick={handleRetry}
className="p-1.5 rounded-lg text-slate-400 hover:text-indigo-600 hover:bg-slate-100 transition-all cursor-pointer"
title="重试最后一轮对话"
>
<RefreshCw className="w-4 h-4" />
</button>
<button
onClick={handleBranch}
className="p-1.5 rounded-lg text-slate-400 hover:text-blue-600 hover:bg-slate-100 transition-all cursor-pointer"
title="分叉当前会话"
>
<GitBranch className="w-4 h-4" />
</button>
</div>
)}
</div>
)}
<div ref={chatEndRef} />
@@ -1269,6 +1486,7 @@ function groupMessagesIntoTurns(messages: MessageRecord[]): ProcessedTurn[] {
if (msg.role === 'user') {
turn.question = msg.content;
turn.questionMessageId = msg.id;
} else if (msg.role === 'assistant') {
const stepNum = msg.step_index;
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
+24 -24
View File
@@ -547,26 +547,26 @@ export function ReaderPanel({
onClick={() => handleVectorize(selectedPaper.bibcode)}
disabled={vectorizing}
className="btn-console btn-console-primary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-2"
title="对文献进行向量化分块入库,以开启学术 AI 问答"
title="对文献进行知识入库,以开启学术 AI 研讨"
>
{vectorizing ? <Loader className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
{vectorizing ? '向量化入库...' : '向量化入库'}
{vectorizing ? '正在进行知识入库...' : '知识入库'}
</button>
)}
{selectedPaper.has_markdown && selectedPaper.has_vector && (
<button
onClick={() => {
showConfirm('确定要重新向量化入库吗?这会清先前该文献的切片记录并重新执行入库。', () => {
showConfirm('确定要重新进行知识入库吗?这会清先前该文献已有的知识点记录并重新写入。', () => {
handleVectorize(selectedPaper.bibcode);
}, '确认重新向量化');
}, '确认重新知识入库');
}}
disabled={vectorizing}
className="btn-console btn-console-secondary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-2"
title="重新为该文献生成 RAG 向量切片"
title="重新为该文献解析知识点并入库"
>
{vectorizing ? <Loader className="w-3.5 h-3.5 animate-spin" /> : <RotateCw className="w-3.5 h-3.5" />}
</button>
)}
@@ -941,56 +941,56 @@ export function ReaderPanel({
top: `${hoverCardPos.y}px`,
zIndex: 9999,
}}
className="console-panel rounded-xl p-4 bg-white border border-slate-200 shadow-xl w-72 text-xs space-y-2 pointer-events-auto animate-in fade-in duration-200"
className="console-panel rounded-xl p-4 bg-[var(--bg-card)] border border-[var(--border-precision)] shadow-md w-72 text-xs space-y-2 pointer-events-auto animate-in fade-in duration-200"
>
<div className="flex items-center justify-between border-b border-slate-100 pb-1.5">
<span className="font-bold text-slate-900 text-sm">{hoveredTarget.target_name}</span>
<span className="font-bold text-[var(--text-main)] text-sm">{hoveredTarget.target_name}</span>
<div className="flex items-center gap-2 select-none">
<a
href={`https://simbad.cds.unistra.fr/simbad/sim-id?Ident=${encodeURIComponent(hoveredTarget.target_name)}`}
target="_blank"
rel="noopener noreferrer"
className="text-[10px] font-bold text-sky-600 hover:text-sky-800 hover:underline cursor-pointer"
className="text-[10px] font-bold text-[var(--accent-blueprint)] hover:text-[#0d5988] hover:underline cursor-pointer"
title="在 SIMBAD 中查询该天体详情"
>
SIMBAD
</a>
<span className="text-[9px] text-slate-300">|</span>
<span className="text-[9px] text-[var(--border-precision)]">|</span>
<a
href={`https://vizier.cds.unistra.fr/viz-bin/VizieR?-c=${encodeURIComponent(hoveredTarget.target_name)}`}
target="_blank"
rel="noopener noreferrer"
className="text-[10px] font-bold text-sky-600 hover:text-sky-800 hover:underline cursor-pointer"
className="text-[10px] font-bold text-[var(--accent-blueprint)] hover:text-[#0d5988] hover:underline cursor-pointer"
title="在 VizieR 中查询相关文献和表数据"
>
VizieR
</a>
</div>
</div>
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 text-slate-600">
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 text-[var(--text-muted)]">
<div>
<span className="text-slate-400 font-semibold">RA (J2000):</span>
<div className="font-mono font-bold text-slate-800">{hoveredTarget.ra || '未知'}</div>
<span className="text-[var(--text-muted)] font-semibold">RA (J2000):</span>
<div className="font-mono font-bold text-[var(--text-main)]">{hoveredTarget.ra || '未知'}</div>
</div>
<div>
<span className="text-slate-400 font-semibold">Dec (J2000):</span>
<div className="font-mono font-bold text-slate-800">{hoveredTarget.dec || '未知'}</div>
<span className="text-[var(--text-muted)] font-semibold">Dec (J2000):</span>
<div className="font-mono font-bold text-[var(--text-main)]">{hoveredTarget.dec || '未知'}</div>
</div>
<div>
<span className="text-slate-400 font-semibold">:</span>
<div className="font-bold text-slate-800">{hoveredTarget.spectral_type || '未知'}</div>
<span className="text-[var(--text-muted)] font-semibold">:</span>
<div className="font-bold text-[var(--text-main)]">{hoveredTarget.spectral_type || '未知'}</div>
</div>
<div>
<span className="text-slate-400 font-semibold"> (V):</span>
<div className="font-bold text-slate-800">
<span className="text-[var(--text-muted)] font-semibold"> (V):</span>
<div className="font-bold text-[var(--text-main)]">
{hoveredTarget.v_magnitude !== null && hoveredTarget.v_magnitude !== undefined
? `${hoveredTarget.v_magnitude.toFixed(2)}`
: '未知'}
</div>
</div>
<div className="col-span-2">
<span className="text-slate-400 font-semibold"> / :</span>
<div className="font-bold text-slate-800">
<span className="text-[var(--text-muted)] font-semibold"> / :</span>
<div className="font-bold text-[var(--text-main)]">
{hoveredTarget.parallax !== null && hoveredTarget.parallax !== undefined
? `${hoveredTarget.parallax.toFixed(2)} mas (~${(1000.0 / hoveredTarget.parallax).toFixed(1)} pc)`
: '未知'}
@@ -999,8 +999,8 @@ export function ReaderPanel({
</div>
{hoveredTarget.aliases && hoveredTarget.aliases.length > 0 && (
<div className="border-t border-slate-100 pt-1.5">
<span className="text-slate-400 font-semibold block mb-0.5">:</span>
<div className="text-[10px] text-slate-500 font-medium leading-relaxed max-h-16 overflow-y-auto font-mono">
<span className="text-[var(--text-muted)] font-semibold block mb-0.5">:</span>
<div className="text-[10px] text-[var(--text-muted)] font-medium leading-relaxed max-h-16 overflow-y-auto font-mono">
{hoveredTarget.aliases.slice(0, 8).join(', ')}
{hoveredTarget.aliases.length > 8 && ' ...'}
</div>
+32 -31
View File
@@ -1,4 +1,4 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap');
@import "tailwindcss";
@plugin "@tailwindcss/typography";
@@ -6,15 +6,18 @@
font-family: 'Inter', system-ui, -apple-system, sans-serif;
color-scheme: light;
--bg-main: #f1f5f9;
/* 极简白蓝学术科技风配色 */
--bg-main: #f4f6f9;
--bg-card: #ffffff;
--bg-sidebar: #f8fafc;
--text-main: #0f172a;
--text-muted: #475569;
--bg-sidebar: #0f2540; /* 保持深色侧边栏作为界面骨架结构 */
--text-main: #0a2540;
--text-muted: #5c6b84;
--accent-blue: #0284c7;
--accent-navy: #1e3a8a;
--border-clean: #e2e8f0;
--accent-blueprint: #106ba3;
--accent-star: #d97706;
--border-precision: #d2d8e2;
--font-mono: 'JetBrains Mono', monospace;
}
body {
@@ -32,7 +35,7 @@ body {
height: 6px;
}
::-webkit-scrollbar-track {
background: #f1f5f9;
background: #f4f6f9;
}
::-webkit-scrollbar-thumb {
background: #cbd5e1;
@@ -45,20 +48,20 @@ body {
/* Premium clean panel cards */
.console-panel {
background: var(--bg-card);
border: 1px solid var(--border-clean);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
border: 1px solid var(--border-precision);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05); /* 弱化阴影,更显扁平学术感 */
}
.console-panel-active {
border-color: var(--accent-blue);
box-shadow: 0 0 0 1px var(--accent-blue), 0 4px 6px -1px rgba(0, 0, 0, 0.05);
border-color: var(--accent-blueprint);
box-shadow: 0 0 0 1px var(--accent-blueprint), 0 1px 3px 0 rgba(0, 0, 0, 0.05);
}
/* High contrast clean console button */
.btn-console {
background: #ffffff;
border: 1px solid #cbd5e1;
color: #334155;
border: 1px solid var(--border-precision);
color: var(--text-main);
font-weight: 500;
transition: all 0.2s ease;
}
@@ -66,42 +69,42 @@ body {
.btn-console:hover:not(:disabled) {
background: #f8fafc;
border-color: #94a3b8;
color: #0f172a;
color: var(--text-main);
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
.btn-console-primary {
background: var(--accent-blue);
border: 1px solid var(--accent-blue);
background: var(--accent-blueprint);
border: 1px solid var(--accent-blueprint);
color: #ffffff;
}
.btn-console-primary:hover:not(:disabled) {
background: #0369a1;
border-color: #0369a1;
background: #0d5988;
border-color: #0d5988;
color: #ffffff;
box-shadow: 0 2px 4px 0 rgba(2, 132, 199, 0.2);
box-shadow: 0 2px 4px 0 rgba(16, 107, 163, 0.2);
}
.btn-console-secondary {
background: #f1f5f9;
border: 1px solid #e2e8f0;
color: #334155;
border: 1px solid var(--border-precision);
color: var(--text-muted);
}
.btn-console-secondary:hover:not(:disabled) {
background: #e2e8f0;
color: #0f172a;
color: var(--text-main);
}
/* Premium clean console select dropdown styling */
.select-console {
display: inline-block;
background-color: #ffffff;
border: 1px solid #cbd5e1;
border: 1px solid var(--border-precision);
border-radius: 0.5rem; /* 8px */
padding: 0.5rem 1.75rem 0.5rem 0.625rem; /* padding-right leaves space for custom arrow */
color: #334155;
color: var(--text-main);
font-size: 0.75rem; /* text-xs */
font-weight: 500;
cursor: pointer;
@@ -116,13 +119,13 @@ body {
.select-console:hover:not(:disabled) {
border-color: #94a3b8;
color: #0f172a;
color: var(--text-main);
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
.select-console:focus {
border-color: #0284c7;
box-shadow: 0 0 0 1px #0284c7;
border-color: var(--accent-blueprint);
box-shadow: 0 0 0 1px var(--accent-blueprint);
}
.select-console:disabled {
@@ -130,5 +133,3 @@ body {
color: #94a3b8;
cursor: not-allowed;
}
+32
View File
@@ -172,3 +172,35 @@ export interface AgentTask {
created_at: string;
updated_at: string;
}
// ── 会话回退 (Rewind) ──
export interface RewindRequest {
n?: number; // 回退 N 个轮次
message_id?: number; // 或指定消息 ID
}
export interface RewindResponse {
rewound_count: number;
target_preview: string;
new_turn_index: number;
session_id: string;
}
export interface RestoreResponse {
restored_count: number;
session_id: string;
}
export interface BranchResponse {
branch_session_id: string;
forked_at_message_id: number;
copied_count: number;
}
export interface RetryResponse {
retried_message: string;
new_turn_index: number;
deleted_count: number;
session_id: string;
}