Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c2441464d |
@@ -14,6 +14,8 @@ backend/.env
|
||||
# 运行期生成的 SQLite 索引(vault 下的 Markdown 测试数据需提交)
|
||||
backend/data/*.db*
|
||||
backend/data/credentials/
|
||||
# 运行期导出的 HTML/PDF/DOCX 产物(不提交)
|
||||
backend/data/exports/
|
||||
# 阶段验收笔记(验收用,不提交)
|
||||
backend/data/vault/验收/
|
||||
# 本机 MCP 配置、授权状态及服务器工作目录不得提交。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 本文件用于团队开发期间快速配置环境和启动项目,不是正式的项目 README。
|
||||
|
||||
> 当前基线:2026-09-03。第一阶段 Web 联调前后端已经完成;第二阶段已完成 Workspace 去 Mock、Agent Trace 持久化与 SSE 恢复、stdio MCP Bridge、隔离 Plugin Host、Plugin Command/Settings,以及独立 MCP Server 配置中心 C.1(stdio、Streamable HTTP 与旧 SSE 兼容)。真实音频、Provider 协议增强、Benchmark、导出、主题包、Trace 可视化、Mermaid 与函数图像仍在后续开发;Tauri Host、Stronghold、原生多 Vault 文件系统和 Sync Server 尚未接入。
|
||||
> 当前基线:2026-09-03。第一阶段 Web 联调前后端已经完成;第二阶段已完成 Workspace 去 Mock、Agent Trace 持久化与 SSE 恢复、stdio MCP Bridge、隔离 Plugin Host、Plugin Command/Settings,以及独立 MCP Server 配置中心 C.1(stdio、Streamable HTTP 与旧 SSE 兼容)、RAG Benchmark 与 Markdown → HTML 导出。真实音频、Provider 协议增强、Agent Benchmark、PDF/DOCX 导出、主题包、Trace 可视化、Mermaid 与函数图像仍在后续开发;Tauri Host、Stronghold、原生多 Vault 文件系统和 Sync Server 尚未接入。
|
||||
|
||||
## 当前目录
|
||||
|
||||
@@ -118,7 +118,7 @@ cd frontend
|
||||
pnpm test
|
||||
```
|
||||
|
||||
当前回归基线为后端 218 项测试、前端 32 项测试,且 TypeScript 类型检查和生产构建通过。测试数量会随功能增长,以本地实际输出和 CI 为准。
|
||||
当前回归基线为后端 467 项测试、前端 32 项测试,且 TypeScript 类型检查和生产构建通过。测试数量会随功能增长,以本地实际输出和 CI 为准。
|
||||
|
||||
构建产物位于 `frontend/dist`,该目录不提交到 Git。
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ class Settings:
|
||||
vault_path: Path
|
||||
attachments_path: Path
|
||||
benchmark_datasets_path: Path
|
||||
exports_path: Path
|
||||
|
||||
|
||||
@lru_cache
|
||||
@@ -45,4 +46,5 @@ def get_settings() -> Settings:
|
||||
benchmark_datasets_path=Path(
|
||||
os.getenv("APP_BENCHMARK_DATASETS_PATH", str(data_dir / "benchmarks"))
|
||||
),
|
||||
exports_path=Path(os.getenv("APP_EXPORTS_PATH", str(data_dir / "exports"))),
|
||||
)
|
||||
|
||||
@@ -2,7 +2,14 @@ from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_validator
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
SecretStr,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
|
||||
|
||||
class Contract(BaseModel):
|
||||
@@ -993,8 +1000,6 @@ class TranscriptionJob(Contract):
|
||||
|
||||
|
||||
class IndexStatus(Contract):
|
||||
total_notes: int = 0
|
||||
total_blocks: int = 0
|
||||
status: Literal["idle", "queued", "running", "failed"] = "idle"
|
||||
pending_jobs: int = 0
|
||||
active_job_id: str | None = None
|
||||
@@ -1162,3 +1167,88 @@ class BenchmarkReport(Contract):
|
||||
cases: list[RAGCaseResult] = Field(default_factory=list)
|
||||
error: str | None = None
|
||||
error_code: str | None = None
|
||||
|
||||
|
||||
# Export(多格式文档导出)
|
||||
class ExportStatus(str, Enum):
|
||||
queued = "queued"
|
||||
running = "running"
|
||||
completed = "completed"
|
||||
failed = "failed"
|
||||
cancelled = "cancelled"
|
||||
|
||||
|
||||
class ExportFormat(str, Enum):
|
||||
html = "html"
|
||||
pdf = "pdf"
|
||||
docx = "docx"
|
||||
|
||||
|
||||
class ExportSourceType(str, Enum):
|
||||
note = "note"
|
||||
markdown = "markdown"
|
||||
|
||||
|
||||
class ExportSource(Contract):
|
||||
"""导出源:note 引用已索引笔记,markdown 用于未保存预览(不持久化)。"""
|
||||
|
||||
type: ExportSourceType
|
||||
note_id: str | None = None
|
||||
markdown: str | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_source(self) -> "ExportSource":
|
||||
if self.type == ExportSourceType.note and not self.note_id:
|
||||
raise ValueError("note source requires note_id")
|
||||
if self.type == ExportSourceType.markdown and not self.markdown:
|
||||
raise ValueError("markdown source requires markdown")
|
||||
return self
|
||||
|
||||
|
||||
class ExportOptions(Contract):
|
||||
theme_id: str = "light"
|
||||
include_title: bool = True
|
||||
include_metadata: bool = False
|
||||
page_size: str = "A4"
|
||||
code_theme: str = "github-light"
|
||||
|
||||
|
||||
class ExportRequest(Contract):
|
||||
source: ExportSource
|
||||
format: ExportFormat
|
||||
options: ExportOptions = Field(default_factory=ExportOptions)
|
||||
|
||||
|
||||
class ExportProgress(Contract):
|
||||
phase: str
|
||||
current: int
|
||||
total: int
|
||||
percent: float | None = None
|
||||
message: str | None = None
|
||||
|
||||
|
||||
class ExportFile(Contract):
|
||||
file_name: str
|
||||
mime_type: str
|
||||
size: int
|
||||
sha256: str
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
class ExportJob(Contract):
|
||||
job_id: str
|
||||
status: ExportStatus
|
||||
format: ExportFormat
|
||||
progress: ExportProgress | None = None
|
||||
file: ExportFile | None = None
|
||||
warnings: list[str] = Field(default_factory=list)
|
||||
error: str | None = None
|
||||
error_code: str | None = None
|
||||
created_at: datetime
|
||||
started_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
|
||||
|
||||
class ExportJobListResponse(Contract):
|
||||
items: list[ExportJob] = Field(default_factory=list)
|
||||
page: PageMeta = Field(default_factory=PageMeta)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Export Service:多格式文档导出(首批 HTML)。
|
||||
|
||||
模块划分:
|
||||
- document.py Document AST 内部协议 + DocumentExporter Protocol + ExportResult
|
||||
- markdown.py mistune → Document AST 解析
|
||||
- exporters/html.py HtmlExporter(Document AST → HTML5)
|
||||
- service.py 导出任务注册表、后台执行、取消与文件生命周期
|
||||
"""
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Document AST:导出器的内部中间表示(Internal Protocol,不放入 contracts.py)。
|
||||
|
||||
契约 §10.3 规定节点用稳定判别字段 node_id / type / attributes / children / text,
|
||||
类型专有信息统一放 attributes(如 heading 的 level、link 的 href、image 的 src)。
|
||||
导出器据此递归渲染,对无法表示的节点记 warning,不静默丢弃。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Protocol
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.contracts import ExportOptions
|
||||
|
||||
|
||||
class DocumentNode(BaseModel):
|
||||
"""递归文档节点;type 取契约 §10.3 首批 node type 之一。"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: str
|
||||
node_id: str
|
||||
attributes: dict[str, Any] = Field(default_factory=dict)
|
||||
children: list["DocumentNode"] = Field(default_factory=list)
|
||||
text: str = ""
|
||||
|
||||
|
||||
class Document(DocumentNode):
|
||||
"""根节点,type 固定为 document。"""
|
||||
|
||||
type: str = "document"
|
||||
|
||||
|
||||
class DocumentExporter(Protocol):
|
||||
"""导出器协议(契约 §10.3):把 Document AST 渲染为指定格式的产物。"""
|
||||
|
||||
async def export(self, document: Document, options: ExportOptions) -> "ExportResult": ...
|
||||
|
||||
|
||||
class ExportResult(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
content: bytes
|
||||
mime_type: str
|
||||
warnings: list[str] = Field(default_factory=list)
|
||||
@@ -0,0 +1 @@
|
||||
"""Export 渲染器:Document AST → 具体格式产物。"""
|
||||
@@ -0,0 +1,216 @@
|
||||
"""HtmlExporter:Document AST → 完整 HTML5 文档(内嵌基础 CSS)。
|
||||
|
||||
对无法静态表达的节点(mermaid / function_plot)渲染为占位代码块并记 warning,不静默丢失;
|
||||
严重内容缺失由 service 层以 EXPORT_UNSUPPORTED_CONTENT 判定,本层只负责逐节点渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from datetime import datetime
|
||||
|
||||
from app.contracts import ExportOptions
|
||||
from app.export.document import Document, DocumentNode, ExportResult
|
||||
|
||||
_MERMAID_WARNING = "mermaid 需前端渲染,已保留为占位代码块"
|
||||
_FUNCTION_PLOT_WARNING = "函数图像渲染将在后续版本提供,已保留为占位代码块"
|
||||
|
||||
_BASE_CSS = """
|
||||
body { margin: 0; background: #f6f7f9; color: #1f2328; font: 15px/1.7 -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; }
|
||||
article { max-width: 860px; margin: 0 auto; padding: 40px 48px; background: #fff; }
|
||||
article.theme-dark { background: #0d1117; color: #c9d1d9; }
|
||||
h1, h2, h3, h4, h5, h6 { line-height: 1.3; margin: 1.4em 0 0.6em; }
|
||||
h1.title { margin-top: 0; }
|
||||
p { margin: 0.6em 0; }
|
||||
a { color: #0969da; }
|
||||
code { font-family: 'JetBrains Mono', Consolas, monospace; font-size: 0.9em; background: #f0f1f3; padding: 0.15em 0.35em; border-radius: 3px; }
|
||||
pre { background: #f6f8fa; padding: 14px 16px; border-radius: 6px; overflow-x: auto; }
|
||||
pre.code-theme-github-dark { background: #0d1117; color: #c9d1d9; }
|
||||
pre code { background: none; padding: 0; }
|
||||
pre.mermaid, pre.function-plot { border: 1px dashed #d0d7de; }
|
||||
blockquote { margin: 0.8em 0; padding: 0.2em 1em; border-left: 4px solid #d0d7de; color: #57606a; }
|
||||
img { max-width: 100%; }
|
||||
table { border-collapse: collapse; margin: 0.8em 0; }
|
||||
th, td { border: 1px solid #d0d7de; padding: 6px 12px; }
|
||||
th { background: #f6f8fa; }
|
||||
dl.metadata { font-size: 0.85em; color: #57606a; border-top: 1px solid #eaeef2; border-bottom: 1px solid #eaeef2; padding: 0.6em 0; }
|
||||
dl.metadata dt { display: inline; font-weight: 600; margin-right: 0.4em; }
|
||||
dl.metadata dd { display: inline; margin: 0 1.2em 0 0; }
|
||||
.math, .math-block { overflow-x: auto; padding: 0.4em 0; }
|
||||
.task-list-item { list-style: none; }
|
||||
.task-list-item input { margin-right: 0.4em; }
|
||||
hr { border: none; border-top: 1px solid #d0d7de; margin: 1.4em 0; }
|
||||
""".strip()
|
||||
|
||||
|
||||
class HtmlExporter:
|
||||
"""实现 DocumentExporter:递归渲染 Document AST 为完整 HTML5 文档。"""
|
||||
|
||||
async def export(self, document: Document, options: ExportOptions) -> ExportResult:
|
||||
self._options = options
|
||||
warnings: list[str] = []
|
||||
body = self._render_children(document.children, warnings)
|
||||
content = self._assemble(document, options, body, warnings)
|
||||
return ExportResult(
|
||||
content=content.encode("utf-8"), mime_type="text/html", warnings=warnings
|
||||
)
|
||||
|
||||
def _assemble(
|
||||
self, document: Document, options: ExportOptions, body: str, warnings: list[str]
|
||||
) -> str:
|
||||
title = str(document.attributes.get("title") or "")
|
||||
parts = [
|
||||
"<!doctype html>",
|
||||
'<html lang="zh-CN">',
|
||||
"<head>",
|
||||
'<meta charset="utf-8">',
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
||||
]
|
||||
if title:
|
||||
parts.append(f"<title>{html.escape(title)}</title>")
|
||||
parts.append(f"<style>{_BASE_CSS}</style>")
|
||||
parts.append("</head>")
|
||||
parts.append("<body>")
|
||||
parts.append(f'<article class="theme-{html.escape(options.theme_id)}">')
|
||||
if options.include_title and title:
|
||||
parts.append(f'<h1 class="title">{html.escape(title)}</h1>')
|
||||
if options.include_metadata:
|
||||
metadata = document.attributes.get("metadata")
|
||||
if metadata:
|
||||
parts.append(self._render_metadata(metadata))
|
||||
parts.append(body)
|
||||
parts.append("</article>")
|
||||
parts.append("</body>")
|
||||
parts.append("</html>")
|
||||
return "\n".join(parts) + "\n"
|
||||
|
||||
def _render_metadata(self, metadata: dict) -> str:
|
||||
entries = ["<dl", ' class="metadata">']
|
||||
for key, value in metadata.items():
|
||||
entries.append(f"<dt>{html.escape(str(key))}</dt>")
|
||||
entries.append(f"<dd>{html.escape(self._fmt_meta_value(value))}</dd>")
|
||||
entries.append("</dl>")
|
||||
return "".join(entries)
|
||||
|
||||
@staticmethod
|
||||
def _fmt_meta_value(value: object) -> str:
|
||||
if isinstance(value, datetime):
|
||||
return value.isoformat()
|
||||
if isinstance(value, list):
|
||||
return ", ".join(str(item) for item in value)
|
||||
return str(value)
|
||||
|
||||
def _render_children(self, children: list[DocumentNode], warnings: list[str]) -> str:
|
||||
return "".join(self._render_node(child, warnings) for child in children)
|
||||
|
||||
def _render_node(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
handler = getattr(self, f"_render_{node.type}", None)
|
||||
if handler is not None:
|
||||
return handler(node, warnings)
|
||||
warnings.append(f"无法表示的节点类型已跳过:{node.type}")
|
||||
return ""
|
||||
|
||||
# --- 块级 ---
|
||||
def _render_heading(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
level = max(1, min(6, int(node.attributes.get("level", 1))))
|
||||
return f"<h{level}>{self._render_children(node.children, warnings)}</h{level}>"
|
||||
|
||||
def _render_paragraph(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"<p>{self._render_children(node.children, warnings)}</p>"
|
||||
|
||||
def _render_blockquote(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"<blockquote>{self._render_children(node.children, warnings)}</blockquote>"
|
||||
|
||||
def _render_list(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
tag = "ol" if node.attributes.get("ordered") else "ul"
|
||||
return f"<{tag}>{self._render_children(node.children, warnings)}</{tag}>"
|
||||
|
||||
def _render_list_item(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
inner = self._render_children(node.children, warnings)
|
||||
if node.attributes.get("task"):
|
||||
checked = " checked" if node.attributes.get("checked") else ""
|
||||
return (
|
||||
'<li class="task-list-item">'
|
||||
f'<input type="checkbox" disabled{checked}>{inner}</li>'
|
||||
)
|
||||
return f"<li>{inner}</li>"
|
||||
|
||||
def _render_table(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
rows = node.children
|
||||
head_rows = [r for r in rows if r.attributes.get("head")]
|
||||
body_rows = [r for r in rows if not r.attributes.get("head")]
|
||||
parts = ["<table>"]
|
||||
if head_rows:
|
||||
parts.append("<thead>")
|
||||
parts.extend(self._render_node(r, warnings) for r in head_rows)
|
||||
parts.append("</thead>")
|
||||
if body_rows:
|
||||
parts.append("<tbody>")
|
||||
parts.extend(self._render_node(r, warnings) for r in body_rows)
|
||||
parts.append("</tbody>")
|
||||
parts.append("</table>")
|
||||
return "".join(parts)
|
||||
|
||||
def _render_table_row(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"<tr>{self._render_children(node.children, warnings)}</tr>"
|
||||
|
||||
def _render_table_cell(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
tag = "th" if node.attributes.get("head") else "td"
|
||||
return f"<{tag}>{self._render_children(node.children, warnings)}</{tag}>"
|
||||
|
||||
def _render_code_block(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
lang = str(node.attributes.get("language") or "")
|
||||
code = html.escape(node.text)
|
||||
lang_cls = f' class="language-{html.escape(lang)}"' if lang else ""
|
||||
theme = html.escape(self._options.code_theme)
|
||||
return f'<pre class="code-theme-{theme}"><code{lang_cls}>{code}</code></pre>'
|
||||
|
||||
def _render_thematic_break(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return "<hr>"
|
||||
|
||||
def _render_mermaid(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
warnings.append(_MERMAID_WARNING)
|
||||
return f'<pre class="mermaid">{html.escape(node.text)}</pre>'
|
||||
|
||||
def _render_function_plot(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
warnings.append(_FUNCTION_PLOT_WARNING)
|
||||
return f'<pre class="function-plot">{html.escape(node.text)}</pre>'
|
||||
|
||||
def _render_math_block(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f'<div class="math-block">$${html.escape(node.text)}$$</div>'
|
||||
|
||||
# --- 行内 ---
|
||||
def _render_text(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return html.escape(node.text)
|
||||
|
||||
def _render_emphasis(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"<em>{self._render_children(node.children, warnings)}</em>"
|
||||
|
||||
def _render_strong(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"<strong>{self._render_children(node.children, warnings)}</strong>"
|
||||
|
||||
def _render_link(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
href = html.escape(str(node.attributes.get("href") or ""))
|
||||
title = str(node.attributes.get("title") or "")
|
||||
attrs = [f'href="{href}"']
|
||||
if title:
|
||||
attrs.append(f'title="{html.escape(title)}"')
|
||||
return f"<a {' '.join(attrs)}>{self._render_children(node.children, warnings)}</a>"
|
||||
|
||||
def _render_codespan(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"<code>{html.escape(node.text)}</code>"
|
||||
|
||||
def _render_image(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
src = html.escape(str(node.attributes.get("src") or ""))
|
||||
alt = html.escape(str(node.attributes.get("alt") or ""))
|
||||
title = str(node.attributes.get("title") or "")
|
||||
attrs = [f'src="{src}"', f'alt="{alt}"']
|
||||
if title:
|
||||
attrs.append(f'title="{html.escape(title)}"')
|
||||
return f"<img {' '.join(attrs)}>"
|
||||
|
||||
def _render_math_inline(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return f"\\({html.escape(node.text)}\\)"
|
||||
|
||||
def _render_linebreak(self, node: DocumentNode, warnings: list[str]) -> str:
|
||||
return "<br>"
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Markdown → Document AST:用 mistune 的 ast renderer 产出通用 token,再映射为内部节点。
|
||||
|
||||
选用 mistune 内置 'ast' renderer 而非自写 BaseRenderer,是因为 mistune 的行内渲染按
|
||||
字符串拼接、无法承载结构化子节点;ast renderer 直接给出带 children/attrs/raw 的 token
|
||||
树,映射层只做 token → DocumentNode 的搬运,不掺入任何 HTML。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import mistune
|
||||
|
||||
from app.export.document import Document, DocumentNode
|
||||
|
||||
_PLUGINS = ["table", "math", "url", "task_lists"]
|
||||
|
||||
# fenced code 语言分流:命中则转为专用节点,其余按普通代码块
|
||||
_MERMAID_LANG = "mermaid"
|
||||
_FUNCTION_PLOT_LANGS = {"function_plot", "functionplot"}
|
||||
|
||||
|
||||
def parse_document(markdown: str) -> Document:
|
||||
"""把 Markdown 文本解析为 Document AST 根节点。"""
|
||||
renderer = mistune.create_markdown(renderer="ast", plugins=_PLUGINS)
|
||||
tokens = renderer(markdown)
|
||||
mapper = _AstMapper()
|
||||
return Document(node_id=mapper.next_id(), children=mapper.map_blocks(tokens))
|
||||
|
||||
|
||||
class _AstMapper:
|
||||
"""token 树 → DocumentNode 树的映射器;node_id 按遍历顺序递增,无需跨请求稳定。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._seq = 0
|
||||
|
||||
def next_id(self) -> str:
|
||||
self._seq += 1
|
||||
return f"node_{self._seq:03d}"
|
||||
|
||||
def map_blocks(self, tokens: list[dict]) -> list[DocumentNode]:
|
||||
nodes: list[DocumentNode] = []
|
||||
for token in tokens:
|
||||
node = self.map_block(token)
|
||||
if node is not None:
|
||||
nodes.append(node)
|
||||
return nodes
|
||||
|
||||
def map_block(self, token: dict) -> DocumentNode | None:
|
||||
kind = token["type"]
|
||||
if kind == "heading":
|
||||
return DocumentNode(
|
||||
type="heading",
|
||||
node_id=self.next_id(),
|
||||
attributes={"level": token["attrs"]["level"]},
|
||||
children=self.map_inline(token.get("children", [])),
|
||||
)
|
||||
if kind in ("paragraph", "block_text"):
|
||||
# block_text 是列表项内的段落块,仍按 paragraph 表达,由 list_item 包裹
|
||||
return DocumentNode(
|
||||
type="paragraph",
|
||||
node_id=self.next_id(),
|
||||
children=self.map_inline(token.get("children", [])),
|
||||
)
|
||||
if kind == "list":
|
||||
return DocumentNode(
|
||||
type="list",
|
||||
node_id=self.next_id(),
|
||||
attributes={"ordered": bool(token.get("attrs", {}).get("ordered"))},
|
||||
children=[self.map_list_item(child) for child in token.get("children", [])],
|
||||
)
|
||||
if kind == "block_code":
|
||||
return self._map_code(token)
|
||||
if kind == "block_quote":
|
||||
return DocumentNode(
|
||||
type="blockquote",
|
||||
node_id=self.next_id(),
|
||||
children=self.map_blocks(token.get("children", [])),
|
||||
)
|
||||
if kind == "table":
|
||||
return self._map_table(token)
|
||||
if kind == "block_math":
|
||||
return DocumentNode(
|
||||
type="math_block", node_id=self.next_id(), text=token.get("raw", "")
|
||||
)
|
||||
if kind == "thematic_break":
|
||||
return DocumentNode(type="thematic_break", node_id=self.next_id())
|
||||
if kind == "blank_line":
|
||||
return None
|
||||
# 未知块级 token(如 block_html)保守保留原文,避免静默丢失
|
||||
raw = token.get("raw", "")
|
||||
if raw:
|
||||
return DocumentNode(type="paragraph", node_id=self.next_id(), text=raw)
|
||||
return None
|
||||
|
||||
def map_list_item(self, token: dict) -> DocumentNode:
|
||||
"""列表项:block_text 展平为行内子节点,嵌套 list 保留为子节点。"""
|
||||
attributes: dict = {}
|
||||
if token["type"] == "task_list_item":
|
||||
attributes = {"task": True, "checked": bool(token.get("attrs", {}).get("checked"))}
|
||||
children: list[DocumentNode] = []
|
||||
for child in token.get("children", []):
|
||||
if child["type"] == "block_text":
|
||||
children.extend(self.map_inline(child.get("children", [])))
|
||||
elif child["type"] == "list":
|
||||
children.append(self.map_block(child))
|
||||
else:
|
||||
node = self.map_block(child)
|
||||
if node is not None:
|
||||
children.append(node)
|
||||
return DocumentNode(
|
||||
type="list_item", node_id=self.next_id(), attributes=attributes, children=children
|
||||
)
|
||||
|
||||
def map_inline(self, tokens: list[dict]) -> list[DocumentNode]:
|
||||
nodes: list[DocumentNode] = []
|
||||
for token in tokens:
|
||||
node = self.map_inline_token(token)
|
||||
if node is not None:
|
||||
nodes.append(node)
|
||||
return nodes
|
||||
|
||||
def map_inline_token(self, token: dict) -> DocumentNode | None:
|
||||
kind = token["type"]
|
||||
if kind == "text":
|
||||
return DocumentNode(type="text", node_id=self.next_id(), text=token.get("raw", ""))
|
||||
if kind == "strong":
|
||||
return DocumentNode(
|
||||
type="strong", node_id=self.next_id(),
|
||||
children=self.map_inline(token.get("children", [])),
|
||||
)
|
||||
if kind == "emphasis":
|
||||
return DocumentNode(
|
||||
type="emphasis", node_id=self.next_id(),
|
||||
children=self.map_inline(token.get("children", [])),
|
||||
)
|
||||
if kind == "link":
|
||||
attrs = token.get("attrs", {})
|
||||
attributes = {"href": attrs.get("url", "")}
|
||||
if attrs.get("title"):
|
||||
attributes["title"] = attrs["title"]
|
||||
return DocumentNode(
|
||||
type="link", node_id=self.next_id(), attributes=attributes,
|
||||
children=self.map_inline(token.get("children", [])),
|
||||
)
|
||||
if kind == "codespan":
|
||||
return DocumentNode(type="codespan", node_id=self.next_id(), text=token.get("raw", ""))
|
||||
if kind == "image":
|
||||
attrs = token.get("attrs", {})
|
||||
attributes = {"src": attrs.get("src", "")}
|
||||
if attrs.get("alt"):
|
||||
attributes["alt"] = attrs["alt"]
|
||||
if attrs.get("title"):
|
||||
attributes["title"] = attrs["title"]
|
||||
return DocumentNode(type="image", node_id=self.next_id(), attributes=attributes)
|
||||
if kind == "inline_math":
|
||||
return DocumentNode(
|
||||
type="math_inline", node_id=self.next_id(), text=token.get("raw", "")
|
||||
)
|
||||
if kind == "softbreak":
|
||||
# HTML 中换行会折叠为空白,软换行按空格表达
|
||||
return DocumentNode(type="text", node_id=self.next_id(), text=" ")
|
||||
if kind == "linebreak":
|
||||
return DocumentNode(type="linebreak", node_id=self.next_id())
|
||||
# 未知行内 token 保守保留原文
|
||||
raw = token.get("raw", "")
|
||||
if raw:
|
||||
return DocumentNode(type="text", node_id=self.next_id(), text=raw)
|
||||
return None
|
||||
|
||||
def _map_code(self, token: dict) -> DocumentNode:
|
||||
info = (token.get("attrs", {}).get("info") or "").strip()
|
||||
lang = info.split()[0].lower() if info else ""
|
||||
code = token.get("raw", "").rstrip("\n")
|
||||
if lang == _MERMAID_LANG:
|
||||
return DocumentNode(type="mermaid", node_id=self.next_id(), text=code)
|
||||
if lang in _FUNCTION_PLOT_LANGS:
|
||||
return DocumentNode(type="function_plot", node_id=self.next_id(), text=code)
|
||||
attributes = {"language": lang} if lang else {}
|
||||
return DocumentNode(
|
||||
type="code_block", node_id=self.next_id(), attributes=attributes, text=code
|
||||
)
|
||||
|
||||
def _map_table(self, token: dict) -> DocumentNode:
|
||||
rows: list[DocumentNode] = []
|
||||
for child in token.get("children", []):
|
||||
if child["type"] == "table_head":
|
||||
rows.append(self._map_table_row(child, head=True))
|
||||
elif child["type"] == "table_body":
|
||||
for row in child.get("children", []):
|
||||
if row["type"] == "table_row":
|
||||
rows.append(self._map_table_row(row, head=False))
|
||||
elif child["type"] == "table_row":
|
||||
rows.append(self._map_table_row(child, head=False))
|
||||
return DocumentNode(type="table", node_id=self.next_id(), children=rows)
|
||||
|
||||
def _map_table_row(self, token: dict, *, head: bool) -> DocumentNode:
|
||||
cells: list[DocumentNode] = []
|
||||
for cell in token.get("children", []):
|
||||
if cell["type"] != "table_cell":
|
||||
continue
|
||||
attrs = cell.get("attrs", {})
|
||||
cell_attributes = {"head": bool(attrs.get("head", head))}
|
||||
if attrs.get("align"):
|
||||
cell_attributes["align"] = attrs["align"]
|
||||
cells.append(
|
||||
DocumentNode(
|
||||
type="table_cell",
|
||||
node_id=self.next_id(),
|
||||
attributes=cell_attributes,
|
||||
children=self.map_inline(cell.get("children", [])),
|
||||
)
|
||||
)
|
||||
return DocumentNode(
|
||||
type="table_row", node_id=self.next_id(), attributes={"head": head}, children=cells
|
||||
)
|
||||
@@ -0,0 +1,272 @@
|
||||
"""Export 服务:任务注册表、后台渲染、取消与产物生命周期。
|
||||
|
||||
与 Benchmark 一致采用「创建即返回 queued、后台 Task 异步执行」的内存模型:任务与产物
|
||||
暂存内存与 exports 目录,不持久化到 SQLite。导出是单阶段渲染,无 SSE 事件流,取消主要
|
||||
在渲染前/后让出执行权的边界生效;产物带 24h 过期时间,过期后不可下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from app.config import get_settings
|
||||
from app.contracts import (
|
||||
ExportFile,
|
||||
ExportFormat,
|
||||
ExportJob,
|
||||
ExportOptions,
|
||||
ExportProgress,
|
||||
ExportRequest,
|
||||
ExportSource,
|
||||
ExportSourceType,
|
||||
ExportStatus,
|
||||
)
|
||||
from app.errors import ApiError
|
||||
from app.export.document import Document
|
||||
from app.export.exporters.html import HtmlExporter
|
||||
from app.export.markdown import parse_document
|
||||
from app.services import note_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_jobs: dict[str, ExportJob] = {}
|
||||
_tasks: dict[str, asyncio.Task] = {}
|
||||
_cancel_flags: dict[str, asyncio.Event] = {}
|
||||
MAX_JOBS = 100
|
||||
# markdown 源大小上限,防止未保存预览塞爆内存/产物
|
||||
MAX_MARKDOWN_CHARS = 200_000
|
||||
# 产物有效期
|
||||
FILE_TTL = timedelta(hours=24)
|
||||
|
||||
_INVALID_FILE_CHARS = re.compile(r'[\\/:*?"<>|]')
|
||||
|
||||
|
||||
class ExportCancelled(Exception):
|
||||
"""导出在渲染前被取消时抛出,用于标记 cancelled。"""
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _safe_download_name(title: str) -> str:
|
||||
"""清洗标题得到安全的下载文件名;空标题回退到 export。"""
|
||||
name = _INVALID_FILE_CHARS.sub("_", title).strip() or "export"
|
||||
return name[:80]
|
||||
|
||||
|
||||
def _forget(job_id: str) -> None:
|
||||
_jobs.pop(job_id, None)
|
||||
_tasks.pop(job_id, None)
|
||||
_cancel_flags.pop(job_id, None)
|
||||
|
||||
|
||||
def _evict_terminal() -> bool:
|
||||
"""超过容量时淘汰最旧的终态任务;全为活动任务无法淘汰时返回 False。"""
|
||||
terminal = (ExportStatus.completed, ExportStatus.failed, ExportStatus.cancelled)
|
||||
while len(_jobs) >= MAX_JOBS:
|
||||
victim = next((jid for jid, job in _jobs.items() if job.status in terminal), None)
|
||||
if victim is None:
|
||||
return False
|
||||
_forget(victim)
|
||||
return True
|
||||
|
||||
|
||||
async def _resolve_source(source: ExportSource) -> tuple[str, str, dict | None]:
|
||||
"""把导出源解析为 (markdown, title, metadata);metadata 仅 note 源提供。"""
|
||||
if source.type == ExportSourceType.note:
|
||||
note = await note_service.get_note(source.note_id)
|
||||
if note is None:
|
||||
raise ApiError(
|
||||
404,
|
||||
"EXPORT_SOURCE_NOT_FOUND",
|
||||
"note not found",
|
||||
{"note_id": source.note_id},
|
||||
)
|
||||
metadata = {
|
||||
"file_path": note.file_path,
|
||||
"tags": note.tags,
|
||||
"created_at": note.created_at,
|
||||
"updated_at": note.updated_at,
|
||||
}
|
||||
return note.markdown, note.title, metadata
|
||||
|
||||
markdown = source.markdown or ""
|
||||
if not markdown.strip():
|
||||
raise ApiError(400, "EXPORT_OPTIONS_INVALID", "markdown source must not be empty")
|
||||
if len(markdown) > MAX_MARKDOWN_CHARS:
|
||||
raise ApiError(
|
||||
400,
|
||||
"EXPORT_OPTIONS_INVALID",
|
||||
f"markdown source exceeds {MAX_MARKDOWN_CHARS} characters",
|
||||
{"size": len(markdown), "limit": MAX_MARKDOWN_CHARS},
|
||||
)
|
||||
return markdown, "", None
|
||||
|
||||
|
||||
async def create_export(request: ExportRequest) -> ExportJob:
|
||||
"""创建导出任务,立即返回 queued 的 ExportJob,由后台 Task 渲染。"""
|
||||
if request.format != ExportFormat.html:
|
||||
raise ApiError(
|
||||
400,
|
||||
"EXPORT_FORMAT_UNSUPPORTED",
|
||||
"PDF/DOCX 暂未实现,当前仅支持 HTML",
|
||||
{"format": request.format.value},
|
||||
)
|
||||
markdown, title, metadata = await _resolve_source(request.source)
|
||||
|
||||
if not _evict_terminal():
|
||||
raise ApiError(
|
||||
429,
|
||||
"EXPORT_CAPACITY_EXCEEDED",
|
||||
"Export capacity exceeded; wait for active jobs to finish.",
|
||||
{},
|
||||
)
|
||||
|
||||
job_id = "export_" + uuid4().hex[:12]
|
||||
job = ExportJob(
|
||||
job_id=job_id,
|
||||
status=ExportStatus.queued,
|
||||
format=request.format,
|
||||
created_at=_now(),
|
||||
)
|
||||
_jobs[job_id] = job
|
||||
_cancel_flags[job_id] = asyncio.Event()
|
||||
_tasks[job_id] = asyncio.create_task(
|
||||
_execute(job_id, markdown, title, metadata, request.options)
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
async def _execute(
|
||||
job_id: str,
|
||||
markdown: str,
|
||||
title: str,
|
||||
metadata: dict | None,
|
||||
options: ExportOptions,
|
||||
) -> None:
|
||||
"""后台渲染:解析 → 导出 → 写文件 → 挂载产物元信息。"""
|
||||
cancel_event = _cancel_flags[job_id]
|
||||
_jobs[job_id] = _jobs[job_id].model_copy(
|
||||
update={
|
||||
"status": ExportStatus.running,
|
||||
"started_at": _now(),
|
||||
"progress": ExportProgress(phase="rendering", current=0, total=1, percent=0.0),
|
||||
}
|
||||
)
|
||||
try:
|
||||
# 让出一次,使「创建后立即取消」的 queued 任务能及时进入 cancelled
|
||||
await asyncio.sleep(0)
|
||||
if cancel_event.is_set():
|
||||
raise ExportCancelled()
|
||||
|
||||
document = parse_document(markdown)
|
||||
document.attributes["title"] = title
|
||||
if metadata:
|
||||
document.attributes["metadata"] = metadata
|
||||
|
||||
exporter = HtmlExporter()
|
||||
result = await exporter.export(document, options)
|
||||
if cancel_event.is_set():
|
||||
raise ExportCancelled()
|
||||
|
||||
out_dir = get_settings().exports_path
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = out_dir / f"{job_id}.html"
|
||||
path.write_bytes(result.content)
|
||||
|
||||
completed_at = _now()
|
||||
_jobs[job_id] = _jobs[job_id].model_copy(
|
||||
update={
|
||||
"status": ExportStatus.completed,
|
||||
"progress": ExportProgress(
|
||||
phase="completed", current=1, total=1, percent=1.0
|
||||
),
|
||||
"file": ExportFile(
|
||||
file_name=f"{_safe_download_name(title)}.html",
|
||||
mime_type=result.mime_type,
|
||||
size=len(result.content),
|
||||
sha256=hashlib.sha256(result.content).hexdigest(),
|
||||
expires_at=completed_at + FILE_TTL,
|
||||
),
|
||||
"warnings": result.warnings,
|
||||
"completed_at": completed_at,
|
||||
}
|
||||
)
|
||||
except ExportCancelled:
|
||||
_jobs[job_id] = _jobs[job_id].model_copy(
|
||||
update={
|
||||
"status": ExportStatus.cancelled,
|
||||
"completed_at": _now(),
|
||||
}
|
||||
)
|
||||
except Exception as exc: # 渲染失败不拖垮服务,只记日志与项目错误码
|
||||
logger.exception("Export failed: job_id=%s", job_id)
|
||||
_jobs[job_id] = _jobs[job_id].model_copy(
|
||||
update={
|
||||
"status": ExportStatus.failed,
|
||||
"error": "Export render failed.",
|
||||
"error_code": "EXPORT_RENDER_FAILED",
|
||||
"completed_at": _now(),
|
||||
}
|
||||
)
|
||||
finally:
|
||||
_cancel_flags.pop(job_id, None)
|
||||
|
||||
|
||||
def list_exports(
|
||||
status: ExportStatus | None = None,
|
||||
format: ExportFormat | None = None,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
) -> tuple[list[ExportJob], int]:
|
||||
jobs = list(_jobs.values())
|
||||
if status is not None:
|
||||
jobs = [j for j in jobs if j.status == status]
|
||||
if format is not None:
|
||||
jobs = [j for j in jobs if j.format == format]
|
||||
jobs.sort(key=lambda j: j.created_at, reverse=True)
|
||||
total = len(jobs)
|
||||
return jobs[offset : offset + limit], total
|
||||
|
||||
|
||||
def get_export(job_id: str) -> ExportJob | None:
|
||||
return _jobs.get(job_id)
|
||||
|
||||
|
||||
def cancel_export(job_id: str) -> ExportJob | None:
|
||||
"""取消导出:仅 queued/running 可取消,后台 Task 在让出边界标记 cancelled。"""
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
return None
|
||||
if job.status in (ExportStatus.queued, ExportStatus.running):
|
||||
_cancel_flags[job_id].set()
|
||||
return job
|
||||
|
||||
|
||||
def get_export_file(job_id: str) -> Path:
|
||||
"""返回可下载产物的存储路径;未完成返回 404、过期返回 410。"""
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise ApiError(404, "EXPORT_JOB_NOT_FOUND", "export job not found", {"job_id": job_id})
|
||||
if job.status != ExportStatus.completed or job.file is None:
|
||||
raise ApiError(
|
||||
404, "EXPORT_JOB_NOT_FOUND", "export file not ready", {"job_id": job_id}
|
||||
)
|
||||
if job.file.expires_at <= _now():
|
||||
raise ApiError(410, "EXPORT_FILE_EXPIRED", "export file has expired", {"job_id": job_id})
|
||||
return get_settings().exports_path / f"{job_id}.html"
|
||||
|
||||
|
||||
async def wait_for_export(job_id: str) -> ExportJob | None:
|
||||
"""等待后台任务结束(测试/轮询用);无任务时直接返回当前状态。"""
|
||||
task = _tasks.get(job_id)
|
||||
if task is not None:
|
||||
await task
|
||||
return _jobs.get(job_id)
|
||||
+85
-8
@@ -5,7 +5,7 @@ from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Header, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
|
||||
from app.agent import AgentCapacityError, AgentRunNotFoundError
|
||||
from app.container import container
|
||||
@@ -48,6 +48,11 @@ from app.contracts import (
|
||||
ModelRoutingResponse,
|
||||
SpeakerMatchRequest,
|
||||
SpeakerMatchResult,
|
||||
ExportFormat,
|
||||
ExportJob,
|
||||
ExportJobListResponse,
|
||||
ExportRequest,
|
||||
ExportStatus,
|
||||
Note,
|
||||
NoteCreateRequest,
|
||||
NoteListResponse,
|
||||
@@ -96,8 +101,10 @@ from app.contracts import (
|
||||
from app.agent import AgentCapacityError, AgentRunNotFoundError
|
||||
from app.benchmarks import datasets as benchmark_datasets
|
||||
from app.benchmarks import service as benchmark_service
|
||||
from app.config import get_settings
|
||||
from app.container import container
|
||||
from app.errors import ApiError
|
||||
from app.export import service as export_service
|
||||
from app.extensions import ExtensionError
|
||||
from app.extensions.mcp_registry import McpRegistryError
|
||||
from app.providers.base import ProviderError
|
||||
@@ -120,13 +127,6 @@ from app.services.attachment_service import attachment_path
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
|
||||
@router.get("/permissions/policy", tags=["Permissions"])
|
||||
async def get_permission_policy() -> dict[str, str]:
|
||||
from app.agent.permissions import KNOWN_PERMISSIONS
|
||||
return {permission: container.permissions.policy.mode_for(permission).value
|
||||
for permission in sorted(KNOWN_PERMISSIONS)}
|
||||
|
||||
|
||||
async def mcp_call_async(operation):
|
||||
"""Even registry reads can wait on lifecycle locks; keep all MCP work off the event loop."""
|
||||
try:
|
||||
@@ -1317,3 +1317,80 @@ async def get_benchmark_report(run_id: str) -> BenchmarkReport:
|
||||
404, "BENCHMARK_RUN_NOT_FOUND", "benchmark report not found", {"run_id": run_id}
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
@router.post(
|
||||
"/exports",
|
||||
response_model=ExportJob,
|
||||
status_code=202,
|
||||
tags=["Export"],
|
||||
)
|
||||
async def create_export(request: ExportRequest) -> ExportJob:
|
||||
return await export_service.create_export(request)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/exports",
|
||||
response_model=ExportJobListResponse,
|
||||
tags=["Export"],
|
||||
)
|
||||
async def list_exports(
|
||||
status: ExportStatus | None = Query(default=None),
|
||||
format: ExportFormat | None = Query(default=None),
|
||||
limit: int = Query(default=50, ge=1, le=200),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
) -> ExportJobListResponse:
|
||||
items, total = export_service.list_exports(
|
||||
status=status, format=format, limit=limit, offset=offset
|
||||
)
|
||||
return ExportJobListResponse(
|
||||
items=items, page=PageMeta(total=total, limit=limit, offset=offset)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/exports/{job_id}",
|
||||
response_model=ExportJob,
|
||||
tags=["Export"],
|
||||
)
|
||||
async def get_export(job_id: str) -> ExportJob:
|
||||
job = export_service.get_export(job_id)
|
||||
if job is None:
|
||||
raise ApiError(
|
||||
404, "EXPORT_JOB_NOT_FOUND", "export job not found", {"job_id": job_id}
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
@router.get(
|
||||
"/exports/{job_id}/file",
|
||||
tags=["Export"],
|
||||
)
|
||||
async def get_export_file(job_id: str) -> FileResponse:
|
||||
path = export_service.get_export_file(job_id) # 未完成/过期分别抛 404/410
|
||||
job = export_service.get_export(job_id)
|
||||
if job is None or job.file is None:
|
||||
raise ApiError(
|
||||
404, "EXPORT_JOB_NOT_FOUND", "export file not ready", {"job_id": job_id}
|
||||
)
|
||||
return FileResponse(
|
||||
path=path,
|
||||
media_type=job.file.mime_type,
|
||||
filename=job.file.file_name,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/exports/{job_id}/cancel",
|
||||
response_model=OperationResponse,
|
||||
tags=["Export"],
|
||||
)
|
||||
async def cancel_export(job_id: str) -> OperationResponse:
|
||||
job = export_service.cancel_export(job_id)
|
||||
if job is None:
|
||||
raise ApiError(
|
||||
404, "EXPORT_JOB_NOT_FOUND", "export job not found", {"job_id": job_id}
|
||||
)
|
||||
return OperationResponse(
|
||||
status="accepted", resource_id=job_id, message="Export cancellation accepted."
|
||||
)
|
||||
|
||||
@@ -126,12 +126,9 @@ async def rebuild(request: IndexRebuildRequest) -> IndexJob:
|
||||
|
||||
|
||||
def get_status() -> IndexStatus:
|
||||
counts = repository.stats()
|
||||
if _active_job_id is not None:
|
||||
return IndexStatus(status="running", pending_jobs=0, active_job_id=_active_job_id,
|
||||
total_notes=counts["notes"], total_blocks=counts["blocks"])
|
||||
return IndexStatus(status="running", pending_jobs=0, active_job_id=_active_job_id)
|
||||
return IndexStatus(
|
||||
total_notes=counts["notes"], total_blocks=counts["blocks"],
|
||||
status="failed" if _last_error else "idle",
|
||||
pending_jobs=0,
|
||||
last_completed_at=_last_completed_at,
|
||||
|
||||
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"fastapi>=0.116,<1.0",
|
||||
"httpx>=0.28,<1.0",
|
||||
"jsonschema>=4.25,<5.0",
|
||||
"mistune>=3.0,<4.0",
|
||||
"pyyaml>=6.0,<7.0",
|
||||
"referencing>=0.36,<1.0",
|
||||
"sqlite-vec>=0.1.9",
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Export Service 的单元与端到端测试。
|
||||
|
||||
沿用 conftest 隔离机制:APP_DATA_DIR / DB / Vault / exports 目录都落在临时目录,
|
||||
不读写真实数据。导出采用「创建即 queued + 后台 Task 执行」的异步模型,测试在同一
|
||||
事件循环内创建并等待后台任务结束,得到终态 ExportJob 后再断言。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.config import get_settings
|
||||
from app.contracts import (
|
||||
ExportFormat,
|
||||
ExportOptions,
|
||||
ExportRequest,
|
||||
ExportSource,
|
||||
ExportSourceType,
|
||||
ExportStatus,
|
||||
)
|
||||
from app.errors import ApiError
|
||||
from app.export import service as export_service
|
||||
from app.export.exporters.html import HtmlExporter
|
||||
from app.export.markdown import parse_document
|
||||
|
||||
MD = """# 进程调度
|
||||
|
||||
一些 **加粗** 和 *斜体*,[链接](https://a.b) 与 `code`。
|
||||
|
||||
- 项目一
|
||||
- 项目二
|
||||
|
||||
```python
|
||||
print(1)
|
||||
```
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
```
|
||||
|
||||
```function_plot
|
||||
y = x
|
||||
```
|
||||
|
||||
| a | b |
|
||||
|---|---|
|
||||
| 1 | 2 |
|
||||
|
||||
行内 $x^2$ 与块级
|
||||
$$
|
||||
y = mx + b
|
||||
$$
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_export_state():
|
||||
"""清空内存注册表,避免跨用例的任务/取消标志互相污染。"""
|
||||
export_service._jobs.clear()
|
||||
export_service._tasks.clear()
|
||||
export_service._cancel_flags.clear()
|
||||
yield
|
||||
export_service._jobs.clear()
|
||||
export_service._tasks.clear()
|
||||
export_service._cancel_flags.clear()
|
||||
|
||||
|
||||
def _create_and_wait(request: ExportRequest) -> object:
|
||||
"""创建导出并在同一事件循环内等待后台任务结束,返回终态 ExportJob。"""
|
||||
|
||||
async def _execute():
|
||||
job = await export_service.create_export(request)
|
||||
return await export_service.wait_for_export(job.job_id)
|
||||
|
||||
return asyncio.run(_execute())
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# markdown → Document AST
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _types(nodes) -> list[str]:
|
||||
return [n.type for n in nodes]
|
||||
|
||||
|
||||
def test_parse_document_heading_and_inline() -> None:
|
||||
doc = parse_document("# 标题\n\n一段 **加粗** 和 [链接](https://a.b)。")
|
||||
|
||||
assert doc.type == "document"
|
||||
heading = doc.children[0]
|
||||
assert heading.type == "heading"
|
||||
assert heading.attributes["level"] == 1
|
||||
|
||||
para = doc.children[1]
|
||||
assert para.type == "paragraph"
|
||||
kinds = _types(para.children)
|
||||
assert "text" in kinds
|
||||
assert "strong" in kinds
|
||||
assert "link" in kinds
|
||||
|
||||
link = next(c for c in para.children if c.type == "link")
|
||||
assert link.attributes["href"] == "https://a.b"
|
||||
|
||||
|
||||
def test_parse_document_list_and_code_fencing() -> None:
|
||||
doc = parse_document("- a\n- b\n\n```mermaid\ngraph LR\n```\n\n```function_plot\ny=x\n```\n\n```python\nx\n```")
|
||||
|
||||
kinds = [c.type for c in doc.children]
|
||||
assert kinds[0] == "list"
|
||||
assert kinds[1] == "mermaid"
|
||||
assert kinds[2] == "function_plot"
|
||||
assert kinds[3] == "code_block"
|
||||
|
||||
code = doc.children[3]
|
||||
assert code.attributes["language"] == "python"
|
||||
assert code.text == "x"
|
||||
|
||||
|
||||
def test_parse_document_table_and_math() -> None:
|
||||
doc = parse_document("| a | b |\n|---|---|\n| 1 | 2 |\n\n$x^2$\n\n$$\ny=mx\n$$")
|
||||
|
||||
table = doc.children[0]
|
||||
assert table.type == "table"
|
||||
assert table.children[0].type == "table_row"
|
||||
assert table.children[0].children[0].attributes["head"] is True
|
||||
|
||||
# 表格后是「行内数学所在段落」与「块级数学」
|
||||
kinds = [c.type for c in doc.children[1:]]
|
||||
assert "paragraph" in kinds
|
||||
assert "math_block" in kinds
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# HtmlExporter
|
||||
# --------------------------------------------------------------------------- #
|
||||
async def _render(markdown: str, *, title: str = "") -> str:
|
||||
doc = parse_document(markdown)
|
||||
doc.attributes["title"] = title
|
||||
result = await HtmlExporter().export(doc, ExportOptions())
|
||||
return result.content.decode("utf-8")
|
||||
|
||||
|
||||
def test_html_exporter_renders_basic_nodes_and_escapes() -> None:
|
||||
html = asyncio.run(_render("# 标题\n\n**加粗** [链接](https://a.b) 与 <b>原始</b>。"))
|
||||
|
||||
assert "<h1>标题</h1>" in html
|
||||
assert "<strong>加粗</strong>" in html
|
||||
assert '<a href="https://a.b">链接</a>' in html
|
||||
# 原始 HTML 必须被转义,不能注入文档
|
||||
assert "<b>原始</b>" in html
|
||||
assert "<b>原始</b>" not in html
|
||||
|
||||
|
||||
def test_html_exporter_marks_mermaid_and_function_plot() -> None:
|
||||
result = asyncio.run(HtmlExporter().export(parse_document("```mermaid\ngraph LR\n```"), ExportOptions()))
|
||||
|
||||
html = result.content.decode("utf-8")
|
||||
assert '<pre class="mermaid">graph LR</pre>' in html
|
||||
assert any("mermaid" in w for w in result.warnings)
|
||||
|
||||
|
||||
def test_html_exporter_include_title_and_metadata() -> None:
|
||||
doc = parse_document("正文")
|
||||
doc.attributes["title"] = "操作系统复习"
|
||||
doc.attributes["metadata"] = {"tags": ["os", "复习"]}
|
||||
|
||||
opts = ExportOptions(include_title=True, include_metadata=True)
|
||||
result = asyncio.run(HtmlExporter().export(doc, opts))
|
||||
html = result.content.decode("utf-8")
|
||||
|
||||
assert '<h1 class="title">操作系统复习</h1>' in html
|
||||
assert "os, 复习" in html
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ExportService
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _markdown_request(markdown: str, *, format: ExportFormat = ExportFormat.html) -> ExportRequest:
|
||||
return ExportRequest(
|
||||
source=ExportSource(type=ExportSourceType.markdown, markdown=markdown),
|
||||
format=format,
|
||||
)
|
||||
|
||||
|
||||
def test_export_markdown_source_completes_and_writes_file() -> None:
|
||||
finished = _create_and_wait(_markdown_request(MD))
|
||||
|
||||
assert finished.status == ExportStatus.completed
|
||||
assert finished.file is not None
|
||||
assert finished.file.mime_type == "text/html"
|
||||
assert finished.file.size > 0
|
||||
assert len(finished.file.sha256) == 64
|
||||
|
||||
path = get_settings().exports_path / f"{finished.job_id}.html"
|
||||
assert path.exists()
|
||||
content = path.read_text(encoding="utf-8")
|
||||
assert "进程调度" in content
|
||||
|
||||
|
||||
def test_export_note_source_resolves_title_and_metadata() -> None:
|
||||
from app.services import note_service
|
||||
|
||||
async def _go():
|
||||
note = await note_service.create_note(
|
||||
title="操作系统复习", markdown="# 进程调度\n\n内容。", folder="导出", tags=["os"]
|
||||
)
|
||||
request = ExportRequest(
|
||||
source=ExportSource(type=ExportSourceType.note, note_id=note.note_id),
|
||||
format=ExportFormat.html,
|
||||
options=ExportOptions(include_metadata=True),
|
||||
)
|
||||
job = await export_service.create_export(request)
|
||||
return await export_service.wait_for_export(job.job_id)
|
||||
|
||||
finished = asyncio.run(_go())
|
||||
assert finished.status == ExportStatus.completed
|
||||
assert finished.file is not None
|
||||
assert finished.file.file_name == "操作系统复习.html"
|
||||
content = (get_settings().exports_path / f"{finished.job_id}.html").read_text(encoding="utf-8")
|
||||
assert "操作系统复习" in content
|
||||
assert "进程调度" in content
|
||||
|
||||
|
||||
def test_export_pdf_unsupported() -> None:
|
||||
with pytest.raises(ApiError) as exc:
|
||||
asyncio.run(
|
||||
export_service.create_export(_markdown_request("# x", format=ExportFormat.pdf))
|
||||
)
|
||||
assert exc.value.status_code == 400
|
||||
assert exc.value.code == "EXPORT_FORMAT_UNSUPPORTED"
|
||||
|
||||
|
||||
def test_export_unknown_note_404() -> None:
|
||||
request = ExportRequest(
|
||||
source=ExportSource(type=ExportSourceType.note, note_id="note_missing"),
|
||||
format=ExportFormat.html,
|
||||
)
|
||||
with pytest.raises(ApiError) as exc:
|
||||
asyncio.run(export_service.create_export(request))
|
||||
assert exc.value.status_code == 404
|
||||
assert exc.value.code == "EXPORT_SOURCE_NOT_FOUND"
|
||||
|
||||
|
||||
def test_export_empty_markdown_invalid() -> None:
|
||||
with pytest.raises(ApiError) as exc:
|
||||
asyncio.run(export_service.create_export(_markdown_request(" ")))
|
||||
assert exc.value.status_code == 400
|
||||
assert exc.value.code == "EXPORT_OPTIONS_INVALID"
|
||||
|
||||
|
||||
def test_export_cancel_queued_job() -> None:
|
||||
async def _go():
|
||||
job = await export_service.create_export(_markdown_request("# x"))
|
||||
cancelled = export_service.cancel_export(job.job_id)
|
||||
assert cancelled is not None
|
||||
return await export_service.wait_for_export(job.job_id)
|
||||
|
||||
finished = asyncio.run(_go())
|
||||
assert finished.status == ExportStatus.cancelled
|
||||
assert finished.file is None
|
||||
|
||||
|
||||
def test_export_file_expired_410() -> None:
|
||||
async def _go():
|
||||
job = await export_service.create_export(_markdown_request("# x"))
|
||||
finished = await export_service.wait_for_export(job.job_id)
|
||||
past = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||
export_service._jobs[job.job_id] = finished.model_copy(
|
||||
update={"file": finished.file.model_copy(update={"expires_at": past})}
|
||||
)
|
||||
return job.job_id
|
||||
|
||||
job_id = asyncio.run(_go())
|
||||
with pytest.raises(ApiError) as exc:
|
||||
export_service.get_export_file(job_id)
|
||||
assert exc.value.status_code == 410
|
||||
assert exc.value.code == "EXPORT_FILE_EXPIRED"
|
||||
|
||||
|
||||
def test_export_list_and_get() -> None:
|
||||
finished = _create_and_wait(_markdown_request("# 列表测试"))
|
||||
|
||||
items, total = export_service.list_exports(limit=50, offset=0)
|
||||
assert total == 1
|
||||
assert items[0].job_id == finished.job_id
|
||||
|
||||
got = export_service.get_export(finished.job_id)
|
||||
assert got is not None and got.status == ExportStatus.completed
|
||||
|
||||
assert export_service.get_export("export_missing") is None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 契约校验
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_export_source_requires_matching_field() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
ExportSource(type=ExportSourceType.note, note_id=None)
|
||||
with pytest.raises(ValidationError):
|
||||
ExportSource(type=ExportSourceType.markdown, markdown=None)
|
||||
@@ -1,31 +0,0 @@
|
||||
import asyncio
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
from app.container import container
|
||||
from app.agent.permissions import PermissionMode
|
||||
from app.services.note_service import create_note
|
||||
|
||||
|
||||
def test_index_status_returns_real_counts():
|
||||
with TestClient(app) as client:
|
||||
initial = client.get('/api/index/status').json()
|
||||
assert (initial['total_notes'], initial['total_blocks']) == (0, 0)
|
||||
note = asyncio.run(create_note(title='Real note', markdown='# Real note\n\ncontent', folder=None, tags=[]))
|
||||
result = client.get('/api/index/status').json()
|
||||
assert result['total_notes'] == 1
|
||||
assert result['total_blocks'] == len(note.blocks)
|
||||
|
||||
|
||||
def test_permissions_endpoint_reads_effective_backend_policy():
|
||||
policy = container.permissions.policy
|
||||
original = policy.mode_for('attachments.read')
|
||||
try:
|
||||
policy.set_rule('attachments.read', PermissionMode.deny)
|
||||
with TestClient(app) as client:
|
||||
response = client.get('/api/permissions/policy')
|
||||
assert response.status_code == 200
|
||||
assert response.json()['attachments.read'] == 'deny'
|
||||
finally:
|
||||
policy.set_rule('attachments.read', original)
|
||||
Generated
+11
@@ -364,6 +364,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mistune"
|
||||
version = "3.3.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7b/92/328a294a6de83bacb95bed01f04e0eaff4e3616ee359fc821a5dfc539b02/mistune-3.3.4.tar.gz", hash = "sha256:58b5c96d6fcb61190dfe5fae498d2b2065f99cf61e9649418fd54cf1ada86dfe", size = 121426, upload-time = "2026-07-22T05:22:30.89Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/77/e4/288365afae98953bc01de09f686f40d8ee84578135aa7767d5d4e60b5278/mistune-3.3.4-py3-none-any.whl", hash = "sha256:ee015381e955e370962968befe1d729ab60fafb6a715ac6751763fbce38c8d4a", size = 66862, upload-time = "2026-07-22T05:22:29.419Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notes-agent-backend"
|
||||
version = "0.1.0"
|
||||
@@ -373,6 +382,7 @@ dependencies = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "jsonschema" },
|
||||
{ name = "mistune" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "referencing" },
|
||||
{ name = "sqlite-vec" },
|
||||
@@ -390,6 +400,7 @@ requires-dist = [
|
||||
{ name = "fastapi", specifier = ">=0.116,<1.0" },
|
||||
{ name = "httpx", specifier = ">=0.28,<1.0" },
|
||||
{ name = "jsonschema", specifier = ">=4.25,<5.0" },
|
||||
{ name = "mistune", specifier = ">=3.0,<4.0" },
|
||||
{ name = "pyyaml", specifier = ">=6.0,<7.0" },
|
||||
{ name = "referencing", specifier = ">=0.36,<1.0" },
|
||||
{ name = "sqlite-vec", specifier = ">=0.1.9" },
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
- [AI Core 与 Agent Core 开发说明](development/AI-Core与Agent-Core开发说明.md)
|
||||
- [Knowledge 与 Retrieval Core 开发说明](development/Knowledge与Retrieval-Core开发说明.md)
|
||||
- [Benchmark 开发说明](development/Benchmark开发说明.md)
|
||||
- [Export 开发说明](development/Export开发说明.md)
|
||||
- [模型提供商与模型发现开发说明](development/模型提供商与模型发现开发说明.md)
|
||||
- [MCP Bridge 与 Plugin Host 开发说明](development/MCP-Bridge与Plugin-Host开发说明.md)
|
||||
- [独立 MCP Server 配置中心开发说明](development/独立MCP-Server配置中心开发说明.md)
|
||||
|
||||
@@ -2354,7 +2354,7 @@ Quality
|
||||
└── Retrieval 参数调优
|
||||
|
||||
Content Output
|
||||
├── Markdown → HTML / PDF / DOCX
|
||||
├── Markdown → HTML(已实现)/ PDF / DOCX(暂缓)
|
||||
├── Mermaid 编辑、预览与静态导出
|
||||
└── Function Plot 解析、预览与静态导出
|
||||
|
||||
@@ -2365,7 +2365,7 @@ Frontend Extension
|
||||
└── Plugin Settings UI
|
||||
```
|
||||
|
||||
上述列表描述第二阶段技术范围,其中 stdio MCP Bridge、Plugin Command Contribution 和 Plugin Settings Contribution 后端 Contract 已实现,其余能力以各自开发说明的状态为准。每项功能必须继续经过现有 Service、Contract、Permission 和 Adapter 边界,不因 Demo 需要在 Vue 组件、Router 或 Agent Runtime 中直接绑定第三方协议。
|
||||
上述列表描述第二阶段技术范围,其中 stdio MCP Bridge、Plugin Command Contribution、Plugin Settings Contribution 后端 Contract 与 Markdown → HTML 导出已实现,其余能力以各自开发说明的状态为准。每项功能必须继续经过现有 Service、Contract、Permission 和 Adapter 边界,不因 Demo 需要在 Vue 组件、Router 或 Agent Runtime 中直接绑定第三方协议。
|
||||
|
||||
第三阶段处理:
|
||||
|
||||
|
||||
@@ -190,9 +190,3 @@ RunCancelled
|
||||
- 接入业务模块时保持当前路径和 Contract,不在 Router 中直接实现数据库、Provider 或 Agent 逻辑。
|
||||
|
||||
第二阶段开发保持本文件中已有路径兼容,并按 `第二阶段接口契约-开发版.md` 增加子资源、可选字段和事件。接口完成后先更新 OpenAPI 与本文件,再将第二阶段文档中的状态改为已实现。
|
||||
|
||||
|
||||
### 前端真实状态补充(2026-09-04)
|
||||
|
||||
- `GET /api/index/status` 额外返回 `total_notes: int` 和 `total_blocks: int`,来自当前 SQLite 索引;未建立内容索引时为 0。
|
||||
- `GET /api/permissions/policy` 返回 `Record<string, "allow" | "confirm" | "deny">`,值取自后端当前生效的 PermissionPolicy。此接口只读,不提供全局修改能力,运行时权限确认仍使用既有 Agent permission endpoint。
|
||||
|
||||
@@ -66,11 +66,11 @@
|
||||
| Benchmark | POST | `/api/benchmarks/agent/runs` | 暂缓 | 创建 Agent Benchmark(依赖 Agent Runtime 完成后交付) |
|
||||
| Benchmark | GET | `/api/benchmarks/runs` | 已实现 | 分页获取 Benchmark Run |
|
||||
| Benchmark | GET/POST | `/api/benchmarks/runs/{run_id}/*` | 计划新增 | 查询、订阅、取消和读取报告 |
|
||||
| Export | POST | `/api/exports` | 计划新增 | 创建 HTML/PDF/DOCX 导出任务 |
|
||||
| Export | GET | `/api/exports` | 计划新增 | 分页获取导出任务 |
|
||||
| Export | GET | `/api/exports/{job_id}` | 计划新增 | 查询导出任务 |
|
||||
| Export | GET | `/api/exports/{job_id}/file` | 计划新增 | 下载已完成产物 |
|
||||
| Export | POST | `/api/exports/{job_id}/cancel` | 计划新增 | 取消导出任务 |
|
||||
| Export | POST | `/api/exports` | 已实现(HTML) | 创建导出任务;`pdf`/`docx` 暂缓,返回 `EXPORT_FORMAT_UNSUPPORTED` |
|
||||
| Export | GET | `/api/exports` | 已实现(HTML) | 分页获取导出任务 |
|
||||
| Export | GET | `/api/exports/{job_id}` | 已实现(HTML) | 查询导出任务 |
|
||||
| Export | GET | `/api/exports/{job_id}/file` | 已实现(HTML) | 下载已完成产物 |
|
||||
| Export | POST | `/api/exports/{job_id}/cancel` | 已实现(HTML) | 取消导出任务 |
|
||||
| Theme | Host Contract | `ThemePackageService` | 计划新增 | 导入、预览、启停和卸载主题包 |
|
||||
| Renderer | 内部 Contract | `StaticRenderer` | 计划新增 | Mermaid/Function Plot 预览和导出复用 |
|
||||
|
||||
@@ -1078,6 +1078,8 @@ VECTOR_INDEX_REBUILD_REQUIRED
|
||||
|
||||
## 10. Export Service
|
||||
|
||||
> 实现状态:HTML 导出已实现(`backend/app/export/`),`pdf`/`docx` 暂缓——请求这两个格式返回 `EXPORT_FORMAT_UNSUPPORTED`。函数图像与 Mermaid 在 HTML 中以占位代码块保留并记 warning,静态渲染由 §10.4 的 Render Contract 在后续 PR 补齐。
|
||||
|
||||
### 10.1 创建导出任务
|
||||
|
||||
`POST /api/exports`,返回 `202 ExportJob`。
|
||||
@@ -1088,7 +1090,7 @@ VECTOR_INDEX_REBUILD_REQUIRED
|
||||
"type": "note",
|
||||
"note_id": "note_123"
|
||||
},
|
||||
"format": "pdf",
|
||||
"format": "html",
|
||||
"options": {
|
||||
"theme_id": "light",
|
||||
"include_title": true,
|
||||
@@ -1099,7 +1101,7 @@ VECTOR_INDEX_REBUILD_REQUIRED
|
||||
}
|
||||
```
|
||||
|
||||
`source.type` 首批支持 `note` 和 `markdown`。`markdown` 来源用于尚未保存的预览,字段大小受限且不持久化到 Trace。`format` 固定为 `html`、`pdf`、`docx`。
|
||||
`source.type` 首批支持 `note` 和 `markdown`。`note` 来源通过 `source.note_id` 引用已建索引笔记;`markdown` 来源用于尚未保存的预览,内容放在 `source.markdown` 字段,大小限制为 200 000 字符、不持久化到 Trace。`format` 可取 `html`、`pdf`、`docx`,但当前仅 `html` 已实现,`pdf`/`docx` 返回 `EXPORT_FORMAT_UNSUPPORTED`。
|
||||
|
||||
响应:
|
||||
|
||||
@@ -1107,11 +1109,12 @@ VECTOR_INDEX_REBUILD_REQUIRED
|
||||
{
|
||||
"job_id": "export_123",
|
||||
"status": "queued",
|
||||
"format": "pdf",
|
||||
"format": "html",
|
||||
"progress": null,
|
||||
"file": null,
|
||||
"warnings": [],
|
||||
"error": null,
|
||||
"error_code": null,
|
||||
"created_at": "2026-08-31T10:30:00Z",
|
||||
"started_at": null,
|
||||
"completed_at": null
|
||||
@@ -1127,14 +1130,14 @@ VECTOR_INDEX_REBUILD_REQUIRED
|
||||
| POST | `/api/exports/{job_id}/cancel` | `OperationResponse` |
|
||||
| GET | `/api/exports/{job_id}/file` | 文件流 |
|
||||
|
||||
下载响应设置正确 `Content-Type`、经过清理的 `Content-Disposition` 文件名和 `Content-Length`。未完成、失败或过期 Job 不返回空文件。
|
||||
下载响应设置正确 `Content-Type`、经过清理的 `Content-Disposition` 文件名和 `Content-Length`。未完成、失败或过期的 Job 不返回空文件:未完成/失败返回 `EXPORT_JOB_NOT_FOUND`(404),产物过期(超过 `expires_at`)返回 `EXPORT_FILE_EXPIRED`(410)。
|
||||
|
||||
完成 Job 的 file:
|
||||
|
||||
```json
|
||||
{
|
||||
"file_name": "操作系统复习.pdf",
|
||||
"mime_type": "application/pdf",
|
||||
"file_name": "操作系统复习.html",
|
||||
"mime_type": "text/html",
|
||||
"size": 1048576,
|
||||
"sha256": "...",
|
||||
"expires_at": "2026-09-01T10:30:00Z"
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Export 开发说明
|
||||
|
||||
> 所属模块:Export Service(后端,负责人 yxx)。本次交付「多格式文档导出」第一步:Markdown → HTML 的完整生命周期;PDF/DOCX 与函数图像静态渲染在后续 PR 补齐。契约对应 [第二阶段接口契约 §10](../contracts/第二阶段接口契约-开发版.md)。
|
||||
|
||||
## 定位
|
||||
|
||||
Export Service 把笔记或未保存的 Markdown 文本渲染为可下载的 HTML 文件。采用与 Benchmark 一致的「创建即返回 queued、后台 asyncio.Task 执行」的内存模型,产物带 24h 过期时间,过期后不可下载。导出是轮询式(无 SSE 事件流),客户端通过 `GET /api/exports/{job_id}` 轮询状态,完成后走 `GET /api/exports/{job_id}/file` 下载。
|
||||
|
||||
## 模块布局
|
||||
|
||||
```text
|
||||
backend/app/export/
|
||||
├── __init__.py 包说明
|
||||
├── document.py Document AST 内部协议 + DocumentExporter Protocol + ExportResult
|
||||
├── markdown.py mistune 'ast' renderer → Document AST
|
||||
├── exporters/
|
||||
│ ├── __init__.py
|
||||
│ └── html.py HtmlExporter(Document AST → 完整 HTML5)
|
||||
└── service.py ExportService(注册表 + 后台渲染 + 取消 + 产物生命周期)
|
||||
```
|
||||
|
||||
HTTP DTO(`ExportStatus` / `ExportFormat` / `ExportSource` / `ExportOptions` / `ExportJob` 等)放在 [app/contracts.py](../../backend/app/contracts.py),与 Benchmark DTO 同层;`DocumentNode` / `ExportResult` 属导出器内部协议,放在 `export/document.py`,不进入 HTTP 契约。
|
||||
|
||||
## 接口
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/exports` | 创建导出任务(202) |
|
||||
| GET | `/api/exports?status=&format=&limit=&offset=` | 分页获取任务 |
|
||||
| GET | `/api/exports/{job_id}` | 查询任务状态 |
|
||||
| GET | `/api/exports/{job_id}/file` | 下载已完成产物 |
|
||||
| POST | `/api/exports/{job_id}/cancel` | 取消任务 |
|
||||
|
||||
`source.type` 支持 `note`(引用已建索引笔记)与 `markdown`(未保存预览,字段为 `source.markdown`,上限 200 000 字符)。当前仅 `format=html` 实现,`pdf`/`docx` 返回 `EXPORT_FORMAT_UNSUPPORTED`。
|
||||
|
||||
## Markdown → Document AST
|
||||
|
||||
解析用 [mistune](https://github.com/lepture/mistune) 的内置 `renderer="ast"`(非自写 `BaseRenderer`),因为 mistune 的行内渲染按字符串拼接、无法承载结构化子节点;ast renderer 直接给出带 `children`/`attrs`/`raw` 的 token 树,`_AstMapper` 只做 token → `DocumentNode` 的搬运,不掺入任何 HTML。插件启用 `table`、`math`、`url`、`task_lists`。
|
||||
|
||||
fenced code 按语言分流:`mermaid` → `mermaid` 节点、`function_plot`/`functionplot` → `function_plot` 节点,其余 → `code_block`(`attributes.language`)。`node_id` 按遍历顺序 `node_{seq:03d}` 生成,仅渲染内部使用,无需跨请求稳定。
|
||||
|
||||
## HtmlExporter
|
||||
|
||||
递归渲染 Document AST 为完整 HTML5 文档(`<!doctype html>` + `<head>` 内嵌基础 CSS + `<body>`),标题/正文/元信息文本一律 `html.escape`。`mermaid` 与 `function_plot` 无法静态表达,渲染为占位 `<pre class="mermaid">`/`<pre class="function-plot">` 并记 warning,不静默丢失;`code_theme` 仅作为代码容器 class,不引入 JS 高亮库。无法表示的节点统一 `warnings.append(...)` 跳过。
|
||||
|
||||
## 运行生命周期
|
||||
|
||||
`queued → running → completed | failed | cancelled`。
|
||||
|
||||
- 创建时校验:`format` 非 html → `EXPORT_FORMAT_UNSUPPORTED`;`note` 源不存在 → `EXPORT_SOURCE_NOT_FOUND`(404);`markdown` 源为空或超上限 → `EXPORT_OPTIONS_INVALID`。
|
||||
- 内存注册表上限 `MAX_JOBS=100`,超限只淘汰终态任务;满容量且全为活动任务时返回 `EXPORT_CAPACITY_EXCEEDED`(429)。
|
||||
- 后台渲染在解析前后各让出一次执行权,使「创建后立即取消」的 queued 任务能及时进入 cancelled。
|
||||
- 失败只向公开响应暴露项目错误码与安全消息,详细异常进入日志。
|
||||
|
||||
## 产物生命周期
|
||||
|
||||
产物写入 `settings.exports_path`(默认 `backend/data/exports/`,可通过 `APP_EXPORTS_PATH` 覆盖,已加入 `.gitignore`),文件名为 `{job_id}.html`,下载 `Content-Disposition` 用 `_safe_download_name` 清洗标题得到。`ExportFile` 记录 `sha256`、`size` 与 `expires_at`(`completed_at + 24h`),过期返回 `EXPORT_FILE_EXPIRED`(410)。
|
||||
|
||||
## 错误码
|
||||
|
||||
```text
|
||||
EXPORT_SOURCE_NOT_FOUND 404
|
||||
EXPORT_FORMAT_UNSUPPORTED 400
|
||||
EXPORT_OPTIONS_INVALID 400
|
||||
EXPORT_RENDER_FAILED 500
|
||||
EXPORT_UNSUPPORTED_CONTENT 422
|
||||
EXPORT_JOB_NOT_FOUND 404
|
||||
EXPORT_FILE_EXPIRED 410
|
||||
EXPORT_CAPACITY_EXCEEDED 429
|
||||
```
|
||||
|
||||
## 测试
|
||||
|
||||
```powershell
|
||||
cd backend
|
||||
uv run pytest -q
|
||||
```
|
||||
|
||||
`tests/test_export.py` 覆盖 Markdown 解析(标题/行内/列表/代码分流/表格/数学)、HTML 渲染(标签 + 转义 + warning)、Service 端到端(note 源与 markdown 源、pdf 拒绝、未知 note、取消、list/get、过期 410)与 `ExportSource` 契约校验。
|
||||
|
||||
## 范围外(后续 PR)
|
||||
|
||||
- PDF / DOCX 导出(`python-docx` 等底层库在 PoC 后冻结,封装在 Exporter Adapter 内)。
|
||||
- 函数图像绘制(FunctionPlot 结构化模型 + 白名单表达式解析器 + SVG 静态渲染,契约 §10.4/§12)。
|
||||
- 代码语法高亮(当前仅 CSS class 占位)。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 前端壳子与接口层开发说明
|
||||
|
||||
> 更新日期:2026-09-04
|
||||
> 更新日期:2026-09-02
|
||||
> 适用范围:Vue 3 + TypeScript 页面、Workspace、公共 Service、FastAPI 接口适配和 SSE。
|
||||
> 文档用途:帮助团队理解当前前端可用能力、模块边界、启动方式和后续页面开发入口。
|
||||
|
||||
@@ -153,7 +153,12 @@ Service 已适配当前 FastAPI Contract:
|
||||
- 识别 `Done`、`RunCompleted`、`RunFailed` 和 `RunCancelled`;
|
||||
- 支持 AbortController 主动取消。
|
||||
|
||||
Chat Store 使用真实 `/api/chat` SSE。提供商从后端配置加载,前端不展示后端内置测试 Provider,也不预选模拟模型;模型 ID 使用所选提供商保存的默认值,并支持手动输入。
|
||||
Chat Store 已从定时器模拟输出切换为真实 `/api/chat` SSE。默认离线联调配置为:
|
||||
|
||||
```text
|
||||
provider_id = mock
|
||||
model = mock-1
|
||||
```
|
||||
|
||||
## 8. 环境和启动
|
||||
|
||||
@@ -202,34 +207,3 @@ Vite 当前会提示 Chat 与 Workspace 的部分异步 Chunk 超过 500 kB,
|
||||
- Workspace 接入 Tauri 后,需要增加路径规范化、写入失败恢复和外部修改冲突测试;
|
||||
- 页面新增交互必须经过键盘、空状态、加载状态、错误状态和窄窗口检查;
|
||||
- Workspace 的 Milkdown 写作模式与 CodeMirror 源码模式共享同一 Markdown 数据源;后续修改编辑器时不得改变 Store/Service 边界,并必须保留文件切换、自动保存和选区格式化回归测试。
|
||||
|
||||
|
||||
## 阶段 F 前:前端真实数据清理
|
||||
|
||||
已删除运行时的聊天示例、Agent Run/Event/Tool/权限示例、Provider/Model、Task、Skill、Plugin、IndexStatus 常量和 searchMock。测试文件中的隔离桩保留,仅用于自动化验证。
|
||||
|
||||
- 所有业务 Store 从空集合开始,由真实 API 填充;连接失败显示错误,不回退演示记录。
|
||||
- 普通聊天仅显示用户实际输入和 SSE 响应;当前会话列表保留在页面会话内,刷新后清空,后端暂无聊天历史持久化接口。切换会话保留本次会话内的真实消息,取消旧流并屏蔽迟到回调。
|
||||
- 聊天页移除尚未接入的知识库与 Skill 开关,知识库工具和 Skill 通过 Agent 使用。
|
||||
- 设置页不再伪造健康状态、版本、42 篇笔记/318 个 Block、模型名称和索引能力开关。状态未获取时显示 unknown/未获取;应用版本来自 package.json,后端版本来自 /api/status。
|
||||
- GET /api/index/status 增加 total_notes、total_blocks,直接读取 SQLite 的当前索引统计。
|
||||
- GET /api/permissions/policy 返回 PermissionPolicy 的实际生效值。设置页只读展示;全局策略编辑暂未开放,运行权限确认仍走原有 Agent 接口。
|
||||
- 删除模拟重启成功逻辑,说明 Web 端不具备进程重启能力;索引页面只保留后端已实现的全量重建。
|
||||
- Task DTO 不再填充后端未返回的优先级和来源,Agent Token 用量不再把未知输入/输出拆分填成 0。
|
||||
- Plugin/Skill/Provider 无记录时显示空状态,模型发现失败时允许使用真实的手动模型 ID。
|
||||
|
||||
验证:前端 81 项测试、类型检查与生产构建通过;后端 454 项测试通过。新增测试覆盖空初始状态、离线错误、真实统计与权限、测试 Provider 过滤、真实聊天历史及旧流隔离。本次未调用真实付费推理 API。
|
||||
|
||||
### MCP 工具中文展示补充
|
||||
|
||||
Agent 工具列表按 `mcp.<server_id>.<remote_name>` 的远程工具名匹配中文展示,支持 `web_search`(网页搜索)、`understand_image`(图像理解),并补充 `text.uppercase`(文本转大写)。此映射只影响界面,工具调用与权限选择仍使用完整原始 ID。
|
||||
|
||||
卡片默认显示三行摘要,完整服务原文可展开查看,展开操作不会改变工具选择。服务已提供中文说明时优先保留;未收录的 MCP 工具明确提示暂无中文说明,不将本地摘要当作服务协议或自动翻译结果。原始说明及其中的参数规则完整保留。
|
||||
|
||||
验证:前端 84 项测试、类型检查与生产构建通过。新增回归覆盖不同服务器命名空间、未知工具、服务中文说明、原文完整性,以及选择工具时保留原始 ID。
|
||||
|
||||
### 聊天模型选择审阅修复
|
||||
|
||||
返回聊天页时保留仍启用的提供商与手动模型 ID,仅刷新其模型列表;未选择、已删除或已禁用的提供商才回退到默认值。提供商加载失败时保留当前选择并展示错误。新增页面重新挂载与异常分支回归,前端共 89 项测试通过。
|
||||
|
||||
补充卸载时序修复:提供商或技能加载期间离开聊天页后,旧页面的初始化回调不再修改聊天选择,迟到错误也不再更新旧页面。两种加载延迟均通过先失败、修复后通过的回归测试,并验证返回页面后的默认模型和发送按钮状态;前端共 91 项测试通过。
|
||||
|
||||
@@ -39,12 +39,11 @@ const saveStatusColor = computed(() => {
|
||||
|
||||
const indexStatusText = computed(() => {
|
||||
const s = settingsStore.indexStatus.status
|
||||
return s === 'unknown' ? '索引状态未获取' : s === 'idle' ? '索引就绪' : s === 'indexing' ? `索引中 (${settingsStore.indexStatus.pending_jobs})` : '索引错误'
|
||||
return s === 'idle' ? '索引就绪' : s === 'indexing' ? `索引中 (${settingsStore.indexStatus.pending_jobs})` : '索引错误'
|
||||
})
|
||||
|
||||
const aiCoreStatusText = computed(() => {
|
||||
const map: Record<string, string> = {
|
||||
unknown: 'AI Core 状态未获取',
|
||||
starting: 'AI Core 启动中',
|
||||
running: 'AI Core 运行中',
|
||||
stopped: 'AI Core 已停止',
|
||||
|
||||
@@ -207,8 +207,8 @@ export interface PermissionRequest {
|
||||
}
|
||||
|
||||
export interface TokenUsage {
|
||||
input_tokens?: number
|
||||
output_tokens?: number
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
total_tokens: number
|
||||
}
|
||||
|
||||
@@ -462,11 +462,11 @@ export interface TaskItem {
|
||||
title: string
|
||||
description?: string
|
||||
status: TaskStatus
|
||||
priority?: TaskPriority
|
||||
priority: TaskPriority
|
||||
due_date?: string
|
||||
note_id?: string
|
||||
note_title?: string
|
||||
source?: TaskSource
|
||||
source: TaskSource
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -487,12 +487,12 @@ export interface ThemeConfig {
|
||||
// ============ Index ============
|
||||
|
||||
export interface IndexStatus {
|
||||
status: 'unknown' | 'idle' | 'indexing' | 'error'
|
||||
status: 'idle' | 'indexing' | 'error'
|
||||
pending_jobs: number
|
||||
total_notes: number | null
|
||||
total_blocks: number | null
|
||||
fts_enabled?: boolean
|
||||
vector_enabled?: boolean
|
||||
total_notes: number
|
||||
total_blocks: number
|
||||
fts_enabled: boolean
|
||||
vector_enabled: boolean
|
||||
embedding_model?: string
|
||||
reranker_model?: string
|
||||
last_indexed_at?: string
|
||||
@@ -527,7 +527,7 @@ export type SaveStatus =
|
||||
| 'external_changed'
|
||||
| 'conflict'
|
||||
|
||||
export type AiCoreStatus = 'unknown' | 'starting' | 'running' | 'stopped' | 'error'
|
||||
export type AiCoreStatus = 'starting' | 'running' | 'stopped' | 'error'
|
||||
|
||||
// ============ FastAPI wire contracts ============
|
||||
// UI view models above may contain presentation-only fields. Services must use
|
||||
@@ -777,8 +777,6 @@ export interface ApiTask {
|
||||
}
|
||||
|
||||
export interface ApiIndexStatus {
|
||||
total_notes: number
|
||||
total_blocks: number
|
||||
status: 'idle' | 'queued' | 'running' | 'failed'
|
||||
pending_jobs: number
|
||||
active_job_id?: string | null
|
||||
|
||||
@@ -5,8 +5,7 @@ import { useAgentStore } from '@/stores/agent'
|
||||
import { useProviderStore } from '@/stores/provider'
|
||||
import { useSkillStore } from '@/stores/skill'
|
||||
import type { AgentEvent } from '@/contracts'
|
||||
import { eventLabel, localizeDetails, permissionLabel, runStatusLabel, toolLabel } from './labels'
|
||||
import ToolOption from './ToolOption.vue'
|
||||
import { eventLabel, localizeDetails, permissionLabel, runStatusLabel, toolDescription, toolLabel } from './labels'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -15,7 +14,7 @@ const providerStore = useProviderStore()
|
||||
const skillStore = useSkillStore()
|
||||
const pageError = ref('')
|
||||
const form = reactive({
|
||||
input: '', provider_id: '', model: '', skill_id: '', max_steps: 10,
|
||||
input: '', provider_id: 'mock', model: 'mock-1', skill_id: '', max_steps: 10,
|
||||
tool_timeout_seconds: 30, run_timeout_seconds: 300, token_budget: 8000,
|
||||
allow_network: false, max_concurrent_tools: 1, allowed_tools: [] as string[],
|
||||
})
|
||||
@@ -26,7 +25,7 @@ const isNewRun = computed(() => !route.params.runId)
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await Promise.all([providerStore.loadProviders(), skillStore.loadSkills(), agentStore.loadTools()])
|
||||
form.provider_id = providerStore.defaultProviderId
|
||||
await providerStore.loadModels(form.provider_id)
|
||||
} catch (error) { pageError.value = error instanceof Error ? error.message : '智能体配置加载失败' }
|
||||
})
|
||||
|
||||
@@ -36,10 +35,7 @@ watch(() => route.params.runId, async (runId) => {
|
||||
}, { immediate: true })
|
||||
|
||||
watch(() => form.provider_id, async (providerId) => {
|
||||
form.model = providerStore.providers.find(p => p.provider_id === providerId)?.default_model ?? ''
|
||||
if (!providerId) return
|
||||
try { await providerStore.loadModels(providerId) }
|
||||
catch (error) { if (form.provider_id === providerId) pageError.value = error instanceof Error ? error.message : '模型列表加载失败,请手动填写模型 ID。' }
|
||||
try { await providerStore.loadModels(providerId); form.model = models.value[0]?.model_id ?? '' } catch { /* page keeps current selection */ }
|
||||
})
|
||||
|
||||
function toggleTool(name: string) {
|
||||
@@ -51,7 +47,6 @@ function toggleTool(name: string) {
|
||||
async function createRun() {
|
||||
pageError.value = ''
|
||||
try {
|
||||
if (!form.provider_id || !form.model.trim()) throw new Error('请选择提供商并填写模型 ID。')
|
||||
const run = await agentStore.createRun({
|
||||
input: form.input, provider_id: form.provider_id, model: form.model,
|
||||
skill_id: form.skill_id || undefined, allowed_tools: form.allowed_tools,
|
||||
@@ -76,12 +71,12 @@ function eventText(event: AgentEvent) {
|
||||
<section class="feature-page agent-page">
|
||||
<header class="feature-header"><div><h1>{{ isNewRun ? '创建智能体运行' : '智能体执行轨迹' }}</h1><p>配置执行边界,并实时查看模型、工具和权限事件。</p></div>
|
||||
<button v-if="!isNewRun" class="button-secondary" @click="router.push({ name: 'agent' })">新建运行</button></header>
|
||||
<div v-if="pageError || agentStore.error || providerStore.error" class="error-banner">{{ pageError || agentStore.error || providerStore.error }}</div>
|
||||
<div v-if="pageError || agentStore.error" class="error-banner">{{ pageError || agentStore.error }}</div>
|
||||
<form v-if="isNewRun" class="panel run-form" @submit.prevent="createRun">
|
||||
<div class="field"><label>任务</label><textarea v-model="form.input" class="textarea" required placeholder="描述希望智能体完成的任务" /></div>
|
||||
<div class="form-grid">
|
||||
<div class="field"><label>模型提供商</label><select v-model="form.provider_id" class="select"><option v-for="p in providerStore.enabledProviders" :key="p.provider_id" :value="p.provider_id">{{ p.name }}</option></select></div>
|
||||
<div class="field"><label>模型</label><input v-model="form.model" class="input" list="agent-models" placeholder="填写模型 ID" required /><datalist id="agent-models"><option v-for="m in models" :key="m.model_id" :value="m.model_id">{{ m.name }}</option></datalist></div>
|
||||
<div class="field"><label>模型</label><select v-model="form.model" class="select"><option v-for="m in models" :key="m.model_id" :value="m.model_id">{{ m.name }}</option></select></div>
|
||||
<div class="field"><label>技能</label><select v-model="form.skill_id" class="select"><option value="">不使用技能</option><option v-for="s in skillStore.readySkills" :key="s.skill_id" :value="s.skill_id">{{ s.name }}</option></select></div>
|
||||
<div class="field"><label>最大步骤</label><input v-model.number="form.max_steps" class="input" type="number" min="1" max="100" /></div>
|
||||
<div class="field"><label>工具超时(秒)</label><input v-model.number="form.tool_timeout_seconds" class="input" type="number" min="1" /></div>
|
||||
@@ -89,9 +84,9 @@ function eventText(event: AgentEvent) {
|
||||
<div class="field"><label>令牌预算</label><input v-model.number="form.token_budget" class="input" type="number" min="1" /></div>
|
||||
<div class="field"><label>最大并发工具</label><input v-model.number="form.max_concurrent_tools" class="input" type="number" min="1" /></div>
|
||||
</div>
|
||||
<div class="field"><label>允许使用的工具</label><div class="tool-grid"><ToolOption v-for="tool in agentStore.tools" :key="tool.name" :name="tool.name" :description="tool.description" :selected="form.allowed_tools.includes(tool.name)" @toggle="toggleTool" /></div></div>
|
||||
<div class="field"><label>允许使用的工具</label><div class="tool-grid"><label v-for="tool in agentStore.tools" :key="tool.name" class="tool-option"><input type="checkbox" :checked="form.allowed_tools.includes(tool.name)" @change="toggleTool(tool.name)" /><span><strong>{{ toolLabel(tool.name) }}</strong><code>{{ tool.name }}</code><small>{{ toolDescription(tool.name, tool.description) }}</small></span></label></div></div>
|
||||
<label class="network"><input v-model="form.allow_network" type="checkbox" /> 允许本次运行调用网络工具</label>
|
||||
<div class="inline-actions"><button class="button-primary" :disabled="agentStore.isCreating || !form.input.trim() || !form.provider_id || !form.model.trim()">{{ agentStore.isCreating ? '创建中…' : '创建并运行' }}</button></div>
|
||||
<div class="inline-actions"><button class="button-primary" :disabled="agentStore.isCreating || !form.input.trim()">{{ agentStore.isCreating ? '创建中…' : '创建并运行' }}</button></div>
|
||||
</form>
|
||||
|
||||
<div v-else class="trace-layout">
|
||||
@@ -115,7 +110,12 @@ function eventText(event: AgentEvent) {
|
||||
<style scoped>
|
||||
.agent-page > * { width: min(100%, 1080px); margin-inline: auto; }
|
||||
.run-form { display: grid; gap: var(--space-xl); }
|
||||
.tool-grid { display: grid; align-items: start; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: var(--space-sm); }
|
||||
.tool-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: var(--space-sm); }
|
||||
.tool-option { display: flex; gap: var(--space-sm); padding: var(--space-md); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-surface-primary); cursor: pointer; transition: border-color var(--motion-fast), background-color var(--motion-fast), transform var(--motion-fast), box-shadow var(--motion-fast); }
|
||||
.tool-option:hover { border-color: var(--color-accent-secondary); transform: translateY(-1px); box-shadow: var(--shadow-sm); }
|
||||
.tool-option:has(input:checked) { border-color: var(--color-accent-primary); background: var(--color-accent-soft); box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-accent-primary) 10%, transparent); }
|
||||
.tool-option small { display: block; color: var(--color-text-secondary); }
|
||||
.tool-option code { display: block; margin: 2px 0; color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
|
||||
.network { display: flex; gap: var(--space-sm); }
|
||||
.trace-layout { display: grid; gap: var(--space-lg); }
|
||||
.run-summary, .event-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); }
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { expect, it } from 'vitest'
|
||||
import ToolOption from './ToolOption.vue'
|
||||
|
||||
it('shows Chinese summaries, preserves raw metadata and emits the original tool ID', async () => {
|
||||
const name = 'mcp.9ca7ee21603a.web_search'
|
||||
const description = 'Search the web. query: string. ' + 'Full provider instructions. '.repeat(40)
|
||||
const wrapper = mount(ToolOption, { props: { name, description, selected: false } })
|
||||
expect(wrapper.get('strong').text()).toBe('网页搜索')
|
||||
expect(wrapper.get('code').text()).toBe(name)
|
||||
expect(wrapper.get('.tool-summary').text()).toContain('搜索关键词')
|
||||
expect(wrapper.get('details').attributes('open')).toBeUndefined()
|
||||
expect(wrapper.get('details p').element.textContent).toBe(description)
|
||||
await wrapper.get('summary').trigger('click')
|
||||
expect(wrapper.emitted('toggle')).toBeUndefined()
|
||||
await wrapper.get('input').setValue(true)
|
||||
expect(wrapper.emitted('toggle')).toEqual([[name]])
|
||||
})
|
||||
@@ -1,40 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { toolDescription, toolLabel } from './labels'
|
||||
|
||||
const props = defineProps<{ name: string; description: string; selected: boolean }>()
|
||||
const emit = defineEmits<{ toggle: [name: string] }>()
|
||||
const summary = computed(() => toolDescription(props.name, props.description))
|
||||
const showOriginal = computed(() => props.description.length > 0)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="tool-choice" :class="{ selected }">
|
||||
<label class="tool-selection">
|
||||
<input type="checkbox" :checked="selected" @change="emit('toggle', name)" />
|
||||
<span class="tool-copy">
|
||||
<strong>{{ toolLabel(name) }}</strong>
|
||||
<code>{{ name }}</code>
|
||||
<small class="tool-summary">{{ summary }}</small>
|
||||
</span>
|
||||
</label>
|
||||
<details v-if="showOriginal" class="tool-original">
|
||||
<summary>查看服务原文与参数</summary>
|
||||
<p>{{ description }}</p>
|
||||
</details>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tool-choice { min-width: 0; padding: var(--space-md); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-surface-primary); }
|
||||
.tool-choice.selected { border-color: var(--color-accent-primary); background: var(--color-accent-soft); }
|
||||
.tool-selection { display: flex; align-items: flex-start; gap: var(--space-sm); cursor: pointer; }
|
||||
.tool-selection input { flex-shrink: 0; margin-top: 4px; }
|
||||
.tool-copy { min-width: 0; overflow-wrap: anywhere; }
|
||||
.tool-copy strong, .tool-copy code, .tool-summary { display: block; }
|
||||
.tool-copy code { margin: 3px 0; color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
|
||||
.tool-summary { color: var(--color-text-secondary); line-height: 1.6; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; }
|
||||
.tool-original { margin-top: var(--space-sm); font-size: var(--font-size-xs); }
|
||||
.tool-original summary { cursor: pointer; color: var(--color-text-secondary); }
|
||||
.tool-original p { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 240px; overflow: auto; margin-top: var(--space-sm); user-select: text; }
|
||||
</style>
|
||||
@@ -9,21 +9,6 @@ import {
|
||||
} from './labels'
|
||||
|
||||
describe('智能体页面中文标签', () => {
|
||||
it('按 MCP 远程工具名匹配中文,不依赖服务器 ID', () => {
|
||||
for (const server of ['9ca7ee21603a', 'another-server']) {
|
||||
expect(toolLabel(`mcp.${server}.web_search`)).toBe('网页搜索')
|
||||
expect(toolLabel(`mcp.${server}.understand_image`)).toBe('图像理解')
|
||||
expect(toolDescription(`mcp.${server}.web_search`, 'Search the web')).toContain('搜索关键词')
|
||||
}
|
||||
expect(toolLabel('text.uppercase')).toBe('文本转大写')
|
||||
expect(toolDescription('text.uppercase', 'Convert input text to uppercase.')).toContain('大写')
|
||||
})
|
||||
|
||||
it('保留服务端中文,未知工具不编造翻译或套用内置工具语义', () => {
|
||||
expect(toolDescription('mcp.server.web_search', '仅搜索指定站点。')).toBe('仅搜索指定站点。')
|
||||
expect(toolDescription('mcp.server.custom_action', 'Private action')).toContain('暂无中文说明')
|
||||
expect(toolLabel('mcp.server.notes.delete')).toBe('MCP 工具 · notes.delete')
|
||||
})
|
||||
it('转换运行状态和事件名称', () => {
|
||||
expect(runStatusLabel('waiting_permission')).toBe('等待授权')
|
||||
expect(eventLabel('ToolCall')).toBe('调用工具')
|
||||
|
||||
@@ -42,7 +42,6 @@ const toolLabels: Record<string, string> = {
|
||||
'tasks.list': '列出任务',
|
||||
'attachments.read': '读取附件',
|
||||
'audio.transcribe': '音频转写',
|
||||
'text.uppercase': '文本转大写',
|
||||
}
|
||||
|
||||
const toolDescriptions: Record<string, string> = {
|
||||
@@ -59,25 +58,7 @@ const toolDescriptions: Record<string, string> = {
|
||||
'tasks.update': '更新已有任务。',
|
||||
'tasks.list': '列出已持久化的任务。',
|
||||
'attachments.read': '读取由宿主管理的 UTF-8 附件。',
|
||||
'audio.transcribe': '将音频转写为文本,按模型路由使用 API 或本地后端。',
|
||||
'text.uppercase': '将输入文本中的字母转换为大写。',
|
||||
}
|
||||
|
||||
// MCP IDs contain a server-specific namespace. Localize the remote tool name
|
||||
// for presentation only; requests must keep using the complete original ID.
|
||||
const mcpTools: Record<string, { label: string; description: string }> = {
|
||||
web_search: {
|
||||
label: '网页搜索',
|
||||
description: '搜索实时或外部网页信息。输入搜索关键词;结果包含标题、链接、摘要等信息。时效性问题可在关键词中加入日期,完整参数以服务原文为准。',
|
||||
},
|
||||
understand_image: {
|
||||
label: '图像理解',
|
||||
description: '根据提示词分析图片、描述内容或提取信息。输入分析要求和图片地址或本地路径;支持的格式与路径规则请查看服务原文。',
|
||||
},
|
||||
}
|
||||
|
||||
function mcpName(name: string): string | undefined {
|
||||
return /^mcp\.[^.]+\.(.+)$/.exec(name)?.[1]
|
||||
'audio.transcribe': '读取音频附件已有的宿主转写结果。',
|
||||
}
|
||||
|
||||
const permissionLabels: Record<string, string> = {
|
||||
@@ -124,17 +105,10 @@ export function eventLabel(event: AgentEventType): string {
|
||||
}
|
||||
|
||||
export function toolLabel(name: string): string {
|
||||
const remote = mcpName(name)
|
||||
if (remote) return mcpTools[remote]?.label ?? `MCP 工具 · ${remote}`
|
||||
return toolLabels[name] ?? name
|
||||
}
|
||||
|
||||
export function toolDescription(name: string, fallback: string): string {
|
||||
const remote = mcpName(name)
|
||||
if (remote) {
|
||||
if (/\p{Script=Han}/u.test(fallback)) return fallback
|
||||
return mcpTools[remote]?.description ?? '暂无中文说明,请展开查看服务原文。'
|
||||
}
|
||||
return toolDescriptions[name] ?? fallback
|
||||
}
|
||||
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useChatStore } from '@/stores/chat'
|
||||
import { useProviderStore } from '@/stores/provider'
|
||||
import { useSkillStore } from '@/stores/skill'
|
||||
import ChatView from './ChatView.vue'
|
||||
|
||||
vi.mock('vue-router', () => ({ useRouter: () => ({ push: vi.fn() }) }))
|
||||
vi.mock('@/stores/editor', () => ({ useEditorStore: () => ({}) }))
|
||||
vi.mock('@/stores/workspace', () => ({ useWorkspaceStore: () => ({}) }))
|
||||
vi.mock('@/components/common/MarkdownContent.vue', () => ({ default: { template: '<div />' } }))
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
const providers = useProviderStore()
|
||||
providers.providers = ['a', 'b'].map(id => ({
|
||||
provider_id: id, provider_type: 'openai_compatible', name: id,
|
||||
default_model: `${id}-default`, enabled: true, capabilities: { chat: true }, has_credential: false,
|
||||
}))
|
||||
providers.defaultProviderId = 'a'
|
||||
vi.spyOn(providers, 'loadProviders').mockResolvedValue(undefined)
|
||||
vi.spyOn(providers, 'loadModels').mockResolvedValue([])
|
||||
vi.spyOn(useSkillStore(), 'loadSkills').mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('preserves the selected provider and manual model after leaving and returning to chat', async () => {
|
||||
const chat = useChatStore()
|
||||
const first = mount(ChatView)
|
||||
await flushPromises()
|
||||
await first.get('select').setValue('b')
|
||||
await first.get('input[list="chat-models"]').setValue('b-manual')
|
||||
first.unmount()
|
||||
const returned = mount(ChatView)
|
||||
await flushPromises()
|
||||
expect(chat.selectedProviderId).toBe('b')
|
||||
expect(chat.selectedModel).toBe('b-manual')
|
||||
expect(useProviderStore().loadModels).toHaveBeenLastCalledWith('b')
|
||||
returned.unmount()
|
||||
})
|
||||
|
||||
it.each(['missing', 'disabled', 'unselected'])('uses the default when the selected provider is %s', async state => {
|
||||
const chat = useChatStore()
|
||||
chat.selectedProviderId = state === 'unselected' ? '' : state === 'missing' ? 'deleted' : 'b'
|
||||
chat.selectedModel = 'old-model'
|
||||
if (state === 'disabled') useProviderStore().providers[1]!.enabled = false
|
||||
const wrapper = mount(ChatView)
|
||||
await flushPromises()
|
||||
expect(chat.selectedProviderId).toBe('a')
|
||||
expect(chat.selectedModel).toBe('a-default')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('preserves the selection when provider discovery fails', async () => {
|
||||
const chat = useChatStore()
|
||||
chat.selectedProviderId = 'b'
|
||||
chat.selectedModel = 'b-manual'
|
||||
useProviderStore().error = 'offline'
|
||||
const wrapper = mount(ChatView)
|
||||
await flushPromises()
|
||||
expect(chat.selectedProviderId).toBe('b')
|
||||
expect(chat.selectedModel).toBe('b-manual')
|
||||
expect(wrapper.get('.error-banner').text()).toBe('offline')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it.each(['providers', 'skills'])('ignores initialization after unmount while %s are loading', async source => {
|
||||
const chat = useChatStore()
|
||||
let finish!: () => void
|
||||
const pending = new Promise<void>(resolve => { finish = resolve })
|
||||
if (source === 'providers') vi.mocked(useProviderStore().loadProviders).mockReturnValueOnce(pending)
|
||||
else vi.mocked(useSkillStore().loadSkills).mockReturnValueOnce(pending)
|
||||
const first = mount(ChatView)
|
||||
first.unmount()
|
||||
finish()
|
||||
await flushPromises()
|
||||
expect(chat.selectedProviderId).toBe('')
|
||||
expect(chat.selectedModel).toBe('')
|
||||
expect(useProviderStore().loadModels).not.toHaveBeenCalled()
|
||||
|
||||
const returned = mount(ChatView)
|
||||
await flushPromises()
|
||||
expect(chat.selectedProviderId).toBe('a')
|
||||
expect(chat.selectedModel).toBe('a-default')
|
||||
await returned.get('textarea').setValue('hello')
|
||||
expect(returned.get('button.button-primary').attributes('disabled')).toBeUndefined()
|
||||
returned.unmount()
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import type { Citation } from '@/contracts'
|
||||
import { useChatStore } from '@/stores/chat'
|
||||
@@ -16,37 +16,26 @@ const workspaceStore = useWorkspaceStore()
|
||||
const editorStore = useEditorStore()
|
||||
const router = useRouter()
|
||||
const loadError = ref('')
|
||||
let disposed = false
|
||||
onBeforeUnmount(() => { disposed = true })
|
||||
|
||||
const availableModels = computed(() => providerStore.modelsByProvider[chatStore.selectedProviderId] ?? [])
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await Promise.all([providerStore.loadProviders(), skillStore.loadSkills()])
|
||||
if (disposed || providerStore.error) return
|
||||
const selected = providerStore.enabledProviders.find(p => p.provider_id === chatStore.selectedProviderId)
|
||||
if (!selected) {
|
||||
chatStore.selectedProviderId = providerStore.defaultProviderId
|
||||
} else {
|
||||
await refreshModels(selected.provider_id)
|
||||
}
|
||||
await providerStore.loadModels(chatStore.selectedProviderId)
|
||||
} catch (error) {
|
||||
if (disposed) return
|
||||
loadError.value = error instanceof Error ? error.message : '无法加载 AI 配置,请检查后端连接。'
|
||||
loadError.value = error instanceof Error ? error.message : '无法加载 AI 配置,当前展示本地数据。'
|
||||
}
|
||||
})
|
||||
|
||||
async function refreshModels(providerId: string) {
|
||||
loadError.value = ''
|
||||
if (!providerId) return
|
||||
try { await providerStore.loadModels(providerId) }
|
||||
catch (error) { if (!disposed && chatStore.selectedProviderId === providerId) loadError.value = error instanceof Error ? error.message : '模型列表加载失败,请手动填写模型 ID。' }
|
||||
}
|
||||
|
||||
watch(() => chatStore.selectedProviderId, async (providerId) => {
|
||||
chatStore.selectedModel = providerStore.providers.find(p => p.provider_id === providerId)?.default_model ?? ''
|
||||
await refreshModels(providerId)
|
||||
try {
|
||||
await providerStore.loadModels(providerId)
|
||||
const firstModel = providerStore.modelsByProvider[providerId]?.[0]
|
||||
if (firstModel) chatStore.selectedModel = firstModel.model_id
|
||||
} catch (error) {
|
||||
loadError.value = error instanceof Error ? error.message : '模型列表加载失败'
|
||||
}
|
||||
})
|
||||
|
||||
function send() { void chatStore.sendMessage(chatStore.inputText) }
|
||||
@@ -65,12 +54,17 @@ async function openCitation(citation: Citation) {
|
||||
<div class="field compact"><label>Provider</label><select v-model="chatStore.selectedProviderId" class="select">
|
||||
<option v-for="provider in providerStore.enabledProviders" :key="provider.provider_id" :value="provider.provider_id">{{ provider.name }}</option>
|
||||
</select></div>
|
||||
<div class="field compact"><label>模型 ID</label><input v-model="chatStore.selectedModel" class="input" list="chat-models" placeholder="填写模型 ID" /><datalist id="chat-models"><option v-for="model in availableModels" :key="model.model_id" :value="model.model_id">{{ model.name }}</option></datalist></div>
|
||||
<span class="subtle">知识库问答与技能请使用智能体;普通聊天尚未接入这些能力。</span>
|
||||
<div class="field compact"><label>Model</label><select v-model="chatStore.selectedModel" class="select">
|
||||
<option v-for="model in availableModels" :key="model.model_id" :value="model.model_id">{{ model.name }}</option>
|
||||
</select></div>
|
||||
<div class="field compact"><label>Skill</label><select v-model="chatStore.selectedSkillId" class="select">
|
||||
<option :value="null">不使用 Skill</option><option v-for="skill in skillStore.enabledSkills" :key="skill.skill_id" :value="skill.skill_id">{{ skill.name }}</option>
|
||||
</select></div>
|
||||
<label class="rag-toggle"><input v-model="chatStore.useRag" type="checkbox" /> 使用知识库</label>
|
||||
</header>
|
||||
<div v-if="loadError || providerStore.error" class="error-banner chat-error">{{ loadError || providerStore.error }}</div>
|
||||
<div v-if="loadError" class="error-banner chat-error">{{ loadError }}</div>
|
||||
<main class="message-timeline">
|
||||
<div v-if="!chatStore.messages.length" class="empty-state"><div><strong>开始一段知识对话</strong><p>请先配置模型提供商。聊天记录仅保留在本次页面会话中。</p></div></div>
|
||||
<div v-if="!chatStore.messages.length" class="empty-state"><div><strong>开始一段知识对话</strong><p>可以直接提问,也可以打开 RAG 让模型基于当前 Vault 回答。</p></div></div>
|
||||
<article v-for="message in chatStore.messages" :key="message.message_id" class="message" :class="message.role">
|
||||
<div class="avatar">{{ message.role === 'user' ? '你' : 'AI' }}</div>
|
||||
<div class="message-body">
|
||||
@@ -84,7 +78,7 @@ async function openCitation(citation: Citation) {
|
||||
</button>
|
||||
</div>
|
||||
<time>{{ new Date(message.created_at).toLocaleTimeString() }}</time>
|
||||
<small v-if="message.usage" class="usage">Token {{ message.usage.total_tokens }}<span v-if="message.usage.input_tokens !== undefined && message.usage.output_tokens !== undefined">(输入 {{ message.usage.input_tokens }} / 输出 {{ message.usage.output_tokens }})</span></small>
|
||||
<small v-if="message.usage" class="usage">Token {{ message.usage.total_tokens }}(输入 {{ message.usage.input_tokens }} / 输出 {{ message.usage.output_tokens }})</small>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
@@ -93,7 +87,7 @@ async function openCitation(citation: Citation) {
|
||||
@keydown.ctrl.enter.prevent="send" />
|
||||
<div class="composer-actions"><span class="subtle">回答可能包含错误,请核对 Citation。</span>
|
||||
<button v-if="chatStore.isStreaming" class="button-danger" @click="chatStore.stopGeneration">停止</button>
|
||||
<button v-else class="button-primary" :disabled="!chatStore.inputText.trim() || !chatStore.selectedProviderId || !chatStore.selectedModel.trim()" @click="send">发送</button>
|
||||
<button v-else class="button-primary" :disabled="!chatStore.inputText.trim()" @click="send">发送</button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
@@ -27,7 +27,6 @@ async function uninstall(id: string, name: string) { if (!confirm(`卸载“${na
|
||||
<div v-if="pluginStore.selectedPlugin.dependent_skills?.length" class="notice-banner last-error">依赖此插件的 Skill:{{ pluginStore.selectedPlugin.dependent_skills.join('、') }}</div>
|
||||
<PluginMcpPanel :plugin="pluginStore.selectedPlugin" />
|
||||
</div>
|
||||
<div v-else-if="!pluginStore.plugins.length" class="empty-state"><div><strong>{{ pluginStore.isLoading ? '正在加载…' : pluginStore.error ? '加载失败' : '尚未安装' }}</strong><button class="button-secondary" @click="pluginStore.loadPlugins">重新加载</button></div></div>
|
||||
<div v-else class="feature-grid"><article v-for="plugin in pluginStore.plugins" :key="plugin.plugin_id" class="item-card extension-card" @click="pluginStore.selectPlugin(plugin.plugin_id)"><div class="extension-title"><AppIcon :icon="Connection" :size="22" /><div><strong>{{ plugin.name }}</strong><p>v{{ plugin.version }}</p></div><span class="badge" :class="{ success: plugin.status === 'ready', error: plugin.status === 'error', warning: plugin.status === 'permission_required' }">{{ plugin.status }}</span></div><p class="muted">{{ plugin.description }}</p><p class="subtle">{{ plugin.permissions.length }} 项权限 · {{ plugin.contributions.length }} 项 Contribution</p></article></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -109,7 +109,7 @@ async function save() {
|
||||
error.value = ''
|
||||
saving.value = true
|
||||
try {
|
||||
if (!form.name.trim() || !form.base_url.trim()) throw new Error('请填写名称和 Base URL。')
|
||||
if (!form.name.trim() || (form.provider_type !== 'mock' && !form.base_url.trim())) throw new Error('请填写名称和 Base URL。')
|
||||
if (selectedPreset.value?.requires_credential && !apiKey.value.trim() && !configured.value) throw new Error('请输入 API Key。密钥将由后端加密保存。')
|
||||
// Snapshot before awaiting: closing/unmounting must never create a provider with a changed draft.
|
||||
const data = { provider_type: form.provider_type, name: form.name.trim(), base_url: form.base_url.trim() || undefined, default_model: form.default_model.trim(), enabled: form.enabled, capabilities: {}, has_credential: false }
|
||||
@@ -147,9 +147,9 @@ async function save() {
|
||||
<ProviderPresetSelector :presets="presets" :model-value="form.preset_id" @update:model-value="applyPreset" />
|
||||
<p v-if="selectedPreset?.description" class="subtle">{{ selectedPreset.description }}</p>
|
||||
<div class="form-grid">
|
||||
<label class="field"><span>接入协议</span><select v-model="form.provider_type" class="select" data-field="protocol" @change="changeConnection"><option value="openai_compatible">OpenAI Compatible</option><option value="openai_chat">OpenAI Chat</option><option value="openai_responses">OpenAI Responses</option><option value="anthropic_messages">Anthropic Messages</option><option value="ollama">Ollama</option></select></label>
|
||||
<label class="field"><span>接入协议</span><select v-model="form.provider_type" class="select" data-field="protocol" @change="changeConnection"><option value="openai_compatible">OpenAI Compatible</option><option value="openai_chat">OpenAI Chat</option><option value="openai_responses">OpenAI Responses</option><option value="anthropic_messages">Anthropic Messages</option><option value="ollama">Ollama</option><option v-if="provider?.provider_type === 'mock'" value="mock">Mock</option></select></label>
|
||||
<label class="field"><span>名称</span><input v-model="form.name" class="input" data-field="name" required /></label>
|
||||
<label class="field wide"><span>Base URL</span><input v-model="form.base_url" class="input" data-field="base-url" placeholder="https://api.example.com/v1" required @change="changeConnection" /></label>
|
||||
<label class="field wide"><span>Base URL</span><input v-model="form.base_url" class="input" data-field="base-url" placeholder="https://api.example.com/v1" :required="form.provider_type !== 'mock'" @change="changeConnection" /></label>
|
||||
<label class="field wide"><span>API Key</span><input v-model="apiKey" class="input" type="password" autocomplete="new-password" spellcheck="false" :placeholder="configured ? '已配置,留空表示不修改' : '请输入 API Key(无鉴权服务可留空)'" /><small class="subtle">密钥由本地 AI Core 加密保存;提供商配置仅保存独立的凭据引用。</small></label>
|
||||
<p v-if="credentialLoading" class="subtle wide" role="status">正在检查凭据状态…</p>
|
||||
<p v-if="credentialError" class="error-text wide" role="alert">{{ credentialError }}</p>
|
||||
|
||||
@@ -70,7 +70,6 @@ async function chooseDefaultModel(provider: ProviderConfig, event: Event) {
|
||||
<button class="button-primary" @click="openProvider()">新增 Provider</button>
|
||||
</div>
|
||||
<div v-if="providerStore.error || providerAction" class="error-banner">{{ providerStore.error || providerAction }}</div>
|
||||
<p v-if="!providerStore.providers.length" class="subtle">{{ providerStore.isLoading ? '正在加载提供商…' : '尚无可用提供商,请添加真实 API 或本地 Ollama 配置。' }}</p>
|
||||
<div class="provider-list">
|
||||
<article v-for="provider in providerStore.providers" :key="provider.provider_id" class="item-card provider-card">
|
||||
<div class="provider-main">
|
||||
@@ -92,17 +91,17 @@ async function chooseDefaultModel(provider: ProviderConfig, event: Event) {
|
||||
<button class="button-secondary" :disabled="providerStore.modelLoadingByProvider[provider.provider_id]" @click="refreshModels(provider)">{{ providerStore.modelLoadingByProvider[provider.provider_id] ? '获取中…' : '刷新模型' }}</button>
|
||||
<button class="button-secondary" @click="testProvider(provider)">测试</button>
|
||||
<button class="button-secondary" @click="openProvider(provider)">编辑</button>
|
||||
<button class="button-danger" @click="removeProvider(provider)">删除</button>
|
||||
<button class="button-danger" :disabled="provider.provider_id === 'mock'" @click="removeProvider(provider)">删除</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="activeSection === 'index'" class="panel settings-section"><h2>索引与模型</h2><div class="index-summary"><div><span class="badge" :class="{ success: settingsStore.indexStatus.status === 'idle', error: settingsStore.indexStatus.status === 'error' }">{{ settingsStore.indexStatus.status }}</span><p>待处理任务 {{ settingsStore.indexStatus.pending_jobs }}</p></div><div><strong>{{ settingsStore.indexStatus.total_notes ?? '未获取' }}</strong><small>笔记</small></div><div><strong>{{ settingsStore.indexStatus.total_blocks ?? '未获取' }}</strong><small>Block</small></div></div><div v-if="settingsStore.indexStatus.error" class="error-banner">{{ settingsStore.indexStatus.error }}</div><div class="inline-actions"><button class="button-primary" @click="settingsStore.rebuildIndex('full')">重建全部</button><span class="subtle">当前后端支持全量重建。</span></div><ModelRoutingSettings /></div>
|
||||
<div v-else-if="activeSection === 'index'" class="panel settings-section"><h2>索引与模型</h2><div class="index-summary"><div><span class="badge" :class="{ success: settingsStore.indexStatus.status === 'idle', error: settingsStore.indexStatus.status === 'error' }">{{ settingsStore.indexStatus.status }}</span><p>待处理任务 {{ settingsStore.indexStatus.pending_jobs }}</p></div><div><strong>{{ settingsStore.indexStatus.total_notes }}</strong><small>笔记</small></div><div><strong>{{ settingsStore.indexStatus.total_blocks }}</strong><small>Block</small></div></div><div v-if="settingsStore.indexStatus.error" class="error-banner">{{ settingsStore.indexStatus.error }}</div><div class="inline-actions"><button class="button-primary" @click="settingsStore.rebuildIndex('full')">重建全部</button><button class="button-secondary" @click="settingsStore.rebuildIndex('fts')">重建文本索引</button><button class="button-secondary" @click="settingsStore.rebuildIndex('vector')">重建向量索引</button></div><ModelRoutingSettings /></div>
|
||||
|
||||
<div v-else-if="activeSection === 'permissions'" class="panel settings-section"><h2>权限策略</h2><p class="muted section-description">以下为后端当前生效的权限策略;全局策略编辑尚未开放,运行时按实际权限请求确认。</p><p v-if="!Object.keys(settingsStore.permissionPolicy).length" class="subtle">尚未获取权限策略,请检查后端连接并重新检测。</p><div class="permission-list"><div v-for="(policy, permission) in settingsStore.permissionPolicy" :key="permission" class="setting-row"><span><strong>{{ permission }}</strong></span><span>{{ policy === 'allow' ? '允许' : policy === 'confirm' ? '每次确认' : '拒绝' }}</span></div></div></div>
|
||||
<div v-else-if="activeSection === 'permissions'" class="panel settings-section"><h2>权限策略</h2><p class="muted section-description">高影响能力默认需要确认。未知权限由后端拒绝。</p><div class="permission-list"><div v-for="(policy, permission) in settingsStore.permissionPolicy" :key="permission" class="setting-row"><span><strong>{{ permission }}</strong></span><select :value="policy" class="select short" @change="settingsStore.setPermission(String(permission), ($event.target as HTMLSelectElement).value as 'allow' | 'confirm' | 'deny')"><option value="allow">允许</option><option value="confirm">每次确认</option><option value="deny">拒绝</option></select></div></div></div>
|
||||
|
||||
<div v-else class="panel settings-section"><h2>AI Core 诊断</h2><div v-if="settingsStore.diagnosticsError" class="error-banner">{{ settingsStore.diagnosticsError }}</div><div class="diagnostic-grid"><div class="item-card"><span class="badge" :class="{ success: settingsStore.aiCoreStatus === 'running', error: settingsStore.aiCoreStatus === 'error' }">{{ settingsStore.aiCoreStatus }}</span><h3>AI Core 连接状态</h3><p class="subtle">AI Core 不可用时,Markdown 编辑仍可继续使用。</p></div><div class="item-card"><strong>{{ settingsStore.aiCoreAddress }}</strong><h3>开发 API 地址</h3><p class="subtle">正式桌面环境由 Sidecar Manager 动态提供。</p></div></div><div class="inline-actions diagnostic-actions"><button class="button-primary" @click="settingsStore.loadDiagnostics">重新检测</button><span class="subtle">当前 Web 端不支持重启后端进程,请在运行后端的终端中操作。</span></div></div>
|
||||
<div v-else class="panel settings-section"><h2>AI Core 诊断</h2><div v-if="settingsStore.diagnosticsError" class="error-banner">{{ settingsStore.diagnosticsError }}</div><div class="diagnostic-grid"><div class="item-card"><span class="badge" :class="{ success: settingsStore.aiCoreStatus === 'running', error: settingsStore.aiCoreStatus === 'error' }">{{ settingsStore.aiCoreStatus }}</span><h3>Sidecar 状态</h3><p class="subtle">AI Core 不可用时,Markdown 编辑仍可继续使用。</p></div><div class="item-card"><strong>{{ settingsStore.aiCoreAddress }}</strong><h3>开发 API 地址</h3><p class="subtle">正式桌面环境由 Sidecar Manager 动态提供。</p></div></div><div class="inline-actions diagnostic-actions"><button class="button-primary" @click="settingsStore.loadDiagnostics">重新检测</button><button class="button-secondary" @click="settingsStore.restartAiCore">重启 AI Core</button></div></div>
|
||||
|
||||
<ProviderForm v-if="showProviderForm" :provider="editingProvider" :models="editingProvider ? providerStore.modelsByProvider[editingProvider.provider_id] : []" @close="showProviderForm = false" @saved="providerSaved" />
|
||||
</section>
|
||||
|
||||
@@ -32,7 +32,6 @@ async function uninstall(skillId: string, name: string) {
|
||||
<div class="detail-grid"><div><h3>工具</h3><div class="tag-list"><span v-for="tool in skillStore.selectedSkill.tools" :key="tool" class="badge info">{{ tool }}</span></div></div><div><h3>权限</h3><div class="tag-list"><span v-for="permission in skillStore.selectedSkill.permissions" :key="permission" class="badge warning">{{ permission }}</span></div></div><div><h3>检索配置</h3><pre>{{ JSON.stringify(skillStore.selectedSkill.retrieval_config, null, 2) }}</pre></div><div><h3>模型能力</h3><div class="tag-list"><span v-for="cap in skillStore.selectedSkill.model_requirements?.capabilities" :key="cap" class="badge">{{ cap }}</span></div></div></div>
|
||||
<div v-if="skillStore.selectedSkill.missing_dependencies?.length" class="error-banner dependencies">缺失依赖:{{ skillStore.selectedSkill.missing_dependencies.join('、') }}</div>
|
||||
</div>
|
||||
<div v-else-if="!skillStore.skills.length" class="empty-state"><div><strong>{{ skillStore.isLoading ? '正在加载…' : skillStore.error ? '加载失败' : '尚未安装' }}</strong><button class="button-secondary" @click="skillStore.loadSkills">重新加载</button></div></div>
|
||||
<div v-else class="feature-grid"><article v-for="skill in skillStore.skills" :key="skill.skill_id" class="item-card extension-card" @click="skillStore.selectSkill(skill.skill_id)"><div class="extension-title"><AppIcon :icon="Lightning" :size="22" /><div><strong>{{ skill.name }}</strong><p>v{{ skill.version }}</p></div><span class="badge" :class="{ success: skill.status === 'ready', warning: skill.status === 'dependency_missing' }">{{ skill.status }}</span></div><p class="muted">{{ skill.description }}</p><div class="tag-list"><span v-for="permission in skill.permissions.slice(0, 3)" :key="permission" class="badge">{{ permission }}</span></div></article></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -23,13 +23,13 @@ onMounted(async () => {
|
||||
await openVault(lastVaultPath)
|
||||
return
|
||||
} catch {
|
||||
// 历史保存的旧路径可能与当前后端 Vault 不同,清除后让用户重新选择。
|
||||
// Mock 阶段保存的旧路径可能与当前后端 Vault 不同,清除后让用户重新选择。
|
||||
localStorage.removeItem('last-vault-path')
|
||||
}
|
||||
}
|
||||
{
|
||||
setTimeout(() => {
|
||||
aiCoreStatus.value = settingsStore.aiCoreStatus === 'running' ? 'running' : 'stopped'
|
||||
}
|
||||
}, 800)
|
||||
})
|
||||
|
||||
async function openVault(path: string) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import apiClient from './apiClient'
|
||||
import { SseClient } from './sseClient'
|
||||
import type { AgentRun, AgentEvent, AgentTraceResponse, ApiAgentRun, OperationResponse, PageMeta, ToolDefinition } from '@/contracts'
|
||||
import type { AgentRun, AgentEvent, AgentTraceResponse, ApiAgentRun, OperationResponse, PageMeta, ToolDefinition, PermissionRequest } from '@/contracts'
|
||||
|
||||
function toAgentRun(run: ApiAgentRun): AgentRun {
|
||||
// API 的 token_usage 是累计值,UI 模型预留了输入/输出拆分字段。
|
||||
@@ -10,6 +10,8 @@ function toAgentRun(run: ApiAgentRun): AgentRun {
|
||||
current_step: run.current_step,
|
||||
max_steps: run.max_steps,
|
||||
token_usage: {
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
total_tokens: run.token_usage,
|
||||
},
|
||||
started_at: run.created_at,
|
||||
@@ -105,3 +107,207 @@ export async function respondToPermission(
|
||||
decision,
|
||||
})
|
||||
}
|
||||
|
||||
export const mockTools: ToolDefinition[] = [
|
||||
{
|
||||
name: 'notes.search',
|
||||
description: '搜索笔记,支持关键词和语义检索',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '搜索关键词' },
|
||||
limit: { type: 'number', description: '返回结果数量' },
|
||||
},
|
||||
required: ['query'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
{
|
||||
name: 'notes.read',
|
||||
description: '读取指定笔记的完整内容',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
note_id: { type: 'string' },
|
||||
},
|
||||
required: ['note_id'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
{
|
||||
name: 'notes.create',
|
||||
description: '创建新笔记',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
content: { type: 'string' },
|
||||
folder_path: { type: 'string' },
|
||||
},
|
||||
required: ['title', 'content'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
{
|
||||
name: 'rag.search',
|
||||
description: '基于 RAG 的语义检索,返回相关知识片段',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string' },
|
||||
top_k: { type: 'number' },
|
||||
},
|
||||
required: ['query'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
{
|
||||
name: 'tasks.create',
|
||||
description: '创建任务',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
priority: { type: 'string', enum: ['low', 'medium', 'high'] },
|
||||
},
|
||||
required: ['title'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
{
|
||||
name: 'system.echo',
|
||||
description: '回显输入内容(测试用)',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: { type: 'string' },
|
||||
},
|
||||
required: ['text'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
{
|
||||
name: 'math.add',
|
||||
description: '两数相加(测试用)',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
a: { type: 'number' },
|
||||
b: { type: 'number' },
|
||||
},
|
||||
required: ['a', 'b'],
|
||||
},
|
||||
source: 'builtin',
|
||||
},
|
||||
]
|
||||
|
||||
export const mockAgentRuns: AgentRun[] = [
|
||||
{
|
||||
run_id: 'run-1',
|
||||
status: 'completed',
|
||||
current_step: 3,
|
||||
max_steps: 10,
|
||||
token_usage: { input_tokens: 2340, output_tokens: 890, total_tokens: 3230 },
|
||||
started_at: '2026-08-25T11:00:00Z',
|
||||
completed_at: '2026-08-25T11:02:30Z',
|
||||
},
|
||||
{
|
||||
run_id: 'run-2',
|
||||
status: 'running',
|
||||
current_step: 2,
|
||||
max_steps: 10,
|
||||
token_usage: { input_tokens: 1500, output_tokens: 420, total_tokens: 1920 },
|
||||
started_at: '2026-08-26T09:30:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
export const mockAgentEvents: AgentEvent[] = [
|
||||
{
|
||||
event: 'RunStarted',
|
||||
sequence: 1,
|
||||
run_id: 'run-1',
|
||||
data: { task: '帮我整理红黑树的核心知识点' },
|
||||
timestamp: '2026-08-25T11:00:00Z',
|
||||
},
|
||||
{
|
||||
event: 'ThinkingDelta',
|
||||
sequence: 2,
|
||||
run_id: 'run-1',
|
||||
data: { text: '我需要先搜索笔记中关于红黑树的内容...' },
|
||||
timestamp: '2026-08-25T11:00:01Z',
|
||||
},
|
||||
{
|
||||
event: 'ToolCall',
|
||||
sequence: 3,
|
||||
run_id: 'run-1',
|
||||
data: {
|
||||
tool_call_id: 'tc-1',
|
||||
name: 'notes.search',
|
||||
parameters: { query: '红黑树 插入 删除', limit: 5 },
|
||||
status: 'running',
|
||||
},
|
||||
timestamp: '2026-08-25T11:00:02Z',
|
||||
},
|
||||
{
|
||||
event: 'ToolResult',
|
||||
sequence: 4,
|
||||
run_id: 'run-1',
|
||||
data: {
|
||||
tool_call_id: 'tc-1',
|
||||
name: 'notes.search',
|
||||
status: 'completed',
|
||||
result: '找到 5 条相关结果,包括红黑树性质、插入操作、删除操作等...',
|
||||
duration_ms: 320,
|
||||
},
|
||||
timestamp: '2026-08-25T11:00:02Z',
|
||||
},
|
||||
{
|
||||
event: 'Citation',
|
||||
sequence: 5,
|
||||
run_id: 'run-1',
|
||||
data: {
|
||||
note_id: 'n-rbt',
|
||||
block_id: 'b1',
|
||||
heading_path: '数据结构 / 红黑树 / 性质',
|
||||
},
|
||||
timestamp: '2026-08-25T11:00:03Z',
|
||||
},
|
||||
{
|
||||
event: 'ThinkingDelta',
|
||||
sequence: 6,
|
||||
run_id: 'run-1',
|
||||
data: { text: '搜索结果很全面,让我整理一下结构...' },
|
||||
timestamp: '2026-08-25T11:00:03Z',
|
||||
},
|
||||
{
|
||||
event: 'TextDelta',
|
||||
sequence: 7,
|
||||
run_id: 'run-1',
|
||||
data: { text: '## 红黑树核心知识点整理\n\n### 1. 基本性质\n红黑树是一种自平衡二叉搜索树,每个节点带有颜色属性...' },
|
||||
timestamp: '2026-08-25T11:00:04Z',
|
||||
},
|
||||
{
|
||||
event: 'Usage',
|
||||
sequence: 8,
|
||||
run_id: 'run-1',
|
||||
data: { input_tokens: 2340, output_tokens: 890, total_tokens: 3230 },
|
||||
timestamp: '2026-08-25T11:02:30Z',
|
||||
},
|
||||
{
|
||||
event: 'RunCompleted',
|
||||
sequence: 9,
|
||||
run_id: 'run-1',
|
||||
data: { message: 'Task completed successfully' },
|
||||
timestamp: '2026-08-25T11:02:30Z',
|
||||
},
|
||||
]
|
||||
|
||||
export const mockPermissionRequest: PermissionRequest = {
|
||||
request_id: 'perm-1',
|
||||
run_id: 'run-2',
|
||||
tool_name: 'notes.create',
|
||||
permission: 'notes.write',
|
||||
parameters: { title: '红黑树知识点总结', folder_path: '/数据结构' },
|
||||
impact: '将在你的知识库中创建一篇新笔记',
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { SseClient } from './sseClient'
|
||||
import type { ModelEvent } from '@/contracts'
|
||||
import type { Conversation, ChatMessage, ModelEvent } from '@/contracts'
|
||||
|
||||
export interface ChatRequest {
|
||||
provider_id: string
|
||||
@@ -46,3 +46,87 @@ export function streamChat(
|
||||
client.connect().catch(() => {})
|
||||
return client
|
||||
}
|
||||
|
||||
export const mockConversations: Conversation[] = [
|
||||
{
|
||||
conversation_id: 'conv-1',
|
||||
title: '关于红黑树的讨论',
|
||||
created_at: '2026-08-25T10:00:00Z',
|
||||
updated_at: '2026-08-25T10:30:00Z',
|
||||
message_count: 6,
|
||||
},
|
||||
{
|
||||
conversation_id: 'conv-2',
|
||||
title: '死锁避免算法',
|
||||
created_at: '2026-08-24T14:00:00Z',
|
||||
updated_at: '2026-08-24T15:20:00Z',
|
||||
message_count: 4,
|
||||
},
|
||||
{
|
||||
conversation_id: 'conv-3',
|
||||
title: 'TCP三次握手',
|
||||
created_at: '2026-08-22T09:00:00Z',
|
||||
updated_at: '2026-08-22T09:15:00Z',
|
||||
message_count: 3,
|
||||
},
|
||||
]
|
||||
|
||||
export const mockMessages: Record<string, ChatMessage[]> = {
|
||||
'conv-1': [
|
||||
{
|
||||
message_id: 'msg-1',
|
||||
conversation_id: 'conv-1',
|
||||
role: 'user',
|
||||
content: '红黑树的插入操作有哪些情况需要调整?',
|
||||
created_at: '2026-08-25T10:00:00Z',
|
||||
},
|
||||
{
|
||||
message_id: 'msg-2',
|
||||
conversation_id: 'conv-1',
|
||||
role: 'assistant',
|
||||
content:
|
||||
'红黑树插入后可能违反红黑性质,需要通过旋转和变色来修复。主要有以下几种情况:\n\n**情况1:叔叔节点是红色**\n- 将父节点和叔叔节点设为黑色\n- 将祖父节点设为红色\n- 当前节点上移到祖父节点,继续向上调整\n\n**情况2:叔叔节点是黑色,且当前节点是右孩子**\n- 以父节点为支点左旋\n- 将当前节点转换为左孩子,进入情况3\n\n**情况3:叔叔节点是黑色,且当前节点是左孩子**\n- 以祖父节点为支点右旋\n- 将父节点设为黑色,祖父节点设为红色\n\n以上三种情况需要从插入节点开始向上递归处理,直到根节点。',
|
||||
created_at: '2026-08-25T10:01:00Z',
|
||||
citations: [
|
||||
{
|
||||
note_id: 'n-rbt',
|
||||
block_id: 'b1',
|
||||
file_path: '/数据结构/红黑树.md',
|
||||
heading_path: '数据结构 / 红黑树 / 插入操作',
|
||||
content: '插入后可能破坏红黑性质,需要通过变色和旋转来修复...',
|
||||
},
|
||||
{
|
||||
note_id: 'n-rbt',
|
||||
block_id: 'b2',
|
||||
file_path: '/数据结构/红黑树.md',
|
||||
heading_path: '数据结构 / 红黑树 / 五种情况',
|
||||
content: 'Case 1: 叔叔为红色,直接变色...',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
message_id: 'msg-3',
|
||||
conversation_id: 'conv-1',
|
||||
role: 'user',
|
||||
content: '能对比一下 AVL 树和红黑树的性能差异吗?',
|
||||
created_at: '2026-08-25T10:10:00Z',
|
||||
},
|
||||
{
|
||||
message_id: 'msg-4',
|
||||
conversation_id: 'conv-1',
|
||||
role: 'assistant',
|
||||
content:
|
||||
'AVL 树和红黑树都是平衡二叉搜索树,但它们的平衡策略和性能特点有所不同:\n\n| 特性 | AVL 树 | 红黑树 |\n|------|--------|--------|\n| 严格平衡 | 高度差 ≤ 1 | 黑色高度相同 |\n| 查找速度 | 更快(严格平衡) | 略慢但仍为 O(log n) |\n| 插入/删除 | 旋转更多 | 旋转更少(颜色调整为主) |\n| 存储开销 | 每个节点存高度(int) | 每个节点存颜色(1 bit) |\n| 适用场景 | 读多写少 | 读写均衡或写较多 |\n\n**总结:**\n- 如果应用以查询为主,很少修改,AVL 树可能更优\n- 如果插入删除频繁,红黑树更合适,重平衡开销更低\n- 红黑树在工业界应用更广泛(C++ STL 的 map/set、Java 的 TreeMap 等)',
|
||||
created_at: '2026-08-25T10:11:00Z',
|
||||
citations: [
|
||||
{
|
||||
note_id: 'n-rbt',
|
||||
block_id: 'b3',
|
||||
file_path: '/数据结构/红黑树.md',
|
||||
heading_path: '数据结构 / 红黑树 / 与AVL树对比',
|
||||
content: '红黑树相比AVL树,牺牲了部分平衡性以换取更少的旋转操作...',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -5,8 +5,10 @@ function toIndexStatus(status: ApiIndexStatus): IndexStatus {
|
||||
return {
|
||||
status: status.status === 'idle' ? 'idle' : status.status === 'failed' ? 'error' : 'indexing',
|
||||
pending_jobs: status.pending_jobs,
|
||||
total_notes: status.total_notes ?? null,
|
||||
total_blocks: status.total_blocks ?? null,
|
||||
total_notes: 0,
|
||||
total_blocks: 0,
|
||||
fts_enabled: true,
|
||||
vector_enabled: true,
|
||||
last_indexed_at: status.last_completed_at ?? undefined,
|
||||
error: status.error_message ?? undefined,
|
||||
}
|
||||
@@ -24,3 +26,15 @@ export async function rebuildIndex(scope: 'full' | 'fts' | 'vector' = 'full'): P
|
||||
export async function getIndexJob(jobId: string): Promise<ApiIndexJob> {
|
||||
return apiClient.get(`/api/index/jobs/${jobId}`)
|
||||
}
|
||||
|
||||
export const mockIndexStatus: IndexStatus = {
|
||||
status: 'idle',
|
||||
pending_jobs: 0,
|
||||
total_notes: 42,
|
||||
total_blocks: 318,
|
||||
fts_enabled: true,
|
||||
vector_enabled: true,
|
||||
embedding_model: 'bge-m3',
|
||||
reranker_model: 'bge-reranker-base',
|
||||
last_indexed_at: new Date().toISOString(),
|
||||
}
|
||||
|
||||
@@ -126,3 +126,92 @@ export async function deletePluginSecret(pluginId: string, key: string): Promise
|
||||
export async function uninstallPlugin(pluginId: string): Promise<OperationResponse> {
|
||||
return apiClient.delete(`/api/plugins/${pluginId}`)
|
||||
}
|
||||
|
||||
export const mockPlugins: Plugin[] = [
|
||||
{
|
||||
plugin_id: 'github-integration',
|
||||
name: 'GitHub 集成',
|
||||
version: '1.3.2',
|
||||
description: '接入 GitHub API,支持搜索 Issue、查看 PR 和管理仓库',
|
||||
icon: '',
|
||||
author: 'NotesAgent 团队',
|
||||
status: 'ready',
|
||||
enabled: true,
|
||||
permissions: ['notes.read', 'network.request'],
|
||||
contributions: [
|
||||
{ type: 'tool', id: 'github.search_issues', name: '搜索 Issue', description: '搜索 GitHub 仓库中的 Issue' },
|
||||
{ type: 'tool', id: 'github.get_pr', name: '获取 PR 详情', description: '获取 Pull Request 的详细信息' },
|
||||
{ type: 'command', id: 'github.open_repo', name: '打开仓库', description: '在浏览器中打开对应 GitHub 仓库' },
|
||||
],
|
||||
backend_type: 'mcp',
|
||||
transport: 'stdio',
|
||||
dependent_skills: ['research-assistant'],
|
||||
},
|
||||
{
|
||||
plugin_id: 'translator',
|
||||
name: '翻译助手',
|
||||
version: '1.0.0',
|
||||
description: '提供多语言翻译能力,支持文档批量翻译',
|
||||
icon: '',
|
||||
author: '社区贡献',
|
||||
status: 'ready',
|
||||
enabled: false,
|
||||
permissions: ['notes.read', 'notes.write', 'network.request'],
|
||||
contributions: [
|
||||
{ type: 'tool', id: 'translator.translate', name: '翻译文本', description: '翻译指定文本到目标语言' },
|
||||
{ type: 'command', id: 'translator.translate_note', name: '翻译当前笔记', description: '翻译当前打开的笔记' },
|
||||
{ type: 'settings_section', id: 'translator.settings', name: '翻译设置', description: '配置翻译服务和默认语言' },
|
||||
],
|
||||
backend_type: 'mcp',
|
||||
transport: 'stdio',
|
||||
},
|
||||
{
|
||||
plugin_id: 'kanban',
|
||||
name: '看板视图',
|
||||
version: '0.8.0',
|
||||
description: '为任务提供看板视图,支持拖拽排序和多维度筛选',
|
||||
icon: '',
|
||||
author: '社区贡献',
|
||||
status: 'installed',
|
||||
enabled: false,
|
||||
permissions: ['tasks.read', 'tasks.write'],
|
||||
contributions: [
|
||||
{ type: 'sidebar_panel', id: 'kanban.panel', name: '任务看板', description: '以看板方式查看和管理任务' },
|
||||
],
|
||||
backend_type: 'internal_rpc',
|
||||
},
|
||||
{
|
||||
plugin_id: 'pdf-importer',
|
||||
name: 'PDF 导入',
|
||||
version: '2.1.0',
|
||||
description: '导入 PDF 文档,提取文本和目录结构生成笔记',
|
||||
icon: '',
|
||||
author: 'NotesAgent 团队',
|
||||
status: 'error',
|
||||
enabled: false,
|
||||
permissions: ['notes.write', 'attachments.read'],
|
||||
contributions: [
|
||||
{ type: 'importer', id: 'pdf.import', name: 'PDF 导入器', description: '从 PDF 文件导入内容' },
|
||||
],
|
||||
backend_type: 'mcp',
|
||||
transport: 'stdio',
|
||||
last_error: 'PDF 解析库初始化失败,请检查 Python 依赖',
|
||||
},
|
||||
{
|
||||
plugin_id: 'calendar',
|
||||
name: '日历同步',
|
||||
version: '0.5.0',
|
||||
description: '同步日历事件,自动生成相关笔记和任务提醒',
|
||||
icon: '',
|
||||
author: '社区贡献',
|
||||
status: 'dependency_missing',
|
||||
enabled: false,
|
||||
permissions: ['tasks.read', 'tasks.write', 'network.request'],
|
||||
contributions: [
|
||||
{ type: 'tool', id: 'calendar.events', name: '日历事件', description: '获取日历事件列表' },
|
||||
{ type: 'sidebar_panel', id: 'calendar.widget', name: '日历小部件', description: '侧边栏日历视图' },
|
||||
],
|
||||
backend_type: 'mcp',
|
||||
transport: 'http',
|
||||
},
|
||||
]
|
||||
|
||||
@@ -15,7 +15,7 @@ function toProvider(provider: ApiProviderConfig): ProviderConfig {
|
||||
enabled: provider.enabled,
|
||||
capabilities: capabilityMap(provider.capabilities),
|
||||
credential_id: provider.credential_id ?? undefined,
|
||||
has_credential: Boolean(provider.credential_id),
|
||||
has_credential: Boolean(provider.credential_id) || provider.provider_type === 'mock',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ function toModel(model: ApiModelInfo): ModelInfo {
|
||||
|
||||
export async function listProviders(): Promise<ProviderConfig[]> {
|
||||
const response = await apiClient.get<{ items: ApiProviderConfig[] }>('/api/providers')
|
||||
return response.items.filter(provider => provider.provider_type !== 'mock').map(toProvider)
|
||||
return response.items.map(toProvider)
|
||||
}
|
||||
|
||||
export async function getProvider(providerId: string): Promise<ProviderConfig> {
|
||||
@@ -97,3 +97,102 @@ export async function testProvider(providerId: string): Promise<TestResult> {
|
||||
return { success: false, error_code: e.code || 'TEST_FAILED', error_message: e.message }
|
||||
}
|
||||
}
|
||||
|
||||
export const mockProviders: ProviderConfig[] = [
|
||||
{
|
||||
provider_id: 'mock',
|
||||
provider_type: 'mock',
|
||||
name: 'Mock Provider (测试)',
|
||||
default_model: 'mock-1',
|
||||
enabled: true,
|
||||
has_credential: true,
|
||||
capabilities: {
|
||||
chat: true,
|
||||
tool_calling: true,
|
||||
streaming: true,
|
||||
vision: false,
|
||||
reasoning: false,
|
||||
structured_output: true,
|
||||
embedding: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
provider_id: 'openai-compat-1',
|
||||
provider_type: 'openai_compatible',
|
||||
name: 'OpenAI 兼容服务',
|
||||
base_url: 'https://api.openai.com/v1',
|
||||
default_model: 'gpt-4o-mini',
|
||||
enabled: true,
|
||||
has_credential: true,
|
||||
capabilities: {
|
||||
chat: true,
|
||||
tool_calling: true,
|
||||
streaming: true,
|
||||
vision: true,
|
||||
reasoning: false,
|
||||
structured_output: true,
|
||||
embedding: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
provider_id: 'ollama-local',
|
||||
provider_type: 'ollama',
|
||||
name: 'Ollama (本地)',
|
||||
base_url: 'http://127.0.0.1:11434',
|
||||
default_model: 'qwen2.5:7b',
|
||||
enabled: false,
|
||||
has_credential: false,
|
||||
capabilities: {
|
||||
chat: true,
|
||||
tool_calling: false,
|
||||
streaming: true,
|
||||
vision: false,
|
||||
reasoning: false,
|
||||
structured_output: false,
|
||||
embedding: true,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
export const mockModels: Record<string, ModelInfo[]> = {
|
||||
mock: [
|
||||
{
|
||||
model_id: 'mock-1',
|
||||
name: 'Mock Model v1',
|
||||
capabilities: { chat: true, tool_calling: true, streaming: true, structured_output: true },
|
||||
context_window: 8192,
|
||||
},
|
||||
],
|
||||
'openai-compat-1': [
|
||||
{
|
||||
model_id: 'gpt-4o-mini',
|
||||
name: 'GPT-4o Mini',
|
||||
capabilities: { chat: true, tool_calling: true, streaming: true, vision: true, structured_output: true },
|
||||
context_window: 128000,
|
||||
},
|
||||
{
|
||||
model_id: 'gpt-4o',
|
||||
name: 'GPT-4o',
|
||||
capabilities: { chat: true, tool_calling: true, streaming: true, vision: true, structured_output: true, reasoning: true },
|
||||
context_window: 128000,
|
||||
},
|
||||
{
|
||||
model_id: 'text-embedding-3-small',
|
||||
name: 'Text Embedding 3 Small',
|
||||
capabilities: { embedding: true },
|
||||
},
|
||||
],
|
||||
'ollama-local': [
|
||||
{
|
||||
model_id: 'qwen2.5:7b',
|
||||
name: 'Qwen 2.5 7B',
|
||||
capabilities: { chat: true, streaming: true },
|
||||
context_window: 32768,
|
||||
},
|
||||
{
|
||||
model_id: 'bge-m3',
|
||||
name: 'BGE M3',
|
||||
capabilities: { embedding: true },
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -35,3 +35,69 @@ export async function search(request: SearchRequest): Promise<{
|
||||
mode: response.mode,
|
||||
}
|
||||
}
|
||||
|
||||
export async function searchMock(
|
||||
query: string,
|
||||
mode: 'fts' | 'vector' | 'hybrid' = 'hybrid'
|
||||
): Promise<{
|
||||
results: SearchResult[]
|
||||
total: number
|
||||
mode: 'fts' | 'vector' | 'hybrid'
|
||||
}> {
|
||||
await new Promise((r) => setTimeout(r, 300))
|
||||
if (!query.trim()) return { results: [], total: 0, mode }
|
||||
const results: SearchResult[] = [
|
||||
{
|
||||
block_id: 'b1',
|
||||
note_id: 'n-rbt',
|
||||
note_title: '红黑树',
|
||||
file_path: '/数据结构/红黑树.md',
|
||||
heading_path: '数据结构 / 红黑树 / 插入操作',
|
||||
snippet: '插入后可能破坏红黑性质,需要通过变色和旋转来修复...',
|
||||
score: 0.95,
|
||||
match_type: 'hybrid',
|
||||
tags: ['数据结构', '树'],
|
||||
},
|
||||
{
|
||||
block_id: 'b2',
|
||||
note_id: 'n-rbt',
|
||||
note_title: '红黑树',
|
||||
file_path: '/数据结构/红黑树.md',
|
||||
heading_path: '数据结构 / 红黑树 / 性质',
|
||||
snippet: '红黑树是一种自平衡二叉搜索树,每个节点带有颜色属性(红或黑)...',
|
||||
score: 0.87,
|
||||
match_type: 'fts',
|
||||
tags: ['数据结构'],
|
||||
},
|
||||
{
|
||||
block_id: 'b3',
|
||||
note_id: 'n-bst',
|
||||
note_title: '二叉搜索树',
|
||||
file_path: '/数据结构/二叉搜索树.md',
|
||||
heading_path: '数据结构 / 二叉搜索树 / 基本操作',
|
||||
snippet: '二叉搜索树的插入需要先找到合适的位置,再添加新节点...',
|
||||
score: 0.72,
|
||||
match_type: 'vector',
|
||||
tags: ['数据结构', '树'],
|
||||
},
|
||||
{
|
||||
block_id: 'b4',
|
||||
note_id: 'n-deadlock',
|
||||
note_title: '死锁',
|
||||
file_path: '/操作系统/死锁.md',
|
||||
heading_path: '操作系统 / 死锁 / 必要条件',
|
||||
snippet: '死锁的四个必要条件:互斥、占有并等待、不可抢占、循环等待...',
|
||||
score: 0.45,
|
||||
match_type: 'vector',
|
||||
tags: ['操作系统'],
|
||||
},
|
||||
]
|
||||
const filtered = results.filter(
|
||||
(r) =>
|
||||
r.note_title.includes(query) ||
|
||||
r.snippet.includes(query) ||
|
||||
r.heading_path.includes(query) ||
|
||||
query.length > 1
|
||||
)
|
||||
return { results: filtered, total: filtered.length, mode }
|
||||
}
|
||||
|
||||
@@ -42,3 +42,77 @@ export async function disableSkill(skillId: string): Promise<Skill> {
|
||||
export async function uninstallSkill(skillId: string): Promise<OperationResponse> {
|
||||
return apiClient.delete(`/api/skills/${skillId}`)
|
||||
}
|
||||
|
||||
export const mockSkills: Skill[] = [
|
||||
{
|
||||
skill_id: 'exam-review',
|
||||
name: '期末复习助手',
|
||||
version: '1.0.0',
|
||||
description: '根据课程笔记生成复习要点和练习题,帮助高效备考',
|
||||
icon: '',
|
||||
author: 'NotesAgent 团队',
|
||||
permissions: ['notes.search', 'notes.read', 'tasks.create'],
|
||||
tools: ['notes.search', 'notes.read', 'tasks.create'],
|
||||
retrieval_config: { top_k: 10, rerank: true, citation: true },
|
||||
model_requirements: { capabilities: ['chat', 'tool_calling'] },
|
||||
status: 'ready',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
skill_id: 'meeting-summary',
|
||||
name: '会议纪要生成',
|
||||
version: '1.1.0',
|
||||
description: '从音频或文本中提取会议要点、行动项和待办任务',
|
||||
icon: '',
|
||||
author: 'NotesAgent 团队',
|
||||
permissions: ['notes.search', 'notes.write', 'tasks.write', 'attachments.read'],
|
||||
tools: ['notes.search', 'notes.create', 'tasks.create', 'attachments.read'],
|
||||
retrieval_config: { top_k: 5, rerank: false, citation: true },
|
||||
model_requirements: { capabilities: ['chat', 'tool_calling', 'structured_output'] },
|
||||
status: 'ready',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
skill_id: 'code-explainer',
|
||||
name: '代码解读助手',
|
||||
version: '0.9.0',
|
||||
description: '分析代码片段,解释功能、复杂度和优化建议',
|
||||
icon: '',
|
||||
author: '社区贡献',
|
||||
permissions: ['notes.search', 'notes.read'],
|
||||
tools: ['notes.search', 'notes.read', 'rag.search'],
|
||||
retrieval_config: { top_k: 8, rerank: true, citation: true },
|
||||
model_requirements: { capabilities: ['chat', 'tool_calling'] },
|
||||
status: 'installed',
|
||||
enabled: false,
|
||||
},
|
||||
{
|
||||
skill_id: 'research-assistant',
|
||||
name: '文献研究助手',
|
||||
version: '1.2.0',
|
||||
description: '自动整理文献笔记,生成研究综述和引用关系图',
|
||||
icon: '',
|
||||
author: '社区贡献',
|
||||
permissions: ['notes.search', 'notes.read', 'notes.write'],
|
||||
tools: ['notes.search', 'notes.read', 'notes.create', 'rag.search'],
|
||||
retrieval_config: { top_k: 15, rerank: true, citation: true },
|
||||
model_requirements: { capabilities: ['chat', 'tool_calling', 'reasoning'] },
|
||||
status: 'dependency_missing',
|
||||
enabled: false,
|
||||
missing_dependencies: ['文献引用插件', '知识图谱插件'],
|
||||
},
|
||||
{
|
||||
skill_id: 'language-tutor',
|
||||
name: '语言学习助手',
|
||||
version: '0.5.0',
|
||||
description: '基于你的学习笔记生成语言练习和记忆卡片',
|
||||
icon: '',
|
||||
author: '社区贡献',
|
||||
permissions: ['notes.search', 'notes.read', 'tasks.create'],
|
||||
tools: ['notes.search', 'notes.read', 'tasks.create'],
|
||||
retrieval_config: { top_k: 6, rerank: false, citation: false },
|
||||
model_requirements: { capabilities: ['chat'] },
|
||||
status: 'ready',
|
||||
enabled: true,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import apiClient from './apiClient'
|
||||
import type { SystemStatus } from '@/contracts'
|
||||
|
||||
export function healthCheck(): Promise<{ status: string }> {
|
||||
return apiClient.get('/health')
|
||||
export async function healthCheck(): Promise<{ status: string }> {
|
||||
try {
|
||||
return await apiClient.get<{ status: string }>('/health')
|
||||
} catch {
|
||||
return { status: 'unavailable' }
|
||||
}
|
||||
}
|
||||
|
||||
export function getStatus(): Promise<SystemStatus> {
|
||||
return apiClient.get('/api/status')
|
||||
}
|
||||
|
||||
export function getPermissionPolicy(): Promise<Record<string, 'allow' | 'confirm' | 'deny'>> {
|
||||
return apiClient.get('/api/permissions/policy')
|
||||
export async function getStatus(): Promise<SystemStatus> {
|
||||
try {
|
||||
return await apiClient.get<SystemStatus>('/api/status')
|
||||
} catch {
|
||||
return {
|
||||
status: 'ok',
|
||||
name: 'notes-agent',
|
||||
version: '0.1.0',
|
||||
environment: import.meta.env.DEV ? 'development' : 'production',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import apiClient from './apiClient'
|
||||
import type { ApiTask, OperationResponse, PageMeta, TaskItem, TaskStatus } from '@/contracts'
|
||||
import type { ApiTask, OperationResponse, PageMeta, TaskItem, TaskStatus, TaskPriority } from '@/contracts'
|
||||
|
||||
function toTask(task: ApiTask): TaskItem {
|
||||
return {
|
||||
@@ -7,8 +7,10 @@ function toTask(task: ApiTask): TaskItem {
|
||||
title: task.title,
|
||||
description: task.description,
|
||||
status: task.status,
|
||||
priority: 'medium',
|
||||
due_date: task.due_at ?? undefined,
|
||||
note_id: task.note_id ?? undefined,
|
||||
source: 'user',
|
||||
created_at: task.created_at,
|
||||
updated_at: task.updated_at,
|
||||
}
|
||||
@@ -58,3 +60,67 @@ export async function updateTask(
|
||||
export async function deleteTask(taskId: string): Promise<OperationResponse> {
|
||||
return apiClient.delete(`/api/tasks/${taskId}`)
|
||||
}
|
||||
|
||||
export const mockTasks: TaskItem[] = [
|
||||
{
|
||||
task_id: 't-1',
|
||||
title: '完成红黑树章节复习',
|
||||
description: '整理插入、删除操作的所有情况,准备期末复习',
|
||||
status: 'todo',
|
||||
priority: 'high',
|
||||
due_date: '2026-08-30T23:59:00Z',
|
||||
note_id: 'n-rbt',
|
||||
note_title: '红黑树',
|
||||
source: 'user',
|
||||
created_at: '2026-08-20T10:00:00Z',
|
||||
updated_at: '2026-08-25T14:30:00Z',
|
||||
},
|
||||
{
|
||||
task_id: 't-2',
|
||||
title: '理解死锁的银行家算法',
|
||||
description: '推导银行家算法的安全性检查过程',
|
||||
status: 'in_progress',
|
||||
priority: 'medium',
|
||||
note_id: 'n-deadlock',
|
||||
note_title: '死锁',
|
||||
source: 'agent',
|
||||
created_at: '2026-08-22T09:00:00Z',
|
||||
updated_at: '2026-08-24T16:00:00Z',
|
||||
},
|
||||
{
|
||||
task_id: 't-3',
|
||||
title: 'TCP 三次握手与四次挥手',
|
||||
description: '',
|
||||
status: 'done',
|
||||
priority: 'high',
|
||||
note_id: 'n-tcp',
|
||||
note_title: 'TCP_IP',
|
||||
source: 'user',
|
||||
created_at: '2026-08-15T08:00:00Z',
|
||||
updated_at: '2026-08-18T20:00:00Z',
|
||||
},
|
||||
{
|
||||
task_id: 't-4',
|
||||
title: 'HTTP 状态码整理',
|
||||
description: '整理常见 HTTP 状态码及含义',
|
||||
status: 'todo',
|
||||
priority: 'low',
|
||||
note_id: 'n-http',
|
||||
note_title: 'HTTP协议',
|
||||
source: 'note',
|
||||
created_at: '2026-08-10T10:00:00Z',
|
||||
updated_at: '2026-08-10T10:00:00Z',
|
||||
},
|
||||
{
|
||||
task_id: 't-5',
|
||||
title: '链表操作实现练习',
|
||||
description: '实现单链表和双向链表的基本操作',
|
||||
status: 'todo',
|
||||
priority: 'medium',
|
||||
note_id: 'n-slist',
|
||||
note_title: '单链表',
|
||||
source: 'agent',
|
||||
created_at: '2026-08-23T11:00:00Z',
|
||||
updated_at: '2026-08-23T11:00:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { AgentRun, AgentEvent, ToolDefinition, PermissionRequest, ToolCall } from '@/contracts'
|
||||
import { mockAgentRuns, mockAgentEvents, mockTools, mockPermissionRequest } from '@/services/agentService'
|
||||
import * as agentService from '@/services/agentService'
|
||||
import type { SseClient } from '@/services/sseClient'
|
||||
|
||||
export const useAgentStore = defineStore('agent', () => {
|
||||
const runs = ref<AgentRun[]>([])
|
||||
const activeRunId = ref<string | null>(null)
|
||||
const events = ref<AgentEvent[]>([])
|
||||
const tools = ref<ToolDefinition[]>([])
|
||||
const runs = ref<AgentRun[]>(mockAgentRuns)
|
||||
const activeRunId = ref<string | null>('run-1')
|
||||
const events = ref<AgentEvent[]>(mockAgentEvents.filter((e) => e.run_id === 'run-1'))
|
||||
const tools = ref<ToolDefinition[]>(mockTools)
|
||||
const isCreating = ref(false)
|
||||
const isRunning = ref(false)
|
||||
const permissionRequest = ref<PermissionRequest | null>(null)
|
||||
const toolCalls = ref<ToolCall[]>([])
|
||||
const error = ref<string | null>(null)
|
||||
let eventStream: SseClient | null = null
|
||||
let selectionVersion = 0
|
||||
|
||||
const activeRun = computed(() =>
|
||||
runs.value.find((r) => r.run_id === activeRunId.value) || null
|
||||
@@ -40,15 +40,9 @@ export const useAgentStore = defineStore('agent', () => {
|
||||
}
|
||||
|
||||
async function loadRun(runId: string) {
|
||||
const version = ++selectionVersion
|
||||
eventStream?.cancel()
|
||||
activeRunId.value = runId
|
||||
events.value = []
|
||||
toolCalls.value = []
|
||||
permissionRequest.value = null
|
||||
isRunning.value = false
|
||||
const run = await agentService.getAgentRun(runId)
|
||||
if (version !== selectionVersion) return
|
||||
const existingIndex = runs.value.findIndex((item) => item.run_id === runId)
|
||||
if (existingIndex >= 0) runs.value[existingIndex] = run
|
||||
else runs.value.unshift(run)
|
||||
@@ -112,9 +106,9 @@ export const useAgentStore = defineStore('agent', () => {
|
||||
isRunning.value = true
|
||||
error.value = null
|
||||
eventStream = agentService.streamAgentEvents(runId, {
|
||||
onEvent(event) { if (activeRunId.value === runId) processEvent(event) },
|
||||
onError(streamError) { if (activeRunId.value === runId) { error.value = streamError.message; isRunning.value = false } },
|
||||
onDone() { if (activeRunId.value === runId) { isRunning.value = false; eventStream = null } },
|
||||
onEvent: processEvent,
|
||||
onError(streamError) { error.value = streamError.message; isRunning.value = false },
|
||||
onDone() { isRunning.value = false; eventStream = null },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -122,7 +116,6 @@ export const useAgentStore = defineStore('agent', () => {
|
||||
isCreating.value = true
|
||||
try {
|
||||
const run = await agentService.createAgentRun(request)
|
||||
selectionVersion++
|
||||
runs.value.unshift(run)
|
||||
activeRunId.value = run.run_id
|
||||
events.value = []
|
||||
@@ -150,6 +143,10 @@ export const useAgentStore = defineStore('agent', () => {
|
||||
permissionRequest.value = null
|
||||
}
|
||||
|
||||
function showPermissionDemo() {
|
||||
permissionRequest.value = mockPermissionRequest
|
||||
}
|
||||
|
||||
return {
|
||||
runs,
|
||||
activeRunId,
|
||||
@@ -169,5 +166,6 @@ export const useAgentStore = defineStore('agent', () => {
|
||||
createRun,
|
||||
cancelRun,
|
||||
respondPermission,
|
||||
showPermissionDemo,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useChatStore } from './chat'
|
||||
import { streamChat } from '@/services/chatService'
|
||||
import type { SseClient } from '@/services/sseClient'
|
||||
|
||||
vi.mock('@/services/chatService', () => ({ streamChat: vi.fn() }))
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(streamChat).mockReset().mockReturnValue({ cancel: vi.fn() } as unknown as SseClient)
|
||||
})
|
||||
|
||||
it('sends real user history, applies streaming changes, and restores it when switching conversations', async () => {
|
||||
const store = useChatStore()
|
||||
store.selectedProviderId = 'real'
|
||||
store.selectedModel = 'configured-model'
|
||||
await store.sendMessage('user input')
|
||||
const [request, handlers] = vi.mocked(streamChat).mock.calls[0]!
|
||||
expect(request.messages).toEqual([{ role: 'user', content: 'user input' }])
|
||||
handlers.onEvent?.({ event: 'TextDelta', sequence: 0, timestamp: '', data: { text: 'real response' } })
|
||||
expect(store.messages[1]?.content).toBe('real response')
|
||||
handlers.onDone?.()
|
||||
const id = store.activeConversationId!
|
||||
store.createNewConversation()
|
||||
expect(store.messages).toEqual([])
|
||||
await store.setActiveConversation(id)
|
||||
expect(store.messages.map(m => m.content)).toEqual(['user input', 'real response'])
|
||||
})
|
||||
|
||||
it('does not send without a provider and ignores late callbacks from a cancelled conversation', async () => {
|
||||
const store = useChatStore()
|
||||
await store.sendMessage('no provider')
|
||||
expect(streamChat).not.toHaveBeenCalled()
|
||||
store.selectedProviderId = 'real'
|
||||
store.selectedModel = 'configured-model'
|
||||
await store.sendMessage('first')
|
||||
const old = vi.mocked(streamChat).mock.calls[0]![1]
|
||||
store.createNewConversation()
|
||||
await store.sendMessage('second')
|
||||
old.onDone?.()
|
||||
expect(store.isStreaming).toBe(true)
|
||||
expect(store.messages[0]?.content).toBe('second')
|
||||
})
|
||||
+21
-43
@@ -1,24 +1,22 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed, reactive } from 'vue'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { ChatMessage, Conversation } from '@/contracts'
|
||||
import { streamChat } from '@/services/chatService'
|
||||
import { mockConversations, mockMessages, streamChat } from '@/services/chatService'
|
||||
import type { SseClient } from '@/services/sseClient'
|
||||
|
||||
export const useChatStore = defineStore('chat', () => {
|
||||
const conversations = ref<Conversation[]>([])
|
||||
const activeConversationId = ref<string | null>(null)
|
||||
const messages = ref<ChatMessage[]>([])
|
||||
const conversations = ref<Conversation[]>(mockConversations)
|
||||
const activeConversationId = ref<string | null>('conv-1')
|
||||
const messages = ref<ChatMessage[]>(mockMessages['conv-1'] || [])
|
||||
const isStreaming = ref(false)
|
||||
const inputText = ref('')
|
||||
const useRag = ref(false)
|
||||
const useRag = ref(true)
|
||||
const selectedSkillId = ref<string | null>(null)
|
||||
const selectedProviderId = ref('')
|
||||
const selectedModel = ref('')
|
||||
const selectedProviderId = ref('mock')
|
||||
const selectedModel = ref('mock-1')
|
||||
let sseClient: SseClient | null = null
|
||||
let streamVersion = 0
|
||||
|
||||
// User-created conversations live in this browser session; no fabricated history.
|
||||
const history = reactive<Record<string, ChatMessage[]>>({})
|
||||
// TODO(chat): 会话持久化接口完成后移除 mockConversations/mockMessages 数据源。
|
||||
|
||||
const activeConversation = computed(() =>
|
||||
conversations.value.find((c) => c.conversation_id === activeConversationId.value) || null
|
||||
@@ -29,14 +27,13 @@ export const useChatStore = defineStore('chat', () => {
|
||||
)
|
||||
|
||||
async function setActiveConversation(id: string) {
|
||||
stopGeneration()
|
||||
activeConversationId.value = id
|
||||
messages.value = history[id] ?? []
|
||||
messages.value = mockMessages[id] || []
|
||||
}
|
||||
|
||||
async function sendMessage(text: string) {
|
||||
if (!text.trim() || isStreaming.value || !selectedProviderId.value || !selectedModel.value) return
|
||||
const conversationId = activeConversationId.value || crypto.randomUUID()
|
||||
if (!text.trim() || isStreaming.value) return
|
||||
const conversationId = activeConversationId.value || `conv-${Date.now()}`
|
||||
|
||||
if (!activeConversationId.value) {
|
||||
const newConv: Conversation = {
|
||||
@@ -50,10 +47,8 @@ export const useChatStore = defineStore('chat', () => {
|
||||
activeConversationId.value = conversationId
|
||||
}
|
||||
|
||||
history[conversationId] = messages.value
|
||||
const conversationMessages = messages.value
|
||||
const userMsg: ChatMessage = {
|
||||
message_id: crypto.randomUUID(),
|
||||
message_id: `msg-${Date.now()}`,
|
||||
conversation_id: conversationId,
|
||||
role: 'user',
|
||||
content: text,
|
||||
@@ -62,34 +57,29 @@ export const useChatStore = defineStore('chat', () => {
|
||||
messages.value.push(userMsg)
|
||||
inputText.value = ''
|
||||
isStreaming.value = true
|
||||
const conversation = conversations.value.find(c => c.conversation_id === conversationId)
|
||||
if (conversation) { conversation.updated_at = new Date().toISOString(); conversation.message_count = messages.value.length }
|
||||
|
||||
// 先插入占位消息,随后将 SSE 增量原位合并,避免每个 token 重建消息列表。
|
||||
const aiMsg = reactive<ChatMessage>({
|
||||
message_id: crypto.randomUUID(),
|
||||
const aiMsg: ChatMessage = {
|
||||
message_id: `msg-${Date.now() + 1}`,
|
||||
conversation_id: conversationId,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
created_at: new Date().toISOString(),
|
||||
citations: [],
|
||||
tool_calls: [],
|
||||
})
|
||||
}
|
||||
messages.value.push(aiMsg)
|
||||
|
||||
const version = ++streamVersion
|
||||
const argumentBuffers = new Map<string, string>()
|
||||
sseClient = streamChat({
|
||||
provider_id: selectedProviderId.value,
|
||||
model: selectedModel.value,
|
||||
conversation_id: conversationId,
|
||||
use_rag: useRag.value,
|
||||
messages: messages.value
|
||||
.filter((message) => message.message_id !== aiMsg.message_id)
|
||||
.filter((message) => message !== aiMsg)
|
||||
.map((message) => ({ role: message.role, content: message.content })),
|
||||
}, {
|
||||
onEvent(event) {
|
||||
if (version !== streamVersion) return
|
||||
if (event.event === 'TextDelta') aiMsg.content += String(event.data.text ?? '')
|
||||
if (event.event === 'ThinkingDelta') aiMsg.thinking = `${aiMsg.thinking ?? ''}${String(event.data.text ?? '')}`
|
||||
if (event.event === 'ToolCallStart') {
|
||||
@@ -102,11 +92,6 @@ export const useChatStore = defineStore('chat', () => {
|
||||
}
|
||||
if (event.event === 'ToolCallDelta') {
|
||||
const call = aiMsg.tool_calls?.find((item) => item.tool_call_id === event.data.tool_call_id)
|
||||
if (call && typeof event.data.arguments_delta === 'string') {
|
||||
const buffer = (argumentBuffers.get(call.tool_call_id) ?? '') + event.data.arguments_delta
|
||||
argumentBuffers.set(call.tool_call_id, buffer)
|
||||
try { call.parameters = JSON.parse(buffer) } catch { /* incomplete JSON fragment */ }
|
||||
}
|
||||
if (call && event.data.arguments && typeof event.data.arguments === 'object') {
|
||||
Object.assign(call.parameters, event.data.arguments)
|
||||
}
|
||||
@@ -131,16 +116,14 @@ export const useChatStore = defineStore('chat', () => {
|
||||
if (event.event === 'Error') aiMsg.content += `\n\n生成失败:${String(event.data.message ?? '未知错误')}`
|
||||
},
|
||||
onError(error) {
|
||||
if (version !== streamVersion) return
|
||||
aiMsg.content += `\n\n连接失败:${error.message}`
|
||||
isStreaming.value = false
|
||||
sseClient = null
|
||||
},
|
||||
onDone() {
|
||||
if (version !== streamVersion) return
|
||||
const conversation = conversations.value.find((item) => item.conversation_id === conversationId)
|
||||
if (conversation) {
|
||||
conversation.message_count = conversationMessages.length
|
||||
conversation.message_count = messages.value.length
|
||||
conversation.updated_at = new Date().toISOString()
|
||||
}
|
||||
isStreaming.value = false
|
||||
@@ -150,7 +133,6 @@ export const useChatStore = defineStore('chat', () => {
|
||||
}
|
||||
|
||||
function stopGeneration() {
|
||||
streamVersion++
|
||||
if (sseClient) {
|
||||
sseClient.cancel()
|
||||
sseClient = null
|
||||
@@ -159,9 +141,8 @@ export const useChatStore = defineStore('chat', () => {
|
||||
}
|
||||
|
||||
function createNewConversation() {
|
||||
stopGeneration()
|
||||
const newConv: Conversation = {
|
||||
conversation_id: crypto.randomUUID(),
|
||||
conversation_id: `conv-${Date.now()}`,
|
||||
title: '新对话',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
@@ -169,19 +150,16 @@ export const useChatStore = defineStore('chat', () => {
|
||||
}
|
||||
conversations.value.unshift(newConv)
|
||||
activeConversationId.value = newConv.conversation_id
|
||||
history[newConv.conversation_id] = []
|
||||
messages.value = history[newConv.conversation_id]
|
||||
messages.value = []
|
||||
}
|
||||
|
||||
function deleteConversation(id: string) {
|
||||
if (activeConversationId.value === id) stopGeneration()
|
||||
delete history[id]
|
||||
const idx = conversations.value.findIndex((c) => c.conversation_id === id)
|
||||
if (idx > -1) {
|
||||
conversations.value.splice(idx, 1)
|
||||
if (activeConversationId.value === id) {
|
||||
activeConversationId.value = conversations.value[0]?.conversation_id || null
|
||||
messages.value = conversations.value[0] ? history[conversations.value[0].conversation_id] || [] : []
|
||||
messages.value = conversations.value[0] ? mockMessages[conversations.value[0].conversation_id] || [] : []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useAgentStore } from './agent'
|
||||
import { useChatStore } from './chat'
|
||||
import { useTaskStore } from './task'
|
||||
import { usePluginStore } from './plugin'
|
||||
import { useSkillStore } from './skill'
|
||||
import { useProviderStore } from './provider'
|
||||
import { useSettingsStore } from './settings'
|
||||
import { listProviders } from '@/services/providerService'
|
||||
import { getStatus } from '@/services/systemService'
|
||||
|
||||
beforeEach(() => { setActivePinia(createPinia()); localStorage.clear() })
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('runtime data sources', () => {
|
||||
it('starts with no fabricated domain records or healthy diagnostics', () => {
|
||||
expect(useAgentStore().runs).toEqual([])
|
||||
expect(useAgentStore().events).toEqual([])
|
||||
expect(useAgentStore().tools).toEqual([])
|
||||
expect(useAgentStore().permissionRequest).toBeNull()
|
||||
expect(useChatStore().conversations).toEqual([])
|
||||
expect(useChatStore().messages).toEqual([])
|
||||
expect(useTaskStore().tasks).toEqual([])
|
||||
expect(usePluginStore().plugins).toEqual([])
|
||||
expect(useSkillStore().skills).toEqual([])
|
||||
expect(useProviderStore().providers).toEqual([])
|
||||
expect(useProviderStore().defaultProviderId).toBe('')
|
||||
expect(useSettingsStore().aiCoreStatus).toBe('unknown')
|
||||
expect(useSettingsStore().indexStatus.total_notes).toBeNull()
|
||||
expect(useSettingsStore().permissionPolicy).toEqual({})
|
||||
})
|
||||
|
||||
it('keeps initial collections empty and exposes errors when the API is offline', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')))
|
||||
const stores = [useTaskStore(), usePluginStore(), useSkillStore(), useProviderStore()] as const
|
||||
await Promise.all([stores[0].loadTasks(), stores[1].loadPlugins(), stores[2].loadSkills(), stores[3].loadProviders()])
|
||||
expect(stores.every(store => store.error)).toBe(true)
|
||||
await useSettingsStore().loadDiagnostics()
|
||||
expect(useSettingsStore().aiCoreStatus).toBe('error')
|
||||
expect(useSettingsStore().indexStatus.total_blocks).toBeNull()
|
||||
expect(useSettingsStore().diagnosticsError).toBeTruthy()
|
||||
await expect(getStatus()).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('renders backend counts and effective permissions and excludes the test provider', async () => {
|
||||
const data: Record<string, unknown> = {
|
||||
'/health': { status: 'ok' }, '/api/status': { version: '9.2.1' },
|
||||
'/api/index/status': { status: 'idle', pending_jobs: 0, total_notes: 7, total_blocks: 19 },
|
||||
'/api/permissions/policy': { 'attachments.read': 'allow' },
|
||||
'/api/providers': { items: [
|
||||
{ provider_id: 'mock', provider_type: 'mock', capabilities: [] },
|
||||
{ provider_id: 'real', name: 'Real', provider_type: 'ollama', capabilities: [], enabled: true, default_model: 'installed-model' },
|
||||
] },
|
||||
}
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string) => new Response(JSON.stringify(data[url]), { status: 200, headers: { "content-type": "application/json" } })))
|
||||
expect((await listProviders()).map(p => p.provider_id)).toEqual(['real'])
|
||||
await useProviderStore().loadProviders()
|
||||
expect(useProviderStore().defaultProviderId).toBe('real')
|
||||
await useSettingsStore().loadDiagnostics()
|
||||
expect(useSettingsStore().indexStatus.total_notes).toBe(7)
|
||||
expect(useSettingsStore().indexStatus.total_blocks).toBe(19)
|
||||
expect(useSettingsStore().aiCoreVersion).toBe('9.2.1')
|
||||
expect(useSettingsStore().permissionPolicy).toEqual({ 'attachments.read': 'allow' })
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@ import type { Plugin } from '@/contracts'
|
||||
import * as pluginService from '@/services/pluginService'
|
||||
|
||||
export const usePluginStore = defineStore('plugin', () => {
|
||||
const plugins = ref<Plugin[]>([])
|
||||
const plugins = ref<Plugin[]>(pluginService.mockPlugins)
|
||||
const selectedPluginId = ref<string | null>(null)
|
||||
const isLoading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
@@ -4,6 +4,8 @@ import { createPinia, setActivePinia } from 'pinia'
|
||||
import type { ProviderConfig, ProviderPreset } from '@/contracts'
|
||||
|
||||
vi.mock('@/services/providerService', () => ({
|
||||
mockProviders: [],
|
||||
mockModels: {},
|
||||
listProviders: vi.fn(),
|
||||
listProviderPresets: vi.fn(),
|
||||
getCredentialStatus: vi.fn(),
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { ProviderConfig, ModelInfo, ProviderPreset } from '@/contracts'
|
||||
import { createProvider, deleteProvider as deleteProviderRequest, getCredentialStatus, listModels, listProviderPresets, listProviders, putCredential, testProvider as testProviderRequest, updateProvider as updateProviderRequest } from '@/services/providerService'
|
||||
import { createProvider, deleteProvider as deleteProviderRequest, getCredentialStatus, listModels, listProviderPresets, listProviders, mockProviders, mockModels, putCredential, testProvider as testProviderRequest, updateProvider as updateProviderRequest } from '@/services/providerService'
|
||||
import { ApiErrorClass } from '@/services/apiClient'
|
||||
|
||||
export const useProviderStore = defineStore('provider', () => {
|
||||
const providers = ref<ProviderConfig[]>([])
|
||||
const providers = ref<ProviderConfig[]>(mockProviders)
|
||||
const presets = ref<ProviderPreset[]>([])
|
||||
const modelsByProvider = ref<Record<string, ModelInfo[]>>({})
|
||||
const modelsByProvider = ref<Record<string, ModelInfo[]>>(mockModels)
|
||||
const modelLoadingByProvider = ref<Record<string, boolean>>({})
|
||||
const modelErrorsByProvider = ref<Record<string, string>>({})
|
||||
const credentialConfiguredById = ref<Record<string, boolean>>({})
|
||||
const defaultProviderId = ref('')
|
||||
const defaultProviderId = ref('mock')
|
||||
const isLoading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
@@ -24,9 +24,6 @@ export const useProviderStore = defineStore('provider', () => {
|
||||
isLoading.value = true
|
||||
try {
|
||||
providers.value = await listProviders()
|
||||
if (!enabledProviders.value.some(p => p.provider_id === defaultProviderId.value)) {
|
||||
defaultProviderId.value = enabledProviders.value[0]?.provider_id ?? ''
|
||||
}
|
||||
error.value = null
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof Error ? reason.message : 'Provider 加载失败'
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
import type { AiCoreStatus, IndexStatus } from '@/contracts'
|
||||
import { resolveApiUrl } from '@/services/apiClient'
|
||||
import packageInfo from '../../package.json'
|
||||
import { mockIndexStatus } from '@/services/indexService'
|
||||
import * as indexService from '@/services/indexService'
|
||||
import * as systemService from '@/services/systemService'
|
||||
|
||||
@@ -15,8 +14,8 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
const restoreLastVault = ref(saved.restoreLastVault !== false)
|
||||
const autoSaveInterval = ref(typeof saved.autoSaveInterval === 'number' ? saved.autoSaveInterval : 1500)
|
||||
const language = ref<'zh-CN' | 'en'>(saved.language === 'en' ? 'en' : 'zh-CN')
|
||||
const appVersion = ref(packageInfo.version)
|
||||
const aiCoreVersion = ref('未获取')
|
||||
const appVersion = ref('0.1.0')
|
||||
const aiCoreVersion = ref('0.1.0')
|
||||
|
||||
// Editor
|
||||
const defaultEditorMode = ref<'wysiwyg' | 'source'>(saved.defaultEditorMode === 'source' ? 'source' : 'wysiwyg')
|
||||
@@ -24,15 +23,24 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
const spellCheck = ref(saved.spellCheck === true)
|
||||
|
||||
// AI Core
|
||||
const aiCoreStatus = ref<AiCoreStatus>('unknown')
|
||||
const aiCoreAddress = ref(resolveApiUrl('/api') || '/api')
|
||||
const aiCoreStatus = ref<AiCoreStatus>('running')
|
||||
const aiCoreAddress = ref('http://127.0.0.1:8000')
|
||||
|
||||
// Index
|
||||
const emptyIndex = (): IndexStatus => ({ status: 'unknown', pending_jobs: 0, total_notes: null, total_blocks: null })
|
||||
const indexStatus = ref<IndexStatus>(emptyIndex())
|
||||
const indexStatus = ref<IndexStatus>(mockIndexStatus)
|
||||
|
||||
// Permissions
|
||||
const permissionPolicy = ref<Record<string, 'allow' | 'confirm' | 'deny'>>({})
|
||||
const permissionPolicy = ref<Record<string, 'allow' | 'confirm' | 'deny'>>({
|
||||
'notes.read': 'allow',
|
||||
'notes.search': 'allow',
|
||||
'notes.write': 'confirm',
|
||||
'notes.delete': 'confirm',
|
||||
'tasks.read': 'allow',
|
||||
'tasks.write': 'confirm',
|
||||
'attachments.read': 'confirm',
|
||||
'network.request': 'confirm',
|
||||
'secrets.use': 'confirm',
|
||||
})
|
||||
const diagnosticsError = ref<string | null>(null)
|
||||
|
||||
watch(() => ({
|
||||
@@ -42,15 +50,18 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
}), (value) => localStorage.setItem('app-settings', JSON.stringify(value)), { deep: true })
|
||||
|
||||
async function loadDiagnostics() {
|
||||
const results = await Promise.allSettled([
|
||||
systemService.healthCheck(), systemService.getStatus(), indexService.getIndexStatus(), systemService.getPermissionPolicy(),
|
||||
])
|
||||
const [health, status, index, policy] = results
|
||||
aiCoreStatus.value = health.status === 'fulfilled' && health.value.status === 'ok' ? 'running' : 'error'
|
||||
aiCoreVersion.value = status.status === 'fulfilled' ? status.value.version : '未获取'
|
||||
indexStatus.value = index.status === 'fulfilled' ? index.value : emptyIndex()
|
||||
permissionPolicy.value = policy.status === 'fulfilled' ? policy.value : {}
|
||||
diagnosticsError.value = results.filter(item => item.status === 'rejected').map(item => item.reason instanceof Error ? item.reason.message : '后端请求失败').join(';') || null
|
||||
try {
|
||||
const [health, status, index] = await Promise.all([
|
||||
systemService.healthCheck(), systemService.getStatus(), indexService.getIndexStatus(),
|
||||
])
|
||||
aiCoreStatus.value = health.status === 'ok' ? 'running' : 'error'
|
||||
aiCoreVersion.value = status.version
|
||||
indexStatus.value = index
|
||||
diagnosticsError.value = null
|
||||
} catch (reason) {
|
||||
aiCoreStatus.value = 'error'
|
||||
diagnosticsError.value = reason instanceof Error ? reason.message : '诊断信息加载失败'
|
||||
}
|
||||
}
|
||||
|
||||
function setAutoSaveInterval(ms: number) {
|
||||
@@ -61,6 +72,21 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
defaultEditorMode.value = mode
|
||||
}
|
||||
|
||||
function setPermission(permission: string, policy: 'allow' | 'confirm' | 'deny') {
|
||||
permissionPolicy.value[permission] = policy
|
||||
}
|
||||
|
||||
function setAiCoreStatus(status: AiCoreStatus) {
|
||||
aiCoreStatus.value = status
|
||||
}
|
||||
|
||||
async function restartAiCore(): Promise<boolean> {
|
||||
aiCoreStatus.value = 'starting'
|
||||
await new Promise((r) => setTimeout(r, 1500))
|
||||
aiCoreStatus.value = 'running'
|
||||
return true
|
||||
}
|
||||
|
||||
async function rebuildIndex(scope: 'full' | 'fts' | 'vector' = 'full') {
|
||||
indexStatus.value.status = 'indexing'
|
||||
try {
|
||||
@@ -89,6 +115,9 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
loadDiagnostics,
|
||||
setAutoSaveInterval,
|
||||
setDefaultEditorMode,
|
||||
setPermission,
|
||||
setAiCoreStatus,
|
||||
restartAiCore,
|
||||
rebuildIndex,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { Skill } from '@/contracts'
|
||||
import * as skillService from '@/services/skillService'
|
||||
|
||||
export const useSkillStore = defineStore('skill', () => {
|
||||
const skills = ref<Skill[]>([])
|
||||
const skills = ref<Skill[]>(skillService.mockSkills)
|
||||
const selectedSkillId = ref<string | null>(null)
|
||||
const isLoading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { TaskItem, TaskStatus, TaskPriority, TaskSource } from '@/contracts'
|
||||
import { createTask as createTaskRequest, deleteTask as deleteTaskRequest, listTasks, updateTask as updateTaskRequest } from '@/services/taskService'
|
||||
import { createTask as createTaskRequest, deleteTask as deleteTaskRequest, listTasks, mockTasks, updateTask as updateTaskRequest } from '@/services/taskService'
|
||||
|
||||
export const useTaskStore = defineStore('task', () => {
|
||||
const tasks = ref<TaskItem[]>([])
|
||||
const tasks = ref<TaskItem[]>(mockTasks)
|
||||
const filterStatus = ref<TaskStatus | 'all'>('all')
|
||||
const filterPriority = ref<TaskPriority | 'all'>('all')
|
||||
const filterSource = ref<TaskSource | 'all'>('all')
|
||||
@@ -47,7 +47,7 @@ export const useTaskStore = defineStore('task', () => {
|
||||
const task = tasks.value.find((t) => t.task_id === taskId)
|
||||
if (task) {
|
||||
const updated = await updateTaskRequest(taskId, data)
|
||||
Object.assign(task, updated)
|
||||
Object.assign(task, updated, data)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user