Files
mnote/rust/crates/mnote-web/src/routes/hermes_tools.rs
T

1637 lines
64 KiB
Rust
Raw Normal View History

use super::hermes_client;
2026-05-14 15:10:33 +08:00
use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use crate::hermes_tools::{artifact, block, doc, manifest, page, ToolCallInput};
2026-05-14 15:10:33 +08:00
use axum::extract::{Extension, Query, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::Json;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::env;
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use tracing::{info, warn};
const HEADER_MNOTE_WEB_OWNER: &str = "x-mnote-web-owner";
const HEADER_HERMES_TOOL_OWNER: &str = "x-mnote-hermes-tool-owner";
pub async fn mnote_audit(
Extension(context): Extension<RequestContext>,
Query(query): Query<HashMap<String, String>>,
) -> Result<(StatusCode, HeaderMap, Json<Value>), WebError> {
ensure_authenticated(&context)?;
let trace_id = query.get("traceId").map(String::as_str);
let tool_call_id = query.get("toolCallId").map(String::as_str);
let persisted_only = query
.get("persistedOnly")
.map(|value| value == "true" || value == "1")
.unwrap_or(false);
let events = if persisted_only {
audit_persisted_events(trace_id, tool_call_id)
} else {
audit_events(trace_id, tool_call_id)
};
Ok((
StatusCode::OK,
stamp_tool_headers(),
Json(json!({
"ok": true,
"traceId": context.trace.trace_id,
"auditStore": if persisted_only { "jsonl" } else { "memory" },
"events": events
})),
))
}
pub async fn mnote_manifest(
Extension(context): Extension<RequestContext>,
) -> Result<(StatusCode, HeaderMap, Json<Value>), WebError> {
ensure_authenticated(&context)?;
Ok((
StatusCode::OK,
stamp_tool_headers(),
Json(json!({
"ok": true,
"traceId": context.trace.trace_id,
"manifest": manifest::manifest()
})),
))
}
pub async fn mnote_call(
State(state): State<AppState>,
Extension(context): Extension<RequestContext>,
Json(input): Json<ToolCallInput>,
) -> Result<(StatusCode, HeaderMap, Json<Value>), WebError> {
2026-05-16 12:34:48 +08:00
let context = authenticated_tool_context(&context, &input)?;
2026-05-14 15:10:33 +08:00
let trace_id = input
.effective_trace_id(&context.trace.trace_id)
.to_string();
let tool_call_id = input.effective_tool_call_id();
let workspace_id = input.effective_workspace_id();
let document_id = input.effective_document_id();
let dry_run = input.dry_run.unwrap_or(false);
let effect = if dry_run {
"dry_run"
} else if is_read_tool(&input.tool_name) {
2026-05-14 15:10:33 +08:00
"read"
} else {
"write"
};
let idempotency_key = idempotency_cache_key(
&input,
workspace_id.as_deref(),
document_id.as_deref(),
dry_run,
);
info!(
trace_id = %trace_id,
session_id = input.session_id.as_deref().unwrap_or(""),
run_id = input.run_id.as_deref().unwrap_or(""),
tool_call_id = %tool_call_id,
tool_name = %input.tool_name,
workspace_id = workspace_id.as_deref().unwrap_or(""),
document_id = document_id.as_deref().unwrap_or(""),
actor_id = input.actor_id.as_deref().unwrap_or(""),
dry_run,
"mnote Hermes tool call started"
);
let profile = input
.profile
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| input.arg_string("profile"))
.or_else(hermes_client::active_profile_name)
.unwrap_or_else(|| "default".into());
2026-05-14 15:10:33 +08:00
audit_push(json!({
"phase": "started",
"traceId": trace_id,
"sessionId": input.session_id,
"runId": input.run_id,
"toolCallId": tool_call_id,
"toolName": input.tool_name,
"workspaceId": workspace_id,
"documentId": document_id,
"actorId": input.actor_id,
"dryRun": dry_run
2026-05-14 15:10:33 +08:00
}));
if hermes_client::is_mnote_tool_disabled(&profile, &input.tool_name) {
let error = WebError::new(
StatusCode::FORBIDDEN,
"mnote_tool_disabled",
"当前 Hermes profile 已关闭该 mnote tool",
)
.with_context(&context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_TOOL_OWNER, "mnote-web-hermes-tools");
audit_push(json!({
"phase": "failed",
"traceId": trace_id,
"sessionId": input.session_id,
"runId": input.run_id,
"toolCallId": tool_call_id,
"toolName": input.tool_name,
"workspaceId": workspace_id,
"documentId": document_id,
"actorId": input.actor_id,
"profile": profile,
"status": error.status().as_u16(),
"message": error.message()
}));
return Err(error);
}
2026-05-14 15:10:33 +08:00
if let Err(error) = ensure_workspace_context(&context, workspace_id.as_deref()) {
audit_push(json!({
"phase": "failed",
"traceId": trace_id,
"sessionId": input.session_id,
"runId": input.run_id,
"toolCallId": tool_call_id,
"toolName": input.tool_name,
"workspaceId": workspace_id,
"documentId": document_id,
"actorId": input.actor_id,
"status": error.status().as_u16(),
"message": error.message()
}));
return Err(error);
}
if let Some(cached) = idempotency_key.as_deref().and_then(idempotency_cache_get) {
info!(
trace_id = %trace_id,
session_id = input.session_id.as_deref().unwrap_or(""),
run_id = input.run_id.as_deref().unwrap_or(""),
tool_call_id = %tool_call_id,
tool_name = %input.tool_name,
workspace_id = workspace_id.as_deref().unwrap_or(""),
document_id = document_id.as_deref().unwrap_or(""),
actor_id = input.actor_id.as_deref().unwrap_or(""),
"mnote Hermes tool call idempotency replay"
);
audit_push(json!({
"phase": "idempotency_replay",
"traceId": trace_id,
"sessionId": cached.get("sessionId").cloned().unwrap_or(Value::Null),
"runId": cached.get("runId").cloned().unwrap_or(Value::Null),
"toolCallId": cached.get("toolCallId").cloned().unwrap_or(Value::Null),
"toolName": cached.get("toolName").cloned().unwrap_or(Value::Null),
"audit": cached.get("audit").cloned().unwrap_or(Value::Null)
}));
return Ok((StatusCode::OK, stamp_tool_headers(), Json(cached)));
}
let result = match input.tool_name.as_str() {
"mnote.doc.fetch" => doc::doc_fetch(&state, &context, &input).await,
"mnote.doc.find" => doc::doc_find(&state, &context, &input).await,
"mnote.doc.plan_update" => doc::plan_update(&state, &context, &input).await,
"mnote.block.fetch" => block::block_fetch(&state, &context, &input).await,
"mnote.block.replace" => block::block_replace(&state, &context, &input).await,
"mnote.block.insert_after" => block::block_insert_after(&state, &context, &input).await,
"mnote.block.delete" => block::block_delete(&state, &context, &input).await,
"mnote.block.move_after" => block::block_move_after(&state, &context, &input).await,
"mnote.doc.apply_block_ops" => block::doc_apply_block_ops(&state, &context, &input).await,
2026-05-17 16:15:52 +08:00
"mnote.doc.markdown_edit" => doc::doc_markdown_edit(&state, &context, &input).await,
2026-05-14 15:10:33 +08:00
"mnote.page.get" => page::page_get(&state, &context, &input).await,
"mnote.page.save" => page::page_save(&state, &context, &input).await,
"mnote.page.update_title" => page::update_title(&state, &context, &input).await,
"mnote.page.update_options" => page::update_options(&state, &context, &input).await,
"mnote.artifact.create_summary" => artifact::create_summary(&state, &context, &input).await,
"mnote.artifact.create_ai_note" => artifact::create_ai_note(&state, &context, &input).await,
_ => Err(
WebError::bad_request_code("mnote_tool_unknown", "未知 mnote Hermes tool")
.with_context(&context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_TOOL_OWNER, "mnote-web-hermes-tools"),
),
};
if let Err(error) = &result {
warn!(
trace_id = %trace_id,
session_id = input.session_id.as_deref().unwrap_or(""),
run_id = input.run_id.as_deref().unwrap_or(""),
tool_call_id = %tool_call_id,
tool_name = %input.tool_name,
workspace_id = workspace_id.as_deref().unwrap_or(""),
document_id = document_id.as_deref().unwrap_or(""),
actor_id = input.actor_id.as_deref().unwrap_or(""),
status = %error.status(),
message = %error.message(),
"mnote Hermes tool call failed"
);
audit_push(json!({
"phase": "failed",
"traceId": trace_id,
"sessionId": input.session_id,
"runId": input.run_id,
"toolCallId": tool_call_id,
"toolName": input.tool_name,
"workspaceId": workspace_id,
"documentId": document_id,
"actorId": input.actor_id,
"status": error.status().as_u16(),
"message": error.message()
}));
}
let result = result?;
let command_id = result.get("commandId").cloned().unwrap_or(Value::Null);
info!(
trace_id = %trace_id,
session_id = input.session_id.as_deref().unwrap_or(""),
run_id = input.run_id.as_deref().unwrap_or(""),
tool_call_id = %tool_call_id,
tool_name = %input.tool_name,
workspace_id = workspace_id.as_deref().unwrap_or(""),
document_id = document_id.as_deref().unwrap_or(""),
actor_id = input.actor_id.as_deref().unwrap_or(""),
effect,
"mnote Hermes tool call completed"
);
let response_body = json!({
"ok": true,
"toolName": input.tool_name,
"toolCallId": tool_call_id,
"traceId": trace_id,
"sessionId": input.session_id,
"runId": input.run_id,
"result": result,
"audit": {
"effect": effect,
"commandId": command_id,
"workspaceId": workspace_id,
"documentId": document_id,
"actorId": input.actor_id,
"dryRun": dry_run,
"idempotencyKey": input.idempotency_key,
"capabilityScope": input.capability_scope
},
"error": null
});
if let Some(key) = idempotency_key {
idempotency_cache_put(key, response_body.clone());
}
audit_push(json!({
"phase": "completed",
"traceId": response_body.get("traceId").cloned().unwrap_or(Value::Null),
"sessionId": response_body.get("sessionId").cloned().unwrap_or(Value::Null),
"runId": response_body.get("runId").cloned().unwrap_or(Value::Null),
"toolCallId": response_body.get("toolCallId").cloned().unwrap_or(Value::Null),
"toolName": response_body.get("toolName").cloned().unwrap_or(Value::Null),
"audit": response_body.get("audit").cloned().unwrap_or(Value::Null)
}));
Ok((StatusCode::OK, stamp_tool_headers(), Json(response_body)))
}
fn is_read_tool(tool_name: &str) -> bool {
matches!(
tool_name,
"mnote.page.get" | "mnote.doc.fetch" | "mnote.doc.find" | "mnote.block.fetch"
)
}
2026-05-14 15:10:33 +08:00
fn audit_log() -> &'static Mutex<Vec<Value>> {
static LOG: OnceLock<Mutex<Vec<Value>>> = OnceLock::new();
LOG.get_or_init(|| Mutex::new(Vec::new()))
}
fn audit_push(event: Value) {
if let Ok(mut log) = audit_log().lock() {
log.push(event.clone());
let overflow = log.len().saturating_sub(500);
if overflow > 0 {
log.drain(0..overflow);
}
}
if let Err(error) = audit_append_persistent(&event) {
warn!(message = %error, "mnote Hermes tool audit 持久化失败");
}
}
fn audit_events(trace_id: Option<&str>, tool_call_id: Option<&str>) -> Vec<Value> {
let Ok(log) = audit_log().lock() else {
return Vec::new();
};
log.iter()
.filter(|event| {
trace_id
.map(|expected| event.get("traceId").and_then(Value::as_str) == Some(expected))
.unwrap_or(true)
})
.filter(|event| {
tool_call_id
.map(|expected| event.get("toolCallId").and_then(Value::as_str) == Some(expected))
.unwrap_or(true)
})
.cloned()
.collect()
}
fn audit_log_path() -> PathBuf {
env::var("MNOTE_HERMES_TOOL_AUDIT_LOG")
.ok()
.filter(|value| !value.trim().is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("tmp").join("mnote-hermes-tool-audit.jsonl"))
}
fn audit_append_persistent(event: &Value) -> Result<(), String> {
let path = audit_log_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.map_err(|error| error.to_string())?;
let line = serde_json::to_string(event).map_err(|error| error.to_string())?;
writeln!(file, "{line}").map_err(|error| error.to_string())
}
fn audit_persisted_events(trace_id: Option<&str>, tool_call_id: Option<&str>) -> Vec<Value> {
let path = audit_log_path();
let Ok(file) = File::open(path) else {
return Vec::new();
};
BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| serde_json::from_str::<Value>(&line).ok())
.filter(|event| {
trace_id
.map(|expected| event.get("traceId").and_then(Value::as_str) == Some(expected))
.unwrap_or(true)
})
.filter(|event| {
tool_call_id
.map(|expected| event.get("toolCallId").and_then(Value::as_str) == Some(expected))
.unwrap_or(true)
})
.collect()
}
fn idempotency_cache() -> &'static Mutex<HashMap<String, Value>> {
static CACHE: OnceLock<Mutex<HashMap<String, Value>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
fn idempotency_cache_key(
input: &ToolCallInput,
workspace_id: Option<&str>,
document_id: Option<&str>,
dry_run: bool,
) -> Option<String> {
if dry_run || is_read_tool(&input.tool_name) {
2026-05-14 15:10:33 +08:00
return None;
}
let idempotency_key = input.idempotency_key.as_deref()?.trim();
if idempotency_key.is_empty() {
return None;
}
Some(format!(
"{}|{}|{}|{}",
input.tool_name,
workspace_id.unwrap_or(""),
document_id.unwrap_or(""),
idempotency_key
))
}
fn idempotency_cache_get(key: &str) -> Option<Value> {
idempotency_cache().lock().ok()?.get(key).cloned()
}
fn idempotency_cache_put(key: String, response: Value) {
if let Ok(mut cache) = idempotency_cache().lock() {
cache.insert(key, response);
}
}
fn ensure_authenticated(context: &RequestContext) -> Result<(), WebError> {
let actor = context.auth.actor_id.trim();
let has_actor = actor != "anonymous" && actor != "hermes" && !actor.is_empty();
2026-05-14 15:10:33 +08:00
if has_actor || context.auth.authorization.is_some() || context.auth.cookie_header.is_some() {
return Ok(());
}
Err(WebError::new(
StatusCode::UNAUTHORIZED,
"mnote_tool_unauthorized",
"mnote Hermes tool 需要登录后访问",
)
.with_context(context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_TOOL_OWNER, "mnote-web-hermes-tools"))
}
2026-05-16 12:34:48 +08:00
fn authenticated_tool_context(
context: &RequestContext,
input: &ToolCallInput,
) -> Result<RequestContext, WebError> {
let context_actor = context.auth.actor_id.trim();
if !context_actor.is_empty() && context_actor != "anonymous" && context_actor != "hermes" {
2026-05-16 12:34:48 +08:00
return Ok(context.clone());
}
let has_cookie_or_auth =
context.auth.authorization.is_some() || context.auth.cookie_header.is_some();
2026-05-16 12:34:48 +08:00
let actor_id = input
.actor_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty() && *value != "anonymous" && *value != "hermes")
2026-05-16 12:34:48 +08:00
.ok_or_else(|| {
WebError::new(
StatusCode::UNAUTHORIZED,
"mnote_tool_unauthorized",
"mnote Hermes tool 需要有效 actorId,不能使用 hermes/anonymous",
2026-05-16 12:34:48 +08:00
)
.with_context(context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_TOOL_OWNER, "mnote-web-hermes-tools")
})?;
if has_cookie_or_auth {
let mut next = context.clone();
next.auth.actor_id = actor_id.to_string();
next.auth.actor_type = input
.arg_string("actorType")
.or_else(|| input.arg_string("actor_type"))
.unwrap_or_else(|| "user".into());
if next.auth.session_id.is_none() {
next.auth.session_id = input.session_id.clone();
}
return Ok(next);
}
2026-05-16 12:34:48 +08:00
let has_run_identity = input
.session_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.is_some()
&& input
.run_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.is_some()
&& input
.tool_call_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.is_some()
&& input
.trace_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.is_some();
if !has_run_identity {
return Err(WebError::new(
StatusCode::UNAUTHORIZED,
"mnote_tool_unauthorized",
"mnote Hermes tool 委托调用缺少 sessionId/runId/toolCallId/traceId",
)
.with_context(context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_TOOL_OWNER, "mnote-web-hermes-tools"));
}
let mut next = context.clone();
next.auth.actor_id = actor_id.to_string();
next.auth.actor_type = "user".into();
if next.auth.session_id.is_none() {
next.auth.session_id = input.session_id.clone();
}
Ok(next)
}
2026-05-14 15:10:33 +08:00
fn ensure_workspace_context(
context: &RequestContext,
input_workspace_id: Option<&str>,
) -> Result<(), WebError> {
let Some(input_workspace_id) = input_workspace_id
.map(str::trim)
.filter(|value| !value.is_empty())
else {
return Ok(());
};
let Some(header_workspace_id) = context
.workspace
.workspace_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
else {
return Ok(());
};
if input_workspace_id == header_workspace_id {
return Ok(());
}
Err(WebError::new(
StatusCode::FORBIDDEN,
"workspace_context_conflict",
"mnote Hermes tool 请求的 workspaceId 与请求上下文不一致",
)
.with_context(context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_TOOL_OWNER, "mnote-web-hermes-tools"))
}
fn stamp_tool_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
if let Ok(name) = HeaderName::from_lowercase(HEADER_MNOTE_WEB_OWNER.as_bytes()) {
headers.insert(name, HeaderValue::from_static("mnote-web"));
}
if let Ok(name) = HeaderName::from_lowercase(HEADER_HERMES_TOOL_OWNER.as_bytes()) {
headers.insert(name, HeaderValue::from_static("mnote-web-hermes-tools"));
}
headers
}
#[cfg(test)]
mod tests {
use crate::app::{build_app, AppConfig, AppState};
use axum::body::{to_bytes, Body};
use axum::http::{Request, StatusCode};
use serde_json::{json, Value};
use std::fs;
use std::sync::{Mutex, OnceLock};
2026-05-14 15:10:33 +08:00
use tower::util::ServiceExt;
fn env_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
2026-05-14 15:10:33 +08:00
fn app() -> axum::Router {
build_app(AppState::new(AppConfig {
service_name: "mnote-web".into(),
service_version: "0.1.0".into(),
bind_addr: "127.0.0.1:0".into(),
public_bind_addr: "127.0.0.1:3000".into(),
legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
enable_legacy_next_compat: true,
enable_debug_shell_routes: false,
enable_editor_actor: true,
2026-05-14 15:10:33 +08:00
hermes_base_path: "/api/hermes".into(),
compat_next_base_path: "/api/compat/next".into(),
convex_url: None,
convex_admin_key: None,
allow_dev_fixtures: true,
query_fixtures_json: Some(
r#"{
"documents:getMeta": {
"id": "doc_1",
"workspace_id": "ws_demo",
"title": "服务端页面",
"can_edit": true,
"wide_layout": false,
"use_small_text": false,
"show_toc": true,
"block_count": 1
},
"documents:getContent": {
"title": "服务端页面",
"content": [
{
"id": "heading_1",
"type": "heading",
"props": { "level": 1 },
"content": [{ "type": "text", "text": "章节一" }]
},
{
"id": "p_1",
"type": "paragraph",
"content": [{ "type": "text", "text": "第一段" }]
},
{
"id": "p_2",
"type": "paragraph",
"content": [{ "type": "text", "text": "第二段" }]
2026-05-14 15:10:33 +08:00
}
],
"revision": 7,
"conflict_detection_key": "doc_1:7"
}
}"#
.into(),
),
mutation_fixtures_json: Some(
r#"{
"documents:updateContent": {"ok": true, "revision": 8, "conflict_detection_key": "doc_1:8"},
"bridgeLogs:recordCommandLog": {"ok": true, "id": "cmd_log_fixture"},
"bridgeLogs:recordDomainEvent": {"ok": true, "id": "event_fixture"}
}"#
.into(),
),
2026-05-14 15:10:33 +08:00
dev_user_id: "dev-user".into(),
dev_user_name: "开发用户".into(),
dev_user_email: "dev@mnote.local".into(),
}))
}
async fn call_tool_ok(payload: Value) -> Value {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(payload.to_string()))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
serde_json::from_slice(&body).expect("json")
}
async fn block_revision_ref(block_id: &str) -> String {
let payload = call_tool_ok(json!({
"toolName": "mnote.doc.fetch",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_ref",
"runId": "run_ref",
"toolCallId": format!("call_ref_{block_id}"),
"traceId": format!("trace_ref_{block_id}"),
"capabilityScope": ["page.read"],
"args": {"scope": "full", "detail": "with_ids"}
}))
.await;
payload["result"]["blocks"]
.as_array()
.expect("blocks")
.iter()
.find(|block| block["blockId"] == json!(block_id))
.and_then(|block| block["revisionRef"].as_str())
.expect("revisionRef")
.to_string()
}
2026-05-14 15:10:33 +08:00
#[tokio::test]
async fn hermes_tools_manifest_returns_first_batch_tools() {
let response = app()
.oneshot(
Request::builder()
.uri("/api/hermes/tools/mnote/manifest")
.header("x-mnote-actor-id", "user_1")
.body(Body::empty())
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
let tools = payload["manifest"]["tools"].as_array().expect("tools");
assert!(tools.iter().any(|tool| tool["name"] == "mnote.page.get"));
assert!(tools.iter().any(|tool| tool["name"] == "mnote.page.save"));
assert!(tools.iter().any(|tool| tool["name"] == "mnote.doc.fetch"));
assert!(tools.iter().any(|tool| tool["name"] == "mnote.doc.find"));
assert!(tools.iter().any(|tool| tool["name"] == "mnote.block.fetch"));
assert!(tools
.iter()
.any(|tool| tool["name"] == "mnote.doc.plan_update"));
assert!(tools
.iter()
.any(|tool| tool["name"] == "mnote.block.replace"));
assert!(tools
.iter()
.any(|tool| tool["name"] == "mnote.block.insert_after"));
assert!(tools
.iter()
.any(|tool| tool["name"] == "mnote.block.delete"));
assert!(tools
.iter()
.any(|tool| tool["name"] == "mnote.block.move_after"));
assert!(tools
.iter()
.any(|tool| tool["name"] == "mnote.doc.apply_block_ops"));
2026-05-16 12:34:48 +08:00
let page_save = tools
.iter()
.find(|tool| tool["name"] == "mnote.page.save")
.expect("page save tool");
assert_eq!(page_save["status"], "available");
2026-05-14 15:10:33 +08:00
assert_eq!(
payload["manifest"]["schemaVersion"],
"mnote.hermes_tool_manifest.v1"
);
}
#[tokio::test]
async fn hermes_tools_page_get_requires_auth() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.body(Body::from(
json!({"toolName":"mnote.page.get","documentId":"doc_1"}).to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
2026-05-16 12:34:48 +08:00
#[tokio::test]
async fn hermes_tools_page_get_accepts_delegated_actor_from_hermes_payload() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.body(Body::from(
json!({
"toolName": "mnote.page.get",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"actorId": "user_hermes",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"capabilityScope": ["page.read"]
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["audit"]["actorId"], "user_hermes");
assert_eq!(payload["result"]["title"], "服务端页面");
}
#[tokio::test]
async fn hermes_tools_call_rejects_profile_disabled_tool() {
let _guard = env_lock().lock().expect("env lock");
let hermes_home = std::env::temp_dir().join(format!(
"mnote-web-hermes-tool-disabled-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&hermes_home);
let profile_dir = hermes_home.join("profiles").join("blocked");
fs::create_dir_all(&profile_dir).expect("profile dir");
fs::write(
profile_dir.join("config.yaml"),
"mnote:\n tools:\n disabled:\n - mnote.page.get\n",
)
.expect("profile config");
std::env::set_var("HERMES_HOME", &hermes_home);
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.page.get",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_disabled",
"runId": "run_disabled",
"toolCallId": "call_disabled",
"traceId": "trace_disabled",
"profile": "blocked",
"capabilityScope": ["page.read"]
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::FORBIDDEN);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["code"], "mnote_tool_disabled");
std::env::remove_var("HERMES_HOME");
let _ = fs::remove_dir_all(&hermes_home);
}
2026-05-14 15:10:33 +08:00
#[tokio::test]
async fn hermes_tools_write_tools_require_auth() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.body(Body::from(
json!({
"toolName": "mnote.page.save",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"idempotencyKey": "idem_1",
"dryRun": false,
"args": {"content": []}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn hermes_tools_page_get_returns_page_aggregate_summary() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.page.get",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"capabilityScope": ["page.read"]
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["toolName"], "mnote.page.get");
assert_eq!(payload["toolCallId"], "call_1");
assert_eq!(payload["result"]["title"], "服务端页面");
assert!(payload["result"]["bodySummary"]
.as_str()
.unwrap_or_default()
.contains("章节一"));
assert_eq!(payload["audit"]["effect"], "read");
}
#[tokio::test]
async fn hermes_tools_doc_fetch_returns_block_projection() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.doc.fetch",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_doc_fetch_1",
"traceId": "trace_doc_fetch_1",
"capabilityScope": ["page.read"],
"args": {"scope": "full", "detail": "with_ids"}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["toolName"], "mnote.doc.fetch");
assert_eq!(payload["audit"]["effect"], "read");
assert_eq!(payload["result"]["revision"], json!(7));
assert_eq!(
payload["result"]["blocks"][0]["blockId"],
json!("heading_1")
);
assert_eq!(payload["result"]["blocks"][0]["text"], json!("章节一"));
assert!(payload["result"]["blocks"][0]["revisionRef"]
.as_str()
.unwrap_or_default()
.starts_with("pageRev:7:block:heading_1:hash:"));
}
#[tokio::test]
async fn hermes_tools_doc_fetch_supports_selection_and_page_xml() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.doc.fetch",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_doc_fetch_selection_1",
"traceId": "trace_doc_fetch_selection_1",
"capabilityScope": ["page.read"],
"args": {
"scope": "selection",
"selectedBlockIds": ["heading_1"],
"format": "page_xml"
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["result"]["schema"], "mnote.page_ai_context.v1");
assert_eq!(payload["result"]["scope"], "selection");
assert_eq!(payload["result"]["format"], "page_xml");
assert_eq!(payload["result"]["blocks"].as_array().unwrap().len(), 1);
assert!(payload["result"]["content"]
.as_str()
.unwrap_or_default()
.contains("<block id=\"heading_1\""));
assert_eq!(payload["result"]["allowedTargetBlockIds"][0], "heading_1");
}
#[tokio::test]
async fn hermes_tools_doc_find_and_block_fetch_use_block_projection() {
let find_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.doc.find",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_doc_find_1",
"traceId": "trace_doc_find_1",
"capabilityScope": ["page.read"],
"args": {"query": "章节一"}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(find_response.status(), StatusCode::OK);
let find_body = to_bytes(find_response.into_body(), usize::MAX)
.await
.expect("body");
let find_payload: Value = serde_json::from_slice(&find_body).expect("json");
assert_eq!(
find_payload["result"]["matches"][0]["blockId"],
json!("heading_1")
);
let fetch_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.fetch",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_block_fetch_1",
"traceId": "trace_block_fetch_1",
"capabilityScope": ["block.read"],
"args": {"blockId": "heading_1", "contextBefore": 1, "contextAfter": 1}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(fetch_response.status(), StatusCode::OK);
let fetch_body = to_bytes(fetch_response.into_body(), usize::MAX)
.await
.expect("body");
let fetch_payload: Value = serde_json::from_slice(&fetch_body).expect("json");
assert_eq!(
fetch_payload["result"]["block"]["blockId"],
json!("heading_1")
);
assert_eq!(fetch_payload["result"]["block"]["text"], json!("章节一"));
assert_eq!(fetch_payload["audit"]["effect"], "read");
}
#[tokio::test]
async fn hermes_tools_plan_update_and_block_move_after_are_dry_run_only() {
let heading_ref = block_revision_ref("heading_1").await;
let plan_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.doc.plan_update",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_plan_1",
"traceId": "trace_plan_1",
"idempotencyKey": "idem_plan_1",
"dryRun": true,
"capabilityScope": ["page.write"],
"args": {
"command": "block_replace",
"blockId": "heading_1",
"content": "替换标题"
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(plan_response.status(), StatusCode::OK);
let plan_body = to_bytes(plan_response.into_body(), usize::MAX)
.await
.expect("body");
let plan_payload: Value = serde_json::from_slice(&plan_body).expect("json");
assert_eq!(plan_payload["audit"]["effect"], "dry_run");
assert_eq!(plan_payload["result"]["diff"][0]["op"], "replace");
let move_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.move_after",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_move_1",
"traceId": "trace_move_1",
"idempotencyKey": "idem_move_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"blockId": "heading_1",
"anchorBlockId": "heading_1",
"revision": 7,
"conflictDetectionKey": "doc_1:7",
"blockRevisionRef": heading_ref.clone(),
"anchorRevisionRef": heading_ref.clone()
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(move_response.status(), StatusCode::OK);
let move_body = to_bytes(move_response.into_body(), usize::MAX)
.await
.expect("body");
let move_payload: Value = serde_json::from_slice(&move_body).expect("json");
assert_eq!(move_payload["result"]["blocked"], true);
assert_eq!(
move_payload["result"]["warnings"][0]["code"],
"block_move_after_blocked"
);
}
#[tokio::test]
async fn hermes_tools_block_replace_and_insert_after_write_through_page_body_save() {
let heading_ref = block_revision_ref("heading_1").await;
let p1_ref = block_revision_ref("p_1").await;
let p2_ref = block_revision_ref("p_2").await;
let replace_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.replace",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_replace_1",
"traceId": "trace_replace_1",
"idempotencyKey": "idem_replace_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"blockId": "heading_1",
"content": "替换后的章节",
"revision": 7,
"conflictDetectionKey": "doc_1:7",
"blockRevisionRef": heading_ref.clone()
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(replace_response.status(), StatusCode::OK);
let replace_body = to_bytes(replace_response.into_body(), usize::MAX)
.await
.expect("body");
let replace_payload: Value = serde_json::from_slice(&replace_body).expect("json");
assert_eq!(replace_payload["audit"]["effect"], "write");
assert_eq!(
replace_payload["result"]["changedBlocks"][0]["blockId"],
json!("heading_1")
);
assert_eq!(
replace_payload["result"]["commandName"],
json!("page.body.save")
);
let insert_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.insert_after",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_insert_1",
"traceId": "trace_insert_1",
"idempotencyKey": "idem_insert_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"anchorBlockId": "heading_1",
"content": "新增段落",
"revision": 7,
"conflictDetectionKey": "doc_1:7",
"anchorRevisionRef": heading_ref.clone()
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(insert_response.status(), StatusCode::OK);
let insert_body = to_bytes(insert_response.into_body(), usize::MAX)
.await
.expect("body");
let insert_payload: Value = serde_json::from_slice(&insert_body).expect("json");
assert_eq!(insert_payload["audit"]["effect"], "write");
assert_eq!(
insert_payload["result"]["changedBlocks"][0]["op"],
json!("insert_after")
);
assert!(insert_payload["result"]["changedBlocks"][0]["blockId"]
.as_str()
.unwrap_or_default()
.starts_with("ai_block_"));
let delete_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.delete",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_delete_1",
"traceId": "trace_delete_1",
"idempotencyKey": "idem_delete_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"blockId": "p_1",
"revision": 7,
"conflictDetectionKey": "doc_1:7",
"blockRevisionRef": p1_ref.clone()
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(delete_response.status(), StatusCode::OK);
let delete_body = to_bytes(delete_response.into_body(), usize::MAX)
.await
.expect("body");
let delete_payload: Value = serde_json::from_slice(&delete_body).expect("json");
assert_eq!(delete_payload["audit"]["effect"], "write");
assert_eq!(
delete_payload["result"]["changedBlocks"][0]["op"],
json!("delete")
);
assert_eq!(
delete_payload["result"]["changedBlocks"][0]["blockId"],
json!("p_1")
);
let move_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.move_after",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_move_write_1",
"traceId": "trace_move_write_1",
"idempotencyKey": "idem_move_write_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"blockId": "heading_1",
"anchorBlockId": "p_2",
"revision": 7,
"conflictDetectionKey": "doc_1:7",
"blockRevisionRef": heading_ref.clone(),
"anchorRevisionRef": p2_ref.clone()
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(move_response.status(), StatusCode::OK);
let move_body = to_bytes(move_response.into_body(), usize::MAX)
.await
.expect("body");
let move_payload: Value = serde_json::from_slice(&move_body).expect("json");
assert_eq!(move_payload["audit"]["effect"], "write");
assert_eq!(
move_payload["result"]["changedBlocks"][0]["op"],
json!("move_after")
);
}
#[tokio::test]
async fn hermes_tools_block_write_requires_fresh_revision_and_block_ref() {
let missing_revision_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.replace",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_missing_revision_1",
"traceId": "trace_missing_revision_1",
"idempotencyKey": "idem_missing_revision_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"blockId": "heading_1",
"content": "不应写入"
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(missing_revision_response.status(), StatusCode::BAD_REQUEST);
assert_eq!(
missing_revision_response
.headers()
.get("x-error-code")
.and_then(|value| value.to_str().ok()),
Some("mnote_tool_write_precondition_required")
);
let stale_ref_response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.block.replace",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_stale_ref_1",
"traceId": "trace_stale_ref_1",
"idempotencyKey": "idem_stale_ref_1",
"dryRun": false,
"capabilityScope": ["block.write"],
"args": {
"blockId": "heading_1",
"content": "不应写入",
"revision": 7,
"conflictDetectionKey": "doc_1:7",
"blockRevisionRef": "pageRev:old:block:heading_1:hash:stale"
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(stale_ref_response.status(), StatusCode::BAD_REQUEST);
assert_eq!(
stale_ref_response
.headers()
.get("x-error-code")
.and_then(|value| value.to_str().ok()),
Some("mnote_tool_conflict")
);
}
2026-05-14 15:10:33 +08:00
#[tokio::test]
async fn hermes_tools_reject_workspace_context_conflict_without_content_leak() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-workspace-id", "ws_other")
.body(Body::from(
json!({
"toolName": "mnote.page.get",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"capabilityScope": ["page.read"]
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response
.headers()
.get("x-error-code")
.and_then(|value| value.to_str().ok()),
Some("workspace_context_conflict")
);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let text = String::from_utf8(body.to_vec()).expect("utf8");
assert!(!text.contains("服务端页面"));
assert!(!text.contains("章节一"));
}
#[tokio::test]
async fn hermes_tools_write_tools_require_idempotency_and_dry_run_flag() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.page.save",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"args": {"content": []}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(
response
.headers()
.get("x-error-code")
.and_then(|value| value.to_str().ok()),
Some("mnote_tool_idempotency_required")
);
}
#[tokio::test]
async fn hermes_tools_page_save_dry_run_returns_diff_without_write() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.page.save",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"idempotencyKey": "idem_save_1",
"dryRun": true,
"args": {"content": [{"type":"paragraph","content":[{"type":"text","text":"AI 写入"}]}]}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["audit"]["effect"], "dry_run");
assert_eq!(payload["result"]["dryRun"], true);
assert_eq!(payload["result"]["commandName"], "page.body.save");
}
#[tokio::test]
async fn hermes_tools_update_options_dry_run_filters_unwired_fields() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.page.update_options",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"idempotencyKey": "idem_options_1",
"dryRun": true,
"args": {"options": {"wideLayout": true, "pageFont": "serif"}}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
let options = &payload["result"]["diff"][0]["payload"]["options"];
assert_eq!(options["wideLayout"], true);
assert!(options.get("pageFont").is_none());
assert_eq!(payload["result"]["ignoredOptions"][0], "pageFont");
assert_eq!(
payload["result"]["warnings"][0]["code"],
"page_option_not_wired"
);
}
#[tokio::test]
async fn hermes_tools_artifact_dry_run_returns_artifact_plan() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.body(Body::from(
json!({
"toolName": "mnote.artifact.create_summary",
"workspaceId": "ws_demo",
"documentId": "doc_1",
"sessionId": "sess_1",
"runId": "run_1",
"toolCallId": "call_1",
"traceId": "trace_1",
"idempotencyKey": "idem_summary_1",
"dryRun": true,
"args": {"summary": "摘要内容"}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
assert_eq!(payload["result"]["dryRun"], true);
assert_eq!(payload["result"]["artifactType"], "summary");
}
}