Compare commits

..
Author SHA1 Message Date
admin e952fea2d8 fix(themes): share code line layout with isolated previews 2026-09-06 17:20:12 +08:00
admin ae3a02e827 feat(editor): add scroll navigation and update theme Markdown behavior 2026-09-06 17:15:41 +08:00
admin ddd24e9c9e fix: coordinate vector migration with concurrent searches and note saves 2026-09-06 16:57:37 +08:00
admin 544ba1216a perf: persist model-isolated sqlite-vec indexes and index new notes incrementally 2026-09-06 16:34:26 +08:00
admin 80471aef31 fix: stabilize background operations and large embedding results 2026-09-06 16:26:17 +08:00
admin 79307b9b00 perf(editor): reduce long-document decoration work and fix fold navigation 2026-09-06 14:30:56 +08:00
admin 13675f6cfd fix(editor): recover missing files and synchronize section toggle 2026-09-06 13:29:19 +08:00
admin 575bf7f58f docs(vault): 更新产品文档和演示导航内容
更新RAG检索增强文档,添加换行标记以改善显示格式。

优化功能演示导航表格布局,调整列宽使内容更易读。

清理多个演示文档的多余空行,统一文档格式规范。
2026-09-06 12:59:22 +08:00
admin e09b4ac0ce feat(editor): add markdown presets, heading folding and external file refresh 2026-09-06 12:57:09 +08:00
admin d21ce23932 feat(editor): add themed callouts and desktop command boundary 2026-09-06 11:33:19 +08:00
admin 15e10dfd68 perf(frontend): defer mermaid and split editor dependencies 2026-09-06 10:42:12 +08:00
admin 6339cf2425 docs: document background indexing and merged phase two behavior 2026-09-06 03:06:40 +08:00
Kronecker e80423781d Merge pull request 'Feat/model usage charts and paper cards完善第二阶段功能与验收:后台索引、图表交互、扩展社区及第三阶段规划' (#31) from feat/model-usage-charts-and-paper-cards into main
Reviewed-on: #31
2026-09-06 03:02:15 +08:00
Kronecker d280191744 Merge pull request 'feat: 完善主题导入、手账工作区与笔记元数据管理' (#27) from feat/theme-import-and-paper-workspace into main
Reviewed-on: #27
2026-09-05 19:42:00 +08:00
128 changed files with 12458 additions and 302 deletions
+1
View File
@@ -18,6 +18,7 @@ backend/.env
# 运行期生成的 SQLite 索引(vault 下的 Markdown 测试数据需提交)
backend/data/*.db*
backend/data/credentials/
backend/data/logs/
# 阶段验收笔记(验收用,不提交)
backend/data/vault/验收/
# 本机 MCP 配置、授权状态及服务器工作目录不得提交。
+17 -1
View File
@@ -4,7 +4,7 @@
NotesAgent 是本地优先的 AI 笔记与知识库项目。当前可运行形态为 Vue/Vite Web 前端与 FastAPI AI CoreMarkdown 和附件保存在本地 Vault,SQLite 管理元数据、全文索引、向量空间、搜索历史、AI 会话、任务、Agent Trace、多模态任务及运行诊断。AI 对话已接入知识库检索,会话与消息由后端持久化并供 Web 和桌面客户端共用。
截至 2026-09-05,第一阶段及第二阶段 A~F 的工程范围已经合并到 `main`。当前已完成真实 Workspace、混合检索与知识库问答、Agent/Tool/Permission、Skill/Plugin、MCP 配置与调用、模型提供商与路由、RAG Benchmark,以及本地 Embedding、音频转写和片段级声纹聚类。Tauri/Rust Host、Stronghold、原生多 Vault 文件系统、生产级 MCP 沙箱和 Sync Server 尚未接入。
截至 2026-09-06,第一阶段及第二阶段 A~F 的工程范围已经合并到 `main`。当前已完成真实 Workspace、混合检索与知识库问答、Agent/Tool/Permission、Skill/Plugin、MCP 配置与调用、模型提供商与路由、RAG Benchmark,以及本地 Embedding、音频转写和片段级声纹聚类。Tauri/Rust Host、Stronghold、原生多 Vault 文件系统、生产级 MCP 沙箱和 Sync Server 尚未接入。
## 目录
@@ -26,8 +26,24 @@ NotesAgent/
- 多模态:API 优先,未配置或响应无效时回退本地;`local_only` 禁止远程调用。任务、修订、事件、来源和回退原因写入 SQLite。
- 模型运行:默认 CPU,可选 CUDA 12.8 组件;固定模型 revision,按需启动独立子进程,交互检索优先排队,CUDA 初始化或显存失败时用同一冻结配置在 CPU 重试一次。
- 可观测性:输入、输出、缓存命中、推理 Token 与音频用量卡片;本地运行诊断保留最近 200 条,不保存正文、文件路径、密钥或异常全文。
- 运行日志:统一查看向量/模型错误、Agent、任务与 HTTP 操作;独立后台存储最近 20,000 条,支持错误码/关联 ID 筛选和游标分页。入口无需打开 Vault,详见 [后台运行日志与压力问题修复](docs/development/后台运行日志与压力问题修复.md)。
- 界面偏好:设置页可即时切换全局中文/英文界面,并控制由系统词典提供的编辑器拼写检查;偏好目前保存于 Web 端设备配置,后续由 Tauri 配置存储接管。
## 第二阶段最新合并(2026-09-06
PR #31 已合并。工作区打开与 HTTP 保存不再等待向量推理;正文和全文索引先可用,向量随后后台更新。“已保存”与“向量就绪”是两个独立状态。Skill / Plugin 支持 ZIP 安装与本地安装状态恢复,并已提供功能示例包;远程社区仍是第三阶段计划。
新增开发说明:
- [工作区后台索引与保存](docs/development/工作区后台索引与保存开发说明.md):状态、并发、恢复和验证。
- [模型隔离向量索引与增量登记](docs/development/模型隔离向量索引与增量登记.md):持久化 sqlite-vec 空间、旧向量复用、外部新增文件增量计算与检索性能验证。
- [Mermaid 预览与缩放](docs/development/Mermaid预览与缩放开发说明.md):大图适配、鼠标缩放和文字裁切修复。
- [扩展安装持久化与社区包](docs/development/扩展安装持久化与社区包开发说明.md):安装边界和示例包验证。
- [模型上下文管理](docs/development/模型上下文管理.md):全局人设、预算估算和摘要限制。
- [第三阶段实施规划](docs/architecture/第三阶段实施规划.md)Tauri Rust 容器、各社区与 Sync Server。
代码基线 `a5c44c4` 的验证结果为后端 621 项、前端 345 项测试通过,前端生产构建通过。这是该提交的回归记录,不表示全部真实厂商及设备场景完成专项验收。
## 本地模型
| 能力 | 当前模型 | 许可 | 说明 |
+6
View File
@@ -101,3 +101,9 @@ uv run pytest
- [阶段 FEmbedding 与知识库问题](../docs/retrospectives/阶段F-Embedding与知识库问题与解决方案.md)
机器可读接口以运行中的 `/openapi.json` 为准。
## 工作区保存与扩展恢复(2026-09-06)
HTTP 保存先写正文、元数据及 FTS,再调度后台向量更新;打开 Vault 的向量计算也不再阻塞入口。手动全量重建接口仍等待完成。待处理标记持久化,重新打开 Vault 可恢复处理;任务详情不是完整持久化队列。
实现与验证见 [工作区后台索引与保存](../docs/development/工作区后台索引与保存开发说明.md)。扩展安装日志、ZIP 限制和社区包测试见 [扩展安装持久化与社区包](../docs/development/扩展安装持久化与社区包开发说明.md)。
+51
View File
@@ -0,0 +1,51 @@
"""Serialize and batch durable Trace writes off the asyncio event loop."""
import asyncio
from contextvars import copy_context
class AsyncTraceWriter:
def __init__(self, repository):
self.repository = repository
self.queue = asyncio.Queue(maxsize=1024)
self.worker = None
async def submit(self, operation, *args):
future = asyncio.get_running_loop().create_future()
await self.queue.put((operation, args, future))
if self.worker is None or self.worker.done():
self.worker = asyncio.create_task(self._drain())
# Cancellation must not let an older snapshot commit after cancellation.
cancelled = False
while not future.done():
try:
await asyncio.shield(future)
except asyncio.CancelledError:
cancelled = True
future.result()
return cancelled
async def _drain(self):
while not self.queue.empty():
batch = []
while len(batch) < 64 and not self.queue.empty():
batch.append(self.queue.get_nowait())
try:
work = asyncio.get_running_loop().run_in_executor(
None, copy_context().run, self.repository.write_batch, [(op, args) for op, args, _ in batch])
# asyncio.run/shutdown may cancel every Task simultaneously. The
# executor Future survives; finish it and release all waiters.
while not work.done():
try:
await asyncio.shield(work)
except asyncio.CancelledError:
pass
work.result()
except Exception as exc:
for _, _, future in batch:
future.set_exception(exc)
else:
for _, _, future in batch:
future.set_result(None)
finally:
for _ in batch:
self.queue.task_done()
+110 -59
View File
@@ -4,6 +4,8 @@ from __future__ import annotations
import asyncio
import json
from app.agent.async_trace import AsyncTraceWriter
from app.operation_logs import log_event, agent_run_id
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from datetime import datetime, timezone
@@ -65,6 +67,9 @@ class RunRecord:
subscribers: set[asyncio.Queue[AgentEvent]] = field(default_factory=set)
task: asyncio.Task[None] | None = None
next_sequence: int = 0
publish_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
cancel_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
persisted_run: AgentRun | None = None
class AgentRuntime:
@@ -84,6 +89,7 @@ class AgentRuntime:
self.skills = skills
self.trace_repository = trace_repository or AgentTraceRepository()
self._records: dict[str, RunRecord] = {}
self._writer = AsyncTraceWriter(self.trace_repository)
async def create_run(self, request: AgentRunCreateRequest) -> AgentRun:
self._prune_records()
@@ -122,19 +128,25 @@ class AgentRuntime:
skill_config=skill_config,
allowed_tools=allowed_tools,
)
self.trace_repository.create_run(
run,
request,
self._config_snapshot(record),
)
# Reserve capacity before yielding to concurrent creators.
self._records[run.run_id] = record
try:
cancelled = await self._writer.submit('create', run.model_copy(deep=True), request.model_copy(deep=True), self._config_snapshot(record))
except BaseException:
self._records.pop(run.run_id, None)
raise
record.persisted_run = run.model_copy(deep=True)
log_event('agent', 'run.created', run_id=run.run_id, provider_id=run.provider_id, model=run.model)
if cancelled:
await self._finish_cancelled(record)
raise asyncio.CancelledError
record.task = asyncio.create_task(self._execute(record), name=run.run_id)
return run.model_copy(deep=True)
def get_run(self, run_id: str) -> AgentRun:
record = self._records.get(run_id)
if record is not None:
return record.run.model_copy(deep=True)
return (record.persisted_run or record.run).model_copy(deep=True)
run = self.trace_repository.recover_interrupted(run_id)
if run is None:
raise AgentRunNotFoundError(run_id)
@@ -145,7 +157,7 @@ class AgentRuntime:
recovered = [
self.trace_repository.recover_interrupted(item.run_id) or item
if item.run_id not in self._records
else self._records[item.run_id].run.model_copy(deep=True)
else (self._records[item.run_id].persisted_run or self._records[item.run_id].run).model_copy(deep=True)
for item in items
]
return recovered, total
@@ -154,25 +166,24 @@ class AgentRuntime:
record = self._records.get(run_id)
if record is None:
return self.get_run(run_id)
if record.run.status in TERMINAL_STATUSES:
return record.run.model_copy(deep=True)
record.run.cancelled = True
record.run.status = AgentRunStatus.cancelled
record.run.updated_at = datetime.now(timezone.utc)
self.permissions.cancel_run(run_id)
self._publish(record, AgentEventType.run_cancelled, {})
async with record.cancel_lock:
if record.task and not record.task.done():
if record.run.status not in TERMINAL_STATUSES:
record.task.cancel()
return record.run.model_copy(deep=True)
self.permissions.cancel_run(run_id)
await asyncio.gather(record.task, return_exceptions=True)
if record.run.status not in TERMINAL_STATUSES:
await self._finish_cancelled(record)
return (record.persisted_run or record.run).model_copy(deep=True)
def resolve_permission(self, run_id: str, request_id: str, decision: str) -> bool:
async def resolve_permission(self, run_id: str, request_id: str, decision: str) -> bool:
record = self._records.get(run_id)
if record is None:
return False
ticket = self.permissions.get_ticket(run_id, request_id)
resolved = self.permissions.resolve(run_id, request_id, decision)
if resolved:
self._publish(
await self._publish(
record,
AgentEventType.permission_resolved,
{
@@ -189,23 +200,24 @@ class AgentRuntime:
record = self._records.get(run_id)
run = self.get_run(run_id)
if record is None:
for event in self.trace_repository.list_events(
for event in await asyncio.to_thread(self.trace_repository.list_events,
run_id, after_sequence=after_sequence
):
yield event
return
# 先注册订阅再读持久化历史;同一事件循环内没有 await,不会丢失交界事件
# 先注册再异步读取历史;历史与实时队列的交界用 sequence 去重
queue: asyncio.Queue[AgentEvent] = asyncio.Queue()
record.subscribers.add(queue)
history = self.trace_repository.list_events(
run_id, after_sequence=after_sequence
)
last_sequence = after_sequence
try:
history = await asyncio.to_thread(self.trace_repository.list_events,
run_id, after_sequence=after_sequence)
for event in history:
last_sequence = event.sequence
yield event
if event.event in {AgentEventType.run_completed, AgentEventType.run_failed, AgentEventType.run_cancelled}:
return
if run.status in TERMINAL_STATUSES:
return
while True:
@@ -232,7 +244,7 @@ class AgentRuntime:
await asyncio.shield(record.task)
except asyncio.CancelledError:
pass
return record.run.model_copy(deep=True)
return (record.persisted_run or record.run).model_copy(deep=True)
def get_trace(
self, run_id: str, *, after_sequence: int, limit: int
@@ -246,23 +258,35 @@ class AgentRuntime:
return trace
async def _execute(self, record: RunRecord) -> None:
token = agent_run_id.set(record.run.run_id)
try:
async with asyncio.timeout(record.request.run_timeout_seconds):
await self._run_loop(record)
except asyncio.CancelledError:
if record.run.status != AgentRunStatus.cancelled:
self._finish_cancelled(record)
await self._finish_cancelled(record)
except TimeoutError:
self._fail(record, "AGENT_TIMEOUT", "Agent run exceeded its timeout.")
await self._fail(record, "AGENT_TIMEOUT", "Agent run exceeded its timeout.")
except ProviderError as exc:
self._fail(record, exc.code, exc.message)
await self._fail(record, exc.code, exc.message)
except Exception as exc:
self._fail(record, "AGENT_FAILED", str(exc))
log_event('agent', 'execution.failed', level='ERROR', error=exc, run_id=record.run.run_id)
await self._fail(record, "AGENT_FAILED", str(exc))
finally:
self.permissions.cancel_run(record.run.run_id)
agent_run_id.reset(token)
async def shutdown(self) -> None:
results = await asyncio.gather(*(self.cancel(run_id) for run_id in list(self._records)), return_exceptions=True)
for result in results:
if isinstance(result, BaseException):
log_event('agent', 'shutdown.failed', level='ERROR', error=result)
await self._writer.queue.join()
async def _run_loop(self, record: RunRecord) -> None:
record.run.status = AgentRunStatus.running
record.run.updated_at = datetime.now(timezone.utc)
self._publish(
await self._publish(
record,
AgentEventType.run_started,
{"provider_id": record.request.provider_id, "model": record.request.model},
@@ -277,7 +301,7 @@ class AgentRuntime:
record.run.updated_at = datetime.now(timezone.utc)
model_call_id = f"model_call_{uuid4().hex}"
started_at = perf_counter()
self._publish(
await self._publish(
record,
AgentEventType.model_call_started,
{
@@ -299,7 +323,7 @@ class AgentRuntime:
)
)
except Exception as exc:
self._publish(
await self._publish(
record,
AgentEventType.model_call_failed,
{
@@ -309,7 +333,7 @@ class AgentRuntime:
},
)
raise
self._publish(
await self._publish(
record,
AgentEventType.model_call_completed,
{
@@ -322,7 +346,7 @@ class AgentRuntime:
},
)
record.run.token_usage += turn.input_tokens + turn.output_tokens
self._publish(
await self._publish(
record,
AgentEventType.usage,
{"token_usage": record.run.token_usage},
@@ -331,12 +355,12 @@ class AgentRuntime:
record.request.token_budget is not None
and record.run.token_usage > record.request.token_budget
):
self._fail(record, "TOKEN_BUDGET_EXCEEDED", "Agent token budget exceeded.")
await self._fail(record, "TOKEN_BUDGET_EXCEEDED", "Agent token budget exceeded.")
return
if turn.tool_calls:
if len(turn.tool_calls) > MAX_TOOL_CALLS_PER_TURN:
self._fail(
await self._fail(
record,
"TOO_MANY_TOOL_CALLS",
f"Provider requested more than {MAX_TOOL_CALLS_PER_TURN} tools in one turn.",
@@ -360,10 +384,17 @@ class AgentRuntime:
async with semaphore:
return await self._execute_tool(record, call, model_call_id)
results = await asyncio.gather(*(execute(call) for call in calls))
executions = [asyncio.create_task(execute(call)) for call in calls]
try:
results = await asyncio.gather(*executions)
finally:
for execution in executions:
if not execution.done():
execution.cancel()
await asyncio.gather(*executions, return_exceptions=True)
for call, result in zip(calls, results):
record.run.tool_results.append(result)
self._collect_citations(record, result)
await self._collect_citations(record, result)
messages.append(
Message(
role=MessageRole.tool,
@@ -376,20 +407,20 @@ class AgentRuntime:
if turn.text is not None:
record.run.output = turn.text
self._publish(record, AgentEventType.text_delta, {"text": turn.text})
await self._publish(record, AgentEventType.text_delta, {"text": turn.text})
record.run.status = AgentRunStatus.completed
record.run.updated_at = datetime.now(timezone.utc)
self._publish(
await self._publish(
record,
AgentEventType.run_completed,
{"output": turn.text, "token_usage": record.run.token_usage},
)
return
self._fail(record, "EMPTY_MODEL_RESPONSE", "Provider returned no text or tool call.")
await self._fail(record, "EMPTY_MODEL_RESPONSE", "Provider returned no text or tool call.")
return
self._fail(record, "MAX_STEPS_EXCEEDED", "Agent reached its maximum step count.")
await self._fail(record, "MAX_STEPS_EXCEEDED", "Agent reached its maximum step count.")
async def _execute_tool(
self, record: RunRecord, call: ToolCall, parent_model_call_id: str
@@ -397,7 +428,7 @@ class AgentRuntime:
started_at = perf_counter()
call_data = call.model_dump(mode="json")
call_data["parent_model_call_id"] = parent_model_call_id
self._publish(record, AgentEventType.tool_call, call_data)
await self._publish(record, AgentEventType.tool_call, call_data)
try:
registered = self.tools.get(call.name)
except ToolNotFoundError:
@@ -411,7 +442,7 @@ class AgentRuntime:
error_code="TOOL_NOT_ALLOWED",
error_message="Tool is not included in allowed_tools.",
)
self._publish_tool_result(
await self._publish_tool_result(
record, result, parent_model_call_id, started_at
)
return result
@@ -425,7 +456,7 @@ class AgentRuntime:
error_code="NETWORK_NOT_ALLOWED",
error_message="Agent run does not allow network tools.",
)
self._publish_tool_result(
await self._publish_tool_result(
record, result, parent_model_call_id, started_at
)
return result
@@ -436,7 +467,7 @@ class AgentRuntime:
# 运行状态必须在等待期间可见,前端才能展示并处理权限确认卡片。
ticket = self.permissions.create_ticket(record.run.run_id, permission)
record.run.status = AgentRunStatus.waiting_permission
self._publish(
await self._publish(
record,
AgentEventType.permission_required,
{
@@ -458,13 +489,18 @@ class AgentRuntime:
error_code="PERMISSION_TIMEOUT",
error_message="Tool permission confirmation timed out.",
)
self._publish_tool_result(
await self._publish_tool_result(
record, result, parent_model_call_id, started_at
)
return result
record.run.status = AgentRunStatus.running
record.run.updated_at = datetime.now(timezone.utc)
self.trace_repository.save_run(record.run)
async with record.publish_lock:
snapshot = record.run.model_copy(deep=True)
cancelled = await self._writer.submit('save', snapshot)
record.persisted_run = snapshot
if cancelled:
raise asyncio.CancelledError
result = (
await self._invoke_tool(record, call)
if decision in {"allow_once", "allow_session"}
@@ -473,10 +509,10 @@ class AgentRuntime:
else:
result = await self._invoke_tool(record, call)
self._publish_tool_result(record, result, parent_model_call_id, started_at)
await self._publish_tool_result(record, result, parent_model_call_id, started_at)
return result
def _publish_tool_result(
async def _publish_tool_result(
self,
record: RunRecord,
result: ToolResult,
@@ -486,7 +522,7 @@ class AgentRuntime:
data = result.model_dump(mode="json")
data["parent_model_call_id"] = parent_model_call_id
data["duration_ms"] = int((perf_counter() - started_at) * 1000)
self._publish(record, AgentEventType.tool_result, data)
await self._publish(record, AgentEventType.tool_result, data)
async def _invoke_tool(self, record: RunRecord, call: ToolCall) -> ToolResult:
try:
@@ -519,28 +555,30 @@ class AgentRuntime:
error_message="Tool permission was denied.",
)
def _finish_cancelled(self, record: RunRecord) -> None:
async def _finish_cancelled(self, record: RunRecord) -> None:
record.run.cancelled = True
record.run.status = AgentRunStatus.cancelled
record.run.updated_at = datetime.now(timezone.utc)
self._publish(record, AgentEventType.run_cancelled, {})
await self._publish(record, AgentEventType.run_cancelled, {})
def _fail(self, record: RunRecord, code: str, message: str) -> None:
if record.run.status in TERMINAL_STATUSES:
async def _fail(self, record: RunRecord, code: str, message: str) -> None:
log_event('agent', 'run.error', level='ERROR', run_id=record.run.run_id, error_code=code)
if record.persisted_run and record.persisted_run.status in TERMINAL_STATUSES:
return
record.run.status = AgentRunStatus.failed
record.run.error_code = code
record.run.error_message = message
record.run.updated_at = datetime.now(timezone.utc)
self._publish(
await self._publish(
record,
AgentEventType.run_failed,
{"code": code, "message": message},
)
def _publish(
async def _publish(
self, record: RunRecord, event_type: AgentEventType, data: dict[str, object]
) -> None:
async with record.publish_lock:
sanitized = sanitize_trace_value(data)
assert isinstance(sanitized, dict)
event = AgentEvent(
@@ -550,14 +588,27 @@ class AgentRuntime:
data=sanitized,
timestamp=datetime.now(timezone.utc),
)
snapshot = record.run.model_copy(deep=True)
try:
cancelled = await self._writer.submit('event', snapshot, event)
except Exception as exc:
log_event('agent', 'trace.write_failed', level='ERROR', error=exc, run_id=record.run.run_id)
raise
record.next_sequence += 1
record.persisted_run = snapshot
record.events.append(event)
self.trace_repository.append_event(record.run, event)
log_event('agent', event_type.value,
level='ERROR' if event_type.value.endswith('Failed') or data.get('success') is False else 'INFO',
run_id=record.run.run_id, provider_id=record.run.provider_id, model=record.run.model,
sequence=event.sequence, step=record.run.current_step, status=snapshot.status.value,
tool=data.get('name'), error_code=data.get('code') or data.get('error_code'))
# 内存只保留实时订阅窗口;完整审计轨迹由 SQLite 保存。
if len(record.events) > MAX_EVENTS_PER_RUN:
del record.events[: len(record.events) - MAX_EVENTS_PER_RUN]
for queue in record.subscribers:
queue.put_nowait(event)
if cancelled:
raise asyncio.CancelledError
@staticmethod
def _request_metadata(record: RunRecord) -> dict[str, object]:
@@ -583,7 +634,7 @@ class AgentRuntime:
"metadata": record.request.metadata,
}
def _collect_citations(self, record: RunRecord, result: ToolResult) -> None:
async def _collect_citations(self, record: RunRecord, result: ToolResult) -> None:
if not result.success or not isinstance(result.output, dict):
return
items = result.output.get("items")
@@ -601,7 +652,7 @@ class AgentRuntime:
continue
known.add(citation.citation_id)
record.run.citations.append(citation)
self._publish(record, AgentEventType.citation, citation.model_dump(mode="json"))
await self._publish(record, AgentEventType.citation, citation.model_dump(mode="json"))
def _get_record(self, run_id: str) -> RunRecord:
try:
@@ -618,7 +669,7 @@ class AgentRuntime:
(
record
for record in self._records.values()
if record.run.status in TERMINAL_STATUSES
if record.run.status in TERMINAL_STATUSES and (record.task is None or record.task.done())
),
key=lambda record: record.run.updated_at,
)
+27 -8
View File
@@ -6,6 +6,7 @@ SQLite 中的事件是 SSE、前端 Trace 和 Benchmark 的共同事实来源。
from __future__ import annotations
from contextlib import nullcontext
import json
import re
from datetime import datetime, timezone
@@ -94,15 +95,30 @@ def sanitize_trace_value(
class AgentTraceRepository:
def write_batch(self, jobs):
conn = connect()
try:
with transaction(conn):
for operation, args in jobs:
if operation == 'create':
self.create_run(*args, _conn=conn)
elif operation == 'save':
self.save_run(*args, _conn=conn)
else:
self.append_event(*args, _conn=conn)
finally:
conn.close()
def create_run(
self,
run: AgentRun,
request: AgentRunCreateRequest,
config_snapshot: dict[str, Any],
*, _conn=None,
) -> None:
conn = connect()
conn = _conn or connect()
try:
with transaction(conn):
with transaction(conn) if _conn is None else nullcontext():
conn.execute(
"""
INSERT INTO agent_runs(
@@ -126,22 +142,24 @@ class AgentTraceRepository:
),
)
finally:
if _conn is None:
conn.close()
def save_run(self, run: AgentRun) -> None:
conn = connect()
def save_run(self, run: AgentRun, *, _conn=None) -> None:
conn = _conn or connect()
try:
with transaction(conn):
with transaction(conn) if _conn is None else nullcontext():
self._update_run(conn, run)
finally:
if _conn is None:
conn.close()
def append_event(self, run: AgentRun, event: AgentEvent) -> None:
def append_event(self, run: AgentRun, event: AgentEvent, *, _conn=None) -> None:
"""在同一事务中保存最新 Run 和事件;复写同一序号时保持幂等。"""
conn = connect()
conn = _conn or connect()
try:
with transaction(conn):
with transaction(conn) if _conn is None else nullcontext():
self._update_run(conn, run)
conn.execute(
"""
@@ -158,6 +176,7 @@ class AgentTraceRepository:
),
)
finally:
if _conn is None:
conn.close()
def get_run(self, run_id: str) -> AgentRun | None:
+6
View File
@@ -116,6 +116,7 @@ class NoteUpdateRequest(Contract):
title: str | None = None
markdown: str | None = None
tags: list[str] | None = None
expected_content_hash: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
class NoteMoveRequest(Contract):
@@ -1131,6 +1132,11 @@ class TranscriptNoteRequest(Contract):
class IndexStatus(Contract):
running_jobs: int = 0
active_searches: int = 0
completed_searches: int = 0
failed_searches: int = 0
cancelled_searches: int = 0
vector_refresh_required: bool = False
total_notes: int = 0
total_blocks: int = 0
+4
View File
@@ -25,6 +25,10 @@ class ApiError(Exception):
async def api_error_handler(_: Request, exc: ApiError) -> JSONResponse:
from app.operation_logs import log_event
log_event('api', 'operation.failed', level='ERROR' if exc.status_code >= 500 else 'WARNING',
error=exc, status=exc.status_code,
**{key: value for key, value in exc.details.items() if key in {'run_id', 'task_id', 'note_id', 'job_id', 'provider_id'}})
body = ErrorResponse(
error=ErrorDetail(code=exc.code, message=exc.message, details=exc.details)
)
+11
View File
@@ -0,0 +1,11 @@
"""Bound embedding result frames so large notes do not exceed pipe line limits."""
import json
def response_lines(response, operation):
if operation == 'embedding' and 'result' in response and 'error_code' not in response:
vectors = response['result']
for offset in range(0, len(vectors), 128):
yield json.dumps({'embedding_offset': offset, 'embedding_chunk': vectors[offset:offset + 128]}, allow_nan=False) + '\n'
response = {**response, 'result': [], 'embedding_count': len(vectors)}
yield json.dumps(response, ensure_ascii=False, allow_nan=False) + '\n'
+16 -1
View File
@@ -189,15 +189,30 @@ class Runtime:
await process.stdin.drain()
process.stdin.close()
final = None
vectors = []
while line := await process.stdout.readline():
message = json.loads(line)
if "progress" in message:
if "embedding_chunk" in message:
chunk = message['embedding_chunk']
if (operation != 'embedding' or not isinstance(chunk, list)
or message.get('embedding_offset') != len(vectors)
or len(vectors) + len(chunk) > len(payload.get('texts', []))):
raise ProviderError('LOCAL_MODEL_INVALID_RESPONSE', '本地向量传输顺序或数量无效。')
vectors.extend(chunk)
elif "progress" in message:
callback = runtime_progress.get()
if callback:
callback(message)
else:
final = message
await process.wait()
if isinstance(final, dict) and 'embedding_count' in final:
if (final['embedding_count'] != len(vectors)
or len(vectors) != len(payload.get('texts', []))):
raise ProviderError('LOCAL_MODEL_INVALID_RESPONSE', '本地向量传输不完整。')
final['result'] = vectors
elif vectors:
raise ProviderError('LOCAL_MODEL_INVALID_RESPONSE', '本地向量传输缺少结束标记。')
return final
try:
result = await asyncio.wait_for(receive(), config.timeout_seconds)
+3 -1
View File
@@ -216,4 +216,6 @@ if __name__ == "__main__":
response = {"error_code": "LOCAL_INFERENCE_FAILED", "message": "本地推理失败,请检查媒体格式、模型和设备配置。"}
if "error_code" in response:
response["diagnostics"] = {"requested_device": request["config"]["device"], "actual_device": request.get("_actual_device", "unknown")}
sys.stdout.buffer.write((json.dumps(response, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8"))
from protocol import response_lines
for line in response_lines(response, request['operation']):
sys.stdout.buffer.write(line.encode('utf-8'))
+11
View File
@@ -0,0 +1,11 @@
from fastapi import APIRouter, Query
from app.operation_logs import get_store
router = APIRouter(prefix='/api/logs', tags=['Diagnostics'])
@router.get('')
def list_logs(limit: int = Query(50, ge=1, le=200), before: int | None = Query(None, ge=1),
level: str = Query('', pattern='^(|INFO|WARNING|ERROR|CRITICAL)$'),
source: str = Query('', max_length=100), q: str = Query('', max_length=200)):
return get_store().query(limit=limit, before=before, level=level, source=source, q=q)
+36
View File
@@ -1,4 +1,7 @@
from contextlib import asynccontextmanager
import asyncio
from time import perf_counter
from uuid import uuid4
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
@@ -14,17 +17,22 @@ from app.local_model_routes import router as local_model_router
from app.usage_routes import router as usage_router
from app.provider_preview_routes import router as provider_preview_router
from app.schemas import HealthResponse, ServiceStatusResponse
from app.log_routes import router as log_router
from app.operation_logs import install_logging, log_event, request_id, shutdown_logging
settings = get_settings()
@asynccontextmanager
async def lifespan(_: FastAPI):
install_logging()
log_event('system', 'service.started')
from app.services import transcription_service
transcription_service.recover_interrupted()
try:
yield
finally:
await container.agent.shutdown()
from app.services import index_service
await index_service.shutdown()
await transcription_service.shutdown()
@@ -35,6 +43,8 @@ async def lifespan(_: FastAPI):
await manager.cancel_download(key)
container.plugins.shutdown()
container.mcp_servers.shutdown()
log_event('system', 'service.stopped')
await asyncio.to_thread(shutdown_logging)
app = FastAPI(
@@ -60,6 +70,32 @@ app.include_router(media_router)
app.include_router(local_model_router)
app.include_router(usage_router)
app.include_router(provider_preview_router)
app.include_router(log_router)
@app.middleware('http')
async def operation_log(request, call_next):
token = request_id.set(uuid4().hex)
started = perf_counter()
status = 500
failure = None
try:
response = await call_next(request)
status = response.status_code
response.headers['X-Request-ID'] = request_id.get()
return response
except Exception as exc:
failure = exc
raise
finally:
# Do not record query strings, request/response bodies or arbitrary URLs.
route = getattr(request.scope.get('route'), 'path', 'unmatched')
if not route.startswith('/api/logs') and (request.method not in {'GET', 'HEAD', 'OPTIONS'} or status >= 400 or perf_counter() - started > 1):
log_event('http', 'request.finished', level='ERROR' if status >= 500 else 'WARNING' if status >= 400 else 'INFO',
error=failure, method=request.method, route=route, status=status,
duration_ms=round((perf_counter() - started) * 1000, 2),
**{k: v for k, v in request.path_params.items() if k in {'run_id', 'task_id', 'note_id', 'job_id', 'provider_id'}})
request_id.reset(token)
@app.get("/health", response_model=HealthResponse, tags=["System"])
+186
View File
@@ -0,0 +1,186 @@
"""Bounded, asynchronous operational diagnostics, separate from business/Trace data.
Only explicitly allowed metadata is stored. Never store prompts, tool arguments,
provider response bodies or raw exception messages in this diagnostic channel.
"""
from __future__ import annotations
import json
import logging
import math
import queue
import re
import sqlite3
import threading
import traceback
from contextvars import ContextVar
from contextlib import closing
from datetime import datetime, timezone
from pathlib import Path
from app.config import get_settings
request_id: ContextVar[str] = ContextVar('log_request_id', default='')
agent_run_id: ContextVar[str] = ContextVar('log_agent_run_id', default='')
_allowed = {'run_id', 'task_id', 'note_id', 'job_id', 'provider_id', 'model',
'device', 'error_code', 'error_type', 'status', 'duration_ms', 'count',
'step', 'sequence', 'tool', 'method', 'route', 'request_id', 'fallback',
'frames', 'source', 'changed_fields'}
_safe = re.compile(r'[^\w .:/@{}\[\],()=+\-]', re.UNICODE)
def metadata(values: dict) -> dict:
result = {}
for key, value in values.items():
if key not in _allowed or value is None:
continue
if isinstance(value, (int, float, bool)):
if not isinstance(value, float) or math.isfinite(value):
result[key] = value
else:
text = str(value)
text = re.sub(r'(?i)(?:bearer\s+\S+|sk-[\w-]+)', '[REDACTED]', text)
result[key] = _safe.sub('', text)[:500]
return result
class LogStore:
def __init__(self, path: Path, *, retain: int = 20_000):
self.path = path
self.retain = retain
self.queue: queue.Queue = queue.Queue(maxsize=4096)
self.dropped = 0
self.failed = 0
self.closed = False
self.state_lock = threading.Lock()
self.thread = threading.Thread(target=self._write, name='operation-logs', daemon=True)
path.parent.mkdir(parents=True, exist_ok=True)
with closing(self._connect()) as conn, conn:
conn.execute('CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY, timestamp TEXT NOT NULL, level TEXT NOT NULL, source TEXT NOT NULL, event TEXT NOT NULL, details TEXT NOT NULL)')
conn.execute('CREATE INDEX IF NOT EXISTS logs_level_id ON logs(level, id)')
conn.execute('CREATE INDEX IF NOT EXISTS logs_source_id ON logs(source, id)')
self.thread.start()
def _connect(self):
conn = sqlite3.connect(self.path, timeout=5)
conn.row_factory = sqlite3.Row
return conn
def emit(self, level: str, source: str, event: str, details: dict):
row = (datetime.now(timezone.utc).isoformat(), level, source[:100], event[:160], json.dumps(metadata(details), ensure_ascii=False))
with self.state_lock:
if self.closed:
return
try:
self.queue.put_nowait(row)
except queue.Full:
self.dropped += 1
def _write(self):
while True:
first = self.queue.get()
batch = [first]
while len(batch) < 128:
try:
batch.append(self.queue.get_nowait())
except queue.Empty:
break
stop = None in batch
rows = [row for row in batch if row is not None]
try:
if rows:
with closing(self._connect()) as conn, conn:
conn.executemany('INSERT INTO logs(timestamp,level,source,event,details) VALUES(?,?,?,?,?)', rows)
conn.execute('DELETE FROM logs WHERE id <= (SELECT id FROM logs ORDER BY id DESC LIMIT 1 OFFSET ?)', (self.retain,))
except Exception:
self.failed += len(rows)
finally:
for _ in batch:
self.queue.task_done()
if stop:
return
def query(self, *, limit=50, before=None, level='', source='', q=''):
clauses, args = [], []
for column, value in [('level', level), ('source', source)]:
if value:
clauses.append(f'{column} = ?')
args.append(value)
if before is not None:
clauses.append('id < ?')
args.append(before)
if q:
clauses.append('(instr(event, ?) > 0 OR instr(details, ?) > 0)')
args += [q, q]
where = ' WHERE ' + ' AND '.join(clauses) if clauses else ''
with closing(self._connect()) as conn, conn:
rows = conn.execute('SELECT * FROM logs' + where + ' ORDER BY id DESC LIMIT ?', (*args, limit + 1)).fetchall()
sources = [row[0] for row in conn.execute('SELECT DISTINCT source FROM logs ORDER BY source')]
items = [{**dict(row), 'details': json.loads(row['details'])} for row in rows[:limit]]
return {'items': items, 'next_cursor': items[-1]['id'] if len(rows) > limit else None,
'sources': sources, 'pending': self.queue.qsize(), 'dropped': self.dropped,
'write_failures': self.failed, 'retention': self.retain}
def close(self):
with self.state_lock:
if self.closed:
return
self.closed = True
self.queue.put(None)
self.thread.join(timeout=15)
_store: LogStore | None = None
_lock = threading.Lock()
def get_store() -> LogStore:
global _store
path = get_settings().data_dir / 'logs' / 'operations.sqlite3'
with _lock:
if _store is None or _store.path != path or _store.closed:
if _store is not None and not _store.closed:
_store.close()
_store = LogStore(path)
return _store
def log_event(module: str, event: str, *, level='INFO', error: BaseException | None = None, **details):
if request_id.get():
details.setdefault('request_id', request_id.get())
if agent_run_id.get():
details.setdefault('run_id', agent_run_id.get())
if error:
details['error_type'] = type(error).__name__
details.setdefault('error_code', getattr(error, 'code', None))
details['frames'] = '; '.join(f'{Path(f.filename).name}:{f.lineno}:{f.name}' for f in traceback.extract_tb(error.__traceback__)[-8:])
try:
get_store().emit(level, module, event, details)
except Exception:
# Logging must not turn a successful save/run into a business failure.
logging.getLogger('operation_log_storage').error('Operational log storage unavailable')
class ApplicationLogHandler(logging.Handler):
def emit(self, record):
if record.name == 'operation_log_storage' or getattr(record, '_notes_operation_logged', False):
return
record._notes_operation_logged = True
# Legacy log messages can include note text/credentials, even in f-strings.
# Preserve source location and error class; structured call sites carry IDs.
log_event(record.name, 'application.warning' if record.levelno < 40 else 'application.error',
level=record.levelname, error=record.exc_info[1] if record.exc_info else None,
frames=f'{Path(record.pathname).name}:{record.lineno}:{record.funcName}')
def install_logging():
# Uvicorn's default logger stops propagation before the root logger.
for name in ('', 'uvicorn'):
logger = logging.getLogger(name)
if not any(isinstance(h, ApplicationLogHandler) for h in logger.handlers):
logger.addHandler(ApplicationLogHandler(level=logging.WARNING))
def shutdown_logging():
if _store is not None and not _store.closed:
_store.close()
+30
View File
@@ -0,0 +1,30 @@
"""Process-local retrieval activity, shared by search, RAG and Agent callers."""
import asyncio
from functools import wraps
active = 0
completed = 0
failed = 0
cancelled = 0
def track_search(operation):
@wraps(operation)
async def wrapped(self, request):
global active, completed, failed, cancelled
if request.mode == 'fts':
return await operation(self, request)
active += 1
try:
result = await operation(self, request)
completed += 1
return result
except asyncio.CancelledError:
cancelled += 1
raise
except Exception:
failed += 1
raise
finally:
active -= 1
return wrapped
+2
View File
@@ -10,6 +10,7 @@ from __future__ import annotations
from datetime import datetime, timezone
from app import repository
from app.retrieval.activity import track_search
from app.contracts import (
Citation,
PageMeta,
@@ -52,6 +53,7 @@ class RetrievalEngine:
# remain authoritative, including monkeypatches on the singleton.
self._routed_defaults = (embedding, vector_store) if route_embeddings else None
@track_search
async def search(self, request: SearchRequest) -> SearchResponse:
if request.mode == SearchMode.fts:
return self._search_fts(request)
+69 -47
View File
@@ -2,15 +2,14 @@
The runtime's model_id is the authoritative space ID (including provider URL,
endpoint, model and dimensions); equal dimensions alone never imply compatibility.
This phase uses a lazy, rebuildable SQLite side table instead of a schema migration.
Search scans only current blocks in one database snapshot and requires complete
coverage. Cosine ranking costs O(blocks * dimensions) with an O(top_k) heap; this
small-vault implementation should become a per-space ANN index at larger scale.
Durable vectors are reused to build per-space/dimension sqlite-vec indexes lazily.
Native exact KNN avoids Python JSON decoding and dot products on every search.
Coverage checks and ranking share one transaction.
"""
from __future__ import annotations
import heapq
import asyncio
import json
import logging
import math
@@ -20,9 +19,11 @@ from typing import Protocol
from app.database.db import connect, transaction
from app.errors import ApiError
from app.operation_logs import log_event
from app.retrieval.vectorstore import VectorHit
from app.retrieval.provenance import record_embedding
from app.retrieval.hybrid import rrf_fuse
from app.retrieval import space_index
logger = logging.getLogger(__name__)
@@ -101,6 +102,8 @@ async def embed_remote(texts: list[str], *, accept_local=False, strict=False, lo
source=result.source,
)
except Exception as exc:
log_event('vectors', 'embedding.failed', level='ERROR' if strict else 'WARNING', error=exc,
count=len(texts), fallback='none' if strict else 'local_index')
# Avoid logging provider exceptions containing credentials or note text.
record_embedding(fallback_reason="REMOTE_EMBEDDING_UNAVAILABLE")
logger.warning("Remote embedding unavailable (%s); using local index", type(exc).__name__)
@@ -118,9 +121,15 @@ def _ensure_table(conn: sqlite3.Connection) -> None:
block_id TEXT NOT NULL REFERENCES blocks(block_id) ON DELETE CASCADE,
dimensions INTEGER NOT NULL CHECK (dimensions > 0),
vector TEXT NOT NULL,
PRIMARY KEY (space_id, block_id)
PRIMARY KEY (space_id, dimensions, block_id)
)
""")
primary = [row[1] for row in sorted(conn.execute('PRAGMA table_info(routed_block_vectors)'), key=lambda row: row[5]) if row[5]]
if primary == ['space_id', 'block_id']:
conn.execute('CREATE TABLE routed_block_vectors_upgrade (space_id TEXT NOT NULL, block_id TEXT NOT NULL REFERENCES blocks(block_id) ON DELETE CASCADE, dimensions INTEGER NOT NULL CHECK(dimensions>0), vector TEXT NOT NULL, PRIMARY KEY(space_id,dimensions,block_id))')
conn.execute('INSERT INTO routed_block_vectors_upgrade SELECT * FROM routed_block_vectors')
conn.execute('DROP TABLE routed_block_vectors')
conn.execute('ALTER TABLE routed_block_vectors_upgrade RENAME TO routed_block_vectors')
conn.execute("""
CREATE INDEX IF NOT EXISTS routed_block_vectors_block_id
ON routed_block_vectors(block_id)
@@ -146,13 +155,14 @@ def store_remote(
conn.executemany(
"""INSERT INTO routed_block_vectors (space_id, block_id, dimensions, vector)
VALUES (?, ?, ?, ?)
ON CONFLICT (space_id, block_id) DO UPDATE SET
ON CONFLICT (space_id, dimensions, block_id) DO UPDATE SET
dimensions = excluded.dimensions, vector = excluded.vector""",
[
(batch.space_id, block_id, batch.dimensions, json.dumps(vector, allow_nan=False))
for block_id, vector in zip(block_ids, batch.vectors)
],
)
space_index.upsert(conn, block_ids, batch)
except BaseException:
conn.execute("ROLLBACK TO routed_vectors_write")
raise
@@ -180,6 +190,50 @@ async def search_remote(query: str, *, top_k: int, accept_local=False, strict=Fa
if batch is None:
return None
if not await _prepare_for_search([batch], strict):
return None
return await asyncio.to_thread(_search_space, batch, top_k, strict)
async def _prepare_indexes(batches):
from app.services.coordination import vault_mutation_lock
def prepare(check_only=False):
conn = connect()
try:
if check_only:
return space_index.is_ready(conn, batches)
space_index.prepare(conn, batches)
finally:
conn.close()
if await asyncio.to_thread(prepare, True):
return
# Share the cooperative gate with saves: never block the event loop on a
# SQLite write lock while a migration owns it in another thread.
async with vault_mutation_lock():
work = asyncio.create_task(asyncio.to_thread(prepare))
cancelled = False
while not work.done():
try:
await asyncio.shield(work)
except asyncio.CancelledError:
cancelled = True
work.result()
if cancelled:
raise asyncio.CancelledError
async def _prepare_for_search(batches, strict):
try:
await _prepare_indexes(batches)
return True
except Exception as exc:
record_embedding(fallback_reason='REMOTE_INDEX_UNAVAILABLE')
if strict:
raise ApiError(409, 'SEMANTIC_INDEX_UNAVAILABLE', '向量索引准备失败,请检查索引状态。') from exc
return False
def _search_space(batch, top_k, strict):
record_embedding(attempted_space={"model_id": batch.space_id, "dimensions": batch.dimensions})
try:
conn = connect()
@@ -195,29 +249,7 @@ async def search_remote(query: str, *, top_k: int, accept_local=False, strict=Fa
if strict:
raise ValueError("semantic index missing")
return None
rows = conn.execute(
"""SELECT b.block_id, r.vector
FROM blocks AS b
LEFT JOIN routed_block_vectors AS r
ON r.block_id = b.block_id AND r.space_id = ? AND r.dimensions = ?
ORDER BY b.block_id""",
(batch.space_id, batch.dimensions),
)
def hits():
for row in rows:
if row["vector"] is None:
raise ValueError("remote space has incomplete block coverage")
vector = _unit_vector(json.loads(row["vector"]), batch.dimensions)
score = math.fsum(a * b for a, b in zip(batch.vectors[0], vector))
yield VectorHit(id=row["block_id"], score=max(0.0, min(1.0, score)))
try:
result = heapq.nlargest(top_k, hits(), key=lambda hit: hit.score)
finally:
# Exceptions may retain the generator/traceback; finalize its
# cursor now so a subsequent rebuild can acquire a write lock.
rows.close()
result = space_index.search(conn, batch, top_k)
record_embedding(source=batch.source, model_id=batch.space_id,
dimensions=batch.dimensions, fallback_reason=None)
return result
@@ -241,6 +273,12 @@ async def _search_partitioned(query: str, policies: set[bool], *, top_k: int, st
if batch is None:
return None
batches[policy] = batch
if not await _prepare_for_search(list(batches.values()), strict):
return None
return await asyncio.to_thread(_search_partitions, batches, policies, top_k, strict)
def _search_partitions(batches, policies, top_k, strict):
conn = connect()
try:
with transaction(conn):
@@ -250,23 +288,7 @@ async def _search_partitioned(query: str, policies: set[bool], *, top_k: int, st
raise ValueError("embedding policies changed while querying")
ranked = []
for policy, batch in batches.items():
rows = conn.execute(
"SELECT b.block_id,r.vector FROM blocks b LEFT JOIN routed_block_vectors r "
"ON r.block_id=b.block_id AND r.space_id=? AND r.dimensions=? "
"WHERE b.embedding_local_only=? ORDER BY b.block_id",
(batch.space_id, batch.dimensions, int(policy)),
)
def hits():
for row in rows:
if row['vector'] is None:
raise ValueError("incomplete policy coverage")
vector = _unit_vector(json.loads(row['vector']), batch.dimensions)
score = math.fsum(a * b for a, b in zip(batch.vectors[0], vector))
yield VectorHit(id=row['block_id'], score=max(0.0, min(1.0, score)))
try:
ranked.append(heapq.nlargest(top_k, hits(), key=lambda hit: hit.score))
finally:
rows.close()
ranked.append(space_index.search(conn, batch, top_k, policy))
spaces = [{"source": b.source, "model_id": b.space_id, "dimensions": b.dimensions,
"local_only": policy} for policy, b in batches.items()]
record_embedding(source="mixed" if len({b.source for b in batches.values()}) > 1 else batch.source,
+89
View File
@@ -0,0 +1,89 @@
"""Persistent vec0 indexes derived from durable routed vectors, one per space/dimension."""
import hashlib
import json
import threading
import sqlite_vec
from app.retrieval.vectorstore import VectorHit
_migration_lock = threading.Lock()
def is_ready(conn, batches):
return all(conn.execute('SELECT 1 FROM sqlite_master WHERE name=?',
(table_name(batch.space_id, batch.dimensions),)).fetchone() for batch in batches)
def prepare(conn, batches):
"""Finish lazy writes before opening a search snapshot. Warm searches do not write."""
from app.retrieval.routed_vectors import _ensure_table
batches = list(batches)
if is_ready(conn, batches):
return
# Waiting holds no read transaction, so a concurrent migration can commit.
with _migration_lock:
if is_ready(conn, batches):
return
conn.execute('BEGIN IMMEDIATE')
try:
_ensure_table(conn)
for batch in batches:
ensure(conn, batch.space_id, batch.dimensions)
conn.execute('COMMIT')
except BaseException:
conn.execute('ROLLBACK')
raise
def table_name(space, dimensions):
return 'routed_vec_' + hashlib.sha256(json.dumps([space, dimensions]).encode()).hexdigest()
def ensure(conn, space, dimensions):
from app.retrieval.routed_vectors import _unit_vector
table = table_name(space, dimensions)
if conn.execute('SELECT 1 FROM sqlite_master WHERE name=?', (table,)).fetchone():
return table
if type(dimensions) is not int or not 0 < dimensions <= 8192:
raise ValueError('unsupported vector dimensions')
conn.execute(f'CREATE VIRTUAL TABLE {table} USING vec0(block_id TEXT PRIMARY KEY, embedding float[{dimensions}], local_only INTEGER)')
for row in conn.execute('SELECT r.block_id,r.vector,b.embedding_local_only FROM routed_block_vectors r JOIN blocks b USING(block_id) WHERE r.space_id=? AND r.dimensions=?', (space, dimensions)):
conn.execute(f'INSERT INTO {table}(block_id,embedding,local_only) VALUES (?,?,?)',
(row[0], sqlite_vec.serialize_float32(_unit_vector(json.loads(row[1]), dimensions)), row[2]))
literal = conn.execute('SELECT quote(?)', (space,)).fetchone()[0]
for event in ('DELETE', 'UPDATE'):
conn.execute(f'''CREATE TRIGGER {table}_{event.lower()} AFTER {event} ON routed_block_vectors
WHEN old.space_id={literal} AND old.dimensions={dimensions}
BEGIN DELETE FROM {table} WHERE block_id=old.block_id; END''')
return table
def upsert(conn, block_ids, batch):
from app.retrieval.routed_vectors import _unit_vector
table = ensure(conn, batch.space_id, batch.dimensions)
for block_id, vector in zip(block_ids, batch.vectors):
conn.execute(f'DELETE FROM {table} WHERE block_id=?', (block_id,))
conn.execute(f'INSERT INTO {table}(block_id,embedding,local_only) SELECT block_id,?,embedding_local_only FROM blocks WHERE block_id=?',
(sqlite_vec.serialize_float32(_unit_vector(vector, batch.dimensions)), block_id))
def search(conn, batch, top_k, policy=None):
table = table_name(batch.space_id, batch.dimensions)
# Coverage checks stay relational; no JSON decoding or Python dot products on the hot path.
where = '' if policy is None else ' AND b.embedding_local_only=?'
params = () if policy is None else (int(policy),)
missing = conn.execute(f'''SELECT 1 FROM blocks b LEFT JOIN routed_block_vectors r
ON r.block_id=b.block_id AND r.space_id=? AND r.dimensions=?
WHERE r.block_id IS NULL{where} LIMIT 1''', (batch.space_id, batch.dimensions, *params)).fetchone()
expected = conn.execute('SELECT COUNT(*) FROM blocks' + ('' if policy is None else ' WHERE embedding_local_only=?'), params).fetchone()[0]
actual = conn.execute(f'SELECT COUNT(*) FROM {table}' + ('' if policy is None else ' WHERE local_only=?'), params).fetchone()[0]
if missing or actual != expected:
raise ValueError('incomplete vector space coverage')
if top_k <= 0:
return []
rows = conn.execute(f'SELECT block_id,distance FROM {table} WHERE embedding MATCH ? AND k=?'
+ ('' if policy is None else ' AND local_only=?'),
(sqlite_vec.serialize_float32(batch.vectors[0]), top_k, *params)).fetchall()
return [VectorHit(id=row[0], score=max(0.0, min(1.0, 1 - row[1] ** 2 / 2))) for row in rows]
+16 -10
View File
@@ -11,6 +11,7 @@ from fastapi.responses import StreamingResponse
from app.agent import AgentCapacityError, AgentRunNotFoundError
from app.container import container
from app.config import get_settings
from app.operation_logs import log_event
from app.extensions.archive import MAX_ZIP_BYTES, install_zip
from app.services.persona_settings import PersonaSettings, load_persona, save_persona
from app.contracts import (
@@ -225,7 +226,7 @@ async def open_workspace(request: WorkspaceOpenRequest) -> WorkspaceSnapshot:
@router.get("/workspace/tree", response_model=list[WorkspaceEntry], tags=["Workspace"])
async def get_workspace_tree() -> list[WorkspaceEntry]:
return workspace_service.get_workspace_tree()
return await workspace_service.refresh_workspace_tree()
@router.post("/workspace/folders", response_model=WorkspaceEntry, tags=["Workspace"])
@@ -286,7 +287,8 @@ async def get_note(note_id: str) -> Note:
@router.patch("/notes/{note_id}", response_model=Note, tags=["Notes"])
async def update_note(note_id: str, request: NoteUpdateRequest) -> Note:
return await note_service.update_note(
note_id, title=request.title, markdown=request.markdown, tags=request.tags, defer_vectors=True
note_id, title=request.title, markdown=request.markdown, tags=request.tags,
expected_content_hash=request.expected_content_hash, defer_vectors=True
)
@@ -454,11 +456,15 @@ async def chat(request: ChatRequest) -> StreamingResponse:
usage = {"input_tokens": input_tokens, "output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens}
elif event.event == ModelEventType.error:
log_event('chat', 'model.error', level='ERROR', provider_id=request.provider_id,
model=request.model, error_code=event.data.get('code'))
if assistant_content:
assistant_content += "\n\n"
assistant_content += str(event.data.get("message", "Model generation failed."))
yield as_sse(event.event.value, event.model_dump_json())
except Exception as exc:
log_event('chat', 'chat.failed', level='ERROR', error=exc,
provider_id=request.provider_id, model=request.model)
failure_message = exc.message if isinstance(exc, ApiError) else "知识库检索或模型生成失败,请检查服务状态。"
if assistant_content:
assistant_content += "\n\n"
@@ -497,7 +503,7 @@ async def chat(request: ChatRequest) -> StreamingResponse:
async def list_agent_runs(
limit: int = Query(default=50, ge=1, le=100), offset: int = Query(default=0, ge=0)
) -> AgentRunListResponse:
items, total = container.agent.list_runs(limit=limit, offset=offset)
items, total = await asyncio.to_thread(container.agent.list_runs, limit=limit, offset=offset)
return AgentRunListResponse(
items=items,
page=PageMeta(total=total, limit=limit, offset=offset),
@@ -602,7 +608,7 @@ async def get_agent_trace(
limit: int = Query(default=200, ge=1, le=500),
) -> AgentTraceResponse:
try:
return container.agent.get_trace(
return await asyncio.to_thread(container.agent.get_trace,
run_id, after_sequence=after_sequence, limit=limit
)
except AgentRunNotFoundError as exc:
@@ -623,7 +629,7 @@ async def decide_agent_permission(
run_id: str, request_id: str, request: PermissionDecisionRequest
) -> OperationResponse:
agent_run_or_404(run_id)
if not container.agent.resolve_permission(run_id, request_id, request.decision):
if not await container.agent.resolve_permission(run_id, request_id, request.decision):
raise ApiError(
404,
"PERMISSION_REQUEST_NOT_FOUND",
@@ -1222,7 +1228,7 @@ async def test_provider(request: ProviderTestRequest) -> ProviderTestResponse:
async def list_tasks(
limit: int = Query(default=50, ge=1, le=100), offset: int = Query(default=0, ge=0)
) -> TaskListResponse:
items, total = task_service.list_tasks(limit=limit, offset=offset)
items, total = await asyncio.to_thread(task_service.list_tasks, limit=limit, offset=offset)
return TaskListResponse(
items=items, page=PageMeta(total=total, limit=limit, offset=offset)
)
@@ -1230,12 +1236,12 @@ async def list_tasks(
@router.post("/tasks", response_model=Task, tags=["Tasks"])
async def create_task(request: TaskCreateRequest) -> Task:
return task_service.create_task(**request.model_dump())
return await task_service.write_in_background(task_service.create_task, **request.model_dump())
@router.get("/tasks/{task_id}", response_model=Task, tags=["Tasks"])
async def get_task(task_id: str) -> Task:
task = task_service.get_task(task_id)
task = await asyncio.to_thread(task_service.get_task, task_id)
if task is None:
raise ApiError(
404, "RESOURCE_NOT_FOUND", "task not found", {"task_id": task_id}
@@ -1245,7 +1251,7 @@ async def get_task(task_id: str) -> Task:
@router.patch("/tasks/{task_id}", response_model=Task, tags=["Tasks"])
async def update_task(task_id: str, request: TaskUpdateRequest) -> Task:
return task_service.update_task(task_id, request.model_dump(exclude_unset=True))
return await task_service.write_in_background(task_service.update_task, task_id, request.model_dump(exclude_unset=True))
@router.delete(
@@ -1254,7 +1260,7 @@ async def update_task(task_id: str, request: TaskUpdateRequest) -> Task:
tags=["Tasks"],
)
async def delete_task(task_id: str) -> OperationResponse:
if not task_service.delete_task(task_id):
if not await task_service.write_in_background(task_service.delete_task, task_id):
raise ApiError(
404, "RESOURCE_NOT_FOUND", "task not found", {"task_id": task_id}
)
+9 -2
View File
@@ -1,7 +1,14 @@
import asyncio
from functools import wraps
from weakref import WeakKeyDictionary
_vault_mutation_lock = asyncio.Lock()
_vault_locks = WeakKeyDictionary()
def vault_mutation_lock():
# Service/test lifecycle restarts must not reuse a lock bound to a closed loop.
loop = asyncio.get_running_loop()
return _vault_locks.setdefault(loop, asyncio.Lock())
def serialized_vault_mutation(operation):
@@ -9,7 +16,7 @@ def serialized_vault_mutation(operation):
@wraps(operation)
async def wrapped(*args, **kwargs):
async with _vault_mutation_lock:
async with vault_mutation_lock():
return await operation(*args, **kwargs)
return wrapped
+43 -8
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import logging
from app.operation_logs import log_event
from datetime import datetime, timezone
from pathlib import Path
@@ -16,7 +17,7 @@ from app.errors import ApiError
from app.knowledge.parser import parse_note
from app.services.note_service import index_note, prepare_note_index
from app.database.db import connect, transaction
from app.services.coordination import _vault_mutation_lock
from app.services.coordination import vault_mutation_lock
from app.retrieval.vectorstore import SqliteVecStore
from app.local_models.runtime import LocalEmbedding
from app.services import note_service
@@ -25,6 +26,7 @@ vector_store = SqliteVecStore()
_jobs: dict[str, IndexJob] = {}
_active_job_id: str | None = None
_active_scope: str | None = None
_last_completed_at: datetime | None = None
_last_error: str | None = None
MAX_JOBS = 100
@@ -33,6 +35,7 @@ _logger = logging.getLogger(__name__)
def _remember_job(job: IndexJob) -> None:
log_event('vectors', 'index.' + job.status, job_id=job.job_id, status=job.status)
_jobs[job.job_id] = job
while len(_jobs) > MAX_JOBS:
oldest = next(iter(_jobs))
@@ -64,7 +67,7 @@ def _scan_vault() -> list[tuple[str, str, str, datetime, datetime]]:
async def rebuild(request: IndexRebuildRequest) -> IndexJob:
global _active_job_id, _last_completed_at, _last_error
global _active_job_id, _active_scope, _last_completed_at, _last_error
if _active_job_id is not None:
raise ApiError(409, "INDEX_BUSY", "索引正在后台计算,请稍后重试。")
job_id = "job_" + uuid4().hex[:12]
@@ -82,6 +85,7 @@ async def rebuild(request: IndexRebuildRequest) -> IndexJob:
saved_paths = {record.file_path: record for record in saved_records.values() if record is not None}
_active_job_id = job_id
_active_scope = 'all'
_last_error = None
_remember_job(IndexJob(
job_id=job_id, status="running", scope=request.scope,
@@ -112,7 +116,7 @@ async def rebuild(request: IndexRebuildRequest) -> IndexJob:
prepared_notes.append((parsed, prepared))
# All network/model awaits precede the transaction. The concrete SQLite
# methods below complete synchronously despite their async interfaces.
async with _vault_mutation_lock:
async with vault_mutation_lock():
if _scan_vault() != docs or saved_records != {key: repository.get_note_record(key) for key in _pending_notes()}:
raise ApiError(409, "INDEX_SNAPSHOT_CHANGED", "笔记在计算期间发生变化,稍后重新计算。")
conn = connect()
@@ -148,6 +152,7 @@ async def rebuild(request: IndexRebuildRequest) -> IndexJob:
finally:
conn.close()
except BaseException as exc:
log_event('vectors', 'index.failed', level='WARNING' if isinstance(exc, asyncio.CancelledError) else 'ERROR', error=exc, job_id=job_id)
_remember_job(IndexJob(
job_id=job_id, status="failed", scope=request.scope,
created_at=datetime.now(timezone.utc),
@@ -156,6 +161,7 @@ async def rebuild(request: IndexRebuildRequest) -> IndexJob:
raise
finally:
_active_job_id = None
_active_scope = None
job = IndexJob(job_id=job_id, status="completed", scope=request.scope, created_at=datetime.now(timezone.utc))
_remember_job(job)
@@ -166,16 +172,26 @@ async def rebuild(request: IndexRebuildRequest) -> IndexJob:
def get_status() -> IndexStatus:
from app.retrieval import activity
counts = repository.stats()
vector_refresh_required = repository.get_index_meta().get('workspace_vectors_pending') == '1' or bool(_pending_notes())
workspace_pending = repository.get_index_meta().get('workspace_vectors_pending') == '1'
notes_pending = len(_pending_notes())
vector_refresh_required = workspace_pending or bool(notes_pending)
running = int(_active_job_id is not None)
# An entire-vault rebuild is one job, not one job per block/note.
pending = 1 if running and _active_scope == 'all' else (1 + running if workspace_pending else max(notes_pending, running))
activity_fields = dict(running_jobs=running, active_searches=activity.active,
completed_searches=activity.completed, failed_searches=activity.failed,
cancelled_searches=activity.cancelled)
if _active_job_id is not None:
return IndexStatus(status="running", pending_jobs=0, active_job_id=_active_job_id, vector_refresh_required=vector_refresh_required,
return IndexStatus(**activity_fields, status="running", pending_jobs=pending, active_job_id=_active_job_id, vector_refresh_required=vector_refresh_required,
total_notes=counts["notes"], total_blocks=counts["blocks"])
return IndexStatus(
**activity_fields,
vector_refresh_required=vector_refresh_required,
total_notes=counts["notes"], total_blocks=counts["blocks"],
status="failed" if _last_error else "idle",
pending_jobs=0,
pending_jobs=pending,
last_completed_at=_last_completed_at,
error_message=_last_error,
)
@@ -227,7 +243,7 @@ def _pending_notes() -> list[str]:
async def _refresh_saved_note(note_id: str) -> None:
global _active_job_id, _last_error, _last_completed_at
global _active_job_id, _active_scope, _last_error, _last_completed_at
record = repository.get_note_record(note_id)
key = f'note_vectors_pending:{note_id}'
if record is None:
@@ -240,13 +256,14 @@ async def _refresh_saved_note(note_id: str) -> None:
parsed.title = record.title
job_id = 'job_' + uuid4().hex[:12]
_active_job_id = job_id
_active_scope = 'note'
_last_error = None
_remember_job(IndexJob(job_id=job_id, status='running', scope='all', created_at=datetime.now(timezone.utc)))
try:
prepared = await prepare_note_index(parsed, strict=True)
if isinstance(note_service.embedding, LocalEmbedding) and parsed.blocks and prepared[1] is None:
raise ApiError(503, "EMBEDDING_UNAVAILABLE", "笔记已保存,后台向量计算未完成。")
async with _vault_mutation_lock:
async with vault_mutation_lock():
current = repository.get_note_record(note_id)
if current != record or note_service._read_markdown(record.file_path) != markdown:
# Another save or rename won the race; leave the durable queue entry intact.
@@ -254,6 +271,14 @@ async def _refresh_saved_note(note_id: str) -> None:
conn = connect()
try:
with transaction(conn):
existing_ids = {row[0] for row in conn.execute('SELECT block_id FROM blocks WHERE note_id=?', (note_id,))}
if existing_ids != {block.block_id for block in parsed.blocks}:
# An external editor changed a newly registered note while inference ran.
# Reconcile that note only; the snapshot check above protects newer saves.
parsed.title = parse_note(markdown=markdown, file_path=record.file_path,
folder=record.folder, tags=record.tags, created_at=record.created_at,
updated_at=record.updated_at, note_id=note_id).title
await index_note(parsed, prepared=prepared, conn=conn)
# Write only vectors: metadata and FTS already represent the saved revision.
vectors, remote = prepared
from app.retrieval.vectorstore import VectorRecord
@@ -261,14 +286,24 @@ async def _refresh_saved_note(note_id: str) -> None:
await vector_store.upsert([VectorRecord(id=b.block_id, vector=v)
for b, v in zip(parsed.blocks, vectors)], conn=conn)
routed_vectors.store_remote(conn, [b.block_id for b in parsed.blocks], remote)
if isinstance(note_service.embedding, LocalEmbedding) and parsed.blocks:
from app.retrieval.space_index import table_name
if remote is None:
raise ApiError(503, 'EMBEDDING_UNAVAILABLE', '笔记已保存,向量计算未完成。')
table = table_name(remote.space_id, remote.dimensions)
missing = conn.execute(f'SELECT 1 FROM blocks b LEFT JOIN {table} v ON v.block_id=b.block_id WHERE b.note_id=? AND v.block_id IS NULL LIMIT 1', (note_id,)).fetchone()
if missing:
raise ApiError(500, 'SEMANTIC_INDEX_WRITE_FAILED', '向量写入未完成,保留待处理标记。')
repository.set_index_meta({key: '0'}, conn=conn)
finally:
conn.close()
_last_completed_at = datetime.now(timezone.utc)
_remember_job(IndexJob(job_id=job_id, status='completed', scope='all', created_at=_last_completed_at))
except BaseException as exc:
log_event('vectors', 'index.failed', level='WARNING' if isinstance(exc, asyncio.CancelledError) else 'ERROR', error=exc, job_id=job_id)
_last_error = str(exc) or '后台向量计算已中断,笔记已保存。'
_remember_job(IndexJob(job_id=job_id, status='failed', scope='all', created_at=datetime.now(timezone.utc)))
raise
finally:
_active_job_id = None
_active_scope = None
@@ -19,6 +19,13 @@ def connection():
def record(**values):
from app.operation_logs import log_event
log_event('models', 'model.' + str(values.get('operation', 'inference')),
level='ERROR' if values.get('status') == 'failed' else 'WARNING' if values.get('status') == 'fallback' else 'INFO',
model=values.get('model'), source=values.get('source'), status=values.get('status'),
device=values.get('actual_device') or values.get('attempted_device'),
error_code=values.get('error_code'), fallback=values.get('fallback_reason'),
duration_ms=round(values.get('elapsed_seconds', 0) * 1000, 2))
safe = {key: value[:240] for key, value in values.items() if key in TEXT and isinstance(value, str)}
safe.update({key: value for key, value in values.items()
if key in NUMBERS and type(value) in (float, int) and math.isfinite(value) and value >= 0})
+29
View File
@@ -2,11 +2,37 @@ from __future__ import annotations
from datetime import datetime, timezone
from uuid import uuid4
import asyncio
from contextvars import copy_context
from functools import partial
from weakref import WeakKeyDictionary
from app import repository
from app.contracts import Task, TaskStatus
from app.database.db import connect, transaction
from app.errors import ApiError
from app.operation_logs import log_event
_write_locks = WeakKeyDictionary()
async def write_in_background(operation, *args, **kwargs):
# SQLite has one writer. Queue cooperatively instead of letting many worker
# threads fight over the file lock and starve unrelated model work.
loop = asyncio.get_running_loop()
lock = _write_locks.setdefault(loop, asyncio.Lock())
async with lock:
work = loop.run_in_executor(None, copy_context().run, partial(operation, *args, **kwargs))
cancelled = False
while not work.done():
try:
await asyncio.shield(work)
except asyncio.CancelledError:
cancelled = True
result = work.result()
if cancelled:
raise asyncio.CancelledError
return result
def _now() -> datetime:
@@ -49,6 +75,7 @@ def create_task(
),
)
row = conn.execute("SELECT * FROM tasks WHERE task_id = ?", (task_id,)).fetchone()
log_event('tasks', 'task.created', task_id=task_id, note_id=note_id, status='todo')
return _task_from_row(row)
finally:
conn.close()
@@ -111,6 +138,7 @@ def update_task(task_id: str, values: dict[str, object]) -> Task:
params,
)
row = conn.execute("SELECT * FROM tasks WHERE task_id = ?", (task_id,)).fetchone()
log_event('tasks', 'task.updated', task_id=task_id, status=row['status'], changed_fields=','.join(values))
return _task_from_row(row)
finally:
conn.close()
@@ -121,6 +149,7 @@ def delete_task(task_id: str) -> bool:
try:
with transaction(conn):
cursor = conn.execute("DELETE FROM tasks WHERE task_id = ?", (task_id,))
log_event('tasks', 'task.deleted' if cursor.rowcount else 'task.not_found', task_id=task_id)
return cursor.rowcount > 0
finally:
conn.close()
+5
View File
@@ -98,6 +98,11 @@ class UsageAttempt:
reasoning_tokens=first("output_tokens_details.reasoning_tokens", "completion_tokens_details.reasoning_tokens"))
def persist(self):
from app.operation_logs import log_event
log_event('providers', 'model.request_finished', level='INFO' if self.completed else 'WARNING',
provider_id=self.provider_id, model=self.model, run_id=self.run_id,
request_id=self.request_id, source=self.source,
status='completed' if self.completed else 'incomplete')
try:
with closing(connection()) as conn:
conn.execute("INSERT OR REPLACE INTO model_usage VALUES (?,?,?,?,?,?,?,?,?,?,?)", (
+9 -1
View File
@@ -105,6 +105,14 @@ def get_workspace_tree() -> list[WorkspaceEntry]:
return _tree(get_settings().vault_path.resolve(), locations)
async def refresh_workspace_tree() -> list[WorkspaceEntry]:
"""Observe external creates/deletes without waiting for vector inference."""
if get_workspace_info().requires_refresh:
await _register_workspace_files()
index_service.schedule_workspace_rebuild()
return get_workspace_tree()
async def open_workspace(requested_path: str | None) -> WorkspaceSnapshot:
"""打开只登记文件与全文索引,不让 Embedding 或厂商网络阻塞工作区。"""
@@ -153,7 +161,7 @@ async def _register_workspace_files() -> None:
created_at=parsed.created_at, updated_at=parsed.updated_at, blocks=parsed.blocks)
conn.execute('UPDATE blocks SET embedding_local_only=? WHERE note_id=?', (int(parsed.embedding_local_only), parsed.note_id))
if prepared:
repository.set_index_meta({'workspace_vectors_pending': '1'}, conn=conn)
repository.set_index_meta({f'note_vectors_pending:{parsed.note_id}': '1' for parsed in prepared}, conn=conn)
finally:
conn.close()
@@ -16,3 +16,5 @@ tags: RAG, 产品
粗排后使用 Reranker 对候选块重新打分,提升相关性。
<br />
@@ -2,7 +2,6 @@
title: 功能演示导航
tags: 演示, 入门
---
# 功能演示导航
这组笔记用于在真实工作区查看 Markdown、代码高亮、图表和检索效果。文中的项目、日期和数据均为演示内容。
@@ -10,12 +9,13 @@ tags: 演示, 入门
## 建议阅读顺序
| 笔记 | 可以查看的功能 |
| --- | --- |
| ----------------------------- | ---------------------- |
| 01 Markdown 与大纲 | 元数据、标题层级、列表、引用、表格与行内代码 |
| 02 多语言代码与公式 | Shiki 语言配色、代码块标签、数学公式 |
| 03 Mermaid 图表集 | 六种常用图型、主题颜色和大图查看 |
| 04 星灯项目资料 | 全文搜索、知识库问答与引用定位 |
| 05 Skill 与 Plugin 操作样例 | 扩展安装、选区命令和只读笔记检查 |
| [06 警告框与提示框](06%20警告框与提示框.md) | 类型与别名、标题、折叠、嵌套和主题配色 |
## 工作区操作
@@ -35,3 +35,4 @@ tags: 演示, 入门
- [ ] 在已配置模型后进行一次带知识库检索的问答。
> 上述清单供体验时自行勾选,不是自动验收结果。模型调用可能产生费用,图表与代码示例本身不会执行代码。
@@ -2,7 +2,6 @@
title: 星灯资料站项目简报
tags: 演示, 星灯项目, 检索
---
# 星灯资料站
星灯资料站是本组演示中的虚构项目,目标是为一个读书小组建立离线可用的学习资料目录。项目代号为 ST-27。
@@ -38,3 +37,4 @@ tags: 演示, 星灯项目, 检索
最后一个问题在本笔记中没有答案。检查回答是否说明资料不足,而不是编造负责人。其他问题可以对照正文并点击引用定位核实。
> 新建笔记需要完成索引后才能参与检索。没有模型配置时,也可以先在搜索页使用项目名、代号或独特检索词查找原文。
@@ -0,0 +1,150 @@
---
title: 警告框与提示框演示
tags: 演示, Markdown, 警告框, 主题
---
# 警告框与提示框
本页展示 GitHub 警告框和 Obsidian 提示框的类型、标题、折叠、嵌套及正文格式。打开工作区写作模式查看效果;切换源码模式查看原始语法。
## 五种常用警告框
> [!NOTE]
> 记录补充信息:这份笔记中的内容都是功能演示,不会执行代码或调用模型。
> [!TIP] 小技巧:快速插入
> 点击编辑器顶部的“提示框”选择器,选择类型后替换模板内容。
> [!IMPORTANT] 保存与显示状态
> 点击标题展开或收起,只改变本次显示状态。要修改默认状态,请在源码中的类型标记后添加 `+``-`
> [!WARNING] 修改前保留原文
> 在演示笔记中练习时,可以先复制一段内容;需要恢复时使用撤销。
> [!CAUTION] 需要重点关注的说明
> `CAUTION``WARNING` 使用同一警告配色。提示框是笔记内容,不是应用报错弹窗。
## 更多类型
> [!ABSTRACT] 本页摘要
> 类型区分语义,标题说明重点,正文保留详细信息。
> [!INFO] 环境信息
> 警告框的边框、标题和背景随主题变化。
> [!TODO] 待办
> - [ ] 展开下方折叠示例。
> - [ ] 切换深色主题。
> - [ ] 保存后重新打开本页。
> [!SUCCESS] 已完成
> 本段展示成功状态,不代表自动测试或实际任务已经完成。
> [!QUESTION] 可以嵌套吗?
> 可以。增加一级引用符号即可在提示框中嵌入另一个提示框。
> [!FAILURE] 未达到预期
> 示例:资料中缺少日期,需要补充后再归档。
> [!DANGER] 风险提示
> 示例:不要把唯一一份原始资料直接覆盖为整理结果。
> [!BUG] 问题记录
> 示例:发现显示异常时,记录主题、操作步骤和对应 Markdown 源码。
> [!EXAMPLE] 示例
> 将提示内容写成一句明确的说明,比只写“注意”更容易理解。
> [!QUOTE] 摘录
> 一条笔记既要保留结论,也要保留形成结论的依据。
## 默认展开与默认折叠
> [!TIP]+ 默认展开:点击标题试试
> 类型后的 `+` 表示默认展开。点击标题可收起,再次点击可展开。
> [!WARNING]- 默认折叠:点击查看内容
> 你已经展开了这段说明。类型后的 `-` 表示重新渲染时默认收起。
>
> 正文可以包含 **加粗**、*斜体*、~~删除线~~ 和 `行内代码`
## 嵌套与混合格式
> [!INFO]+ 一次资料整理
> 先整理来源,再检查缺漏。
>
> 1. 收集原始资料。
> 2. 按主题分组。
> 3. 为尚未确认的内容添加说明。
>
> > [!SUCCESS] 已收集
> > 原始笔记、会议纪要和参考链接已放入同一文件夹。
>
> > [!WARNING]- 尚待确认
> > 一条资料缺少发布日期,需要补充来源。
>
> | 项目 | 状态 |
> | --- | --- |
> | 原始资料 | 已归档 |
> | 日期核对 | 待补充 |
>
> ```python
> notes = ["原始资料", "整理结果"]
> print(len(notes))
> ```
>
> 行内公式:$a^2 + b^2 = c^2$。
## 类型别名
别名不区分大小写。下面的表格列出兼容关系。
| 类型 | 别名 |
| --- | --- |
| abstract | summary、tldr |
| tip | hint |
| success | check、done |
| question | help、faq |
| warning | caution、attention |
| failure | fail、missing |
| danger | error |
| quote | cite |
> [!summary] 摘要别名
> 这段使用 `summary`,外观与 `abstract` 一致。
> [!check] 成功别名
> 这段使用 `check`,外观与 `success` 一致。
> [!custom-demo] 未知类型的回退
> 自定义类型暂时使用 note 外观,源文件中的类型名仍然保留。
## 语法对照
以下围栏中的内容应当保持为代码,不渲染成警告框。
```markdown
> [!NOTE] 自定义标题
> 正文内容。
> [!WARNING]- 默认折叠
> 点击标题查看正文。
> [!TIP]+ 默认展开
> 默认可见的正文。
```
普通行内代码也保持原样:`[!WARNING]`
> 这是一段普通引用,没有提示类型标记,因此不应显示为警告框。
## 主题与保存体验清单
- [ ] 在浅色、深色、护眼主题下区分信息、成功、警告与危险颜色。
- [ ] 使用纸间时光,查看纸张虚线边框和嵌套层次。
- [ ] 使用 Ocean Blue 与 Midnight Purple,检查标题和正文是否清晰。
- [ ] 点击折叠标题,并使用 Tab、Enter 或空格体验键盘操作。
- [ ] 在源码模式修改一个类型或标题,再切回写作模式。
- [ ] 保存并重新打开,确认类型、标题、正文与默认折叠状态保持一致。
这是一份手动体验清单,未勾选不表示功能失败。桌面容器的原生格式快捷键与元数据转换仍属于第三阶段规划。
@@ -0,0 +1,958 @@
# 长文渲染压力测试
## 第 1 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 1
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 2 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 2
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 3 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 3
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 4 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 4
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 5 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 5
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 6 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 6
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 7 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 7
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 8 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 8
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 9 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 9
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 10 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 10
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 11 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 11
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 12 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 12
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 13 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 13
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 14 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 14
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 15 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 15
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 16 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 16
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 17 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 17
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 18 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 18
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 19 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 19
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 20 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 20
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 21 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 21
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 22 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 22
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 23 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 23
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 24 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 24
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 25 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 25
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 26 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 26
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 27 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 27
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 28 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 28
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 29 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 29
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 30 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 30
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 31 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 31
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 32 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 32
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 33 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 33
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 34 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 34
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 35 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 35
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 36 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 36
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 37 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 37
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 38 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 38
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 39 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 39
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 40 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 40
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 41 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 41
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 42 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 42
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 43 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 43
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 44 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 44
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 45 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 45
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 46 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 46
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 47 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 47
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 48 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 48
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 49 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 49
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 50 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 50
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 51 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 51
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 52 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 52
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 53 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 53
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 54 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 54
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 55 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 55
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 56 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 56
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 57 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 57
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 58 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 58
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 59 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 59
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 60 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 60
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 61 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 61
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 62 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 62
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 63 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 63
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 64 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 64
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 65 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 65
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 66 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 66
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 67 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 67
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 68 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 68
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 69 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 69
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 70 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 70
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 71 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 71
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 72 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 72
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 73 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 73
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 74 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 74
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 75 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 75
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 76 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 76
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 77 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 77
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 78 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 78
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 79 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 79
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 80 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 80
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 81 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 81
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 82 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 82
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 83 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 83
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 84 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 84
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 85 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 85
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 86 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 86
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 87 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 87
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 88 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 88
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 89 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 89
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 90 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 90
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 91 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 91
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 92 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 92
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 93 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 93
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 94 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 94
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 95 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 95
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 96 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 96
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
> [!TIP] 验收提示
> 内容需要保留,折叠后仍可展开。
| 项目 | 状态 |
| --- | --- |
| 渲染 | 待验证 |
```javascript
const note = { title: "长文测试", ready: true };
console.log(note);
```
## 第 97 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 97
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 98 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 98
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 99 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 99
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 100 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 100
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 第 101 节:知识整理
本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。本地知识库保存课程记录与项目思考,编辑时需要稳定响应。长篇文档包含章节结构和引用信息,阅读过程中可以随时折叠展开。这里使用生成的测试内容验证渲染性能,不读取真实笔记。
### 小结 101
重点包含 **强调文字**`inlineCode` 和 [链接](https://example.com)。
## 文末校验
结束标记:长文内容完整。
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+250
View File
@@ -0,0 +1,250 @@
"""Offline Agent/runtime and task API load test; all state lives in a temporary directory."""
from __future__ import annotations
import argparse
import asyncio
import json
import inspect
import math
import os
import pathlib
import platform
import sys
import tempfile
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
def stats(values):
values = sorted(values)
return {"count": len(values), "median_ms": round(values[len(values)//2], 2),
"p95_ms": round(values[min(len(values)-1, math.ceil(len(values)*.95)-1)], 2),
"max_ms": round(values[-1], 2)} if values else {"count": 0}
async def main(output):
# Set before importing any app modules: container has import-time initialization.
with tempfile.TemporaryDirectory(prefix="notes-agent-task-stress-") as directory:
root = pathlib.Path(directory)
os.environ.update(APP_DATA_DIR=str(root / 'data'), APP_DB_PATH=str(root / 'app.db'),
APP_VAULT_PATH=str(root / 'vault'))
from app.container import container
from app.contracts import AgentRunCreateRequest, AgentRunStatus
from app.agent.runtime import AgentRuntime, AgentCapacityError
from app.agent.permissions import PermissionMode
from app.main import app
import httpx
report = {"python": platform.python_version(), "platform": platform.platform(),
"provider": "mock with 50 ms injected delay per model turn; no network", "results": []}
def save(name, value):
report['results'].append({"scenario": name, **value})
output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report['results'][-1], ensure_ascii=False), flush=True)
async def measured(operation):
delays = []
async def heartbeat():
while True:
start = time.perf_counter()
await asyncio.sleep(.01)
delays.append(max(0, (time.perf_counter()-start)*1000-10))
pulse = asyncio.create_task(heartbeat())
await asyncio.sleep(0)
start = time.perf_counter()
try:
result = await operation()
await asyncio.sleep(.02)
return {**result, "elapsed_ms": round((time.perf_counter()-start)*1000, 2),
"event_loop_lag": stats(delays)}
finally:
pulse.cancel()
await asyncio.gather(pulse, return_exceptions=True)
adapter = container.providers.get('mock').adapter
original = adapter.complete
async def delayed(request):
await asyncio.sleep(.05)
return await original(request)
adapter.complete = delayed
runtime = container.agent
for concurrency in (1, 10, 50, 200):
async def batch():
durations, sequences, statuses = [], [], []
semaphore = asyncio.Semaphore(concurrency)
async def one(index):
async with semaphore:
start = time.perf_counter()
created = await runtime.create_run(AgentRunCreateRequest(
input=f'/tool system.echo {{"text":"pressure-{index}"}}',
provider_id='mock', model='mock-1', allowed_tools=['system.echo']))
events = [event async for event in runtime.events(created.run_id)]
done = await runtime.wait(created.run_id)
durations.append((time.perf_counter()-start)*1000)
statuses.append(done.status.value)
sequence = [event.sequence for event in events]
sequences.append(sequence == list(range(len(sequence))))
assert done.status == AgentRunStatus.completed
assert done.tool_results[0].output == {"text": f"pressure-{index}"}
replay = [event.sequence async for event in runtime.events(created.run_id, after_sequence=2)]
assert replay == sequence[3:]
return created.run_id
ids = await asyncio.gather(*(one(i) for i in range(max(20, concurrency))))
assert all(sequences)
recovered = AgentRuntime(container.providers, container.tools, container.permissions,
trace_repository=runtime.trace_repository)
assert all(recovered.get_run(run_id).status == AgentRunStatus.completed for run_id in ids)
assert not any(record.subscribers for record in runtime._records.values())
return {"concurrency": concurrency, "runs": len(ids), "latency": stats(durations),
"completed": statuses.count('completed'), "ordered_events_and_replay": True,
"terminal_recovery": True, "retained_records": len(runtime._records)}
save('agent_tool_runs', await measured(batch))
# Hold model calls so all 200 records remain active while testing admission.
gate = asyncio.Event()
async def blocked(request):
await gate.wait()
return await original(request)
adapter.complete = blocked
async def capacity():
ids = [(await runtime.create_run(AgentRunCreateRequest(input='capacity', provider_id='mock', model='mock-1'))).run_id for _ in range(200)]
rejected = False
try:
await runtime.create_run(AgentRunCreateRequest(input='overflow', provider_id='mock', model='mock-1'))
except AgentCapacityError:
rejected = True
await asyncio.sleep(0)
latencies = []
for run_id in ids:
start = time.perf_counter()
await runtime.cancel(run_id)
latencies.append((time.perf_counter()-start)*1000)
states = await asyncio.gather(*(runtime.wait(run_id) for run_id in ids))
assert rejected and all(run.status == AgentRunStatus.cancelled for run in states)
assert all(not record.task or record.task.done() for record in runtime._records.values())
return {"active_limit": 200, "overflow_rejected": rejected, "cancelled": len(states), "cancel_latency": stats(latencies)}
save('capacity_and_cancel', await measured(capacity))
adapter.complete = delayed
async def permissions():
tool = container.tools.get('system.echo')
previous = tool.definition.permission
tool.definition.permission = 'stress.confirm'
container.permissions.policy.set_rule('stress.confirm', PermissionMode.confirm)
async def one(index):
created = await runtime.create_run(AgentRunCreateRequest(input='/tool system.echo {"text":"permission"}',
provider_id='mock', model='mock-1', allowed_tools=['system.echo'], tool_timeout_seconds=30))
stream = runtime.events(created.run_id)
try:
async for event in stream:
if event.event.value == 'PermissionRequired':
if index % 2: await runtime.cancel(created.run_id)
else: assert await runtime.resolve_permission(created.run_id, str(event.data['request_id']), 'allow')
break
finally:
await stream.aclose()
return (await runtime.wait(created.run_id)).status.value
try:
states = await asyncio.wait_for(asyncio.gather(*(one(i) for i in range(20))), 60)
assert states.count('completed') == states.count('cancelled') == 10
assert not any(record.subscribers for record in runtime._records.values())
return {"runs": 20, "approved_completed": 10, "cancelled_waiting_permission": 10, "subscribers_released": True}
finally:
tool.definition.permission = previous
save('permission_wait', await measured(permissions))
async def failures():
active = 0
async def injected(request):
text = request.messages[-1].content
if text == 'inject-provider-error': raise RuntimeError('injected offline provider failure')
if text == 'inject-model-timeout': await asyncio.sleep(60)
return await delayed(request)
tool = container.tools.get('system.echo')
executor = tool.executor
async def slow_tool(arguments, context):
nonlocal active
active += 1
try:
if arguments.text == 'slow': await asyncio.sleep(60)
value = executor(arguments, context)
return await value if inspect.isawaitable(value) else value
finally: active -= 1
adapter.complete = injected
tool.executor = slow_tool
async def one(index):
mode = index % 4
text = ['normal', 'inject-provider-error', 'inject-model-timeout', '/tool system.echo {"text":"slow"}'][mode]
created = await runtime.create_run(AgentRunCreateRequest(input=text, provider_id='mock', model='mock-1',
allowed_tools=['system.echo'], run_timeout_seconds=1 if mode == 2 else 30, tool_timeout_seconds=1))
result = await runtime.wait(created.run_id)
if mode == 0: assert result.status == AgentRunStatus.completed
elif mode == 1: assert result.status == AgentRunStatus.failed and result.error_code == 'AGENT_FAILED'
elif mode == 2: assert result.status == AgentRunStatus.failed and result.error_code == 'AGENT_TIMEOUT'
else: assert result.tool_results[0].error_code == 'TOOL_TIMEOUT'
try:
await asyncio.wait_for(asyncio.gather(*(one(i) for i in range(20))), 45)
assert active == 0
return {"runs": 20, "success": 5, "provider_errors": 5, "model_timeouts": 5,
"tool_timeouts": 5, "remaining_tool_executors": active}
finally:
adapter.complete = delayed
tool.executor = executor
save('failure_and_timeout_isolation', await measured(failures))
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://stress.local') as client:
for count in (100, 1000):
async def tasks():
timings = {name: [] for name in ('create', 'update', 'list', 'delete')}
async def call(method, path, **kwargs):
start = time.perf_counter()
response = await client.request(method, path, **kwargs)
response.raise_for_status()
return response.json(), (time.perf_counter()-start)*1000
semaphore = asyncio.Semaphore(20)
async def create(index):
async with semaphore:
body, duration = await call('POST', '/api/tasks', json={'title': f'压测任务 {index}', 'description': '独立测试数据'})
timings['create'].append(duration)
return body['task_id']
ids = await asyncio.gather(*(create(i) for i in range(count)))
first, _ = await call('GET', '/api/tasks')
seen = []
for offset in range(0, count, 100):
body, duration = await call('GET', f'/api/tasks?limit=100&offset={offset}')
timings['list'].append(duration)
seen.extend(item['task_id'] for item in body['items'])
assert len(set(seen)) == count and set(seen) == set(ids)
async def change(run_id):
async with semaphore:
body, duration = await call('PATCH', f'/api/tasks/{run_id}', json={'status': 'done'})
assert body['status'] == 'done'
timings['update'].append(duration)
_, duration = await call('DELETE', f'/api/tasks/{run_id}')
timings['delete'].append(duration)
await asyncio.gather(*(change(run_id) for run_id in ids))
final, _ = await call('GET', '/api/tasks')
assert final['page']['total'] == 0
return {"tasks": count, "client_concurrency": 20, "latencies": {key: stats(value) for key, value in timings.items()},
"default_page_count": len(first['items']), "default_total": first['page']['total'],
"pagination_complete": True, "final_total": 0}
save('task_api_crud', await measured(tasks))
report['database_bytes'] = (root / 'app.db').stat().st_size
report['complete'] = True
output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
container.plugins.shutdown()
container.mcp_servers.shutdown()
from app.operation_logs import shutdown_logging
await asyncio.to_thread(shutdown_logging)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--output', type=pathlib.Path, required=True)
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
asyncio.run(main(args.output))
+96
View File
@@ -0,0 +1,96 @@
"""Real loopback HTTP task load with a separate, temporary Uvicorn process."""
import argparse
import asyncio
import json
import math
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
from time import perf_counter
import httpx
def stats(values):
values = sorted(values)
return {'count': len(values), 'p95_ms': round(values[math.ceil(len(values)*.95)-1], 2),
'max_ms': round(values[-1], 2)} if values else {'count': 0}
async def main(args):
with tempfile.TemporaryDirectory(prefix='notes-task-http-') as directory:
root = Path(directory)
env = {**os.environ, 'APP_DATA_DIR': str(root/'data'), 'APP_DB_PATH': str(root/'app.db'), 'APP_VAULT_PATH': str(root/'vault')}
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]
process = subprocess.Popen([sys.executable, '-m', 'uvicorn', 'app.main:app', '--host', '127.0.0.1', '--port', str(port), '--log-level', 'error'],
cwd=Path(__file__).resolve().parents[1], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
try:
async with httpx.AsyncClient(base_url=f'http://127.0.0.1:{port}', timeout=30) as client:
for _ in range(150):
if process.poll() is not None: raise RuntimeError('Isolated Uvicorn exited')
try:
(await client.get('/health')).raise_for_status(); break
except httpx.HTTPError: await asyncio.sleep(.1)
else: raise TimeoutError('Isolated Uvicorn startup')
sem = asyncio.Semaphore(args.concurrency)
timings = {key: [] for key in ('create', 'update', 'list', 'delete', 'health')}
errors = []
async def request(method, path, kind, **kwargs):
start = perf_counter()
response = await client.request(method, path, **kwargs)
timings[kind].append((perf_counter()-start)*1000)
response.raise_for_status()
return response.json()
async def health():
while True:
try: await request('GET', '/health', 'health')
except httpx.HTTPError as error: errors.append(type(error).__name__)
await asyncio.sleep(.05)
heartbeat = asyncio.create_task(health())
start = perf_counter()
try:
async def create(index):
async with sem:
return (await request('POST', '/api/tasks', 'create', json={'title': f'HTTP 压测 {index}'}))['task_id']
ids = await asyncio.gather(*(create(i) for i in range(args.count)))
seen = []
for offset in range(0, args.count, 100):
page = await request('GET', f'/api/tasks?limit=100&offset={offset}', 'list')
seen.extend(item['task_id'] for item in page['items'])
assert set(seen) == set(ids) and len(seen) == args.count
async def change(task_id):
async with sem:
updated = await request('PATCH', f'/api/tasks/{task_id}', 'update', json={'status': 'done'})
assert updated['status'] == 'done'
await request('DELETE', f'/api/tasks/{task_id}', 'delete')
await asyncio.gather(*(change(task_id) for task_id in ids))
remaining = await request('GET', '/api/tasks', 'list')
assert remaining['page']['total'] == 0
finally:
heartbeat.cancel(); await asyncio.gather(heartbeat, return_exceptions=True)
report = {'transport': 'real loopback HTTP, separate Uvicorn process', 'tasks': args.count,
'concurrency': args.concurrency, 'elapsed_ms': round((perf_counter()-start)*1000, 2),
'latencies': {key: stats(value) for key,value in timings.items()}, 'health_errors': errors,
'pagination_complete': True, 'final_total': 0}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False))
finally:
process.terminate()
try: process.wait(timeout=10)
except subprocess.TimeoutExpired: process.kill(); process.wait()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--count', type=int, default=1000)
parser.add_argument('--concurrency', type=int, default=20)
args = parser.parse_args()
if args.count < 1 or args.concurrency < 1: parser.error('count and concurrency must be positive')
asyncio.run(main(args))
+64
View File
@@ -0,0 +1,64 @@
"""Synthetic, isolated exact-search comparison; does not access the user Vault."""
import heapq
import json
import math
import random
import sqlite3
import statistics
import sys
import tempfile
import time
from pathlib import Path
import sqlite_vec
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.retrieval import space_index
from app.retrieval.routed_vectors import RemoteEmbeddings, _unit_vector
def main():
rng = random.Random(42)
count, dimensions = 4000, 384
with tempfile.TemporaryDirectory(prefix='notes-vec-bench-') as temporary:
conn = sqlite3.connect(Path(temporary) / 'vectors.db')
conn.row_factory = sqlite3.Row
conn.enable_load_extension(True)
sqlite_vec.load(conn)
conn.enable_load_extension(False)
conn.execute('CREATE TABLE blocks(block_id TEXT PRIMARY KEY, embedding_local_only INTEGER)')
conn.execute('CREATE TABLE routed_block_vectors(space_id TEXT,block_id TEXT,dimensions INTEGER,vector TEXT,PRIMARY KEY(space_id,dimensions,block_id))')
vectors = [_unit_vector([rng.uniform(-1, 1) for _ in range(dimensions)], dimensions) for _ in range(count)]
conn.executemany('INSERT INTO blocks VALUES (?,0)', [(str(i),) for i in range(count)])
conn.executemany('INSERT INTO routed_block_vectors VALUES (?,?,?,?)', [('benchmark', str(i), dimensions, json.dumps(v)) for i, v in enumerate(vectors)])
start = time.perf_counter()
space_index.ensure(conn, 'benchmark', dimensions)
migration_ms = (time.perf_counter() - start) * 1000
conn.commit()
query = vectors[0]
batch = RemoteEmbeddings('benchmark', dimensions, [query])
def legacy():
def hits():
for row in conn.execute('SELECT block_id,vector FROM routed_block_vectors'):
vector = _unit_vector(json.loads(row[1]), dimensions)
yield row[0], max(0., min(1., math.fsum(a*b for a,b in zip(query,vector))))
return heapq.nlargest(20, hits(), key=lambda hit:hit[1])
def native():
return [(hit.id,hit.score) for hit in space_index.search(conn,batch,20)]
measurements = {}
results = {}
for name, operation in [('python_json_scan', legacy), ('sqlite_vec',native)]:
elapsed = []
for _ in range(5):
start = time.perf_counter()
results[name] = operation()
elapsed.append((time.perf_counter()-start)*1000)
measurements[name] = {'median_ms':statistics.median(elapsed), 'samples_ms':elapsed}
assert [hit[0] for hit in results['python_json_scan']] == [hit[0] for hit in results['sqlite_vec']]
print(json.dumps({'blocks':count,'dimensions':dimensions,'top_k':20,'migration_ms':migration_ms,
'same_top_k':True,'measurements':measurements},indent=2))
conn.close()
if __name__ == '__main__':
main()
+4 -3
View File
@@ -112,7 +112,7 @@ def test_permission_confirmation_resumes_agent() -> None:
break
assert request_id is not None
assert container.agent.resolve_permission(
assert await container.agent.resolve_permission(
created.run_id, request_id, "allow_once"
)
completed = await container.agent.wait(created.run_id)
@@ -370,8 +370,9 @@ def test_cancelling_permission_wait_cancels_run() -> None:
)
async with asyncio.timeout(2):
while container.agent.get_run(created.run_id).status != AgentRunStatus.waiting_permission:
await asyncio.sleep(0)
async for event in container.agent.events(created.run_id):
if event.event == AgentEventType.permission_required:
break
cancelled = await container.agent.cancel(created.run_id)
await container.agent.wait(created.run_id)
+68
View File
@@ -0,0 +1,68 @@
import asyncio
from types import SimpleNamespace
import pytest
from app.retrieval import activity
from app.services import index_service
@pytest.fixture(autouse=True)
def reset_activity(monkeypatch):
for field in ('active', 'completed', 'failed', 'cancelled'):
monkeypatch.setattr(activity, field, 0)
monkeypatch.setattr(index_service, '_active_job_id', None)
monkeypatch.setattr(index_service, '_active_scope', None)
monkeypatch.setattr(index_service, '_last_error', None)
monkeypatch.setattr(index_service.repository, 'stats', lambda: {'notes': 16, 'blocks': 3787})
monkeypatch.setattr(index_service.repository, 'get_index_meta', lambda: {})
def test_pending_rebuild_and_incremental_jobs(monkeypatch):
meta = {'workspace_vectors_pending': '1', 'note_vectors_pending:a': '1', 'note_vectors_pending:b': '1'}
monkeypatch.setattr(index_service.repository, 'get_index_meta', lambda: meta)
status = index_service.get_status()
assert status.vector_refresh_required and status.pending_jobs == 1
assert status.running_jobs == 0
monkeypatch.setattr(index_service, '_active_job_id', 'job_test')
monkeypatch.setattr(index_service, '_active_scope', 'all')
status = index_service.get_status()
assert (status.status, status.pending_jobs, status.running_jobs) == ('running', 1, 1)
monkeypatch.setattr(index_service, '_active_scope', 'note')
assert index_service.get_status().pending_jobs == 2
meta.pop('workspace_vectors_pending')
assert index_service.get_status().pending_jobs == 2
monkeypatch.setattr(index_service, '_active_job_id', None)
monkeypatch.setattr(index_service, '_last_error', 'failed')
status = index_service.get_status()
assert (status.status, status.pending_jobs, status.running_jobs) == ('failed', 2, 0)
meta.clear()
assert index_service.get_status().pending_jobs == 0
def test_search_activity_covers_completion_failure_and_cancellation():
async def scenario():
gate = asyncio.Event()
@activity.track_search
async def search(_self, request):
await gate.wait()
if request.query == 'fail':
raise ValueError('failure')
return 'ok'
tasks = [asyncio.create_task(search(None, SimpleNamespace(mode=mode, query=query)))
for mode, query in [('vector', 'ok'), ('hybrid', 'fail'), ('vector', 'cancel'), ('fts', 'ok')]]
await asyncio.sleep(0)
assert index_service.get_status().active_searches == 3
tasks[2].cancel()
with pytest.raises(asyncio.CancelledError):
await tasks[2]
gate.set()
results = await asyncio.gather(*tasks, return_exceptions=True)
assert results[0] == results[3] == 'ok'
status = index_service.get_status()
assert (status.active_searches, status.completed_searches, status.failed_searches, status.cancelled_searches) == (0, 1, 1, 1)
assert status.pending_jobs == 0
asyncio.run(scenario())
+36
View File
@@ -12,6 +12,42 @@ from app.local_models.runtime import Runtime
from app.providers.base import ProviderError
@pytest.mark.parametrize('threaded', [False, True])
def test_large_embedding_result_crosses_pipe_limit_without_truncation(monkeypatch, tmp_path, threaded):
import app.local_models.runtime as module
import app.local_models.process as process_module
from app.local_models.protocol import response_lines
vector = [0.012345678901234567] * 384
result = {'result': [vector] * 2111}
assert len(json.dumps(result).encode()) > 16 * 1024 * 1024
assert max(map(len, response_lines(result, 'embedding'))) < 16 * 1024 * 1024
worker = tmp_path / 'large_worker.py'
protocol_dir = Path(module.__file__).parent
worker.write_text(
'import sys,json\n'
f'sys.path.insert(0, {str(protocol_dir)!r})\n'
'from protocol import response_lines\n'
'request=json.load(sys.stdin)\n'
'vector=[0.012345678901234567]*384\n'
'for line in response_lines({"result":[vector]*len(request["payload"]["texts"])}, "embedding"):\n'
' sys.stdout.write(line)\n', encoding='utf-8')
monkeypatch.setattr(module, 'read_state', lambda key: {'status': 'installed'})
monkeypatch.setattr(module, 'interpreter', lambda *_: Path(sys.executable))
original_async = asyncio.create_subprocess_exec
original_threaded = process_module.ThreadedProcess
async def spawn(*args, **kwargs):
if threaded:
raise NotImplementedError
return await original_async(sys.executable, str(worker), **kwargs)
monkeypatch.setattr(module.asyncio, 'create_subprocess_exec', spawn)
monkeypatch.setattr(process_module, 'ThreadedProcess',
lambda args, **kwargs: original_threaded((sys.executable, str(worker)), **kwargs))
actual = asyncio.run(Runtime().infer('bekko', 'embedding', {'texts': ['test'] * 2111}))
assert actual == result['result']
def test_download_resumes_partial_and_checks_digest(monkeypatch):
payload = b'verified-model-weights'
entry = {'path':'model.safetensors','size':len(payload),'hash':hashlib.sha256(payload).hexdigest(),
+151
View File
@@ -0,0 +1,151 @@
import asyncio
import json
import logging
import threading
from pathlib import Path
from app.operation_logs import LogStore, ApplicationLogHandler, get_store, log_event, shutdown_logging
def test_logs_persist_filter_cursor_and_retention(tmp_path):
store = LogStore(tmp_path / 'logs.db', retain=3)
try:
for i in range(6):
store.emit('ERROR' if i % 2 else 'INFO', 'vectors', 'embedding.failed', {'run_id': f'run_{i}'})
store.queue.join()
first = store.query(limit=2)
assert len(first['items']) == 2 and first['next_cursor']
assert len(store.query(before=first['next_cursor'])['items']) == 1
assert len(store.query(level='ERROR')['items']) == 2
assert len(store.query(q='run_5')['items']) == 1
assert not store.query(source='tasks')['items']
finally:
store.close()
reopened = LogStore(tmp_path / 'logs.db', retain=3)
try:
assert len(reopened.query()['items']) == 3
finally:
reopened.close()
def test_logs_exclude_content_and_legacy_exception_messages():
try:
log_event('vectors', 'embedding.failed', level='ERROR',
error=ValueError('private note and secret'), model='embedding-v1',
prompt='private note', arguments={'api_key': 'secret'}, api_key='secret')
handler = ApplicationLogHandler()
record = logging.LogRecord('app.sample', logging.ERROR, __file__, 1,
'private note and secret %s', ('credentials',), None)
handler.emit(record)
handler.emit(record) # a logger propagated to another installed handler
store = get_store()
store.queue.join()
data = json.dumps(store.query())
assert len(store.query()['items']) == 2
assert 'private note' not in data and 'credentials' not in data and 'api_key' not in data
assert 'ValueError' in data and 'embedding-v1' in data
finally:
shutdown_logging()
def test_http_log_correlates_task_operations_without_body():
import httpx
from app.main import app
async def scenario():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
response = await client.post('/api/tasks', json={'title': 'private title'})
assert response.status_code == 200
rid = response.headers['x-request-id']
store = get_store()
await asyncio.to_thread(store.queue.join)
result = (await client.get('/api/logs', params={'q': rid})).json()
assert len(result['items']) >= 2
assert 'private title' not in json.dumps(result)
assert any(item['event'] == 'task.created' for item in result['items'])
assert (await client.get('/api/logs', params={'limit': 201})).status_code == 422
try:
asyncio.run(scenario())
finally:
shutdown_logging()
def test_trace_writer_batches_off_loop_and_survives_cancel():
from app.agent.async_trace import AsyncTraceWriter
started, release = threading.Event(), threading.Event()
class Repository:
def write_batch(self, jobs):
assert threading.current_thread() is not threading.main_thread()
started.set()
assert release.wait(2)
self.jobs = jobs
async def scenario():
repo = Repository()
writer = AsyncTraceWriter(repo)
pending = asyncio.create_task(writer.submit('save', 'snapshot'))
while not started.is_set():
await asyncio.sleep(.001)
pending.cancel()
writer.worker.cancel() # simultaneous application shutdown
await asyncio.sleep(.005)
assert not pending.done()
release.set()
assert await asyncio.wait_for(pending, 2) is True
assert repo.jobs == [('save', ('snapshot',))]
assert writer.queue.empty()
asyncio.run(scenario())
def test_trace_write_failure_is_reported_and_next_submission_recovers():
from app.agent.async_trace import AsyncTraceWriter
class Repository:
fail = True
def write_batch(self, jobs):
if self.fail:
self.fail = False
raise OSError('disk unavailable')
async def scenario():
import pytest
writer = AsyncTraceWriter(Repository())
with pytest.raises(OSError):
await writer.submit('save', 'first')
assert not await writer.submit('save', 'second')
await writer.queue.join()
asyncio.run(scenario())
def test_log_write_failure_does_not_stall_queue(tmp_path, monkeypatch):
store = LogStore(tmp_path / 'failed.db')
try:
def broken():
raise OSError('disk unavailable')
monkeypatch.setattr(store, '_connect', broken)
store.emit('ERROR', 'vectors', 'embedding.failed', {'duration_ms': float('nan')})
store.queue.join()
assert store.failed == 1
finally:
store.close()
def test_cancelled_task_write_keeps_its_slot_until_commit():
from app.services.task_service import write_in_background
started, release = threading.Event(), threading.Event()
order = []
def first():
started.set()
assert release.wait(2)
order.append('first')
async def scenario():
import pytest
pending = asyncio.create_task(write_in_background(first))
while not started.is_set():
await asyncio.sleep(.001)
pending.cancel()
second = asyncio.create_task(write_in_background(lambda: order.append('second')))
await asyncio.sleep(.01)
assert order == []
release.set()
with pytest.raises(asyncio.CancelledError):
await pending
await second
assert order == ['first', 'second']
asyncio.run(scenario())
+155
View File
@@ -66,6 +66,161 @@ async def seed():
return apple, banana
def test_native_spaces_isolate_dimensions_and_reuse_without_json_scan(runtime, monkeypatch):
from app.retrieval import space_index
async def scenario():
apple, banana = await seed()
ids = [b.block_id for note in (apple, banana) for b in note.blocks]
conn = connect()
try:
with transaction(conn):
routed_vectors.store_remote(conn, ids, routed_vectors.RemoteEmbeddings('space-a', 4, [[1., 0., 0., 0.]] * len(ids)))
assert conn.execute('SELECT COUNT(DISTINCT dimensions) FROM routed_block_vectors').fetchone()[0] == 2
finally:
conn.close()
# A new connection uses the persistent native index, without reading vector JSON.
def forbidden(*args, **kwargs):
raise AssertionError('query decoded stored JSON')
monkeypatch.setattr(space_index.json, 'loads', forbidden)
hits = await routed_vectors.search_remote('apple orchard', top_k=2, strict=True)
assert len(hits) == 2
assert hits[0].id == apple.blocks[0].block_id
asyncio.run(scenario())
def test_legacy_vectors_migrate_without_document_embedding(runtime):
from app.retrieval import space_index
async def scenario():
apple, banana = await seed()
conn = connect()
table = space_index.table_name('space-a', 3)
try:
with transaction(conn):
conn.execute(f'DROP TRIGGER {table}_delete')
conn.execute(f'DROP TRIGGER {table}_update')
conn.execute(f'DROP TABLE {table}')
conn.execute('ALTER TABLE routed_block_vectors RENAME TO saved_vectors')
conn.execute('CREATE TABLE routed_block_vectors(space_id TEXT,block_id TEXT REFERENCES blocks(block_id) ON DELETE CASCADE,dimensions INTEGER,vector TEXT,PRIMARY KEY(space_id,block_id))')
conn.execute('INSERT INTO routed_block_vectors SELECT * FROM saved_vectors')
conn.execute('DROP TABLE saved_vectors')
finally:
conn.close()
runtime.calls.clear()
hits = await routed_vectors.search_remote('apple orchard', top_k=2, strict=True)
assert len(hits) == 2
assert runtime.calls == [['apple orchard']]
asyncio.run(scenario())
@pytest.mark.parametrize('partitioned', [False, True])
def test_concurrent_first_search_serializes_migration_and_warm_search_is_read_only(runtime, monkeypatch, partitioned):
import threading
from app.retrieval import space_index
async def scenario():
await seed()
table = space_index.table_name('space-a', 3)
conn = connect()
try:
with transaction(conn):
conn.execute(f'DROP TRIGGER {table}_delete')
conn.execute(f'DROP TRIGGER {table}_update')
conn.execute(f'DROP TABLE {table}')
finally:
conn.close()
entered, release, second = threading.Event(), threading.Event(), threading.Event()
original_ensure, original_prepare = space_index.ensure, space_index.prepare
calls = []
def ensure(*args):
calls.append(1)
entered.set()
assert release.wait(5)
return original_ensure(*args)
def prepare(*args):
if entered.is_set():
second.set()
return original_prepare(*args)
monkeypatch.setattr(space_index, 'ensure', ensure)
monkeypatch.setattr(space_index, 'prepare', prepare)
batch = routed_vectors.RemoteEmbeddings('space-a', 3, [[1., 0., 0.]])
async def search():
if entered.is_set():
second.set()
await routed_vectors._prepare_indexes([batch])
if partitioned:
return await asyncio.to_thread(routed_vectors._search_partitions, {False: batch}, {False}, 2, True)
return await asyncio.to_thread(routed_vectors._search_space, batch, 2, True)
tasks = []
try:
tasks.append(asyncio.create_task(search()))
assert await asyncio.to_thread(entered.wait, 5)
tasks.append(asyncio.create_task(search()))
assert await asyncio.to_thread(second.wait, 5)
release.set()
first, other = await asyncio.gather(*tasks)
assert first == other and len(first) == 2
assert len(calls) == 1
# Prepared indexes are reusable even with SQLite query_only enforced.
original_connect = routed_vectors.connect
def read_only():
connection = original_connect()
connection.execute('PRAGMA query_only=ON')
return connection
monkeypatch.setattr(routed_vectors, 'connect', read_only)
assert await search() == first
finally:
release.set()
await asyncio.gather(*tasks, return_exceptions=True)
asyncio.run(scenario())
@pytest.mark.parametrize('cancel_search', [False, True])
def test_save_waits_for_migration_even_when_search_is_cancelled(runtime, monkeypatch, cancel_search):
import threading
from app.retrieval import space_index
async def scenario():
apple, _ = await seed()
table = space_index.table_name('space-a', 3)
conn = connect()
try:
with transaction(conn):
conn.execute(f'DROP TRIGGER {table}_delete')
conn.execute(f'DROP TRIGGER {table}_update')
conn.execute(f'DROP TABLE {table}')
finally:
conn.close()
entered, release = threading.Event(), threading.Event()
original = space_index.ensure
def slow(*args):
entered.set()
assert release.wait(5)
return original(*args)
monkeypatch.setattr(space_index, 'ensure', slow)
# Keep the subsequent vector job queued; test saving and its durable marker.
monkeypatch.setattr(index_service, 'schedule_workspace_rebuild', lambda: None)
query = asyncio.create_task(routed_vectors.search_remote('apple orchard', top_k=2, strict=True))
save = None
try:
assert await asyncio.to_thread(entered.wait, 5)
if cancel_search:
query.cancel()
save = asyncio.create_task(note_service.update_note(apple.note_id, markdown='Saved during migration', defer_vectors=True))
await asyncio.sleep(0.02)
assert not save.done()
release.set()
saved = await asyncio.wait_for(save, 5)
assert saved.markdown == 'Saved during migration'
assert (await note_service.get_note(apple.note_id)).markdown == saved.markdown
assert repository.get_index_meta()[f'note_vectors_pending:{apple.note_id}'] == '1'
# Query may observe the saved revision's pending index, but saving must succeed.
result = (await asyncio.gather(query, return_exceptions=True))[0]
if cancel_search:
assert isinstance(result, asyncio.CancelledError)
finally:
release.set()
await asyncio.gather(*([query, save] if save else [query]), return_exceptions=True)
asyncio.run(scenario())
@pytest.mark.parametrize("outcome", ["api", "api_failure", "missing_space"])
def test_benchmark_reports_actual_embedding_and_fallback(runtime, outcome):
from app.benchmarks import service
+31
View File
@@ -114,3 +114,34 @@ def test_workspace_openapi_paths_are_published() -> None:
"/api/workspace/folders/delete",
"/api/notes/{note_id}/rename",
} <= paths.keys()
def test_external_files_are_registered_and_removed_without_vector_wait(monkeypatch) -> None:
from app.services import index_service
scheduled = []
monkeypatch.setattr(index_service, 'schedule_workspace_rebuild', lambda: scheduled.append(True))
vault = get_settings().vault_path
vault.mkdir(parents=True, exist_ok=True)
external = vault / 'external.md'
external.write_text('# External\n', encoding='utf-8')
tree = asyncio.run(get_workspace_tree())
assert tree[0].note_id is not None
external.rename(vault / 'renamed.md')
tree = asyncio.run(get_workspace_tree())
assert [item.name for item in tree] == ['renamed.md']
(vault / 'renamed.md').unlink()
assert asyncio.run(get_workspace_tree()) == []
assert len(scheduled) == 3
def test_save_rejects_external_content_change() -> None:
import hashlib
from app.contracts import NoteUpdateRequest
from app.routes import update_note
original = '# Original\n'
note = asyncio.run(create_note(NoteCreateRequest(title='Conflict', markdown=original)))
disk = get_settings().vault_path / note.file_path
disk.write_text('# External\n', encoding='utf-8')
with pytest.raises(ApiError) as error:
asyncio.run(update_note(note.note_id, NoteUpdateRequest(markdown='# Editor\n', expected_content_hash=hashlib.sha256(original.encode()).hexdigest())))
assert error.value.code == 'NOTE_CONTENT_CONFLICT'
assert disk.read_text(encoding='utf-8') == '# External\n'
@@ -5,6 +5,33 @@ from app.config import get_settings
from app.services import index_service, workspace_service
def test_external_new_note_does_not_rebuild_existing_notes(monkeypatch):
from app.services import note_service
async def scenario():
await note_service.create_note(title='Existing', markdown='Keep existing vectors', folder=None, tags=[])
calls = []
original = index_service.prepare_note_index
async def record(parsed, **kwargs):
calls.append(parsed.file_path)
return await original(parsed, **kwargs)
async def forbidden(*args, **kwargs):
raise AssertionError('full rebuild should not run')
monkeypatch.setattr(index_service, 'prepare_note_index', record)
monkeypatch.setattr(index_service, 'rebuild', forbidden)
path = get_settings().vault_path / 'external.md'
path.write_text('# External\n\nNew content', encoding='utf-8')
try:
await workspace_service.refresh_workspace_tree()
await index_service._background_task
assert calls == ['external.md']
assert not index_service.get_status().vector_refresh_required
await workspace_service.open_workspace(None)
assert calls == ['external.md']
finally:
await index_service.shutdown()
asyncio.run(scenario())
def test_open_returns_before_vectors_and_deduplicates_background(monkeypatch):
async def scenario():
started, release = asyncio.Event(), asyncio.Event()
+18
View File
@@ -41,6 +41,10 @@ pnpm dev
编辑器使用 Milkdown/Crepe 与 CodeMirror 6Markdown 展示使用 marked、DOMPurify 和 Shiki。Provider logo 位于 `src/assets/providers`,授权与来源说明随目录保存。
写作模式支持按标题折叠章节及全部展开/折叠;“设置 → 编辑器 → 标题样式”可按 H1–H6 设置字号、粗细与标题字体。设置本地保存,不改写 Markdown;详见 [标题折叠与样式开发说明](../docs/development/标题折叠与样式开发说明.md)。
工作区和静态预览支持 GitHub alerts / Obsidian callout 的类型、别名、标题、嵌套与折叠。桌面快捷键使用预留的 v1 编辑命令边界,尚未接入 Tauri 原生快捷键与元数据转换处理器;见 [警告框与桌面编辑命令开发说明](../docs/development/警告框与桌面编辑命令开发说明.md)。
语言设置会即时更新主导航、页面标题和各功能页面,并同步更新文档与编辑器的 `lang`。拼写检查使用浏览器或桌面 WebView 提供的本地词典,开关会即时作用于可视化 Markdown、源码编辑器以及普通文本输入;JSON、密码等结构化或敏感输入保持关闭。
## 数据边界
@@ -78,3 +82,17 @@ pnpm build
- 异步页面需要处理加载、空数据、后端错误、重复提交和迟到响应。
- 功能行为或契约变化时,同一提交同步更新测试和相关文档。
- 页面需求见[前端页面需求说明](../docs/contracts/前端页面需求说明-开发版.md),后端行为以运行时 `/openapi.json` 为准。
## 保存状态与图表联调(2026-09-06)
“已保存”表示正文与全文索引请求成功;向量可能仍在后台计算。状态栏定期刷新索引状态;保存期间继续输入会补存。Vault 入口具有超时、错误与重试提示。
Mermaid 大图打开时适配窗口,支持平滑滚轮缩放和鼠标位置补偿;行内中键启用滚轮控制,移动鼠标退出。标签段落样式与正文隔离,避免 foreignObject 内文字裁切。
开发和验证方法见 [后台索引与保存](../docs/development/工作区后台索引与保存开发说明.md)、[Mermaid 预览与缩放](../docs/development/Mermaid预览与缩放开发说明.md)。
## 构建体积检查
执行 `pnpm build` 后运行 `pnpm build:report`,查看入口静态 JS 依赖与大块清单。分组策略、统计口径及保留的大资源见 [前端构建分块优化开发说明](../docs/development/前端构建分块优化开发说明.md)。
Markdown 语法预设、主题适配和外部文件刷新规则见 [开发说明](../docs/development/Markdown语法预设与外部文件刷新.md)。
+2 -1
View File
@@ -8,7 +8,8 @@
"build": "vue-tsc -b && vite build",
"test": "vitest run",
"preview": "vite preview",
"type-check": "vue-tsc --noEmit"
"type-check": "vue-tsc --noEmit",
"build:report": "node scripts/build-size.mjs"
},
"dependencies": {
"@codemirror/commands": "6.11.0",
+19
View File
@@ -0,0 +1,19 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { gzipSync } from 'node:zlib'
const root = fileURLToPath(new URL('../dist/', import.meta.url))
const manifest = JSON.parse(readFileSync(resolve(root, '.vite/manifest.json'), 'utf8'))
const files = new Map(Object.values(manifest).filter(x => x.file.endsWith('.js')).map(x => [x.file, x]))
const sizes = file => { const bytes = readFileSync(resolve(root, file)); return { bytes: bytes.length, gzip: gzipSync(bytes).length } }
const closure = key => {
const seen = new Set()
function visit(k) { if (seen.has(k)) return; seen.add(k); for (const i of manifest[k]?.imports ?? []) visit(i) }
visit(key)
return [...new Set([...seen].map(k => manifest[k]?.file).filter(f => f?.endsWith('.js')))]
}
const entries = Object.entries(manifest).filter(([key, value]) => value.isEntry || /(?:WorkspaceView|VisualMarkdownEditor|VaultEntry|ChatView)\.vue$/.test(key)).map(([key]) => {
const files = closure(key)
return { entry: key, files, bytes: files.reduce((n, f) => n + sizes(f).bytes, 0), gzip: files.reduce((n, f) => n + sizes(f).gzip, 0) }
})
console.log(JSON.stringify({ entries, largest: [...files.keys()].map(file => ({ file, ...sizes(file) })).sort((a,b) => b.bytes-a.bytes).slice(0,15), chunks: files.size }, null, 2))
+29 -4
View File
@@ -1,6 +1,6 @@
theme_id: paper-moments
name: 纸间时光 · Paper Moments
version: 1.6.2
version: 1.9.0
author: NotesAgent
description: 奶油纸张、手帐虚线与粉蓝胶带,把每天的灵感好好收藏。
min_app_version: 0.2.0
@@ -9,6 +9,15 @@ css_entry: theme.css
license: MIT
---
[data-theme="paper-moments"] {
--color-markdown-selection: #ecd3c7;
--color-editor-scroll-background: #fff9e9;
--color-editor-scroll-text: #875343;
--color-callout-info: #406b7b;
--color-callout-success: #536f43;
--color-callout-warning: #875f25;
--color-callout-danger: #a34e42;
--color-callout-important: #805c7e;
--color-callout-quote: #6e6053;
color-scheme: light;
--color-background-primary: #faf7ee;
--color-background-secondary: #f3eee3;
@@ -149,9 +158,13 @@ license: MIT
padding: 44px 40px 60px 52px;
border: 1px solid #685949;
border-radius: 8px 16px 8px 8px;
outline: 1px dashed #c5b9a7;
outline-offset: -10px;
background: linear-gradient(90deg, transparent 32px, #e9cfc7 32px 34px, transparent 34px), #fffef8;
/* Small repeated tiles retain the stitching without a document-height dashed outline. */
background:
linear-gradient(#c5b9a7 50%, transparent 50%) 10px 0 / 1px 8px repeat-y,
linear-gradient(#c5b9a7 50%, transparent 50%) calc(100% - 10px) 0 / 1px 8px repeat-y,
linear-gradient(90deg, #c5b9a7 50%, transparent 50%) 0 10px / 8px 1px repeat-x,
linear-gradient(90deg, #c5b9a7 50%, transparent 50%) 0 calc(100% - 10px) / 8px 1px repeat-x,
linear-gradient(90deg, transparent 32px, #e9cfc7 32px 34px, transparent 34px), #fffef8;
box-shadow: 6px 6px 0 #d8e6e2, 12px 12px 0 #f0d8cf;
}
[data-theme="paper-moments"] .milkdown-host .ProseMirror::before {
@@ -322,3 +335,15 @@ license: MIT
/* Nested choices retain a quiet paper border without repeating tape/shadows. */
[data-theme="paper-moments"] .surface-nested { border: 1px dashed #c5b9a7; background: #fffdf5; border-radius: 6px; }
[data-theme="paper-moments"] .surface-nested.selected { border-color: var(--color-accent-primary); background: var(--color-accent-soft); }
/* Callout paper: no tape over titles, no repeated shadows in nested blocks. */
[data-theme="paper-moments"] .markdown-callout,
[data-theme="paper-moments"] .milkdown .ProseMirror blockquote.markdown-callout {
border-radius: 10px 3px 10px 3px;
outline: 1px dashed color-mix(in srgb, var(--callout-color) 30%, transparent);
outline-offset: -6px;
box-shadow: 3px 3px 0 color-mix(in srgb, var(--callout-color) 12%, transparent);
padding: 14px 18px;
}
[data-theme="paper-moments"] .markdown-callout .markdown-callout { box-shadow: none; }
[data-theme="paper-moments"] .markdown-callout > .callout-title { font-family: Georgia, 'Noto Serif SC', 'Songti SC', SimSun, serif; }
+5 -2
View File
@@ -12,6 +12,8 @@ import TitleBar from './TitleBar.vue'
import CommandPalette from './CommandPalette.vue'
import { getIndexStatus } from '@/services/indexService'
import { navigateToCitation } from '@/composables/useCitationNavigation'
import { useWorkspaceRefresh } from '@/composables/useWorkspaceRefresh'
useWorkspaceRefresh()
defineProps<{
showSecondarySidebar?: boolean
@@ -27,8 +29,9 @@ const router = useRouter()
let statusTimer: ReturnType<typeof setTimeout> | undefined
let disposed = false
async function pollIndex() {
try { settingsStore.indexStatus = await getIndexStatus() } catch { /* retain last status; retry */ }
if (!disposed) statusTimer = setTimeout(pollIndex, 5000)
try { const status = await getIndexStatus(); if (!disposed) settingsStore.indexStatus = status } catch { /* retain last status; retry */ }
const busy = settingsStore.indexStatus.status === 'indexing' || settingsStore.indexStatus.active_searches
if (!disposed) statusTimer = setTimeout(pollIndex, busy || route.name === 'settings' || route.name === 'search' ? 1000 : 5000)
}
onMounted(() => { void settingsStore.loadDiagnostics(); void pollIndex() })
onUnmounted(() => { disposed = true; clearTimeout(statusTimer) })
@@ -3,6 +3,10 @@ import DiagramInteractions from './DiagramInteractions.vue'
import { computed, ref, watch } from 'vue'
import { renderMarkdown } from '@/utils/markdown'
import { useThemeStore } from '@/stores/theme'
import { useHeadingAppearanceStore } from '@/stores/headingAppearance'
const headingAppearance = useHeadingAppearanceStore()
import { useMarkdownPreferencesStore } from '@/stores/markdownPreferences'
const markdownPreferences = useMarkdownPreferencesStore()
const props = defineProps<{ source: string }>()
const themeStore = useThemeStore()
@@ -12,15 +16,15 @@ let renderVersion = 0
const diagramTheme = computed<'light' | 'dark'>(() => (themeStore.isDark ? 'dark' : 'light'))
// Mermaid SVG CSS
watch([() => props.source, diagramTheme, () => themeStore.currentThemeId], async ([source, theme]) => {
watch([() => props.source, diagramTheme, () => themeStore.currentThemeId, () => JSON.stringify(markdownPreferences.normalized)], async ([source, theme]) => {
const version = ++renderVersion
const result = await renderMarkdown(source, { theme })
const result = await renderMarkdown(source, { theme, preferences: markdownPreferences.normalized })
if (version === renderVersion) html.value = result
}, { immediate: true, flush: 'post' })
</script>
<template>
<DiagramInteractions><div class="markdown-content" v-html="html" /></DiagramInteractions>
<DiagramInteractions :data-heading-style="headingAppearance.preferences.custom ? 'custom' : undefined" :style="headingAppearance.cssVariables"><div class="markdown-content" :data-code-wrap="markdownPreferences.normalized.wrapCode" :data-line-numbers="markdownPreferences.normalized.lineNumbers" :style="{ '--markdown-code-indent': markdownPreferences.normalized.indent }" v-html="html" /></DiagramInteractions>
</template>
<style>
@@ -32,12 +36,10 @@ watch([() => props.source, diagramTheme, () => themeStore.currentThemeId], async
.markdown-content li::marker { color: var(--color-markdown-marker); font-weight: 700; }
.markdown-content .shiki { overflow: auto; margin: .85em 0; padding: 16px; border: 1px solid var(--color-code-border); border-radius: 6px; background: var(--color-code-background) !important; color: var(--color-code-text); font-family: var(--font-ui-mono); font-size: .875em; line-height: 1.45; tab-size: 4; }
.markdown-content code { padding: .1em .3em; border-radius: var(--radius-sm); background: var(--color-background-tertiary); font-family: var(--font-ui-mono); }
.markdown-content .shiki code { display: block; min-width: max-content; padding: 0; background: transparent; font: inherit; }
.markdown-content :not(pre) > code { background: var(--color-code-background); color: var(--color-code-text); border: 1px solid var(--color-code-border); }
.markdown-content div.markdown-math { overflow-x: auto; padding-block: .5em; }
.markdown-content h4, .markdown-content h5, .markdown-content h6 { margin: 1em 0 .5em; font-weight: 600; }
.markdown-content input[type="checkbox"] { margin-right: .45em; accent-color: var(--color-accent-primary); }
.markdown-content .shiki .line { display: block; min-height: 1.45em; }
.markdown-content blockquote { padding-left: 1em; border-left: 3px solid var(--color-accent-primary); color: var(--color-text-secondary); }
.markdown-content table { width: 100%; margin: .65em 0; border-collapse: collapse; }
.markdown-content th, .markdown-content td { padding: .45em .65em; border: 1px solid var(--color-markdown-grid); text-align: left; }
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { computed, ref } from 'vue'
import { ArrowLeftBold, ArrowRightBold, Brush, ChatDotRound, CircleCheck, Connection, Cpu, FolderOpened, Lightning, Monitor, Search, Setting } from '@element-plus/icons-vue'
import { ArrowLeftBold, ArrowRightBold, Brush, ChatDotRound, CircleCheck, Connection, Cpu, Document, FolderOpened, Lightning, Monitor, Search, Setting } from '@element-plus/icons-vue'
import AppIcon from './AppIcon.vue'
import { t } from '@/i18n'
@@ -20,6 +20,7 @@ const navItems = computed(() => [
{ name: 'plugins', icon: Connection, label: 'Plugin' },
{ name: 'mcp-servers', icon: Monitor, label: 'MCP' },
{ name: 'themes', icon: Brush, label: t('主题', 'Themes') },
{ name: 'logs', icon: Document, label: t('日志', 'Logs') },
{ name: 'settings', icon: Setting, label: t('设置', 'Settings') },
])
+2 -6
View File
@@ -38,11 +38,7 @@ const saveStatusColor = computed(() => {
return map[editorStore.saveStatus] || 'var(--color-text-tertiary)'
})
const indexStatusText = computed(() => {
const s = settingsStore.indexStatus.status
if (s === 'idle' && settingsStore.indexStatus.vector_refresh_required) return t('全文可用 · 向量待重建', 'Full text ready · vectors need rebuilding')
return s === 'unknown' ? t('索引状态未获取', 'Index status unavailable') : s === 'idle' ? t('索引就绪', 'Index ready') : s === 'indexing' ? t('后台计算索引', 'Indexing in background') : t('索引错误', 'Index error')
})
const indexStatusText = computed(() => settingsStore.indexStatusLabel)
const aiCoreStatusText = computed(() => {
const map: Record<string, string> = {
@@ -78,7 +74,7 @@ const showEditorInfo = computed(() => route.name === 'workspace')
{{ saveStatusText }}
</span>
<span class="status-item" :title="indexStatusText">
<span class="status-dot" :style="{ background: settingsStore.indexStatus.status === 'error' ? 'var(--color-error)' : settingsStore.indexStatus.status === 'indexing' ? 'var(--color-warning)' : 'var(--color-success)' }" />
<span class="status-dot" :style="{ background: settingsStore.indexStatus.status === 'error' ? 'var(--color-error)' : settingsStore.indexStatus.status === 'unknown' ? 'var(--color-text-tertiary)' : settingsStore.indexStatus.status === 'indexing' || settingsStore.indexStatus.vector_refresh_required || settingsStore.indexStatus.active_searches ? 'var(--color-warning)' : 'var(--color-success)' }" />
{{ indexStatusText }}
</span>
<span class="status-item" :style="{ color: aiCoreColor }">
@@ -0,0 +1,40 @@
import { onMounted, onUnmounted } from 'vue'
import { useWorkspaceStore } from '@/stores/workspace'
import { useEditorStore } from '@/stores/editor'
/** Web fallback until the desktop host supplies filesystem events. No overlapping polls. */
export function useWorkspaceRefresh() {
const workspace = useWorkspaceStore()
const editor = useEditorStore()
let stopped = false
let running = false
let timer: ReturnType<typeof setTimeout> | undefined
async function refresh() {
if (running || stopped) return
clearTimeout(timer)
running = true
try {
if (document.visibilityState !== 'hidden' && workspace.hasVault) {
await workspace.refreshFileTree()
if (!stopped) {
if (editor.currentFilePath && editor.currentFilePath === workspace.activeFilePath && !workspace.activeFile) editor.setExternalChanged()
else await editor.checkExternalFile()
}
}
} catch { /* Keep the existing tree; the store exposes the error and retries. */ }
finally {
running = false
if (!stopped) timer = setTimeout(refresh, 2000)
}
}
onMounted(() => {
window.addEventListener('focus', refresh)
document.addEventListener('visibilitychange', refresh)
void refresh()
})
onUnmounted(() => {
stopped = true; clearTimeout(timer)
window.removeEventListener('focus', refresh)
document.removeEventListener('visibilitychange', refresh)
})
}
+10
View File
@@ -507,6 +507,11 @@ export interface ThemeConfig {
// ============ Index ============
export interface IndexStatus {
running_jobs?: number
active_searches?: number
completed_searches?: number
failed_searches?: number
cancelled_searches?: number
vector_refresh_required?: boolean
status: 'unknown' | 'idle' | 'indexing' | 'error'
pending_jobs: number
@@ -801,6 +806,11 @@ export interface ApiTask {
}
export interface ApiIndexStatus {
running_jobs?: number
active_searches?: number
completed_searches?: number
failed_searches?: number
cancelled_searches?: number
vector_refresh_required?: boolean
total_notes: number
total_blocks: number
+7 -2
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { computed, watch, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAgentStore } from '@/stores/agent'
import { localeTag, t } from '@/i18n'
@@ -8,6 +8,10 @@ import { runStatusLabel } from './labels'
const agentStore = useAgentStore()
const router = useRouter()
const error = ref('')
const page = ref(1)
const pages = computed(() => Math.max(1, Math.ceil(agentStore.sortedRuns.length / 50)))
const visibleRuns = computed(() => agentStore.sortedRuns.slice((page.value - 1) * 50, page.value * 50))
watch(pages, count => { page.value = Math.min(page.value, count) })
onMounted(async () => {
try { await agentStore.loadRuns() } catch (reason) { error.value = reason instanceof Error ? reason.message : t('运行记录加载失败', 'Failed to load runs') }
@@ -20,8 +24,9 @@ function selectRun(runId: string) { void router.push({ name: 'agent', params: {
<div class="sidebar-panel">
<button class="button-primary new-button" @click="router.push({ name: 'agent' })"> {{ t('新建运行', 'New run') }}</button>
<p v-if="error" class="subtle error-text">{{ error }}</p>
<div v-if="pages > 1" class="inline-actions"><button class="button-secondary" :disabled="page === 1" @click="page--">{{ t('上一页', 'Previous') }}</button><span>{{ page }} / {{ pages }}</span><button class="button-secondary" :disabled="page === pages" @click="page++">{{ t('下一页', 'Next') }}</button></div>
<div class="sidebar-list">
<button v-for="run in agentStore.sortedRuns" :key="run.run_id" class="sidebar-list-item run-item"
<button v-for="run in visibleRuns" :key="run.run_id" class="sidebar-list-item run-item"
:class="{ active: agentStore.activeRunId === run.run_id }" @click="selectRun(run.run_id)">
<span class="badge" :class="{ success: run.status === 'completed', error: run.status === 'failed', warning: run.status === 'waiting_permission' }">{{ runStatusLabel(run.status) }}</span>
<strong>{{ run.run_id.slice(0, 12) }}</strong><small>{{ run.started_at ? new Date(run.started_at).toLocaleString(localeTag()) : t('等待开始', 'Waiting to start') }}</small>
@@ -41,6 +41,17 @@ async function switchToTree(wrapper: ReturnType<typeof mountTree>) {
}
describe('TraceTimeline 树形视图', () => {
it('bounds rendered events while searching the complete history', async () => {
const events = Array.from({ length: 1000 }, (_, i) => event('TextDelta', { text: `message-${i}` }))
const wrapper = mountTree(events)
expect(wrapper.findAll('.event-card')).toHaveLength(200)
await wrapper.findAll('button').find(button => button.text() === '下一页')!.trigger('click')
expect(wrapper.findAll('.event-card')).toHaveLength(200)
await wrapper.get('input').setValue('message-999')
expect(wrapper.findAll('.event-card')).toHaveLength(1)
expect(wrapper.text()).toContain('message-999')
wrapper.unmount()
})
it('filters errors while retaining tree ancestors and final tool data', async () => {
const events = sampleEvents()
const result = events.find(item => item.event === 'ToolResult')!
+29 -7
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { localeTag, t } from '@/i18n'
import { computed, ref } from 'vue'
import { computed, ref, watch } from 'vue'
import type { TraceNode, AgentEvent } from '@/contracts'
import { buildTraceNodes, getToolCallsFromEvents, getTotalDuration } from '@/services/traceService'
import { eventLabel, localizeDetails } from './labels'
@@ -37,9 +37,12 @@ const filteredEvents = computed(() => {
})
const filteredTree = computed(() => {
if (!filtering.value) return traceNodes.value
const matches = (node: TraceNode) => filteredEvents.value.some(event => event.sequence === node.sequence
|| (node.type === 'tool_call' && node.data.tool_call_id != null && node.data.tool_call_id === event.data.tool_call_id)
|| (node.type === 'model_call' && node.data.model_call_id != null && node.data.model_call_id === event.data.model_call_id))
const sequences = new Set(filteredEvents.value.map(event => event.sequence))
const tools = new Set<unknown>(filteredEvents.value.map(event => event.data.tool_call_id).filter(id => id != null))
const models = new Set<unknown>(filteredEvents.value.map(event => event.data.model_call_id).filter(id => id != null))
const matches = (node: TraceNode) => sequences.has(node.sequence)
|| (node.type === 'tool_call' && tools.has(node.data.tool_call_id))
|| (node.type === 'model_call' && models.has(node.data.model_call_id))
const prune = (nodes: TraceNode[]): TraceNode[] => nodes.flatMap(node => {
const children = prune(node.children)
return matches(node) || children.length ? [{ ...node, children }] : []
@@ -50,6 +53,17 @@ function resetFilters() { query.value = ''; eventType.value = ''; toolName.value
const traceNodes = computed(() => buildTraceNodes(props.events))
const toolCalls = computed(() => getToolCallsFromEvents(props.events))
const toolSummary = computed(() => {
const groups = new Map<string, { key: string; name: string; status: string; count: number; duration_ms: number }>()
for (const call of toolCalls.value) {
const key = `${call.name}:${call.status}`
const group = groups.get(key) ?? { key, name: call.name, status: call.status, count: 0, duration_ms: 0 }
group.count++
group.duration_ms += call.duration_ms ?? 0
groups.set(key, group)
}
return [...groups.values()]
})
const totalDuration = computed(() => getTotalDuration(props.events))
const summaryStats = computed(() => {
@@ -153,6 +167,12 @@ function flatNodes(nodes: TraceNode[], depth = 0): Array<{ node: TraceNode; dept
}
const flatTrace = computed(() => flatNodes(filteredTree.value))
const page = ref(1)
const pageCount = computed(() => Math.max(1, Math.ceil((viewMode.value === 'tree' ? flatTrace.value.length : filteredEvents.value.length) / 200)))
const visibleEvents = computed(() => filteredEvents.value.slice((page.value - 1) * 200, page.value * 200))
const visibleTrace = computed(() => flatTrace.value.slice((page.value - 1) * 200, page.value * 200))
watch([query, eventType, toolName, errorsOnly, viewMode], () => { page.value = 1 })
watch(pageCount, count => { page.value = Math.min(page.value, count) })
</script>
<template>
@@ -199,11 +219,12 @@ const flatTrace = computed(() => flatNodes(filteredTree.value))
<button v-if="filtering" class="button-secondary" @click="resetFilters">清除筛选</button>
<span aria-live="polite">{{ filteredEvents.length }} / {{ events.length }} 事件</span>
</div>
<nav v-if="pageCount > 1" class="inline-actions"><button class="button-secondary" :disabled="page === 1" @click="page--">{{ t('上一页', 'Previous') }}</button><span>{{ page }} / {{ pageCount }}</span><button class="button-secondary" :disabled="page === pageCount" @click="page++">{{ t('下一页', 'Next') }}</button></nav>
<p v-if="filtering && !filteredEvents.length" class="subtle" role="status">没有匹配的事件</p>
<div v-if="viewMode === 'timeline'" class="timeline-view">
<div class="timeline">
<article
v-for="event in filteredEvents"
v-for="event in visibleEvents"
:key="event.sequence"
class="event-card"
:class="{ expanded: isDetailOpen(`event-${event.sequence}`) }"
@@ -255,7 +276,7 @@ const flatTrace = computed(() => flatNodes(filteredTree.value))
</div>
<div v-else class="tree-view">
<div v-for="item in flatTrace" :key="item.node.id" class="tree-node" :style="{ paddingLeft: `${item.depth * 24 + 8}px` }">
<div v-for="item in visibleTrace" :key="item.node.id" class="tree-node" :style="{ paddingLeft: `${item.depth * 24 + 8}px` }">
<div
class="node-row"
:class="[getNodeStatusClass(item.node), { 'detail-open': isDetailOpen(item.node.id) }]"
@@ -303,9 +324,10 @@ const flatTrace = computed(() => flatNodes(filteredTree.value))
<div v-if="!filtering && toolCalls.length > 0 && viewMode === 'timeline'" class="tool-calls-summary panel">
<h3 class="panel-title">工具调用统计</h3>
<div class="tool-call-list">
<div v-for="call in toolCalls" :key="call.tool_call_id" class="tool-call-item" :class="call.status">
<div v-for="call in toolSummary" :key="call.key" class="tool-call-item" :class="call.status">
<span class="tool-status-dot"></span>
<code class="tool-name">{{ call.name }}</code>
<span>{{ call.count }} {{ t('次', 'calls') }}</span>
<span v-if="call.duration_ms != null" class="tool-duration">
{{ formatDuration(call.duration_ms) }}
</span>
@@ -0,0 +1,41 @@
// @vitest-environment happy-dom
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { afterEach, expect, it, vi } from 'vitest'
import EditorHeader from './EditorHeader.vue'
import { useEditorStore } from '@/stores/editor'
import { useWorkspaceStore } from '@/stores/workspace'
import * as service from '@/services/workspaceService'
afterEach(() => vi.restoreAllMocks())
it('offers recovery for a missing file, supports cancel, and releases navigation after confirmation', async () => {
const pinia = createPinia(); setActivePinia(pinia)
vi.spyOn(service, 'getNoteId').mockResolvedValue('id')
const read = vi.spyOn(service, 'readFileContent').mockResolvedValue('original')
const editor = useEditorStore(), workspace = useWorkspaceStore()
await editor.loadFile('/removed.md'); workspace.openFile('/removed.md')
editor.updateContent('unsaved'); editor.setExternalChanged()
const wrapper = mount(EditorHeader, { global: { plugins: [pinia], stubs: { ActionDialog: { name: 'ActionDialog', template: '<div />', props: ['message'], emits: ['resolve'] } } } })
const close = () => wrapper.findAll('button').find(button => button.text() === '关闭当前笔记')!
try {
expect(wrapper.text()).toContain('原文件已删除或移动')
expect(wrapper.text()).not.toContain('重新加载外部版本')
expect(wrapper.text()).toContain('下载 Markdown 副本')
await close().trigger('click')
wrapper.findComponent({ name: 'ActionDialog' }).vm.$emit('resolve', null); await flushPromises()
expect(editor.content).toBe('unsaved')
await close().trigger('click')
wrapper.findComponent({ name: 'ActionDialog' }).vm.$emit('resolve', ''); await flushPromises()
expect(editor.currentFilePath).toBeNull(); expect(workspace.activeFilePath).toBeNull()
read.mockResolvedValue('another file')
await editor.loadFile('/other.md')
expect(editor.content).toBe('another file')
} finally { wrapper.unmount() }
})
it('does not discard text changed after confirmation was opened', async () => {
setActivePinia(createPinia())
const editor = useEditorStore()
editor.currentFilePath = '/removed.md'; editor.updateContent('before'); editor.setExternalChanged()
editor.updateContent('after')
expect(await editor.discardExternalChanges('/removed.md', 'before')).toBe(false)
expect(editor.content).toBe('after')
})
+37 -2
View File
@@ -1,11 +1,39 @@
<script setup lang="ts">
import { useEditorStore } from '@/stores/editor'
import { useWorkspaceStore } from '@/stores/workspace'
import { computed } from 'vue'
import { computed, ref } from 'vue'
import ActionDialog from '@/components/common/ActionDialog.vue'
import { useActionDialog } from '@/composables/useActionDialog'
import { t } from '@/i18n'
const editorStore = useEditorStore()
const workspaceStore = useWorkspaceStore()
const { actionDialog, resolveAction, askConfirm } = useActionDialog()
const reloadError = ref('')
const needsRecovery = computed(() => ['conflict', 'external_changed'].includes(editorStore.saveStatus))
const missingFile = computed(() => needsRecovery.value && editorStore.currentFilePath === workspaceStore.activeFilePath && !workspaceStore.activeFile && !workspaceStore.treeRefreshError)
function downloadCopy() {
const url = URL.createObjectURL(new Blob([editorStore.content], { type: 'text/markdown;charset=utf-8' }))
const link = document.createElement('a')
link.href = url
link.download = `${(editorStore.currentFilePath?.split('/').pop() ?? 'note.md').replace(/\.md$/i, '')}-recovered.md`
document.body.append(link); link.click(); link.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}
async function discard() {
const path = editorStore.currentFilePath, snapshot = editorStore.content
if (!path || !(await askConfirm(t('关闭将丢弃当前编辑内容。需要保留时,请先下载 Markdown 副本。确认关闭?', 'Closing discards the current editor content. Download a Markdown copy first if needed. Close?')))) return
if (!(await editorStore.discardExternalChanges(path, snapshot))) return
workspaceStore.closeFile(path)
workspaceStore.setActiveFile(null)
reloadError.value = ''
}
async function reload() {
const path = editorStore.currentFilePath, snapshot = editorStore.content
if (!(await askConfirm(t('重新加载会丢弃当前未保存内容。请先复制需要保留的文字。继续吗?', 'Reload discards unsaved edits. Copy any text you need to keep first. Continue?')))) return
if (path !== editorStore.currentFilePath || snapshot !== editorStore.content) return
try { await editorStore.reloadExternalFile(); reloadError.value = '' } catch (error) { reloadError.value = error instanceof Error ? error.message : '重新加载失败' }
}
const statusText = computed<Record<string, string>>(() => ({
idle: t('空闲', 'Idle'), dirty: t('未保存', 'Unsaved'), saving: t('保存中…', 'Saving…'), saved: t('已保存', 'Saved'), save_failed: t('保存失败', 'Save failed'),
@@ -15,14 +43,20 @@ const statusText = computed<Record<string, string>>(() => ({
<template>
<header class="editor-header">
<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />
<div class="file-identity"><strong>{{ workspaceStore.activeFile?.name ?? t('未命名笔记', 'Untitled note') }}</strong><small>{{ workspaceStore.activeFilePath }}</small></div>
<div class="editor-actions">
<span class="save-status" :class="editorStore.saveStatus">{{ statusText[editorStore.saveStatus] }}</span>
<button v-if="needsRecovery && !missingFile" class="button-secondary" @click="reload">{{ t('重新加载外部版本', 'Reload external version') }}</button>
<span v-if="missingFile" class="save-status conflict">{{ t('原文件已删除或移动', 'Original file deleted or moved') }}</span>
<button v-if="needsRecovery" class="button-secondary" @click="downloadCopy">{{ t('下载 Markdown 副本', 'Download Markdown copy') }}</button>
<button v-if="needsRecovery" class="button-secondary" @click="discard">{{ t('关闭当前笔记', 'Close current note') }}</button>
<span v-if="reloadError" class="save-status conflict" role="alert">{{ reloadError }}</span>
<div class="mode-switch" :aria-label="t('编辑模式', 'Editor mode')">
<button type="button" :class="{ active: editorStore.mode === 'wysiwyg' }" @click="editorStore.setMode('wysiwyg')">{{ t('写作', 'Writing') }}</button>
<button type="button" :class="{ active: editorStore.mode === 'source' }" @click="editorStore.setMode('source')">{{ t('源码', 'Source') }}</button>
</div>
<button type="button" class="save-button" :disabled="editorStore.saveStatus === 'saving'" @click="editorStore.save">{{ t('保存', 'Save') }}</button>
<button type="button" class="save-button" :disabled="['saving','conflict','external_changed'].includes(editorStore.saveStatus)" @click="editorStore.save">{{ t('保存', 'Save') }}</button>
</div>
</header>
</template>
@@ -40,6 +74,7 @@ const statusText = computed<Record<string, string>>(() => ({
.file-identity { display: grid; min-width: 0; }
.file-identity strong, .file-identity small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-identity small { color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
.editor-actions { flex-wrap: wrap; justify-content: flex-end; }
.editor-actions, .mode-switch { display: flex; align-items: center; gap: var(--space-sm); }
.save-status { color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
.save-status.dirty, .save-status.external_changed { color: var(--color-warning); }
+7 -1
View File
@@ -3,12 +3,14 @@ import { defineAsyncComponent, ref, watch } from 'vue'
import { useEditorStore } from '@/stores/editor'
import { useSettingsStore } from '@/stores/settings'
import { useThemeStore } from '@/stores/theme'
import EditorScrollButtons from './EditorScrollButtons.vue'
const VisualMarkdownEditor = defineAsyncComponent(() => import('./VisualMarkdownEditor.vue'))
const editorStore = useEditorStore()
const settingsStore = useSettingsStore()
const themeStore = useThemeStore()
const sourceEditor = ref<HTMLTextAreaElement | null>(null)
const container = ref<HTMLElement | null>(null)
watch(() => editorStore.headingRequest, request => {
const input = sourceEditor.value
if (!request || !input || request.path !== editorStore.currentFilePath) return
@@ -24,13 +26,17 @@ function updateContent(event: Event) {
</script>
<template>
<VisualMarkdownEditor v-if="editorStore.mode === 'wysiwyg'" :key="`${editorStore.currentFilePath ?? 'empty'}:${themeStore.resolvedCodeBlockTheme}:${settingsStore.language}`"
<div ref="container" class="editor-scroll-pane">
<VisualMarkdownEditor v-if="editorStore.mode === 'wysiwyg'" :key="`${editorStore.currentFilePath ?? 'empty'}:${editorStore.contentRevision}:${themeStore.resolvedCodeBlockTheme}:${settingsStore.language}`"
:initial-content="editorStore.content" />
<textarea v-else ref="sourceEditor" class="editor-pane source" :value="editorStore.content" :spellcheck="settingsStore.spellCheck"
:lang="settingsStore.language" :aria-label="settingsStore.language === 'en' ? 'Markdown source editor' : 'Markdown 源码编辑器'" @input="updateContent" />
<EditorScrollButtons :container="container" :content="editorStore.content" />
</div>
</template>
<style scoped>
.editor-scroll-pane { position: relative; display: flex; flex-direction: column; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
.editor-pane {
box-sizing: border-box;
flex: 1;
@@ -0,0 +1,47 @@
// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import EditorScrollButtons from './EditorScrollButtons.vue'
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); document.body.innerHTML = '' })
it('shows only useful directions, scrolls the editor, and hides empty or short documents', async () => {
vi.useFakeTimers()
vi.stubGlobal('matchMedia', () => ({ matches: false }))
const container = document.createElement('div')
const viewport = document.createElement('textarea')
viewport.className = 'source'
container.append(viewport)
document.body.append(container)
Object.defineProperty(viewport, 'scrollHeight', { configurable: true, value: 1000 })
Object.defineProperty(viewport, 'clientHeight', { configurable: true, value: 200 })
const scroll = vi.fn()
viewport.scrollTo = scroll
const wrapper = mount(EditorScrollButtons, { props: { container, content: 'A long note' } })
const update = async (top: number) => {
viewport.scrollTop = top
viewport.dispatchEvent(new Event('scroll'))
await vi.advanceTimersByTimeAsync(40)
}
try {
await update(0)
expect(wrapper.findAll('button')).toHaveLength(1)
expect(wrapper.find('button').attributes('aria-label')).toBe('滑动到底部')
await wrapper.find('button').trigger('click')
expect(scroll).toHaveBeenLastCalledWith({ top: 1000, behavior: 'smooth' })
await update(400)
expect(wrapper.findAll('button')).toHaveLength(2)
await update(800)
expect(wrapper.findAll('button')).toHaveLength(1)
expect(wrapper.find('button').attributes('aria-label')).toBe('滑动到顶部')
await wrapper.find('button').trigger('click')
expect(scroll).toHaveBeenLastCalledWith({ top: 0, behavior: 'smooth' })
await wrapper.setProps({ content: ' \n' })
await update(400)
expect(wrapper.findAll('button')).toHaveLength(0)
Object.defineProperty(viewport, 'scrollHeight', { value: 200 })
await wrapper.setProps({ content: 'Short note' })
await update(0)
expect(wrapper.findAll('button')).toHaveLength(0)
} finally { wrapper.unmount() }
})
@@ -0,0 +1,62 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { Top, Bottom } from '@element-plus/icons-vue'
import AppIcon from '@/components/common/AppIcon.vue'
import { t } from '@/i18n'
const props = defineProps<{ container: HTMLElement | null; content: string }>()
const hasContent = computed(() => !!props.content.trim())
const canUp = ref(false), canDown = ref(false)
let viewport: HTMLElement | null = null
let frame = 0
let mutation: MutationObserver | undefined
let resize: ResizeObserver | undefined
function update() {
frame = 0
const next = props.container?.querySelector<HTMLElement>('.milkdown-host, textarea.source') ?? null
if (next !== viewport) {
viewport?.removeEventListener('scroll', schedule)
resize?.disconnect()
viewport = next
viewport?.addEventListener('scroll', schedule, { passive: true })
}
if (viewport) {
resize?.observe(viewport)
for (const child of viewport.children) resize?.observe(child)
const document = viewport.querySelector('.ProseMirror')
if (document) resize?.observe(document)
}
const max = viewport ? viewport.scrollHeight - viewport.clientHeight : 0
const visible = hasContent.value && max > 2
canUp.value = visible && viewport!.scrollTop > 2
canDown.value = visible && viewport!.scrollTop < max - 2
}
function schedule() { if (!frame) frame = requestAnimationFrame(update) }
function scroll(to: 'top' | 'bottom') {
viewport?.scrollTo({ top: to === 'top' ? 0 : viewport.scrollHeight,
behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' })
}
watch(() => props.container, container => {
mutation?.disconnect()
resize?.disconnect()
mutation = new MutationObserver(schedule)
resize = new ResizeObserver(schedule)
if (container) mutation.observe(container, { childList: true, subtree: true, characterData: true, attributes: true })
schedule()
}, { immediate: true, flush: 'post' })
watch(() => props.content, schedule)
onBeforeUnmount(() => {
cancelAnimationFrame(frame)
mutation?.disconnect()
resize?.disconnect()
viewport?.removeEventListener('scroll', schedule)
})
</script>
<template>
<div v-if="canUp || canDown" class="editor-scroll-buttons" :aria-label="t('文档滚动', 'Document scrolling')">
<button v-if="canUp" type="button" class="button-secondary" :title="t('滑动到顶部', 'Scroll to top')" :aria-label="t('滑动到顶部', 'Scroll to top')" @click="scroll('top')"><AppIcon :icon="Top" :size="20" /></button>
<button v-if="canDown" type="button" class="button-secondary" :title="t('滑动到底部', 'Scroll to bottom')" :aria-label="t('滑动到底部', 'Scroll to bottom')" @click="scroll('bottom')"><AppIcon :icon="Bottom" :size="20" /></button>
</div>
</template>
@@ -0,0 +1,20 @@
// @vitest-environment happy-dom
import { expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia } from 'pinia'
import HeadingStyleSettings from './HeadingStyleSettings.vue'
it('previews individual heading settings and restores theme inheritance', async () => {
localStorage.clear()
const wrapper = mount(HeadingStyleSettings, { global: { plugins: [createPinia()] } })
try {
expect(wrapper.get('input[aria-label="H1 字号"]').attributes('disabled')).toBeDefined()
await wrapper.get('input[type="checkbox"]').setValue(true)
await wrapper.get('input[aria-label="H1 字号"]').setValue(42)
await wrapper.get('select[aria-label="H1 粗细"]').setValue('400')
expect(wrapper.get('.heading-style-preview').attributes('style')).toContain('--heading-1-size: 42px')
expect(wrapper.get('.heading-style-preview').attributes('style')).toContain('--heading-1-weight: 400')
await wrapper.get('button').trigger('click')
expect(wrapper.get('.heading-style-preview').attributes('data-heading-style')).toBeUndefined()
expect(wrapper.get('.heading-style-preview').attributes('style') ?? '').not.toContain('--heading-1-size')
} finally { wrapper.unmount() }
})
@@ -0,0 +1,37 @@
<script setup lang="ts">
import { useHeadingAppearanceStore } from '@/stores/headingAppearance'
import { t } from '@/i18n'
const appearance = useHeadingAppearanceStore()
</script>
<template>
<details class="ui-disclosure heading-style-settings">
<summary>{{ t('标题样式', 'Heading styles') }}</summary>
<div class="heading-settings-body">
<label><input v-model="appearance.preferences.custom" type="checkbox" /> {{ t('自定义标题样式', 'Customize heading styles') }}</label>
<p class="subtle">{{ t('关闭时跟随主题。设置作用于正文 H1–H6,不改写 Markdown,也不改变笔记属性标题。', 'Disable to follow the theme. Applies to document H1H6 without rewriting Markdown or the metadata title.') }}</p>
<label>{{ t('标题字体', 'Heading font') }}
<select v-model="appearance.preferences.family" class="select" :disabled="!appearance.preferences.custom">
<option value="inherit">{{ t('跟随正文', 'Follow body') }}</option><option value="serif">{{ t('衬线字体', 'Serif') }}</option><option value="sans-serif">{{ t('无衬线字体', 'Sans serif') }}</option><option value="monospace">{{ t('等宽字体', 'Monospace') }}</option>
</select>
</label>
<div v-for="(level, index) in appearance.preferences.levels" :key="index" class="heading-setting-row">
<strong>H{{ index + 1 }}</strong>
<label>{{ t('字号 px', 'Size px') }}<input v-model.number="level.size" class="input" type="number" min="12" max="72" :disabled="!appearance.preferences.custom" :aria-label="`H${index + 1} ${t('字号', 'size')}`" /></label>
<label>{{ t('粗细', 'Weight') }}<select v-model.number="level.weight" class="select" :disabled="!appearance.preferences.custom" :aria-label="`H${index + 1} ${t('粗细', 'weight')}`"><option :value="400">{{ t('常规', 'Regular') }}</option><option :value="500">Medium</option><option :value="600">Semibold</option><option :value="700">{{ t('加粗', 'Bold') }}</option><option :value="800">Extra bold</option></select></label>
</div>
<button class="button-secondary" type="button" @click="appearance.reset">{{ t('恢复跟随主题', 'Restore theme defaults') }}</button>
<div class="heading-style-preview" :data-heading-style="appearance.preferences.custom ? 'custom' : undefined" :style="appearance.cssVariables">
<div class="markdown-content"><component :is="`h${index + 1}`" v-for="(_, index) in appearance.preferences.levels" :key="index">H{{ index + 1 }} {{ t('标题预览', 'Heading preview') }}</component></div>
</div>
</div>
</details>
</template>
<style scoped>
.heading-settings-body { display: grid; gap: 14px; padding: 16px; }
.heading-setting-row { display: grid; grid-template-columns: 40px minmax(0, 1fr) minmax(0, 1fr); gap: 12px; align-items: end; }
.heading-setting-row label { display: grid; gap: 6px; min-width: 0; }
.heading-setting-row strong { align-self: center; }
.heading-style-preview { border: 1px solid var(--color-border-default); border-radius: var(--radius-md); padding: 16px; overflow-wrap: anywhere; background: var(--color-surface-primary); color: var(--color-text-primary); }
</style>
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useMarkdownPreferencesStore, markdownPresets } from '@/stores/markdownPreferences'
import { t } from '@/i18n'
const store = useMarkdownPreferencesStore()
const name = ref('')
const error = ref('')
function save() { error.value = store.savePreset(name.value) ? '' : t('请输入名称,最多保存 20 个预设。', 'Enter a name; up to 20 presets.'); if (!error.value) name.value = '' }
</script>
<template>
<section class="markdown-preferences surface-nested">
<h3>{{ t('Markdown 语法与编辑预设', 'Markdown syntax and editing presets') }}</h3>
<p class="subtle">{{ t('语法和代码设置在下次打开写作编辑器时应用;不批量改写已有笔记。静态预览即时更新。', 'Syntax and code settings apply when the visual editor next opens; existing notes are not rewritten in bulk. Static previews update immediately.') }}</p>
<div class="inline-actions"><button class="button-secondary" @click="store.apply(markdownPresets.extended)">{{ t('扩展 Markdown', 'Extended Markdown') }}</button><button class="button-secondary" @click="store.apply(markdownPresets.github)">GitHub</button><button class="button-secondary" @click="store.apply(markdownPresets.plain)">{{ t('基础 Markdown', 'Basic Markdown') }}</button></div>
<div class="form-grid">
<label>{{ t('标题语法', 'Heading syntax') }}<select v-model="store.preferences.heading" class="select"><option value="atx">ATX (#)</option><option value="setext">Setext (=== / ---)</option></select></label>
<label>{{ t('无序列表', 'Bullet list') }}<select v-model="store.preferences.bullet" class="select"><option>-</option><option>*</option><option>+</option></select></label>
<label>{{ t('有序列表', 'Ordered list') }}<select v-model="store.preferences.incrementList" class="select"><option :value="true">1. 2. 3.</option><option :value="false">1. 1. 1.</option></select></label>
<label>{{ t('代码围栏', 'Code fence') }}<select v-model="store.preferences.fence" class="select"><option value="`">```</option><option value="~">~~~</option></select></label>
</div>
<p class="subtle">{{ t('Setext 适用于 H1/H2H3–H6 仍使用 #。写作模式保存时会规范化整篇正文的标记;源码模式保留手写语法。', 'Setext applies to H1/H2; H3H6 use #. Visual-mode saves normalize document markers; source mode preserves handwritten syntax.') }}</p>
<div class="markdown-switches">
<label><input v-model="store.preferences.autoLinks" type="checkbox" />{{ t('自动识别裸链接', 'Recognize bare URLs') }}</label>
<label><input v-model="store.preferences.math" type="checkbox" />{{ t('数学公式', 'Math') }}</label>
<label><input v-model="store.preferences.callouts" type="checkbox" />{{ t('警告框与提示框', 'Alerts and callouts') }}</label>
<label><input v-model="store.preferences.diagrams" type="checkbox" />Mermaid</label>
<label><input v-model="store.preferences.lineNumbers" type="checkbox" />{{ t('代码行号', 'Code line numbers') }}</label>
<label><input v-model="store.preferences.wrapCode" type="checkbox" />{{ t('代码自动换行', 'Wrap code') }}</label>
</div>
<div class="form-grid">
<label>{{ t('代码缩进', 'Code indent') }}<select v-model.number="store.preferences.indent" class="select"><option :value="2">2</option><option :value="4">4</option><option :value="8">8</option></select></label>
<label>{{ t('新建代码块默认语言', 'Default language for new code blocks') }}<input v-model="store.preferences.defaultLanguage" class="input" maxlength="40" placeholder="python" /></label>
</div>
<form class="inline-actions" @submit.prevent="save"><input v-model="name" class="input" maxlength="40" :aria-label="t('预设名称', 'Preset name')" :placeholder="t('我的预设名称', 'My preset name')" /><button class="button-primary">{{ t('保存为预设', 'Save preset') }}</button></form>
<p v-if="error" class="error-banner" role="alert">{{ error }}</p>
<div v-for="(preset, index) in store.customPresets" :key="preset.name" class="inline-actions"><strong>{{ preset.name }}</strong><button class="button-secondary" @click="store.apply(preset.preferences)">{{ t('应用', 'Apply') }}</button><button class="button-danger" @click="store.customPresets.splice(index, 1)">{{ t('删除', 'Delete') }}</button></div>
</section>
</template>
<style scoped>
.markdown-preferences { display: grid; gap: 16px; padding: 16px; margin-block: 16px; }
.markdown-preferences .form-grid > label { display: grid; gap: 6px; min-width: 0; }
.markdown-switches { display: grid; grid-template-columns: repeat(auto-fit,minmax(190px,1fr)); gap: 12px; }
.markdown-switches label { display: flex; align-items: center; gap: 8px; }
.inline-actions { flex-wrap: wrap; }
</style>
@@ -13,6 +13,10 @@ import { useThemeStore } from '@/stores/theme'
import { codeBlockConfig } from '@milkdown/kit/component/code-block'
import { EditorView as CodeMirror } from '@codemirror/view'
import { renderMarkdown } from '@/utils/markdown'
import { useEditorStore } from '@/stores/editor'
import { executeEditorCommand } from '@/services/editorCommandService'
import { headingFoldKey } from './headingFolding'
import { useMarkdownPreferencesStore } from '@/stores/markdownPreferences'
type EditorComponent = { getEditor: () => Editor | undefined }
@@ -51,6 +55,161 @@ afterEach(() => {
})
describe('VisualMarkdownEditor formatting toolbars', () => {
it('opens a rendered Markdown link on Ctrl click without changing its source', async () => {
const wrapper = mount(VisualMarkdownEditor, {
props: { initialContent: '[**文档**](https://example.com/docs)' }, attachTo: document.body,
})
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
const before = editor.action(getMarkdown())
const open = vi.spyOn(window, 'open').mockReturnValue(null)
try {
const link = wrapper.get('.ProseMirror a')
await link.trigger('click', { ctrlKey: true, button: 0 })
expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer')
expect(editor.action(getMarkdown())).toBe(before)
} finally { open.mockRestore() }
})
it('applies syntax and renderer preferences when opening the visual editor', async () => {
const preferences = useMarkdownPreferencesStore()
preferences.preferences.heading = 'setext'
preferences.preferences.bullet = '+'
preferences.preferences.fence = '~'
preferences.preferences.callouts = false
preferences.preferences.math = false
preferences.preferences.autoLinks = false
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: '# Heading\n\n- first\n- second\n\n> [!NOTE]\n> text\n\nhttps://example.com\n\n```text\ncode\n```' }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
const result = editor.action(getMarkdown())
expect(result).toContain('Heading\n===')
expect(result).toContain('+ first')
expect(result).toContain('~~~text')
expect(wrapper.find('.markdown-callout').exists()).toBe(false)
expect(wrapper.find('.ProseMirror a').exists()).toBe(false)
})
it('folds heading sections, retains nested state and opens hidden outline targets', async () => {
const source = '# A\n\nbody\n\n## B\n\nchild\n\n# C\n\nvisible'
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: source }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
await wrapper.get('.heading-fold-toggle[aria-label="折叠 H2 B"]').trigger('click')
await wrapper.get('.heading-fold-toggle[aria-label="折叠 H1 A"]').trigger('click')
expect(wrapper.findAll('.heading-fold-hidden').length).toBeGreaterThan(1)
await wrapper.get('.heading-fold-toggle[aria-label="展开 H1 A"]').trigger('click')
expect(wrapper.get('.heading-fold-toggle[aria-label="展开 H2 B"]').attributes('aria-expanded')).toBe('false')
editor.action(ctx => {
const view = ctx.get(editorViewCtx)
let position = 0
view.state.doc.descendants((node, pos) => { if (node.isText && node.text === 'child') position = pos })
view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, position)))
expect(headingFoldKey.getState(view.state)?.size).toBe(0)
})
expect(wrapper.find('.heading-fold-hidden').exists()).toBe(false)
expect(editor.action(getMarkdown()).trim()).toBe(source)
await wrapper.get('button[aria-label="折叠所有章节"]').trigger('click')
expect(wrapper.findAll('.section-actions button')).toHaveLength(1)
expect(wrapper.get('.section-actions button').text()).toBe('全部展开')
await wrapper.get('.heading-fold-toggle[aria-label="展开 H1 C"]').trigger('click')
expect(wrapper.get('.section-actions button').text()).toBe('全部折叠')
await wrapper.get('button[aria-label="折叠所有章节"]').trigger('click')
await wrapper.get('button[aria-label="展开所有章节"]').trigger('click')
expect(wrapper.get('.section-actions button').text()).toBe('全部折叠')
expect(wrapper.find('.heading-fold-hidden').exists()).toBe(false)
})
it('reuses heading decorations for cursor-only moves and invalidates them for folds and edits', async () => {
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: '# A\n\nfirst paragraph\n\nsecond paragraph' }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
editor.action(ctx => {
const view = ctx.get(editorViewCtx), plugin = headingFoldKey.get(view.state)!
const decorations = () => plugin.props.decorations!.call(plugin, view.state)
const initial = decorations()
view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, 6)))
expect(decorations()).toBe(initial)
view.dispatch(view.state.tr.insertText('新增'))
expect(decorations()).not.toBe(initial)
})
await wrapper.get('.section-actions button').trigger('click')
expect(wrapper.find('.heading-fold-hidden').exists()).toBe(true)
await wrapper.get('.section-actions button').trigger('click')
expect(wrapper.find('.heading-fold-hidden').exists()).toBe(false)
})
it('returns to the top after collapsing many sibling chapters from the document end', async () => {
const source = Array.from({ length: 100 }, (_, i) => `# Chapter ${i}\n\nBody ${i}`).join('\n\n')
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: source }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
editor.action(ctx => {
const view = ctx.get(editorViewCtx)
view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(view.state.doc.content.size - 1))))
})
const viewport = wrapper.get('.milkdown-host').element as HTMLElement
viewport.scrollTop = 5000
await wrapper.get('.section-actions button').trigger('click')
expect(viewport.scrollTop).toBe(0)
editor.action(ctx => expect(ctx.get(editorViewCtx).state.selection.from).toBe(1))
expect(editor.action(getMarkdown()).trim()).toBe(source)
})
it('offers expand all when individually collapsed parents hide expanded children', async () => {
const source = '# A\n\nbody\n\n## B\n\nchild\n\n# C\n\nbody'
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: source }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
await wrapper.get('.heading-fold-toggle[aria-label="折叠 H1 A"]').trigger('click')
expect(wrapper.get('.section-actions button').text()).toBe('全部折叠')
await wrapper.get('.heading-fold-toggle[aria-label="折叠 H1 C"]').trigger('click')
expect(wrapper.get('.section-actions button').text()).toBe('全部展开')
expect(wrapper.get('.heading-fold-toggle[aria-label="折叠 H2 B"]').attributes('aria-expanded')).toBe('true')
await wrapper.get('.heading-fold-toggle[aria-label="展开 H1 A"]').trigger('click')
expect(wrapper.get('.section-actions button').text()).toBe('全部折叠')
expect(wrapper.get('.heading-fold-toggle[aria-label="折叠 H2 B"]').attributes('aria-expanded')).toBe('true')
await wrapper.get('.heading-fold-toggle[aria-label="折叠 H1 A"]').trigger('click')
await wrapper.get('.section-actions button').trigger('click')
expect(wrapper.find('.heading-fold-hidden').exists()).toBe(false)
expect(wrapper.get('.section-actions button').text()).toBe('全部折叠')
expect(editor.action(getMarkdown()).trim()).toBe(source)
})
it('renders and folds callouts without losing portable Markdown on serialization', async () => {
const source = '> [!WARNING]- 注意\n>\n> **正文**\n>\n> > [!TIP] 内层\n> > 内容'
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: source }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
expect(wrapper.findAll('.markdown-callout')).toHaveLength(2)
expect(wrapper.get('.markdown-callout').attributes('data-collapsed')).toBe('true')
await wrapper.get('.callout-title').trigger('click')
expect(wrapper.get('.markdown-callout').attributes('data-collapsed')).toBe('false')
const markdown = editor.action(getMarkdown())
expect(markdown.trim()).toBe(source)
})
it('dispatches native-ready commands through editor transactions and rejects invalid parameters', async () => {
useEditorStore().currentFilePath = 'test.md'
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: 'text' }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
expect(await executeEditorCommand('editor.heading', 8)).toEqual({ ok: false, reason: 'invalid-params' })
expect(await executeEditorCommand('editor.heading', 2)).toEqual({ ok: true })
expect(editor.action(getMarkdown())).toContain('## text')
expect(await executeEditorCommand('editor.callout', { type: 'tip', body: '**test**' })).toEqual({ ok: true })
expect(wrapper.find('.markdown-callout').exists()).toBe(true)
useEditorStore().saveStatus = 'conflict'
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: false, reason: 'unavailable' })
})
it('keeps code examples as ordinary quotes and renders newly typed markers', async () => {
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: '> `[!NOTE]`\n\n> text' }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
expect(wrapper.find('.markdown-callout').exists()).toBe(false)
editor.action(ctx => {
const view = ctx.get(editorViewCtx)
let position = 0
view.state.doc.descendants((node, pos) => { if (node.isText && node.text === 'text') position = pos })
view.dispatch(view.state.tr.insertText('[!TIP]', position, position + 4))
})
expect(wrapper.find('.markdown-callout').exists()).toBe(true)
expect(editor.action(getMarkdown())).toContain('[!TIP]')
})
it('renders the supported format matrix and preserves inline code', async () => {
const source = ['# H1','## H2','### H3','#### H4','##### H5','###### H6',
'正文 **粗体** *斜体* ~~删除~~ `s` 与 ``a`b``', '> 引用', '- 项目\n - 子项', '1. 第一\n2. 第二',
@@ -4,19 +4,22 @@ import { useActionDialog } from '@/composables/useActionDialog'
const { actionDialog, resolveAction, askPrompt } = useActionDialog()
import DiagramInteractions from '@/components/common/DiagramInteractions.vue'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Link } from '@element-plus/icons-vue'
import { Link, Fold, Expand } from '@element-plus/icons-vue'
import { Crepe } from '@milkdown/crepe'
import { codeBlockConfig } from '@milkdown/kit/component/code-block'
import { basicSetup } from 'codemirror'
import { keymap } from '@codemirror/view'
import { keymap, EditorView as CodeEditorView } from '@codemirror/view'
import { indentUnit } from '@codemirror/language'
import { EditorState as CodeEditorState } from '@codemirror/state'
import { indentWithTab } from '@codemirror/commands'
import { shikiEditorTheme, shikiLanguages, renderCodeLanguage } from './shikiCodeMirror'
import './language-icons.css'
import { installLanguagePickerPopover } from './languagePickerPopover'
import { installCodeBlockLabels } from './codeBlockLabels'
import { installLinkNavigation } from './linkNavigation'
import { createMermaidPreview } from './mermaidPreview'
import { splitNoteMetadata, updateMetadataTags } from './noteMetadata'
import { getMarkdown } from '@milkdown/kit/utils'
import { getMarkdown, $remark, $prose } from '@milkdown/kit/utils'
import {
createCodeBlockCommand,
toggleEmphasisCommand,
@@ -28,8 +31,10 @@ import {
wrapInHeadingCommand,
wrapInOrderedListCommand,
} from '@milkdown/kit/preset/commonmark'
import { commandsCtx, editorViewCtx } from '@milkdown/kit/core'
import { TextSelection } from '@milkdown/kit/prose/state'
import { commandsCtx, editorViewCtx, parserCtx, remarkStringifyOptionsCtx } from '@milkdown/kit/core'
import { Slice } from '@milkdown/kit/prose/model'
import { registerEditorCommands, type CommandHandler, type EditorCommandId } from '@/services/editorCommandService'
import { TextSelection, Plugin } from '@milkdown/kit/prose/state'
import { callCommand } from '@milkdown/kit/utils'
import AppIcon from '@/components/common/AppIcon.vue'
import { useEditorStore } from '@/stores/editor'
@@ -37,11 +42,18 @@ import { useSettingsStore } from '@/stores/settings'
import { useThemeStore } from '@/stores/theme'
import { applyMarkdownFontSize, fontSizeMarkdownPlugin } from './fontSizeMarkdown'
import { inlineCodeInputPlugin } from './inlineCodeInput'
import { calloutPlugin, configureCalloutSerialization } from './calloutPlugin'
import { calloutTypes } from '@/utils/callouts'
import { headingFoldingPlugin, headingFoldTransaction, headingFoldKey, headingSections } from './headingFolding'
import { useHeadingAppearanceStore } from '@/stores/headingAppearance'
import { useMarkdownPreferencesStore } from '@/stores/markdownPreferences'
import { t } from '@/i18n'
import '@milkdown/crepe/theme/common/style.css'
import '@milkdown/crepe/theme/frame.css'
const props = defineProps<{ initialContent: string }>()
const headingAppearance = useHeadingAppearanceStore()
const markdownPreferences = { ...useMarkdownPreferencesStore().normalized }
const metadata = ref(splitNoteMetadata(props.initialContent))
const tagDraft = ref('')
function setTags(tags: string[]) {
@@ -63,10 +75,87 @@ const settingsStore = useSettingsStore()
const themeStore = useThemeStore()
const editorRoot = ref<HTMLElement | null>(null)
const loading = ref(true)
const allHeadingsFolded = ref(false)
const hasFoldableHeadings = ref(false)
const fontSizeInput = ref(16)
let crepe: Crepe | null = null
let disposeLanguagePicker: (() => void) | undefined
let disposeCodeLabels: (() => void) | undefined
let disposeLinkNavigation: (() => void) | undefined
let disposeCommands: (() => void) | undefined
let disposed = false
function insertMarkdown(source: string) {
crepe?.editor.action(ctx => {
const doc = ctx.get(parserCtx)(source)
if (!doc) throw new Error('Invalid Markdown')
const view = ctx.get(editorViewCtx)
view.dispatch(view.state.tr.replaceSelection(new Slice(doc.content, 0, 0)).scrollIntoView())
view.focus()
})
}
function insertCallout(event: Event) {
const select = event.target as HTMLSelectElement
if (select.value) insertMarkdown(`> [!${select.value.toUpperCase()}]\n> ${t('提示内容', 'Callout content')}`)
select.value = ''
}
function installCommands() {
const targetPath = editorStore.currentFilePath
const handlers: Partial<Record<EditorCommandId, CommandHandler>> = {}
for (const [id, action] of [['editor.heading.toggle-fold', 'toggle'], ['editor.heading.fold-all', 'all'], ['editor.heading.unfold-all', 'none']] as const) {
handlers[id] = () => { foldHeadings(action); return { ok: true } }
}
const toolbar: ToolbarCommand[] = ['bold', 'italic', 'ordered-list', 'bullet-list', 'inline-code', 'code-block', 'inline-math', 'math-block']
for (const command of toolbar) {
if (!markdownPreferences.math && command.includes('math')) continue
handlers[`editor.${command}`] = () => { runCommand(command); return { ok: true } }
}
handlers['editor.paragraph'] = () => { crepe!.editor.action(callCommand(turnIntoTextCommand.key)); return { ok: true } }
handlers['editor.heading'] = params => {
if (!Number.isInteger(params) || Number(params) < 1 || Number(params) > 6) return { ok: false, reason: 'invalid-params' }
crepe!.editor.action(callCommand(wrapInHeadingCommand.key, Number(params)))
return { ok: true }
}
handlers['editor.font-size'] = params => {
if (typeof params !== 'number' || !Number.isFinite(params) || params < 8 || params > 96) return { ok: false, reason: 'invalid-params' }
fontSizeInput.value = params
applyFontSizeValue()
return { ok: true }
}
handlers['editor.insert-markdown'] = params => {
if (typeof params !== 'string' || !params.trim() || params.length > 100000) return { ok: false, reason: 'invalid-params' }
insertMarkdown(params)
return { ok: true }
}
handlers['editor.callout'] = params => {
if (!markdownPreferences.callouts) return { ok: false, reason: 'unsupported' }
if (!params || typeof params !== 'object') return { ok: false, reason: 'invalid-params' }
const { type, title = '', body = '', fold = '' } = params as Record<string, unknown>
if (typeof type !== 'string' || !/^[\w-]{1,64}$/.test(type) || typeof title !== 'string' || /[\r\n]/.test(title)
|| typeof body !== 'string' || !['', '+', '-'].includes(String(fold)) || title.length + body.length > 100000) return { ok: false, reason: 'invalid-params' }
insertMarkdown(`> [!${type}]${fold} ${title}\n${body.split(/\r?\n/).map(line => `> ${line}`).join('\n')}`)
return { ok: true }
}
disposeCommands = registerEditorCommands({
available: () => !loading.value && !!crepe && editorStore.mode === 'wysiwyg' && editorStore.saveStatus !== 'conflict'
&& !!targetPath && targetPath === editorStore.currentFilePath && crepe.editor.action(ctx => ctx.get(editorViewCtx).editable),
handlers,
})
}
function foldHeadings(action: 'toggle' | 'all' | 'none') {
crepe?.editor.action(ctx => {
const view = ctx.get(editorViewCtx)
const tr = headingFoldTransaction(view.state, action)
if (tr) view.dispatch(tr)
if (action === 'all') {
const viewport = editorRoot.value?.closest<HTMLElement>('.milkdown-host')
if (viewport) viewport.scrollTop = 0
}
})
}
const diagramPreviews = new Map<string, { source: string; apply: (value: HTMLElement) => void }>()
function renderDiagram(source: string, apply: (value: HTMLElement) => void) {
for (const [id, entry] of diagramPreviews) {
@@ -114,7 +203,7 @@ function runCommand(command: ToolbarCommand) {
'ordered-list': callCommand(wrapInOrderedListCommand.key),
'bullet-list': callCommand(wrapInBulletListCommand.key),
'inline-code': callCommand(toggleInlineCodeCommand.key),
'code-block': callCommand(createCodeBlockCommand.key, ''),
'code-block': callCommand(createCodeBlockCommand.key, markdownPreferences.defaultLanguage),
'inline-math': callCommand('ToggleLatex'),
'math-block': callCommand(createCodeBlockCommand.key, 'LaTeX'),
}
@@ -181,7 +270,7 @@ onMounted(async () => {
crepe = new Crepe({
root: editorRoot.value,
defaultValue: metadata.value?.body ?? props.initialContent,
features: { [Crepe.Feature.TopBar]: false },
features: { [Crepe.Feature.TopBar]: false, [Crepe.Feature.Latex]: markdownPreferences.math },
featureConfigs: {
[Crepe.Feature.Placeholder]: { text: t('开始记录你的想法…', 'Start writing your thoughts…') },
[Crepe.Feature.CodeMirror]: {
@@ -245,12 +334,54 @@ onMounted(async () => {
languages: shikiLanguages(themeStore.resolvedCodeBlockTheme),
renderLanguage: renderCodeLanguage,
renderPreview: (language, content, applyPreview) => language.trim().toLowerCase() === 'mermaid'
? renderDiagram(content, applyPreview)
? markdownPreferences.diagrams ? renderDiagram(content, applyPreview) : null
: config.renderPreview(language, content, applyPreview),
extensions: [basicSetup, keymap.of([indentWithTab]), shikiEditorTheme(themeStore.resolvedCodeBlockTheme)],
extensions: [basicSetup, keymap.of([indentWithTab]), shikiEditorTheme(themeStore.resolvedCodeBlockTheme),
indentUnit.of(' '.repeat(markdownPreferences.indent)), CodeEditorState.tabSize.of(markdownPreferences.indent),
...(markdownPreferences.wrapCode ? [CodeEditorView.lineWrapping] : [])],
})))
crepe.editor.config(ctx => ctx.update(remarkStringifyOptionsCtx, options => ({
...options, setext: markdownPreferences.heading === 'setext', bullet: markdownPreferences.bullet,
incrementListMarker: markdownPreferences.incrementList, fence: markdownPreferences.fence,
})))
if (!markdownPreferences.autoLinks) crepe.editor.use($remark('disable-bare-autolinks', () => () => (tree, file) => {
type Ast = { type: string; value?: string; url?: string; children?: Ast[]; position?: { start: { offset?: number }; end: { offset?: number } } }
const source = String(file.value)
const walk = (node: Ast) => {
if (node.type === 'link' && node.position) {
const raw = source.slice(node.position.start.offset, node.position.end.offset)
if (/^(?:https?:\/\/|www\.)\S+$/.test(raw)) {
node.type = 'text'; node.value = raw; delete node.children; delete node.url
}
}
node.children?.forEach(walk)
}
walk(tree as Ast)
}))
crepe.editor.use(fontSizeMarkdownPlugin)
crepe.editor.use(inlineCodeInputPlugin)
if (markdownPreferences.callouts) crepe.editor.use(calloutPlugin)
crepe.editor.use(headingFoldingPlugin)
crepe.editor.use($prose(() => new Plugin({
view(view) {
const sync = (current: typeof view) => {
const sections = headingSections(current.state.doc)
const folded = headingFoldKey.getState(current.state)
hasFoldableHeadings.value = sections.length > 0
// Hidden descendants retain their own state but are not visible expanded sections.
let hiddenUntil = -1
allHeadingsFolded.value = sections.length > 0 && sections.every(section => {
if (section.from < hiddenUntil) return true
if (!folded?.has(section.from)) return false
hiddenUntil = section.end
return true
})
}
sync(view)
return { update: sync }
},
})))
if (markdownPreferences.callouts) crepe.editor.config(configureCalloutSerialization)
crepe.on((listener) => {
listener.markdownUpdated((_ctx, markdown, previousMarkdown) => {
// /
@@ -263,8 +394,10 @@ onMounted(async () => {
await crepe.create()
if (editorRoot.value) disposeLanguagePicker = installLanguagePickerPopover(editorRoot.value)
if (editorRoot.value) disposeCodeLabels = installCodeBlockLabels(editorRoot.value)
if (editorRoot.value) disposeLinkNavigation = installLinkNavigation(editorRoot.value)
applyProofingPreferences()
loading.value = false
if (!disposed) installCommands()
})
watch([() => settingsStore.spellCheck, () => settingsStore.language], applyProofingPreferences)
@@ -282,15 +415,24 @@ watch(() => editorStore.headingRequest, request => {
})
})
onBeforeUnmount(() => { diagramPreviews.clear(); disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
onBeforeUnmount(() => { disposed = true; disposeCommands?.(); diagramPreviews.clear(); disposeLinkNavigation?.(); disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
defineExpose({ getEditor: () => crepe?.editor })
</script>
<template>
<DiagramInteractions class="visual-editor">
<DiagramInteractions class="visual-editor" :class="{ 'hide-code-line-numbers': !markdownPreferences.lineNumbers }" :data-heading-style="headingAppearance.preferences.custom ? 'custom' : undefined" :style="headingAppearance.cssVariables">
<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />
<div class="markdown-toolbar" role="toolbar" :aria-label="t('Markdown 格式工具栏', 'Markdown formatting toolbar')">
<div class="section-actions">
<button type="button" :disabled="loading || !hasFoldableHeadings"
:title="allHeadingsFolded ? t('展开所有章节正文', 'Expand all section content') : t('折叠所有章节,保留标题', 'Collapse all sections, keeping headings visible')"
:aria-label="allHeadingsFolded ? t('展开所有章节', 'Unfold all sections') : t('折叠所有章节', 'Fold all sections')"
@click="foldHeadings(allHeadingsFolded ? 'none' : 'all')">
<AppIcon :icon="allHeadingsFolded ? Expand : Fold" :size="16" />
<span>{{ allHeadingsFolded ? t('全部展开', 'Expand all') : t('全部折叠', 'Collapse all') }}</span>
</button>
</div>
<label class="toolbar-select heading-select" :title="t('设置标题级别', 'Set heading level')">
<span class="format-glyph heading-glyph">H</span>
<select :aria-label="t('标题级别', 'Heading level')" @change="applyHeading">
@@ -321,9 +463,15 @@ defineExpose({ getEditor: () => crepe?.editor })
<span class="toolbar-divider" />
<button type="button" :title="t('行内代码', 'Inline code')" :aria-label="t('行内代码', 'Inline code')" @pointerdown.prevent="runCommand('inline-code')"><code class="code-glyph">&lt;/&gt;</code></button>
<button type="button" :title="t('代码块', 'Code block')" :aria-label="t('代码块', 'Code block')" @pointerdown.prevent="runCommand('code-block')"><span class="block-glyph">{ }</span></button>
<button type="button" :title="t('行内公式', 'Inline formula')" :aria-label="t('行内公式', 'Inline formula')" @pointerdown.prevent="runCommand('inline-math')"><span class="math-glyph">ƒx</span></button>
<button type="button" :title="t('公式块', 'Formula block')" :aria-label="t('公式块', 'Formula block')" @pointerdown.prevent="runCommand('math-block')"><span class="math-glyph"></span></button>
<button v-if="markdownPreferences.math" type="button" :title="t('行内公式', 'Inline formula')" :aria-label="t('行内公式', 'Inline formula')" @pointerdown.prevent="runCommand('inline-math')"><span class="math-glyph">ƒx</span></button>
<button v-if="markdownPreferences.math" type="button" :title="t('公式块', 'Formula block')" :aria-label="t('公式块', 'Formula block')" @pointerdown.prevent="runCommand('math-block')"><span class="math-glyph"></span></button>
<button type="button" :title="t('插入链接', 'Insert link')" :aria-label="t('插入链接', 'Insert link')" @pointerdown.prevent="applyLink"><AppIcon :icon="Link" :size="17" /></button>
<label class="toolbar-select">
<select v-if="markdownPreferences.callouts" :aria-label="t('插入警告框', 'Insert callout')" @change="insertCallout">
<option value="">{{ t('提示框', 'Callout') }}</option>
<option v-for="(_, type) in calloutTypes" :key="type" :value="type">{{ type }}</option>
</select>
</label>
</div>
<div v-if="loading" class="editor-loading">{{ t('正在加载编辑器', 'Loading editor') }}</div>
<div class="milkdown-host" :class="{ loading }">
@@ -343,10 +491,16 @@ defineExpose({ getEditor: () => crepe?.editor })
<style scoped>
.visual-editor { display: flex; flex: 1; min-height: 0; flex-direction: column; background: var(--color-background-primary); }
.hide-code-line-numbers :deep(.cm-lineNumbers) { display: none; }
.markdown-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 2px; min-height: 42px; padding: 5px var(--space-lg); border-bottom: 1px solid var(--color-border-subtle); background: var(--color-surface-primary); }
.markdown-toolbar button { display: inline-grid; place-items: center; min-width: 32px; min-height: 30px; padding: 4px 8px; border-radius: var(--radius-sm); color: var(--color-text-primary); }
.markdown-toolbar button:hover, .toolbar-select:hover { background: var(--color-background-hover); color: var(--color-text-primary); }
.markdown-toolbar button:focus-visible, .toolbar-select:focus-within { outline: 2px solid var(--color-border-focus); outline-offset: 1px; }
.section-actions { display: inline-flex; align-items: center; flex-shrink: 0; margin-inline-end: 8px; padding: 2px; border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-background-secondary); }
.markdown-toolbar .section-actions button { display: inline-flex; align-items: center; justify-content: center; gap: 5px; min-height: 28px; padding: 4px 8px; font: inherit; font-size: var(--font-size-xs); line-height: 1.25; white-space: nowrap; color: var(--color-text-secondary); }
.section-actions :deep(.app-icon) { transform: rotate(90deg); }
.markdown-toolbar .section-actions button:hover:not(:disabled) { background: var(--color-background-hover); color: var(--color-accent-primary); }
.markdown-toolbar .section-actions button:disabled { opacity: .45; cursor: default; }
.format-glyph { font-family: Georgia, 'Times New Roman', serif; font-size: 17px; line-height: 1; }
.heading-glyph { font-weight: 800; }
.font-size-glyph { font-size: 18px; }
@@ -0,0 +1,99 @@
import { $prose } from '@milkdown/kit/utils'
import { Plugin } from '@milkdown/kit/prose/state'
import { Decoration, DecorationSet } from '@milkdown/kit/prose/view'
import type { Node as ProseNode } from '@milkdown/kit/prose/model'
import { parseCallout } from '@/utils/callouts'
import '@/styles/callouts.css'
import { remarkStringifyOptionsCtx, type Editor } from '@milkdown/kit/core'
export const configureCalloutSerialization: Parameters<Editor['config']>[0] = ctx => {
ctx.update(remarkStringifyOptionsCtx, options => ({
...options,
handlers: { ...options.handlers, blockquote(node, _parent, state, info) {
const exit = state.enter('blockquote')
const tracker = state.createTracker(info)
tracker.move('> ')
tracker.shift(2)
const result = state.indentLines(state.containerFlow(node, tracker.current()), (line, _index, blank) => `>${blank ? '' : ' '}${line}`)
exit()
// Only remove escaping from a leading callout marker, never body literals.
return result.replace(/^(> )\\\[!([\w-]+)\\?\]/, '$1[!$2]')
} },
}))
}
const markerCache = new WeakMap<ProseNode, { from: number; to: number }[]>()
function calloutMarkers(doc: ProseNode) {
const cached = markerCache.get(doc)
if (cached) return cached
const markers: { from: number; to: number }[] = []
doc.descendants((node, position) => {
if (node.type.name !== 'blockquote' || node.firstChild?.type.name !== 'paragraph' || node.firstChild.firstChild?.marks.length) return
const callout = parseCallout(node.firstChild.textBetween(0, node.firstChild.content.size, '\n', '\n'))
if (callout) markers.push({ from: position + 2, to: position + 2 + callout.markerLength })
})
markerCache.set(doc, markers)
return markers
}
// Keep native blockquotes in the document: typing, undo and Markdown serialization
// remain Milkdown transactions; the view never rewrites a user's callout source.
export const calloutPlugin = $prose(() => new Plugin({
props: {
decorations(state) {
const decorations: Decoration[] = []
for (const { from, to } of calloutMarkers(state.doc)) {
const editing = state.selection.from <= to && state.selection.to >= from
decorations.push(Decoration.inline(from, to, { class: editing ? 'callout-marker-editing' : 'callout-marker' }))
}
return DecorationSet.create(state.doc, decorations)
},
nodeViews: {
blockquote(initialNode) {
const dom = document.createElement('blockquote')
const header = document.createElement('button')
header.type = 'button'
header.className = 'callout-title'
header.contentEditable = 'false'
const contentDOM = document.createElement('div')
contentDOM.className = 'callout-body'
dom.append(header, contentDOM)
let signature = ''
let foldable = false
const update = (node: typeof initialNode) => {
if (node.type.name !== 'blockquote') return false
const callout = node.firstChild?.type.name === 'paragraph' && !node.firstChild.firstChild?.marks.length
? parseCallout(node.firstChild.textBetween(0, node.firstChild.content.size, '\n', '\n')) : null
dom.className = callout ? 'markdown-callout' : ''
header.hidden = !callout
foldable = !!callout?.fold
header.disabled = !foldable
if (callout) {
dom.dataset.callout = callout.type
const next = `${callout.name}:${callout.fold}`
if (signature !== next) dom.dataset.collapsed = String(callout.fold === '-')
signature = next
header.textContent = `${foldable ? (dom.dataset.collapsed === 'true' ? '▸ ' : '▾ ') : ''}${callout.title}`
if (foldable) header.setAttribute('aria-expanded', String(dom.dataset.collapsed !== 'true'))
else header.removeAttribute('aria-expanded')
} else {
delete dom.dataset.callout
delete dom.dataset.collapsed
signature = ''
}
return true
}
let current = initialNode
header.onclick = () => {
if (!foldable) return
dom.dataset.collapsed = String(dom.dataset.collapsed !== 'true')
update(current)
}
update(initialNode)
return { dom, contentDOM, update(node) { current = node; return update(node) },
stopEvent: event => header.contains(event.target as Node),
ignoreMutation: mutation => mutation.type !== 'selection' && !contentDOM.contains(mutation.target) }
},
},
},
}))
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { expect, it } from 'vitest'
import { expect, it, vi } from 'vitest'
import { installCodeBlockLabels } from './codeBlockLabels'
it('keeps footer labels in sync when the language changes and stops after disposal', async () => {
@@ -16,3 +16,21 @@ it('keeps footer labels in sync when the language changes and stops after dispos
await new Promise(resolve => setTimeout(resolve, 0))
expect(block.dataset.languageLabel).toBe('TypeScript')
})
it('ignores code text mutations and discovers newly inserted code blocks', async () => {
const root = document.createElement('div')
root.innerHTML = '<div class="milkdown-code-block"><button class="language-button">Python</button><div class="cm-content">old</div></div>'
const dispose = installCodeBlockLabels(root)
const scan = vi.spyOn(root, 'querySelectorAll')
try {
root.querySelector('.cm-content')!.textContent = 'new code'
await new Promise(resolve => setTimeout(resolve, 0))
expect(scan).not.toHaveBeenCalled()
const block = document.createElement('div')
block.className = 'milkdown-code-block'
block.innerHTML = '<button class="language-button">Rust</button>'
root.append(block)
await new Promise(resolve => setTimeout(resolve, 0))
expect(block.dataset.languageLabel).toBe('Rust')
} finally { dispose(); scan.mockRestore() }
})
@@ -1,11 +1,38 @@
/** Mirror the live picker label for theme decorations without changing Markdown. */
/** Mirror changed language labels without rescanning every code block on each DOM mutation. */
export function installCodeBlockLabels(root: HTMLElement): () => void {
const sync = () => root.querySelectorAll<HTMLElement>('.milkdown-code-block').forEach(block => {
const sync = (block: HTMLElement) => {
const label = block.querySelector('.language-button')?.textContent?.trim() || 'Plain text'
if (block.dataset.languageLabel !== label) block.dataset.languageLabel = label
}
const discover = (node: Node, blocks: Set<HTMLElement>) => {
if (!(node instanceof HTMLElement)) return
if (node.matches('.milkdown-code-block')) blocks.add(node)
node.querySelectorAll<HTMLElement>('.milkdown-code-block').forEach(block => blocks.add(block))
}
const observer = new MutationObserver(records => {
const changed = new Set<HTMLElement>()
for (const record of records) {
const element = record.target instanceof Element ? record.target : record.target.parentElement
// CodeMirror viewport/text changes do not change the footer's language.
const label = element?.closest('.language-button')
const block = label?.closest<HTMLElement>('.milkdown-code-block')
if (block) changed.add(block)
if ([...record.removedNodes].some(node => node instanceof Element &&
(node.matches('.language-button') || node.querySelector('.language-button')))) {
const owner = element?.closest<HTMLElement>('.milkdown-code-block')
if (owner) changed.add(owner)
}
for (const node of record.addedNodes) {
discover(node, changed)
if (node instanceof Element && (node.matches('.language-button') || node.querySelector('.language-button'))) {
const owner = node.closest<HTMLElement>('.milkdown-code-block')
if (owner) changed.add(owner)
}
}
}
changed.forEach(block => { if (root.contains(block)) sync(block) })
})
const observer = new MutationObserver(sync)
root.querySelectorAll<HTMLElement>('.milkdown-code-block').forEach(sync)
observer.observe(root, { subtree: true, childList: true, characterData: true })
sync()
return () => observer.disconnect()
}
@@ -1,15 +1,20 @@
import { $prose } from '@milkdown/kit/utils'
import { Plugin, TextSelection } from '@milkdown/kit/prose/state'
import { Decoration, DecorationSet } from '@milkdown/kit/prose/view'
import type { Node } from '@milkdown/kit/prose/model'
import type { Editor } from '@milkdown/kit/core'
import { editorViewCtx } from '@milkdown/kit/core'
const decorationCache = new WeakMap<Node, DecorationSet>()
const openingTag = /^<span style="font-size:\s*(\d+(?:\.\d+)?)px">$/i
const closingTag = /^<\/span>$/i
export const fontSizeMarkdownPlugin = $prose(() => new Plugin({
props: {
decorations(state) {
const cached = decorationCache.get(state.doc)
if (cached) return cached
const decorations: Decoration[] = []
const stack: Array<{ from: number; size: string }> = []
@@ -36,7 +41,9 @@ export const fontSizeMarkdownPlugin = $prose(() => new Plugin({
}
})
return DecorationSet.create(state.doc, decorations)
const result = DecorationSet.create(state.doc, decorations)
decorationCache.set(state.doc, result)
return result
},
},
}))
@@ -0,0 +1,32 @@
// @vitest-environment happy-dom
import { expect, it } from 'vitest'
import { Schema } from '@milkdown/kit/prose/model'
import { EditorState, TextSelection } from '@milkdown/kit/prose/state'
import { headingSections, headingFoldTransaction } from './headingFolding'
const schema = new Schema({ nodes: {
doc: { content: 'block+' }, text: { group: 'inline' },
heading: { group: 'block', content: 'inline*', attrs: { level: { default: 1 } } },
paragraph: { group: 'block', content: 'inline*' },
blockquote: { group: 'block', content: 'block+' },
} })
const h = (level: number, text: string) => schema.nodes.heading!.create({ level }, schema.text(text))
const p = (text: string) => schema.nodes.paragraph!.create(null, schema.text(text))
it('ends sections at same-or-higher headings and confines nested quotes to their parent', () => {
const doc = schema.nodes.doc!.create(null, [h(1, 'A'), p('a'), h(2, 'B'), p('b'), h(1, 'C'), p('c'), schema.nodes.blockquote!.create(null, [h(2, 'D'), p('d')])])
const sections = headingSections(doc)
expect(sections.map(section => doc.nodeAt(section.from)?.textContent)).toEqual(['A', 'B', 'C', 'D'])
expect(sections[0]!.end).toBe(sections[2]!.from)
expect(sections[1]!.end).toBe(sections[2]!.from)
expect(sections[3]!.end).toBe(doc.content.size - 1)
})
it('moves the caret out of collapsed content without changing document content or history', () => {
const doc = schema.nodes.doc!.create(null, [h(1, 'A'), p('body'), h(1, 'B')])
const state = EditorState.create({ doc, selection: TextSelection.create(doc, 5) })
const tr = headingFoldTransaction(state, 'all')!
expect(tr.doc.eq(doc)).toBe(true)
expect(tr.docChanged).toBe(false)
expect(tr.selection.from).toBe(1)
expect(tr.getMeta('addToHistory')).toBe(false)
expect(headingSections(doc)).toHaveLength(1)
})
@@ -0,0 +1,136 @@
import { $prose } from '@milkdown/kit/utils'
import { Plugin, PluginKey, TextSelection, type EditorState } from '@milkdown/kit/prose/state'
import { Decoration, DecorationSet } from '@milkdown/kit/prose/view'
import type { Node } from '@milkdown/kit/prose/model'
import { t } from '@/i18n'
export const headingFoldKey = new PluginKey<Set<number>>('heading-folding')
type Section = { from: number; body: number; end: number; level: number }
const sectionCache = new WeakMap<Node, Section[]>()
const decorationCache = new WeakMap<Node, WeakMap<Set<number>, DecorationSet>>()
/** A section ends at the next sibling heading of the same or a higher rank. */
export function headingSections(doc: Node): Section[] {
const cached = sectionCache.get(doc)
if (cached) return cached
const sections: Section[] = []
function visit(parent: Node, start: number) {
const children: { node: Node; pos: number }[] = []
parent.forEach((node, offset) => children.push({ node, pos: start + offset }))
const following: { pos: number; level: number }[] = []
for (let i = children.length - 1; i >= 0; i--) {
const { node, pos } = children[i]!
if (node.type.name === 'heading') {
while (following.length && following[following.length - 1]!.level > node.attrs.level) following.pop()
const next = following[following.length - 1]
const body = pos + node.nodeSize
const end = next?.pos ?? start + parent.content.size
if (end > body) sections.push({ from: pos, body, end, level: Number(node.attrs.level) })
following.push({ pos, level: Number(node.attrs.level) })
}
if (!node.isTextblock && node.childCount) visit(node, pos + 1)
}
}
visit(doc, 0)
sections.sort((a, b) => a.from - b.from)
sectionCache.set(doc, sections)
return sections
}
export function headingFoldTransaction(state: EditorState, action: 'toggle' | 'all' | 'none', position?: number) {
const sections = headingSections(state.doc)
const folded = new Set(headingFoldKey.getState(state) ?? [])
if (action === 'none') folded.clear()
else if (action === 'all') sections.forEach(section => folded.add(section.from))
else {
const section = position === undefined
? sections.filter(item => item.from <= state.selection.from && item.end >= state.selection.from).pop()
: sections.find(item => item.from === position)
if (!section) return null
if (folded.has(section.from)) folded.delete(section.from)
else folded.add(section.from)
}
const tr = state.tr
const enclosing = sections.find(section => folded.has(section.from) && state.selection.to >= section.body && state.selection.from < section.end)
if (action === 'all' && sections.length) tr.setSelection(TextSelection.near(state.doc.resolve(sections[0]!.from + 1))).scrollIntoView()
else if (enclosing) tr.setSelection(TextSelection.near(state.doc.resolve(enclosing.from + 1)))
return tr.setMeta(headingFoldKey, folded).setMeta('addToHistory', false)
}
export const headingFoldingPlugin = $prose(() => new Plugin<Set<number>>({
key: headingFoldKey,
state: {
init: () => new Set(),
apply(tr, previous) {
const explicit = tr.getMeta(headingFoldKey) as Set<number> | undefined
if (explicit) return explicit
if (!previous.size) return previous
const sections = headingSections(tr.doc)
if (!tr.docChanged) {
if (!tr.selectionSet) return previous
const opened = sections.filter(section => previous.has(section.from) && tr.selection.to >= section.body && tr.selection.from < section.end)
if (!opened.length) return previous
const next = new Set(previous)
opened.forEach(section => next.delete(section.from))
return next
}
const positions = new Set(sections.map(section => section.from))
const mapped = new Set<number>()
for (const old of previous) {
const result = tr.mapping.mapResult(old, 1)
if (!result.deleted && positions.has(result.pos)) mapped.add(result.pos)
}
// Outline jumps, find and keyboard navigation must never leave a hidden caret.
if (tr.selectionSet || tr.docChanged) {
for (const section of sections) if (tr.selection.to >= section.body && tr.selection.from < section.end) mapped.delete(section.from)
}
return mapped
},
},
props: {
decorations(state) {
const folded = headingFoldKey.getState(state) ?? new Set<number>()
const cached = decorationCache.get(state.doc)?.get(folded)
if (cached) return cached
const sections = headingSections(state.doc)
const decorations: Decoration[] = []
for (const section of sections) {
const collapsed = folded.has(section.from)
decorations.push(Decoration.widget(section.from + 1, view => {
const button = document.createElement('button')
button.type = 'button'; button.className = 'heading-fold-toggle'; button.contentEditable = 'false'
button.setAttribute('aria-expanded', String(!collapsed))
button.setAttribute('aria-label', `${collapsed ? t('展开', 'Expand') : t('折叠', 'Collapse')} H${section.level} ${state.doc.nodeAt(section.from)?.textContent ?? ''}`)
button.onmousedown = event => event.preventDefault()
button.onclick = event => {
event.preventDefault()
const tr = headingFoldTransaction(view.state, 'toggle', section.from)
if (tr) view.dispatch(tr)
}
return button
}, { key: `${section.from}:${collapsed}:${state.doc.nodeAt(section.from)?.textContent}`, side: -1, stopEvent: () => true }))
}
const hidden: { body: number; end: number }[] = []
for (const section of sections) {
if (!folded.has(section.from)) continue
const previous = hidden[hidden.length - 1]
if (previous && section.body <= previous.end) previous.end = Math.max(previous.end, section.end)
else hidden.push({ body: section.body, end: section.end })
}
let rangeIndex = 0
if (hidden.length) state.doc.descendants((node, pos) => {
if (!node.isBlock) return
while (hidden[rangeIndex] && pos >= hidden[rangeIndex]!.end) rangeIndex++
const range = hidden[rangeIndex]
if (range && pos >= range.body && pos + node.nodeSize <= range.end) {
decorations.push(Decoration.node(pos, pos + node.nodeSize, { class: 'heading-fold-hidden' }))
return false
}
})
const result = DecorationSet.create(state.doc, decorations)
let byState = decorationCache.get(state.doc)
if (!byState) { byState = new WeakMap(); decorationCache.set(state.doc, byState) }
byState.set(folded, result)
return result
},
},
}))
@@ -0,0 +1,42 @@
// @vitest-environment happy-dom
import { expect, it, vi } from 'vitest'
import { installLanguagePickerPopover } from './languagePickerPopover'
it('measures only open menus on ancestor scroll and cleans up scheduled work', async () => {
const root = document.createElement('div')
root.innerHTML = '<div><button class="language-button" data-expanded="false">JS</button><div class="language-picker"><input class="search-input"></div></div>'
document.body.append(root)
const menu = root.querySelector<HTMLElement>('.language-picker')!
const trigger = root.querySelector<HTMLElement>('button')!
let open = false
menu.showPopover = vi.fn(() => { open = true })
menu.hidePopover = vi.fn(() => { open = false })
const matches = menu.matches.bind(menu)
vi.spyOn(menu, 'matches').mockImplementation(selector => selector === ':popover-open' ? open : matches(selector))
const measure = vi.spyOn(trigger, 'getBoundingClientRect')
let callback: FrameRequestCallback | undefined
const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(fn => { callback = fn; return 42 })
const cancel = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
const dispose = installLanguagePickerPopover(root)
try {
document.dispatchEvent(new Event('scroll'))
expect(raf).not.toHaveBeenCalled()
expect(measure).not.toHaveBeenCalled()
trigger.dataset.expanded = 'true'
await new Promise(resolve => setTimeout(resolve, 0))
expect(menu.showPopover).toHaveBeenCalledOnce()
measure.mockClear()
document.dispatchEvent(new Event('scroll'))
document.dispatchEvent(new Event('scroll'))
expect(raf).toHaveBeenCalledOnce()
callback!(0)
expect(measure).toHaveBeenCalledOnce()
document.dispatchEvent(new Event('scroll'))
dispose()
expect(cancel).toHaveBeenCalledWith(42)
expect(menu.hidePopover).toHaveBeenCalledOnce()
raf.mockClear()
document.dispatchEvent(new Event('scroll'))
expect(raf).not.toHaveBeenCalled()
} finally { dispose(); root.remove(); vi.restoreAllMocks() }
})
@@ -1,43 +1,68 @@
/** Promote Milkdown's menu to the top layer without moving its Vue-owned DOM. */
/** Promote menus to the top layer; only open menus need scroll measurements. */
export function installLanguagePickerPopover(root: HTMLElement): () => void {
const menus = new Set<HTMLElement>()
function sync() {
root.querySelectorAll<HTMLElement>('.language-picker').forEach(menu => {
const openMenus = new Set<HTMLElement>()
let frame = 0
function sync(menu: HTMLElement) {
if (!root.contains(menu)) { menus.delete(menu); openMenus.delete(menu); return }
const trigger = menu.parentElement?.querySelector<HTMLElement>('.language-button')
if (!trigger || typeof menu.showPopover !== 'function') return
menus.add(menu)
menu.setAttribute('popover', 'manual')
const search = menu.querySelector<HTMLInputElement>('.search-input')
if (search) {
search.autocomplete = 'off'
search.spellcheck = false
}
if (search) { search.autocomplete = 'off'; search.spellcheck = false }
if (trigger.dataset.expanded !== 'true' || !menu.firstElementChild) {
openMenus.delete(menu)
if (menu.matches(':popover-open')) menu.hidePopover()
return
}
openMenus.add(menu)
if (!menu.matches(':popover-open')) menu.showPopover()
const anchor = trigger.getBoundingClientRect()
const below = window.innerHeight - anchor.bottom - 16
const above = anchor.top - 16
const below = window.innerHeight - anchor.bottom - 16, above = anchor.top - 16
const placeAbove = below < 240 && above > below
const available = Math.max(80, placeAbove ? above : below)
menu.style.setProperty('--picker-list-height', `${Math.min(280, Math.max(32, available - 64))}px`)
const bounds = menu.getBoundingClientRect()
menu.style.setProperty('--picker-left', `${Math.max(12, Math.min(anchor.left, window.innerWidth - bounds.width - 12))}px`)
menu.style.setProperty('--picker-top', `${Math.max(12, placeAbove ? anchor.top - bounds.height - 8 : anchor.bottom + 8)}px`)
}
function discover(node: Node, changed: Set<HTMLElement>) {
if (!(node instanceof HTMLElement)) return
if (node.matches('.language-picker')) changed.add(node)
node.querySelectorAll<HTMLElement>('.language-picker').forEach(menu => changed.add(menu))
}
const observer = new MutationObserver(records => {
const changed = new Set<HTMLElement>()
let removed = false
for (const record of records) {
const target = record.target instanceof Element ? record.target : record.target.parentElement
const menu = target?.closest<HTMLElement>('.language-picker')
if (menu) changed.add(menu)
if (record.type === 'attributes') {
const sibling = target?.parentElement?.querySelector<HTMLElement>('.language-picker')
if (sibling) changed.add(sibling)
}
record.addedNodes.forEach(node => discover(node, changed))
removed ||= record.removedNodes.length > 0
}
if (removed) for (const menu of menus) if (!root.contains(menu)) { menus.delete(menu); openMenus.delete(menu) }
changed.forEach(sync)
})
for (const menu of menus) if (!root.contains(menu)) menus.delete(menu)
const positionOpenMenus = () => {
if (!openMenus.size || frame) return
frame = requestAnimationFrame(() => { frame = 0; openMenus.forEach(sync) })
}
const observer = new MutationObserver(sync)
root.querySelectorAll<HTMLElement>('.language-picker').forEach(sync)
observer.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-expanded'] })
root.addEventListener('scroll', sync, true)
window.addEventListener('resize', sync)
sync()
// The outer editor viewport is an ancestor of root, so listen in capture on the document.
document.addEventListener('scroll', positionOpenMenus, { capture: true, passive: true })
window.addEventListener('resize', positionOpenMenus)
return () => {
observer.disconnect()
root.removeEventListener('scroll', sync, true)
window.removeEventListener('resize', sync)
for (const menu of menus) if (menu.matches(':popover-open')) menu.hidePopover()
observer.disconnect(); cancelAnimationFrame(frame)
document.removeEventListener('scroll', positionOpenMenus, true)
window.removeEventListener('resize', positionOpenMenus)
for (const menu of openMenus) if (menu.matches(':popover-open')) menu.hidePopover()
menus.clear(); openMenus.clear()
}
}
@@ -0,0 +1,33 @@
// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from 'vitest'
import { installLinkNavigation } from './linkNavigation'
afterEach(() => { document.body.innerHTML = ''; vi.restoreAllMocks() })
it('opens nested link content with Ctrl/Command click but leaves ordinary editing alone', () => {
const root = document.createElement('div')
root.innerHTML = '<div class="ProseMirror"><a href="https://example.com/docs"><strong>Docs</strong></a></div>'
document.body.append(root)
const dispose = installLinkNavigation(root)
const open = vi.spyOn(window, 'open').mockReturnValue(null)
const target = root.querySelector('strong')!
const click = (options: MouseEventInit) => {
const event = new MouseEvent('click', { bubbles: true, cancelable: true, ...options })
target.dispatchEvent(event)
return event
}
expect(click({}).defaultPrevented).toBe(false)
click({ ctrlKey: true, button: 2 })
expect(open).not.toHaveBeenCalled()
expect(click({ ctrlKey: true }).defaultPrevented).toBe(true)
expect(open).toHaveBeenLastCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer')
click({ metaKey: true })
expect(open).toHaveBeenCalledTimes(2)
root.querySelector('a')!.href = 'javascript:alert(1)'
expect(click({ ctrlKey: true }).defaultPrevented).toBe(true)
expect(open).toHaveBeenCalledTimes(2)
dispose()
root.querySelector('a')!.href = 'https://example.com'
expect(click({ ctrlKey: true }).defaultPrevented).toBe(false)
expect(open).toHaveBeenCalledTimes(2)
})
@@ -0,0 +1,20 @@
/** Editable anchors need explicit navigation; plain clicks keep editing the link. */
export function installLinkNavigation(root: HTMLElement): () => void {
const navigate = (event: MouseEvent) => {
if (event.button !== 0 || !(event.ctrlKey || event.metaKey) || event.altKey) return
const target = event.target instanceof Element ? event.target : (event.target as Node | null)?.parentElement
const link = target?.closest<HTMLAnchorElement>('.ProseMirror a[href]')
if (!link || !root.contains(link)) return
const href = link.getAttribute('href')?.trim()
if (!href) return
// Consume modified clicks before Milkdown's link editor or native navigation.
event.preventDefault()
event.stopPropagation()
let url: URL
try { url = new URL(href, document.baseURI) } catch { return }
if (!['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol)) return
window.open(url.href, '_blank', 'noopener,noreferrer')
}
root.addEventListener('click', navigate, true)
return () => root.removeEventListener('click', navigate, true)
}
@@ -1,13 +1,37 @@
// @vitest-environment happy-dom
import { afterEach, expect, it } from 'vitest'
import { afterEach, expect, it, vi } from 'vitest'
import { Compartment } from '@codemirror/state'
import { bundledLanguagesInfo } from 'shiki/langs'
import { EditorView } from '@codemirror/view'
import { shikiLanguage, shikiLanguages } from './shikiCodeMirror'
import { getCodeTokenizer } from '@/utils/markdown'
import * as markdown from '@/utils/markdown'
const editors: EditorView[] = []
afterEach(() => { editors.splice(0).forEach(view => view.destroy()) })
afterEach(() => { editors.splice(0).forEach(view => view.destroy()); vi.restoreAllMocks() })
it('reuses highlighting across recreated views and bounds retained entries', async () => {
const tokenize = vi.fn(await getCodeTokenizer('github-light', 'javascript'))
vi.spyOn(markdown, 'getCodeTokenizer').mockResolvedValue(tokenize)
const support = await shikiLanguage('javascript', 'github-light')
const create = (doc: string) => {
const view = new EditorView({ doc, extensions: [support] })
editors.push(view)
return view
}
const source = 'const answer = 42'
create(source)
const recreated = create(source)
expect(tokenize).toHaveBeenCalledTimes(1)
expect(recreated.dom.textContent).toContain(source)
recreated.dispatch({ changes: { from: 0, to: source.length, insert: 'let changed = 1' } })
expect(tokenize).toHaveBeenCalledTimes(2)
expect(recreated.dom.textContent).toContain('let changed = 1')
for (let i = 0; i < 33; i++) create(`const value = ${i}`)
const before = tokenize.mock.calls.length
create(source)
expect(tokenize).toHaveBeenCalledTimes(before + 1)
})
it.each(['github-light', 'github-dark'] as const)('uses Shiki %s tokens and updates editable content', async theme => {
const support = await shikiLanguage('python', theme)
@@ -7,6 +7,10 @@ type CodeTheme = 'github-light' | 'github-dark'
export async function shikiLanguage(language: string, theme: CodeTheme): Promise<LanguageSupport> {
const tokenize = await getCodeTokenizer(theme, language)
// Milkdown recreates off-screen CodeMirror views. Reuse immutable ranges for
// identical code within this language/theme, with a bounded retention budget.
const cache = new Map<string, DecorationSet>()
let cachedCharacters = 0
const highlights = ViewPlugin.fromClass(class {
decorations: DecorationSet
@@ -17,7 +21,13 @@ export async function shikiLanguage(language: string, theme: CodeTheme): Promise
}
highlight(view: EditorView): DecorationSet {
const tokens = tokenize(view.state.doc.toString(), language)
const source = view.state.doc.toString()
const cached = cache.get(source)
if (cached) {
cache.delete(source); cache.set(source, cached)
return cached
}
const tokens = tokenize(source, language)
const ranges = tokens.flatMap((line, index) => {
let offset = view.state.doc.line(index + 1).from
return line.flatMap(token => {
@@ -31,7 +41,15 @@ export async function shikiLanguage(language: string, theme: CodeTheme): Promise
}).range(from, offset)]
})
})
return Decoration.set(ranges)
const decorations = Decoration.set(ranges)
if (source.length <= 16000) {
cache.set(source, decorations); cachedCharacters += source.length
while (cache.size > 32 || cachedCharacters > 64000) {
const oldest = cache.keys().next().value!
cachedCharacters -= oldest.length; cache.delete(oldest)
}
}
return decorations
}
}, { decorations: value => value.decorations })
@@ -0,0 +1,65 @@
// @vitest-environment happy-dom
import { mount, flushPromises } from '@vue/test-utils'
import { afterEach, expect, it, vi } from 'vitest'
import LogsView from './LogsView.vue'
const get = vi.hoisted(() => vi.fn())
vi.mock('@/services/apiClient', () => ({ default: { get } }))
afterEach(() => { vi.useRealTimers(); vi.clearAllMocks() })
const page = (id: number, next: number | null) => ({ items: [{ id, timestamp: '2026-09-06T01:00:00Z', level: 'ERROR', source: 'vectors', event: 'embedding.failed', details: { error_code: 'LOCAL_CUDA_OOM' } }], next_cursor: next, sources: ['vectors'], pending: 0, dropped: 0, write_failures: 0, retention: 20000 })
it('loads older logs without paging away and applies filters', async () => {
get.mockResolvedValueOnce(page(4, 4)).mockResolvedValueOnce(page(2, null)).mockResolvedValue(page(8, null))
const wrapper = mount(LogsView)
await flushPromises()
expect(wrapper.get('details').classes()).toContain('ui-disclosure')
await wrapper.findAll('button').find(button => button.text() === '向上滚动加载更早日志')!.trigger('click')
await flushPromises()
expect(get.mock.lastCall![1].params.before).toBe(4)
expect(wrapper.findAll('details').map(row => row.attributes('data-log-id'))).toEqual(['2', '4'])
await wrapper.get('input[maxlength="200"]').setValue('LOCAL_CUDA_OOM')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(get.mock.lastCall![1].params).toMatchObject({ before: undefined, q: 'LOCAL_CUDA_OOM' })
wrapper.unmount()
})
it('follows at the bottom, pauses while reading, and loads history on scroll', async () => {
vi.useFakeTimers()
get.mockResolvedValue(page(10, 10))
const wrapper = mount(LogsView)
await flushPromises()
const viewport = wrapper.get('.log-list').element as HTMLElement
Object.defineProperty(viewport, 'scrollHeight', { configurable: true, value: 1000 })
Object.defineProperty(viewport, 'clientHeight', { configurable: true, value: 200 })
viewport.scrollTop = 800
await wrapper.get('.log-list').trigger('scroll')
get.mockResolvedValueOnce({ ...page(11, 10), items: [...page(11, 10).items, ...page(10, 10).items] })
await vi.advanceTimersByTimeAsync(5000)
await flushPromises()
expect(wrapper.findAll('details').map(row => row.attributes('data-log-id'))).toEqual(['10', '11'])
expect(viewport.scrollTop).toBe(1000)
viewport.scrollTop = 400
await wrapper.get('.log-list').trigger('scroll')
const calls = get.mock.calls.length
await vi.advanceTimersByTimeAsync(5000)
expect(get).toHaveBeenCalledTimes(calls)
get.mockResolvedValueOnce(page(9, null))
viewport.scrollTop = 0
await wrapper.get('.log-list').trigger('scroll')
await flushPromises()
expect(get.mock.lastCall![1].params.before).toBe(10)
expect(wrapper.findAll('details').map(row => row.attributes('data-log-id'))).toEqual(['9', '10', '11'])
wrapper.unmount()
})
it('surfaces storage loss and transport errors without polling after unmount', async () => {
vi.useFakeTimers()
get.mockResolvedValueOnce({ ...page(1, null), dropped: 3, write_failures: 1 }).mockRejectedValue(new Error('offline'))
const wrapper = mount(LogsView)
await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('3')
await wrapper.get('input[type="checkbox"]').setValue(true)
await vi.advanceTimersByTimeAsync(5000)
expect(wrapper.text()).toContain('offline')
wrapper.unmount()
const calls = get.mock.calls.length
await vi.advanceTimersByTimeAsync(10000)
expect(get).toHaveBeenCalledTimes(calls)
})
+117
View File
@@ -0,0 +1,117 @@
<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import apiClient from '@/services/apiClient'
import { t } from '@/i18n'
interface LogEntry { id: number; timestamp: string; level: string; source: string; event: string; details: Record<string, unknown> }
interface LogPage { items: LogEntry[]; next_cursor: number | null; sources: string[]; pending: number; dropped: number; write_failures: number; retention: number }
const page = ref<LogPage>({ items: [], next_cursor: null, sources: [], pending: 0, dropped: 0, write_failures: 0, retention: 20000 })
const level = ref(''), source = ref(''), query = ref(''), error = ref('')
const loading = ref(false), live = ref(true), following = ref(true)
const scroller = ref<HTMLElement>()
const atLatest = ref(true)
const MAX_VISIBLE = 500
let applied = { level: '', source: '', q: '' }
let revision = 0
let timer: ReturnType<typeof setInterval> | undefined
let adjusting = false
async function load(reset = false, older = false) {
if (older && (loading.value || !page.value.next_cursor)) return
if (reset) applied = { level: level.value, source: source.value, q: query.value.trim() }
const version = ++revision
const viewport = scroller.value
const oldHeight = viewport?.scrollHeight ?? 0
const oldTop = viewport?.scrollTop ?? 0
// Preserve a visible row when adding history and trimming the opposite edge.
const anchor = older && viewport ? [...viewport.querySelectorAll<HTMLElement>('[data-log-id]')].find(row => row.getBoundingClientRect().bottom > viewport.getBoundingClientRect().top) : undefined
const anchorTop = anchor?.getBoundingClientRect().top
const anchorId = anchor?.dataset.logId
loading.value = true
try {
const result = await apiClient.get<LogPage>('/api/logs', { params: { limit: 50, before: older ? page.value.next_cursor ?? undefined : undefined, ...applied } })
if (version !== revision) return
// If the reader scrolled away during a refresh, leave their view untouched.
if (!reset && !older && !following.value) return
const previous = page.value.items
const overlaps = result.items.some(item => previous.some(old => old.id === item.id))
const combined = older || (!reset && overlaps) ? [...previous, ...result.items] : result.items
const all = [...new Map(combined.map(item => [item.id, item])).values()].sort((a, b) => a.id - b.id)
const trimmed = all.length > MAX_VISIBLE
const items = older ? all.slice(0, MAX_VISIBLE) : all.slice(-MAX_VISIBLE)
let cursor = older || reset || !overlaps ? result.next_cursor : page.value.next_cursor
if (!older && trimmed) cursor = items[0]?.id ?? null
if (older && trimmed) atLatest.value = false
if (!older) atLatest.value = true
adjusting = true
page.value = { ...result, items, next_cursor: cursor }
error.value = ''
await nextTick()
if (version !== revision) return
if (viewport) {
if (older) {
const retained = anchorId ? viewport.querySelector<HTMLElement>(`[data-log-id="${anchorId}"]`) : undefined
viewport.scrollTop = retained && anchorTop != null ? oldTop + retained.getBoundingClientRect().top - anchorTop : oldTop + viewport.scrollHeight - oldHeight
} else if (reset || following.value) {
viewport.scrollTop = viewport.scrollHeight
following.value = true
}
}
} catch (reason) {
if (version === revision) error.value = reason instanceof Error ? reason.message : t('日志加载失败', 'Failed to load logs')
} finally { if (version === revision) { loading.value = false; adjusting = false } }
}
function onScroll() {
const viewport = scroller.value
if (!viewport || adjusting) return
following.value = atLatest.value && viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop < 24
if (viewport.scrollTop < 80 && viewport.scrollHeight > viewport.clientHeight && !error.value) void load(false, true)
}
onMounted(() => {
void load(true)
timer = setInterval(() => { if (live.value && following.value && !loading.value && !document.hidden) void load() }, 5000)
})
onUnmounted(() => { revision++; clearInterval(timer) })
</script>
<template>
<section class="feature-page logs-page">
<header class="feature-header"><div><h1>{{ t('运行日志', 'Operation logs') }}</h1><p>{{ t('集中查看向量模型、智能体、任务与后台操作。', 'Inspect models, agents, tasks and background operations.') }}</p></div><button class="button-secondary" :disabled="loading" @click="load(true)">{{ t('刷新', 'Refresh') }}</button></header>
<form class="panel log-filters" @submit.prevent="load(true)">
<label class="field">{{ t('级别', 'Level') }}<select v-model="level" class="select"><option value="">{{ t('全部', 'All') }}</option><option>INFO</option><option>WARNING</option><option>ERROR</option><option>CRITICAL</option></select></label>
<label class="field">{{ t('模块', 'Module') }}<select v-model="source" class="select"><option value="">{{ t('全部', 'All') }}</option><option v-for="item in page.sources" :key="item">{{ item }}</option></select></label>
<label class="field log-search">{{ t('事件、错误码或关联 ID', 'Event, error code or correlation ID') }}<input v-model="query" class="input" maxlength="200" /></label>
<button class="button-primary" :disabled="loading">{{ t('筛选', 'Filter') }}</button>
<label><input v-model="live" type="checkbox" /> {{ t('自动跟随新日志', 'Follow new logs') }}</label>
</form>
<p class="subtle">{{ t('本地保留最近', 'Locally retains the latest') }} {{ page.retention.toLocaleString() }} {{ t('条日志;不记录正文、提示词、工具参数及密钥。', 'events; excludes content, prompts, tool arguments and credentials.') }}</p>
<p v-if="page.dropped || page.write_failures" class="error-banner" role="alert">{{ t('日志存储不完整队列溢出', 'Incomplete logging: queue overflow') }} {{ page.dropped }} · {{ t('写入失败', 'Write failures') }} {{ page.write_failures }}</p>
<p v-if="error" class="error-banner" role="alert">{{ error }}</p>
<div class="inline-actions log-controls"><span class="subtle" role="status">{{ live && following ? t('正在跟随最新日志', 'Following latest logs') : t('已暂停跟随,可自由查看历史', 'Following paused; browse history freely') }}</span><button class="button-secondary" :disabled="loading" @click="live = true; load(true)">{{ t('回到最新', 'Back to latest') }}</button><span class="subtle">{{ t('待写入', 'Pending') }} {{ page.pending }}</span></div>
<div ref="scroller" class="panel log-list" :aria-busy="loading" tabindex="0" :aria-label="t('日志列表向上滚动加载历史', 'Log list; scroll up for history')" @scroll.passive="onScroll">
<div class="history-status"><button v-if="page.next_cursor" class="button-secondary" :disabled="loading" @click="load(false, true)">{{ loading ? t('加载中…', 'Loading…') : t('向上滚动加载更早日志', 'Scroll up for older logs') }}</button><span v-else class="subtle">{{ t('已到保留日志的开头', 'Beginning of retained logs') }}</span></div>
<p v-if="!page.items.length">{{ loading ? t('加载中', 'Loading') : t('暂无符合条件的日志', 'No matching logs') }}</p>
<details v-for="entry in page.items" :key="entry.id" :data-log-id="entry.id" class="ui-disclosure log-entry">
<summary><span class="badge" :class="{ error: entry.level === 'ERROR' || entry.level === 'CRITICAL', warning: entry.level === 'WARNING' }">{{ entry.level }}</span><time>{{ new Date(entry.timestamp).toLocaleString() }}</time><span>{{ entry.source }}</span><strong>{{ entry.event }}</strong></summary>
<dl><template v-for="(value, key) in entry.details" :key="key"><dt>{{ key }}</dt><dd>{{ value }}</dd></template></dl>
</details>
</div>
</section>
</template>
<style scoped>
.logs-page > * { width: 100%; max-width: 1180px; margin-inline: auto; box-sizing: border-box; }
.logs-page > .subtle { margin-block: var(--space-md); }
.log-controls { margin-block: var(--space-md); }
.log-list { height: min(65vh, 800px); min-height: 240px; overflow-y: auto; overscroll-behavior: contain; overflow-anchor: none; scroll-behavior: auto; }
.history-status { text-align: center; margin-bottom: var(--space-md); }
.log-filters { display: flex; align-items: end; flex-wrap: wrap; gap: var(--space-md); }
.log-filters .field { min-width: 140px; margin: 0; }
.log-search { flex: 1; }
.log-entry { border-bottom: 1px solid var(--color-border-subtle); padding: var(--space-sm); }
.log-entry + .log-entry { margin-top: var(--space-xs); }
.log-entry summary { display: flex; flex-wrap: wrap; gap: var(--space-sm); cursor: pointer; align-items: center; overflow-wrap: anywhere; }
.log-entry summary::after { margin-left: auto; }
.log-entry dl { display: grid; grid-template-columns: minmax(100px, 160px) 1fr; gap: var(--space-sm); font-size: var(--font-size-sm); }
.log-entry dd { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; min-width: 0; }
.log-entry dt, .log-entry time { color: var(--color-text-secondary); }
</style>
@@ -7,6 +7,31 @@ import { useProviderStore } from '@/stores/provider'
import { useSettingsStore } from '@/stores/settings'
beforeEach(() => { localStorage.clear(); setActivePinia(createPinia()) })
it('separates unfinished indexing from retrieval activity and retains short search totals', async () => {
const store = useSettingsStore()
vi.spyOn(store, 'loadDiagnostics').mockResolvedValue()
const providers = useProviderStore()
vi.spyOn(providers, 'loadProviders').mockResolvedValue()
vi.spyOn(providers, 'loadPresets').mockResolvedValue()
vi.spyOn(providers, 'refreshEnabledModels').mockResolvedValue()
const wrapper = mount(SettingsView, { global: { stubs: { UsageCard: true, LocalModelSettings: true, ModelRoutingSettings: true } } })
await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '索引与模型')!.trigger('click')
expect(wrapper.text()).toContain('未完成索引 未获取')
store.indexStatus = { status: 'idle', pending_jobs: 1, running_jobs: 0, total_notes: 16, total_blocks: 3787, vector_refresh_required: true,
active_searches: 0, completed_searches: 2, failed_searches: 1, cancelled_searches: 0 }
await flushPromises()
expect(wrapper.text()).toContain('全文可用 · 向量待重建')
expect(wrapper.text()).toContain('未完成索引 1')
expect(wrapper.text()).toContain('已完成 2')
expect(wrapper.text()).toContain('失败 1')
store.indexStatus.status = 'indexing'
store.indexStatus.running_jobs = 1
await flushPromises()
expect(wrapper.text()).toContain('后台计算索引')
expect(wrapper.findAll('button').find(button => button.text() === '重建全部')!.attributes('disabled')).toBeDefined()
wrapper.unmount()
})
it('shows provider status and enables testing only after a successful enable', async () => {
const store = useProviderStore()
store.providers = [{ provider_id: 'p1', name: 'Example', provider_type: 'openai_compatible', enabled: false, default_model: '', capabilities: {}, has_credential: false }]
@@ -5,6 +5,8 @@ const { actionDialog, resolveAction, askConfirm } = useActionDialog()
import { computed, onMounted, ref } from 'vue'
import type { ProviderConfig } from '@/contracts'
import ProviderForm from './ProviderForm.vue'
import HeadingStyleSettings from '@/features/editor/HeadingStyleSettings.vue'
import MarkdownPreferenceSettings from '@/features/editor/MarkdownPreferenceSettings.vue'
import ChatPersonaDialog from '@/features/chat/ChatPersonaDialog.vue'
import ProviderLogo from './ProviderLogo.vue'
import ModelRoutingSettings from './ModelRoutingSettings.vue'
@@ -85,7 +87,7 @@ async function chooseDefaultModel(provider: ProviderConfig, event: Event) {
<ChatPersonaDialog v-if="showPersona" @close="showPersona = false" />
<div v-if="activeSection === 'general'" class="panel settings-section"><h2>{{ t('通用', 'General') }}</h2><label class="setting-row"><span><strong>{{ t('恢复上次 Vault', 'Restore last Vault') }}</strong><small>{{ t('启动后自动打开最近使用的知识库', 'Open the most recently used knowledge base at startup') }}</small></span><input v-model="settingsStore.restoreLastVault" type="checkbox" /></label><div class="setting-row"><span><strong>{{ t('自动保存间隔', 'Autosave interval') }}</strong><small>{{ t('编辑停止后等待多久写入文件', 'How long to wait after editing before saving') }}</small></span><select v-model.number="settingsStore.autoSaveInterval" class="select short"><option :value="500">0.5 {{ t('秒', 'sec') }}</option><option :value="1500">1.5 {{ t('秒', 'sec') }}</option><option :value="3000">3 {{ t('秒', 'sec') }}</option></select></div><div class="setting-row"><span><strong>{{ t('界面语言', 'Interface language') }}</strong><small>{{ t('切换后立即应用到界面', 'Applied to the interface immediately') }}</small></span><select v-model="settingsStore.language" class="select short"><option value="zh-CN">简体中文</option><option value="en">English</option></select></div><div class="setting-row"><span><strong>{{ t('版本', 'Version') }}</strong><small>Desktop / AI Core</small></span><span>{{ settingsStore.appVersion }} / {{ settingsStore.aiCoreVersion }}</span></div></div>
<div v-else-if="activeSection === 'editor'" class="panel settings-section"><h2>{{ t('编辑器', 'Editor') }}</h2><div class="setting-row"><span><strong>{{ t('默认模式', 'Default mode') }}</strong><small>{{ t('新打开文件使用的编辑器模式', 'Editor mode used for newly opened files') }}</small></span><select v-model="settingsStore.defaultEditorMode" class="select short"><option value="wysiwyg">{{ t('写作与预览', 'Writing and preview') }}</option><option value="source">{{ t('Markdown 源码', 'Markdown source') }}</option></select></div><div class="setting-row"><span><strong>{{ t('字号', 'Font size') }}</strong></span><input v-model.number="themeStore.fontEditorSize" class="input short" type="number" min="12" max="32" /></div><div class="setting-row"><span><strong>{{ t('行高', 'Line height') }}</strong></span><input v-model.number="themeStore.lineHeight" class="input short" type="number" min="1.2" max="2.4" step="0.1" /></div><div class="setting-row"><span><strong>{{ t('行宽', 'Line width') }}</strong><small>{{ t('Markdown 预览最大字符宽度', 'Maximum character width for Markdown preview') }}</small></span><input v-model.number="settingsStore.editorLineWidth" class="input short" type="number" min="40" max="140" /></div><label class="setting-row"><span><strong>{{ t('拼写检查', 'Spell check') }}</strong><small>{{ t('在写作与源码编辑器中使用系统拼写检查', 'Use system spell checking in visual and source editors') }}</small></span><input v-model="settingsStore.spellCheck" type="checkbox" /></label></div>
<div v-else-if="activeSection === 'editor'" class="panel settings-section"><h2>{{ t('编辑器', 'Editor') }}</h2><div class="setting-row"><span><strong>{{ t('默认模式', 'Default mode') }}</strong><small>{{ t('新打开文件使用的编辑器模式', 'Editor mode used for newly opened files') }}</small></span><select v-model="settingsStore.defaultEditorMode" class="select short"><option value="wysiwyg">{{ t('写作与预览', 'Writing and preview') }}</option><option value="source">{{ t('Markdown 源码', 'Markdown source') }}</option></select></div><div class="setting-row"><span><strong>{{ t('字号', 'Font size') }}</strong></span><input v-model.number="themeStore.fontEditorSize" class="input short" type="number" min="12" max="32" /></div><div class="setting-row"><span><strong>{{ t('行高', 'Line height') }}</strong></span><input v-model.number="themeStore.lineHeight" class="input short" type="number" min="1.2" max="2.4" step="0.1" /></div><div class="setting-row"><span><strong>{{ t('行宽', 'Line width') }}</strong><small>{{ t('Markdown 预览最大字符宽度', 'Maximum character width for Markdown preview') }}</small></span><input v-model.number="settingsStore.editorLineWidth" class="input short" type="number" min="40" max="140" /></div><label class="setting-row"><span><strong>{{ t('拼写检查', 'Spell check') }}</strong><small>{{ t('在写作与源码编辑器中使用系统拼写检查', 'Use system spell checking in visual and source editors') }}</small></span><input v-model="settingsStore.spellCheck" type="checkbox" /></label><MarkdownPreferenceSettings /><HeadingStyleSettings /></div>
<div v-else-if="activeSection === 'providers'" class="settings-section">
<section class="panel provider-settings-card">
@@ -126,7 +128,32 @@ async function chooseDefaultModel(provider: ProviderConfig, event: Event) {
<UsageCard />
</div>
<div v-else-if="activeSection === 'index'" class="panel settings-section"><h2>{{ t('索引与模型', 'Index and Models') }}</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>{{ t('待处理任务', 'Pending jobs') }} {{ settingsStore.indexStatus.pending_jobs }}</p></div><div><strong>{{ settingsStore.indexStatus.total_notes ?? t('未获取', 'Unavailable') }}</strong><small>{{ t('笔记', 'Notes') }}</small></div><div><strong>{{ settingsStore.indexStatus.total_blocks ?? t('未获取', 'Unavailable') }}</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')">{{ t('重建全部', 'Rebuild all') }}</button><span class="subtle">{{ t('当前后端支持全量重建', 'The current backend supports a full rebuild.') }}</span></div><ModelRoutingSettings /></div>
<div v-else-if="activeSection === 'index'" class="panel settings-section">
<h2>{{ t('索引与模型', 'Index and Models') }}</h2>
<div class="index-summary">
<div>
<span class="badge" :class="{ success: settingsStore.indexStatus.status === 'idle' && !settingsStore.indexStatus.vector_refresh_required && !settingsStore.indexStatus.active_searches, error: settingsStore.indexStatus.status === 'error' }">{{ settingsStore.indexStatusLabel }}</span>
<p>{{ t('未完成索引', 'Unfinished indexing jobs') }} {{ settingsStore.indexStatus.status === 'unknown' ? t('未获取', 'Unavailable') : settingsStore.indexStatus.pending_jobs }}</p>
<small>{{ t('运行中', 'Running') }} {{ settingsStore.indexStatus.running_jobs ?? t('未获取', 'Unavailable') }}</small>
</div>
<div><strong>{{ settingsStore.indexStatus.total_notes ?? t('未获取', 'Unavailable') }}</strong><small>{{ t('笔记', 'Notes') }}</small></div>
<div><strong>{{ settingsStore.indexStatus.total_blocks ?? t('未获取', 'Unavailable') }}</strong><small>Block</small></div>
</div>
<p class="subtle">{{ t('未完成数包含运行中的任务;全库重建计为一个任务,不是笔记或 Block 数量。', 'Unfinished jobs include running jobs. A full rebuild counts as one job, not the number of notes or blocks.') }}</p>
<div class="index-search-activity">
<h3>{{ t('向量 / 混合检索', 'Vector / hybrid searches') }}</h3>
<div class="inline-actions">
<span>{{ t('进行中', 'Active') }} {{ settingsStore.indexStatus.active_searches ?? t('未获取', 'Unavailable') }}</span>
<span>{{ t('已完成', 'Completed') }} {{ settingsStore.indexStatus.completed_searches ?? t('未获取', 'Unavailable') }}</span>
<span>{{ t('失败', 'Failed') }} {{ settingsStore.indexStatus.failed_searches ?? t('未获取', 'Unavailable') }}</span>
<span>{{ t('已取消', 'Cancelled') }} {{ settingsStore.indexStatus.cancelled_searches ?? t('未获取', 'Unavailable') }}</span>
</div>
<p class="subtle">{{ t('统计本次 AI Core 启动以来的检索,包含搜索、对话和智能体调用;不计纯全文检索。', 'Counts searches, chat and agent retrievals since AI Core started; excludes full-text-only searches.') }}</p>
</div>
<div v-if="settingsStore.indexStatus.error" class="error-banner">{{ settingsStore.indexStatus.error }}</div>
<div class="inline-actions"><button class="button-primary" :disabled="settingsStore.indexStatus.status === 'indexing'" @click="settingsStore.rebuildIndex('full')">{{ t('重建全部', 'Rebuild all') }}</button><span class="subtle">{{ t('当前后端支持全量重建。', 'The current backend supports a full rebuild.') }}</span></div>
<ModelRoutingSettings />
</div>
<div v-else-if="activeSection === 'permissions'" class="panel settings-section"><h2>{{ t('权限策略', 'Permission Policy') }}</h2><p class="muted section-description">{{ t('以下为后端当前生效的权限策略;全局策略编辑尚未开放,运行时按实际权限请求确认。', 'These policies are active in the backend. Global policy editing is not yet available; runtime requests are confirmed as needed.') }}</p><p v-if="!Object.keys(settingsStore.permissionPolicy).length" class="subtle">{{ t('尚未获取权限策略,请检查后端连接并重新检测。', 'Permission policy is unavailable. Check the backend connection and try again.') }}</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' ? t('允许', 'Allow') : policy === 'confirm' ? t('每次确认', 'Confirm each time') : t('拒绝', 'Deny') }}</span></div></div></div>
+8 -2
View File
@@ -3,12 +3,17 @@ import ActionDialog from '@/components/common/ActionDialog.vue'
import { useActionDialog } from '@/composables/useActionDialog'
const { actionDialog, resolveAction, askConfirm } = useActionDialog()
import AppDialog from '@/components/common/AppDialog.vue'
import { onMounted, reactive, ref } from 'vue'
import { computed, watch, onMounted, reactive, ref } from 'vue'
import type { TaskItem, TaskStatus } from '@/contracts'
import { useTaskStore } from '@/stores/task'
import { localeTag, t } from '@/i18n'
const taskStore = useTaskStore()
const page = ref(1)
const pageCount = computed(() => Math.max(1, Math.ceil(taskStore.filteredTasks.length / 100)))
const visibleTasks = computed(() => taskStore.filteredTasks.slice((page.value - 1) * 100, page.value * 100))
watch(() => [taskStore.filterStatus, taskStore.filterPriority, taskStore.filterSource], () => { page.value = 1 })
watch(pageCount, count => { page.value = Math.min(page.value, count) })
const showForm = ref(false)
const editingId = ref<string | null>(null)
const actionError = ref('')
@@ -44,13 +49,14 @@ async function remove(task: TaskItem) {
<header class="feature-header"><div><h1>{{ t('任务', 'Tasks') }}</h1><p>{{ t('管理用户、笔记和 Agent 产生的行动项。', 'Manage action items created by users, notes, and agents.') }}</p></div><button class="button-primary" @click="resetForm(); showForm = true"> {{ t('新建任务', 'New task') }}</button></header>
<div v-if="taskStore.error || actionError" class="error-banner">{{ taskStore.error || actionError }}</div>
<div v-if="taskStore.filteredTasks.length" class="task-list">
<article v-for="task in taskStore.filteredTasks" :key="task.task_id" class="item-card task-card">
<article v-for="task in visibleTasks" :key="task.task_id" class="item-card task-card">
<button class="status-check" :class="{ done: task.status === 'done' }" :title="t('切换完成状态', 'Toggle completion')" @click="setStatus(task, task.status === 'done' ? 'todo' : 'done')">{{ task.status === 'done' ? '' : '' }}</button>
<div class="task-content"><div class="task-title"><strong :class="{ completed: task.status === 'done' }">{{ task.title }}</strong></div><p v-if="task.description" class="muted">{{ task.description }}</p><div class="subtle"><span>{{ task.status }}</span><span v-if="task.due_date">{{ t('截止', 'Due') }} {{ new Date(task.due_date).toLocaleString(localeTag()) }}</span><span v-if="task.note_id">{{ t('关联 Note', 'Linked Note') }}: {{ task.note_id }}</span></div></div>
<div class="inline-actions"><button class="icon-button" @click="editTask(task)">{{ t('编辑', 'Edit') }}</button><button class="button-danger" @click="remove(task)">{{ t('删除', 'Delete') }}</button></div>
</article>
</div>
<div v-else class="empty-state"><div><strong>{{ taskStore.isLoading ? t('正在加载任务…', 'Loading tasks…') : t('没有符合条件的任务', 'No matching tasks') }}</strong><p>{{ t('创建一项任务,或调整左侧筛选条件。', 'Create a task or adjust the filters.') }}</p></div></div>
<nav v-if="pageCount > 1" class="inline-actions"><button class="button-secondary" :disabled="page === 1" @click="page--">{{ t('上一页', 'Previous') }}</button><span>{{ page }} / {{ pageCount }} · {{ taskStore.filteredTasks.length }}</span><button class="button-secondary" :disabled="page === pageCount" @click="page++">{{ t('下一页', 'Next') }}</button></nav>
<AppDialog v-if="showForm" :label="t('任务表单', 'Task form')" @close="showForm = false"><div class="modal"><h2>{{ editingId ? t('编辑任务', 'Edit task') : t('新建任务', 'New task') }}</h2><form @submit.prevent="saveTask"><div class="field"><label>{{ t('标题', 'Title') }}</label><input v-model="form.title" class="input" required /></div><div class="field"><label>{{ t('描述', 'Description') }}</label><textarea v-model="form.description" class="textarea" /></div><div class="field"><label>{{ t('截止时间', 'Due date') }}</label><input v-model="form.due_date" class="input" type="datetime-local" /></div><div class="field"><label>{{ t('关联 Note ID', 'Linked Note ID') }}</label><input v-model="form.note_id" class="input" /></div><div class="inline-actions"><button class="button-primary">{{ t('保存', 'Save') }}</button><button type="button" class="button-secondary" @click="showForm = false">{{ t('取消', 'Cancel') }}</button></div></form></div></AppDialog>
</section>
</template>
@@ -4,7 +4,9 @@ import { mount } from '@vue/test-utils'
// Vitest disables CSS by default, including CSS raw imports. Load the real files here.
vi.mock('@/styles/features.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/features.css', 'utf8') }))
vi.mock('@/styles/tokens.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/tokens.css', 'utf8') }))
vi.mock('@/styles/callouts.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/callouts.css', 'utf8') }))
import CommunityThemePreview from './CommunityThemePreview.vue'
vi.mock('@/styles/markdown-behavior.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/markdown-behavior.css', 'utf8') }))
import { mockCommunityThemes } from '@/services/themePackageService'
const themes = [...['light','dark','sepia'].map(theme_id => ({theme_id,name:theme_id,builtin:true})), ...mockCommunityThemes.map(t => ({...t,builtin:false}))]
it.each(themes)('previews shared component states safely for $theme_id', theme => {
@@ -15,11 +17,24 @@ it.each(themes)('previews shared component states safely for $theme_id', theme =
const doc = new DOMParser().parseFromString(iframe.attributes('srcdoc')!, 'text/html')
expect(doc.documentElement.dataset.theme).toBe(theme.theme_id)
expect(doc.querySelector('script')).toBeNull()
for (const selector of ['.editor-scroll-buttons button', '.markdown-content h6', '.task-list-item input:checked', '.markdown-content[data-code-wrap="true"][data-line-numbers="true"] .line', '.heading-fold-toggle']) expect(doc.querySelector(selector), selector).not.toBeNull()
expect(doc.querySelector('style')!.textContent).toContain('.editor-scroll-buttons button:focus-visible')
expect(doc.querySelector('style')!.textContent).toContain(".markdown-content[data-code-wrap='true'] .shiki code")
expect(doc.querySelectorAll('.specimen-callouts > aside.markdown-callout')).toHaveLength(14)
expect(doc.querySelector('.specimen-callouts > details[open]')).not.toBeNull()
expect(doc.querySelector('.specimen-callouts > details:not([open])')).not.toBeNull()
expect(doc.querySelector('style')!.textContent).toContain('.callout-title:focus-visible')
expect(doc.querySelector('meta[http-equiv="Content-Security-Policy"]')?.getAttribute('content')).toContain("default-src 'none'")
for (const selector of ['input.input','input:disabled','textarea.textarea','select.select','.ui-disclosure[open]','.ui-disclosure:not([open])','.button-primary:disabled','.badge.success','.error-banner','.specimen-markdown code','.specimen-markdown table','.specimen-chart','.specimen-long']) expect(doc.querySelector(selector), selector).not.toBeNull()
expect(doc.querySelector('style')!.textContent).toContain('.button-primary:hover')
expect(doc.querySelector('style')!.textContent).not.toContain('color:white')
const rules = Array.from(doc.styleSheets[0]!.cssRules) as CSSStyleRule[]
// The sandbox cannot inherit MarkdownContent's component stylesheet.
const codeRule = rules.find(rule => rule.selectorText === '.markdown-content .shiki code')!
const lineRule = rules.find(rule => rule.selectorText === '.markdown-content .shiki .line')!
expect(codeRule.style.getPropertyValue('display')).toBe('block')
expect(lineRule.style.getPropertyValue('display')).toBe('block')
expect(lineRule.style.getPropertyValue('min-height')).toBe('1.45em')
const rootRule = rules.filter(rule => rule.selectorText === 'html').pop()!
const bodyRule = rules.filter(rule => rule.selectorText === 'body').pop()!
// The embedded document must override the app-shell overflow lock.
@@ -5,6 +5,10 @@ import { t } from '@/i18n'
import { getCommunityThemePreviewCss, mockCommunityThemes } from '@/services/themePackageService'
import tokensCss from '@/styles/tokens.css?raw'
import featuresCss from '@/styles/features.css?raw'
import headingsCss from '@/styles/headings.css?raw'
import markdownBehaviorCss from '@/styles/markdown-behavior.css?raw'
import calloutsCss from '@/styles/callouts.css?raw'
import { calloutTypes } from '@/utils/callouts'
import specimenHtml from './themeSpecimen.html?raw'
const props = defineProps<{ themeId: string; name?: string; css?: string }>()
@@ -20,8 +24,9 @@ const previewDocument = computed(() => {
policy.content = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'"
doc.head.append(policy)
const style = doc.createElement('style')
style.textContent = `${tokensCss}\n${featuresCss}\n${props.css ?? getCommunityThemePreviewCss(props.themeId)}\nhtml { height:100% !important; overflow-y:auto !important; overflow-x:hidden !important; overscroll-behavior:contain; } body { height:auto !important; min-height:100%; overflow:visible !important; margin:0; padding:24px; background:var(--color-background-primary); color:var(--color-text-primary); font:16px/1.6 system-ui; } article { min-width:0; } .theme-specimen { display:grid; gap:16px; margin-top:20px; } .surface-nested { padding:12px; border:1px solid var(--color-border-default); border-radius:var(--radius-md); } .specimen-markdown { overflow:auto; } .specimen-markdown code { background:var(--color-code-background, var(--color-background-secondary)); color:var(--color-code-text, var(--color-text-primary)); padding:3px 6px; border-radius:4px; } .specimen-markdown pre { padding:12px; background:var(--color-background-secondary); } .specimen-markdown blockquote { border-left:3px solid var(--color-accent-primary); padding-left:12px; } .specimen-markdown table { width:100%; border-collapse:collapse; } .specimen-markdown td,.specimen-markdown th { padding:8px; border:1px solid var(--color-border-default); } .specimen-markdown th { background:var(--color-markdown-table-header); } .specimen-chart > div { display:flex; align-items:flex-end; gap:12px; height:100px; border-bottom:1px solid var(--color-border-default); } .specimen-chart span { width:36px; } .specimen-long { overflow-wrap:anywhere; } @media(max-width:480px) { body { padding:12px; } .form-grid { grid-template-columns:minmax(0,1fr); } }`
style.textContent = `${tokensCss}\n${featuresCss}\n${calloutsCss}\n${headingsCss}\n${props.css ?? getCommunityThemePreviewCss(props.themeId)}\nhtml { height:100% !important; overflow-y:auto !important; overflow-x:hidden !important; overscroll-behavior:contain; } body { height:auto !important; min-height:100%; overflow:visible !important; margin:0; padding:24px; background:var(--color-background-primary); color:var(--color-text-primary); font:16px/1.6 system-ui; } article { min-width:0; } .theme-specimen { display:grid; gap:16px; margin-top:20px; } .surface-nested { padding:12px; border:1px solid var(--color-border-default); border-radius:var(--radius-md); } .specimen-markdown { overflow:auto; } .specimen-markdown code { background:var(--color-code-background, var(--color-background-secondary)); color:var(--color-code-text, var(--color-text-primary)); padding:3px 6px; border-radius:4px; } .specimen-markdown pre { padding:12px; background:var(--color-background-secondary); } .specimen-markdown blockquote { border-left:3px solid var(--color-accent-primary); padding-left:12px; } .specimen-markdown table { width:100%; border-collapse:collapse; } .specimen-markdown td,.specimen-markdown th { padding:8px; border:1px solid var(--color-border-default); } .specimen-markdown th { background:var(--color-markdown-table-header); } .specimen-chart > div { display:flex; align-items:flex-end; gap:12px; height:100px; border-bottom:1px solid var(--color-border-default); } .specimen-chart span { width:36px; } .specimen-long { overflow-wrap:anywhere; } @media(max-width:480px) { body { padding:12px; } .form-grid { grid-template-columns:minmax(0,1fr); } }`
style.textContent += `\n${markdownBehaviorCss}\n.specimen-scroll { position:relative; min-height:110px; }`
doc.head.append(style)
const article = doc.createElement('article')
article.className = 'panel'
@@ -33,6 +38,22 @@ const previewDocument = computed(() => {
const button = doc.createElement('button'); button.className = 'button-primary'; button.textContent = t('示例按钮', 'Example button')
journal.append(text)
const specimen = doc.createElement('template'); specimen.innerHTML = specimenHtml
const callouts = doc.createElement('section'); callouts.className = 'specimen-callouts'
const caption = doc.createElement('h2'); caption.textContent = t('警告框与提示框', 'Alerts and callouts'); callouts.append(caption)
for (const type of Object.keys(calloutTypes)) {
const block = doc.createElement('aside'); block.className = 'markdown-callout'; block.dataset.callout = type
const title = doc.createElement('div'); title.className = 'callout-title'; title.textContent = type
const body = doc.createElement('div'); body.className = 'callout-body'; body.textContent = t('提示正文:检查文字、边框与主题配色。', 'Callout body: check text, borders and theme colors.')
block.append(title, body); callouts.append(block)
}
for (const open of [false, true]) {
const details = doc.createElement('details'); details.className = 'markdown-callout'; details.dataset.callout = 'warning'; details.open = open
const summary = doc.createElement('summary'); summary.className = 'callout-title'; summary.textContent = t('可折叠警告框', 'Collapsible callout')
const body = doc.createElement('div'); body.className = 'callout-body'
const nested = doc.createElement('aside'); nested.className = 'markdown-callout'; nested.dataset.callout = 'tip'; nested.textContent = t('嵌套提示内容', 'Nested callout content')
body.append(nested); details.append(summary, body); callouts.append(details)
}
specimen.content.append(callouts)
article.append(header, journal, button, specimen.content); doc.body.append(article)
return '<!doctype html>' + doc.documentElement.outerHTML
})
@@ -96,7 +96,7 @@ it.each(mockCommunityThemes)('previews uninstalled $theme_id using its actual CS
it('offers and applies the paper theme update without discarding the active theme', async () => {
const store = useThemeStore()
const old = await inspectThemePackage(paperPackage.replace('version: 1.6.2', 'version: 1.6.1'))
const old = await inspectThemePackage(paperPackage.replace(/^version: .+$/m, 'version: 1.6.1'))
await store.installThemeFromInspection(old.manifest, old.css)
store.applyTheme('paper-moments')
wrapper = mount(ThemesView, { global: { stubs: { MarkdownContent: true } } })
@@ -105,6 +105,6 @@ it('offers and applies the paper theme update without discarding the active them
const card = wrapper.findAll('article.theme-card').find(item => item.text().includes('Paper Moments'))!
await card.findAll('button').find(button => button.text() === '更新')!.trigger('click')
await flushPromises()
expect(store.allThemes.find(theme => theme.theme_id === 'paper-moments')?.version).toBe('1.6.2')
expect(store.allThemes.find(theme => theme.theme_id === 'paper-moments')?.version).toBe('1.9.0')
expect(document.getElementById('theme-style-paper-moments')!.textContent).toContain('.surface-nested')
})
@@ -1,4 +1,5 @@
<script setup lang="ts">
import HeadingStyleSettings from '@/features/editor/HeadingStyleSettings.vue'
import AppDialog from '@/components/common/AppDialog.vue'
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
import MarkdownContent from '@/components/common/MarkdownContent.vue'
@@ -222,6 +223,7 @@ onMounted(() => {
<div class="field"><label>{{ t('字体', 'Font') }}</label><select v-model="themeStore.fontEditorFamily" class="select"><option value="system-ui">{{ t('系统字体', 'System font') }}</option><option value="serif">{{ t('衬线字体', 'Serif') }}</option><option value="var(--font-ui-mono)">{{ t('等宽字体', 'Monospace') }}</option></select></div>
<div class="field"><label>{{ t('代码块样式', 'Code block style') }}</label><select v-model="themeStore.codeBlockTheme" class="select"><option value="auto">{{ t('跟随主题', 'Follow theme') }}</option><option value="github-light">GitHub Light</option><option value="github-dark">GitHub Dark</option></select><small>{{ t('Markdown 渲染使用对应的 Shiki GitHub 主题', 'Markdown rendering uses the matching Shiki GitHub theme') }}</small></div>
</div>
<HeadingStyleSettings />
<div class="editor-preview" :style="{ fontSize: `${themeStore.fontEditorSize}px`, lineHeight: themeStore.lineHeight, fontFamily: themeStore.fontEditorFamily }">
<div class="preview-heading"><h3>{{ t('主题预览', 'Theme Preview') }}</h3><span class="badge info">{{ codeThemeLabel }}</span></div>
<p>{{ t('知识的价值不只在于保存,更在于被重新发现和使用。', 'Knowledge gains value when it can be rediscovered and used.') }}</p>
@@ -17,3 +17,23 @@ console.log(note);</code></pre><table><thead><tr><th>名称</th><th>状态</th><
<figure class="specimen-chart"><figcaption>数据配色示例</figcaption><div role="img" aria-label="本地用量 30,提供商用量 70"><span style="height:30%;background:var(--color-accent-primary)"></span><span style="height:70%;background:var(--color-accent-secondary)"></span></div></figure>
<p class="subtle specimen-long">超长模型标识:provider/model-with-a-very-long-identifier-for-layout-validation-012345678901234567890123456789</p>
</div>
<section class="surface-nested markdown-preferences"><h2>Markdown 语法预设</h2><label>标题样式 <select class="select"><option>ATX (#)</option><option>Setext</option></select></label><label><input type="checkbox" checked> 警告框与提示框</label><button class="button-secondary">保存为预设</button></section>
<section class="milkdown"><div class="ProseMirror"><h2><button class="heading-fold-toggle" aria-expanded="true" aria-label="折叠示例标题"></button>悬停查看折叠箭头</h2><p>折叠按钮跟随主题,键盘聚焦时也可见。</p></div></section>
<section class="markdown-content specimen-markdown">
<h2>Markdown 行为与状态</h2>
<h4>四级标题</h4><h5>五级标题</h5><h6>六级标题</h6>
<p><a href="#markdown-preview-target">链接:检查悬停与键盘焦点</a><code>行内代码</code><strong>强调</strong><em>斜体</em><del>删除线</del>。选中这段文字检查主题选区颜色。</p>
<ul><li>无序列表<ul><li>嵌套列表</li></ul></li></ul><ol><li>有序列表</li><li>第二项</li></ol>
<ul><li class="task-list-item"><input type="checkbox" disabled> 未完成任务</li><li class="task-list-item"><input type="checkbox" checked disabled> 已完成任务</li></ul>
<blockquote><p>普通引用</p><blockquote>嵌套引用</blockquote></blockquote><hr>
<details class="markdown-callout" data-callout="tip"><summary class="callout-title">点击展开提示</summary><div class="callout-body"><p>提示内的 <code>代码</code> 与列表也继承主题。</p></div></details>
<p id="markdown-preview-target">ATX 和 Setext 解析后使用相同标题样式;关闭扩展语法时保留源码展示。</p>
<pre><code>&gt; [!NOTE]
关闭警告框扩展时显示原始内容
```mermaid
graph LR; A--&gt;B
```</code></pre>
</section>
<section class="surface-nested specimen-scroll"><p>工作区滚动按钮:悬停、按下或 Tab 聚焦检查配色。</p><div class="editor-scroll-buttons"><button class="button-secondary" aria-label="滑动到顶部" title="滑动到顶部"></button><button class="button-secondary" aria-label="滑动到底部" title="滑动到底部"></button></div></section>
<section class="markdown-content specimen-markdown" data-code-wrap="true" data-line-numbers="true"><h3>代码换行与行号</h3><pre class="shiki"><code><span class="line">const description = "这是一段用于检查代码自动换行、行号与主题配色的较长说明,较窄视口下也应该保留可读内容。";</span><span class="line">console.log(description);</span></code></pre></section>
@@ -66,6 +66,7 @@ async function openFolderPicker() {
</div>
<div class="vault-card">
<button class="btn" @click="router.push('/logs')">{{ t('查看运行日志', 'View operation logs') }}</button>
<div v-if="openError" class="error-banner" role="alert">{{ openError }} <button class="btn" @click="initializeVault" :disabled="isLoading">{{ t('重试', 'Retry') }}</button></div>
<p v-if="isLoading" role="status">{{ t('正在打开知识库', 'Opening knowledge base') }}</p>
<h2 class="card-title">{{ t('选择知识库', 'Select Knowledge Base') }}</h2>
@@ -216,6 +216,7 @@ function containingFolder(path: string): string {
<template>
<section class="file-tree-panel" @click="closeContextMenu" @keydown.esc="closeContextMenu" @wheel.passive="revealSearch">
<p v-if="workspaceStore.treeRefreshError" class="subtle" role="status">{{ t('文件树暂未同步将自动重试', 'File tree sync delayed; retrying automatically.') }}</p>
<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />
<div class="workspace-tabs" role="tablist" :aria-label="t('工作区导航', 'Workspace navigation')" @keydown="navigateTabs">
<button id="workspace-files-tab" role="tab" aria-controls="workspace-files-panel" :aria-selected="activeTab === 'files'" :tabindex="activeTab === 'files' ? 0 : -1" @click="switchTab('files')">{{ t('文件', 'Files') }}</button>
+1
View File
@@ -4,6 +4,7 @@ import App from './App.vue'
import router from './router'
import './styles/tokens.css'
import './styles/features.css'
import './styles/markdown-behavior.css'
import { useThemeStore } from './stores/theme'
import { useSettingsStore } from './stores/settings'
import { watch } from 'vue'
+2
View File
@@ -3,6 +3,7 @@ import { useWorkspaceStore } from '@/stores/workspace'
import { t } from '@/i18n'
const routes = [
{ path: '/logs', name: 'logs', component: () => import('@/features/logs/LogsView.vue'), meta: { title: '运行日志' } },
{ path: '/media', name: 'media', component: () => import('@/features/media/MediaView.vue'), meta: { title: '音视频转写', requiresVault: true } },
{
path: '/',
@@ -91,6 +92,7 @@ router.beforeEach((to) => {
export function updateDocumentTitle(to = router.currentRoute.value) {
const baseTitle = 'NotesAgent'
const titles: Record<string, string> = {
logs: t('运行日志', 'Operation logs'),
media: t('音视频转写', 'Media Transcription'),
'vault-entry': t('选择知识库', 'Select Knowledge Base'),
workspace: t('工作区', 'Workspace'),
@@ -0,0 +1,25 @@
import { afterEach, expect, it, vi } from 'vitest'
import { executeEditorCommand, registerEditorCommands, getEditorCommandCapabilities } from './editorCommandService'
let dispose: (() => void) | undefined
afterEach(() => dispose?.())
it('reports unsupported, disabled and invalid commands without side effects', async () => {
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: false, reason: 'unavailable' })
const handler = vi.fn(() => ({ ok: true as const }))
let available = false
dispose = registerEditorCommands({ available: () => available, handlers: { 'editor.bold': handler } })
expect(getEditorCommandCapabilities().find(item => item.id === 'editor.bold')).toMatchObject({ supported: true, enabled: false })
await executeEditorCommand('editor.bold')
expect(handler).not.toHaveBeenCalled()
available = true
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: true })
expect(await executeEditorCommand('editor.metadata.edit')).toEqual({ ok: false, reason: 'unsupported' })
expect(await executeEditorCommand('arbitrary-command')).toEqual({ ok: false, reason: 'unsupported' })
})
it('old editor disposal cannot unregister the replacement editor', async () => {
const old = registerEditorCommands({ available: () => true, handlers: {} })
dispose = registerEditorCommands({ available: () => true, handlers: { 'editor.bold': () => ({ ok: true }) } })
old()
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: true })
dispose()
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: false, reason: 'unavailable' })
})
@@ -0,0 +1,34 @@
/** Versioned frontend boundary for future native menus/shortcuts; no Tauri IPC yet. */
export const editorCommandVersion = 1
export const editorCommandIds = [
'editor.bold', 'editor.italic', 'editor.strikethrough', 'editor.inline-code',
'editor.paragraph', 'editor.heading', 'editor.bullet-list', 'editor.ordered-list',
'editor.task-list', 'editor.blockquote', 'editor.callout', 'editor.code-block',
'editor.inline-math', 'editor.math-block', 'editor.mermaid', 'editor.link',
'editor.image', 'editor.table', 'editor.horizontal-rule', 'editor.hard-break',
'editor.font-size', 'editor.insert-markdown', 'editor.import-note-properties',
'editor.metadata.edit', 'editor.metadata.title', 'editor.metadata.tags',
'editor.reference-link', 'editor.html', 'editor.undo', 'editor.redo',
'editor.heading.toggle-fold', 'editor.heading.fold-all', 'editor.heading.unfold-all',
] as const
export type EditorCommandId = typeof editorCommandIds[number]
export type CommandResult = { ok: true } | { ok: false; reason: 'unsupported' | 'unavailable' | 'invalid-params' | 'failed' }
export type CommandHandler = (params: unknown) => CommandResult | Promise<CommandResult>
type Target = { available: () => boolean; handlers: Partial<Record<EditorCommandId, CommandHandler>> }
let active: Target | undefined
export function registerEditorCommands(target: Target) {
active = target
return () => { if (active === target) active = undefined }
}
export function getEditorCommandCapabilities() {
return editorCommandIds.map(id => ({ id, supported: !!active?.handlers[id], enabled: !!active?.handlers[id] && active.available() }))
}
export async function executeEditorCommand(id: string, params?: unknown): Promise<CommandResult> {
if (!(editorCommandIds as readonly string[]).includes(id)) return { ok: false, reason: 'unsupported' }
const target = active
if (!target || !target.available()) return { ok: false, reason: 'unavailable' }
const handler = target.handlers[id as EditorCommandId]
if (!handler) return { ok: false, reason: 'unsupported' }
try { return await handler(params) } catch { return { ok: false, reason: 'failed' } }
}
+5
View File
@@ -3,6 +3,11 @@ import type { ApiIndexJob, ApiIndexStatus, IndexStatus } from '@/contracts'
function toIndexStatus(status: ApiIndexStatus): IndexStatus {
return {
running_jobs: status.running_jobs,
active_searches: status.active_searches,
completed_searches: status.completed_searches,
failed_searches: status.failed_searches,
cancelled_searches: status.cancelled_searches,
vector_refresh_required: status.vector_refresh_required ?? false,
status: status.status === 'idle' ? 'idle' : status.status === 'failed' ? 'error' : 'indexing',
pending_jobs: status.pending_jobs,
+12 -4
View File
@@ -1,4 +1,10 @@
import mermaid from 'mermaid'
let mermaidPromise: Promise<typeof import('mermaid')['default']> | undefined
function loadMermaid() {
return mermaidPromise ??= import('mermaid').then(module => module.default).catch(error => {
mermaidPromise = undefined
throw error
})
}
import { computed } from 'vue'
import { useThemeStore } from '@/stores/theme'
@@ -23,7 +29,8 @@ export function mermaidThemeVariables(dark: boolean) {
}
}
function ensureInitialized(theme: 'light' | 'dark') {
async function ensureInitialized(theme: 'light' | 'dark') {
const mermaid = await loadMermaid()
mermaid.initialize({
startOnLoad: false,
theme: 'base',
@@ -34,6 +41,7 @@ function ensureInitialized(theme: 'light' | 'dark') {
sequence: { useMaxWidth: true },
gantt: { useMaxWidth: true },
})
return mermaid
}
let queue: Promise<unknown> = Promise.resolve()
function serialized<T>(work: () => Promise<T>): Promise<T> {
@@ -66,9 +74,9 @@ async function renderMermaidNow(
options: { theme?: 'light' | 'dark'; mode?: 'interactive' | 'static' } = {}
): Promise<MermaidRenderResult> {
const theme = options.theme ?? 'light'
ensureInitialized(theme)
const id = `mermaid-${Date.now()}-${++renderCounter}`
try {
const mermaid = await ensureInitialized(theme)
const result = await mermaid.render(id, source)
const parser = new DOMParser()
const doc = parser.parseFromString(result.svg, 'image/svg+xml')
@@ -131,7 +139,7 @@ export function useMermaidTheme() {
export async function validateMermaid(source: string): Promise<{ valid: boolean; error?: MermaidParseError }> {
try {
await serialized(async () => { ensureInitialized('light'); await mermaid.parse(source) })
await serialized(async () => { const mermaid = await ensureInitialized('light'); await mermaid.parse(source) })
return { valid: true }
} catch (error) {
const message = error instanceof Error ? error.message : '未知错误'
+1 -1
View File
@@ -25,7 +25,7 @@ export async function createNote(data: {
export async function updateNote(
noteId: string,
data: { title?: string; markdown?: string; tags?: string[] }
data: { title?: string; markdown?: string; tags?: string[]; expected_content_hash?: string }
): Promise<ApiNote> {
return apiClient.patch(`/api/notes/${noteId}`, data)
}
+11 -2
View File
@@ -361,7 +361,7 @@ export const mockCommunityThemes: ThemeManifest[] = [
{
theme_id: 'ocean-blue',
name: 'Ocean Blue',
version: '1.3.1',
version: '1.6.0',
author: 'community',
description: '宁静的海洋蓝色主题,适合长时间阅读',
min_app_version: '0.2.0',
@@ -373,7 +373,7 @@ export const mockCommunityThemes: ThemeManifest[] = [
{
theme_id: 'midnight-purple',
name: 'Midnight Purple',
version: '2.1.1',
version: '2.4.0',
author: 'night-owl',
description: '深紫色暗夜主题,适合编码',
min_app_version: '0.2.0',
@@ -464,6 +464,15 @@ export function getCommunityThemePreviewCss(themeId: string): string {
return buildCommunityThemeCss(themeId, t.is_dark) + `
[data-theme="${themeId}"] {
color-scheme: ${t.is_dark ? 'dark' : 'light'};
--color-markdown-selection: ${t.is_dark ? '#443252' : '#d4eaf5'};
--color-editor-scroll-background: var(--color-surface-elevated);
--color-editor-scroll-text: var(--color-accent-primary);
--color-callout-info: ${t.is_dark ? '#9dbbff' : '#126589'};
--color-callout-success: ${t.is_dark ? '#a7d58c' : '#267049'};
--color-callout-warning: ${t.is_dark ? '#efc886' : '#885c13'};
--color-callout-danger: ${t.is_dark ? '#ff9caf' : '#b13d4d'};
--color-callout-important: ${t.is_dark ? '#d4afff' : '#7050a3'};
--color-callout-quote: ${t.is_dark ? '#b0b9dd' : '#53697d'};
--color-text-inverse: ${t.is_dark ? '#1a1b26' : '#ffffff'};
--color-text-disabled: color-mix(in srgb, var(--color-text-primary) 45%, var(--color-surface-primary));
--color-background-overlay: ${t.is_dark ? '#000000a6' : '#00000073'};
+8 -2
View File
@@ -19,6 +19,7 @@ export interface VaultInfo {
}
let cachedTree: FileNode[] | null = null
let treeRequestVersion = 0
const noteIdByPath = new Map<string, string>()
const typeByPath = new Map<string, FileNode['type']>()
@@ -88,6 +89,7 @@ export async function getRecentVaults(): Promise<VaultInfo[]> {
}
export async function openVault(path: string): Promise<VaultInfo> {
treeRequestVersion++
const snapshot = await apiClient.post<ApiWorkspaceSnapshot>('/api/workspace/open', { path }, { timeoutMs: 15000 })
cacheEntries(snapshot.items)
return {
@@ -104,7 +106,9 @@ export async function createVault(path: string, name: string): Promise<VaultInfo
}
export async function refreshTree(): Promise<FileNode[]> {
const entries = await apiClient.get<ApiWorkspaceEntry[]>('/api/workspace/tree')
const version = ++treeRequestVersion
const entries = await apiClient.get<ApiWorkspaceEntry[]>('/api/workspace/tree', { timeoutMs: 10000 })
if (version !== treeRequestVersion) return cachedTree ?? []
return cacheEntries(entries)
}
@@ -122,10 +126,12 @@ export async function getNoteId(filePath: string): Promise<string> {
return requireNoteId(filePath)
}
export async function saveFileContent(filePath: string, content: string): Promise<void> {
export async function saveFileContent(filePath: string, content: string, expectedContent?: string): Promise<void> {
const metadata = splitNoteMetadata(content)
const expectedHash = expectedContent === undefined ? undefined : Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(expectedContent)))).map(byte => byte.toString(16).padStart(2, '0')).join('')
await noteService.updateNote(await requireNoteId(filePath), {
markdown: content,
...(expectedHash ? { expected_content_hash: expectedHash } : {}),
// Explicit [] clears the index; absent tags retain API-managed tags.
...(metadata?.hasTags ? { tags: metadata.tags } : {}),
})
+15 -2
View File
@@ -58,9 +58,22 @@ export const useAgentStore = defineStore('agent', () => {
tools.value = await agentService.listTools()
}
let listVersion = 0
async function loadRuns() {
const resp = await agentService.listAgentRuns()
runs.value = resp.items
const version = ++listVersion
const items: AgentRun[] = []
let offset = 0
do {
const resp = await agentService.listAgentRuns({ limit: 100, offset })
if (version !== listVersion) return
items.push(...resp.items)
offset += resp.items.length
if (!resp.items.length || offset >= resp.total) break
} while (true)
const active = runs.value.find(run => run.run_id === activeRunId.value)
const merged = new Map(items.map(item => [item.run_id, item]))
if (active && !merged.has(active.run_id)) merged.set(active.run_id, active)
runs.value = [...merged.values()]
}
async function loadRun(runId: string) {
+50 -7
View File
@@ -3,10 +3,13 @@ import { ref, computed } from 'vue'
import type { SaveStatus } from '@/contracts'
import * as workspaceService from '@/services/workspaceService'
import { t } from '@/i18n'
import { ApiErrorClass } from '@/services/apiClient'
export const useEditorStore = defineStore('editor', () => {
const mode = ref<'wysiwyg' | 'source'>('wysiwyg')
const content = ref('')
const contentRevision = ref(0)
let diskContent: string | undefined
const saveStatus = ref<SaveStatus>('idle')
const lastSavedAt = ref<string | null>(null)
const currentNoteId = ref<string | null>(null)
@@ -35,13 +38,14 @@ export const useEditorStore = defineStore('editor', () => {
function updateContent(newContent: string) {
content.value = newContent
saveStatus.value = 'dirty'
if (saveStatus.value !== 'conflict' && saveStatus.value !== 'external_changed') saveStatus.value = 'dirty'
}
let saveTimer: ReturnType<typeof setTimeout> | null = null
let pendingSave: Promise<void> | null = null
function scheduleAutoSave(delay = 1500) {
if (saveStatus.value === 'conflict' || saveStatus.value === 'external_changed') return
if (saveTimer) clearTimeout(saveTimer)
saveTimer = setTimeout(() => {
saveTimer = null
@@ -51,20 +55,23 @@ export const useEditorStore = defineStore('editor', () => {
async function save() {
if (!currentFilePath.value) return
if (saveStatus.value === 'conflict' || saveStatus.value === 'external_changed') return
if (pendingSave) return pendingSave
// 保存路径与正文都取快照;请求完成时用户可能已继续输入或切换文件。
const targetPath = currentFilePath.value
const snapshot = content.value
const baseline = diskContent
saveStatus.value = 'saving'
pendingSave = (async () => {
try {
await workspaceService.saveFileContent(targetPath, snapshot)
await workspaceService.saveFileContent(targetPath, snapshot, baseline)
if (currentFilePath.value === targetPath) {
diskContent = snapshot
saveStatus.value = content.value === snapshot ? 'saved' : 'dirty'
lastSavedAt.value = new Date().toISOString()
}
} catch {
if (currentFilePath.value === targetPath) saveStatus.value = 'save_failed'
} catch (error) {
if (currentFilePath.value === targetPath) saveStatus.value = error instanceof ApiErrorClass && error.code === 'NOTE_CONTENT_CONFLICT' ? 'conflict' : 'save_failed'
} finally {
pendingSave = null
if (currentFilePath.value === targetPath && saveStatus.value === 'dirty') scheduleAutoSave()
@@ -86,7 +93,7 @@ export const useEditorStore = defineStore('editor', () => {
}
if (pendingSave) await pendingSave
if (saveStatus.value === 'dirty' || saveStatus.value === 'save_failed') await save()
if (saveStatus.value === 'dirty' || saveStatus.value === 'save_failed') {
if (['dirty', 'save_failed', 'conflict', 'external_changed'].includes(saveStatus.value)) {
throw new Error(t('当前文件保存失败,已阻止切换以避免内容丢失。', 'The current file could not be saved. Switching was blocked to prevent data loss.'))
}
// 版本号使较慢的旧读取不能覆盖用户后选择的新文件。
@@ -102,6 +109,7 @@ export const useEditorStore = defineStore('editor', () => {
currentFilePath.value = filePath
currentNoteId.value = loadedNoteId
content.value = loadedContent
diskContent = loadedContent
saveStatus.value = 'saved'
lastSavedAt.value = new Date().toISOString()
} catch (error) {
@@ -122,14 +130,44 @@ export const useEditorStore = defineStore('editor', () => {
}
function setExternalChanged() {
if (saveStatus.value === 'dirty') {
if (saveTimer) { clearTimeout(saveTimer); saveTimer = null }
if (saveStatus.value === 'dirty' || saveStatus.value === 'save_failed' || saveStatus.value === 'conflict') {
saveStatus.value = 'conflict'
} else {
saveStatus.value = 'external_changed'
}
}
// TODO(editor): 桌面文件监听接入后提供冲突对比/合并界面,而非只阻止切换。
async function checkExternalFile() {
if (!currentFilePath.value || pendingSave || diskContent === undefined || saveStatus.value === 'conflict') return
const path = currentFilePath.value, baseline = diskContent
try {
const latest = await workspaceService.readFileContent(path)
if (path !== currentFilePath.value || pendingSave || diskContent !== baseline || latest === baseline) return
if (content.value === baseline && saveStatus.value === 'saved') {
content.value = latest; diskContent = latest; contentRevision.value++
} else {
setExternalChanged(); saveStatus.value = 'conflict'
}
} catch { /* Tree polling reports missing files; transient network errors retain edits. */ }
}
async function reloadExternalFile() {
const path = currentFilePath.value, snapshot = content.value
if (!path || pendingSave) return
const latest = await workspaceService.readFileContent(path)
if (path !== currentFilePath.value || content.value !== snapshot || pendingSave) return
if (saveTimer) { clearTimeout(saveTimer); saveTimer = null }
content.value = latest; diskContent = latest; saveStatus.value = 'saved'; contentRevision.value++
}
async function discardExternalChanges(path: string, snapshot: string): Promise<boolean> {
if (pendingSave) await pendingSave
if (currentFilePath.value !== path || content.value !== snapshot) return false
closeFile()
return true
}
function closeFile() {
loadVersion++
@@ -137,6 +175,7 @@ export const useEditorStore = defineStore('editor', () => {
currentFilePath.value = null
currentNoteId.value = null
content.value = ''
diskContent = undefined
saveStatus.value = 'idle'
lastSavedAt.value = null
highlightBlockId.value = null
@@ -153,6 +192,10 @@ export const useEditorStore = defineStore('editor', () => {
jumpToHeading,
mode,
content,
contentRevision,
checkExternalFile,
reloadExternalFile,
discardExternalChanges,
saveStatus,
lastSavedAt,
currentNoteId,

Some files were not shown because too many files have changed in this diff Show More